var Rayon = {
	ajaxurl: PATHRACINE + "/AjaxListProduct",	// Servlet executée ajax
	redirectUrl : PATHRACINE + "/ListProductCategorie",
	numPage: 1,							// Numero de la page
	rows: "",							// Nombre de réponse par page
	sort: "",							// Ordre de trie des produit
	facet: "",							// Requete Temporaire pour facette
	from : "",  						// Différencie le clic catégorie du click facette
	search: "", 						// mot moteur de recherche
	nivCategorie:1, 					// niveau de catégorie pour les requêtes solr
	
	// Valeur par défaut
	init:{
		idCategorie: null,	// Id de catégorie
		nivCategorie: null, // Niveau de la catégorie
		ttPage: 1			// Nombre de page totale
	},
	
	load: function(param){
		$.extend(this, this.init, param);
		
		// Gestionnaire d'evenement
		$(".btnBack").click(function(){
			Rayon.action("page", -1);
			return false;
		});
		
		$(".btnNext").click(function(){
			Rayon.action("page", +1);
			return false;
		});
		
		$(".btnRows").click(function(){
			Rayon.action("rows", $(this).attr("req"));
			return false;
		});
		
		$(".btnSort").change(function(){
			$(".btnSort").val($(this).val());
			Rayon.action("sort", $(this).val());
		});
		
		$(".facette :checkbox[name]").click(function(){
			Rayon.queryFacet(this, $(this).attr("name"));
		});
		
		$(".liste_1 > li > a[req]").click(function(){
			$(".liste_1 > li > a[req]").removeClass("bold");
			$(this).addClass("bold");
			Rayon.action("categorieFromCategorie", $(this).attr("req"));
			return false;	
		});
		
		$("#titre_gamme").click(function(){
			$("#gamme").slideDown("slow");
			$("#ligne_produit").slideUp("slow");
		});
		
		$("#titre_ligne_produit").click(function(){
			$("#gamme").slideUp("slow");
			$("#Facette").slideUp("slow");
			$("#ligne_produit").slideDown("slow");
		});
	},
	
	// Action sur la page
	action: function(param, value){
		switch (param) {
		case "page":
			// Pagination : Page Suivante, Precedente
			var newPage = this.numPage + parseInt(value);
			if(newPage < 1 || newPage > this.ttPage){
				return false;
			}
			this.numPage = newPage;
		break;
		case "sort":
			this.numPage = 1;
			this.sort = value;
		break;
		case "rows":
			this.numPage = 1;
			this.rows = value;
		break;
		case "categorie":
			this.idCategorie = value;
		break;
		case "categorieFromCategorie":
			this.numPage = 1;
			this.from = "categorie";
			this.idCategorie = value;
		break;
		case "liste_ligne_produit":
			this.nivCategorie = 3;
			this.idCategorie = value;
		break;
		default: 
			// Si action inconnu alors rien
			return false;
		break;
		}
		// Mise a jour de la liste
		this.maj();
	},
	
	// Mise a jour de la liste
	maj: function(){
	
		var search = $("#Rechercher").val();
		if (search != "Rechercher" && $.trim(search) != ''){
			this.search = $.trim(search);
		}	

		if (this.page == "homeSearch" && this.nivCategorie == 2){
			this.nivCategorie -= 1;
		}	
		
		
		var params = {
			'CategorieID': this.idCategorie, 
			'NivCategorie': this.nivCategorie,
			'sort': this.sort, 
			'rows': this.rows,
			'numPage': this.numPage, 
			'facet': this.facet,
			'from': this.from,
			'CategorieMarqueID':this.categorieMarqueID, // utilisée pour la maj de la liste produit Marque
			'search': this.search // utilisé pour le moteur de recherche
		};
		 
		if (this.from == "categorie"){
			params.facet = '';
		}
		 
		if (this.nivCategorie == 1 && this.page != "homeSearch" && catalogueID == "1"){	
			// on est dans la servlet listProductUnivers
			var paramFacet = {
				'facet': this.facet,
				'CategorieID': this.idCategorie,
				'TypeID': this.nivCategorie,
				'search': this.search
			};
			var url = this.redirectUrl +"?"+ paramsGlobal+"&"+jQuery.param(paramFacet);
			window.location = url;
			return false;
		}

		//$.getScript(this.ajaxurl +"?"+ paramsGlobal +"&"+ jQuery.param(params));
		$.ajax({ type: "GET", url: this.ajaxurl +"?"+ paramsGlobal +"&"+ jQuery.param(params), success: function(){} , dataType: "script", cache: true });
	},
	
	// Filtre par facettes
	queryFacet: function(checked,from){
		var result = "";
		var input = new Array();
		
		$(".facette :checked[name != '']").each(function(){
			var name = $(this).attr("name");
			var value = $(this).val();
			// Utilisé pour facette tranche prix.
			if(name != "facet_queries"){
				value = name +':"'+  value +'"';
			}
			
			input[name] = (input[name] != null) ? input[name] +" OR "+ value : value;
		});
		
		for(field in input){
			if(result != ""){result += " AND ";}
			result += "+(" + input[field] + ")";
		}
		
		// Sauvegarde la requete
		this.facet = result;
		this.numPage = 1;
		this.from=from;
		this.maj();
	},
	
	// Affiche la liste
	display: function(numFound, ttPage, nbProductMarqueStar, niveauCategorie){		
		this.ttPage = ttPage;
		Produit.display();
		$(".numPage").text(this.numPage);
		
		var txtNumFound = (numFound > 1) ? " articles" : " article";
		$(".numFound").text(numFound + txtNumFound);
		$(".ttPage").text(ttPage);
		// Affiche le nombre de produit de la marque Star (Chanel)
		if(nbProductMarqueStar > 0){
			var urlListProdMarqueStar = PATHRACINE + "/ListProductCategorieChanel?"+ paramsGlobal +"&CategorieID="+ this.idCategorie +"&NiveauID="+ niveauCategorie;
			if (this.search != ""){	
				urlListProdMarqueStar +=  "&search=" + this.search;
			}
			
			var lienMarqueStar = $("<a class=\"grisClair bold underline\"/>").attr("href", urlListProdMarqueStar);
			
			if(nbProductMarqueStar == 1){
				lienMarqueStar.text(nbProductMarqueStar + " produit CHANEL");
				$("#nbProductMarqueStar").html(lienMarqueStar).append(" correspond à votre recherche");
			}else{
				lienMarqueStar.text(nbProductMarqueStar + " produits CHANEL");
				$("#nbProductMarqueStar").html("Découvrir les ").append(lienMarqueStar).append(" qui correspondent à votre recherche");
			}
			
			$(".liste_resultats").css("display", "");
		}else{
			$(".liste_resultats").css("display", "none");
		}
	}
}

