
//create a holder for various bits of kitchen info
var oKchnInfo = new Object();
oKchnInfo.currentState = "";
oKchnInfo.nextState = "";
oKchnInfo.nextHref = null;
oKchnInfo.handleLink = function(oHref, nxtState)
{
	oKchnInfo.nextState = nxtState;
	oKchnInfo.nextHref = oHref;
	oKchnInfo.nextIID = $(oHref).getUrlParam('iid');
	if ( oKchnInfo.currentState != oKchnInfo.nextState )
	{
		logItem("requesting state change to: " + nxtState);
		changeState(nxtState);
		//showPage(nxtState);
	}
	else if ( nxtState == "/recipes" )
	{
		logItem("state remained '/recipes', iid= " + oKchnInfo.nextIID);
		setTimeout( function () {oKchnInfo.nextHref = null;}, 5000);
		showRecipe(oKchnInfo.nextIID);
	}
	else if ( nxtState == "/table" )
	{
		logItem("state remained '/table', iid= " + oKchnInfo.nextIID);
		setTimeout( function () {oKchnInfo.nextHref = null;}, 5000);
		showArticle(oKchnInfo.nextIID);
	}
	else if ( nxtState == "/ask" )
	{
		logItem("state remained '/ask', iid= " + oKchnInfo.nextIID);
		setTimeout( function () {oKchnInfo.nextHref = null;}, 5000);
		showAskTheChefSection(oKchnInfo.nextIID);
	}
}
oKchnInfo.setCurrentState = function(curState)
{
	oKchnInfo.currentState = curState;
	if ( oKchnInfo.nextHref )
	{
		oKchnInfo.handleLink(oKchnInfo.nextHref, curState);
	}
	else if ( curState == "/table" )
	{
		//the following should display the main "at the table" page.
		showArticle('spcl01');
	}
	else if ( curState == "/ask" )
	{
		//the following should display the main "Ask the Chef" page.
		//showAskTheChefSection('blahblah');
	}
}

//FUNCTIONS BEING CALLED FROM FLASH >> JS:
/*	0. function hideCategory()
	This function will be called when the user is on a category detail page 
	any time the user clicks on the flash site outside of the html overlay. */
function hideCategory()
{
	logItem("hideCategory() funciton called");
	$('#categoryOverlay').jqmHide();
}

/*	1. function hideRecipe()
	This function will be called when the user is on the recipes and tips page 
	any time the user clicks on the flash site outside of the html overlay. */
function hideRecipe()
{
	logItem("hideRecipe() funciton called");
	$('#recipeOverlay').jqmHide();
}

/*	2. function showCategory(categoryID)
	This function will be called anytime a user clicks on a recipe category inside 
	of the carousel. */
function showCategory(categoryID)
{
	logItem("showCategory() funciton called with parameter: " + categoryID);
	
	resetDynamicContent();
	
	$('#recipeLoaded').load('/cooking-entertaining/load-category.jsp?iid=' + categoryID);
	$('#recipeOverlay').jqmShow();
	
	/*
	if (categoryID.indexOf("c")===0 )
	{
		//$('#recipeLoaded').html('');
		$('#recipeLoaded').load('/cooking-entertaining/load-tip.jsp?iid=' + categoryID + '1');
		$('#recipeOverlay').jqmShow();
		//showHideEmbelishments();

	} else {
		//$('#recipeLoaded').html('');
		$('#recipeLoaded').load('/cooking-entertaining/load-category.jsp?iid=' + categoryID);
		$('#recipeOverlay').jqmShow();
		//showHideEmbelishments();
	}
	*/
}

/*	3. function showRecipe(recipeID)
	This function will be called when a user clicks on a recipe link in the
	recipes' carousel. */
