/*
	ajoute le produit prod_id au dressing
*/
function fctAddToDressingVA(e)
{	var prod_id = jQuery(e).parents("div.item:first").attr('pid') ;
	var prod_mid = jQuery(e).parents("div.item:first").attr('mid') ;
		
	e.className = "inDressing" ;
	var url = "http://"+HTTP_HOST+'/ajax.php?do=addToDressing&mid='+prod_mid+'&pid='+ prod_id ;

	jQuery.ajax({url:url, method:'get', success: function(xmlResponse, textResponse)
	{	
		if(xmlResponse.getElementsByTagName("return") && xmlResponse.getElementsByTagName("return")[0].firstChild.nodeValue == "true")
		{	
		}
		else
		{	if(xmlReponse.getElementsByTagName("message") && xmlResponse.getElementsByTagName("message")[0].firstChild.nodeValue)
			{	alert(xmlReponse.getElementsByTagName("message")[0].firstChild.nodeValue);
			}
		}
	}});
	jQuery(e).html('ajouté');
}

/* change de mode d'affichage */
changeMode = function(mode)
{	var isCoverFlow = mode == 'coverFlow' ;
	ecrireCookie("modeCoverFlow",isCoverFlow ? '1' : '0') ;
	window.location.reload() ;
}

/* modifier l'image d'un produit lors du survol de celui-ci */
function onMouseOverProductImg(e)
{	jQuery(e).find('img.prod').each(function()
	{	var src2 = jQuery(this).attr("_src2") ;
		if (src2) // il existe une image au survol
		{	src2 = MEDIA_HTTP + src2 ;
			if (! this.src0)	this.src0 = this.src ; // source d'origine
			jQuery(this).attr('src',src2) ;
		}
		else
			src2 = jQuery(this).attr("src") ;

		var href = jQuery(this).parents("a:first").attr("href") ;
		var title = jQuery(this).parents("div.item:first").attr("title") ;
		var mark = jQuery(this).parents("div.item:first").attr("mark_label") ; 
		if(mark != "undefined" && mark != "") {
            title = title+" by "+mark;
        }        
		var pid = jQuery(this).parents("div.item:first").attr("pid") ;
		var x= jQuery(this).parents("div.item:first").attr("offsetLeft") + jQuery(this).parents("div.item:first").attr("offsetWidth") / 2 - 100 ;
		var y= jQuery(this).parents("div.item:first").attr("offsetTop") + jQuery(this).parents("div.item:first").attr("offsetHeight") / 2 - 205 ;
		var tailles = '' ;
		if (lstLstTaille && lstLstTaille[pid]) // construire la liste des taille en partant de la fin pour des raison esthétiques
		{	var lstTaille = lstLstTaille[pid] ;
			var i = lstTaille.length ;
			var nb = 1 ;

			while ((i--) > 0)
			{	var ref_id = lstTaille[i][0] ;
				var dispo = lstTaille[i][1] ;
				var ref_label = lstTaille[i][2] ;
				if (nb++ >= 8) // 7 taille par ligne
				{	tailles = "<br />" + tailles ;
					nb = 1 ; 
				}
				tailles = '<a _ref_id="' + ref_id + '" class="' + (dispo ? 'dispo': 'indispo') + '">' + ref_label + '</a>' + tailles ;
			}
			
			for(var i in lstLstTaille[pid])
			{	var ref_id = lstLstTaille[pid][i][0] ;
				var ref_dispo = lstLstTaille[pid][i][1] ;
				var ref_label = lstLstTaille[pid][i][2] ;
			}
		} ;

		jQuery("#zoom").find("span.tailles").html(tailles) ;
		jQuery("#zoom").css("left",x).css("top",y).css("background-image","url("+src2+")") ;
		jQuery("#zoom").attr('title',title).attr("href",href).show() ;
	});
}
/* rétablir l'image d'un produit */
function onMouseOutProductImg(e)
{	jQuery(e).find('img.prod').each(function()
	{	if (this.src0)	this.src = this.src0 ; // récupérer la source d'origine
	});
}

