﻿//    prevent background image flicker in IE
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {};

// create CSS hook for JS-enabled clients
if (jQuery.browser.msie) {
	jQuery("html").addClass("js ie");
} else {
	jQuery("html").addClass("js");
}

// tracking functions

var Kellogg = Kellogg || {};

Kellogg.trackers = [];

Kellogg.track = function (str) {
	for (var i = 0, l = Kellogg.trackers.length; i < l; i++) {
		if (typeof Kellogg.trackers[i]._trackPageview === "function") {
			if (str) {
				Kellogg.trackers[i]._trackPageview(str);
			} else {
				Kellogg.trackers[i]._trackPageview();
			}
		}
	}
};

// Kellogg.Carousel = (function () {
// 	var $c, $slides, $direct, $d = jQuery(document), that;
// 	return {
// 		init: function (c, s, supressNav) {
// 			var $nav, $prev, $next;
// 			that = this;
// 			$c = jQuery(c);
// 			that.speed = s || that.speed;
// 			if (!$c.length) {
// 				return false;
// 			}
// 			$slides = $c.find(".slide").css({zIndex: 1, display: "block"});
// 			if (!jQuery.browser.msie) {
// 				$slides.css({opacity: 0});
// 			}
// 			that.last = $slides.length - 1;
// 			
// 			if (that.last && !supressNav) { // multiple slides, so insert prev/next/direct navigation links
// 				$nav = jQuery('<div class="nav"></div>').appendTo($c);
// 				$prev = jQuery('<a href="#" class="prev"></a>').appendTo($nav);
// 				$next = jQuery('<a href="#" class="next"></a>').appendTo($nav);
// 				for (var i = 0; i <= that.last; i++) {
// 					jQuery('<a href="#" class="direct">' + (i + 1) + '</a>').insertBefore($next);
// 				}
// 				$direct = $nav.find(".direct");
// 				$prev.click(function (e) {
// 					that.pause();
// 					that.stopped = true;
// 					that.previous();
// 					this.blur();
// 					e.preventDefault();
// 				});
// 				$next.click(function (e) {
// 					that.pause();
// 					that.stopped = true;
// 					that.next();
// 					this.blur();
// 					e.preventDefault();
// 				});
// 				$direct.click(function (e) {
// 					that.pause();
// 					that.stopped = true;
// 					that.gotoframe( $direct.index(this) );
// 					this.blur();
// 					e.preventDefault();
// 				});
// 				$nav.fadeIn(1000);
// 			}
// 			
// 			$c.hover(that.pause, that.play);
// 			
// 			// pause carousel when megamenus or overlays are active
// 			$d.bind("megamenuShow overlayShow", function () {
// 				that.pausers++;
// 				that.pause();
// 			});
// 			$d.bind("megamenuHide overlayHide", function () {
// 				that.pausers--;
// 				if (!that.pausers) {
// 					that.play();
// 				}
// 			});
// 			
// 			this.show(true);
// 			this.play();
// 		},
// 		
// 		show: function (started) {
// 			if (jQuery.browser.msie) {
// 				$slides.eq(that.current).css({zIndex: 2}).show();
// 				if (started) {
// 					$c.removeClass("loading");
// 				}
// 			} else {
// 				$slides.eq(that.current).css({zIndex: 2}).stop().fadeTo(500, 1, function () {
// 					if (started) {
// 						$c.removeClass("loading");
// 					}
// 				});
// 			}
// 			if ($direct && $direct.length) {
// 				$direct.removeClass("on").eq(that.current).addClass("on");	
// 			}
// 			$d.trigger( "carouselShow", [that.current] );
// 		},
// 		
// 		hide: function () {
// 			if (jQuery.browser.msie) {
// 				$slides.eq(that.current).css({zIndex: 1}).hide();
// 			} else {
// 				$slides.eq(that.current).stop().fadeTo(500, 0).css({zIndex: 1});
// 			}
// 		},
// 		
// 		pause: function () {
// 			window.clearInterval(that.timer);
// 		},
// 		
// 		play: function () {
// 			if (!that.stopped) {
// 				window.clearInterval(that.timer);
// 				that.timer = window.setInterval(that.next, that.speed);
// 			}
// 		},
// 		
// 		gotoframe: function (i) {
// 			that.hide();
// 			that.current = i;
// 			that.show();
// 		},
// 		
// 		next: function () {
// 			that.hide();
// 			that.current = (that.current < that.last) ? that.current + 1 : 0;
// 			that.show();
// 		},
// 		
// 		previous: function () {
// 			that.hide();
// 			that.current = (that.current > 0) ? that.current - 1 : that.last;
// 			that.show();
// 		},
// 		
// 		current: 0,
// 		
// 		last: 0,
// 		
// 		pausers: 0,
// 		
// 		speed: 6000,
// 		
// 		stopped: false,
// 		
// 		timer: null
// 	};
// }) (); // self-invoking!


 BGC.track.init('UA-5624474-1','UA-5870493-11');
 $(function(){
	var name = "username";
    if(readCookie(name)){
		BGC.track.init("UA-5870493-31");
	}	
}); 

var local = function(){
	var x = document.location.hostname.split('.'),
		d =/^\D{2}g{2}.-/;
	return d.test(x[x.length-2])
}();

var fbuid = (!!local) ? 'dc01cdf4da3879caef72d1a2a0d7568d' : '3b5ed1be86bce91504e8401b15353a0c' ;
//mds = 2b6f984ae4622d7c15d81f83b088506e
//bg = dc01cdf4da3879caef72d1a2a0d7568d