function showRecipe(recipeID)
{
	logItem("showRecipe() funciton called with parameter: " + recipeID);
	
	if ( recipeID )
	{
		resetDynamicContent();
		//$('#recipeLoaded').html('');
		
		if (recipeID.indexOf("adasearch") >= 0) 
		{
			$('#searchWrapper .advancedSearchOptions').click();
		}
		else 
		{
			if ( recipeID.indexOf("c")===0 )
			{
				$('#recipeLoaded').load('/cooking-entertaining/load-tip.jsp?iid=' + recipeID, function() {
					kitchenTrack("/load-tip.jsp?iid=" + recipeID, "cooking tip " + recipeID);
					//$('body').css('background','none');
				});			
			}
			else
			{			
				$('#recipeLoaded').load('/cooking-entertaining/load-recipe.jsp?iid=' + recipeID, function() {
					kitchenTrack("/load-recipe.jsp?iid=" + recipeID, "recipe " + recipeID);
					//$('body').css('background','none');
				});
			}
		}
				
		//window.location.hash = "#/recipes/r" + recipeID;
		$('#recipeOverlay').jqmShow();
		//showHideEmbelishments();

		if (isIE6) {
			var viewportwidth = document.documentElement.clientWidth;
			var viewportheight = document.documentElement.offsetHeight - 165;
			
			setTimeout( function () {$('.jqmKitchenOverlay').css('height',viewportheight);}, 1000);
		}
	}
}
//function showArticle(id) is NOT called from Flash - just internal for us.
function showArticle(articleID)
{
	logItem("showArticle() funciton called with parameter: " + articleID);
	
	resetDynamicContent();
	//$('#tableLoaded').html('');
	if ( articleID.indexOf("e")===0 )
	{
		$('#tableLoaded').load('/cooking-entertaining/load-ent.jsp?iid=' + articleID,function() {
			kitchenTrack("/load-ent.jsp?iid=" + articleID, "entertaining tip " + articleID);
			setTimeout('setNewHeight(true)', 100);
			//showHideEmbelishments();
		});
		//window.location.hash = "#/table/" + articleID;
	}
	else if ( articleID.indexOf("spcl")===0 )
	{
		$('#tableLoaded').load('/cooking-entertaining/load-special.jsp?iid=' + articleID,function() {
			kitchenTrack("/load-special.jsp?iid=" + articleID, "At the Table");
			setTimeout('setNewHeight(true)', 100);
			//showHideEmbelishments();
		});		
		//window.location.hash = "#/table";
	}
	else
	{
		$('#tableLoaded').load('/cooking-entertaining/load-article.jsp?iid=' + articleID,function() {
			kitchenTrack("/load-article.jsp?iid=" + articleID, "article " + articleID);
			setTimeout('setNewHeight(true)', 100);
			//showHideEmbelishments();
		});
		//window.location.hash = "#/table/" + articleID;
	}
	//$('#articleOverlay').jqmShow();
	$('#tableOverlay').show('fast',function() {
		setTimeout('setNewHeight(true)', 100);
		//showHideEmbelishments();
	});
	$('#footer').hide();
}
function showAskTheChefSection(sectionID)
{
    logItem("showAskTheChefSection() funciton called with parameter: " + sectionID);
    
	if ( sectionID )
	{
		var chefID = sectionID.toLowerCase();
	    
	    if (chefID == "calendar") 
	    {
			$('.jqmWindow div').html('');
			$('.jqmWindow div').load('/inc/jsp/calendar-of-events.jsp');
			$('.jqmWindow').jqmShow();
			return false;
		} else {
	    
		    if ( chefID )
			{
				resetDynamicContent();
						
				$('#chefLoaded').load('/cooking-entertaining/load-chef.jsp?iid=' + chefID,function() {
					kitchenTrack("/load-chef.jsp?iid=" + chefID, "section " + chefID);
					setTimeout('setNewHeight(true)', 100);		
				});
				
				$('#chefOverlay').jqmShow();
				
				if (isIE6) {
					var viewportwidth = document.documentElement.clientWidth;
					var viewportheight = document.documentElement.offsetHeight - 165;
					
					setTimeout( function () {$('.jqmKitchenOverlay').css('height',viewportheight);}, 1000);
				}
			}
		}	
	}
	
	//$('#footer').hide();
}

function updateTopic(topicName) 
{
	//Hide all topics and show selected topic
	$('.topic, .videoSection').hide();
	$('#' + topicName).show();
	
	//Change the css based on which topic was selected
	$(".relatedTopicsTom a").removeClass("sel");	
	$(".relatedTopicsTom a#" + topicName + "Link").addClass("sel");
	$("a.tomVideoLink").removeClass("selVideo");
	
	$(".relatedTopics a").removeClass("sel");	
	$(".relatedTopics a#" + topicName + "Link").addClass("sel");
	
	if (topicName.indexOf("Videos") > -1) {		
		var id = $('div#' + topicName + " p:first-child a").attr("id");
		var strHTML = "<a id='" + id + "' class='tomVideoLink' href=''><img src='/images/kitchen/video_play.jpg' width='375px' height='230px' alt='' border='0' /></a>";
		$('div#tomVideoFlash').html(strHTML);	
	}
}


