// fonctions liees a l'URL (re)writing

// main object : Criteres
// used to aggregate the criteria on a page (from a form or a url)
// and make some modifications on them
// then build a querystring (for a container through ajax) or a url (for redirection)
// main way to be used :
// var oCriteres = new Criteres(path, action); // instanciation
// oCriteres.detect/oCriteres.setCriteres/oCriteres.setCritereValue => modification
// oCriteres.buildUrlFromCriteres / oCriteres.buildQueryStringFromCriteres => final use

/*
 * idArbo : Id univers
 * objForm : objet javascript du formulaire sur lequel s'applique cet objet Criteres
 * lstCriteresP : liste des criteres principaux
 * lstCriteres : liste complète des critères pour ce formulaire
 * urlbase : chemin de l'url
 * action : nom de la page
 */

var Criteres = function (idArbo, objForm, lstCriteresP, lstCriteres, urlbase, action) {
	this.cSeparator = '/'; // in case the separator would be different some day...
	this.cAnchor = '#'; // anchor delimitation in URL
	this.cMarqueModeleSeparator = '_';
	// delimiting letters for arguments
	this.criterePPrefix = 'p';
	this.critereFPrefix = 'f';
	//global variables
	//instantiated here, their values are set at the end of the forms
	this.lstCriteres = lstCriteres;
	this.currentHash = "";
	this.previousHash = null;

	this.idArbo = idArbo;
	this.form = objForm;		// Objet formulaire sur lequel s'appliquent ces critères
	this.critereValues = {};	// liste des valeurs de criteres
	if ( typeof(lstCriteresP) !== "undefined" ) {
		this.criteresP = lstCriteresP.split(",");	// liste des criteres prioritaires
	} else {
		this.criteresP = [];
	}
	this.criteresF = [];	// liste des criteres secondaires
	this.urlbase = "";
	this.action = "";

	this.destURL = ""; // url à charger dans le bloc résultat
	this.destContainer = ""; // id du conteneur dans lequel charger le résultat

	this.urlbase = urlbase;
	this.action = action;

	this.previousCategIndex = 0; // selectedIndex du dernier select#categ changé

	// liste constante des associations n/nom de critere
	this.critereNames = {
		"-2": "marque",
		"-1": "modele",
		"0": "categ",
		"1": "localisation",
		"2": "sous_cat",
		"3": "prix",
		"4": "kilo",
		"5": "energie",
		"6": "mill",
		"7": "sellerie",
		"8": "boite",
		"9": "cv",
		"10": "garantie",
		"11": "seg",
		"12": "profil",
		"13": "page",
		"14": "tri",
		"15": "affichage",
		"16": "carros",
		"17": "modele_RSI",
		"18": "photo",
		"19": "cp",
		"20": "couleur",
		"21": "main",
		"22": "options",
		"23": "portes",
		"24": "cylindree",
		"25": "parpage",
		"26": "cle_RSI",
		"27": "referer",
		"28": "label",
		"29": "avantage"
			// Nb d'éléments par page
	};

	this.energies = {
		"D": "diesel",
		"E": "essence",
		"G": "GPL",
		"H": "hybride",
		"W": "electrique"
	};
	this.energies_2 = [];
	for (var e in this.energies) {
		this.energies_2[this.energies[e]] = e;
	}

	this.formaterLibUrl = function (mylabel) {
		var tmp = mylabel.replace(/[\xE0-\xE5]/gi,"a");
		tmp = tmp.replace(/[\xE7]/gi,"c");
		tmp = tmp.replace(/[\xE8-\xEB]/gi,"e");
		tmp = tmp.replace(/[\xEC-\xEF]/gi,"i");
		tmp = tmp.replace(/[\xF2-\xF6]/gi,"o");
		tmp = tmp.replace(/[\xF9-\xFC]/gi,"u");
		tmp = tmp.replace(/[^A-Z|a-z|0-9| |-]+/gi, " ");
		tmp = tmp.replace(/ /g, "+");
		tmp = tmp.replace(/\++/g, "+");
		tmp = tmp.toLowerCase().replace(/(\b[a-z])/g, function () {return arguments[0].toUpperCase();});
		return tmp;
	};

	this.getCurrentHash = function () {
		this.currentHash = document.location.hash;
		return this.currentHash;
	};
	this.getCritereValue = function (critereName) {
		return this.critereValues[critereName];
	};
	this.setCritereValue = function (critereName, critereValue) {
		this.critereValues[critereName] = critereValue;
	};
	this.setCritereP = function (criteresP) {
		this.criteresP = criteresP.split(',');
	};
	this.estCritereP = function (critereName) {
		var ret = false, i;

		if ( critereName.substr(0,4) === "prix" ) {
			critereName = "prixmin";
		} else if ( critereName.substr(0,4) === "kilo" ) {
			critereName = "kmmin";
		} else if ( critereName.substr(0,4) === "mill" ) {
			critereName = "millmin";
		}
		for (i = 0;i < this.criteresP.length; ++i)
		{
			if (critereName === this.criteresP[i])
			{
				ret = true;
				break;
			}
		}
		return ret;
	};
	/* Nécessite au préalable l'appel de setCriteres() */
	this.getNombreCriteresRenseignees = function() {
		var resNbCriteres = 0;
		// parcours des criteres enregistres
		for (indexCritere in this.critereNames) {
			// si une valeur existe et qu'elle n'est pas vide
			if ( typeof(this.critereValues[this.critereNames[indexCritere]]) !== "undefined" &&
					this.critereValues[this.critereNames[indexCritere]].length !== 0) {
				resNbCriteres++;
			}
		}
		return resNbCriteres;
	};

	this.readMarqueModele = function (marque_modele) {
		marque_modele = marque_modele.replace(/-[0-9]+$/,"").replace(/-[0-9]+\.html/,"");
		if ( marque_modele.match(/^[0-9]+$/) ) {
			marque_modele = "";
		}
		if (marque_modele.indexOf(this.cMarqueModeleSeparator) === -1)
		{
			
			if ( marque_modele.indexOf(".") != -1 ) {
				marque_modele= marque_modele.substr(0, marque_modele.indexOf("."));
			}
			this.setCritereValue("marque", marque_modele);
			this.setCritereValue("modele", "");
		}
		else
		{
			this.setCritereValue("marque", marque_modele.substr(0, marque_modele.indexOf(this.cMarqueModeleSeparator)));
			var p = marque_modele.substr(1 + marque_modele.indexOf(this.cMarqueModeleSeparator));
			if ( p.indexOf(".") != -1 ) {
				p = p.substr(0, p.indexOf("."));
			}
			this.setCritereValue("modele", p);
		}
	};

	/*
	 * fonction d'interpretation des criteres depuis l'url
	 */
	this.detect = function () {
		this.detectUrl();
		this.detectAncre();
	};

	/*
	 * analyse de la partie avant l'ancre pour remplir les parametres
	 */
	this.detectUrl = function () {
		// split the location into a list
		var url = window.location.pathname;
		url = url.substr(url.indexOf(this.urlbase) + this.urlbase.length);

		if ( this.action !== "" ) {
			var sLocationList = url.substr(0, url.indexOf(this.action) - 1);
		} else {
			sLocationList = url;
		}
		var locationList = sLocationList.split(this.cAnchor)[0].split(this.cSeparator);

		for (var indexLocation = 0;indexLocation < locationList.length;/* incrementation is made in the loop */) {
			var locationItem = locationList[indexLocation];

			if (locationList[indexLocation].charAt(0) === this.criterePPrefix)
			{
				// if element is like 'p{n}' where n is an integer
				var n = parseInt(locationItem.substr(1, locationItem.length - 1), 10);
				if ( !isNaN(n) ) {
					// check if we are in the limits
					if (indexLocation+1 <= locationList.length-1) {
						var value = locationList[indexLocation+1];
						this.criteresP[this.criteresP.length] = this.critereNames[n];
						this.setCritereValue(this.critereNames[n], value);
						indexLocation += 2;
					} else {
						// elsewhere, deny the parameter
						indexLocation++;
						continue;
					}
				} else {
					this.readMarqueModele(locationItem);
					indexLocation++;
					continue;
				}
			} else {
				this.readMarqueModele(locationItem);
				indexLocation++;
				continue;
			}
		}

		var queryString = window.location.search.substring(1);
		var split1 = queryString.split('&');
		var i, split2;
		for (i = 0; split1[i]; i++)
		{
			split2 = split1[i].split('=');
			var n = parseInt(split2[0].substring(1), 10);
			if (!isNaN(n))
			{
				this.setCritereValue(this.critereNames[n], split2[1]);
			}
			else if ( split2[0]==="libmarque" ) {
				this.setCritereValue("marque", split2[1]);
			} else if ( split2[0]==="libmodele" ) {
				this.setCritereValue("modele", split2[1]);
			}
		}

		// detection of the page
		// this piece of code must be done before
		var sAfterAction = url.substr(url.indexOf(this.action) + this.action.length);
		if (sAfterAction.charAt(0) === "-") {
			// => a page in the URL
			var page = sAfterAction.substr(1, sAfterAction.indexOf('.') - 1);
			if (page.length !== 0)
			{
				this.setCritereValue("page", page);
				this.criteresF[this.criteresF.length] = "page";
			}
		}
	};

	/*
	 * analyse de la partie apres l'ancre pour remplir les parametres
	 */
	this.detectAncre = function () {
		// si pas d'ancre, on sort
		if (window.location.href.split(this.cAnchor).length <= 1) {
			return;
		}

		// on splite l'ancre en un tableau
		var locationList = window.location.href.split(this.cAnchor)[1].split(this.cSeparator);

		// pour chaque élément du tableau
		for (var indexLocation = 0;indexLocation < locationList.length - 1;)
		{
			var locationItem = locationList[indexLocation];
			// if element is like 'f{n}' where n is an integer
			if (locationItem.substr(0, 1) === this.critereFPrefix)
			{
				// on prend la valeur du n
				var n = parseInt(locationItem.substr(1, locationItem.length - 1), 10);
				if (!isNaN(n))
				{
					// on suppose que la valeur suivante est la valeur à sauvegarder
					var value = decodeURIComponent( locationList[indexLocation+1] );
					this.criteresF[this.criteresF.length] = this.critereNames[n];
					// on sauve la valeur
					this.setCritereValue(this.critereNames[n], value);
					// on avance de 2 dans la liste (nom f{n} + valeur)
					indexLocation += 2;
				}
			}
			else
			{
				// on incrémente d'un pour éviter la boucle infinie
				indexLocation += 1;
			}
		}
	};

	/*
	 * construction des chaines de caractère intervalles
	 */
	this.getIntervallePrimaireString = function (min, max, unit) {
		if (unit !== "") unit = '+'+unit;
		if ( min === '' ) {
			if ( max !== "" ) {
				return 'moins+de+' + max + unit;
			} else {
				return "";
			}
		} else if (max === '') {
			return 'plus+de+' + min + unit;
		} else if (min === max) {
			return max + unit;
		} else {
			return 'de+' + min + '+a+' + max + unit;
		}
	};
	this.getIntervalleSecondaireString = function (min, max) {
		if ( min === '' ) {
			if ( max !== "" ) {
				return '-' + max;
			} else {
				return "";
			}
		} else if (max === '') {
			return min + '-';
		} else if (min === max) {
			return max;
		} else {
			return min + '-' + max;
		}
	};

	/*
	 * fonction d'interpretation des criteres depuis un formulaire
	 */
	this.setCriteres = function (myform) {
		var marque, modele, categorie, prixmin, prixmax, modele_RSI, modeleSelect, garantie, options, tmp, i;
		if ( arguments.length < 1 ) {
			myform = this.form;
		}
		if ( $(myform).find("[name='marque']").length != 0 ) {
			marque = this.getValue(myform, "marque");
			if (marque !== '')
			{
				this.setCritereValue("marque", marque);
				if ( $(myform).find("[name='modele']").length != 0 ) {
					modele = this.getValue(myform, "modele");
					if ("mo_" === modele.substr(0,3))
					{
						// modele rsi
						modele_RSI = modele;
						// on suppose que "modele est une combo "select-one"
						modeleSelect = myform["modele"];
						i = modeleSelect.selectedIndex - 1;
						// on remonte dans les options jusqu'à la premiere qui soit un modele pur (et non un modele rsi)
						while("mo_" === modeleSelect.options[i].value.substr(0,3)) {
							i--;
						}
						modele = modeleSelect.options[i].value;
						// 2 valeurs a retourner...
						this.setCritereValue("modele", modele);
						this.setCritereValue(this.critereNames[17], modele_RSI);
					} else {
						this.setCritereValue("modele", modele);
					}
				}
			} else {
				this.setCritereValue("marque", "");
			}
		}

		if ( $(myform).find("[name='categ']").length !== 0 ) {
			categorie = this.getValue(myform, "categ");
			if ( (categorie[0] === "vp") && ((this.idArbo === 7) || (this.idArbo === 46)) ) {
				this.setCritereValue("categ", "");
			} else {
				this.setCritereValue("categ", categorie[0]);
			}
			// Sous-categorie
			this.setCritereValue("sous_cat", categorie[1]);
		}

		// Localisation
		if ( $(myform).find("[name='departement']").length !== 0 ) {
			tmp = this.getValue(myform, "departement");
			if ( tmp !== '' ) {
				this.setCritereValue("localisation", tmp);
			} else if ( $(myform).find("[name='region']").length !== 0 ) {
				this.setCritereValue("localisation", this.getValue(myform, "region"));
			}
		}

		// Budget
		if ( $(myform).find("[name='prixmin']").length !== 0 ) {
			prixmin = this.getValue(myform, "prixmin");
			prixmax = this.getValue(myform, "prixmax");
			if ( prixmin !== '' || prixmax !== '' ) {
				// prixmin et prixmax ont la meme priorite
				if ( this.estCritereP("prix") ) {
					this.setCritereValue("prix", this.getIntervallePrimaireString(prixmin, prixmax, "E"));
				} else {
					this.setCritereValue("prix", this.getIntervalleSecondaireString(prixmin, prixmax));
				}
			} else {
				this.setCritereValue("prix", "");
			}
		}

		// Km
		if ( $(myform).find("[name='kmmin']").length !== 0 ) {
			var kilomin = this.getValue(myform, "kmmin");
			var kilomax = this.getValue(myform, "kmmax");
			if(kilomin !== '' || kilomax !== '')
			{
				if(this.estCritereP("kilo"))
				{
					this.setCritereValue("kilo", this.getIntervallePrimaireString(kilomin, kilomax, "km"));
				}
				else
				{
					this.setCritereValue("kilo", this.getIntervalleSecondaireString(kilomin, kilomax));
				}
			} else {
				this.setCritereValue("kilo", "");
			}
		}

		// Energie
		if ( $(myform).find("[name='energie']").length !== 0 ) {
			var energie = this.getValue(myform, "energie");
			if(energie.length === 1 && this.idArbo != 13 && this.idArbo != 286) {
				energie = this.energies[energie];
			}
			this.setCritereValue("energie", energie);
		}

		// Age
		if ( $(myform).find("[name='mill']").length !== 0 ) {
			this.setCritereValue("mill", this.getValue(myform, "mill"));
		} else if ( $(myform).find("[name='millmin']").length !== 0 ) {
			var millmin = this.getValue(myform, "millmin");
			var millmax = this.getValue(myform, "millmax");
			if(millmin !== '' || millmax !== '')
			{
				if(this.estCritereP("mill"))
				{
					this.setCritereValue("mill", this.getIntervallePrimaireString(millmin, millmax, ""));
				}
				else
				{
					this.setCritereValue("mill", this.getIntervalleSecondaireString(millmin, millmax));
				}
			} else {
				this.setCritereValue("mill", "");
			}
		}

		// Sellerie
		if ( $(myform).find("[name='sellerie']").length !== 0 ) {
			this.setCritereValue("sellerie", this.getValue(myform, "sellerie"));
		}

		// Transmission
		if ( $(myform).find("[name='boite']").length !== 0 ) {
			this.setCritereValue("boite", this.getValue(myform, "boite"));
		}

		// Puissance fiscale OU din
		//	fiscale
		if ( ($(myform).find("[name='puis_fisc_min']").length !== 0) ||
			($(myform).find("[name='puis_ch_min']").length !== 0) ||
			($(myform).find("[name='cv']").length !== 0) ) {
			var puis_min = this.getValue(myform, "puis_fisc_min");
			var puis_max = this.getValue(myform, "puis_fisc_max");
			if ( (puis_min === "") && (puis_max === "") ) {
				puis_min = puis_max = this.getValue(myform, "cv");
			}
			if ( (puis_min === "") && (puis_max === "") ) {
				//	DIN
				puis_min = this.getValue(myform, "puis_ch_min");
				puis_max = this.getValue(myform, "puis_ch_max");
				if ( this.estCritereP("cv") ) {
					this.setCritereValue("cv", this.getIntervallePrimaireString(puis_min, puis_max, "ch"));
				} else {
					this.setCritereValue("cv", this.getIntervalleSecondaireString(puis_min, puis_max));
				}
			} else {
				if ( this.estCritereP("cv") ) {
					this.setCritereValue("cv", this.getIntervallePrimaireString(puis_min, puis_max, "cv"));
				} else {
					this.setCritereValue("cv", this.getIntervalleSecondaireString(puis_min, puis_max));
				}
			}
		}
		// Garantie
		if ( ($(myform).find("[name='garantie_argus']").length !== 0) || ($(myform).find("[name='garantie_pro']").length !== 0) ) {
				garantie = '';
				if ( this.getValue(myform, "garantie_argus") === "1" ) {
					garantie += "argus";
				}
				if ( this.getValue(myform, "garantie_pro") === "1" ) {
					if (garantie != '') {
						garantie += ",";
					}
					garantie += "pro";
				}
			this.setCritereValue("garantie", garantie);
		}
		// Segment
		if ( $(myform).find("[name='seg']").length !== 0 ) {
			this.setCritereValue("seg", this.getValue(myform, "seg"));
		}

		// Profil

		// Pagination
		if ( $(myform).find("[name='page']").length !== 0 ) {
			this.setCritereValue("page", this.getValue(myform, "page"));
		}

		// Tri
		if ( $(myform).find("[name='tri']").length !== 0 ) {
			this.setCritereValue("tri", this.getValue(myform, "tri"));
		}

		// Affichage

		// Carrosserie
		if ( $(myform).find("[name='carros']").length !== 0 ) {
			this.setCritereValue("carros", this.getValue(myform, "carros"));
		}

		// Mod RSI

		// Photo
		if ( $(myform).find("[name='photo']").length !== 0 ) {
			this.setCritereValue("photo", this.getValue(myform, "photo"));
		}

		// Cp + Distance
		if ( $(myform).find("[name='cp']").length !== 0 ) {
			tmp = this.getValue(myform, "cp");
			if ( tmp !== "" ) {
				if ( $(myform).find("[name='distance']").length !== 0 ) {
					i = this.getValue(myform, "distance");
					if ( i !== "" ) {
						tmp = this.getValue(myform, "cp") + "," + i;
					}
				}
				this.setCritereValue("cp", tmp);
			} else {
				this.setCritereValue("cp", "");
			}
		}
		
		// Couleur
		if ( $(myform).find("[name='couleur']").length !== 0 ) {
			this.setCritereValue("couleur", this.getValue(myform, "couleur"));
		}

		// 1re main
		if ( $(myform).find("[name='main']").length !== 0 ) {
			this.setCritereValue("main", this.getValue(myform, "main"));
		}

		// Options
		if ( this.idArbo === 7 ) {
			options = [];
			$(myform).find("input:checkbox:checked:not([name='photo'],[name='garantie_argus'],[name='garantie_pro'])").each(function(){
				options[options.length] = $(this).attr("name");
			});
			tmp = this.getValue(myform, "clim");
			if ( tmp !== "" ) {
				options[options.length] = "clim=" + tmp;
			}
			this.setCritereValue("options", options.join(","));
		}

		// Nb portes
		if ( $(myform).find("[name='portes']").length !== 0 ) {
			this.setCritereValue("portes", this.getValue(myform, "portes"));
		}

		// Nb d'éléments par page
		if ( $(myform).find("[name='parpage']").length !== 0 ) {
			this.setCritereValue("parpage", this.getValue(myform, "parpage"));
		}
		// Cle RSI
		if ( $(myform).find("[name='version']").length !== 0 ) {
			this.setCritereValue("cle_RSI", this.getValue(myform, "version"));
		}

		// Label
		if ( $(myform).find("[name='label']").length !== 0 ) {
			this.setCritereValue("label", this.getValue(myform, "label"));
		}

		// Avantage
		if ( $(myform).find("[name='avantage']").length !== 0 ) {
			this.setCritereValue("avantage", this.getValue(myform, "avantage"));
		}
	};

	/*
	 * fonction inverse : remplissage d'un formulaire à partir des critères enregistrés
	 */
	this.fillFormulaireWithCriteres = function(myform) {
		var indexCritere;
		if ( arguments.length < 1 ) {
			myform = this.form;
		}
		// Desactive tous les champs
		$(myform).find(":enabled").attr("disabled","disabled");
		// Remplis avec les valeurs sélectionnées
		for(indexCritere in this.critereNames) {
			if ( typeof(this.critereValues[this.critereNames[indexCritere]]) !== "undefined" &&
					this.critereValues[this.critereNames[indexCritere]].length !== 0) {
				//cas spécial du modèle: si 17 (modele_RSI) est renseigné, ce dernier est prioritaire
				if ( indexCritere == '-1'
					&& typeof(this.critereValues[this.critereNames[17]]) !== "undefined"
					&& this.critereValues[this.critereNames[17]].length !== 0) {
					//rien, on laisse le critere 17 faire son oeuvre
				}
				else {
					this.setValue(myform, this.critereNames[indexCritere], this.critereValues[this.critereNames[indexCritere]], true);
				}
			}
		}
		// Charge le formulaire
		$(myform).find(":disabled").removeAttr("disabled");
		this.changeCrit();
	};

	this.getConvertedValue = function(item, value) {
		switch(item){
			case "energie":
				return this.energies_2[value];
			default:
				return value;
		}
	};

	/*
	 * set the value of an item in a form, whatever the type of input (hidden/text/radio/checkbox/select/textarea)
	 */
	this.setCombo = function (item, value) {
		var o = $(this.form).find("select[name='" + item + "']");
		if ( o.length !== 0 ) {
			o.find("option").remove();
			o.append("<option value='" + value + "'></option>");
			o.attr("value", value);
		}
	};
	this.setValue = function(myform, item, value, addOptionIfNotExists) {
		var l,e,v, oJq, vMin,vMax;
		if(arguments.length === 3) {
			addOptionIfNotExists = false;
		}
/*
auto	"-2": "marque",
auto	"-1": "modele",
auto	"0": "categ",
ok		"1": "localisation",
ok(auto)"2": "sous_cat",
ok		"3": "prix",
ok		"4": "kilo",
ok	"5": "energie",
auto	"6": "mill",
auto	"7": "sellerie",
ok		"8": "boite",
ok		"9": "cv",
ok		"10": "garantie",
		"11": "seg",
		"12": "profil",
		"13": "page",
		"14": "tri",
		"15": "affichage",
		"16": "carros",
		"17": "modele_RSI",
ok(auto)"18": "photo",
ok		"19": "--inutilise--",
auto	"20": "couleur",
auto	"21": "main",
ok		"22": "options",
auto	"23": "portes"
*/
		switch(item) {
			case "energie":
				if ( (this.idArbo !== 286) && typeof(this.energies_2[value]) !== "undefined" ) {
					this.setCombo(item, this.energies_2[value]);
				} else {
					this.setCombo(item, value);
				}
				break;
			case "options":
				l = value.split(",");
				for (e in l) {
					if ( l[e].indexOf("=") !== -1 ) {
						v = l[e].split("=");
						this.setCombo(v[0], v[1]);
					} else {
						$(myform).find("input[name='" + l[e] + "']").attr("checked",true);
					}
				}
				break;
			case "cv":
			case "kilo":
			case "prix":
			case "mill":
				// Intervalles
				l = value.match(/([0-9]+)/g);
				if ( $.isArray(l) && (l.length === 1) ) {
					if ( (value.substr(0,5) === "moins") || (value.charAt(0) === "-") ) {
						// Valeur max
						vMin = "";
						vMax = l[0];
					} else if ( (value.substr(0,4) === "plus") || (value.charAt(value.length-1) === "-") ) {
						// Valeur min
						vMin = l[0];
						vMax = "";
					} else {
						// Valeur directe
						vMin = l[0];
						oJq = $(myform).find("[name='cv']");
						if ( (item === "cv") && (oJq.length !== 0) ) {
							this.setCombo("cv",vMin);
							break;
						} else {
							vMax = l[0];
						}
					}
				} else if ( $.isArray(l) && (l.length === 2) ) {
					// Valeurs min et max
					vMin = l[0];
					vMax = l[1];
				} else {
					// Aucune valeur
					break;
				}
				switch (item) {
					case "cv":
						if ( $(myform).find("[name='puis_ch_min']").length != 0 ) {
							e = "puis_ch_";
						} else {
							e = "puis_fisc_";
						}
						break;
					case "kilo": e = "km"; break;
					case "prix": e = "prix"; break;
					case "mill": e = "mill"; break;
				}
				this.setCombo(e + "min",vMin);
				this.setCombo(e + "max",vMax);
				break;
			case "garantie":
				// Garantie argus ou pro
				l = value.split(",");
				for (e in l) {
					if ( l[e] === "argus" ) {
						$(myform).find("[name='garantie_argus']").attr("checked",true);
					} else if ( l[e] === "pro" ) {
						$(myform).find("[name='garantie_pro']").attr("checked",true);
					}
				}
				break;
			case "sous_cat":
			case "modele_RSI":
				switch(item) {
					case "sous_cat":
						// sous-categorie --> a mettre dans categ
						item = "categ";
						break;
					case "modele_RSI":
						item = "modele";
						break;
				}
			case "cp":
				l = value.split(",");
				$(myform).find("[name='cp']").attr("value",l[0]);
				if ( l.length > 1 ) {
					this.setCombo("distance",l[1]);
				}
				break;
			default:
				$(myform).find("[name='" + item + "']").each(function (){
					if ( $(this).is("select") ) {
						$(this).find("option").remove();
						l = value.split(",");
						for (e in l) {
							$(this).append("<option value='" + l[e] + "'></option>");
							$(this).attr("value", l[e]);
						}
					} else if ( $(this).is("input:checkbox,input:radio") ) {
						l = value.split(",");
						$(this).each(function(){
							for (e=0; e < l.length; e++) {
								if ( l[e] === $(this).attr("value") ) {
									$(this).attr("checked",true);
									break;
								}
							}
						});
					} else if ( $(this).is("input") ) {
						$(this).attr("value", value);
					}

				});
				break;
		}
	};

	/*
	 * construire la chaine query string selon les criteres enregistres
	 * "&marque=mar&modele=mod&p0=t&f1=..."
	 * no distinction between p and f criteria, they are in the order of their respective indexes
	 */
	this.buildQueryStringFromCriteres = function() {
		var newQueryString = "", indexCritere, v;

		v = this.getCritereValue("marque");
		if ( (typeof(v) !== "undefined") && (v.length !== 0) ) {
			newQueryString += "&marque=" + this.formaterLibUrl(v);

			v = this.getCritereValue("modele");
			if ( (typeof(v) !== "undefined") && (v.length !== 0) ) {
				newQueryString += "&modele=" + this.formaterLibUrl(v);
			}
		}

		// parcours des criteres enregistres
		for (indexCritere in this.critereNames) {
			if ( indexCritere >= 0 ) {
				// si une valeur existe et qu'elle n'est pas vide
				if ( typeof(this.critereValues[this.critereNames[indexCritere]]) !== "undefined" &&
						this.critereValues[this.critereNames[indexCritere]].length !== 0) {
					// rajout à la query string
					newQueryString += "&" +
						( this.estCritereP(this.critereNames[indexCritere]) ? this.criterePPrefix : this.critereFPrefix ) +
						indexCritere + "=" + this.critereValues[this.critereNames[indexCritere]];
				}
			}
		}

		return newQueryString;
	};

	/*
	 * construire l'URL selon les criteres enregistres
	 * "/baseurl/marque_modele/p0/v0/.../action.html#f0/w0/..."
	 */
	this.buildUrlFromCriteres = function() {
        var bAtLeastOneCriterium = ((this.idArbo === 7) || (this.idArbo === 46)); // variable to know if at least one criterium is defined
		var url = this.urlbase;	// 2 variables are built : one for the part before the anchor...
		var ancre = ""; // ... one for the part thereafter
		var marqMod = "";

		var marque = this.getCritereValue("marque");
		if ((typeof(marque) !== "undefined") && (marque.length !== 0)) {
			// at least one criterium is defined
			bAtLeastOneCriterium = true;

			if ( this.estCritereP("marque") ) {
				marqMod += this.formaterLibUrl(marque);
			} else {
				marqMod += this.critereFPrefix + "-2/" + this.formaterLibUrl(marque) + this.cSeparator;
			}
			var modele = this.getCritereValue("modele");
			if( (typeof(modele) !== "undefined") && modele.length !== 0 ) {
				if ( this.estCritereP("modele") ) {
					marqMod += this.cMarqueModeleSeparator + this.formaterLibUrl(modele);
				} else {
					marqMod += this.critereFPrefix + "-1/" + this.formaterLibUrl(modele) + this.cSeparator;
				}
			}
		}
		if ( (marqMod !== "") && ((this.idArbo !== "minisite") || (this.action.length !== 0))  ) {
			if ( this.estCritereP("marque") ) {
				url += marqMod + this.cSeparator;
			} else {
				ancre += marqMod;
			}
		}

		// parcours des criteres enregistres
		for (var indexCritere in this.critereNames)
		{
			if ( indexCritere >= 0 ) {
				if ( typeof(this.critereValues[this.critereNames[indexCritere]]) !== "undefined" &&
					this.critereValues[this.critereNames[indexCritere]].length !== 0)
				{
					// at least one criterium is defined
					bAtLeastOneCriterium = true;

					// if primary criterieum => added to the url
					if(this.estCritereP(this.critereNames[indexCritere])) {
						url += this.criterePPrefix + indexCritere + this.cSeparator + this.critereValues[this.critereNames[indexCritere]] + this.cSeparator;
					} else {
						// if secondary criterium => added to the part after the anchor
						if ( (indexCritere != 13) || this.critereValues[this.critereNames[indexCritere]] > 1 ) {
							ancre += this.critereFPrefix + indexCritere + this.cSeparator + this.critereValues[this.critereNames[indexCritere]] + this.cSeparator;
						}
					}
				}
			}
		}

		// build the full url
		if ((this.idArbo === 7 && this.containsFCriteres())
			|| (this.idArbo === 46 && this.containsFCriteresFT())
			|| (this.idArbo === 286 && this.containsFCriteresFT()))
		{
			var i, flag, flag2, addurl;
			url = this.urlbase + (this.idArbo == 7 || this.idArbo == 286 ? "annonces.cfm":"fiches.cfm") + "?";
			flag = flag2 = 0;
			ancre = "";
			for (i = -2; this.critereNames[i]; i++)
			{
				if (i != 13 && i != 14 && i != 15 && i != 25
					&& typeof(this.critereValues[this.critereNames[i]]) !== 'undefined'
					&& this.critereValues[this.critereNames[i]].length)
				{
					if ( this.critereNames[i] === "marque" ) {
						addurl = "libmarque" + '=' + this.critereValues[this.critereNames[i]];
					} else if ( (this.critereNames[i] === "modele") ) {
						if ( this.critereValues["marque"] != "" ) { // On ne peut pas choisir de modele sans marque (mais des fois ça arrive)
							addurl = "libmodele" + '=' + this.critereValues[this.critereNames[i]];
						} else {
							addurl = "";
						}
					}
					else if (this.idArbo === 7 && this.estCritereP(this.critereNames[i]))
					{
						addurl = 'p' + i + '=' + this.critereValues[this.critereNames[i]];
					}
					else
					{
						addurl = 'f' + i + '=' + this.critereValues[this.critereNames[i]];
					}
					url += (flag?'&':'') + addurl;
					flag = 1;
				}
				else if (!this.search
						&& typeof(this.critereValues[this.critereNames[i]]) !== 'undefined'
						&& this.critereValues[this.critereNames[i]].toString().length ) {
                    if ( (i === 13) ) {
                    	if ( (this.critereValues['page'] > 1) || (document.location.hash.indexOf("f13") != -1) ) {
                           ancre += (!flag2?'#':'') + 'f' + i + '/' + this.critereValues[this.critereNames[i]] + '/';
                           flag2 = 1;
                        }
                    } else {
                        ancre += (!flag2?'#':'') + 'f' + i + '/' + this.critereValues[this.critereNames[i]] + '/';
                        flag2 = 1;
                    }
				}
			}
			url += ancre;
		}
		else if(bAtLeastOneCriterium) {

			if (this.urlbase == url && this.idArbo != 286 && this.idArbo !== "minisite") {	// pas de criteres principaux passés
				url = url + (this.action.length === 0 ? '' : this.action + ".html") + (ancre.length === 0 ? '' : (this.search ? '' : "#" + ancre));
			} else if ( this.idArbo === "minisite" ) {
				if ( (this.action.length === 0) && (marqMod !== "") ) {
					url += marqMod + ".html";
				} else if ( this.action.length !== 0 ) {
					url = url + this.action + ".html";
				}
				url += (ancre.length === 0 ? '' : (this.search ? '' : "#" + ancre));
			} else {
				if (this.action.length === 0)	// action vide, retire le / de la fin d'url
					url = url.substr(0, url.length - 1);
				url = url + this.action + ".html" + (ancre.length === 0 ? '' : (this.search ? '' : "#" + ancre));
			}
		}
		// else, in order to go back to the form page
		// we let the url like it is (i.e. urlbase), without the action

		return url;
	};

	this.containsFCriteres = function()
	{
		var j, k;

		j = k = 0;
		for (i in this.critereValues)
		{
			if (typeof (this.critereValues[i]) !== 'undefined' && this.critereValues[i].length
				&& i !== "page"
				&& i !== "tri"
				&& i !== "affichage"
				&& i !== "parpage")
			{
				j++;
				if (this.estCritereP(i))
				{
					k++;
				}
			}
		}
		if (j > k)
		{
			return (1);
		}
		return (0);
	};

	this.containsFCriteresFT = function()
	{
		var j, k;

		j = k = 0;
		for (i in this.critereValues)
		{
			if (typeof (this.critereValues[i]) !== 'undefined' && this.critereValues[i].length
				&& i !== "page"
				&& i !== "tri"
				&& i !== "affichage"
				&& i !== "parpage")
			{
				j++;
				if (i === "marque" || i === "modele")
				{
					k++;
				}
			}
		}
		if (j > k)
		{
			return (1);
		}
		return (0);
	};

	/*
	 * get the value of an item from a form, whatever the type of input (hidden/text/radio/checkbox/select/textarea)
	 */
	this.getValue = function(myform, item) {
		// retourne la valeur du champ ou '' si n'existe pas
		var retour;
		var jqEl = $(myform).find("[name=" + item + "]");

		if ( item === "categ" ) {
			retour = [];
			if ( jqEl.is("select") ) {
				// Si la categorie est une sous-categorie (=le libelle commence par un espace insecable) --> retrouve la categorie
				// Retourne un tableau [cat,sous_cat]
				jqEl = jqEl[0];
				if ( jqEl.options[jqEl.selectedIndex].text.charAt(0) === String.fromCharCode(160) ) {
					for (var i=jqEl.selectedIndex; (i >= 0) && (jqEl.options[i].text.charAt(0) === String.fromCharCode(160)); i--) {}
					if ( i >= 0 ) {
						retour[0] = jqEl.options[i].value;
						retour[1] = jqEl.options[jqEl.selectedIndex].value;
					} else {
						retour[0] = jqEl.options[jqEl.selectedIndex].value;
						retour[1] = "";
					}
				} else {
					retour[0] = jqEl.options[jqEl.selectedIndex].value;
					retour[1] = "";
				}
			} else {
				// Cas special categorie en boutons radio
				retour[0] = jqEl.filter(":checked").val();
				if ( (retour[0] === "vu") || (retour[0] === 2) ) {
					retour[0] = "vu";
					retour[1] = "";
				} else {
					if ( typeof(retour[0]) == "undefined")
						retour[1] = "";
					else
						retour[1] = retour[0];
					retour[0] = "vp";
				}
			}
			return retour;
		} else {
			if ( jqEl.is("input:checkbox,input:radio") ) {
				retour = [];
				jqEl.filter(":checked").each(function() {retour[retour.length] = $(this).val();});
			} else {
				retour = jqEl.val();
			}
		}
		if ( retour && $.isArray(retour) ) {
			return retour.join(",");
		} else if ( retour ) {
			return retour;
		} else {
			return "";
		}
	};

	/*
	 * Chargement de destURL dans le div destContainer dès que l'url de la page change
	 */
	this.initRefresh = function (objName, destContainer, destURL) {
		this.destContainer = destContainer;
		this.destURL = destURL;
		this.objName = objName;
		this.timer = setInterval(this.objName + "._checkRefresh()",100);
	};
	this._checkRefresh = function() {
		var sParamPub = "";
		if ( this.getCurrentHash() !== this.previousHash ) {
			clearInterval(this.timer);
			this.detectAncre();

			if (typeof rappCritSec == "function" && typeof this.form != "undefined") {
				$('#critkmmax').remove();
				$('#critkmmin').remove();
				$('#critpuis_ch_max').remove();
				$('#critpuis_ch_min').remove();
				for(i=0; i<this.form.elements.length; i++)
				{
					var nomCritRef = this.form.elements[i].name;
					var valCritRef = this.form.elements[i].value;
					var typeCritRef = this.form.elements[i].type;
					if(typeCritRef != "checkbox" && valCritRef != '')
					{
						rappCritSec (nomCritRef);
					}
					if(typeCritRef=="checkbox" && this.form.elements[i].checked == true)
					{
						rappCritSec (nomCritRef);
					}
				}
			}

			if ( $("#attente").length === 0 ) {
				$("#" + this.destContainer).html("<h2>Chargement...</h2>");
			} else {
				$("#" + this.destContainer).html($("#attente").html());
			}
			if ( typeof(PubLoader) !== "undefined" ) {
				sParamPub = PubLoader.getParamPub(this.critereValues["kilo"],
						this.critereValues["sous_cat"],
						this.critereValues["prix"],
						this.critereValues["mill"]);
			}
			// Recharge les pubs une fois que le contenu est chargé
			$("#" + this.destContainer).load(this.destURL + this.buildQueryStringFromCriteres(), null, function () {
				if ( typeof(PubLoader) !== "undefined" && !PubLoader.bFirstCall ) {
					reloadPub(sParamPub);
				}
			});
			this.previousHash = this.currentHash;
			this.timer = setInterval(this.objName + "._checkRefresh()",100);
		}
	};

	/*
	 *
	 */

	this.clearForm = function () {
		$(':input',this.form)
		 .not(':button, :submit, :reset, :hidden')
		 .val('')
		 .removeAttr('checked')
		 .removeAttr('selected');
		$('#selectionBar').hide();
		$('#rappCrit').hide();
		this.form.modele.options.length = 0;
		this.form.modele.options[0] = new Option ("Indifférent","");
		this.form.rappcrit.value = '';
		this.setCriteres();
		this.changeCrit();
		window.location.href=oCriteres.buildUrlFromCriteres();
	};

	this.changeCrit = function (objSrc, iTous) {
		if (objSrc && (objSrc.length != null) && (objSrc[0].type == 'select-one') && (objSrc[0].id == 'categ')) {
			if ((objSrc[0].options[objSrc[0].selectedIndex].value=='vi') && $('#selectVIfunction')) {
				objSrc[0].selectedIndex = this.previousCategIndex;
				eval($('#selectVIfunction').val());
				return;
			}
			this.previousCategIndex = objSrc[0].selectedIndex;
		}
		var oJq, oMe, urlParams, aList, aList2, i, newList = "";
		if ( arguments.length < 2 ) {
			iTous = 1;
		}
		if ( arguments.length < 1 ) {
			objSrc = {"name":""};
		} else {
			switch(objSrc.attr("name")) {
				case "marque":
					this.form.modele.options.length = 0;
					this.form.modele.options[0] = new Option ("Indifférent","");
					this.setCritereValue("modele","");
					break;
			}
			objSrc = {"name":objSrc.attr("name")};
		}
		oJq = $(this.form);
		oMe = this;
		urlParams = oJq.serialize();
        $("#rechBut").html("<a style=\"cursor:normal;\"><img src=\"/img/occasion3/bouton/b_rechercher_off.gif\"></a>");
		oJq.find(":enabled").attr("disabled","disabled");
		oJq.find("input,select").siblings("label").css("color","#C2C2C2");
		aList = this.lstCriteres.split("&");
		// Supprime les input text de la liste des criteres a recharger
		aList2 = aList[0].split(",");
		for (i=0; i < aList2.length;i++) {
			if ( oJq.find("[name='"+aList2[i]+"']").not(":text,[type='hidden']").length != 0 ) {
				newList += "," + aList2[i];
			}
		}
		// Ajout les eventuels parametres supplementaires
		for (i=1; i < aList.length;i++) {
			newList += "&" + aList[i];
		}
		newList = newList.substr(1,newList.length);
		$.getJSON("/include/getListes.cfm?" + urlParams + "&iTous=" + iTous + "&univ=" + this.idArbo + "&liste=" + newList, {}, function(data){
			for (i = 0; i < data.length; i++) {
				if(objSrc.name !== data[i].NAME) {
					switch (data[i].TYPE) {
						case 'radio':
							break;
						case 'cbs':
							if ( (data[i].VALUES.length === 1) && (data[i].VALUES[0] == 0) ) {
								oJq.find("input#"+data[i].NAME).attr("rien",1);
							} else {
								oJq.find("input#"+data[i].NAME).removeAttr("rien");
							}
							break;
						case "count":
							$("#nbPA").text(data[i].VALUES[0].toString().replace(/([0-9]{3}$)+/," $1") + " annonce" + ((parseInt(data[i].VALUES[0].toString(),10)<2?"":"s")));
							break;
						default:
							oJq.find("select#"+data[i].NAME).html("");
							if (iTous > 0) {
								if (data[i].NAME !== "categ") {
									if (iTous === 1) {
										oJq.find("select#"+data[i].NAME).append($("<option></option>").attr("value","").text("Indifférent "));
									} else {
										if (data[i].NAME === "marque") {
											oJq.find("select#"+data[i].NAME).append($("<option></option>").attr("value","").text("Marque"));
										} else if (data[i].NAME === "modele") {
											oJq.find("select#"+data[i].NAME).append($("<option></option>").attr("value","").text("Modèle"));
										} else {
											oJq.find("select#"+data[i].NAME).append($("<option></option>").attr("value","").text("Indifférent"));
										}
									}
								}
							}
							for (var j = 0; j < data[i].VALUES.length; j++) {
								arrVal = data[i].VALUES[j].toString().split('|');
								v = $("<option></option>");
								v.attr("value",arrVal[1]);
								v.text(arrVal[0]);
								if (arrVal[1] == data[i].SELECTED) {
									v.attr("selected", true);
								}
								oJq.find("select#"+data[i].NAME).append(v);
								v = null;
							}
						}
					}
			}
			oJq.find(":disabled:not([rien])").removeAttr("disabled");
			oJq.find(":not([disabled])").siblings("label").css("color","black");
			oMe.setComboIntervalle("prix");
			oMe.setComboIntervalle("km");
			oMe.setComboIntervalle("puis_ch_");
			oMe.setComboIntervalle("puis_fisc_");
			oMe.setComboIntervalle("mill");
			if (newList.indexOf('addVI=true')>0) {
				oJq.find('select#categ').find('option[value="vi"]').remove();
				oJq.find('select#categ').append($("<option></option>").attr("value","vi").text("Véhicules Industriels"));
			}
	        $("#rechBut").html("<a onclick=\"javascript:rech();\" style=\"cursor:pointer;\"><img src=\"/img/occasion3/bouton/b_rechercher.gif\"></a>");
		});
	};

	/*
	 * Pour les intervalles, si la borne inf est sélectionnée, désactive dans la liste de la borne sup les valeurs
	 * qui sont inférieures à celle sélectionnée en borne inf. Et inversement.
	 */
	this.setComboIntervalle = function (name) {
		var oMin = $(this.form).find("select[name='" + name + "min']");
		if ( oMin.length ) {
			var oMax = $(this.form).find("select[name='" + name + "max']");
			if ( oMax.length ) {
				var n = parseInt($(oMin).find("option:selected").attr("value"),10);
				if ( $.browser.msie && ($.browser.version <= 7) ) {
					// Impossible de mettre à disable une option sur ie < 8
					if ( !isNaN(n) ) {
						$(oMax).find("option,optgroup").each(function () {
							if ( ($(this).attr("value") === "") || (parseInt($(this).attr("value"),10) > n) ) {
								if ( $(this).is("optgroup") ) {
									$(this).replaceWith("<option value=\"" + $(this).attr("value") + "\">" + $(this).attr("label") + "</option>");
								}
							} else {
								if ( $(this).is("option") ) {
									$(this).replaceWith("<optgroup value=\"" + $(this).attr("value") + "\" label=\"" + $(this).text() + "\" />");
								}
							}
						});
					}
					var n = parseInt($(oMax).find("option:selected").attr("value"),10);
					if ( !isNaN(n) ) {
						$(oMin).find("option,optgroup").each(function () {
							if ( ($(this).attr("value") === "") || (parseInt($(this).attr("value"),10) < n) ) {
								if ( $(this).is("optgroup") ) {
									$(this).replaceWith("<option value=\"" + $(this).attr("value") + "\">" + $(this).attr("label") + "</option>");
								}
							} else {
								if ( $(this).is("option") ) {
									$(this).replaceWith("<optgroup value=\"" + $(this).attr("value") + "\" label=\"" + $(this).text() + "\" />");
								}
							}
						});
					}
				} else {
					if ( !isNaN(n) ) {
						$(oMax).find("option").each(function () {
							if ( ($(this).attr("value") === "") || (parseInt($(this).attr("value"),10) > n) ) {
								$(this).attr("disabled",false);
							} else {
								$(this).attr("disabled",true);
							}
						});
					}
					var n = parseInt($(oMax).find("option:selected").attr("value"),10);
					if ( !isNaN(n) ) {
						$(oMin).find("option").each(function () {
							if ( ($(this).attr("value") === "") || (parseInt($(this).attr("value"),10) < n) ) {
								$(this).attr("disabled",false);
							} else {
								$(this).attr("disabled",true);
							}
						});
					}
				}
			}
		}
	};

	this.checkForm = function (myform) {
		var cpt = 0, v, v2;
		$(myform).find("select option:selected").each(function () {
			if ( $(this).attr("value") !== "" ) {
				cpt++;
			}
		});
		$(myform).find(":text").each(function () {
			if ( !isBlank($(this).attr("value")) ) {
				cpt++;
			}
		});
		cpt += $(myform).find("(input:checkbox,input:radio):checked").length;
		if ( cpt < 2 ) {
			alert("Veuillez choisir au moins 2 critères...");
			return false;
		}
		oJq = $(myform).find("[name='prixmin']");
		if ( oJq.length !== 0 ) {
			v = oJq.attr("value");
			if ( !isBlank(v) ) {
				if ( !isNumeric(v) ){
					alert("Le prix min doit être numerique.");
					return false;
				}
			} else {
				v = "";
			}
			v2 = $(myform).find("[name='prixmax']").attr("value");
			if ( !isBlank(v2) ) {
				if ( !isNumeric(v2) ) {
					alert("Le prix max doit être numerique.");
					return false;
				}
			} else {
				v2 = "";
			}
			if ( (v !== "") && (v2 !== "") ) {
				if ( v-v2 > 0 ) {
					alert("Le prix minimum ne peut être supérieur au prix maximum.");
					return false;
				}
			}
		}
		oJq = $(myform).find("[name='puis_fisc_min']");
		if ( oJq.length !== 0 ) {
			v = oJq.attr("value");
			v2 = $(myform).find("[name='puis_fisc_max']").attr("value");
			if ( (v !== "") && (v2 !== "") ) {
				if ( v-v2 > 0 ) {
					alert("La puissance fiscale minimum ne peut être supérieur à la puissance fiscale maximum.");
					return false;
				}
			}
		}
		oJq = $(myform).find("[name='millmin']");
		if ( oJq.length !== 0 ) {
			v = oJq.attr("value");
			v2 = $(myform).find("[name='millmax']").attr("value");
			if ( (v !== "") && (v2 !== "") ) {
				if ( v-v2 > 0 ) {
					alert("L'âge minimum ne peut être supérieur à l'âge maximum.");
					return false;
				}
			}
		}
		return true;

	};
}