$(document).ready(function() {
	productPromos();	
	recipePromos();
	homepageRecipeOfTheWeek()
	navSearch();
	shoplist();
	socialBookmarking();
	recipeBoxEmpty();
	veggieType();
	loadInsiderHome();
	recipeHovers();/*Meal Planner*/
	commentScroll();/*Guide to Meatless Eating*/	
	rct();/*Recipe Conversion Tool*/
	toggleArchive();
	contestContentHeight();
	externalLinks();
	rotateFeature();
	cycleVideo(readCookie('msf_video'));
	prepVidSidebar();
	checkForVideo();
	sidebarVideoPopulate();
	vidBannerPopulate();
	
		// 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;
		}
	
	$('a.ga_grill').click(function(){
		BGC.track('PDF | download | guidetomeatlesseating')
	})
	
	$('a.ga_facebook').click(function(){
		BGC.track('offsitelink | fanus | facebook')
	})
	
	$('.cooking_video a, #more_vids_list a, .cooking_video_link').click(function(){
		overlay($('#video_overlay'));
		cookingVid($(this).attr('rel'));
		return false;
	})
	
	// $('#inpop-videos a').click(function(){
	// 		var vid = readCookie('msf_video') || 'chili';
	// 		var loop = vidArrayLength;
	// 		var i = 0;
	// 		
	// 		overlay($('#video_overlay'));
	// 		cookingVid(vid);
	// 		
	// 		while(loop--){
	// 			if(vidArray[loop][4] == vid){
	// 				i = loop;
	// 				break;
	// 			}
	// 		}
	// 		createCookie('msf_video',(!!vidArray[i+1]) ? vidArray[i+1][4] : vidArray[0][4],365)
	// 		return false;	
	// 	})
	
	$('#mask, .msoverlay_close, #nutImg, .btn_close').live('click',function(){
		if($('#reg_overlay').is(':visible')){
			$('#reg_overlay').find('iframe').attr('src','');
		}
		$('#mask, .msoverlay, .window').hide();
		try{
			swfobject.removeSWF("ms_video");
			$('<div id="ms_video"/>').prependTo($('#video_content'));
		}
		catch(e){}
		return false;
	})
	
	/* Product Landing */
	$('body#product_landing, body#healthy_options').each(function(){
		if(typeof(query.view) != 'undefined'){
			$('#product_nav').hide()
		}
	}).find('.productbox:last').css({
		'background-image':'none',
		'margin-bottom':0,
		'padding-bottom':0
	})
	
	/* Product Detail */
	$('#product_detail').find('#product_content h4:not(:eq(0))').css('cursor','pointer').click(function(){
		$(this).toggleClass('toggled').next().slideToggle(250);
	}).end().find('#divNutrition a').click(function(){
		var x = $(this).attr('href'),
			$i = $('<img id="nutImg" class="msoverlay" src="http://www.morningstarfarms.com'+x+'" title="Click to close image.">'),
			$img = $('#nutImg');
			
		$i.load(function(){
			overlay($img);
			$('#mask').height(Math.max($img.height()+75), $(this).height());	
		});
		
		if($img.length == 0){
			$('#boxes').append($i)
			$img = $('#nutImg');
		}
		else{
			$img.attr('src','http://www.morningstarfarms.com'+x)
		}


	})
	
	//Tracking
	$('.add_to_list').live('click',function(){
		var x= $(this).parents('#product_content').find('h1').text();
		BGC.track('/addtoshoppinglist/'+x)
	})
	
	
	// New Recipes Page
	$('#searchRecipesLink').click(function(){
		searchRecipes('product','19711');
		return false;
	});	

// VIDEO OVERLAY POPUP
	
		function overlayLaunch(vidID){
	
		
			var $o, that = this;
			var vidImg = vidArray[vidID][3];
			var changeBookmark = "#video_bookmark_" + vidID;
			var changeThumb = "#video_" + vidID + "_thumb";
			var changeToNowPlayingThumb = "url(/images/overlay_" + vidImg + "_nowplaying.jpg)";
			var addFlashContent = "<div id=\"flashcontent\"><\/div>";	
			// show overlay
			$o = $("#videos");
			$o.modal({
				onOpen: function (dialog) {
						dialog.overlay.fadeIn(200, function () {
						dialog.container.fadeIn(200);
						dialog.data.fadeIn(200);
					});	
					
					// check to see if user has flash
					if (swfobject.hasFlashPlayerVersion("9.0.47")) {
									$("#videoframe").prepend(addFlashContent);
									// populate sidebar videos from vidArray
										$("div.video_thumb").each(function (i) {
												var vid = "div#" + $(this).attr("id");
												var vidNum = $(this).attr("id").replace("id_", "");
												var video = vidArray[vidNum][3];
																				
												vidA = vid + " a.videochanger";
												vidImage = "#video_" + vidNum + "_thumb";
												vidDesc = vid + " .video_desc";
												
												var videoThumb = "url(/images/overlay_" + video + ".jpg)";
												$(vidA).html(vidArray[vidNum][1]).attr("name", video);
												$(vidImage).css("background-image", videoThumb);
												$(vidDesc).html(vidArray[vidNum][2]);
											});	
																		
												
												// set correct bookmark and thumbnail 
												$("div.video_bookmark").removeClass("video_bookmark_on");
												$(changeBookmark).addClass("video_bookmark_on");
												$(changeThumb).addClass("nowplaying").css("background-image", changeToNowPlayingThumb);
												
												
												// set correct video 
														var params = {
														align:"TL",
														scale:"noScole",
														scaleMode:"noScole",
														allowScriptAccess:"always",
														allowFullScreen:"true",
														bgcolor:"#FFFFFF"
													};
											
											
													var flashvars = {};
													
													flashvars.videoURL =  videoDomain + "/" + vidArray[vidID][3] + ".mp4";
													flashvars.previewImage = "/images/" + vidArray[vidID][3] + "_default.jpg";
													flashvars.autoPlay = "true";
													flashvars.scaleMode = "maintainAspectRatio";
													flashvars.loop = "false";
													flashvars.backgroundColor1 = "0x487837";
													flashvars.backgroundColor2 = "0x5e8851";
													flashvars.movieBackgroundColor = "0x000000";
													flashvars.inkColor = "0xc8dbb2";
													flashvars.highlightColor = "0xffffff";
													flashvars.playButoon = "true";
													flashvars.seekBar = "true";
													flashvars.timeBar = "true";
													flashvars.volumeButton = "true";
													flashvars.fullScreenButton = "true";
													flashvars.autoHide = "false";
													flashvars.autoHideFullScreen = "true";
													flashvars.offsetY = "0";
													flashvars.offsetYFullScreen = "25";
													flashvars.margins = "0";
													flashvars.marginsFullScreen = "0";
													flashvars.volume = "70";
													flashvars.bufferTime = "15";
													var attributes = {id:"flashcontent"};
													
													swfobject.embedSWF("swf/jcplayer.swf", "flashcontent", "410", "255", "9.0.47", "swf/expressinstall.swf", flashvars, params, attributes);
								
									// Overlay video changer
											
											var $changer = $(".videochanger");		
											$changer.click(function (e) {
														
													var currentID = $(".nowplaying").attr("id");
													var currentNum = currentID.replace("video_", "").replace("_thumb", "");
													var currentThumb = "#" + currentID;
													var removeNowPlayingThumb = "url(/images/overlay_" +  vidArray[currentNum][3] + ".jpg)";
									
													var changeID = $(this).parents("div.video_thumb").attr("id");
													var changeNum = changeID.replace("id_", "");
													var changeBookmark = "#video_bookmark_" + changeNum;
													var changeThumb = "#video_" + changeNum + "_thumb";
													var changeToNowPlayingThumb = "url(/images/overlay_" + vidArray[changeNum][3] + "_nowplaying.jpg)";
														
													$("div.video_bookmark").removeClass("video_bookmark_on");
													$(changeBookmark).addClass("video_bookmark_on");
													$(currentThumb).css("background-image", removeNowPlayingThumb).removeClass("nowplaying");
													$(changeThumb).css("background-image", changeToNowPlayingThumb).addClass("nowplaying").removeClass("video_thumb_on");;
													
													var flashvars = {
													videoURL: videoDomain + "/" + vidArray[changeNum][3] + ".mp4",
													previewImage: "/images/" + vidArray[changeNum][3] + "_default.jpg",
													autoPlay: "true",
													backgroundColor1: "0x487837",
													backgroundColor2: "0x5e8851",
													movieBackgroundColor: "0x000000",
													inkColor: "0xc8dbb2",
													highlightColor: "0xffffff",
													bufferTime: "15"
													};
													
													var attributes = {id:"flashcontent"};	
													swfobject.embedSWF("swf/jcplayer.swf", "flashcontent", "410", "255", "9.0.47", "swf/expressinstall.swf", flashvars, params, attributes);
									
													//BGC.track("/Video/" + changeName + "/Play");
											
														return false;
												});
									
												$changer.bind("mouseleave", function (e) {
													var changeThumb = $(this).parents("div.video_thumb").attr("id").replace("id_", "#video_") + "_thumb";				
													if (!$(changeThumb).hasClass("nowplaying")){
														$(changeThumb).removeClass("video_thumb_on");
													}
												});
												
												$changer.bind("mouseenter", function (e) {
													var changeThumb = $(this).parents("div.video_thumb").attr("id").replace("id_", "#video_") + "_thumb";
													if (!$(changeThumb).hasClass("nowplaying")){
															$(changeThumb).addClass("video_thumb_on");
													}
												});
												
							} else {
								//if user doen't have the most current flash
								$('#videos').html("").css({
									"height" : "351px",
									"width" : "625px",
									"background-color" : "transparent",
									"background-image" : "url(/images/overlay_video_noflash.png)",
									"background-position" : "top left",
									"background-repeat" : "no-repeat",
									"position" : "absolute",
									"top" : "40px",
									"left" : "127px",
									"cursor" : "pointer"
								});
								
								$('#videos').click(function (e) {
									window.open("http://get.adobe.com/flashplayer/");
								});
								
							}
							
	
				},
				
				onClose: function (dialog) {
				$("#flashcontent").remove();	
				dialog.data.fadeOut(200);
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			},
			overlay: 80
		});
						
	
	};
						
/*For recipe search results.*/
function vidBannerPopulate(){		
	// uses vidArray from msf.js
	$("div.banner_links").each(function (i) {
		var t = $(this),
			ai = t.attr('rel');

		t.find('.videoURL').html(vidArray[ai][1]).attr("name", vidArray[ai][3]);
		t.find('.rs_video_thumb').css("background-image", "url(/images/rs_" + vidArray[ai][3] + ".jpg)");
		t.find('.videoCaption').html(vidArray[ai][2]);
		t.find('.launcher').click(function (e) {
			$(this).attr('href',"recipe_detail.aspx?id=" + vidArray[ai][0] + "&vid=" + ai);
			//BGC.track("/Video/" + changeName + "/Play");
		}).bind("mouseover mouseout", function (e) {
			t.find('.rs_video_thumb').toggleClass("rs_video_thumb_on");
		})
	});
};

/*For recipe/product detail pages.*/
function sidebarVideoPopulate(){
	var s = $('#sidebar_video_links');
	var arr = vidArray[s.attr('name')] || vidArray[0];		
	if(s.length < 1){return false};

	$("#videoURL").html(arr[1]);
	$("#videoCaption").html(arr[2]);
	$("#rd_video_thumb").css("background-image", "url(/images/rd_" + arr[3] + ".jpg)");

	$('.launchlink').click(function(e) {
		overlay($('#video_overlay'));
		cookingVid(arr[4]);
		//BGC.track("/Video/" + changeName + "/Play");
		e.preventDefault();
	}).mouseover(function(){
		$("#rd_video_thumb").css('background-position','bottom left')
	}).mouseout(function(){
		$("#rd_video_thumb").css('background-position','top left')
	});
};			
				
// END VIDEO AND OVERLAY COMPONENTS
		
  
  // insert print link
  if(!$("#recipe-detail").size() && window.print) $("#tell-friend").after('<p id="print-page"><a href="#" onclick="window.print(); BGC.track(\'/action/print/printthispage'+window.location.pathname+'\'); return false;">Print this page</a></p>');
  
  highlightNav = function(p) {
    $(p).addClass("on");
    $(p).parents("li").addClass("on");
  };
  
  getBaseURL = function(url) {
    if(url.indexOf("#") != -1) {
      return url.split("#")[0];
    } else {
      return url;
    }
  };

  // expand nav: match page URL with left nav URL to highlight
  $("#nav a").not("[href$='#']").each(function() {
    if(getBaseURL(location.href).toLowerCase() == this.href.toLowerCase()) {
      highlightNav($(this).parent());
    }
  });
	
	// duplcate of above function used for navigation on Creative Exchange "Tunnel" pages
  $("#ce-navigation a").not("[href$='#']").each(function() {
    if(getBaseURL(location.href).toLowerCase() == this.href.toLowerCase()) {
      highlightNav($(this).parent());
    }
  });

  // init add to recipe box widget (wrapped in a function so we can call again when paging through search results)
  initAddRecipeBox = function() {
    $("a.add-recipe, p.add-recipe a").bind("click", function() {
      var me = $(this);
        try {
          $.ajax({
            url: me.attr("href"),
            type: "GET",
            success: function(req) {
              if(req.trim() == 'true') {
                me.before("In your recipe box");
                $(me).parent().toggleClass("add-recipe-on");
                me.remove();
				BGC.track("/RecipeBox/add")
              } else {
                ajaxError();
              }
            },
            error: ajaxError
          });
        } catch(err) {ajaxError(err);}
        this.blur();
        return false;
    }).css('visibility','visible');
  };
  
  //initAddRecipeBox();
  
  // init remove from recipe box widget
  $("a.remove-recipe").bind("click", function() {
    this.blur();
    $(this).parents("tr").children("td").addClass("highlight");
    if(window.confirm("Are you sure you want to remove this recipe?")) {
      var me = $(this);
      try {
        $.ajax({
          url: me.attr("href"),
          type: "GET",
          success: function(req) {
            if(req.trim() == 'true') {
              $(me).parents("tr").hide().remove();
              if(!$("#table-recipe-box tbody tr").size()) {
                $("#recipe-box-empty").show();
                $("#table-recipe-box").hide();
              }
			  BGC.track("/RecipeBox/remove")
			  recipeBoxEmpty();
            } else {
              ajaxError();
            }
          },
          error: ajaxError
        });
      } catch(err) {ajaxError(err);}
    } else {
      $(this).parents("tr").children("td").removeClass("highlight");
    }
    return false;
  }).css('visibility','visible');
  
  initSearchResults = function() {
    // style search results tables
    if($("table.search-results").size()) {
      alternateRows($("table.search-results")[0]);
    }
    
    // add AJAX calls for next/previous
    $("p.search-nav a").each(function() {
      $(this).bind("click", function() {
        var loading = $("#loading");
        loading.show();
        var href = $(this).attr("href");
        var container = $(this).parents("div.results");
        container.fadeTo(250, 0.01, function() {container.load(href, function() {
            container.fadeTo(250, 1.0, function() {
              loading.hide();
            });
            dhtmlHistory.add(escape(href));
            currentLocation = href;
            initSearchResults();
            initAddRecipeBox();
          });
        });
        window.scrollTo(0, $("table.search-results").offset().top - 50);
        return false;
      });
    });
  };
  
  var currentLocation = "";
  
  historyChange = function(newLocation, historyData) {
    try{console.log("cur: " + currentLocation); console.log("new: " + newLocation);} catch(err){}
    //alert("cur: " + currentLocation + "\n" + "new: " + newLocation);
    if(newLocation && newLocation != currentLocation) {
      $("#recipe-results").load(unescape(newLocation), function() {
        initSearchResults();
        initAddRecipeBox();
      });
    }
  };
  
  
   // recipe search page scripts
	$('#search_box').click(function(){
		$('#sresults_expand').addClass('expand');
		$('#browse_expand').removeClass('brexpand');
		$('#share_expand').slideUp('fast');
		$('#search_expand').slideDown('fast');
		// return false;
	});
	
	//Mouse hover Browse expand functionality
	$('#browse_box').hover(function() {
		setTimeout(function(){
			$('#sresults_expand').addClass('expand');
			$('#search_expand').slideUp('fast');
			$('#share_expand').slideUp('fast');
			$('#browse_expand').addClass('brexpand');
			},3000);
		
		 return false;
	}); 
	
	$('#browse_box').click(function() {
		$('#sresults_expand').addClass('expand');
		$('#search_expand').slideUp('fast');
		$('#share_expand').slideUp('fast');
		$('#browse_expand').addClass('brexpand');
		// return false;
	}); 

	$('#share_box').click(function(){
		$('#sresults_expand').addClass('expand');
		$('#search_expand').slideUp('fast');
		$('#browse_expand').removeClass('brexpand');
		$('#share_expand').slideDown('fast');
		// return false;
	});
	
	// new search-results table styles
		stripeTable = function() {
		$('.search-results tr:even').addClass('even');
	}
	
	// tag cloud and filtered results ajax
  	tagClickCallback = function(data, status) {
  		data = "<div>" + data + "</div>";
		var tagsmarkup = $("#tagmarkup", data);
		var resultsmarkup = $("#resultsmarkup", data);
		$("#browse_expand").html(tagsmarkup.html());
		$("#recipe-results").html(resultsmarkup.html());
		bindTagClicks();
		bindResultClicks();
		vidBannerPopulate();
	};
	
  	bindTagClicks = function() {
  		$('#browse_expand a').unbind("click").click(function(e) { 
  			var u = $(this).attr("href").split("/");
			u = "get_" + u.pop();
			$.get(u, {}, tagClickCallback, 'html');
			$('#breset').addClass('reset_reveal');
			BGC.track(u);
			e.preventDefault();
		}); 
	};
	
  	bindResetClick = function() {
		$('#breset a').click(function(e){
			var u = "get_recipe_search.aspx";
			$.get(u, {}, tagClickCallback, 'html');
			$('#breset').removeClass('reset_reveal');
			e.preventDefault();
		});
  	};
  	
  	 $("#loader").ajaxStart(function () {
  	  		$(this).show();
  	  });
  	   	
  	  $("#loader").ajaxComplete(function () {
  	   		$(this).hide();
			stripeTable();
  	  });
	
	// sort - pagination ajax
  	resultClickCallback = function(data, status) {
  		data = "<div>" + data + "</div>";
		var resultsmarkup = $("#resultsmarkup", data);
		$("#recipe-results").html(resultsmarkup.html());
		bindResultClicks();
		vidBannerPopulate();
	};
	
  	bindResultClicks = function() {
		$('#recipe-results a[href*="sort="], #recipe-results a[href*="page="]').unbind("click").click(function(e) { 
			var u = $(this).attr("href").split("/");
			u = "get_" + u.pop();
			$.get(u, {}, resultClickCallback, 'html');
			e.preventDefault();
		}); 
	};

  
  // search results page?
   // if($("body#recipe_search").size()) {
   //     // initialize the DHTML History
   //     // framework
   //     dhtmlHistory.initialize();
   //     
   //     // subscribe to DHTML history change
   //     // events
   //     dhtmlHistory.addListener(historyChange);
   //     
   //    // init search results
   //     initSearchResults();
   //   }
  
  // init form validation
  if($("form.validate").size()) {
    initFormValidation();
  }
  
  // clean up promotion detail content
  try {
    $("#content div.para > li").wrap("<ul></ul>");
  } catch(err) {}

//if close button is clicked
/*
!!MDS Commented for MS functionality.
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});	*/

	
	stripeTable();
		
				
});					

