var sortValues = [ "rating", "productname" ];
var filterValues = [ "", "CAT_LinkSausage", "CAT_SmokedSausage",
                    ["CAT_LunchMeat", "SUB_LunchMeat_ThinSliced", "SUB_LunchMeat_UltraThin", "SUB_LunchMeat_HeartySlices", "SUB_LunchMeat_VarietyPack", "SUB_LunchMeat_FamilySize","SUB_LunchMeat_LowerSodium"],
                    "CAT_CocktailLinks", "CAT_SummerSausage",
                    ["CAT_Ham", "SUB_Ham_BoneIn", "SUB_Ham_Boneless"]];

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"));
	var value = index >= 0 && index <= filterValues.length ? filterValues[index] : filterValues[0];
	if (value instanceof Array) {
		var subindex = $("#filterContainer ul li.selected ul.subcategories li").index($("#filterContainer ul li.selected ul.subcategories li.selected"));
		value = subindex >= 0 && subindex < value.length ? value[subindex] : value[0];
	}
	return value;
}

function filterClick() {
	var parent = $(this).closest("li");
	$("#filterContainer ul li.selected").removeClass("selected").removeClass("expanded");
	$("#filterContainer ul.subcategories").hide();
	parent.addClass("selected");
	var index = $("#filterContainer > ul > li").index($("#filterContainer > ul > li.selected:first"));
	if (filterValues[index] instanceof Array) {
		parent.addClass("expanded");
		parent.find("ul").show().find("li:first").addClass("selected");        
	}
	refreshItems();
	return false;
}

function filterSubCatClick() {
	var parent = $(this).closest("li");
	$(this).closest("ul.subcategories").find("li.selected").removeClass("selected");
	parent.addClass("selected");
	refreshItems();
	return false;
}

function useDetailsView() {
	if(tabFlag)
			return false;
	else
			return true;
}

function refreshItems() {
	$("#productsList").html(loadingMarkup);
	$.ajax({
		type: "POST",
		url: basePath + "ajax/products/" + (useDetailsView() ? "detailsview" : "listview") + ".aspx",
		dataType: "html",
		data: { sort: sortValue(), filter: filterValue() },
		success: function(html){
			$("#temporal").html(html);
			$("#productsList").html($("#temporal").find(".productView"));
			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(productChange);
				});
			} else {
				$(".footerContent #bottomNav").fadeOut('slow');
				$(".footerContent #bottomNav .scrollable .items").html("");
			}
			resetProductFunctions();
		},
		error: function(){
			$("#productsList").html(ajaxErrorMarkup);
		}
	});
}

function productChange() {
	$("#productsList").html(loadingMarkup);
	var productId = $(this).find("input:first").attr("value");
	$.ajax({
		type: "GET",
		url: basePath + "ajax/products/product.aspx?id=" + productId,
		dataType: "html",
		success: function(html){
			$("div#productsList").html(html);
			resetProductFunctions();
		},
		error: function(){
			$("#productsList").html(ajaxErrorMarkup);
		}
	});
	return false;
}

function resetProductFunctions(){
	setupProducts("#productsList");
	setupTabs();
	//itemTitleReplace();
	reinitializeAddThis();
  //Call popup to load the nutritional Info
	$('.showNutritional').click(showNutritionalPopUp);	
}

$(document).ready(function () {
	$("#sortContainer ul li a").click(sortClick);
	$("#filterContainer > ul > li > a").click(filterClick);
	$("#filterContainer ul.subcategories li a").click(filterSubCatClick);
	$("#bottomNav .items > a").click(productChange);
	
  $(".thickbox").click(applyProductPopUpIFR);
  //Call popup to load the nutritional Info
	$('.showNutritional').click(showNutritionalPopUp);	
	setupProducts("#productsList");	
	//Call popup to load the previous print recipes
	$('#suggestProduct').click(suggestProductClick);
	// 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;
	});
});

//Call popup to load suggest a product     
function suggestProductClick(){                                                                  
    $('#suggestContainer').modal();   
    $("#modalPopUpContainer a.modalCloseImg").css({top:"5px",right:"5px"});      
}

//Call popup to load the nutritional Info
function showNutritionalPopUp(){	 
	var productId = $(this).attr("rel");
	var clickedElement = this;
	$.ajax({
		type: "GET",
		url: basePath + "ajax/products/nutritionFacts.aspx?id=" + productId,
		dataType: "html",
		success: function(html){
			$("div.modalNutritional", clickedElement.parentNode).html(html);
			$("div.modalNutritional ul.nutritionFactImages li:first img", clickedElement.parentNode).load(function() {
			    getNutritionImageLarge($(this).closest("li"), true);
			});
			$("div.modalNutritional", clickedElement.parentNode).modal();	
			applyReciperVideoPopUpIFR();
			$('.selectFactInfo').change(showNutritionalInfoPopUP);
			$(".infoToShow0").css('display','block');	
			applyProductPopUpIFR();			 		
		},
		error: function(){
			$("div.modalNutritional").html("Error!");
		}
	});
	return false;
}

//Show nutritional info popup and change the image to display
function showNutritionalInfoPopUP(){

    var optionSelected = $(this).val();
    var parent = $(this).closest("#simplemodal-data");          
    var list=$("ul.nutritionFactImages li", parent);                                                               
    for(var i=0;i<list.length;i++){  
        $("."+$(list[i]).attr('class'), parent).css('display','none');                                               
    }                
    $("."+optionSelected, parent).css('display','block');
    var pic = $("."+optionSelected, parent);
    getNutritionImageLarge(pic, false);
}

//Get Large to show the nutritional Image on the popup
function getNutritionImageLarge(pic, validateZero){
  
    var pic_real_width = pic.width();
    var pic_real_height = pic.height();   
    if (validateZero && pic_real_height==0)
        return;   
    
   
        
    if ((pic_real_height>350)&&(pic_real_height<=525)){            
       $('#modalPopUpContainer').css({height:"560px",width:"660px"});
         
    }else if ((pic_real_height>525)&&(pic_real_height<600)){            
       $('#modalPopUpContainer').css({height:"600px",width:"700px"});                   
    }else{                 
       $('#modalPopUpContainer').css({height:"400px",width:"860px"});
     
    }                                         
    var popupW = $('#modalPopUpContainer').width();
    $('#modalPopUpContainer').css({left: '50%', marginLeft: (popupW/2*-1)+'px'});

    applyProductPopUpIFR();   

}