jQuery(document).ready(function(){
	initAccordion(jQuery("#accordion .sectionHeader"));
	jQuery("#accordion .sectionHeader").bind("click", toggleAccordion);
	jQuery("#accordion .externalLink").unbind("click", toggleAccordion);
	// ajax functions
	setupAjax();
	jQuery(".recipeListBlock .selectList .previous a").hide();
	jQuery(".recipeListBlock .tabs a, .recipeList .selectList a").bind("click", getNewRecipeList);
	jQuery(".recipeListBlock .recipeList #typePlat").bind("change", getNewRecipeList); 
});


function initAccordion(obj) {
	jQuery(obj).next().hide();
	jQuery(obj).parent().removeClass("active");
	jQuery(obj).parents(":eq(1)").find("#first").addClass("active");
	jQuery(obj).parents(":eq(1)").find("#first div").show();
}


function toggleAccordion() {
	if(jQuery(this).parent().attr("class") != "active") {
		var myItem = jQuery(this);
		jQuery("#accordion li").removeClass("active");
		jQuery(this).parent().addClass("active");
		jQuery("#accordion li div:visible").slideUp(500);
		jQuery(myItem).next().slideDown(500);
	}
	jQuery(this).blur();
	return false;
}


//////////* AJAX RECIPE-RELATED FUNCTIONS *///////////


//setting up global ajax calls parameters
function setupAjax() {
	$.ajaxSetup({
		url: "/a_table/Interface/getListRecipeByIdCategory.aspx",
		type: "POST",
		dataType: "json"
	});
}


//Getting new recipe items