// close document.ready

ajaxError = function(req) {
  alert("Sorry, the server was unable to process your request. Please try again.");
  //alert(req);
};

imageMissing = function(img) {
  if($("#recipe_details").size()) {
    img.src = "/etc/designs/kelloggs/morningstarfarms/images/recipe.gif";
  } else {
    img.src = "/etc/designs/kelloggs/morningstarfarms/images/recipe_small.gif";
  }
};

var recipeBoxEmpty = function(){
	if(document.getElementById('divRecipes')){
		var table = document.getElementById('divRecipes').getElementsByTagName('table').length;
		var copy = document.getElementById('recipe-box-empty');
		if (table > 0) {
			copy.style.display = "none";
		}
	}
	else {
		return true;
	}
  }
  
// utility functions
////////////////////////////////////////

createCookie = function(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; Expires="+date.toGMTString();
  }
  else expires = "";  
  document.cookie = name+"="+value+expires+"; path=/";
}

createCookie = function(name,value,days,domain) {
	  
	  var cookie_string = name + "=" + escape(value );
	  if (days)
	  {
		var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    cookie_string += "; Expires=" + date.toGMTString();
	  }/* Commented for IE 8 Cookie creation issue.
	  else{
		  cookie_string += "; expires="+""; 
	  }*/

	  cookie_string += "; path=/";
	 
	  if (domain){
	        cookie_string += "; domain=" + escape(domain);
	  }
	  document.cookie = cookie_string;
}

readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

var query = (function () {
    var qString, queryStart, query, parts,returnVals1, returnVals = {};
    qString = window.location+"";
    queryStart = qString.substring(qString.lastIndexOf(':')+1);
    if (queryStart==-1) {
        return returnVals;
    }
    //query = qString.substring(queryStart + 1, qString.length);
    parts = queryStart.split(".");
    if(parts[0]){
        returnVals1 = parts[0];
    }
    return returnVals1;
}) (); // self-invoking!

// recipe submit functions
////////////////////////////////////////

initIngredients = function() {
  var l = $("#ingredients")[0];
  
	if(l.value) {
		var arrIngredients = l.value.split("^");
		for(var i=0; i<arrIngredients.length; i++) {
      var arrParts = arrIngredients[i].split("|");
			insertIngredientRow(arrParts[0], getUnitText(arrParts[1], arrParts[0]), arrParts[2]);
		}
	}
};

addIngredient = function() {
  var q = $("#quantity")[0];
  var u = $("#unit")[0];
  var i = $("#ingredient")[0];
  
  // validate
  if(!i.value) {
    alert("Enter an ingredient.");
		i.focus();
		return false;
	}
  
  var qc = q.value.cleanIngredient();
  var ic = i.value.cleanIngredient();
	
	// insert row	
	insertIngredientRow(qc, getUnitText(u.value, qc), ic);
	
	// update hidden value
  var l = $("#ingredients")[0];	
	l.value = l.value ? l.value + "^" + qc + "|" + u.value + "|" + ic : qc + "|" + u.value + "|" + ic;
	
	//alert(l.value);
	
	// reset form values
	q.value = "";
	u.selectedIndex = 0;
  i.value = "";
	q.focus();
  return false;
};

insertIngredientRow = function(q, u, i) {
	var table = $("#tbl_ingredients")[0];
	if(table) {
		var tr = table.insertRow(table.rows.length);
		// insert the cells
		var td = [];
	  td[0] = tr.insertCell(0);
    td[1] = tr.insertCell(1);
    
    td[0].className = "ingredient";
    td[1].className = "delete";
   
		td[0].innerHTML = '<p>' + q + ' ' + u + ' ' + i + '</p>';
		td[1].innerHTML = '<p><a href="#" onclick="deleteIngredientRow(this.parentNode.parentNode.parentNode);this.blur();return false;"><img src="/images/trash.gif" border="0"></a></p>';
	}
  table.parentNode.className = "section";
  alternateRows(table);
};

