
/*
Permet de compléter la clause where avec le prix ou les kilomètres
*/
function CreateBetween(tw, champ, min, max) {
	if ( (min > 0) && (max > 0) ) {
		tw = tw + champ + ' BETWEEN ' + min + ' AND ' + max + ' AND ';
	} else {
		if (min > 0) {
			tw = tw + champ + ' >= ' + min + ' AND ';
		} else {
			if (max > 0) {
				tw = tw + champ + ' <= ' + max + ' AND ';
			}
		}
	}
	return tw;
}

/*
Complete la clause Where
*/
function CreateBorne(tw) {
	var pmin = document.getElementById('prixmin').value;
	var pmax = document.getElementById('prixmax').value;
	var kmin = document.getElementById('kmmin').value;
	var kmax = document.getElementById('kmmax').value;

	tw = CreateBetween(tw, "PvTTC", pmin, pmax);
	tw = CreateBetween(tw, "Km", kmin, kmax);
	return tw;
}

/*
Creation de la clause Where

Si le paramètre element est un des select, la construction de la clause where s'arrète.
Si le paramètre element est "null", toutes les lignes de critères sont balayées.
Dans tous les cas, si l'option choisie du select de gauche n'est pas la première,
Si l'option choisie du select de droite n'est pas non plus la première,
la ligne "champ LIKE 'choix'" est construite.
*/
function CreateWhere(element) {
	var j;
	var propre;
	var postwhere = document.getElementById('postwhere');
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');
	var tw = clausewhere;

	j = 0;
	tw = CreateBorne(tw);
	while ( (tag[j] != element) && (tag[j] != null) ) {
		if ( (tag[j].selectedIndex != 0) && (tag[j+1].selectedIndex != 0) ) {
			propre = tag[j+1].value;
			propre = propre.substring( 0, propre.indexOf(' (') );
			tw = tw + criteres[tag[j].selectedIndex].champ + "=" + '\'' + propre + '\'' + " AND ";
		}
		j += 2;
	}
	tw = tw.substring(0, tw.length - 5);
	postwhere.value = tw;
	return tw;
}