var Ems = {
	display: function(ems_liste) {
		$(".ems_liste").html(ems_liste);
	}
}

var Produit = {
	idContent: ".liste_donnees",
	html: "",
	
	// Ajoute ems
	appendEms: function(data){
		this.html += data;
	},
	
	// Ajoute un produit a la liste
	add: function(urlFP, productBiz, pathImg, libelleMarque, libelleProduit, sticker1, sticker2, descProduit, prixBarreTTC, prixTTC, searchsource, fil_ariane4product, productId, displayHand){		
		
		var prix = '<td class="prix">à partir de<br><span class="t12 bold redRubine">'+ prixTTC +'</span></td>';
		if(prixBarreTTC.charAt(0) != '0') {
			prix = '<td class="prix"><span class="barre">'+prixBarreTTC+'</span><br/>à partir de<br><span class="t12 bold redRubine">'+ prixTTC +'</span></td>';
		}
		
		var stickers = '<td class="stickers">&nbsp;</td>';
		if(sticker1 != '') {
			stickers = '<td class="stickers"><img src="'+PATHSTICKER+'/'+sticker1+'" width="50" height="50" border="0" alt=""></td>';
			
			if(sticker2 != '') {
				stickers = '<td class="stickers"><img src="'+PATHSTICKER+'/'+sticker1+'" width="50" height="50" border="0" alt=""><img src="'+PATHSTICKER+'/'+sticker2+'" width="50" height="50" border="0" alt=""></td>';
			}
		}
		
		var achatExpress = '';
		if(displayHand == 'true') {
			achatExpress = '<div class="ae">'
				+ '<div class="hand">'
				+ '<img class="lien_achat_express"  marque="'+libelleMarque+'" source="'+searchsource +'" idcats="'+fil_ariane4product+'" req="'+productId+'"   src="'+ PATHRES +'/fr_FR/img/btn_ae.png" width="85" height="17" border="0" alt=""/>'
				+ '</div>'
				+ '</div>';
		}		
		
		var data = '<tr>'
			+ '<td class="produit">'
			+ achatExpress
			+ '<a href="'+ urlFP +'"><img src="'+ pathImg +'" width="85" height="85" border="0" alt=""/></a></td>'
			+ '<td class="marque">'+ libelleMarque +'<br><span class="whiteFont">'
			+ productBiz +'</span></td>'
			+ stickers
			+ '<td class="description"><h3><a href="'+ urlFP +'" class="plain">'+ libelleProduit +'</a></h3>'+ descProduit +'</td>'
			+ prix
		+ '</tr>';
		
		this.html += data;		
		return this;
	},
	// Affiche les produits
	display: function(){
		$(this.idContent).html(this.html);
		this.html = "";
	}
}