function showHideEmbelishments() {
	var maxRand = 10;
	var randNumSpoon = Math.floor(Math.random()*maxRand+1);
	var randNumParsleyLong = Math.floor(Math.random()*maxRand+1);
	var randNumParsleyShort = Math.floor(Math.random()*maxRand+1);

	if (randNumSpoon < 6) {
		$('div.spoon').hide();
	}
	if (randNumParsleyLong < 6) {
		$('div.parsleyLong').hide();
	}
	if (randNumParsleyShort < 6) {
		$('div.parsleyShort').hide();
	}
}

function updateIntroCopy(section) {
	logItem("updateIntroCopy() funciton called with parameter " + section);
	$('#introWrapper').load('/cooking-entertaining/inc/jsp/intro-wrapper-content.jsp?section=' + section);
}

function showRecipeCloseOther(recipeID) {
	$('#chefOverlay').jqmHide();
	window.location = "/cooking-entertaining/#/recipes";	
	var functionStr = "showRecipe('" + recipeID + "')";
	setTimeout ( functionStr, 1000 );	
}

function setNewHeight(bool) {
	if (bool) {
		var tableOverlay = $('#tableOverlay').outerHeight();
//		var recipeOverlay = $('#recipeOverlay').outerHeight();
		var windowHeight = $(window).height();


//		var pageHeight = (tableOverlay > recipeOverlay) ? tableOverlay : recipeOverlay;
		var pageHeight = (tableOverlay > windowHeight) ? tableOverlay : windowHeight;
		$('body').css('height',pageHeight);
	} else {
		$('body').css('height','auto');
	}
}

/*	4. function showPage(pageID)
	This function will be called when the flash animations to a new state 
	have finished. */
function showPage(pageID)
{
	var alertMsg = "showPage() funciton called with parameter: " + pageID;
	$('#searchWrapper,#introWrapper').hide();
	if ( pageID )
	{
		oKchnInfo.setCurrentState(pageID);
		$('body').removeClass('atTheTable').removeClass('recipesTips').removeClass('askTheChef');
		$('#introWrapper').removeClass('askChefIntro');
		
		var eventIdPrefix = '/load/html/page/';
		
		if ( pageID == "/" )
		{
			$('body').css('background-image', 'url(/images/kitchen/bodybkgd/BkgdCEcounter.jpg?v=2)');
			$('#flashFader').hide();
			trackEvent(eventIdPrefix + 'landing');
		}
		else if ( pageID == "/recipes" )
		{
			updateIntroCopy("recipe");
			$('body').addClass('recipesTips').css('background-image', 'url(/images/kitchen/bodybkgd/BkgdCEcarousel.jpg?v=2)');
			$('#flashFader').hide();
			$('div#searchWrapper').css({top : '500px', left : '50px'});
			$('#searchWrapper,#introWrapper').show();
			
			trackEvent(eventIdPrefix + 'recipesAndTips');
			fireSrTag("RecipesTips");
			fireFlTag("src=1352258;type=dietc152;cat=dcrec866");
		}
		else if ( pageID == "/table" )
		{
			$('body').addClass('atTheTable').css('background-image', 'url(/images/kitchen/bodybkgd/BkgdCEdining.jpg?v=2)');
			$('#flashFader').show();
			
			trackEvent(eventIdPrefix + 'atTheTable');
			fireSrTag("AtTheTable");
			fireFlTag("src=1352258;type=dietc152;cat=dcatt190");
		}
		else if ( pageID == "/ask" )
		{					
			updateIntroCopy("chef");
			$('body').addClass('askTheChef').css('background-image', 'url(/images/kitchen/bodybkgd/BkgdCEcounter.jpg?v=2)');
			$('#flashFader').hide();
			$('div#searchWrapper').css({'top' : '530px', 'left' : '30px'});
			$('#introWrapper').addClass('askChefIntro');
			$('#searchWrapper,#introWrapper').show();
			
			trackEvent(eventIdPrefix + 'eatWell');
			fireSrTag("AsktheChef");
			fireFlTag("src=1352258;type=dietc152;cat=dcask314");						
		}
		else 
		{
			$('body').css('background-image', 'url(/images/kitchen/bodybkgd/BkgdCEkitchen.jpg?v=2)');
		}
	}
	
	logItem(alertMsg);
}