deleteIngredientRow = function(tr) {
  var table = $("#tbl_ingredients")[0];
  tr.className = "highlight";
	if(window.confirm("Delete this ingredient?")) {
	
		// update hidden values
		var i = tr.rowIndex;
		var l = $("#ingredients")[0];
		var arrIngredients = l.value.split("^");
		
		arrIngredients.splice(i, 1);
		
		l.value = arrIngredients.join("^");
		
		//alert(l.value);
		
		// delete row
		table.deleteRow(i);
    if(!table.rows.length) {
      table.parentNode.className = "";
    }
	}
  alternateRows(table);
  $("#quantity")[0].focus();
};

getUnitText = function(v, q) {
  var u = $("#unit")[0];
  q = q.trim();
  if(u) {
    for(var i=0; i<u.length; i++) {
      if(u.options[i].value == v) {
        if(q.isSingular()) {
          return u.options[i].className;
        } else {
          return u.options[i].text;
        }
      }
    }
  }
  return "";
};

alternateRows = function(table) {
  $(table).find("tr:even").removeClass("highlight").addClass("even");
  $(table).find("tr:odd").removeClass("highlight").addClass("odd");
};

String.prototype.cleanIngredient = function () {
	return this.replace(/[\^\|]/g, "");
};

String.prototype.isSingular = function() {
  return ((this === null) || (this.length === 0) || (/^(\d+\/\d+|0?\.\d+|1)$/.test(this)));
};

createTextCounter = function(id, maxlimit) {
	// add event handlers to textarea
	var el = document.getElementById(id);
	el.onkeydown = function(){textCounter(this.id, maxlimit);};
	el.onkeyup = function(){textCounter(this.id, maxlimit);};
	// add SPAN element to the field hint div
	var c = document.getElementById(id + "-H");
	c.innerHTML = c.innerHTML + "<span></span>";
	// update the text counter
	textCounter(id, maxlimit);
};

textCounter = function(id, maxlimit) {
	var el = document.getElementById(id);
	if (el.value.length > maxlimit) {
    el.value = el.value.substring(0, maxlimit);
    alert('Your text may not exceed ' + maxlimit + ' characters in length.' );
		textCounter(id, maxlimit);
  } else {
    var c = document.getElementById(id + "-H");
		var s = c.getElementsByTagName("SPAN")[0];
		if(s) {
			s.innerHTML = "(" + (maxlimit - el.value.length) + " characters remaining)";
		}
  }
};

exitMessage = function() {
	return confirm('You are now leaving the Morningstar Farms Web site.\n\nDo you want to continue?');
};

popUpWindow = function(URL,windowName,width,height) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = Math.round((w-width)/2);
	var topPos = Math.round((h-height)/2);
	var defaults = "scrollbars = 0, resizable";
	var centerOnScreen = "top="+topPos+", left="+leftPos+", width="+width+", height="+height;
	var options = centerOnScreen + " ," + defaults;
	var msgWindow = window.open(URL,windowName,options);
	if(!msgWindow) {
		return false;
	} else {
		msgWindow.creator=self;
		msgWindow.focus();
	}
  return true;
};

function OutsideURLWarning(url) {
	/* 
		Turning off all bumper pages for now, due to conflicts with Facebook and consistent behavior
		
	var result = popUpWindow("/bumper.htm?URL=" + escape(url), "bumper", 530, 475);
	return (result == false); 
	
	*/
	
	return (result == true); 
	
}


// validation prototypes
////////////////////////////////////////

String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.isEmpty = function() {
  return ((this === null) || (this.length === 0) || (/^\s+$/.test(this)));
};

String.prototype.isProfane = function() {
	return this; //disabling the profanity filtering
	var badwords = ["69", "666", "ahole", "anal", "anarchist", "anarchists", "anarchy", "anus", "aryan", "aryans", "ash0le", "ash0les", "asholes", "ass", "ass hoe", "ass lick", "Ass Monkey", "asses", "Assface", "assh0le", "assh0lez", "asshole", "assholes", "assholz", "asskisser", "asswipe", "azzhole", "babe", "babes", "baby batter", "balls", "banging", "bangle", "bassterds", "bastard", "Bastard", "bastards", "bastardz", "basterds", "basterdz", "beaner", "beastial", "beastiality", "beastility", "beaver", "beer", "belly whacker", "bestial", "bestiality", "Biatch", "bible fucker", "bitch", "bitcher", "bitchers", "bitches", "bitchin", "bitching", "Blow Job", "blow job", "blowjob", "blowjobs", "blumpkin", "boffing", "bonehead", "boner", "boob", "brain banger", "breasted", "breasts", "brown eye", "browneye", "browntown", "bucket cunt", "buff", "bugger", "bukakke", "bull dyke", "bull shit", "bullshit", "bum", "bung hole", "butch", "butt", "butt breath", "butt fucker", "butt hair", "butt head", "buttface", "buttfuck", "buttfucker", "butthead", "butthole", "buttpicker", "butts", "buttwipe", "byotch", "c0ck", "c0cks", "c0k", "camel hump", "camel jockey", "camel toe", "cannabis", "carpet muncher", "Carpet Muncher", "cawk", "cawks", "chicken head", "chink", "christ", "cigs", "circle jerk", "circumcise", "clam", "cleveland steamer", "Clit", "clit", "clit clitoris", "cnts", "cntz", "cobia", "cock", "cock sucker", "cockhead", "cock-head", "cockpenis", "cocks", "cocksuck", "cocksucked", "CockSucker", "cocksucker", "cock-sucker", "cocksucking", "cocksucks", "coon", "cootch", "cooter", "cornhole", "crack", "crap", "cum", "cummer", "cumming", "cums", "cumshot", "cunilingus", "cunillingus", "cunnilingus", "cunt", "cuntlick", "cuntlicker", "cuntlicking", "cunts", "cuntvagina", "cuntz", "cyberfuc", "cyberfuck", "cyberfucked", "cyberfucker", "cyberfuckers", "cyberfucking", "damn", "damnation", "darkie", "dead", "dick", "dickhead", "dickpenis", "died", "dik", "dike", "dild0", "dild0s", "dildo", "dildos", "dilld0", "dilld0s", "dingleberry", "dink", "dinks", "dipshit", "dirty", "Dirty Sanchez", "dominatricks", "dominatrics", "dominatrix", "dong", "donkey punch", "douche", "douche bag", "dumbass", "dune coon", "dutch oven", "dyke", "ejaculate", "ejaculated", "ejaculates", "ejaculating", "ejaculatings", "ejaculation", "enema", "enemas", "f u c k", "f u c k e r", "fag", "fag1t", "faget", "fagg1t", "fagget", "fagging", "faggit", "faggot", "faggs", "fagit", "fagot", "fagots", "fags", "fagz", "faig", "faigs", "fantasies", "fart", "farted", "farting", "fartings", "farts", "farty", "fatass", "fatso", "felatio", "fellatio", "fetish", "fingerfuck", "fingerfucked", "fingerfucker", "fingerfuckers", "fingerfucking", "fingerfucks", "fist", "fist fuck", "fistfuck", "fistfucked", "fistfucker", "fistfuckers", "fistfucking", "fistfuckings", "fistfucks", "flagellate", "flesh", "flipping the bird", "frigid", "f u c k", "f.u.c.k.", "fuck", "fuck stick", "fucked", "fucker", "fuckers", "fuckin", "fucking", "fuckings", "fuckme", "fucks", "fudge packer", "Fudge Packer", "fuk", "Fukah", "Fuken", "fuker", "Fukin", "Fukk", "Fukkah", "Fukken", "Fukker", "Fukkin", "fuks", "furburger", "g00k", "gangbang", "gangbanged", "gangbangs", "gash", "gay", "gayboy", "gaygirl", "gays", "gaysex", "gayz", "gazongers", "geisha", "giz", "goatse", "goddamn", "God-damned", "gonads", "gook", "gringo", "guinne", "gun", "guns", "h00r", "h0ar", "h0re", "hard on", "hardcoresex", "hash", "hells", "hiv", "hoar", "homo", "honky", "hooker", "hoor", "hoore", "horniest", "horny", "hot carl", "hotsex", "hussy", "hustler", "hymen", "jack off", "jackass", "jacking off", "jackoff", "jack-off", "jap", "japs", "jerk", "jerkoff", "jerk-off", "jesus", "jesus christ", "jew", "jews", "jiggaboo", "jisim", "jism", "jiss", "jiz", "jizm", "jizz", "jugs", "jungle bunny", "kike", "kill", "killer", "killing", "kinky", "kkk", "klan", "klux", "knives", "knob", "knobs", "knobz", "kock", "kondum", "kondums", "kraut", "kum", "kummer", "kumming", "kums", "kunilingus", "kunt", "kunts", "kuntz", "latex", "Lesbian", "lesbian", "lesbians", "lesbo", "Lezzian", "lingerie", "Lipshits", "Lipshitz", "loser", "love mayo", "lsd", "lust", "lustful", "lusting", "lusty", "mace", "madame", "mafia", "marijuana", "masochist", "masokist", "massterbait", "masstrbait", "masstrbate", "masterbaiter", "masterbate", "masterbates", "masturbate", "masturbating", "Masturbation", "masturbation", "merde", "mistress", "money shot", "moon cricket", "moose knuckle", "Motha Fucker", "Motha Fuker", "Motha Fukkah", "Motha Fukker", "mothafuck", "mothafucka", "mothafuckas", "mothafuckaz", "mothafucked", "mothafucker", "mothafuckers", "mothafuckin", "mothafucking", "mothafuckings", "mothafucks", "mother fucker", "Mother Fucker", "Mother Fukah", "Mother Fuker", "Mother Fukkah", "Mother Fukker", "motherfuck", "motherfucked", "motherfucker", "mother-fucker", "motherfuckers", "motherfuckin", "motherfucking", "motherfuckings", "motherfucks", "mound", "muff", "muff diving", "munitions", "murder", "murderer", "Mutha Fucker", "Mutha Fukah", "Mutha Fuker", "Mutha Fukkah", "Mutha Fukker", "mutilation", "n1gr", "naked", "nakedness", "nastt", "nasty", "naughty", "nazi", "nazis", "negligee", "nerd", "nigga", "nigger", "nigger", "niggers", "nigur", "niiger", "niigr", "nipple", "nob", "nobhead", "nude", "nudity", "nymph", "orafis", "orgasim", "orgasim", "orgasims", "orgasm", "orgasms", "orgasum", "oriface", "orifice", "orifiss", "packi", "packie", "packy", "paki", "pakie", "paky", "panties", "panty", "papist", "pcp", "pecker", "peeenus", "peeenusss", "peenus", "peinus", "pen1s", "penas", "penetration", "penis", "penis-breath", "penises", "penus", "penuus", "perforate the colon", "pervert", "perverted", "phonesex", "Phuc", "Phuck", "Phuk", "phuk", "phuked", "Phuker", "phuking", "phukked", "Phukker", "phukking", "phuks", "phuq", "pimp", "pink sock", "piss", "pissed", "pisser", "pissers", "pisses", "pissin", "pissing", "pissoff", "playmate", "playmates", "polac", "polack", "polak", "Poonani", "Poonanni", "poontang", "porch monkey", "porn", "porno", "pornography", "pornos", "pr1c", "pr1ck", "pr1k", "prairie nigger", "prick", "prickpenis", "pricks", "prostitute", "punk", "puss", "pusse", "pussee", "pussies", "pussy", "pussys", "puuke", "puuker", "queef", "queer", "queers", "queerz", "quickie", "qweers", "qweerz", "qweir", "raghead", "rape", "recktum", "rectum", "rectus", "retard", "rifle", "rifles", "rim job", "rogue", "rum", "rusty trombone", "sadist", "sand nigger", "satan", "satanism", "scank", "schlong", "screw", "screwing", "semen", "sensual", "sensuous", "sex", "sexual", "sexuality", "sexually", "sexy", "Sh!t", "sh1t", "sh1ter", "sh1ts", "sh1tter", "sh1tz", "sheister", "shit", "shit face", "shited", "shitfeces", "shitfull", "shiting", "shitings", "shits", "shitted", "shitter", "shitters", "shitting", "shittings", "Shitty", "shitty", "Shity", "shitz", "shocker", "Shyt", "Shyte", "Shytty", "Shyty", "skanck", "skank", "skankee", "skankey", "skanks", "Skanky", "skeet", "skin flute", "slag", "slant", "slave", "slaves", "slay", "slayer", "sleaze", "slut", "slutprostitute", "sluts", "Slutty", "slutz", "smack", "smut", "snatch", "snowball", "snuff", "son-of-a-bitch", "spank", "spank the monkey", "spanked", "spanking", "Spaz", "sperm", "spic", "spik", "spunk", "strip", "strippers", "striptease", "studs", "suck", "sucker", "sucking", "suicide", "supremacy", "swinger", "swingers", "taint", "taste the waste", "teabagging", "testicle", "testicles", "thc", "tip drill", "tit", "titbreast", "tits", "toss the salad", "towel head", "turd", "twat", "twot", "underwear", "va1jina", "vag1na", "vagiina", "vagina", "vaginas", "vaj1na", "vajina", "vart", "virginity", "virgins", "vullva", "vulva", "w0p", "wanker", "wench", "wenches", "wetback", "Wetback", "wh00r", "wh0re", "whipped", "whiskey", "White Cracker", "Whitey", "whore", "wine", "witchcraft", "wog", "wop", "xrated", "xxx"];
	var lowerCaseCheck = this.toLowerCase(), bl = badwords.length, me = this, clean = "####################";
  RegExp.multiline = true;
	for(var i=0;i<bl;i++) {
		if(lowerCaseCheck.indexOf(badwords[i]) != -1) {
      me = me.replace(new RegExp("" + badwords[i] + "", "gi"), clean.substring(0, badwords[i].length));
    }
	}
	return me;
};