/* clique filtre couleur */
function clickColor(e)
{	jQuery(e).toggleClass('current') ;
	applyFilter() ;
}

/* clique supprimer ma sélection */
function clearFilter(e)
{	jQuery(e).parents("div.level1").each(function()
	{	jQuery(this).find("input[checked]").removeAttr('checked') ;
		jQuery(this).find("img.current").removeClass('current') ;
	}) ;
	applyFilter() ;
}

function clickPage(e)
{	var page = parseInt(jQuery(e).html(),10);

	jQuery("#zoom").hide() ; // refermer le zoom s'il est ouvert

	if (page != pageCourante)
	{	jQuery(window).scrollTop(0);
		applyFilter(page) ;
	}
}
function clickNbProdParPage(e)
{	var nbProd = parseInt(jQuery(e).find('option:selected').attr('value'),10);

	if (nbProdParPage != nbProd)
	{	ecrireCookie("nbProdParPage",nbProd) ;
		if (nbProdParPage)
			applyFilter() ;
		else
			location.reload() ;
		nbProdParPage = nbProd ;
	}
}

fctApplyFilter = null ;
/* appliquer les filtres */
function applyFilter(page)
{	if (page)
	{	pageCourante = page ;
		ecrireCookie("pageCourante",pageCourante) ;
	}
	// affichage du masque patientez
	var productLst = jQuery('div#productLst') ;
	var width = jQuery(productLst)[0].offsetWidth ; 
	var height = jQuery(productLst)[0].offsetHeight ; 

	var patientez = jQuery('div#patientez') ;	
	jQuery(patientez).show().css('width',width).css('height',height) ;
	jQuery(patientez).find("img").show() ;

	if (fctApplyFilter)	clearTimeout(fctApplyFilter) ; // supprimer le timer s'il est en cours
	fctApplyFilter = setTimeout(function()
	{	
		// category
		var category_ids = '' ;
		jQuery('div#filtre_category input[type=checkbox]').each(function()
		{	if (jQuery(this).attr('checked'))
			{	category_ids += ',' + jQuery(this).attr('filter_id') ;
			}
			else
				jQuery(this).removeAttr("checked") ;
		});
		if (category_ids) category_ids += ',' ;
		ecrireCookie("filtre_category",category_ids) ;

		// color
		var color_ids = '' ;
		jQuery('div#filtre_color div.colorList img.current').each(function()
		{	color_ids += ',' + jQuery(this).attr('filter_id') ;
		});
		if (color_ids) color_ids += ',' ;
		ecrireCookie("filtre_color",color_ids) ;

		// prix
		var px_ids = '' ;
		jQuery('div#filtre_prix input[type=checkbox]').each(function()
		{	if (jQuery(this).attr('checked'))
			{	jQuery(this).attr("checked","checked") ;
				px_ids += ',' + jQuery(this).attr('filter_id') ;
			}
			else
				jQuery(this).removeAttr("checked") ;
		});
		if (px_ids) px_ids += ',' ;
		ecrireCookie("filtre_prix",px_ids) ;

		// item_is_
		var item_is_ids = '' ;
		jQuery('div#filtre_item_is input[type=checkbox]').each(function()
		{	if (jQuery(this).attr('checked'))
			{	jQuery(this).attr("checked","checked") ;
				item_is_ids += ',' + jQuery(this).attr('filter_id') ;
			}
			else
				jQuery(this).removeAttr("checked") ;
		});
		if (item_is_ids) item_is_ids += ',' ;
		ecrireCookie("filtre_item_is",item_is_ids) ;

		// subcategory
		var subcategory_ids = '' ;
		jQuery('div#filtre_subcategory input[type=checkbox]').each(function()
		{	if (jQuery(this).attr('checked'))
			{	jQuery(this).attr("checked","checked") ;
				subcategory_ids += ',' + jQuery(this).attr('filter_id') ;
			}
			else
				jQuery(this).removeAttr("checked") ;
		});
		if (subcategory_ids) subcategory_ids += ',' ;
		ecrireCookie("filtre_subcategory",subcategory_ids) ;

		// mark
		var mark_ids = '' ;
		jQuery('div#filtre_mark input[type=checkbox]').each(function()
		{	if (jQuery(this).attr('checked'))
			{	jQuery(this).attr("checked","checked") ;
				mark_ids += ',' + jQuery(this).attr('filter_id') ;
			}
			else
				jQuery(this).removeAttr("checked") ;
		});
		if (mark_ids) mark_ids += ',' ;
		ecrireCookie("filtre_mark",mark_ids) ;

		// new
		var new_ids = '' ;
		jQuery('div#filtre_new input[type=checkbox]').each(function()
		{	if (jQuery(this).attr('checked'))
			{	jQuery(this).attr("checked","checked") ;
				new_ids += ',' + jQuery(this).attr('filter_id') ;
			}
			else
				jQuery(this).removeAttr("checked") ;
		});
		if (new_ids) new_ids += ',' ;
		ecrireCookie("filtre_new",new_ids) ;

		// 
		var displayed_category_ids = ',' ;
		var displayed_color_ids = ',' ;
		var displayed_px_ids = ',' ;

		var displayed_item_is_ids = ',' ;
		var displayed_subcategory_ids = ',' ;
		var displayed_mark_ids = ',' ;
		var displayed_new_ids = ',' ;
		
		var nbShown = 0 ;
		
		var lstShown = new Array() ;
		// appliquer le filter
		jQuery(productLst).find('div.item').each(function()
		{	var show = true ; // montrer le produit par défaut
			
			// category
			var cat_id = jQuery(this).attr('cat_id') ;
			if (category_ids) // appliquer filtre couleur
			{	show &= category_ids.indexOf(',' + cat_id + ',')>=0 ;
			}
			// color
			var color_id = jQuery(this).attr('color_id') ;
			if (color_ids) // appliquer filtre couleur
			{	show &= color_ids.indexOf(',' + color_id + ',')>=0 ;
			}
			// prix
			var px_id = jQuery(this).attr('px_id') ;
			if (px_ids) // appliquer filtre prix
			{	show &= px_ids.indexOf(',' + px_id + ',')>=0 ;
			}
			// item_is
			var item_is_id = jQuery(this).attr('item_is_id') ;
			if (item_is_ids) // appliquer filtre couleur
			{	show &= item_is_ids.indexOf(',' + item_is_id + ',')>=0 ;
			}
			// subcategory
			var scat_id = jQuery(this).attr('scat_id') ;
			if (subcategory_ids) // appliquer filtre couleur
			{	show &= subcategory_ids.indexOf(',' + scat_id + ',')>=0 ;
			}
			// mark
			var mark_id = jQuery(this).attr('mark_id') ;
			if (mark_ids) // appliquer filtre couleur
			{	show &= mark_ids.indexOf(',' + mark_id + ',')>=0 ;
			}
			// new
			var new_id = jQuery(this).attr('new_id') ;
			if (new_ids) // appliquer filtre couleur
			{	show &= new_ids.indexOf(',' + new_id + ',')>=0 ;
			}

			// affichage oui ou non
			if (! show)
			{	jQuery(this).addClass('h') ;
/*				jQuery(this).css('display','none') ;*/
			}
			else
			{	nbShown++;

				jQuery(this).attr('indice',nbShown-1);
				
				if (displayed_category_ids && displayed_category_ids.indexOf(","+cat_id+",")<0)
					displayed_category_ids += cat_id+"," ;
				if (displayed_color_ids && displayed_color_ids.indexOf(","+color_id+",")<0)
					displayed_color_ids += color_id+"," ;
				if (displayed_px_ids && displayed_px_ids.indexOf(","+px_id+",")<0)
					displayed_px_ids += px_id+"," ;

				if (displayed_item_is_ids && displayed_item_is_ids.indexOf(","+item_is_id+",")<0)
					displayed_item_is_ids += item_is_id+"," ;
				if (displayed_subcategory_ids && displayed_subcategory_ids.indexOf(","+scat_id+",")<0)
					displayed_subcategory_ids += scat_id+"," ;
				if (displayed_mark_ids && displayed_mark_ids.indexOf(","+mark_id+",")<0)
					displayed_mark_ids += mark_id+"," ;
				if (displayed_new_ids && displayed_new_ids.indexOf(","+new_id+",")<0)
					displayed_new_ids += new_id+"," ;
					
				lstShown.push(this) ;
			}
		}) ;

		var indice = 0 ;
		var nbPage = 0 ;
		var pagination = jQuery(".pagination") ;

		jQuery(pagination).find("a.page:gt(0)").remove(); // supprimer les pages au dela de la premiere

		if (nbProdParPage)
		{	var nbLigneMax = Math.ceil(nbProdParPage / 4 ) ;
			var nbProdParPage2 = nbLigneMax * 4 ;

			nbPage = Math.ceil(nbShown / nbProdParPage2) ;

			if (typeof(pageCourante === "string"))	pageCourante = parseInt(pageCourante,10) ;

			if (pageCourante<1)	
				pageCourante = 1 ;
			else if (pageCourante > nbPage)	
				pageCourante = nbPage ;
			var indiceMin = (pageCourante-1) * nbProdParPage2 ;
			var indiceMax = indiceMin + nbProdParPage2 - 1 ;
			
		}
		else
		{	var indiceMin = 0 ;
			var indiceMax = nbShown ;
			pageCourante = 0 ;
		}
		if (nbPage > 1)
		{
			if (pageCourante > 1)
				jQuery(pagination).find("a.prec").removeClass('hidden').addClass('shown').removeClass('inactif');
			else
				jQuery(pagination).find("a.prec").removeClass('hidden').addClass('shown').addClass('inactif');

			if (pageCourante < nbPage)
				jQuery(pagination).find("a.suiv").removeClass('hidden').addClass('shown').removeClass('inactif');
			else
				jQuery(pagination).find("a.suiv").removeClass('hidden').addClass('shown').addClass('inactif');

			jQuery(pagination).find("a.page:first").each(function()
			{	var first = this ;
				var last = this ;
				var pg = 1 ;
				var prec = false ;
				if (pg==pageCourante)
					jQuery(last).removeClass('hidden').addClass('shown').addClass('current');
				else
					jQuery(last).removeClass('hidden').addClass('shown').removeClass('current');

				for(var pg=2; pg <= nbPage; pg++)
				{	if (pg == nbPage)
						var delta = 0 ;
					else
						var delta = Math.abs(pg - pageCourante) ;
					if (delta > deltaMax && prec) // la page précédente est déjà sous forme "..."
						html = null ;
					else if (delta > deltaMax) // cette page doit être sous forme "..."
						html = false ;
					else
						html = pg ;
					if (html !== null) // afficher ce numéro de page
					{	last = jQuery(first).clone().insertAfter(last).html(html ? html : "&hellip;") ; 
						if (! html)	prec = last ; 
						else		prec = null ;
						if (pg==pageCourante)
							jQuery(last).addClass('current');
						else
							jQuery(last).removeClass('current');
					}
				}
			});
		}
		else
		{	jQuery(pagination).find("a.prec").addClass('hidden').removeClass('shown') ;
			jQuery(pagination).find("a.suiv").addClass('hidden').removeClass('shown') ;
			jQuery(pagination).find("a.page:first").addClass('hidden').removeClass('shown')  ;
		}

		var displayedProd_ids = '' ;
		for(var indice=0; indice<lstShown.length; indice++)
		{	var e = lstShown[indice] ;
			var show = indice >= indiceMin && indice <= indiceMax ; // le produit est visible s'il est dans la bonne page
			if (show)
			{	//jQuery(e).css('display','block').find("img.prod").each(function()
				jQuery(e).removeClass('h').find("img.prod").each(function()
				{	var src = jQuery(this).attr('src') ;
					if (! src)
					{	var src = jQuery(this).attr('_src1') ;
						jQuery(this).attr('src', MEDIA_HTTP+src).show() ;
					}
				});
				displayedProd_ids += jQuery(e).attr('pid') + ',' ;
			}
			else
				jQuery(e).addClass('h') ;
//				jQuery(e).css('display','none') ;
		}

		lstShown = null ;
		
		jQuery("#displayed_Prod span.nbProd").html(nbShown ? nbShown : "aucun") ;
		jQuery("#displayed_Prod span.pluriel").html((nbShown>1) ? "s" : "") ;

		//
		hideShowFilters("div#filtre_category",displayed_category_ids) ;
		hideShowColorFilter("div#filtre_color",displayed_color_ids) ;
		hideShowFilters("div#filtre_prix",displayed_px_ids) ;
		hideShowFilters("div#filtre_item_is",displayed_item_is_ids) ;
		hideShowFilters("div#filtre_subcategory",displayed_subcategory_ids) ;
		hideShowFilters("div#filtre_mark",displayed_mark_ids) ;
		hideShowFilters("div#filtre_new",displayed_new_ids) ;

		jQuery(patientez).hide() ;
		jQuery(patientez).find("img").hide() ;

		// envoyer la liste des produit au serveur pour stockage dans une variable de session
		var url = "http://"+HTTP_HOST+'/ajax.php?do=setDisplayedProd_ids' ;
		var data = 	{	displayedProd_ids:displayedProd_ids/* ,
						filtre_category:category_ids ,
						filtre_color:color_ids ,
						filtre_item_is:item_is_ids ,
						filtre_mark:mark_ids ,
						filtre_new:new_ids ,
						filtre_prix:px_ids ,
						filtre_subcategory:subcategory_ids ,
						pageCourante:pageCourante ,
					*/
					} ;
		jQuery.post(url, data) ;
	},100) ;
}
function hideShowColorFilter(selector,display_ids)
{	var nbChecked = jQuery(selector+" img.current").length ; // nombre de checkbox cochées
	var nbShown = 0 ;
	
	jQuery(selector+" img").each(function()
	{	var filter_id = jQuery(this).attr('filter_id') ;
		var show = nbChecked || display_ids.indexOf(','+filter_id+',')>=0 ;
		if (show)
		{	jQuery(this).show() ;
			nbShown++ ;
		}
		else
			jQuery(this).hide() ;
	});
	if (! nbShown) // aucune ligne visible
		jQuery(selector).hide() ;
	else 
	{	jQuery(selector).show() ;
		if (nbChecked)
			jQuery(selector+" div.all").show() ;
		else
			jQuery(selector+" div.all").hide() ;
	}
}
function hideShowFilters(selector,display_ids)
{	var nbChecked = 0 ; // nombre de checkbox cochées
	jQuery(selector+" input[type=checkbox]").each(function()
	{	if (jQuery(this).attr("checked"))	nbChecked++ ;
	}) ;
	var nbShown = 0 ;
	
	jQuery(selector+" input[type=checkbox]").each(function()
	{	var filter_id = jQuery(this).attr('filter_id') ;
		var show = nbChecked || display_ids.indexOf(','+filter_id+',')>=0 ;
		if (show)
		{	jQuery(this).parent().show() ;
			nbShown++ ;
		}
		else
			jQuery(this).parent().hide() ;
	});
	if (! nbShown) // aucune ligne visible
		jQuery(selector).hide() ;
	else 
	{	jQuery(selector).show() ;
		if (nbChecked)
			jQuery(selector+" li.all").show() ;
		else
			jQuery(selector+" li.all").hide() ;
	}
}

