// fonctions liees a l'URL (re)writing

// in case the separator would be different some day...
var cSeparator = '/';
// anchor delimitation in URL
var cAnchor = '#';
var cMarqueModeleSeparator = '_';
// delimiting letters for arguments
var criterePPrefix = 'p';
var critereFPrefix = 'f';

//global variables
//instantiated here, their values are set at the end of the forms
var lstCriteresP;
var lstCriteresF;

function formaterLibUrl(mylabel)
{
	var tmp = mylabel.replace(/[^A-Z|a-z|0-9| |\-|\+]+/g, "");
	tmp = tmp.replace(/ /g, "+");
	tmp = tmp.replace("++", "+");

	return tmp;
}

var previousHash = "";

function getCurrentHash()
{
	var splitUrl = window.location.href.split('#');
	return (splitUrl.length == 2 ? splitUrl[1] : '');
}

function Criteres()
{
	// liste des valeurs de criteres
	this.critereValues = Array();
	// liste des criteres prioritaires
	this.criteresP = Array();
	// liste des criteres secondaires
	this.criteresF = Array();

	this.urlbase = "";
	this.action = "";

	// liste constante des association n/nom de critere
	this.critereNames = Array();
		this.critereNames[-2] = "marque";
		this.critereNames[-1] = "modele";
		this.critereNames[0] = "categ";
		this.critereNames[3] = "prix";
		this.critereNames[4] = "kilo";
		this.critereNames[5] = "energie";
		this.critereNames[6] = "mill";
		this.critereNames[8] = "boite";
		this.critereNames[9] = "cv";
		this.critereNames[11] = "seg";
		this.critereNames[13] = "page";
		this.critereNames[14] = "tri";
		this.critereNames[16] = "carros";
		this.critereNames[17] = "modele_RSI";

	this.categories = Array();
		this.categories[1] = "vp";
		this.categories[2] = "vu";
		this.categories[4] = "moto";

	/*
	this.carrosseries = Array();
		this.carrosseries[2] = formaterLibUrl("Berline 3 portes");
		this.carrosseries[3] = formaterLibUrl("Berline 4 portes");
		this.carrosseries[4] = formaterLibUrl("Berline 5 portes");
		this.carrosseries[8] = formaterLibUrl("Break 5 portes");
		this.carrosseries[11] = formaterLibUrl("Cabriolet 2 portes");
	*/

	this.energies = Array();
		this.energies['D'] = "diesel";
		this.energies['E'] = "essence";
		this.energies['G'] = "GPL";
		this.energies['H'] = "hybride";

	this.energies_2 = Array();
		this.energies_2["diesel"] = "D";
		this.energies_2["essence"] = "E";
		this.energies_2["GPL"] = "G";
		this.energies_2["hybride"] = "H";
	
	// booleen indiquant si la detection a eu lieu
	this.detected = false;
	this.configured = false;
}