var Facette = {
	html: "",
	
	// Affiche les facettes	
	display: function(){
		$(".avs .facette:gt(0)").remove();
		$(".avs").append(this.html);
		this.html = "";
		$(".facette :checkbox[name != '']").click(function(){
			Rayon.queryFacet(this,$(this).attr("name"));
		});
	},
	
	// Ajoute une facette
	add: function(name){
		if (!$("#"+name).length == 0){
			$("#"+name).remove();
		}	
		var data = '<li class="facette" id="'+ name +'">Par '+ name +'<br/>'+ this.value.display() +'</li>'
		this.html += data;
		return this;
	},
	
	value: {
		html: "",
		
		add: function(name, value, count, checked){
			var data = '<li>'
				+ '<input type="checkbox"';
			if(checked){
				data+=" checked ";
			}	
			data+= '  id="'+ value +'" value="'+ value +'" name="'+ name +'"';
			if (value.indexOf('--',value)>0){
				valueLibelle = value.substring(value.indexOf('--',value)+2,value.length);
			}else{
				valueLibelle= value;
			}	
			data+='/><label for="'+ value +'">'+ valueLibelle +' ('+ count +')</label>'+ '</li>';
			
			if (this.html != ""){this.html += '<li class="interstice"></li>';}
			
			this.html += data;
			
			return this;
		},

		display: function(){
			var data = '<ul class="liste_n">'+ this.html +'</ul>';
			this.html = "";
			
			return data;
		}
	},
	checkedFacette : function (libelleMarque){
		$('#'+libelleMarque).attr("id");
		$('#'+libelleMarque).attr("checked","checked");
	},	
	// cette fonction désactive les autres facette dont l'intitulé n'est pas égale à idFacette  
	disableOther: function (idCategorieFacet, availableFacet){
			if (idCategorieFacet != "categorie"){
				$(".avs > li").each(function(){
					idCurrentFacette = $(this).attr('id');
					if (idCurrentFacette != idCategorieFacet && idCurrentFacette != ''){
						$('#'+idCurrentFacette+' .liste_n > li > input').each(function(){
							var contient=false; 
							for ( var int = 0; int < availableFacet.length; int++) {
								if ($(this).attr("id")== availableFacet[int]){
								
									contient = true;
								}
							}
							if (!contient){
								$(this).removeAttr("checked");
								$(this).attr("disabled","disabled");
							}else{
								$(this).removeAttr("disabled");
								
							}	
						});
					}else{
						contient = false;
						$(this).find("input").each(function(){
							if ($(this).attr("checked") == true){
								contient = true;
							}	
						});
						if (!contient && ($(this).attr("id") !='')){
							for ( var int = 0; int < availableFacet.length; int++) {
								$(this).find("input").each(function(){
									if ($(this).attr("id")== availableFacet[int]){
										$(this).removeAttr("disabled");
									}	
										
								});
							}	
						}	
					}	
				});
				}
			// réactivation des autres options de la facette elle même si tout est décoché
			
		}		
	
}