var sortValues = [ "rating", "totalcooktime", "recipename", "productname" ];
var filterValues = [ "FeaturedRecipes", "Appetizers", "Breakfast", "Lunch", "Dinner", "SaladsSoupsAndStews", "Grill", "SoulFood", "BetterForYou", "HasDemo", "MyRecipeBox", "KeywordSearch" ];
//var filterValues = [ "FeaturedRecipes", "Appetizers", "Breakfast", "Lunch", "Dinner", "SaladsSoupsAndStews", "Grill", "SoulFood", "HasDemo", "MyRecipeBox", "KeywordSearch" ];
var recipesLastKeywordQuery = "";
var productIDsQuery = "";
var productFilterState = new Object();
var changesFlag = false;
function sortValue() {
	var index = $("#sortContainer ul li").index($("#sortContainer ul li.selected:first"));
	return index >= 0 && index <= sortValues.length ? sortValues[index] : sortValues[0];
}

function sortClick() {
	$("#sortContainer ul li.selected").removeClass("selected");
	$(this).closest("li").addClass("selected");
	refreshItems();
	return false;
}

function filterValue() {
	var index = $("#filterContainer ul li").index($("#filterContainer ul li.selected:first"));
	return index >= 0 && index <= filterValues.length ? filterValues[index] : filterValues[0];
}

function filterClick() {
	$("#filterContainer ul li.selected").removeClass("selected");
	$("#filterContainer ul li.keywordSearch").removeClass("expanded");
	if ($(".selectProducts").hasClass("selected"))
	{
		if (productIDsQuery == "")
		{
			$(".selectProducts").removeClass("selected");
			$(this).closest("li").addClass("selected");
		}
	}
	else
	{
		$(this).closest("li").addClass("selected");
	}
	var filter = filterValue();
	if (filter == "KeywordSearch") {
		$(this).closest("li").addClass("expanded");
		$("#filterContainer .keywordSearchTerms").show();
		$("div#leftSideProductControl").css("top", "531px");
	} else  {
		refreshItems();
		$("#filterContainer .keywordSearchTerms").hide();
		$("div#leftSideProductControl").css("top", "511px");
	}
	return false;
}

function filterKeywordSearchGo() {
	recipesLastKeywordQuery = $("#keywordSearchText").attr("value");
	refreshItems();
}

function showProductSelector(){
	saveProductSelectorState();
	$(this.parentNode).addClass("expanded");
	$(this).addClass("selected");
	$("#filterContainer ul li.selected").removeClass("selected");
	$("div.productSelectorPopup, div.whiteFix, div.borderTopFix").fadeIn();
	return false;
}

function hideProductSelector(){
	$("#productSelector").removeClass("expanded");
	$("div.productSelectorPopup, div.whiteFix, div.borderTopFix").fadeOut();
	$(".productTree>ul>li").removeClass("selected");
	if ($(this).hasClass("closeSelector") || $(this).hasClass("cancelProdSelection")) {
		if(changesFlag) {
			restoreSelectionControl();
			changesFlag = false;
		}
	}
	return false;
}

function productSelectionClick() {
	$(this.parentNode).toggleClass("selected").siblings("li").removeClass("selected");
	return false;
}

function submitProductSelectorFilter(){
	productIDsQuery = "";
	var values = new Array();
	var productList = new Array();
	var repeater = 0;
	var selectedProdList = "";
	$(".productTree input[type='checkbox']:checked").each(function(){
		if($(this).val() != "all"){
			values[repeater] = $(this).val();
			productList[repeater] = $(this).siblings("span").text();
			repeater++;
		}
	});
	values = uniqueArr(values);
	productList = uniqueArr(productList);
	for(i=0; i < values.length; i++){
		productIDsQuery += values[i];
		if((i+1) < values.length)
			productIDsQuery += "|";
		selectedProdList += "<a href='#' rel='" + values[i] + "' class='productSelected' title='Remove Product'>"
		+ productList[i] + "</a>";
	}
	if (productIDsQuery == "")
	{
		$(".selectProducts").removeClass("selected");
		$("#filterContainer ul li:first").addClass("selected");
	}
	refreshItems();
	$("#productFilterList").html(selectedProdList);
	hideProductSelector();
	$(".productTree>ul>li").removeClass("selected");
	changesFlag = false;
	return false;
}

