/*
* 2007-2011 PrestaShop 
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2011 PrestaShop SA
*  @version  Release: $Revision: 7014 $
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/


/*
 * jQuery BBQ: Back Button & Query Library - v1.1.1 - 1/22/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 */

(function($,n){var g,o=n.location,k=Array.prototype.slice,q=decodeURIComponent,a=$.param,c,j,u,b=$.bbq=$.bbq||{},p,t,h,e=$.event.special,d="hashchange",z="querystring",C="fragment",x="elemUrlAttr",i="href",s="src",w=/^.*\?|#.*$/g,v=/^.*\#/,B={};function D(E){return typeof E==="string"}function A(F){var E=k.call(arguments,1);return function(){return F.apply(this,E.concat(k.call(arguments)))}}function l(E){return E.replace(/^[^#]*#?(.*)$/,"$1")}function m(E){return E.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(G,L,E,H,F){var N,K,J,M,I;if(H!==g){J=E.match(G?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);I=J[3]||"";if(F===2&&D(H)){K=H.replace(G?v:w,"")}else{M=j(J[2]);H=D(H)?j[G?C:z](H):H;K=F===2?H:F===1?$.extend({},H,M):$.extend({},M,H);K=a(K)}N=J[1]+(G?"#":K||!J[1]?"?":"")+K+I}else{N=L(E!==g?E:o[i])}return N}a[z]=A(f,0,m);a[C]=c=A(f,1,l);$.deparam=j=function(H,E){var G={},F={"true":!0,"false":!1,"null":null};$.each(H.replace(/\+/g," ").split("&"),function(K,P){var J=P.split("="),O=q(J[0]),I,N=G,L=0,Q=O.split("]["),M=Q.length-1;if(/\[/.test(Q[0])&&/\]$/.test(Q[M])){Q[M]=Q[M].replace(/\]$/,"");Q=Q.shift().split("[").concat(Q);M=Q.length-1}else{M=0}if(J.length===2){I=q(J[1]);if(E){I=I&&!isNaN(I)?+I:I==="undefined"?g:F[I]!==g?F[I]:I}if(M){for(;L<=M;L++){O=Q[L]===""?N.length:Q[L];N=N[O]=L<M?N[O]||(Q[L+1]&&isNaN(Q[L+1])?{}:[]):I}}else{if($.isArray(G[O])){G[O].push(I)}else{if(G[O]!==g){G[O]=[G[O],I]}else{G[O]=I}}}}else{if(O){G[O]=E?g:""}}});return G};function y(G,E,F){if(E===g||typeof E==="boolean"){F=E;E=a[G?C:z]()}else{E=D(E)?E.replace(G?v:w,""):E}return j(E,F)}j[z]=A(y,0);j[C]=u=A(y,1);$[x]||($[x]=function(E){return $.extend(B,E)})({a:i,base:i,iframe:s,img:s,input:s,form:"action",link:i,script:s});h=$[x];function r(H,F,G,E){if(!D(G)&&typeof G!=="object"){E=G;G=F;F=g}return this.each(function(){var K=$(this),I=F||h()[(this.nodeName||"").toLowerCase()]||"",J=I&&K.attr(I)||"";K.attr(I,a[H](J,G,E))})}$.fn[z]=A(r,z);$.fn[C]=A(r,C);b.pushState=p=function(H,E){if(D(H)&&/^#/.test(H)&&E===g){E=2}var G=H!==g,F=c(o[i],G?H:{},G?E:2);o[i]=F+(/#/.test(F)?"":"#")};b.getState=t=function(E,F){return E===g||typeof E==="boolean"?u(E):u(F)[E]};b.removeState=function(E){var F={};if(E!==g){F=t();$.each($.isArray(E)?E:arguments,function(H,G){delete F[G]})}p(F,2)};e[d]=$.extend(e[d],{add:function(E,G,F){return function(I){var H=I[C]=c();I.getState=function(J,K){return J===g||typeof J==="boolean"?j(H,J):j(H,K)[J]};E.apply(this,arguments)}}})})(jQuery,this);

/*
 * jQuery hashchange event - v1.1 - 1/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 */
(function($,i,b){var h=i.location,j,k=$.event.special,c="hashchange",e=$.browser,f=document.documentMode,g=e.msie&&(f===b||f<8),d="on"+c in i&&!g;function a(l){l=l||h.href;return l.replace(/^[^#]*#?(.*)$/,"$1")}$[c+"Delay"]=100;k[c]=$.extend(k[c],{setup:function(){if(d){return false}j.start()},teardown:function(){if(d){return false}j.stop()}});j=(function(){var l={},q,m,n,p;function o(){n=p=function(r){return r};if(g){m=$('<iframe src="javascript:0"/>').hide().appendTo("body")[0].contentWindow;p=function(){return a(m.document.location.href)};n=function(t,r){if(t!==r){var s=m.document;s.open().close();s.location.hash="#"+t}};n(a())}}l.start=function(){if(q){return}var s=a();n||o();(function r(){var u=a(),t=p(s);if(u!==s){n(s=u,t);$(i).trigger(c)}else{if(t!==s){h.href=h.href.replace(/#.*/,"")+"#"+t}}q=setTimeout(r,$[c+"Delay"])})()};l.stop=function(){if(!m){q&&clearTimeout(q);q=0}};return l})()})(jQuery,this);


String.prototype.truncate = function(length) {
	  if (this.length > length) {
	    return this.slice(0, length - 3) + "...";
	  } else {
	    return this;
	  }
	};


function ps_round(value, precision)
{
	if (typeof(roundMode) == 'undefined')
		roundMode = 2;
	if (typeof(precision) == 'undefined')
		precision = 2;
	
	method = roundMode;
	if (method == 0)
		return ceilf(value, precision);
	else if (method == 1)
		return floorf(value, precision);
	precisionFactor = precision == 0 ? 1 : Math.pow(10, precision);
	return Math.round(value * precisionFactor) / precisionFactor;
}

function	autoUrl(name, dest)
{
	var loc;
	var id_list;

	id_list = document.getElementById(name);
	loc = id_list.options[id_list.selectedIndex].value;
	if (loc != 0)
		location.href = dest+loc;
	return ;
}

function	autoUrlNoList(name, dest)
{
	var loc;

	loc = document.getElementById(name).checked;
	location.href = dest + (loc == true ? 1 : 0);
	return ;
}

/*
** show or hide element e depending on condition show
*/
function toggle(e, show)
{
	e.style.display = show ? '' : 'none';
}

function toggleMultiple(tab)
{
    var len = tab.length;

    for (var i = 0; i < len; i++)
        if (tab[i].style)
            toggle(tab[i], tab[i].style.display == 'none');
}

/**
* Show dynamicaly an element by changing the sytle "display" property
* depending on the option selected in a select.
*
* @param string $select_id id of the select who controls the display
* @param string $elem_id prefix id of the elements controlled by the select
*   the real id must be : 'elem_id'+nb with nb the corresponding number in the
*   select (starting with 0).
*/
function showElemFromSelect(select_id, elem_id)
{
	var select = document.getElementById(select_id);
	for (var i = 0; i < select.length; ++i)
	{
	    var elem = document.getElementById(elem_id + select.options[i].value);
		if (elem != null)
			toggle(elem, i == select.selectedIndex);
	}
}

/**
* Get all div with specified name and for each one (by id), toggle their visibility
*/
function openCloseAllDiv(name, option)
{
	var tab = $('*[name='+name+']');
	for (var i = 0; i < tab.length; ++i)
		toggle(tab[i], option);
}

/**
* Toggle the value of the element id_button between text1 and text2
*/
function toggleElemValue(id_button, text1, text2)
{
	var obj = document.getElementById(id_button);
	if (obj)
		obj.value = ((!obj.value || obj.value == text2) ? text1 : text2);
}

function addBookmark(url, title)
{
	if (window.sidebar)
		return window.sidebar.addPanel(title, url, "");
	else if ( window.external )
		return window.external.AddFavorite( url, title);
	else if (window.opera && window.print)
		return true;
	return true;
}

function writeBookmarkLink(url, title, text, img)
{
	var insert = '';
	if (img)
		insert = writeBookmarkLinkObject(url, title, '<img src="' + img + '" alt="' + escape(text) + '" title="' + escape(text) + '" />') + '&nbsp';
	insert += writeBookmarkLinkObject(url, title, text);
	document.write(insert);
}

function writeBookmarkLinkObject(url, title, insert)
{
	if (window.navigator.userAgent.indexOf('Chrome') != -1)
		return ('');
	else if (window.sidebar || window.external)
		return ('<a href="javascript:addBookmark(\'' + escape(url) + '\', \'' + escape(title) + '\')">' + insert + '</a>');
	else if (window.opera && window.print)
		return ('<a rel="sidebar" href="' + escape(url) + '" title="' + escape(title) + '">' + insert + '</a>');
	return ('');
}

function checkCustomizations()
{
	var pattern = new RegExp(' ?filled ?');

	if (typeof customizationFields != 'undefined')
		for (var i = 0; i < customizationFields.length; i++)
			/* If the field is required and empty then we abort */
			if (parseInt(customizationFields[i][1]) == 1 && ($('#' + customizationFields[i][0]).html() == '' ||  $('#' + customizationFields[i][0]).html() != $('#' + customizationFields[i][0]).val()) && !pattern.test($('#' + customizationFields[i][0]).attr('class')))
				return false;
	return true;
}

function emptyCustomizations()
{
	if(typeof(customizationFields) == 'undefined') return;
	
	for (var i = 0; i < customizationFields.length; i++)
	{
		$('#' + customizationFields[i][0]).html('');
		$('#' + customizationFields[i][0]).val('');
	}
}

function ceilf(value, precision)
{
	if (typeof(precision) == 'undefined')
		precision = 0;
	var precisionFactor = precision == 0 ? 1 : Math.pow(10, precision);
	var tmp = value * precisionFactor;
	var tmp2 = tmp.toString();
	// If the current value has already the desired precision
	if (tmp2.indexOf('.') === false)
		return (value);
	if (tmp2.charAt(tmp2.length - 1) == 0)
		return value;
	return Math.ceil(tmp) / precisionFactor;
}

function floorf(value, precision)
{
	if (typeof(precision) == 'undefined')
		precision = 0;
	var precisionFactor = precision == 0 ? 1 : Math.pow(10, precision);
	var tmp = value * precisionFactor;
	var tmp2 = tmp.toString();
	// If the current value has already the desired precision
	if (tmp2.indexOf('.') === false)
		return (value);
	if (tmp2.charAt(tmp2.length - 1) == 0)
		return value;
	return Math.floor(tmp) / precisionFactor;
}

function setCurrency(id_currency)
{
	$.ajax({
		type: 'POST',
		url: baseDir + 'changecurrency.php',
		data: 'id_currency='+parseInt(id_currency),
		success: function(msg)
		{
			location.reload(true);
		}
	});
}

function isArrowKey(k_ev)
{
	var unicode=k_ev.keyCode? k_ev.keyCode : k_ev.charCode;
	if (unicode >= 37 && unicode <= 40)
		return true;

}

var products = {
	nb_pages : 0,
	numberOfProducts : 0,
	current_page : 1,
	current_id_category : _global.id_category,
	current_sort : '',
	current_sort_way : '',
	
	filter_m : [],
	filter_tp : [],
	filter_f : [],
	filter_t : [],
	filter_c : [],
	filter_cat : [],
	filter_col : [],

	s_m : 'm[]',
	s_tp : 'tp[]',
	s_f : 'f[]',
	s_t : 't[]',
	s_c : 'c[]',
	s_cat : 'cat[]',
	s_col : 'col[]',

	addFilter : '',

	load : function(){
		var that = this;
		var params = {
			search : this.s_m + '+' + this.s_tp + '+' + this.s_f + '+' + this.s_t + '+' + this.s_c + '+' + this.s_cat + '+' + this.s_col,
			addFilter : this.addFilter,
			page : this.current_page,
			orderBy : this.current_sort,
			orderWay : this.current_sort_way,
			id_category : this.current_id_category
		};

		$.blockUI();

		$.ajax({
			type : 'GET',
			async : true,
			url : 'testJson.php',
			cache : true,
			dataType : "json",
			data : params,
			success : function(data){
				$.unblockUI();
				that.updateMenu(data.menu);
				that.process(data);
			}
		});
		
	},

	updateMenu : function(json){

		if (json.manufacturers) {
			this.updateManufacturers(json.manufacturers, "manufacturers", "marque");
		} else {
			$('#manufacturers li').addClass("disabled");
		}

		if (json.collections) {
			this.updateCollections(json.collections);
		} else {
			$('.ul_collections li').addClass("disabled");
		}

		if (json.categories) {
			this.updateCategories(json.categories, "categories", "category");
		} else {
			$('#categories li').addClass("disabled");
		}

		if (json.types) {
			this.updateFeatures(json.types, "types", "type");
		} else {
			$('#types li').addClass("disabled");
		}
		
		if (json.forms) {
			this.updateFeatures(json.forms, "forms", "forme");
		} else {
			$('#forms li').addClass("disabled");
		}

		if (json.sizes) {
			if (json.sizes.tailleusa) {
				this.updateSizes(json.sizes.tailleusa, "tailleUsa");
			} else {
				this.hideSizes("tailleUsa");
			}
			
			if (json.sizes.tailleslip) {
				this.updateSizes(json.sizes.tailleslip, "tailleSlip");
			} else {
				this.hideSizes("tailleSlip");
			}
			
			if (json.sizes.taillesocks) {
				this.updateSizes(json.sizes.taillesocks, "tailleSocks");
			} else {
				this.hideSizes("tailleSocks");
			}

			if (json.sizes.taillesuniques) {
				this.updateSizes(json.sizes.taillesuniques, "taillesuniques");
			} else {
				this.hideSizes("taillesuniques");
			}
			
			if (json.sizes.bonnet) {
				this.updateSizes(json.sizes.bonnet, "bonnets");
			} else {
				this.hideSizes("bonnets");
			}
			
			if (json.sizes.taillefrbis) {
				this.updateSizes(json.sizes.taillefrbis, "tailleFrBis");
			} else {
				this.hideSizes("tailleFrBis");
			}
			
			if (json.sizes.taillesenfants) {
				this.updateSizes(json.sizes.taillesenfants, "tailleEnfants");
			} else {
				this.hideSizes("tailleEnfants");
			}
			
			if (json.sizes.tourpoitrine) {
				this.updateSizes(json.sizes.tourpoitrine, "tourpoitrine");
			} else {
				this.hideSizes("tourpoitrine");
			}
			

		}

	},

	hideSizes : function(ULid){
		$('#'+ULid+' li input').attr("disabled", true);
		$('#'+ULid+' li span').addClass("disabled");
	},

	initSizes : function(ULid){
		$('#'+ULid+' li input').attr("disabled", false);
		$('#'+ULid+' li span').removeClass("disabled");
	},

	reInitBut : function(but){
		if (but!='types') { $('#types li').removeClass("disabled"); }
		if (but!='forms') { $('#forms li').removeClass("disabled"); }
		if (but!='tailleUsa') { this.initSizes('tailleUsa'); }
		if (but!='tailleSlip') { this.initSizes('tailleSlip'); }
		if (but!='tailleSocks') { this.initSizes('tailleSocks'); }
		if (but!='taillesuniques') { this.initSizes('taillesuniques'); }
		if (but!='bonnets') { this.initSizes('bonnets'); }
		if (but!='tailleFrBis') { this.initSizes('tailleFrBis'); }
		if (but!='tailleEnfants') { this.initSizes('tailleEnfants'); }
		if (but!='tourpoitrine') { this.initSizes('tourpoitrine'); }
	},

	updateFeatures : function(json, ULid, key){
		var html = [];
		
		if (json.length>0) {
			$('#'+ULid+' li').addClass("disabled");
			for (var i in json){
				var id = json[i].id_feature_value;
				var name = json[i].value;
				//html.push('<li rel="'+id+'" id="'+key+'_'+id+'" name="'+key+'"><span class="delete"></span><a href="#">'+name+'</a></li>');
				$('li#'+key+'_'+id).removeClass("disabled");
			}
			//this.updateUL(ULid, html);
		} else {
			//$('#'+ULid+' li').removeClass("disabled");
		}
	},

	updateManufacturers : function(json, ULid, key){
		var html = [];
		
		if (json.length>0) {
			$('#'+ULid+' li').addClass("disabled");
			for (var i in json){
				var id = json[i].id_manufacturer;
				var name = json[i].name;
				//html.push('<li rel="'+id+'" id="'+key+'_'+id+'" name="'+key+'"><span class="delete"></span><a href="#">'+name+'</a></li>');
				$('li#'+key+'_'+id).removeClass("disabled");
			}
			//this.updateUL(ULid, html);
		} else {
			//$('#'+ULid+' li').removeClass("disabled");
		}
	},

	updateCollections : function(json){
		var html = [];
		
		if (json.length>0) {
			$('.ul_collections li').addClass("disabled");
			for (var i in json){
				var id = json[i].id_feature_value;
				var id_manufacturer = json[i].id_manufacturer;
				var name = json[i].value;
				$('li#collection_'+id).removeClass("disabled");
			}
		} else {
			//$('#'+ULid+' li').removeClass("disabled");
		}
	},


	updateCategories : function(json, ULid, key){
		var html = [];
		
		if (json.length>0) {
			$('#'+ULid+' li').addClass("disabled");
			for (var i in json){
				var id = json[i].id_category;
				var name = json[i].name;
				//html.push('<li rel="'+id+'" id="'+key+'_'+id+'" name="'+key+'"><span class="delete"></span><a href="#">'+name+'</a></li>');
				$('li#'+key+'_'+id).removeClass("disabled");
			}
			//this.updateUL(ULid, html);
		} else {
			//$('#'+ULid+' li').removeClass("disabled");
		}
	},


	updateSizes : function(json, ULid){
		var html = [];

		if (json.length>0) {
			$('#'+ULid+' li input').attr("disabled", true);
			$('#'+ULid+' li span').addClass("disabled");

			for (var i in json){
				var id = json[i].id_attribute,
					idgroup = json[i].id_attribute_group,
					name = json[i].name,
					input_id = ULid+'-'+id,
					li = $('input#'+input_id).parent();
				//html.push('<li rel="'+id+','+idgroup+'" class="field" name="'+ULid+'"><input type="checkbox" value="'+id+','+idgroup+'" name="'+name+'" id="'+input_id+'"><span>'+name+'</span></li>');
				$('input#'+input_id).attr("disabled", false).next().removeClass("disabled");
			}
			//this.updateUL(ULid, html);
		} else {
			//$('#'+ULid+' li input').attr("disabled", false);
			//$('#'+ULid+' li span').removeClass("disabled");
		}
	},

	updateUL : function(ULid, html){
		//$('#'+ULid).html( html.join('') );
		//$('#'+ULid+' li a').click(this.clk);
		//$('#'+ULid+' li .delete').click(this.del);
		//$('#'+ULid+' li input').click(this.sel);
		$('#'+ULid).block(); setTimeout(function(){$('#'+ULid).unblock();}, 80);
	},

	process : function(json){
		var html = [];
		this.nb_pages = json.numberOfPages;
		this.nb_products = json.numberOfProducts;
		
		for (var p in json.products){
			var id = json.products[p].id;
			var img = json.products[p].img;
			var isNew = json.products[p].isNew;
			var isOddment = json.products[p].isOddment;
			var on_sale = json.products[p].on_sale;
			var logo = json.products[p].logo;
			var name = json.products[p].name;
			var old_price = json.products[p].old_price;
			var price = json.products[p].price;
			var product_url = json.products[p].product_url;
			var reduction = json.products[p].reduction;
			var text = json.products[p].text;

			html.push('<li class="ajax_block_product alternate_item clearfix">');
			html.push('	<div class="center_block">');
			html.push('		<a title="'+name+'" class="product_img_link" href="'+product_url+'"><img width="180" height="230" alt="'+name+'" src="'+img+'"></a>');
			html.push('		<h3><a title="'+name+'" href="'+product_url+'">'+name.truncate(44)+'</a></h3>');
			html.push('		<p class="product_desc"><a title="'+text+'" href="'+product_url+'"></a></p>');
			html.push('	</div>');
			html.push('	<div class="right_block">');
			html.push('		<div>');

			if (isNew===true)		{ html.push('			<span class="bx new">Nouveaute</span>'); }
			if (isOddment===true)	{ html.push('			<span class="bx discount">Fin de collection</span>'); }
			if (on_sale===true)		{ html.push('			<span class="bx on_sale">Solde</span>'); }

			if (old_price!=0) { html.push('			<span style="display: inline;" class="xprice">'+old_price+' &euro;</span>'); }
			html.push('			<span style="display: inline;" class="price">'+price+' &euro;</span>');

			html.push('			<span class="availability">En stock</span>');
			html.push('		</div>');
			html.push('		<a title="Ajouter au panier" href="http://www.mesdessous.fr/panier?add&amp;id_product='+id+'&amp;token=xxx" rel="ajax_id_product_'+id+'" class="button ajax_add_to_cart_button exclusive">Ajouter au panier</a>');
			html.push('		<a title="Voir le produit" href="'+product_url+'" class="button">Voir le produit</a>');
			html.push('	</div>');
			html.push('</li>');

		}

		$("#product_list").html(html.join(''));
		$("#nbpdxdiv").html('Il y a '+this.nb_products+' produits');
		
		this.paginate();
	},

	setPage : function(p){

		if($(window).scrollTop() > 200){
			$('body').animate({scrollTop:0},'slow');   //Chrome
			$('html').animate({scrollTop:0},'slow');   //le reste
		}
		
		this.current_page = p;
		this.paginate();
		this.load();
	},

	setOrder : function(newval){
		if (newval=='pricem'){
			this.current_sort_way='asc';
			this.current_sort='price';
		}
		if (newval=='pricep'){
			this.current_sort_way='desc';
			this.current_sort='price';
		}
		if (newval=='alpha'){
			this.current_sort_way='asc';
			this.current_sort='alpha';
		}
		if (newval=='nouveaute'){
			this.current_sort_way='desc';
			this.current_sort='nouveaute';
		}
		if (newval==''){
			this.current_sort_way='';
			this.current_sort='';
		}
		this.current_page=1;
		this.load();
	},

	paginate : function(){
		var html = [],
			n = this.current_page + 1,
			c = 0,
			visible = 5;
			
		html.push('<ul class="pagination">');
		html.push('<li ' + (this.current_page==1?'class="disabled"':'')  + ' class="pagination_previous">' + (this.current_page==1?'<span>&laquo;&nbsp;</span>':'<a href="#" onclick="products.setPage('+(this.current_page-1)+');return false;">&laquo;&nbsp;</a>') + '</li>');
		html.push('<li class="p_1"><a href="#" onclick="products.setPage(1);return false;">1</a></li>');

		if (this.current_page-visible>2) { html.push('<li class="truncate">...</li>'); }
		
		for (var i=Math.max(1, this.current_page-visible-1);i<Math.min(this.nb_pages-1, this.current_page+visible);i++){
			var p = i+1;
			html.push('<li class="p_'+p+'"><a href="#" onclick="products.setPage('+p+');return false;">'+p+'</a></li>');
		}
		
		if (this.current_page+visible<this.nb_pages-1){ html.push('<li class="truncate">...</li>'); }
		
		if (this.nb_pages>1) {
			html.push('<li class="p_'+this.nb_pages+'"><a href="#" onclick="products.setPage('+this.nb_pages+');return false;">'+this.nb_pages+'</a></li>');
		}
				
		html.push('<li class="pagination_next" ' +  (this.current_page==this.nb_pages?'class="disabled"':'')  + '>' + (this.current_page==this.nb_pages?'<span>&nbsp;&raquo;</span>':'<a href="#" onclick="products.setPage('+n+');return false;">&nbsp;&raquo;</a>') + '</li>');
		html.push('</ul>');
		
		var mypag = html.join('');
		$("#pagination").html(mypag);
		$("#paginationTop").html(mypag);
		$('.p_'+this.current_page).addClass('current').html('<span>'+this.current_page+'</span>');
	},

	serialize : function(key, array){
		return key + '[' + array.join('-') + ']';
	},

	resetFilters : function(){
		this.filter_m = []; // marques
		this.filter_tp = []; // types
		this.filter_f = []; // formes
		this.filter_t = []; // sizes
		this.filter_c = []; // colors
		this.filter_cat = []; // categories
		this.filter_col = []; // collections
		this.current_sort = '';
		this.current_sort_way = '';

		$('.box .rubs ul .selected').removeClass('selected');
		$('.box .rubs ul li input').attr('checked', false);
		$('.box .rubs ul li input').attr('disabled', false);
	},

	getFilters : function(){
		var that = this;
		
		this.filter_m = []; // marques
		this.filter_tp = []; // types
		this.filter_f = []; // formes
		this.filter_t = []; // sizes
		this.filter_c = []; // colors
		this.filter_cat = []; // categories
		this.filter_col = []; // collections
		
		this.mySelect_m = [];
		this.mySelect_tp = [];
		this.mySelect_f = [];
		this.mySelect_t = [];
		this.mySelect_c = [];
		this.mySelect_cat = [];
		this.mySelect_col = [];
		
		this.addFilter = '';

		$('.box .rubs ul .selected').each(function(){
			var li = $(this),
				value = li.attr('rel'),
				filter = li.attr('name'),
				/* Kevin Codfert*/
				name = li.children("a:first").text();
				/*----*/
				
			if (filter=="marque"){ 
				that.addFilter = 'm'; that.filter_m.push(value);
				/* Kevin Codfert*/ 
				/*that.mySelect_m.push([name,value]);*/
				that.mySelect_m.push(name);
				/*----*/
			}
			if (filter=="category"){ 
				that.addFilter = 'cat'; that.filter_cat.push(value);
				/* Kevin Codfert*/ 
				/*that.mySelect_cat.push([name,value]);*/
				that.mySelect_cat.push(name);
				/*----*/
				
			}
			if (filter=="collection"){ 
				that.addFilter = 'col'; that.filter_col.push(value); 
				/* Kevin Codfert*/ 
				/*that.mySelect_col.push([name,value]);*/
				that.mySelect_col.push(name);
				/*----*/
			}
			if (filter=="type"){ 
				that.addFilter = 'tp'; that.filter_tp.push(value); 
				/* Kevin Codfert*/ 
				/*that.mySelect_tp.push([name,value]);*/
				that.mySelect_tp.push(name);
				/*----*/
			}
			if (filter=="forme"){ 
				that.addFilter = 'f'; that.filter_f.push(value);
				/*that.mySelect_f.push([name,value]);*/
				that.mySelect_f.push(name);
			}
			
			textSelection = '';
			if(that.mySelect_m.join(", ") !=''){
				textSelection += '<li><span style="font-weight:bold">Marques : </span><span style="font-size:8px;">'+that.mySelect_m.join(", ") +'</span></li>';
			}
			if(that.mySelect_cat.join(", ") !=''){
				textSelection += '<li><span style="font-weight:bold">Categories : </span><span style="font-size:8px;">'+that.mySelect_cat.join(", ") + '</span></li>';
			}
			if(that.mySelect_tp.join(", ") !=''){
				textSelection += '<li><span style="font-weight:bold">Types : </span><span style="font-size:8px;">'+that.mySelect_tp.join(", ") + '</span></li>';
			}
			if(that.mySelect_f.join(", ") !=''){
				textSelection += '<li><span style="font-weight:bold">Formes : </span><span style="font-size:8px;">'+that.mySelect_f.join(", ") + '</span></li>';
			}
			
			$('#selection').html(textSelection);

			if (filter=="tourpoitrine" || filter=="tailleSlip" || filter=="tailleFrBis" || filter=="tailleUsa" || filter=="tailleSocks" || filter=="tailleUsaDouble" || filter=="taillesuniques" || filter=="tailleEnfants"){ that.addFilter = 't'; that.filter_t.push(value); }
			if (filter=="bonnets"){ that.addFilter = 't'; that.filter_t.push(value); }

		});

		
		
		this.s_m = this.serialize('m', this.filter_m);
		this.s_tp = this.serialize('tp', this.filter_tp);
		this.s_f = this.serialize('f', this.filter_f);
		this.s_t = this.serialize('t', this.filter_t);
		this.s_c = this.serialize('c', this.filter_c);
		this.s_cat = this.serialize('cat', this.filter_cat);
		this.s_col = this.serialize('col', this.filter_col);

		this.current_page=1;
		this.load();

	},
	
	clk : function(){
		var li = $(this).parent(),
			expandable = li.hasClass('expandable');
			disabled = li.hasClass('disabled');
		if (expandable){
			if(!disabled){
				if (li.hasClass('opened')){
					li.removeClass('opened');
					li.removeClass('selected');
					li.children().children().removeClass('selected');
				} else {
					li.addClass('opened');
					li.addClass('selected');
				}
			}

		} else {
			
			if(!disabled){
				if (li.hasClass('selected')){
					li.removeClass('selected');
				} else {
					li.addClass('selected');
				}
			}else{
				alert('Ce critère n\'existe pas dans cette combinaison, vous pouvez déselectionner d\'autres critères');	
			}
			
		}
		
		products.getFilters();
		return false;
	},
	
	del : function(){
		var li = $(this).parent(),
			value = li.attr('rel'),
			filter = li.attr('name'),
			expandable = li.hasClass('expandable');
			disabled = li.hasClass('disabled');
			
		if(expandable){
			if(!disabled){
				
				if (li.hasClass('opened')){
					li.removeClass('opened');
					li.removeClass('selected');
					li.children().children().removeClass('selected');
				} else {
					li.addClass('opened');
					li.addClass('selected');
				}
			}
			
		} else {
			if(!disabled){
			
				if (li.hasClass('selected')){
					li.removeClass('selected');
		
				} else {
					li.addClass('selected');
				}
			}else{
				alert('Ce critère n\'existe pas dans cette combinaison, vous pouvez déselectionner d\'autres critères');	
			}
			
		}
		products.getFilters();
		return false;
	},

	sel : function(){
		var li = $(this).parent(),
			value = li.attr('rel'),
			filter = li.attr('name');
		
		if ($(this).is(":checked")){
			li.addClass('selected');
		} else {
			li.removeClass('selected');
		}
		
		products.getFilters();
		//return false;
	}


}

function resetchoice(){
	$('.box .rubs ul li input').attr('checked', false);
	$('.box .rubs ul li input').attr('disabled', false);
	$('.expandable').each(function(){
			 li = $(this);
			 li.removeClass('opened');
	});
	manageURLFragment();
	$('#selection').html('');
	
	sortselectInitHtml  = '<option selected="selected" value="">Sélectionner</option>';
	sortselectInitHtml += '<option value="alpha">de A à Z</option>';
	sortselectInitHtml += '<option value="pricem">Le moins cher</option>';
	sortselectInitHtml += '<option value="pricep">Le plus cher</option>';
	sortselectInitHtml += '<option value="nouveaute">Nouveauté</option>';
	$('#sortselect').html(sortselectInitHtml);

}

function initCategories(){
	$('.box .rubs ul li a').click(products.clk);
	$('.box .rubs ul li .delete').click(products.del);
	$('.box .rubs ul li input').click(products.sel);


	$('.box dl').click(function(){
		var btn = $(this),
			box = $('.rubs', btn.parent());
		if (btn.hasClass('closed')){
			box.slideDown(300);
			btn.removeClass('closed');
		} else {
			box.slideUp(150);
			btn.addClass('closed');
		}
	});
}



var menumarques = {
	clk : function(){
		var li = $(this).parent(),
			expandable = li.hasClass('expandable');
			
		if (expandable){
			if (li.hasClass('opened')){
				li.removeClass('opened');
			} else {
				li.addClass('opened');
			}
		}
		return false;
	}
}



function initMenu(){
	$('.box .rubs ul li[name=marque] > a').click(menumarques.clk);
	$('.box .rubs ul li[name=marque] > span').click(menumarques.clk);
}


function setTypesFilters(k){
	var values = k[1].split('-');
	$('.box .rubs ul#types li').removeClass('selected');
	for (var i in values){
		$('#type_'+values[i]).addClass('selected');
	}
}

function setCategoriesFilters(k){
	var values = k[1].split('-');
	$('.box .rubs ul.shrink li').removeClass('selected');
	for (var i in values){
		$('#category_'+values[i]).addClass('selected');
	}
}

function setFormesFilters(k){
	var values = k[1].split('-');
	$('.box .rubs ul#forms li').removeClass('selected');
	for (var i in values){
		$('#forme_'+values[i]).addClass('selected');
	}
}

function setManufacturersFilters(k){
	var values = k[1].split('-');
	$('.box .rubs ul#manufacturers li').removeClass('selected');
	$('.box .rubs ul#manufacturers li ul li').removeClass('selected');
	for (var i in values){
		$('#marque_'+values[i]).addClass('selected');
		$('#marque_'+values[i]).addClass('opened');
		/*$('#marque_'+values[i]+' ul li').addClass('selected');*/
	}
}

function manageURLFragment() {
	$(window).bind('hashchange', function(e) {
		var fragment = $.param.fragment();
		
		products.resetFilters();

		var az = fragment.split('/');
		for (var x in az) {
			if (az[x]){
				var k = az[x].split('=');
				if (k[0]=='m'){setManufacturersFilters(k);}
				if (k[0]=='c'){setCategoriesFilters(k);}
				if (k[0]=='t'){setTypesFilters(k);}
				if (k[0]=='f'){setFormesFilters(k);}
			}
		}
		products.getFilters();
		
	});
	$(window).trigger('hashchange');
}


var myMenuAccount = {

	state : false,

	show : function(){
		var o = $('#myBlockmenuAccount'),
			self = this;
			
		if (o.hasClass('hover')){
		} else {
			o.show().addClass('hover');
		}
		$('#myBlockAccount h4').addClass('selected');
	},

	hide : function(){
		var o = $('#myBlockmenuAccount');
		if (o.hasClass('hover')){
			o.hide().removeClass('hover');
		}
		$('#myBlockAccount h4').removeClass('selected');
	}

};


//On dom ready
$().ready(function(){

	ajaxCart.collapse();
	
	$('#headerMenu ul.menu li').hover(
		function(){
			menuID = $(this).attr('rel');
			$('#'+menuID).css('display','block');
		},
		function(){
			menuID = $(this).attr('rel');
			$('#'+menuID).css('display','none');
		}
	);
	$('#headerMenu div.menuder').hover(
		function(){
			$(this).css('display','block');
		},
		function(){
			$(this).css('display','none');
		}
	);
	
	
	$('#myBlockAccount h4').hover(
		function(){
			myMenuAccount.show();
			myMenuAccount.state=false;
		},
	
		function(){
			if (myMenuAccount.state===true){
				myMenuAccount.hide();
			}
		}
	);

	$('#myBlockmenuAccount').hover(
		function(){
		},
		function(){
			myMenuAccount.hide();
			myMenuAccount.state = true;	
		}
	);
	


	// Hide all elements with .hideOnSubmit class when parent form is submit
	$('form').submit(function(){
		$(this).find('.hideOnSubmit').hide();
	});

});