String.prototype.isEmail = function() {
	return (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(this));
};


// validation functions
////////////////////////////////////////

initFormValidation = function() {
  var start = new Date();
  
  var foc; // where to put focus on form load
  
  // hide empty error spans
  $("span.error").each(function(){
    if(this.innerHTML === "") {
      $(this).hide();
    } else {
      // error condition, so place focus on first error field
      if(!foc) {
        foc = $(this).siblings("input")[0];
        if(!foc) {
          foc = $(this).siblings("select")[0];
        }
      }
    }
  });
  
  // add validation handlers to forms
  $("form.validate").submit(function(e) { 
    return validateForm(this);
  });
  
  // set tab index, disable autocomplete
  var tab = 1;
  $("form.validate input, form.validate select, form.validate textarea").each(function() {
    $(this).addClass("tabme");
  });
  $("form.validate .tabme").each(function() {
    if(this.type != "hidden") {
			this.setAttribute("autocomplete", "off");
			this.tabIndex = tab;
      if(tab == 1 && !foc) {
        foc = this;
      }
      tab++;
		}
  });
  
  // show form
  $("form.validate").css("visibility", "visible");
  
  // focus first input or first error input
  if(foc&& foc.focus && foc.type !="hidden") {
    foc.focus();
  }
  
 //alert(new Date() - start);
};

validateForm = function(f) {
  // validate required fields
  var result = $.map($(f).find(".required").not("span"), function(el) {
    return testField(el, true) ? null : false;
  });
  
  // validate optional fields
  var result2 = $.map($(f).find(".optional"), function(el) {
    return testField(el, false) ? null : false;
  });
  
  if(result[0] === false || result2[0] === false) {
    // focus on first error field
    var errfield = $(".errorfield")[0];
    if(errfield) {
      errfield.focus();
    }
    return false;
  }
  
  return true;
};

testField = function(el, required) {
  var id = el.id;
  
  switch(id) {
    
    case "youremail":
    case "theiremail":
      var v = $(el).val();
      var eid = $("#" + id + "_error");
      if(required) {
        if(v.isEmpty()) {
          showErr(el, eid, "Please type an e-mail address.");
          return false;
        }
      }
      if(!v.isEmpty()) {
        if(!v.isEmail()) {
          showErr(el, eid, "Please type an e-mail address in the following format: yourname@example.com");
          return false;
        }
      }
      hideErr(el, eid);
      break;
      
    case "yourname":
    case "theirname":
      var v = $(el).val();
      var eid = $("#" + id + "_error");
      if(required) {
        if(v.isEmpty()) {
          showErr(el, eid, "Please enter first name.");
          return false;
        } 
      }
      if(!v.isEmpty()) {
         var vp = v.isProfane();
         if(v != vp) {
          $(el).val(vp);
          showErr(el, eid, "Some information may be incorrect or inappropriate. Please try again.");
          return false;
        }
      }
      hideErr(el, eid);
      break;
      
    case "theirmessage":
      var v = $(el).val();
      var eid = $("#" + id + "_error");
      if(required) {
        if(v.isEmpty()) {
          showErr(el, eid, "Please enter a message.");
          return false;
        } 
      }
      if(!v.isEmpty()) {
         var vp = v.isProfane();
         if(v != vp) {
          $(el).val(vp);
          showErr(el, eid, "Some information may be incorrect or inappropriate. Please try again.");
          return false;
        }
      }
      hideErr(el, eid);
      break;
      
    case "txtKeyword":
      var v = $(el).val();
      var eid = $("#" + id + "_error");
      if(required) {
        // part of a validation group? (product and promo advanced search)
        if($(el).parents("fieldset.validate-group").size()) {
          if(v.isEmpty()) { // validate the additional fields in the group
            var result = false;
            $(el).parents("fieldset.validate-group").find(".group").each(function() {
              if(testField(this, false)) result = true;
            });
            if(!result) {
              showErr(el, eid, "Please select or enter at least one search criterion.");
              return false;
            }
          }
        } else if(v.isEmpty()) {
          showErr(el, eid, "Keyword is required.");
          return false;
        }
      }
      hideErr(el, eid);
      break;
      
    case "ddlCategories":
    case "ddlBrands":
    case "ddlTypes":
      var v = $(el).val();
      if(v.isEmpty()) {
        return false;
      }
      break;
      
    case "zip":
      var v = $(el).val();
      var eid = $("#" + id + "_error");
      if(required) {
        if(v.isEmpty()) {
          showErr(el, eid, "Please type a ZIP code.");
          return false;
        }
      }
      if(!v.isEmpty()) {
         if(!v.isZIP()) {
          showErr(el, eid, "Please type a valid 5-digit U.S. ZIP code.");
          return false;
        }
      }
      hideErr(el, eid);
      break;
  }
  return true;
};

hideErr = function(input, el) {
  $(input).removeClass("errorfield");
  el.hide();
  el.html("");
};

showErr = function(input, el, msg) {
  $(input).addClass("errorfield");
  el.hide();
  el.html(msg);
  el.fadeIn(1000);
};