/*
Remplissage du DIV Numpoli avec les Numpoli sélectionnés.

Création de la requête Where, requête Ajax des Numpoli y correspondant.
*/
function FillRequest() {
	var champ;
	var req;
	var tw;
	var x;
	var c;
	var texte;
	var liens = " - ";
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');
	var temp = document.getElementById('numpoli');

	tw = CreateWhere(null);
	if (tw.length > 0) {
		tw = "&where=" + encodeURIComponent(tw);
	}
	champ = "champ=Numpoli";
	req = new createXHR();
	req.onreadystatechange=function() {
		if ( req.readyState == 4 ) {
			if ( req.status == 200 ) {
				x = 0;
				compteur = 0 ;
				while ( x < req.responseText.length ) {
					c = req.responseText.indexOf("\n", x);
					texte = req.responseText.substring(x, c);
					liens = liens + '<a href="/vo/fiche.php?ref=' + texte + '">' + texte + '</a> - ';
					x = c + 1;
					compteur += 1;
				}
				if (compteur == 0) {
					texte = "<br>Aucun véhicule sélectionné.<br>";
				} else {
					texte = "" + compteur + " véhicules correspondants."  + "<br><br>";
				}
				if (affichenumpoli) {
					temp.innerHTML = texte + liens;
				} else {
					temp.innerHTML = texte;
				}
			}
		}
	};
	req.open("POST", "/vo/bateaux/getrequest.php", true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(champ + tw);
}

/*
Remplit le sélect de droite en fonction de celui de gauche

Le paramètre element est le select de gauche.
On vide d'abord le select de droite et on récupère l'indice sélectionné dans celui de gauche.
On crèe la clause where avec les lignes prédentes.
On récupère le nom du champ réel dans le tableau criteres.
La requête Ajax récupè les champs correspondants dans la BD.
Les champs options du select de droite sont construits.
*/
function FillSelect(tag, j) {
	var champ;
	var seltofill;
	var sel;
	var x;
	var opt;
	var texte;
	var tw;
	var i;

	seltofill = tag[j+1];
	seltofill.innerHTML = "";
	i = tag[j].selectedIndex;
	if (i != 0) {
		seltofill.disabled = false;
		tw = CreateWhere(tag[j]);
		if (tw.length > 0) {
			tw = "&where=" + encodeURIComponent(tw);
		}
		champ = "champ=" + criteres[i].champ;
		opt = document.createElement('option');
		opt.setAttribute('value', criteres[i].invite);
		opt.text = criteres[i].invite;
		try {
			seltofill.add(opt, null);
		} catch(ie) {
			seltofill.add(opt);
		}
		sel = new createXHR();
		sel.onreadystatechange=function() {
			if ( sel.readyState == 4 ) {
				if ( sel.status == 200 ) {
					x = 0;
					while ( x < sel.responseText.length ) {
						c = sel.responseText.indexOf("\n", x);
						texte = sel.responseText.substring(x, c);
						opt = document.createElement('option');
						opt.setAttribute('value', texte);
						opt.text = texte;
						try {
							seltofill.add(opt, null);
						} catch(ie) {
							seltofill.add(opt);
						}
						x = c + 1;
					}
				}
			}
		};
		sel.open("POST", "/vo/bateaux/getselect.php", true);
		sel.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		sel.send(champ + tw);
	} else {
		seltofill.disabled = true;
	}
}

/*
Réinitialise les lignes de select situés sous un changement de critère

element est recherché dans la liste des selects.
Lorsqu'il est trouvé, les lignes suivantes sont réinitialisées avec les nouveaux critères.
*/
function UpdateSelect(element) {
	var j = 0;
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');

	while ( (element != tag[j]) && (j < tag.length) ) {
		j += 2;
	}
	while (j < tag.length) {
		FillSelect(tag, j);
		j += 2;
	}
	FillRequest();
	DisableSelect();
}

/*
Réinitialise les critères situés sous un changement de choix (select de droite)

element est le select de gauche recherché.
Trouvé, les lignes suivantes sont adaptées.
*/
function UpdateChoix(element) {
	var j = 1;
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');

	while ( (element != tag[j]) && (j < tag.length) ) {
		j += 2;
	}
	j += 1;
	while (j < tag.length) {
		FillSelect(tag, j);
		j += 2;
	}
	FillRequest();
	DisableSelect();
}

/*
Remplis le tableau des choix des selects

Le tableau choisis est remplit avec "faux".
Pour chaque ligne de select, la valeur "vrai" est stockée dans l'index sélectionné.
*/
function FillChoisis() {
	var i;
	var j;
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');

	i = 0;
	j = 0;
	choisis.length = criteres.length;
	for (s=0; s < choisis.length; s++) {
		choisis[s] = false;
	}
	while (i < lignes) {
		choisis[tag[j].selectedIndex] = true;
		j += 2;
		i += 1;
	}
}

/*
Désactive les entrées déjà utilisées des selects de gauche

FillChoisis positionne les entrées utilisées.
Pour chaque option de chaque select de gauche, si l'entree est déjà utilisée, elle est désactivée.
Sinon, elle est activée
*/
function DisableSelect() {
	var i;
	var j;
	var o;
	var opt;
	var on;
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');

	FillChoisis();
	i = 0;
	j = 0;
	while (i < lignes) {
		opt = tag[j].getElementsByTagName('option');
		for (o=1; o < opt.length; o++) {
			on = false;
			if ( choisis[o] == true ) {
				if ( o != tag[j].selectedIndex ) {
					on = true;
				}
			}	
			opt[o].disabled = on;
		}
		j += 2;
		i += 1;
	}		
}

/*
Suppréssion d'une ligne de sélection

element est le bouton "-" d'une ligne.
les 2 selects de la ligne, le bouton "+" et le saut de ligne sont détruits.
Le nouveaux choix est alors recalculé.
*/
function DelCritere(element) {
	var valeur;
	var opt;
	var td;
	var liste = document.getElementById('selecteurs');
	var tag = liste.getElementsByTagName('select');

	if (lignes > 1)	{
		lignes -= 1;
		td = element.parentNode;
		liste.removeChild(td.parentNode);
	}
	UpdateChoix(tag[0]);
}

/*
Ajout d'une lignes de sélection

Si tous les critères ne sont pas exploités, une nouvelle ligne de deux boutons, 
deux select et un <p> sont généré dynamiquement.
Le select de gauche est remplit avec le tableau criteres.
Cela déclenche son onchange qui force le remplissage du select de droite.
*/
function AddCritere() {
	var compo;
	var opt;
	var entree;
	var i;
	var tag;
	var tr;
	var td;
	var liste = document.getElementById('selecteurs');
	var prix = document.getElementById('insertion');

	if (lignes < criteres.length - 1) {
		lignes += 1;

		compo = document.createElement('tr');
		tr = liste.insertBefore(compo, prix);
		compo = document.createElement('td');
		td = tr.appendChild(compo);
		try {
			compo = document.createElement('<input type="button" class="boutonmoins" onclick="DelCritere(this);" value="  -  ">');
		} catch(ff) {
			compo = document.createElement('input');
			compo.setAttribute('type', 'button');
			compo.setAttribute('class', 'boutonmoins');
			compo.setAttribute('onclick', 'DelCritere(this);');
			compo.setAttribute('value', '  -  ');
		}
		td.appendChild(compo);
		compo = document.createElement('td');
		td = tr.appendChild(compo);
		try {
			compo = document.createElement('<select class="selectgauche" onchange="UpdateSelect(this);">');
		} catch(ff) {
			compo = document.createElement('select');
			compo.setAttribute('class', 'selectgauche');
			compo.setAttribute('onchange', 'UpdateSelect(this);');
		}
		entree = td.appendChild(compo);
		for (i = 0; i < criteres.length; i++) {
			opt = document.createElement('option');
			opt.setAttribute('value', criteres[i].libelle);
			opt.text = criteres[i].libelle;
			try {
				entree.add(opt, null);
			} catch(ie) {
				entree.add(opt);
			}
		}
		compo = document.createElement('td');
		td = tr.appendChild(compo);
		try {
			compo = document.createElement('<select class="selectdroit" onchange="UpdateChoix(this);">');
		} catch(ff) {
			compo = document.createElement('select');
			compo.setAttribute('class', 'selectdroit');
			compo.setAttribute('onchange', 'UpdateChoix(this);');
		}
		td.appendChild(compo);
		compo.disabled = true;
		compo = document.createElement('td');
		td = tr.appendChild(compo);
		try {
			compo = document.createElement('<input type="button" class="boutonplus" onclick="AddCritere(this);" value="  +  " >');
		} catch(ff) {
			compo = document.createElement('input');
			compo.setAttribute('type', 'button');
			compo.setAttribute('class', 'boutonplus');
			compo.setAttribute('onclick', 'AddCritere();');
			compo.setAttribute('value', '  +  ');
		}
		td.appendChild(compo);
	}
	DisableSelect();
}

/*
*/
function ForceNumber(element) {
	var valeur = new Number(element.value);
	if (valeur > 0) {
		element.value = valeur;
	} else {
		element.value = "";
	}
	UpdateChoix(null);
}

/*
Sert à structurer les variables dans le tableau criteres
*/
function Critere(champ, libelle, invite) {
	this.champ = champ;
	this.libelle = libelle;
	this.invite = invite;
}

/*
Initialisation des variables

Est lancé sur le onload du body HTML.
Il crée et initialise les variables globales du programme.
Il génère ensuite la première ligne de select.
Attention, toutes les lignes du tableau criteres sont terminées par une virgule
Sauf la dernière.
La première est constante.
*/
function Initial()	{
	lignes = 0;
	compteur = 0;
	affichenumpoli = false;
	criteres = new Array(
		new Critere("", "Choisissez un critère...", ""),
		new Critere("Categorie", "Silhouette", "Indifférente"), 
		new Critere("GenreTxt", "Genre", "Indifférent"),
		new Critere("Marque", "Marque", "Indifférente"),
		new Critere("Famille", "Modèle", "Indifférent"),
		new Critere("Version", "Version", "Indifférente"),		
		new Critere("Energie", "Energie", "Indifférente"),
		new Critere("NbPortes", "Nombre de Portes", "Indifférent"),
		new Critere("NbPlaces", "Nombre de Places", "Indifférent"),		
		new Critere("Couleur", "Couleur", "Indifférente"),
		new Critere("Millesime", "Année", "Indifférente"),
		new Critere("Puissance", "Puissance Fiscale (en CV)", "Indifférente"), 
		new Critere("PuissanceReelle", "Puissance Réelle (en ch DIN)", "Indifférente"),
		new Critere("Ville", "Point de Vente", "Indifférent")
	);
	clausewhere = " WHERE Photos.Type='VG' AND Photos.Rang='01' AND Stock.Garantie REGEXP 'mois' AND Stock.Numpoli=Photos.Numpoli AND ";
	choisis = new Array();
	AddCritere();
	CreateWhere(null);
}