function fctChangeTri(tri)
{	jQuery('#ordre_tri select[name=ordre_tri] option').each(function()
	{	var selected = jQuery(this).attr('value') == tri ;
		jQuery(this).attr('selected',selected) ;
	});
	jQuery("#ordre_tri").submit() ;
}

var shouldApplyFilter = false ;
function fctCalculFiltre(id)
{	var selector = "#" + id ;
	var value = lireCookie(id) ;
	if (value)
	{	if (selector == "#filtre_color")
		{	jQuery(selector).find("img").each(function()
			{	var filter_id = jQuery(this).attr('filter_id') ;
				if (value.indexOf(','+filter_id+',')>=0)
				{	jQuery(this).addClass("current") ;
					shouldApplyFilter = true ;
				}
			});
		}
		else
		{	jQuery(selector).find("li input").each(function()
			{	
                var filter_id = jQuery(this).attr('filter_id') ;
                //console.debug("selector : "+selector+" / filter_id = "+filter_id+" / cookie value = "+value);
				if (value.indexOf(','+filter_id+',')>=0)
				{	//jQuery(this).attr('checked',true) ;
                    jQuery(this).attr("checked", "checked") ;
					shouldApplyFilter = true ;
				}
			});
		}
	}
}

/* initialisation du viewAll après onLoad */
function initViewAll()
{	var url = ''+document.location ;
	var p = url.indexOf("#") ;
	if (p>0)	url = url.substr(0,p) ;
	if (url == lireCookie('carrouselUrl')) // on se trouve sur la même page, appliquer les filtres
	{	/*
        fctCalculFiltre("filter_genre") ;
		fctCalculFiltre("filter_category") ;
		fctCalculFiltre("filtre_color") ;
		fctCalculFiltre("filter_prix") ;
		fctCalculFiltre("filter_item_is") ;
		fctCalculFiltre("filter_subcategory") ;
		fctCalculFiltre("filter_mark") ;
		fctCalculFiltre("filter_new") ;
		*/
		fctCalculFiltre("filtre_genre") ;
		fctCalculFiltre("filtre_category") ;
		fctCalculFiltre("filtre_color") ;
		fctCalculFiltre("filtre_prix") ;
		fctCalculFiltre("filtre_item_is") ;
		fctCalculFiltre("filtre_subcategory") ;
		fctCalculFiltre("filtre_mark") ;
		fctCalculFiltre("filtre_new") ;
	}
	ecrireCookie("carrouselUrl",url) ;

	// ouvrir les rubriques dont les filtres sont cochés et rendre les rubriques cliquables
	jQuery("table#viewAll td.filter div.level1 h3").each(function()
	{	var parent = jQuery(this).parent() ;

		if (jQuery(parent).find('li input:checked, img.current').length) // le filtre dispose au moins d'une option cochee
			jQuery(parent).addClass('opened') ; // il est deploye

		jQuery(this).bind('click', function()
		{	if (jQuery(this).parent().find('input[checked]').length==0 && jQuery(this).parent().find('img.current').length==0)
				jQuery(this).parent().toggleClass('opened') ;
		});
	}) ;

	// appliquer les filtres
	if (shouldApplyFilter)
		applyFilter() ;

	// parcourir la liste des produits
	var displayedProd_ids = '' ; // id des produits visibles
	jQuery("#productLst").find("div.item").each(function()
	{	if (! jQuery(this).hasClass('h')) // produit visible
		{	displayedProd_ids += jQuery(this).attr('pid') + ',' ;
		}
		jQuery(this).find("img.picto").each(function()
		{	var src = jQuery(this).attr('_src1') ;
			jQuery(this).attr('src', MEDIA_HTTP+src).show() ; // la source de l'image du picto
		});
		jQuery(this).find("a.img").bind("mouseover", function(){onMouseOverProductImg(this)} ) ;
		jQuery(this).find("a.img").bind("mouseout", function(){onMouseOutProductImg(this)} ) ;
		jQuery(this).find("div.lDressing a.dressing").bind("click", function(){fctAddToDressingVA(this)} ) ;
		var _href = jQuery(this).find("a.img").attr('href') ;
		if (_href)
			jQuery(this).find("div.lDressing a.details").attr('href', _href) ;
	}) ;
	
	// envoyer les displayedProd_ids
	var url = "http://"+HTTP_HOST+'/ajax.php?do=setDisplayedProd_ids' ;
	var data = {displayedProd_ids:displayedProd_ids} ;
	jQuery.post(url, data) ;

	shouldApplyFilter = false ;
}