/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop, 
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements 
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 * 
 * For accurate readings make sure to use pixel values.
 *
 * @name offset	
 * @type Object
 * @param HTMLElement refElement The offset returned will be relative to this elemen.
 * @cat DOM
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(refElem) {
	if (!this[0]) throw 'jQuery.fn.offset requires an element.';

	refElem = (refElem) ? jQuery(refElem)[0] : null;
	var x = 0, y = 0, elem = this[0], parent = this[0], sl = 0, st = 0;
	do {
		if (parent.tagName == 'BODY' || parent.tagName == 'HTML') {
			// Safari and IE don't add margin for static and relative
			if ((jQuery.browser.safari || jQuery.browser.msie) && jQuery.css(parent, 'position') != 'absolute') {
				x += parseInt(jQuery.css(parent, 'marginLeft')) || 0;
				y += parseInt(jQuery.css(parent, 'marginTop'))  || 0;
			}
			break;
		}

		x += parent.offsetLeft || 0;
		y += parent.offsetTop  || 0;

		// Mozilla and IE do not add the border
		if (jQuery.browser.mozilla || jQuery.browser.msie) {
			x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
			y += parseInt(jQuery.css(parent, 'borderTopWidth'))  || 0;
		}

		// Need to get scroll offsets in-between offsetParents
		var op = parent.offsetParent;
		do {
			sl += parent.scrollLeft || 0;
			st += parent.scrollTop  || 0;
			parent = parent.parentNode;
		} while (parent != op);
	} while (parent);

	if (refElem) {
		var offset = jQuery(refElem).offset();
		x  = x  - offset.left;
		y  = y  - offset.top;
		sl = sl - offset.scrollLeft;
		st = st - offset.scrollTop;
	}

	// Safari and Opera do not add the border for the element
	if (jQuery.browser.safari || jQuery.browser.opera) {
		x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y += parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
	}

	return {
		top:  y - st,
		left: x - sl,
		width:  elem.offsetWidth,
		height: elem.offsetHeight,
		borderTop:  parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0,
		borderLeft: parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0,
		marginTop:  parseInt(jQuery.css(elem, 'marginTopWidth'))  || 0,
		marginLeft: parseInt(jQuery.css(elem, 'marginLeftWidth')) || 0,
		scrollTop:  st,
		scrollLeft: sl,
		pageYOffset: window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop  || 0,
		pageXOffset: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0
	};
};

var veg = function(mark){
	var p = mark.parentNode.parentNode.getElementsByTagName('label');
	var pl = p.length;
	for(var l=0; l<pl; l++){
		p[l].style.backgroundImage='none';
	}
	mark.parentNode.style.backgroundImage = 'url(/images/check.gif)';
}


var veggieType = function(){
	if(document.getElementById('btnSubmit')){
		document.getElementById('btnSubmit').onclick=function(){
			Kellogg.track("/action/veggietypesurvey/advancescreen"+(submitCount+2))
		}
	}
	
	if(document.getElementById('btnSkip')){
		document.getElementById('btnSkip').onclick=function(){
			Kellogg.track("/action/veggietypesurvey/skip"+(submitCount+2))
		}
	}

	if(document.getElementById('chalkboard')){
		var c = document.getElementById('chalkboard');
		var clickable = c.getElementsByTagName('input');
		var cc = clickable.length;
		for(var l=0; l<cc; l++){
			if(clickable[l].getAttribute('type') == 'radio') {
				if(clickable[l].checked) {
					veg(clickable[l])
				}
				clickable[l].onclick=function(){
					veg(this);
				}
			}	
		}
		var submitCount =0;
		var set1 = ['fs-1','fs-2','fs-3'];
		var set2 = ['fs-4','fs-5','fs-6'];
		var set3 = ['fs-7','fs-8','fs-9'];
		
		if(document.getElementById('Form1')){
			document.getElementById('Form1').onsubmit=function(){
				submitCount++;
				switch(submitCount){
					case(1):
						for(var loop = 0; loop<set1.length; loop++) {
							document.getElementById(set1[loop]).style.display = 'none';
						}
						
						for(var loop = 0; loop<set2.length; loop++) {
							document.getElementById(set2[loop]).style.display = 'block';
						}				
						return false;
					break;
					
					case(2):
						for(var loop = 0; loop<set2.length; loop++) {
							document.getElementById(set2[loop]).style.display = 'none';
						}
						for(var loop = 0; loop<set3.length; loop++) {
							document.getElementById(set3[loop]).style.display = 'block';
						}
						document.getElementById('btnSubmit').style.backgroundImage = 'url(/images/hd_type_continue.gif)'				
						return false;
					break;
					
					default:
					return true;
				}
			}
		}
	}
	//Tracking for the veggie type thank-you page.
	if(document.getElementById('typecontinue')){
		Kellogg.track("/action/veggietypesurvey/complete");
		document.getElementById('typecontinue').onclick=function(){
			Kellogg.track("/action/veggietypesurvey/complete")
		}
		return true;
	}
}


var loadInsiderHome = function(){
	$('#insider_landing_recipes').appendTo('#wrapper_inner');
	$('#btnInsiderLogin, #btnInsiderJoin').click(function(e){
		var $reg = $('#reg_overlay'),
			s = ($(this).attr('rel') == 'signup') ? 'RegistrationLaunch.aspx?bypasslogin=1' : 'RegistrationLaunch.aspx',
			t = ($(this).attr('rel') == 'signup') ? '/insiderlanding/signup' : '/insiderlanding/login';
		$reg.find('iframe').attr('src',s);
		overlay($reg);
		BGC.track(t);
		e.preventDefault();
	})

	var over = function(x){
		if(ie6 == 1) {
			x.setAttribute('title', x.firstChild.nodeValue);
		}
		else {
			x.parentNode.parentNode.getElementsByTagName('img')[0].style.display = "block";
		}
	}

	var out = function(x){
		if (!ie6) {
			var d = x.parentNode.parentNode.getElementsByTagName('img')[0];
			setTimeout(function(){d.style.display='none'},1000);
		
			if(document.getElementById('xdb')) {
				var db = document.getElementById('xdb');
				db.parentNode.parentNode.getElementsByTagName('img')[0].style.display="none";
				db.id="";
			}
		}
	}
	
	if(document.getElementById('inpop-list')){
		var ie6 = 0;
		if(typeof(XMLHttpRequest) == 'undefined') {
			ie6 = 1;
		}
		else {
			/*Preload the PNGs.*/
			var img = new Image();
			var images = ['/images/pop_weeklyideas.png','/images/pop_recipebox.png','/images/pop_recipeexchange.png','/images/pop_guide.png','/images/pop_comfortfood.png','/images/pop_products.png',]
			var imgl = images.length;
			for(var l=0; l<imgl; l++){
				img.src=images[l];
			}			
		}

		var d = document.getElementById('inpop-list');
		var a = d.getElementsByTagName('a');
		var al = a.length;
		for(var i=0; i<al; i++) {
			a[i].onmouseover = function(){over(this)}
			a[i].onmouseout = function(){out(this)}
		}
		/*Show one of the word bubbles pop on load.*/
		defaultBubble = a[0];
		defaultBubble.id="xdb"
		over(defaultBubble);
	}
}

var recipeHovers = function(){
	if(document.body.id == "weeklyideas"){
		var d = document.getElementById('content').getElementsByTagName('a');
		var dl = d.length;
		for(l=0; l<dl; l++){
			if(d[l].className.indexOf('recipelink') != -1) {
				d[l].onmouseover = function() {
					var x = this.getElementsByTagName('img');
					if (x != null && x.length > 0) {
						x[0].style.display='block';
					}
				}
				d[l].onmouseout = function() {
					var x = this.getElementsByTagName('img');
					if (x != null && x.length > 0) {
						x[0].style.display='none';
					}
				}
			}
		}
	}
}

var commentScroll = function(){
/*Can't override .net form action location, so dynamically adding an anchor to URL for article comments.*/
	if(document.getElementById('anc-comment')){
		/*document.location += '#anc-comment';*/
		return true;
	}
}

var shoplist = function(){
	if(document.getElementById('shoppinglist')) {
		var flagShow = function() {
			if(window.XMLHttpRequest){
				this.parentNode.firstChild.style.display = "block";
				
			}
		}
		
		var flagHide = function() {
			if(window.XMLHttpRequest){
				var x = this.parentNode.firstChild;
				setTimeout(function(){x.style.display='none'},250);
				
			}
		}
	
		var d = document.getElementsByTagName('table');
		var dl = d.length;
		for (var t=0; t<dl; t++) {
			if(d[t].className.indexOf('tblshoppinglist') != -1) {
				var links = d[t].getElementsByTagName('a');
				var ll = links.length;
				for (var i=0;i<ll;i++){
					links[i].onmouseover=flagShow;
					links[i].onmouseout=flagHide;
					links[i].onmouseout();

					links[i].style.cursor='pointer';
					links[i].style.cursor='pointer';
					
					if (i == 0 && links[i].id.equals('rptRecipes__ctl0_rptIngredients__ctl0_lnkUp')) {
						links[i].style.cursor='default';
					}
					
					if (i == ll-2 && links[i].id.equals('rptRecipes__ctl0_rptIngredients__ctl0_lnkDown')) {
						links[i].style.cursor='default';
					}
				}
			
				var inputs = d[t].getElementsByTagName('input');
				var il = inputs.length;
				for (var j=0;j<il;j++ ) {
					if(inputs[j].getAttribute('type') == 'text'){
						inputs[j].onblur = function(){
							        try {
										$.post("/bin/msf/ShoppingList.json", { amount: this.value, inname: this.id } );
							        } catch(err) {alert(err)}
						}
					}
				}
			}
		}
	}
}

/* Recipe Conversion Tool */