// accesseurs en lecture/ecriture sur la liste de valeurs
Criteres.prototype.addCritere = function(critereName, critereValeur) {this.critereValues[critereName] = critereValeur;}
Criteres.prototype.removeCritere = function(critereName) {this.critereValues[critereName] = null;}
Criteres.prototype.getCritereValue = function(critereName) {return this.critereValues[critereName];}
Criteres.prototype.setCritereValue = function(critereName, critereValue) {this.critereValues[critereName] = critereValue;}
// accesseurs en lecture sur les attributs d'etat
Criteres.prototype.getDetected = function() {return this.detected;}
Criteres.prototype.getConfigured = function() {return this.configured;}
//accesseurs en lecture sur les attributs de configuration
Criteres.prototype.getUrlBase = function() {return this.urlbase;}
Criteres.prototype.getAction = function() {return this.action;}
//methode de configuration (appelee apres l'instanciation
Criteres.prototype.configure = function(urlbase, action) {this.urlbase = urlbase; this.action = action; this.configured = true;}
Criteres.prototype.getCritereName = function(i) {return this.critereNames[i];}
Criteres.prototype.setCritereP = function(criteresP) {this.criteresP = criteresP.split(',');}
Criteres.prototype.setCritereF = function(criteresF) {this.criteresF = criteresF.split(',');}
Criteres.prototype.estCritereP = function(critereName)
{
	var ret = false;

	for(i = 0;i < this.criteresP.length;++ i)
	{
		if(critereName == this.criteresP[i])
		{
			ret = true;
			break;
		}
	}
	return ret;
}
// un critere est secondaire si'l n'est pas primaire
Criteres.prototype.estCritereF = function(critereName)
{
	return (! this.estCritereP(critereName));

	/*
	var ret = false;

	for(i = 0;i < this.criteresF.length;++ i)
	{
		if(critereName == this.criteresF[i])
		{
			ret = true;
			break;
		}
	}
	return ret;
	*/
}
Criteres.prototype.readMarqueModele = function(marque_modele)
{
	if(marque_modele.indexOf(cMarqueModeleSeparator) == -1)
	{
		this.setCritereValue("marque", marque_modele);
		this.setCritereValue("modele", "");
		this.criteresP[this.criteresP.length] = "marque";
	}
	else
	{
		this.setCritereValue("marque", marque_modele.substr(0, marque_modele.indexOf(cMarqueModeleSeparator)));
		this.setCritereValue("modele", marque_modele.substr(1 + marque_modele.indexOf(cMarqueModeleSeparator)));
		this.criteresP[this.criteresP.length] = "marque";
		this.criteresP[this.criteresP.length] = "modele";
	}
}
// fonction d'interpretation des criteres depuis l'url
Criteres.prototype.detect = function()
{
	this.detectUrl();
	this.detectAncre();
	this.detected = true;
}
//analyse de la partie avant l'ancre pour remplir les parametres
Criteres.prototype.detectUrl = function()
{
	// split the location into a list
	var url = window.location.href.substr('http://'.length);
	url = url.substr(url.indexOf(this.urlbase) + this.urlbase.length);

	var sLocationList = url.substr(0, url.indexOf(this.action) - 1);
	var locationList = sLocationList.split(cAnchor)[0].split(cSeparator);

	for(indexLocation = 0;indexLocation < locationList.length;)
	{
		var locationItem = locationList[indexLocation];
		
		if(locationItem[0] == criterePPrefix)
		{
			// if element is like 'p{n}' where n is an integer
			var n = parseInt(locationItem.substr(1, locationItem.length - 1));
			if(! isNaN(n))
			{
				var value = locationList[indexLocation+1];
				this.criteresP[this.criteresP.length] = this.critereNames[n];
				this.setCritereValue(this.critereNames[n], value);
				indexLocation += 2;
			}
			else
			{
				this.readMarqueModele(locationItem);
				++ indexLocation;
				continue;
			}
		}
		else
		{
			this.readMarqueModele(locationItem);
			++ indexLocation;
			continue;
		}
	}

	// 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[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
Criteres.prototype.detectAncre = function()
{
	// si pas d'ancre, on sort
	if(window.location.href.split(cAnchor).length <= 1)
		return;

	// on splite l'ancre en un tableau
	var locationList = window.location.href.split(cAnchor)[1].split(cSeparator);

	// pour chaque élément du tableau
	for(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) == critereFPrefix)
		{
			// on prend la valeur du n
			var n = parseInt(locationItem.substr(1, locationItem.length - 1));
			if(! isNaN(n))
			{
				// on suppose que la valeur suivante est la valeur à sauvegarder
				var value = 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;
		}
	}
}
Criteres.prototype.existsField = function(myform, myfield)
{
	var bFound = false;
	for(i = 0;i < myform.elements.length;++ i)
		if(myform.elements[i].name == myfield)
		{
			bFound = true;
			break;
		}
	return bFound;
}
Criteres.prototype.getIntervallePrimaireString = function(min, max, unit)
{
	if(min == '')
		return '+de+' + max + '+' + unit;
	else if(max == '')
		return 'plus+de+' + min + '+' + unit;
	else if(min == max)
		return max + '+' + unit;
	else
		return 'de+' + min + '+à+' + max + '+' + unit;
}
Criteres.prototype.getIntervalleSecondaireString = function(min, max)
{
	if(min == '')
		return '-' + max;
	else if(max == '')
		return min + '-';
	else if(min == max)
		return max;
	else
		return min + '-' + max;
}