function loadPage(nxtState, pageURL)
{
	showPage(nxtState);

	logItem("loadPage() function called: " + nxtState + ", " + pageURL);
	
	resetDynamicContent();
	
	if (nxtState == '/recipes')
	{
		$('#recipeLoaded').load(pageURL);
		oKchnInfo.nextHref = new Object();
		$('#recipeOverlay').jqmShow();
		//showHideEmbelishments();
	} else if (nxtState == '/ask') {
		$('#chefLoaded').load(pageURL);
		oKchnInfo.nextHref = new Object();
		$('#chefOverlay').jqmShow();
	}	

}

/*	5. function applicationReady()
	This function will be called when the Preloader Flash is ready to 
	proceed (after it's done, well, preloading :-). */
function applicationReady()
{
	var alertMsg = "applicationReady() funciton called";
	oKchnInfo.currentState = "ready";
	alertMsg += "\ncurrent state set to \"ready\"";
	try
	{
		if ( window.location.hash.length > 1 )
		{
			alertMsg += "\nfound hash data, will 'auto' launch()";
			launch();
		}
		else
		{
            //will pass the following session var into javascript - 
            //if value is not null, will pass in flashvar to skip
            //kitchen intro video (so it's only shown once/browser session)
            setSvar('skippedKitchenVideoIntro', (new Date()).toString());
        }
	}
	catch(arerr1) {}
	logItem(alertMsg);
}

//FUCNTIONS BEING CALLED FROM JS >> FLASH:
/*  1. function changeState(newState)
	This function will be called when the user clicks on the nav in the upper left hand 
	corner of the page.  The function will take the new state in the form an int.  
	Phenomblue will provide the int values of each state. */
function changeState(newState)
{
	$('#tableOverlay').hide('fast',function() {
		setTimeout('setNewHeight(false)', 100)
	});	
	
	$('#footer').show();
	
	var flashObjID = "kitchenFlash";
	var alertMsg = "changeState() funciton called with parameter: " + newState;
	
	alertMsg += "\nlooking for DOM object with ID: " + flashObjID;
	//look for Flash object with id attribute from swfobject call
	var $flash = $('#' + flashObjID);
	if ( $flash.size() == 0 )
	{
		alertMsg += "\nNOT FOUND!";
	}
	else
	{
		alertMsg += "\nlooking for ExternalInterface function named: changeState... ";
		if ( typeof $flash.get(0).changeState != "undefined" )
		{
			$flash.get(0).changeState(newState);						
			alertMsg += "invoked";
		}
		else
		{
			alertMsg += "NOT FOUND!";
		}
	}
	logItem(alertMsg);
}

/*  2. function hideRecipeOrCategory()
	This function will be called when the user closes an HTML overlay displaying 
	either a recipe or a category. */
function hideRecipeOrCategory()
{
	var flashObjID = "kitchenFlash";
	var alertMsg = "hideRecipeOrCategory() funciton called";
	//window.location.hash = "#/recipes";
	alertMsg += "\nlooking for DOM object with ID: " + flashObjID;
	//look for Flash object with id attribute from swfobject call
	var $flash = $('#' + flashObjID);
	if ( $flash.size() == 0 )
	{
		alertMsg += "\nNOT FOUND!";
	}
	else
	{
		alertMsg += "\nlooking for ExternalInterface function named: hideRecipeOrCategory... ";
		if ( typeof $flash.get(0).hideRecipeOrCategory != "undefined" )
		{
			$flash.get(0).hideRecipeOrCategory();
			alertMsg += "invoked";			
		}
		else
		{
			alertMsg += "NOT FOUND!";
		}
	}
	logItem(alertMsg);
}

/*  3. function launch()
	This function will be called when the user closes on a main kitchen navigation item 
	while still at the Preloader (before the intro video plays). */
function launch()
{
	var flashObjID = "kitchenFlash";
	var alertMsg = "launch() funciton called";
	
	alertMsg += "\nlooking for DOM object with ID: " + flashObjID;
	//look for Flash object with id attribute from swfobject call
	var $flash = $('#' + flashObjID);
	if ( $flash.size() == 0 )
	{
		alertMsg += "\nNOT FOUND!";
	}
	else
	{
		alertMsg += "\nlooking for ExternalInterface function named: launch... ";
		if ( typeof $flash.get(0).launch != "undefined" )
		{
			$flash.get(0).launch();
			alertMsg += "invoked";
		}
		else
		{
			alertMsg += "NOT FOUND!";
		}
	}
	logItem(alertMsg);
}