var rct = function(){
	if(document.getElementById('recipe_conversion')) {
		var d = document.getElementById('rct_ballbearings');
		
		switch(query){
			case('american'):
				d.innerHTML = '<img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_beanskillet.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_chili.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_american_burger.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_burger.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_omelet.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_blueburger.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_club.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_jambalayashrimp.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_american_sausagearugala.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_pattymelt.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_burgersalad.jpg" width="150" height="225" alt="">'
			break;
			case('delivery'):
				d.innerHTML = '<img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_szechwan.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_stirfry.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_sausage_pizza.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_mooshuwrap.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_artichokedip.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_springrolls.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_tabbouleh.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_calzones.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_takeout_mangoriblet.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_chiknpearsalad.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_pomodoro.jpg" width="150" height="225" alt="">'
			break;
			case('breakfast'):
				d.innerHTML = '<img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_breakfast_sandwich.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_breakfast_casserole.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_breakfast_skillet.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_breakfast_pancake.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_breakfast_focaccia.jpg" width="150" height="225" alt="">';
			break;
			case('southern'):
				d.innerHTML = '<img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_quesadillas.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_brunch_tortillas.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_chipolteburritos.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_tostadas.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_eggrolls.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_beantriangles.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_bbqrcorn.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_bbqmangop.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_sw_swriblet.jpg" width="150" height="225" alt="">';
			break;
			case('mom'):
				d.innerHTML = '<img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_maccheese.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_sausage_casserole.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_potpie.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_crumblepie.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_greenbean.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_meatlessloaf.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_salads_leeksoup.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_slasagna.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_spaghetti.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_mom_lasagna.jpg" width="150" height="225" alt="">'
			break;
			default:
				d.innerHTML = '<img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_new_04.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_new_05.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_new_01.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_new_02.jpg" width="150" height="225" alt=""><img src="/content/dam/kelloggs/morningstarfarms/comfortmakeover/sideimages/rct_bb_new_03.jpg" width="150" height="225" alt="">'
			break;
		}
		
		var l = document.getElementById('rct_nav_left');	
		var r = document.getElementById('rct_nav_right');
		var prev;
		var catLength = d.getElementsByTagName('img').length;
		var pos = Math.floor(catLength/2);
		if (pos%2 == 0) {pos=pos-1};
		
		var swap = function(x) {
			var i = "main" + x;
			document.getElementById(i).style.top=0;
			if(typeof(prev) != "undefined"){
				var j = "main" + prev
				document.getElementById(j).style.top="-9000px";
			}
			prev = x;
		}
		
		var navLeft = function(){
			var style = d.style.left;
			pos = (pos > 1) ? pos-1 : catLength;
			d.insertBefore(d.lastChild, d.firstChild);
			swap(pos);
			BGC.track("/MakeOver/scrollleft")
			return false;
		}
		
		var navRight = function(){
			var style = d.style.left;
			pos = (pos < catLength) ? pos+1 : 1;
			d.appendChild(d.firstChild);
			swap(pos);
			BGC.track("/MakeOver/scrollright")
			return false;
		}
			
		l.onclick=navLeft;
		r.onclick=navRight;
		swap(pos);
		
		var trackViewRecipe = function(){
			BGC.track("/MakeOver/viewrecipe")
		}
		
		/*Navigation Highlight*/
		if(document.getElementById('rct_cats')) {
			var nav = document.getElementById('rct_cats').getElementsByTagName('a');
			var nl = nav.length;
			if(typeof(query) == "undefined") {
				nav[0].className = "rct_current";
			}
			else {
				for(var l=0; l<nl; l++) {
					if(nav[l].getAttribute('rel') == query) {
						nav[l].className = "rct_current";
					}
					nav[l].onclick = function(){BGC.track("/MakeOver/foodcategory/"+this.getAttribute('rel')); return true;}
				}
			}
		}
		
		var ptags = document.getElementsByTagName('p');
		var ptagslength = ptags.length;
		for(var ploop = 0; ploop < ptagslength;ploop++) {
			if(ptags[ploop].className == "rct_c_comment_copy"){
				if(ptags[ploop].innerHTML.toLowerCase().indexOf('<strong></strong>') != -1){
					ptags[ploop].parentNode.style.marginBottom = "30px";				
					ptags[ploop].style.display = "none";

				}
			}
		}
		
var hidCom = document.getElementById('hdnComment');
if(hidCom){
if(hidCom.value == "1") {
	var cP="main"+pos;
	var commentForm = document.getElementById(cP).getElementsByTagName('fieldset')[0];
	var blurb = document.getElementById(cP).getElementsByTagName('div')[2];
	blurb.style.display = "none";
	commentForm.style.display = "block";
}
}
		
		/*Comment Form Switch*/
		/*console.log(document.getElementById('rct_commentblurb').getElementsByTagName('a')[0])
		document.getElementById('rct_commentblurb').getElementsByTagName('a')[0].onclick = function() {
			document.getElementById('rct_commentblurb').style.display = "none";
			document.getElementById('commentform').style.display = "block";
			return false;
		}*/
	}/* /Primary If*/
}

var addShop = function(x){
	try {
		$.get(x.href);
		x.parentNode.innerHTML="Added to list";
	} catch(err) {alert(err)}
}

var showComment = function(x){
	var blurb = x.parentNode.parentNode;
	var commentForm = blurb.parentNode.getElementsByTagName('fieldset')[0];
	blurb.style.display = "none";
	commentForm.style.display = "block";		
	return false;	
}

var socialBookmarking = function() {
	if(document.getElementById('socialbookmark-intro-link')) {
		var sbl = document.getElementById('socialbookmark-intro-link');
		var sbi = document.getElementById('socialbookmark-intro');
		//var sbia = sbi.getElementsByTagName('a')[0];
		sbl.onmouseover = function(){sbi.style.display="block"; return false;};
		sbl.onclick = function(){return false;};
		//sbi.onmouseout = function(){sbi.style.display="none"; return false;};
		$('#socialbookmark-intro').hover(function(){return true}, function(){$(this).toggle()});
		
	}
	else {
		var x = setTimeout(socialBookmarking, 1000);
	}
}

var productPromos = function(){
	if(document.getElementById('product_promos')) {
		switch(query['id']){
		case('355'):
			document.getElementById('product_promos').style.marginTop="10px";
			document.getElementById('product_promos').innerHTML = '<a href="http://living.health.com/2008/05/08/americas-healthiest-food-breakfast/" target="_blank" onclick="OutsideURLWarning(this); return false;"><img src="/images/product_promo_healthmag.jpg" width="261" height="161" alt=""></a>';
		break;
		
		case('321'):
        case('323'):
        case('331'):
        case('5710'):
        case('5950'):
        case('320'):
        case('314'):
			document.getElementById('product_promos').innerHTML = '<img src="/images/product_promo_chefsbest2009.jpg" width="250" height="120" alt="">';
		break;		        
		}
	}
}

var recipePromos = function(){
	if(document.getElementById('recipe_promos')) {
		var d = document.getElementById('recipe_promos');
		var ryanScott = '<div><span>This exclusive <em>Morningstar Farms&reg;</em> recipe was created by five-star chef Ryan Scott.</span></div>';
		switch(query['id']){
			case('10842'):
			case('10841'):
			case('10822'):
			case('10821'):
				d.innerHTML = ryanScott;
		}
	}
}

var homepageRecipeOfTheWeek = function(){
	if(document.getElementById('home_sidebar_rotw')){
		Date.prototype.getWeek = function() {
			var onejan = new Date(this.getFullYear(),0,1);
			return Math.ceil((((this - onejan) / 86400000) + onejan.getDay())/7);
		}
		
		/*Debuggable (or exploitable, for the source-code readers): add a querystring of rotw=[week_number_in_year]*/
		if(typeof(query['rotw']) != 'undefined'){
			if(!isNaN(query['rotw'])){
				var week = query['rotw'];
			}
			else{
				var today = new Date();
				var week = today.getWeek();	
			}
		}
		else {
			var today = new Date();
			var week = today.getWeek();
		}
		
		var r =[
			["rotw_burger_gardenveggie.jpg","Garden Veggie Deluxe Burger","7543"],
			["rotw_burger_american.jpg","Classic American Burger","9943"],
			["rotw_ribletwrap.jpg","Mango Riblet Wrap","10884"],
			["rotw_burger_chunkygrilled.jpg","Burgers with Chunky Grilled Vegetables","5443"],
			["rotw_potatosalad.jpg","Warm Italian Sausage, Potato and Arugula Salad","10886"],
			["rotw_chilipepperburgers.jpg","Southwest Chili Pepper Burgers","4268"],
			["rotw_quesadillas.jpg","Barbecue Riblet and Corn Quesadillas","10882"],
			["rotw_jambalaya.jpg","Jambalaya-Style Rice with Shrimp and Sausage","10862"],
			// ["rotw_chicagodog.jpg","Chicago Style Dogs","9942"],
			["rotw_pizza.jpg","Spicy Black Bean Burger Pizza","6402"],	
			["rotw_riblets.jpg","Barbecue Riblets with Mango-Pinepple Salsa","10883"]
		]
		var selR = (52-week)%r.length;
		if (selR < 0) { selR = 0;}	
		var d = document.getElementById('home_sidebar_rotw');
		var src = d.getElementsByTagName('a')[0].href = '/recipe_detail.aspx?id='+r[selR][2];
		var img = d.getElementsByTagName('img')[0].src = '/images/'+r[selR][0];
		var src = d.getElementsByTagName('a')[1].href = '/recipe_detail.aspx?id='+r[selR][2];
		var title = document.getElementById('rotw_recipe_name').firstChild.innerHTML = r[selR][1];
		var print = document.getElementById('rotw_print').href='/print/print_full.aspx?id='+r[selR][2];
	}
}

var toggleArchive = function(x){
	if(document.getElementById('guidelist')){
		$('.archive_toggle').find('a').click(function(){
			$(this).parent().parent().find('.archive').slideToggle('fast');
			$(this).parent().toggleClass('at_less');
			$(this).find('span').toggle();
			return false;
		})
	}
}