function selectorControlCheckClick(){
	changesFlag = true;
	var inputObj = $(this);
	if(inputObj.is(":checked") && inputObj.val() == "all") {
		inputObj.closest("ul").find("li input:checkbox:enabled").attr('checked', true);
	} else if (inputObj.val() == "all"){
		inputObj.closest("ul").find("li input:checkbox:enabled").attr('checked', false);
	} else {
		var allOption = inputObj.closest("ul").find("input:checkbox[value='all']");
		if(allOption.is(":checked")) {
			allOption.attr('checked', false);
		}
	}
}

function removeSpecificProduct(){
	var productId = $(this).attr("rel");
	$(".productTree input[value='" + productId + "']:checked").each(function(){
		var siblingAllOption = $(this).closest("ul").find("input:checkbox[value='all']");
		if (siblingAllOption.is(":checked"))
			siblingAllOption.attr('checked', false);
		$(this).attr('checked', false);
	});
	submitProductSelectorFilter();
	return false;
}

function saveProductSelectorState() {
	productFilterState = new Object();
	var tempArray = new Array();
	$(".productTree>ul>li").each(function(i){
		tempArray = new Array();
		$("ul li input:checkbox", this).each(function(j){
			tempArray[j] = $(this).attr('checked');
		});
		productFilterState[i] = tempArray;
	});
}

function restoreSelectionControl() {
	var qtyCategories = $(".productTree>ul>li").length;
	var tempArray = new Array();
	$(".productTree>ul>li").each(function(i) {
		tempArray = productFilterState[i];
		$("ul li input:checkbox", this).each(function(j) {
			$(this).attr('checked', tempArray[j]);
		});
	});
}
    
function refreshItems() {
	$("#recipesList").html(loadingMarkup);
	var currentContiner = basePath;
	if (filterValue() == "FeaturedRecipes" )
	{
		if (tabFlag)
		{
			currentContiner += "ajax/recipes/" + (tabFeaturedRecipe ? "detailsview" : "listview") + ".aspx";
			changeTabStyle(tabFeaturedRecipe);
		}
		else
		{
			currentContiner += "ajax/recipes/" + (useDetailsView() ? "detailsview" : "listview") + ".aspx";
			changeTabStyle(useDetailsView());
		}
	}
	else
	{
		currentContiner += "ajax/recipes/" + (useDetailsView() ? "detailsview" : "listview") + ".aspx";
		changeTabStyle(useDetailsView());
	}
	var submitData;
	if (productIDsQuery != "") {
		changeTabStyle(tabSelected);
		currentContiner = basePath + "ajax/recipes/" + (tabSelected ? "detailsview" : "listview") + ".aspx";
	    submitData = { sort: sortValue(), filter: "all", keywords: "", productsIds: productIDsQuery };
	} else {
		tabSelected = false;
	    submitData = { sort: sortValue(), filter: filterValue(), keywords: recipesLastKeywordQuery, productsIds: "" };
	}
	$.ajax({
		type: "POST",
		url: currentContiner,
		dataType: "html",
		data: submitData,
		success: function(html){
			$("#temporal").html(html);
			var temporal = $("#temporal").find(".recipeView");
			$("#recipesList").html(temporal);
			if(useDetailsView() && $("#temporal").find("a").length > 1){
				$(".footerContent #bottomNav").fadeIn('slow', function(){
					$(".scrollable .items").html($("#temporal").find("a"));
					$(".scrollable .items").prepend(activeIndMarkup);
					createCarousel();
					$("#bottomNav .items > a").click(recipeChange);
				});
			} else {
				
				$(".footerContent #bottomNav").fadeOut('slow');
				$(".footerContent #bottomNav .scrollable .items").html("");
			}
			resetRecipesFunctions();
		},
		error: function(){
			$("#recipesList").html(ajaxErrorMarkup);
		}
	});
}

function changeTabStyle (currentTab)
{
	if (currentTab)
	{
		if ($('.displayTabs ul li a.list').parent().hasClass("selected") )
		{
			$('.displayTabs ul li a.list').parent().removeClass("selected").siblings("li").addClass("selected");
			$('.displayTabs ul li a.detail').css("background-position","-115px -27px");
			$('.displayTabs ul li a.list').css("background-position","0 0px");
		}
	}
	else
	{
		if ($('.displayTabs ul li a.detail').parent().hasClass("selected") )
		{
			$('.displayTabs ul li a.detail').parent().removeClass("selected").siblings("li").addClass("selected");
			$('.displayTabs ul li a.list').css("background-position","0 -27px");
			$('.displayTabs ul li a.detail').css("background-position","-115px 0px");
		}
	}
}


function useDetailsView() 
{
	if(tabFlag)
	{	
		return false;
	}
	else
	{
		return true;
	}
}