function getNewRecipeList(ref) {
	
	
	if(jQuery(this).parent().attr("class") != "active") {
		var activatedElm = jQuery(this);
				
		//current items
		var currentRecipeItems = jQuery(".recipeItems li");
		var currentMealTypes = jQuery(".recipeList #typePlat option");
		
		
		//creating loading layer
		jQuery(".recipeItems #loading, .recipeListBlock #mask").remove();
		jQuery(".recipeListBlock").prepend("<div id=\"mask\"></div>");
		jQuery(".recipeItems").append("<li id=\"loading\"><div><p>chargement des informations...</p></div></li>");
		
		
		// defining params
		var needHeaderElement = 0;
		var catId = jQuery(this).attr("rel");
		var numPage = 0;
		
		if(jQuery(this).parents(":eq(1)").attr("class") == "tabs"){
			jQuery(this).parents(":eq(1)").find("li").removeClass("active");
			jQuery(this).parent().addClass("active");
			needHeaderElement = 1;
			
			//extending loading layer to cover everything we change
			jQuery(".recipeItems #loading").addClass("extended");
		}else if(jQuery(this).attr("name") == "typePlat"){	
			catId = jQuery(this).val();
		}else if(jQuery(this).parents(":eq(1)").attr("class") == "selectList") {
			numPage = jQuery(this).attr("href");
		}else{
			numPage = jQuery(this).attr("href");
		}
		
		// setting needHeaderElement for new ajax attempt
		if(ref.data.ElementNode != undefined) {
			if(ref.data.ElementNode.parents(":eq(1)").attr("class") == "tabs"){
				needHeaderElement = 1;	
			}
			jQuery(".recipeItems #loading").addClass("extended");
		}
		
		//start of ajax call
		jQuery(".recipeItems #loading").fadeIn(450, function(){
			jQuery(".recipeListBlock #mask").show();
			jQuery.ajax({
				data: "idCat="+catId+"&numPage="+numPage+"&needHeaderElement="+needHeaderElement,
				beforeSend: function(){},
				success: function(data){
					//cleaning old items
					currentRecipeItems.remove();
					
					myData = eval("(" + data + ")");
					
					var recipeArray = myData.RecipeItems;
					var mealType = myData.ComboBoxItem;
					
					//Ptsan : if no mealtype, no need to display combo box and Recipe
					//		
					
//					console.log(myData.RecipeItems.length);
//					console.log(myData.ComboBoxItem.length);
//					if (myData.RecipeItems.length==0)
//					    jQuery(".recipeItems").hide();
//					 else
//					   jQuery(".recipeItems").show();
//					    

					if (needHeaderElement){					    
					    if (myData.ComboBoxItem.length==0)
					        jQuery(".headerList select").hide(); //direct access to select does not work. need to access it from parent					   
 				       else
                        jQuery(".headerList select").show();					       
					}
					    					

					    
					    switch(needHeaderElement) {
						    // combo change or page change
						    case 0:
							    for(var i = 0; i < recipeArray.length; i++) {
								    jQuery(".recipeItems").append("<li><a href=\""+recipeArray[i].link+"\"><img src=\""+recipeArray[i].urlImage+"\" alt=\""+recipeArray[i].label+"\" /></a><a href=\""+recipeArray[i].link+"\" class=\"recipeLabel\">"+recipeArray[i].label+"</a></li>");
								    if(i % 2) {
									    jQuery(".recipeItems li:last").addClass("rightItem");
								    }
							    }
							   
							    if(myData.HasNextPage == 1){
								    jQuery(".selectList .next a:hidden").fadeIn(450);
							    }							   
							    
							    break;
						    // click on a new tab
						    case 1:
							    if(jQuery(".homeRecettes").length > 0) {
								    jQuery(".recipeList .labelTitle img").attr({
									    src: myData.LabelTitle.urlImage,
									    alt: myData.LabelTitle.text
								    });
								    jQuery(".recipeList .labelTitle img").attr({
									    src: myData.LabelTitle.urlImage,
									    alt: myData.LabelTitle.text
								    });
								    var myClone = jQuery(".recipeList p.headerList img").clone();
								    jQuery(".recipeList p.headerList").html(myData.IntroELements.text);
								    myClone.attr({
									    src: myData.IntroELements.urlImage,
									    alt: ""
								    }).appendTo(".recipeList p.headerList");
							    }else{
								    jQuery(".recipeList p.headerList strong").text(myData.LabelTitle.text);
							    }
    							
							    for(var i = 0; i < mealType.length; i++) {
								    jQuery(".recipeList #typePlat").append("<option value=\""+mealType[i].ComboBoxItemValue+"\">"+mealType[i].ComboBoxItemText+"</option>");
							    }
							    //removing old recipe items and old meal type items
							    currentMealTypes.remove();
							    jQuery(".recipeList #typePlat option:eq('0')").attr("selected", "selected");
    							
							    for(var i = 0; i < recipeArray.length; i++) {
								    jQuery(".recipeItems").append("<li><a href=\""+recipeArray[i].link+"\"><img src=\""+recipeArray[i].urlImage+"\" alt=\""+recipeArray[i].label+"\" /></a><a href=\""+recipeArray[i].link+"\" class=\"recipeLabel\">"+recipeArray[i].label+"</a></li>");
								    if(i % 2) {
									    jQuery(".recipeItems li:last").addClass("rightItem");
								    }
							    }
							    jQuery(".selectList .previous a").fadeOut(450);
							    if(myData.HasNextPage == 1){
								    jQuery(".selectList .next a:hidden").fadeIn(450);
							    }
							    jQuery(".selectList .previous a").attr("href", "0");
							    jQuery(".selectList .next a").attr("href", "1");
							    break;			
					   // }		
					}
					//removing loading layer
					jQuery(".recipeItems #loading").fadeOut(450, function(){
						jQuery(".recipeListBlock #mask").remove();
						jQuery(".recipeItems #loading").remove();
					});
				}, 
				complete:function(theRequest, message){
					// page number
					switch(activatedElm.parent().attr("class")){
						case "headerList":
							numPage = 0;
							// updating category label
							var myCat = jQuery(activatedElm).val();
							jQuery(".selectList a").attr("rel", myCat);
							break;
						case "previous":
							if(numPage > 0) {
								var currentPage = parseInt(numPage) - 1;
							}else{
								var currentPage = numPage;
							}
							if(myData.HasPreviousPage == 1){
								jQuery(".selectList .previous a:hidden").fadeIn(450);
								jQuery(".recipeList .previous a").attr("href", currentPage);
							}else{
								jQuery(".selectList .previous a").fadeOut(450);
							}
							if(myData.HasNextPage == 1){
								jQuery(".selectList .next a:hidden").fadeIn(450);
								var nextPage = parseInt(jQuery(".recipeList .next a").attr("href"));
								jQuery(".recipeList .next a").attr("href", nextPage - 1);
							}
							break;
						case "next":
							if(numPage > 0) {
								var currentPage = parseInt(numPage) - 1;
							}else{
								var currentPage = numPage;
							}
							
							if(myData.HasNextPage == 1){
								numPage = parseInt(numPage) + 1;
								jQuery(".selectList .next a:hidden").fadeIn(450);
								jQuery(".recipeList .next a").attr("href", numPage);
							}else{
								jQuery(".selectList .next a").fadeOut(450);
							}
							if(myData.HasPreviousPage == 1){
								jQuery(".selectList .previous a:hidden").fadeIn(450);
								jQuery(".recipeList .previous a").attr("href", currentPage);
							}
							break;
						default:
							// updating category label
							var myCat = jQuery(activatedElm).attr("rel");
							jQuery(".selectList a").attr("rel", myCat);
							break;
					}				
				},
				error: function(theRequest, errorType, exceptionObject){
					jQuery(".recipeItems #loading p").html("Une erreur est survenue.<a href=\"\">R&eacute;essayer</a>");
				} 
			});
		});
	}
	jQuery(this).blur();
	return false;
}