function resetDynamicContent()
{
	$('#recipeLoaded').empty();
	$('#tableLoaded').empty();
	$('#chefLoaded').empty();
}


function mainNavRequest(requestedState)
{
	/* if (oKchnInfo.currentState == 'ready')
	{
		launch(); //'ready' indicates preloader ready to play intro
	}
	else if (oKchnInfo.currentState.indexOf("/")==0)
	{*/
		oKchnInfo.nextHref = null;
		changeState(requestedState);
	/*}
	else
	{
		var alertMsg = "??? mainNavRequest() called, requestedState=" + requestedState + ", currentState=" + oKchnInfo.currentState;
		logItem(alertMsg);
	}*/
}

function kitchenTrack(trkurl, trktitle)
{
	try
	{
		dcsMultiTrack("DCS.dcssip", DCS.dcssip, "DCS.dcsuri", window.location.pathname + trkurl, "WT.ti", trktitle);
	}
	catch(trkerr1) {}
}

function fireSrTag(tag)
{
	try
	{
		if ( tag )
		{
			var searchRevTag = new Image();
			searchRevTag.src = "https://s1.srtk.net/www/delivery/ti.php?trackerid=696&cb=1045758303&_sr_amount=0&_sr_page_values=" + tag;
		}
	}
	catch(srterr1) {}
}

function fireFlTag(tag)
{
	try
	{
		if ( tag )
		{
			logItem("fireFlTag called with tag=" + tag);
			
			var rndOrd = Math.floor(Math.random()*100000000);
			floodlightTag = "http://fls.doubleclick.net/activityi;" + tag + ";ord=" + rndOrd + "?";
			
			var flDiv = document.getElementById("DCLK_FLDiv");
			if ( ! flDiv )
			{
				flDiv = document.body.appendChild(document.createElement("div"));
				flDiv.setAttribute("id","DCLK_FLDiv");
				flDiv.style.position = "absolute";
				flDiv.style.visibility = "hidden";
				flDiv.style.top = "0px";
			}
			var iFrameHTML = '<iframe id="DCLK_FLIframe" src="' + floodlightTag + '"></iframe>';
			flDiv.innerHTML = iFrameHTML;			
			
			//alert ("iFrameHTML = " + iFrameHTML); //uncomment if needed for local testing
		}
	}
	catch(srterr1) 
	{
		logItem("fireFlTag error - " + flerr1);
	}
}

$(document).ready(function () 
{
	//setup overlay divs
	$.jqm.params.overlayClass = 'jqmKitchenOverlay';
	
	
	var closeItem = function(hash) { hash.w.fadeOut('1000',function(){ hash.o.remove(); hideRecipeOrCategory(); resetDynamicContent();}); };
	$('#recipeOverlay,#categoryOverlay,#chefOverlay').jqm({onHide:closeItem});
	
	$('#tableOverlay').jqm({overlay:0});
	
	//while in the "kitchen", update nav links to request the Flash to change 
	//to the appropriate state (instead of actually "linking" some place.)
	$('#navCE a.link').click(function(evnt)
	{
		mainNavRequest("/");
		return false;
	});
	$('#navCERT a').click(function(evnt)
	{
		mainNavRequest("/recipes");
		return false;
	});
	$('#navCEAT a').click(function(evnt)
	{
		mainNavRequest("/table");
		return false;
	});
	
	$('#navCEAC a').click(function(evnt)
	{
		mainNavRequest("/ask");
		return false;
	});	
	
	var swfvrsnId = null;
	try
	{
		swfvrsnId = DKO.swfvrsnId;
	}
	catch(underr1)
	{
		swfvrsnId = "1.1.1";
	}
	
	//use standard swfobject2 to embed the Flash
	var flashvars = {};
	if (DKO.skipVideo && DKO.skipVideo > "")
	{
        flashvars = { skipIntro: "true"};
        //logItem(flashvars);
    }
	var params = {
		menu: "false",
		wmode: "transparent"
	};
	var attributes = {
		id: "kitchenFlash",
		name: "kitchenFlash"
	};
	swfobject.embedSWF(
			"/cooking-entertaining/Preloader.swf?vrsn=" + swfvrsnId, 
			"kitchenReplace", 
			"990", "550", "9.0.0", 
			null, 
			flashvars, params, attributes);
});