function recipeChange(){
	$("#recipesList").html(loadingMarkup);
	var recipeId = $(this).find("input:first").attr("value");
	$.ajax({
		type: "GET",
		url: basePath + "ajax/recipes/recipe.aspx?id=" + recipeId,
		dataType: "html",
		success: function(html){
			$("div#recipesList").html(html);			
			resetRecipesFunctions();			
		},
		error: function(){
			$("#recipesList").html(ajaxErrorMarkup);
		}
	});
	return false;
}

/** This clones the left side filters and put them on My Recipes Box dialog when there's no recipes added */
function cloneFilters(){
	$("#filterContainer ul").clone().appendTo(".internalMsg");
	// Hide the undesired elements
	$(".internalMsg ul li").filter(function (){
		return /My Recipe Box/i.test($(this).text()) || /Keyword/i.test($(this).text());
	}).css("display","none");
}

function resetRecipesFunctions () {
	setupRecipes("#recipesList");
	setupTabs();
	//itemTitleReplace();
	reinitializeAddThis();
	$('.printItem').click(printItemClick);	
	$('.showVideo').click(showVideoPopUp);  
}

function showBFYDisclamer() {
	var triggerPosition = $(this).position();
	$('#bfyPopup').css({'top':triggerPosition.top - 172,'left':triggerPosition.left + 15}).fadeIn();
}

function hideBFYDisclamer() {
	$('#bfyPopup').fadeOut();
	return false;
}

$(document).ready(function () {
	$("#sortContainer ul li a").click(sortClick);
	$("#filterContainer ul li a").click(filterClick);
	$("#keywordSearchButton").click(filterKeywordSearchGo);
	$("a.selectProducts").live("click", showProductSelector);
	$("a.closeSelector, a.cancelProdSelection").live("click", hideProductSelector);
	$("div.productSelectorPopup ul li a").live("click", productSelectionClick);
	$("span.bfyDisclaimer").mouseover(showBFYDisclamer);
	$("a.closeBFY").click(hideBFYDisclamer);
	$("a.acceptProdSelection").live("click", submitProductSelectorFilter);
    setupRecipes("#recipesList");
    $('.printItem').click(printItemClick);       
    $('.showVideo').click(showVideoPopUp);           
    //Call popup to load the previous print recipes
		$('#suggestRecipe').click(suggestRecipeClick);
    // check for what is/isn't already checked and match it on the fake ones
    $("input:checkbox").each( function() {
	    (this.checked) ? $("#fake"+this.id).addClass('checkedSubstituted') : $("#fake"+this.id).removeClass('checkedSubstituted');
    });
    // function to 'check' the fake ones and their matching checkboxes
    $(".checkSubstituted").click(function(){
	    ($(this).hasClass('checkedSubstituted')) ? $(this).removeClass('checkedSubstituted') : $(this).addClass('checkedSubstituted');
	    $(this.hash).trigger("click");
	    return false;
    });
    
    $(".substitutes").live("mouseover",function(){        
        substituteHeight = $(this).find(".sub-tooltip-content").height();
        substituteOffset = $(this).offset();
    });
    $("ul.productList li input:checkbox").live("click", selectorControlCheckClick);
		$("a.productSelected").live("click", removeSpecificProduct);
});

//function to print the recipe
function printRecipe(){                              
   $('#modalPopUpContainer').css({left:"100px",top:"30px"});
   print();         
}
 
//Call popup to load the previous print recipes      
function printItemClick(){        
    var recipeView = $(this).closest("div.recipeView")[0];
    $('.printContainer', recipeView).modal();
    $('.printContainer .image img').css({border:"1px solid #D5D5D5"});
    applyReciperPrintPopUpIFR(); 
    return false;
}

//Call popup to load suggest a recipe     
function suggestRecipeClick(){                                                                  
    $('#suggestContainer').modal();   
    $("#modalPopUpContainer a.modalCloseImg").css({top:"5px",right:"5px"});
}

//Call popup to load the recipe's videos
function showVideoPopUp(){	 
	var recipeId = $(this).attr("rel");
	var clickedElement = this;
	$.ajax({
		type: "GET",
		url: basePath + "ajax/recipes/watchVideo.aspx?id=" + recipeId,
		dataType: "html",
		success: function(html){
		    $("div.modalVideo", clickedElement.parentNode).html(html);
			$("div.modalVideo", clickedElement.parentNode).modal();							
			applyReciperVideoPopUpIFR();		
		},
		error: function(){
			$("div.modalVideo").html("Error!");
		}
	});
	return false;
}
