/*
 * primary JavaScript file for AllBran.com
 * requires: $.js (written and tested against $ version 1.5.2)
 * requires: bgc.js, PIE.htc, plugins.js
  *
 
/*add ie and version hooks to html*/
if ($.browser.msie) {
	var browVer = parseInt ( $.browser.version );
	var classList = "ie ie" + browVer +" "+ $("html").attr("class");
} else {
	var classList = "not-ie" + $("html").attr("class");	
}	
$("html").attr('class', classList);

// prevent background image flicker in IE
try {
	if (!window.opera) document.execCommand("BackgroundImageCache", false, true);
} catch(err) {};

// GA initialization and pageview tracking
BGC.track.init("UA-5870493-13");
BGC.track();


/*create namespace*/
var Keebler = Keebler || {};

Keebler.Tracking = {
	init: function () {
		// class-based GA tracking hooks
		// link tracking (finds and tracks links with class="track category|action|label" applied)
		$("a.track").live("click", function (e) {
			var ev = getEventString(this.className), target = null, callback = null, href = null;
			if (ev) {
				if (this.className.match(/action/)) { // use "action" rather than "event" tracking
					ev = "/" + ev.replace(/\|/g, "/");
				}
				target = this.target;
				if ( !target || target.match(/^_(self)|(top)$/i) ) {
					href = $(e.target).closest("a")[0].href;
					callback = function () {
						if ( target.match(/^_top$/i) ) {
							top.location.href = href;
						} else {
							location.href = href;
						}
					};
					e.preventDefault();
				}
				BGC.track(ev, callback);
			}
		});
		
		// form view/submit "action" (virtual pageview) tracking
		$("form.track").each(function () {
			var ev = getEventString(this.className).replace(/\|/g, "/");
			if (ev) {
				BGC.track(ev + "/view");
				$(this).submit(function (e) {
					if (Page_IsValid) { // only track the submit action if the .NET validation routine passed
						BGC.track(ev + "/submit");
					}
				});
			}
		});
		
		function getEventString (s) {
			var ev = "";
			s = s.split(" ");
			$.each(s, function () {
				if (this.indexOf("|") > -1) {
					ev = this.toString();
					return;
				}
			});
			return ev;
		}
	}
};
Keebler.UI ={
	Flash: {
		init: function () {
			$(".flash-replace").each(function () {
				flashembed( this, {
					src: this.getAttribute("data-swf"),
					version: getVersion(this),
					wmode: this.getAttribute("data-swf-wmode"),
					base: this.getAttribute("data-swf-base")
				}, jsonParse( this.getAttribute("data-flashvars") || "{}" ) );
				
				if ( this.getAttribute("data-overlay") ) { // display this swf in an overlay?
					Keebler.UI.Overlay.init({
						type: "inline",
						id: this.getAttribute("data-overlay"),
						overlayStyle: {
							width: parseInt(this.getAttribute("data-overlay-width"), 10),
							height: parseInt(this.getAttribute("data-overlay-height"), 10),
							centerV: !!this.getAttribute("data-centerv") || false
						},
						src: $("#" + this.id)
					});
				}
			}).removeClass("flash-replace"); // ensure flash replacement only happens one time!
			
			function getVersion (el) {
				var v = el.getAttribute("data-swf-version").split(",");
				$.each(v, function (i) {
					v[i] = parseInt(v[i], 10);
				});
				return v;
			}
		}
	},
	Overlay: {
		init: function (options) {
			var $o = $("#" + options.id);
			if ( !$o.length ) { // create the overlay content container if it doesn't exist already
				$o = $('<div id="' + options.id + '" class="overlay-window"></div>').appendTo("body");
			}
			
			$o.empty();
			
			$o.append('<a href="#" class="jqmClose">Close</a>');
			$o.append('<div class="content"></div>');
			
			if (options.overlayStyle) {
				$o.css(options.overlayStyle);
				$o.css({display: "block"}); // element must be "block" to get the offsetWidth
				$o.css({marginLeft: -($o[0].offsetWidth / 2)}); // center the overlay
				if (options.overlayStyle.centerV) {
					$o.css({top: "50%", marginTop: -($o[0].offsetHeight / 2)}); // center the overlay
				}
				$o.css({display: "none"});
			}
			
			$o.jqm({
				modal: true,
				//trigger: options.trigger, see addTrigger()
				overlay: 90,
				onShow: loadContent,
				onHide: function (hash) {
					$o.fadeOut("fast", function () {
						$o.children(".content").empty();
						hash.o.remove();
						//$.scrollTo(0, 0);
						// publish "overlayHide" notification
						$o.trigger("overlayHide");
						// tracking
						BGC.track("overlay|" + $o.attr("id") + "|close");
					});
				}
			});
			
			Keebler.UI.Overlay.addTrigger(null, options.id);
			
			function loadContent (hash) {
				var $c = $o.children(".content"), $i;
				
				switch (options.type) {
					case "iframe":
						var $i = $('<iframe src="' + hash.t.href + '" frameborder="0" marginwidth="0" marginheight="0"></iframe>').appendTo($c);
						if (options.iframeWidth) {
							$i.css({width: options.iframeWidth});
						}
						if (options.iframeHeight) {
							$i.css({height: options.iframeHeight});
						}
						break;
					case "inline":
						$( options.src /*.clone(true)*/ ).appendTo($c).show();
						break;
				}

				$o.fadeIn(600);
				
				$.scrollTo($o, 400);
				
				// publish "overlayShow" notification
				$o.trigger("overlayShow");
				
				// tracking
				BGC.track("overlay|" + $o.attr("id") + "|open");
			}
		},
		
		addTrigger: function (e, id) {
			if (id) {
				var $t = $("." + id).removeClass("overlay-trigger");
				$("#" + id).jqmAddTrigger($t)
			} else {
				$(e.target).find(".overlay-trigger").each(function () {
					id = $(this).removeClass("overlay-trigger")[0].className;
					$("#" + id).jqmAddTrigger(this);
				});
			}
		},
		
		/*don't have video so code can leave this out*/
		closeVideo: function () {
			$("#overlay-tv").jqmHide();
			$(document).trigger("videoFinish");
		}
	},/*last element in UI object*/
	
	Nav:{		
		init: function(){
			/*remove non used items from the nav*/
			$('nav ul.second > li')
				.not('nav ul.second:visible >li')
				.remove();
			
			/*prevent actions on the a in those items but only for the
			cookies, crackers, other goodies pages*/	
			$('nav ul.second > li >a').click(function(e){
				if ($('#recipe_detail, .recipe-page').length != 1){
					e.preventDefault();			
				}
			});
			
			/*fnd the product in the nav and make the parent 'active"*/
			var limiter = location.search.substr(10,location.search.length);
			if ( limiter === "cookies" || limiter=== "crackers" || limiter==="other-goodies"){
				var add =  window.location.pathname + location.search;
				$('nav ul.second div > a').each(function(){
					var $this = $(this); 
					if("/" + $this.attr('href')== add){       
						$this.parent().parent().parent().parent().addClass('active');
						return false;
					}
				});
			};

			/*point the src attr to the value of the data-image attr*/
			$('.mega-menu img').each(function(){
			    var path = $(this).attr('data-image');
			    $(this).attr('src', path);
			});

			$("ul.second > li").hoverIntent({
				over: show,
				timeout: 125,
				out: hide
			});
			
			function show(){ 		
				var $this = $(this),
					$menu = $this.find('.mega-menu').fadeIn(125),
					$menuImgs = $menu.find('img');
				
				if ($menuImgs ){
				    while ($menuImgs.length){	
				    	var mHeight = 0;
					    $menuImgs = $menuImgs.filter(':lt(4)')		 
					       .each(function( ){	
					       		var $this = $(this);
					       		mHeight = Math.max($this.height(), mHeight);
							})
							.each(function(){
								var $this = $(this),
									height = $this.height(),
									pad = mHeight - height;	
								if (height) {
									$this.css('padding-top', pad);
								}					
							})
							.end()
							.slice(4);
				    }
				}
				var $it = $this.find('.mega-menu div' );
				if ($it){
					while ($it.length) {
						$it = $it.filter(':lt(4)').equalizeCols().end().slice(4);
					}		
				}
			}
					
			function hide(){ 		
				 $(this).find('.mega-menu').fadeOut(0);
			}
			
		}
		
	}
}
$(document).ready(function(){	

	Keebler.Tracking.init();
	Keebler.UI.Flash.init()
	Keebler.UI.Nav.init()
			
	/**column hider for empty cols*/		
	if 	($('.column').length > 0){		
		$('.column').each(
			function(){
				if ( $(this).children('*').length < 2){
					$(this).hide();
			}
		});
	}
		
	/** random ernie client side*/		
	var ernieRand = Math.floor(Math.random()*9 + 1), elf_path = "/img/elf/Elf_Facts"+ernieRand+".png";
	$(".ernie-bubble").attr({'src': elf_path});
	
	/**head image path fixer**/	
	if ($('.headImage').length > 0 ){
		var path = decodeURI($('.headImage').attr('src').toLowerCase() );	
		if (path.match(/\s/) ){
			$('.headImage').attr('src',  path.replace(/\s/g, '-') );
		}
	}
		
		
	/** where to buy */
	$body = $('body');
	if ( $body.hasClass("wtb") ) {
		// set the document.domain property to allow the dynamic iframe scripting to work
		// get the current hostname and strip off the subdomain
		var dd = location.hostname.split(".");
		while (dd.length > 2){
			dd.shift();
		}			
		document.domain = dd.join(".");
		
		// get search params from the querystring and pass through to WTB launcher
		if(BGC.query.brand) {
			$("#brand").val(BGC.query.brand);
		}
		
		if(BGC.query.product) {
			$("#product").val(BGC.query.product);
		}
		
		if(BGC.query.zip) {
			$("#zip").val(BGC.query.zip);
		}
		
		// csr view?
		if(BGC.query.csr) {
			$("#locator").val("1");
			$("#csrsearch").val("1");
		}
		  
		$("#wtb_form").trigger("submit");
		
		DYNIFS.resize('wtb_frame');
		DYNIFS.resize('reg_frame');
	} 			
		
	/**equalize all multi-column layouts.**/
	var $it = $('.itemCell.top');
	var $ie7Shadow = $('.ie7 .css3-container');
	if ($it){
		while ($it.length) {
			$it = $it.filter(':lt(3)').equalizeCols().end().slice(3);
			$ie7Shadow.filter(':lt(3)').equalizeCols().end().slice(3);
		}		
	}	
		
	/*tracking binders*/
	$('.addthis_button_facebook').bind('click', function(e){
		var str="";
		if ($('.product.detail').length ){
			str = "externalsite|productlink|facebook";
		}
		else if ($('.recipes.detail').length ){
			str = "externalsite|recipelink|facebook";			
		}	
		BGC.track(str);
	});
	
	$('.addthis_button_twitter').bind('click', function(e){
		var str="";
		if ($('.product.detail').length ){
			str = "externalsite|productlink|twitter";
		}
		else if ($('.recipes.detail').length ){
			str = "externalsite|recipelink|twitter";			
		}	
		BGC.track(str);
	});
	
	$('.print').bind('click', function(){
		var str = "action|printrecipe|"+ encodeURI($(this).attr('data-name'));
		BGC.track(str);
	});	
	
	$('.overlay-nutrition').bind('click', function(){	
		var str = "action|viewnutrition|"+ encodeURI($(this).attr('data-name'));
		BGC.track(str);
	});
	
	$('.wheretobuy').bind('click', function(){	
		var str = "action|wheretobuy|"+ encodeURI($(this).attr('data-name'));
		BGC.track(str);
	});
		
}); //end doc ready
	
	