// search functionality
var navSearch = function(){
	if (document.forms['navSearch'] != null){
		var d = document.forms['navSearch'][0];
		var val = "Quick Recipe Search";
		d.value=val;
		d.onfocus=function(){
				this.value="";
				this.style.color="#000000";
		};
		d.onblur=function(){
			if(this.value == ""){
				this.value=val;
			}
			this.style.color="#7F7F7F";
		};
	}
}

// overlay(s)
	launchoverlay = function(id) {
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
		
		window.scrollTo(0,0);
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(500);	
		$('#mask').fadeTo("fast",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/1.5);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(500); 
	};
	
	buildoverlay = function(id, url){
	    $.get(url, null, function(data){$("#boxes").append(data); launchoverlay(id)}, "text");
	};
	
	hideoverlay = function(){
	    $('#mask, .window').hide();
	};
	

function externalLinks(){
	var $a = $('a');
	$a.filter('[href$=.pdf]').attr('target','_blank')
	$a.filter('[rel=ext]').attr('target','_blank');
	
	/*
	$('.ext').click(function(){
		OutsideURLWarning(this.href);
		return false;
	});
	*/

};

function rotateFeature(){
    var $a = $('#home_sidebar_rotating div');
    if($a.length > 0){
	    $a.toggle();
	    var x = setTimeout(rotateFeature, 5000);
    };
};

function contestContentHeight(){
	var c = $('#contestContent');
	if(c.length > 0){
		var marginDiff = 0//43;
		var side = $('#sidebar').height();
		var content = $('#content').height();
		if(side > content){
			c.css('paddingBottom',side-content+marginDiff)
		}
		//console.log(side,'-',content, side-content+marginDiff)
	};
};

function swfContest(){
	buildoverlay('#regov','/overlay_sweeps_registration.aspx');
	BGC.track('/action/partiesthatcook/registration');
}

		// vidArray used on the homepage to set the video cookie, as well as on the search results page to set the recipe search results video banner

		var vidArray = new Array();
		vidArray[0] = new Array("2167", "Quick and Easy Meatless Chili", "Making this super-satisfying family meal is simple. Just take a look!", "video_chili", 'chili');
		vidArray[1] = new Array("10882", "Barbecue Riblet and Corn Quesadillas", "Watch how to cook up these sweet and smoky crowd pleasers, meatless-style.", "video_riblet", 'riblet');
		vidArray[2] = new Array("10886", "Warm Italian Sausage, Potato and Arugula Salad", "See how simple it is to toss together this refreshing twist on potato salad.", "video_salad",'salad');
		vidArray[3] = new Array("1932", "Asian Veggie Stir-Fry", "Better-for-you stir-fry can be quick, easy and flavorful - just watch!", "video_stirfry",'stirfry');
		
		var vidArrayLength = vidArray.length;

function searchRecipes(criteria, value){
/*
	Criteria:Value keys. Pick one of the below.
	category:numeric. KIC ID;
	product:numeric. KIC ID;
	time:{15,30,45,60,90};
	txtSearch:string;
	txtSearch2:string;
*/
	criteria = criteria || 'txtSearch';
	value = value || '';
	var x = '<form action="/recipe_search.aspx" id="searchRecipes" method="post"><input type="hidden" name="'+criteria+'" value="'+value+'"></form>';
	$('body').append(x);
	$('#searchRecipes').submit();
}

/*Flash function for sausage update. 2010 Q1*/
function altVisit(){
	var x = (readCookie('flashSwap') == 1) ? 0 : 1;
	createCookie('flashSwap',x,365);
	return x;
}

/* MDS Video Functionality */
function overlay(element){
	
	element = element || $('<div id="overlay_canvas"></div>')
	var w = $(document).width(),
		h = $(document).height(),
		ew = element.width(),
		eh = element.height();

	element.css({'left':(w-ew)/2, 'top':'75px'}).show();

	$('#mask').css({'width':w,'height':h}).show();
}

function cycleVideo(vid){
	if($('.cooking_video').length == 0){return false;}

	vid = (vid != null && vid != 'undefined') ? vid : 'chili';
	var e = $('.cooking_video'),
		hover = '<div class="hoverstate" rel="'+vid+'">&nbsp;</div>';

	e.hide().siblings('#vid_'+vid).show().each(function(){
		$(this).find('.video_copy').append($('#more_vids_hd, #more_vids_list')); //Eliminate the gap caused by clearing elements.
		var x = $(this).next('.cooking_video'),
			cookieString = (x.length > 0) ? x.attr('rel') : e.eq(0).attr('rel');
			
		createCookie('msf_video',cookieString,365)
	});
	$('#more_vids_list').children().show().siblings('#li_'+vid).hide();
	
	//Add and give functionality to .hoverstate.
	$('.video_thumb').append(hover);
	$('.hoverstate').click(function(){
		overlay($('#video_overlay'));
		cookingVid($(this).attr('rel'))
	}).mouseover(function(){
		$(this).css('background-position','bottom left')
	}).mouseout(function(){
		$(this).css('background-position','top left')
	})
};

function checkForVideo(){
	if(!!query.vid){
		if(parseInt(query.vid) < vidArrayLength){
			overlay($('#video_overlay'));
			cookingVid(vidArray[query.vid][4]);
		}
	}
}

function prepVidSidebar(){
	var vidSidebar = '';
	
	for(var i=0; i<vidArrayLength; i++){
		vidSidebar+='<div rel="'+vidArray[i][4]+'">';
		vidSidebar+='<img src="/images/dot.gif" class="ms_video_image '+vidArray[i][3]+'_img" height="74" width="133">';
		vidSidebar+='<h4>'+vidArray[i][1]+'</h4>';
		vidSidebar+='<p>'+vidArray[i][2]+'</p>'
		vidSidebar+='</div>'+"\r\n"
	}
	$('#ms_video_sidebar').html(vidSidebar);
	
	$('.ms_video_image').click(function(){
		cookingVid($(this).parent().attr('rel'))
	}).mouseover(function(){
		$(this).css('background-position','bottom left')
	}).mouseout(function(){
		$(this).css('background-position','top left')
	})
}

function cookingVid(videoID){
	var video = videoID || 'chili',
		arrayIndex = 0,
		l = vidArrayLength;
		
		while(l--){
			if(vidArray[l][4] == video){
				arrayIndex = l;
				break;
			}
		}

	/*SWF Object/Video Embed*/
	var params = {
		align:"TL",
		scale:"noScole",
		scaleMode:"noScole",
		allowScriptAccess:"always",
		allowFullScreen:"true",
		wmode:"transparent"
	};
		
	var vars={
		videoURL:videoDomain + "/video_" + video + ".mp4",
		previewImage:"/images/video_" + video + "_default.jpg?r="+Math.random(),
		autoPlay:"false",
		loop:"false",
		backgroundColor1:"0x487837",
		backgroundColor2:"0x5e8851",
		movieBackgroundColor:"0x000000",
		inkColor:"0xc8dbb2",
		highlightColor:"0xffffff",
		playButoon:"true",
		seekBar:"true",
		timeBar:"true",
		volumeButton:"true",
		fullScreenButton:"true",
		autoHide:"false",
		autoHideFullScreen:"true",
		offsetY:"0",
		offsetYFullScreen:"25",
		margins:"0",
		marginsFullScreen:"0",
		volume:"70",
		bufferTime:"15",
		smoothing:"auto"
	};

	var attributes = {}; 

	swfobject.embedSWF("swf/jcplayer.swf", "ms_video", "410", "255", "9.0.47", "swf/expressinstall.swf", vars, params, attributes);
	
	/*Video Sidebar*/
	prepVidSidebar();
	$('#ms_video_sidebar>div[rel='+video+'] .ms_video_image').css({'background-position':'0 -74px','cursor':'default'}).unbind();
	
	/*Social Bookmarking*/
	var pageUrl = "http://" + window.location.host + "/?vid="+arrayIndex;
	var pageTitle = vidArray[arrayIndex][1];
	addthis.button('#video_bookmark', {ui_click: "true"}, {url: pageUrl, title: pageTitle});
	
	/*Recipe Link*/
	$('#video_recipe_link').attr('href','/recipe_detail.aspx?id='+vidArray[arrayIndex][0])
}

function ws_close(){
	$('#mask, .msoverlay').hide();
}


/* Grilling Phase 3 Flash */
function flashSetVid(x){
	var x = x || 'null'; //Yes, null is intentionally set to a string and is therefore not truly null. I know.
	$('body').data('flashString',x)
}

function flashPassVid(){
	return $('body').data('flashString') || 'null'; //Yes, null is intentionally set to a string and is therefore not truly null. I know.
	//set to videoName in swf.
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookieWithDomain(name, domain){
	createCookie(name,"",-1,domain);
}

function eraseCookie(name){
    createCookie(name,"",-1);
}

function addItemToShoppingList(category, id){

	CQ.Ext.Ajax.request({
	"method": "POST",
	"async" : false,
	"url": "/bin/msf/ShoppingList.json",
	"success": function(response) {
	var responseInfo = CQ.Ext.util.JSON.decode(response.responseText);
	if (responseInfo.code == 1){
	if (category == "recipe"){
	alert("Recipe added to the shopping list");
	}
	if (category == "product"){
	alert("Product added to the shopping list");
	}
	}else{
	if (category == "recipe"){
	alert("Unable save the recipe to the shopping list");
	}
	if (category == "product"){
	alert("Unable save the product to the shopping list");
	}
	}
	},
	"failure": function(){
	CQ.Log.error("Error trying to save item to shopping list");
	},
	"scope": this,
	"params": {
	"method": category,
	"action" : "add",
	"val" : id
	}
	});
	}