//fonction d'interpretation des criteres depuis un formulaire
Criteres.prototype.setCriteres = function(myform)
{
	var marque = this.getValue(myform, "marque");
	if(marque != '')
	{
		this.setCritereValue("marque", marque);

		modele = this.getValue(myform, "modele");
		if(modele != '')
		{
			if("mo_" == modele.substr(0,3))
			{
				// modele rsi
				var modele_RSI = modele; 
				// on suppose que "modele est une combo "select-one"
				var 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", "");
		this.setCritereValue("modele", "");
	}

	var categorie = this.getValue(myform, "categ");
	if(categorie.length != 0 && ! isNaN(parseInt(categorie)))
		categorie = this.categories[categorie];
	if(categorie.length != 0)
		this.setCritereValue("categ", categorie);

	this.setCritereValue("carros", this.getValue(myform, "carros"));

	var prixmin = this.getValue(myform, "prixmin");
	var prixmax = this.getValue(myform, "prixmax");
	if(prixmin != '' || prixmax != '')
	{
		// prixmin et prixmax ont la meme priorite
		if(this.estCritereP("prixmin"))
		{
			this.setCritereValue("prix", this.getIntervallePrimaireString (prixmin, prixmax, "€"));
		}
		else
		{
			this.setCritereValue("prix", this.getIntervalleSecondaireString (prixmin, prixmax ));
		}
	}
	else
		this.setCritereValue("prix", "");

	var kilomin = this.getValue(myform, "kilomin");
	var kilomax = this.getValue(myform, "kilomax");
	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", "");

	var energie = this.getValue(myform, "energie");
	if(energie.length == 1)
		energie = this.energies[energie];
	this.setCritereValue("energie", energie);

	this.setCritereValue("mill", this.getValue(myform, "mill"));

	this.setCritereValue("boite", this.getValue(myform, "boite"));

	var puis_fisc_mini = this.getValue(myform, "puis_fisc_mini");
	var puis_fisc_maxi = this.getValue(myform, "puis_fisc_maxi");
	if(puis_fisc_mini.length != 0 || puis_fisc_maxi.length != 0)
	{
		if(this.estCritereP("cv"))
		{
			this.setCritereValue("cv", this.getIntervallePrimaireString(puis_fisc_mini, puis_fisc_maxi, "€"));
		}
		else
		{
			this.setCritereValue("cv", this.getIntervalleSecondaireString(puis_fisc_mini, puis_fisc_maxi));
		}
	}
	else
	{
		var cv = this.getValue(myform, "cv");
		if(cv.length != 0)
		{
			if(this.estCritereP("cv"))
			{
				this.setCritereValue("cv", this.getIntervallePrimaireString(cv, cv, "€"));
			}
			else
			{
				this.setCritereValue("cv", this.getIntervalleSecondaireString(cv, cv));
			}
		}
		else
			this.setCritereValue("cv", "");
	}

	this.setCritereValue("seg", this.getValue(myform, "seg"));

	this.setCritereValue("page", this.getValue(myform, "page"));

	this.setCritereValue("tri", this.getValue(myform, "tri"));
}
Criteres.prototype.fillFormulaireWithCriteres = function(myform)
{
	for(indexCritere = -2;indexCritere < this.critereNames.length; ++ indexCritere)
	{
		if(this.critereValues[this.critereNames[indexCritere]] != null
			&& this.critereValues[this.critereNames[indexCritere]].length != 0)
		{
			this.setValue(myform, this.critereNames[indexCritere], this.critereValues[this.critereNames[indexCritere]], true);
		}
	}
}
Criteres.prototype.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)
Criteres.prototype.setValue = function(myform, item, value, addOptionIfNotExists)
{
	if(arguments.length == 3)
		addOptionIfNotExists = false;

	// check if element exists in form
	var found = false;	
	for(i = 0;i < myform.elements.length;++ i)
	{
		if(myform.elements[i].name == item)
		{
			found = true;
			break;
		}
	}

	// if yes...
	if(found)
	{
		// get the element
		var itemField = myform.elements[item];
		switch(itemField.type)
		{
			case 'select-one':
				// case simple select
				var optionFound = false;
				for(i = 0;i < itemField.options.length;++ i)
				{
					if(itemField.options[i].value == value)
					{
						itemField.selectedIndex = i;
						optionFound = true;
						break;
					}
				}
				if(!optionFound && addOptionIfNotExists)
				{
					// create an option
					var newOption = new Option(value, this.getConvertedValue(item, value));
					itemField.options[itemField.options.length] = newOption;
					// select the just-added item
					itemField.selectedIndex = itemField.options.length - 1;
				}
				break;
			case 'select-multiple':
				// select-multiple => spliter la valeur selon les ',' et selectionner les options correspondantes
				var valueList = value.split(',');
				for(o = 0;o < itemField.options.length;++ o)
				{
					var bThisOptionValueFound = false;

					// get through the list of values to check
					for(j = 0;j < valueList.length;++ j)
					{
						if(itemField.options[o].value == valueList[j])
						{
							itemField.options[o].selected = true;
							bThisOptionValueFound = true;
							break;
						}
					}
					// if the value of the option is not found among the values, unselect it
					if(! bThisOptionValueFound)
						itemField.options[o].selected = false;
				}
				break;
			case 'text':
				itemField.value = value;
				break;
			case 'hidden':
				itemField.value = value;
				break;
			case 'textarea':
				itemField.value = value;
				break;
			default:
				// checkbox ou radio => spliter la valeur selon les ',' et cocher les elements correspondants
				var valueList = value.split(',');
				for(i = 0;i < myform.elements.length;++ i)
				{
					var myCheckboxOrRadio = myform.elements[i];
					if(myCheckboxOrRadio.name == item)
					{
						var bThisCheckboxOrRadioValueFound = false;

						// get through the list of values to check
						for(j = 0;j < valueList.length;++ j)
						{
							if(myCheckboxOrRadio.value == valueList[j])
							{
								myCheckboxOrRadio.checked = true;
								bThisCheckboxOrRadioValueFound = true;
								break;
							}
						}
						// if the value of the cb is not found among the values, uncheck it
						// in case it would have been checked by cache
						if(! bThisCheckboxOrRadioValueFound)
							myCheckboxOrRadio.checked = false;
					}
				}
		}
	}
}
// 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
Criteres.prototype.buildQueryStringFromCriteres = function()
{
	var newQueryString = "";

	if(this.getCritereValue("marque").length != 0)
	{
		newQueryString += "&marque=" + formaterLibUrl(this.getCritereValue("marque"));

		if(this.getCritereValue("modele").length != 0)
			newQueryString += "&modele=" + formaterLibUrl(this.getCritereValue("modele"));
	}

	// parcours des criteres enregistres
	for(indexCritere = 0;indexCritere < this.critereNames.length; ++ indexCritere)
	{
		// si une valeur existe et qu'elle n'est pas vide
		if(this.critereValues[this.critereNames[indexCritere]] != null
				&& this.critereValues[this.critereNames[indexCritere]].length != 0)
			// rajout à la query string
			newQueryString += "&"
				+ ( this.estCritereP(this.critereNames[indexCritere]) ? criterePPrefix : 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/..."
Criteres.prototype.buildUrlFromCriteres = function()
{
	// variable to know if at least one criterium is defined
	var bAtLeastOneCriterium = false;
	// 2 variables are built : one for the part before the anchor...
	var url = this.urlbase;
	// ... one for the part thereafter
	var ancre = "";

	var marque = this.getCritereValue("marque");
	if(marque != null && marque.length != 0)
	{
		// at least one criterium is defined
		bAtLeastOneCriterium = true;

		url += formaterLibUrl(marque);

		var modele = this.getCritereValue("modele");
		if(modele != null && modele.length != 0)
			url += cMarqueModeleSeparator + formaterLibUrl(modele);
		url += cSeparator;
	}

	// parcours des criteres enregistres
	for(indexCritere = 0;indexCritere < this.critereNames.length; ++ indexCritere)
	{
		if(this.critereValues[this.critereNames[indexCritere]] != null
			&& 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 += criterePPrefix + indexCritere + cSeparator + this.critereValues[this.critereNames[indexCritere]] + cSeparator;
			else
				// if secondary criterium => added to the part after the anchor
				ancre += critereFPrefix + indexCritere + cSeparator + this.critereValues[this.critereNames[indexCritere]] + cSeparator;
		}
	}

	// build the full url
	if(bAtLeastOneCriterium)
		url = url + this.action + ".html" + (ancre.length == 0 ? '' : "#" + 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;
}
// les 3 fonctions suivantes retournent les indexes des criteres non nuls : Tous/seulement primaires/seulement secondaires
Criteres.prototype.getAllCriteresIndexesWithValue = function()
{
	var indexesWithValue = Array();

	// parcours des criteres enregistres
	for(indexCritere = 0;indexCritere < this.critereNames.length; ++ indexCritere)
	{
		// si une valeur existe et qu'elle n'est pas vide
		if(this.critereValues[this.critereNames[indexCritere]] != null
				&& this.critereValues[this.critereNames[indexCritere]].length != 0)
			indexesWithValue[indexesWithValue.length] = indexCritere;
	}

	return indexesWithValue;
}
Criteres.prototype.getAllPCriteresIndexesWithValue = function()
{
	var indexesWithValue = Array();

	// parcours des criteres enregistres
	for(indexCritere = 0;indexCritere < this.critereNames.length; ++ indexCritere)
	{
		// si une valeur existe et qu'elle n'est pas vide
		if(this.critereValues[this.critereNames[indexCritere]] != null
				&& this.critereValues[this.critereNames[indexCritere]].length != 0)
			if(this.estCritereP(critereNames[indexCritere]))
				indexesWithValue[indexesWithValue.length] = indexCritere;
	}

	return indexesWithValue;
}
Criteres.prototype.getAllFCriteresIndexesWithValue = function()
{
	var indexesWithValue = Array();

	// parcours des criteres enregistres
	for(indexCritere = 0;indexCritere < this.critereNames.length; ++ indexCritere)
	{
		// si une valeur existe et qu'elle n'est pas vide
		if(this.critereValues[this.critereNames[indexCritere]] != null
				&& this.critereValues[this.critereNames[indexCritere]].length != 0)
			if(this.estCritereF(critereNames[indexCritere]))
				indexesWithValue[indexesWithValue.length] = indexCritere;
	}

	return indexesWithValue;
}
//get the value of an item from a form, whatever the type of input (hidden/text/radio/checkbox/select/textarea)
Criteres.prototype.getValue = function(myform, item)
{
	// retourne la valeur du champ ou '' si n'existe pas
	var retour = '';

	var found = false;

	for(i = 0;i < myform.elements.length;++ i)
	{
		if(myform.elements[i].name == item)
		{
			found = true;
			break;
		}
	}

	if(!found)
	{
		retour = '';
	}
	else
	{
		var itemField = myform.elements[item];
		switch(itemField.type)
		{
			case 'select-one':
				// select simple : attention au 'null'
				retour = itemField.options[itemField.selectedIndex].value;
				if('' + retour == 'null')
					retour = '';
				break;
			case 'select-multiple':
				var first = true;
				for(o = 0;o < itemField.options.length;++ o)
				{
					if(itemField.options[o].selected)
					{
						if(! first)
							retour += ',';
						retour += itemField.options[o].value;
						first = false;
					}
				}
				break;
			case 'text':
				retour = itemField.value;
				break;
			case 'hidden':
				retour = itemField.value;
				break;
			case 'textarea':
				retour = itemField.value;
				break;
			default:
				// checkbox ou radio => boucler et construire une chaine delimitee par des virgules des valeurs selectionnees
				var first = true;
				for(i = 0;i < myform.elements.length;++ i)
				{
					if(myform.elements[i].name == item)
					{
						if(myform.elements[i].checked)
						{
							if(! first)
								retour += ',';
							retour += myform.elements[i].value;
							first = false;
						}
					}
				}
		}
	}

	return retour;
}

/*
// pour debugging
Criteres.prototype.getCriteresValues() = function()
{
	var s = "";
	for(i = 0;i < critereNames.length;++ i)
	{
		s += critereNames[i] + " = " + critereValues[critereNames[i]] + "\n";
	}
	return s;
}
Criteres.prototype.alertCriteresValues = function() {alert(this.getCritereValues());}
*/

/*
// old way

function estprimaire(montype)
{
	var bTrouve = false;
	for(i = 0; i < lstCriteresP.length;++ i)
	{
		if(montype == lstCriteresP[i])
		{
			bTrouve = true;
			break;
		}
	}
	return bTrouve;
}

function estsecondaire(montype)
{
	var bTrouve = false;
	for(i = 0; i < lstCriteresF.length;++ i)
	{
		if(montype == lstCriteresF[i])
		{
			bTrouve = true;
			break;
		}
	}
	return bTrouve;
}

function getLettre(montype)
{
	return (estprimaire(montype) ? criterePPrefix : critereFPrefix);
}

// build a full URL from a form
// myform : name of the form to apply
// baseURL, action => to build the full URL
// mode : 1: main parameters / 2: second parameters

function getURLForForm(myform, baseUrl, action, detectCriteres)
{
	// check the argument
	if(arguments.length == 3)
		detectCriteres = false;
	if(detectCriteres)
	{
		detectCriteres();
	}

	var chaine_primaire = "";
	var chaine_secondaire = "";

	/////////////////////////////////
	// PARAMETRES PRINCIPAUX
	/////////////////////////////////

	/////////////////////////////////
	// MARQUE
	/////////////////////////////////
	var marque = getValue(myform, "marque");
	if(marque)
	{
		if(marque != '')
		{
			chaine_primaire += marque;

			/////////////////////////////////
			// MODELE
			/////////////////////////////////
			modele = getValue(myform, "modele");
			if(modele != '')
			{
				if("mo_" == modele.substr(0,3))
				{
					// modele rsi
					var modele_RSI = modele; 
					// on suppose que "modele est une combo "select-one"
					var 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...
					chaine_primaire += cMarqueModeleSeparator + modele + cSeparator;
					chaine_secondaire += 'f17' + cSeparator + modele_RSI + cSeparator;
				}
				// enlever le 'rn_' potentiel
				// modele = modele.replace('rn_', '');
				chaine_primaire += cMarqueModeleSeparator + modele + cSeparator;
			}
			else
			{
				// pas de modele
				chaine_primaire += cSeparator;
			}
		}
	}

	/////////////////////////////////
	// CATEGORIE
	// Une valeur parmi la liste suivante, écrite en respectant les règles définies plus haut
	// vp (Voiture particulière)
	// vu (Utilitaire léger)
	// motos (Moto & cyclo)
	// Tracteur agricole
	// Moissonneuse batteuse
	/////////////////////////////////
	var categorie = getValue(myform, "type");
	if(categorie != "" && ! isNaN(parseInt(categorie)))
	{
		switch(parseInt(categorie))
		{
		case 1:
			categorie = "vp";
			break;
		case 2:
			categorie = "vu";
			break;
		case 4:
			categorie = "moto";
			break;
		}
	}
	if(categorie.length != 0)
	{
		if(estprimaire("type"))
			chaine_primaire += 'p0' + cSeparator + categorie + cSeparator;
		else
			chaine_secondaire += 'f0' + cSeparator + categorie + cSeparator;
	}

	/////////////////////////////////
	// LIEU
	/////////////////////////////////

	/////////////////////////////////
	// CAROSSERIE
	/////////////////////////////////
	var carrosserie = getValue(myform, "carros");
	if(carrosserie.length != 0)
	{
		if(estprimaire("carros"))
			chaine_primaire += 'p2' + cSeparator + carrosserie + cSeparator;
		else
			chaine_secondaire += 'f2' + cSeparator + carrosserie + cSeparator;
	}

	/////////////////////////////////
	// BUDGET
	/////////////////////////////////
	var prixmin = getValue(myform, "prixmin");
	var prixmax = getValue(myform, "prixmax");
	if(prixmin != '' || prixmax != '')
	{
		// prixmin et prixmax ont la meme priorite
		if(estcritereprimaire("prixmin"))
		{
			chaine_primaire += 'p3' + getIntervallePrimaireString (prixmin, prixmax, "€");
		}
		else
		{
			chaine_secondaire += 'f3' + getIntervalleSecondaireString(prixmin, prixmax);
		}
	}

	/////////////////////////////////
	// KILOMETRAGE
	/////////////////////////////////
	var kilomin = getValue(myform, "kilomin");
	var kilomax = getValue(myform, "kilomax");
	if(kilomin != '' || kilomax != '')
	{
		if(estcritereprimaire("kilo"))
		{
			chaine_primaire += 'p4' + getIntervallePrimaireString (kilomin, kilomax, "km");
		}
		else
		{
			chaine_secondaire += 'f4' + getIntervalleSecondaireString(kilomin, kilomax);
		}
	}

	/////////////////////////////////
	// ENERGIE
	/////////////////////////////////
	var energie = getValue(myform, "energie");
	if(energie.length != 0)
	{
		if(energie.length == 1)
		{
			switch(energie.toUpperCase()[0])
			{
			case 'D':
				energie = "diesel";
				break;
			case 'E':
				energie = "essence";
				break;
			case 'G':
				energie = "GPL";
				break;
			case 'H':
				energie = "hybride";
				break;
			}
		}
		if(estprimaire("energie"))
			chaine_primaire += 'p5' + cSeparator + energie + cSeparator;
		else
			chaine_secondaire += 'f5' + cSeparator + energie + cSeparator;
	}

	/////////////////////////////////
	// TRANSMISSION
	/////////////////////////////////
	var boite = getValue(myform, "boite");
	if(boite.length != 0)
	{
		if(estprimaire("boite"))
			chaine_primaire += 'p8' + cSeparator + boite + cSeparator;
		else
			chaine_secondaire += 'f8' + cSeparator + boite + cSeparator;
	}

	/////////////////////////////////
	// PUISSANCE FISCALE
	/////////////////////////////////
	var puis_fisc_min = getValue(myform, "puis_fisc_min");
	var puis_fisc_max = getValue(myform, "puis_fisc_max");
	if(puis_fisc_min != '' || puis_fisc_max != '')
	{
		if(estprimaire("puis_fisc"))
		{
			chaine_primaire += 'p9' + getIntervallePrimaireString(puis_fisc_min, puis_fisc_max, "€");
		}
		else
		{
			chaine_secondaire += 'p9' + getIntervalleSecondaireString(puis_fisc_min, puis_fisc_max);
		}
	}

	/////////////////////////////////
	// PAGE
	/////////////////////////////////
	var page = getValue(myform, "page");
	if(page != '')
	{
		if(estprimaire("page"))
			chaine_primaire += 'p13' + cSeparator + page + cSeparator;
		else
			chaine_secondaire += 'f13' + cSeparator + page + cSeparator;
	}

	/////////////////////////////////
	// TRI
	/////////////////////////////////
	var tri = getValue(myform, "tri");
	if(tri != '')
	{
		if(estprimaire("tri"))
			chaine_primaire += 'p14' + cSeparator + tri + cSeparator;
		else
			chaine_secondaire += 'f14' + cSeparator + tri + cSeparator;
	}

	var url = baseUrl;
	if(url[url.length - 1] != cSeparator)
		url += cSeparator;
	url += chaine_primaire + action + ".html" + (chaine_secondaire.length == 0 ? "" : "#" + chaine_secondaire);

	return url; 
}

function detectCriteres ()
{
	// split the location into a list
	var url = window.location.href.substr('http://'.length);
	var locationList = url.split(cAnchor)[0].split(cSeparator);

	for(indexLocation = 0;indexLocation < locationList.length - 1;)
	{
		var locationItem = locationList[indexLocation];

		if(locationItem[0] == criterePPrefix)
		{
			// if element is like 'p{n}' where n is an integer
			var n = parseInt(locationItem.substr(1, locationItem.length - 1));
			if(isNaN(n))
			{
				++ indexLocation;
				continue;
			}
			else
			{
				var value = locationList[indexLocation+1];

				if(n == 0)
					lstCriteresP[lstCriteresP.length] = "categ";

				if(n == 2)
					lstCriteresP[lstCriteresP.length] = "carros";

				if(n == 5)
					lstCriteresP[lstCriteresP.length] = "energie";

				indexLocation += 2;
			}
		}
		else
		{
			++ indexLocation;
			continue;
		}
	}
}

// change the value of a param (ex : fxxx) after the anchor
function setValueAfterAnchor(url, name, value)
{
	var urlmodified = '';

	// if there is an anchor
	if(url.indexOf(cAnchor) != -1)
	{
		// split the anchor into a list ([blabla,] param1, value1, param2, value2, ...)
		var anchor = url.split(cAnchor)[1];
		var listParamsValues = (anchor[anchor.length - 1] != cSeparator ?
									anchor
									: anchor.substr(0, anchor.length - 1))
								.split(cSeparator);

		var paramFound = false;
		for(i = 0;i < listParamsValues.length;++ i)
		{
			// search for the param we want to change the value of
			if(listParamsValues[i] == name)
			{
				// we assume that the value follows the name
				listParamsValues[i + 1] = value;
				paramFound = true;
				break;
			}
		}
		if(paramFound)
		{
			// remake the anchor based on the modified list
			newAnchor = listParamsValues.join(cSeparator);
			urlmodified = url.split(cAnchor)[0] + cAnchor + newAnchor;
		}
		else
		{
			// not obvious to set the parameter at the right place => put it at the end
			newAnchor = listParamsValues.join(cSeparator) + cSeparator + name + cSeparator + value;
			urlmodified = url.split(cAnchor)[0] + cAnchor + newAnchor;
		}
	}
	else
	{
		// no anchor => the value does not exist => add it directly
		urlmodified = url + cAnchor + name + cSeparator + value + cSeparator;
	}

	return urlmodified;
}

function fillFormWithAnchor (myform)
{
	var urlAnalyzer = window.location.href.split(cAnchor);
	// no anchor ==> nothing to do
	if(urlAnalyzer.length == 1)
		return;

	// split the anchor into a list
	var anchorList = urlAnalyzer[1].split(cSeparator);

	for(indexAnchor = 0;indexAnchor < anchorList.length - 1;)
	{
		var anchorItem = anchorList[indexAnchor];

		if(anchorItem[0] == critereFPrefix)
		{
			// if element is like 'f{n}' where n is an integer
			var n = parseInt(anchorItem.substr(1, anchorItem.length - 1));
			if(isNaN(n))
			{
				++ indexAnchor;
				continue;
			}
			else
			{
				var value = anchorList[indexAnchor+1];

				/////////////////////////////////
				// TRANSMISSION
				/////////////////////////////////
				if(n == 0)
					setValue(myform, "boite", value);

				/////////////////////////////////
				// PRIX
				/////////////////////////////////
				if(n == 1)
				{
					if(value.length > 0)
					{
						if(value[0] == '-')
						{
							// cas -prixmax
							setValue(myform, "prixmin", "");
							setValue(myform, "prixmax", value.substr(1, value.length - 1));
						}
						else if(value[value.length - 1] == '-')
						{
							// cas prixmax-
							setValue(myform, "prixmin", value.substr(0, value.length - 1));
							setValue(myform, "prixmax", "");
						}
						else
						{
							// cas prixmax(=prixmin)
							dashPos = value.indexOf('-');
							if(dashPos == -1)
							{
								setValue(myform, "prixmin", value);
								setValue(myform, "prixmax", value);
							}
							else
							{
								// cas prixmin-prixmax
								setValue(myform, "prixmin", value.substr(0, dashPos));
								setValue(myform, "prixmax", value.substr(dashPos + 1, value.length - dashPos));
							}
						}
					}
				}

				/////////////////////////////////
				// PUISSANCE FISCALE
				/////////////////////////////////
				if(n == 3)
				{
					if(value.length > 0)
					{
						if(value[0] == '-')
						{
							// cas -puis_fisc_mini
							setValue(myform, "puis_fisc_mini", value.substr(1, value.length - 1));
							setValue(myform, "puis_fisc_maxi", "");
						}
						else if(value[value.length - 1] == '-')
						{
							// cas puis_fisc_maxi-
							setValue(myform, "puis_fisc_mini", "");
							setValue(myform, "puis_fisc_maxi", value.substr(0, value.length - 1));
						}
						else
						{
							// cas puis_fisc_maxi(=puis_fisc_mini)
							dashPos = value.indexOf('-');
							if(dashPos == -1)
							{
								setValue(myform, "puis_fisc_mini", value);
								setValue(myform, "puis_fisc_maxi", value);
							}
							else
							{
								// cas puis_fisc_mini-puis_fisc_maxi
								setValue(myform, "puis_fisc_mini", value.substr(0, dashPos - 1));
								setValue(myform, "puis_fisc_maxi", value.substr(dashPos + 1, value.length - dashPos));
							}
						}
					}
				}

				/////////////////////////////////
				// PAGE
				/////////////////////////////////
				if(n == 13)
					setValue(myform, "page", value);

				/////////////////////////////////
				// TRI
				/////////////////////////////////
				if(n == 14)
					setValue(myform, "tri", value);

				indexAnchor += 2;
			}
		}
		else
		{
			++ indexAnchor;
			continue;
		}
	}
}

function fillFormWithLocation (myform)
{
	// split the location into a list
	var url = window.location.href.substr('http://'.length);
	var locationList = url.split(cAnchor)[0].split(cSeparator);

	for(indexLocation = 0;indexLocation < locationList.length - 1;)
	{
		var locationItem = locationList[indexLocation];

		if(locationItem[0] == criterePPrefix)
		{
			// if element is like 'p{n}' where n is an integer
			var n = parseInt(locationItem.substr(1, locationItem.length - 1));
			if(isNaN(n))
			{
				++ indexLocation;
				continue;
			}
			else
			{
				var value = locationList[indexLocation+1];

				/////////////////////////////////
				// CATEGORIE
				/////////////////////////////////
				if(n == 0)
					setValue(myform, "type", value);

				/////////////////////////////////
				// CAROSSERIE
				/////////////////////////////////
				if(n == 2)
					setValue(myform, "carros", value);

				/////////////////////////////////
				// ENERGIE
				/////////////////////////////////
				if(n == 5)
					setValue(myform, "energie", value);

				indexLocation += 2;
			}
		}
		else
		{
			++ indexLocation;
			continue;
		}
	}
}

// set the value of an item in a form, whatever the type of input (hidden/text/radio/checkbox/select/textarea)
function setValue(myform, item, value)
{
	var found = false;

	for(i = 0;i < myform.elements.length;++ i)
	{
		if(myform.elements[i].name == item)
		{
			found = true;
			break;
		}
	}

	if(found)
	{
		var itemField = myform.elements[item];
		switch(itemField.type)
		{
			case 'select-one':
				for(i = 0;i < itemField.options.length;++ i)
				{
					if(itemField.options[i].value == value)
					{
						itemField.selectedIndex = i;
						break;
					}
				}
				break;
			case 'select-multiple':
				// select-multiple => spliter la valeur selon les ',' et selectionner les options correspondantes
				var valueList = value.split(',');
				for(o = 0;o < itemField.options.length;++ o)
				{
					var bThisOptionValueFound = false;

					// get through the list of values to check
					for(j = 0;j < valueList.length;++ j)
					{
						if(itemField.options[o].value == valueList[j])
						{
							itemField.options[o].selected = true;
							bThisOptionValueFound = true;
							break;
						}
					}
					// if the value of the option is not found among the values, unselect it
					if(! bThisOptionValueFound)
						itemField.options[o].selected = false;
				}
				break;
			case 'text':
				itemField.value = value;
				break;
			case 'hidden':
				itemField.value = value;
				break;
			case 'textarea':
				itemField.value = value;
				break;
			default:
				// checkbox ou radio => spliter la valeur selon les ',' et cocher les elements correspondants
				var valueList = value.split(',');
				for(i = 0;i < myform.elements.length;++ i)
				{
					var myCheckboxOrRadio = myform.elements[i];
					if(myCheckboxOrRadio.name == item)
					{
						var bThisCheckboxOrRadioValueFound = false;

						// get through the list of values to check
						for(j = 0;j < valueList.length;++ j)
						{
							if(myCheckboxOrRadio.value == valueList[j])
							{
								myCheckboxOrRadio.checked = true;
								bThisCheckboxOrRadioValueFound = true;
								break;
							}
						}
						// if the value of the cb is not found among the values, uncheck it
						// in case it would have been checked by cache
						if(! bThisCheckboxOrRadioValueFound)
							myCheckboxOrRadio.checked = false;
					}
				}
		}
	}
}

// make a common query string (param1=value1&param2=value2) based on the current url
// domaine : common domaine (ex : /neuf/fiche_technique/)
// action : action in the domaine (ex : fiches / annonces)
// formatted data : any data represented between domaine and action
// thus, we scan the url : http://server/domaine/formatted_data/p0/v0/p1/v1/.../pn/vn/action.html#[googleanalytics/]f0/w0/f1/w1/.../fn/wn
// and return "[depending on formatted_data]&p0=v0&p1=v1...&pn=vn&f0=w0&f1=w1...&fn=wn"
// if formatted_data="marque[_modele]" (marque with optional underscore-delimitated modele)
// we return this : "&marque=marquev&modele=modelev&p0=v0&p1=v1...&pn=vn&f0=w0&f1=w1...&fn=wn"

function getCompleteUrlForContainer (domaine, action, formatted_data)
{
	// returned value
	var newQueryString = "";

	// remove the http://
	var url = window.location.href.substr('http://'.length);

	// split the preanchor and the anchor
	var urlAnalyzer = url.split(cAnchor);

	var preAnchor = urlAnalyzer[0];

	// removes the action
	if(preAnchor.indexOf(action) != -1)
		preAnchor = preAnchor.substring(0, preAnchor.indexOf(action));
	// removes the domaine (and server by the same way)
	if(preAnchor.indexOf(domaine) != -1)
		preAnchor = preAnchor.substring(preAnchor.indexOf(domaine) + domaine.length);

	// split the rest
	var locationList = preAnchor.split(cSeparator);

	var begin = 0;
	if(formatted_data == "marque[_modele]")
	{
		var marque_modele = locationList[0];
		begin = 1;
		var underscorePos = marque_modele.indexOf('_');
		if(underscorePos != -1)
		{
			newQueryString += "&marque=" + marque_modele.substr(0, underscorePos);
			newQueryString += "&modele=" + marque_modele.substr(underscorePos + 1, marque_modele.length - underscorePos); // "rn_"
		}
		else
		{
			newQueryString += "&marque=" + marque_modele;
		}
	}
	// else if(formatted_data == toto)
	// this function should be enriched here 

	// going through the url...
	// no systematic increment, made in the loop
	for(indexLocation = begin;indexLocation < locationList.length - 1;)
	{
		var locationItem = locationList[indexLocation];

		if(locationItem[0] == criterePPrefix)
		{
			// if element is like 'p{n}' where n is an integer
			var n = parseInt(locationItem.substr(1, locationItem.length - 1));
			if(isNaN(n))
			{
				++ indexLocation;
				continue;
			}
			else
			{
				var value = locationList[indexLocation+1];
				newQueryString += "&p" + n + "=" + value;
				indexLocation += 2; // 2 because we have just taken the following
			}
		}
		else
		{
			++ indexLocation;
			continue;
		}
	}

	// page
	var sAfterAction = urlAnalyzer[0].substr(urlAnalyzer[0].indexOf(action) + action.length);
	if(sAfterAction[0] == '-')
	{
		// => a page in the URL
		newQueryString += "&f13=" + sAfterAction.substr(1, sAfterAction.indexOf('.') - 1);
	}

	// is there an anchor ?
	if(urlAnalyzer.length > 1)
	{
		// split the anchor into a list
		var anchorList = urlAnalyzer[1].split(cSeparator);
		// going through the anchor...
		// no systematic increment, made in the loop
		for(indexAnchor = 0;indexAnchor < anchorList.length - 1;)
		{
			var anchorItem = anchorList[indexAnchor];
	
			if(anchorItem[0] == critereFPrefix)
			{
				// if element is like 'f{n}' where n is an integer
				var n = parseInt(anchorItem.substr(1, anchorItem.length - 1));
				if(isNaN(n))
				{
					++ indexAnchor;
					continue;
				}
				else
				{
					var value = anchorList[indexAnchor+1];
					newQueryString += "&f" + n + "=" + value;
					indexAnchor += 2; // 2 because we have just taken the following
				}
			}
			else
			{
				++ indexAnchor;
				continue;
			}
		}
	}

	return newQueryString;
}
*/
