// Renvoie la liste de tous les champs du formulaire avec leur valeur
function getAjaxFormParams(thisForm) {
	var input;
	var params = '';
	if (thisForm) {
		for (var i = 0; i < thisForm.getElementsByTagName('input').length; i ++) {
			input = thisForm.getElementsByTagName('input')[i];
			if (input.type == 'text' 
					|| input.type == 'hidden'
					|| input.type == 'file'
					|| input.type == 'password'
					|| input.type == 'checkbox' && input.checked
					|| input.type == 'radio' && input.checked) {
				if (input.name != '') {
					if (params != '') {
						params += '&';
					}
					params += input.name + '=' + escapeChar(input.value);
				}
			}
		}
		for (var i = 0; i < thisForm.getElementsByTagName('select').length; i ++) {
			input = thisForm.getElementsByTagName('select')[i];
			if (input.name != '') {
				if (params != '') {
					params += '&';
				}
				if (input.selectedIndex >= 0) {
					params += input.name + '=' + escapeChar(input.options[input.selectedIndex].value);
				} else {
					params += input.name + '=0';
				}
			}
		}
		for (var i = 0; i < thisForm.getElementsByTagName('textarea').length; i ++) {
			input = thisForm.getElementsByTagName('textarea')[i];
			if (input.name != '') {
				if (params != '') {
					params += '&';
				}
//				params += input.name + '=' + input.options[input.selectedIndex].value;
				params += input.name + '=' + escapeChar(input.value);
			}
		}
	}
	
	return params;
}
function escapeChar(text) {
	var textTmp = text;
	textTmp = textTmp.replace(/&/g, '%26');
	textTmp = textTmp.replace(/\+/g, '%2B');
	textTmp = textTmp.replace(/=/g, '%3D');
	return textTmp;
}
//Renvoi un message d'attente avec sauts de ligne
function getAjaxWait() {
	var html = '';
	html += '<div id="gifLoading" width="100%" align="center">';
	html += '<br/><br/>';
	html += '<img src="img/icon/run.gif" width="20" alt="Traitement en cours. Veuillez patienter..." title="Traitement en cours. Veuillez patienter...">';
	html += '<br/><br/><br/>';
	html += '</div>';
	return html;
}
//Renvoi un message d'attente sans sauts de ligne
function getAjaxWaitShort() {
	var html = '';
	html += '<div width="100%" align="center">';
	html += '<img src="img/icon/run.gif" width="20" alt="Traitement en cours. Veuillez patienter..." title="Traitement en cours. Veuillez patienter...">';
	html += '</div>';
	return html;
}

// RAZ d'une liste
function razListe(formName, idListe, actionListe, returnFunction) {
	var thisForm = '';
	eval('thisForm = document.' + formName);

	// Récupération des paramètres du formulaire
	var params = getAjaxFormParams(thisForm);
	
	// Affichage de l'attente
	$(idListe).innerHTML = getAjaxWait();

	// Appel de la fonction de liste en Ajax
	AJAXRequest('main.php?action=' + actionListe + '&saction=raz', params, returnFunction);
}

// Tri d'une liste
function sortListe(formName, idListe, sortField, actionListe, returnFunction) {
	var thisForm = '';
	eval('thisForm = document.' + formName);

	// Récupération des paramètres du formulaire
	var params = getAjaxFormParams(thisForm);
	//alert(params);

	// Affichage de l'attente
	$(idListe).innerHTML = getAjaxWait();

	// Appel de la fonction de liste en Ajax
	AJAXRequest('main.php?action=' + actionListe + '&field=' + sortField, params, returnFunction);
}

// Pagination d'une liste
function pageListe(formName, idListe, pageNumber, actionListe, returnFunction) {
	var thisForm = '';
	eval('thisForm = document.' + formName);
	
	// Récupération des paramètres du formulaire
	var params = getAjaxFormParams(thisForm);

	// Affichage de l'attente
	$(idListe).innerHTML = getAjaxWait();

	// Appel de la fonction de liste en Ajax
	AJAXRequest('main.php?action=' + actionListe + '&page=' + pageNumber, params, returnFunction);
}

/*************************************************************
**************************************************************
* Ajout des td du html dans le row
**************************************************************
**************************************************************/
function addCellsToRow(row, htmlCells) {
	var cell;
	var htmlCellsTmp = htmlCells;
	
	var tmp = 0;
	var cellContentTDEnd = 0;
	
	while (htmlCellsTmp.indexOf('<td') >= 0 && htmlCellsTmp.indexOf('</td>') >= 0) {
		// Code html de la cellule
		nextCell = htmlCellsTmp.substring(htmlCellsTmp.indexOf('<td'), htmlCellsTmp.indexOf('>') + 1);
		
		// Classe de la cellule
		if (nextCell.indexOf('class="') >= 0) {
			cellClass = nextCell.substring(nextCell.indexOf('class="') + 7, nextCell.indexOf('"', nextCell.indexOf('class="')+7));
		} else {
			cellClass = '';
		}
		// Alignement de la cellule
		if (nextCell.indexOf('align="') >= 0) {
			cellAlign = nextCell.substring(nextCell.indexOf('align="') + 7, nextCell.indexOf('"', nextCell.indexOf('align="')+7));
		} else {
			cellAlign = '';
		}
		// Style de la cellule
		if (nextCell.indexOf('style="') >= 0) {
			cellStyle = nextCell.substring(nextCell.indexOf('style="') + 7, nextCell.indexOf('"', nextCell.indexOf('style="')+7));
		} else {
			cellStyle = '';
		}
		// Nowrap de la cellule
		if (nextCell.indexOf('nowrap') >= 0) {
			cellWrap = true;
		} else {
			cellWrap = false;
		}
		
		// Contenu de la cellule (on récupère le contenu html en tenant compte de l'existance d'autres td dans la cellule)
		cellContentTD = htmlCellsTmp.indexOf('<td');
		cellContentTDEnd = htmlCellsTmp.indexOf('</td', cellContentTD+1);
		while (htmlCellsTmp.indexOf('<td', cellContentTD+1) > 0 
				&& htmlCellsTmp.indexOf('<td', cellContentTD+1) < cellContentTDEnd) {
			cellContentTD = htmlCellsTmp.indexOf('<td', cellContentTD+1);
			cellContentTDEnd = htmlCellsTmp.indexOf('</td', cellContentTDEnd+1);
		}
		cellContent = htmlCellsTmp.substring(htmlCellsTmp.indexOf('>') + 1, cellContentTDEnd);

		// Ajout de la cellule
		cell = row.insertCell(-1);
		if (cellClass != '') {
			cell.className = cellClass;
		}
		if (cellAlign != '') {
			cell.align = cellAlign;
		}
		
		if (cellStyle != '') {
			cell.style.cssText = cellStyle;
		}
		cell.noWrap = cellWrap;
		cell.innerHTML = cellContent;

		// Cellules suivantes
		htmlCellsTmp = htmlCellsTmp.substring(cellContentTDEnd + 5);
	}
}

/**
 * Crée et envoie la requête HTTP au serveur
 * Paramètres:
 * 	- (String) uri : fichier PHP visé
 *		- (String) post_data : la chaîne de requête en POST
 *		- (Ref) callbackFunction : référence de la function qui va réaliser les traitements spécifiques
 *											avant, pendant et après réception des données
 *		- (String) elmt : nom de l'élément visé par le traitement de la function callbackFunction
 */
function AJAXRequest(uri, post_data, callbackFunction, loadedElement)
{
	var xhr = false; //Futur objet XMLHttpRequest

	// Instanciation d'un objet XMLHttpRequest
	if(window.XMLHttpRequest) { // Mozilla, Safari, ... les vrais navigateurs
		xhr = new XMLHttpRequest();
		//Force le type MIME pour l'envoi
		if(xhr.overrideMimeType) {
			xhr.overrideMimeType('text/xml');
			// un appel de fonction supplémentaire pour écraser l'en-tête envoyé par le serveur,
			// juste au cas où il ne s'agit pas de text/xml, pour certaines versions de navigateurs Mozilla.
		}
	}
	else {
		if(window.ActiveXObject) { // IE
		 	try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
	    	}
	    	catch (e) {
	        	try {
	        		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	        	}
	        	catch (e) { alert(e.description); }
	    	}
		}
	}

	if(!xhr) {
	    alert('Abandon : Impossible de créer une instance XMLHTTP.');
	    return false;
	}

	// Affectation d'une fonction qui traitera les données retournées par le serveur
	xhr.onreadystatechange = function() {
		if(loadedElement === undefined || loadedElement === null){
			callbackFunction(xhr);
		} else {
			callbackFunction(xhr, loadedElement);
		}
	};

	// Envoi des variables à l'url
	xhr.open("POST", uri, true);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send(post_data);

	/*
	Statut possibles à lé réception
	UNSENT = 0;
	OPENED = 1;
	HEADERS_RECEIVED = 2;
	LOADING = 3;
	DONE = 4;
	*/
}

//Cette fonction retourne la valeur du champ 'field' dans le flux passé en paramètre
function getXhrValue(xhr, field){
	var retour = '';
	//Fonction récupérant le flux généré par la requête ajax
	if (xhr.readyState == 4) {// Réception des données
		if (xhr.status == 200) {// Statut OK HTTP 200
			var doc = xhr.responseXML;
			if (window.ActiveXObject) {
				//On utilise ie
				var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0" );
				var root;
				var newElem;
				xmlDoc.async = false;
				xmlDoc.loadXML(xhr.responseText);

				//Traitement du flux XML
				if(xmlDoc 
						&& xmlDoc.getElementsByTagName("valide") 
						&& xmlDoc.getElementsByTagName("valide")[0]
						&& xmlDoc.getElementsByTagName("valide")[0].childNodes[0]
						&& xmlDoc.getElementsByTagName("valide")[0].childNodes[0].nodeValue
						&& trim(xmlDoc.getElementsByTagName("valide")[0].childNodes[0].nodeValue) == 1){
					try{
						retour = trim(xmlDoc.getElementsByTagName(field)[0].childNodes[0].nodeValue);
					}
					catch(err){
						//alert(err.description);
					}
				}
			} else {
				//On utilise un autre navigateur
				
				//Traitement du flux XML
				if(doc 
						&& doc.getElementsByTagName("valide") 
						&& doc.getElementsByTagName("valide").item(0)
						&& doc.getElementsByTagName("valide").item(0).firstChild
						&& trim(doc.getElementsByTagName("valide").item(0).firstChild.data) == 1) {
					try{
						retour = trim(doc.getElementsByTagName(field).item(0).firstChild.data);
					}
					catch(err){
						//alert(err.description);
					}
				}
			}
		}
	}
	return retour;
}

//Cette fonction retourne le code html du flux passé en paramètre
function getXhrValueHTML(xhr, field){
	var retour = '';
	//Fonction récupérant le flux généré par la requête ajax
	if (xhr.readyState == 4) {// Réception des données
		if (xhr.status == 200) {// Statut OK HTTP 200
			var doc = xhr.responseText;
			retour = doc;
		}
	}
	return retour;
}

//Cette fonction retourne la liste des valeurs des éléments du champ 'field'
//dans le flux passé en paramètre
function getXhrList(xhr, valueField, textField, htmlListId){
	//Fonction récupérant le flux généré par la requête ajax
	if (xhr.readyState == 4) {// Réception des données
		if (xhr.status == 200) {// Statut OK HTTP 200
			var doc = xhr.responseXML;
			if (window.ActiveXObject) {
				//On utilise ie
				var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0" );
				var root;
				var newElem;
				xmlDoc.async = false;
				xmlDoc.loadXML(xhr.responseText);

				//Traitement du flux XML
				if(trim(xmlDoc.getElementsByTagName("valide")[0].childNodes[0].nodeValue) == 1){
					try{
						$(htmlListId).options.length=0;
						var i = 0;
						while(xmlDoc.getElementsByTagName(valueField)[i]){
							$(htmlListId).options[i+1] = new Option(xmlDoc.getElementsByTagName(textField)[i].childNodes[0].nodeValue, xmlDoc.getElementsByTagName(valueField)[i].childNodes[0].nodeValue);
							i++;
						}
					}
					catch(err){/*alert(err.description);*/}
				}
			} else {
				//On utilise un autre navigateur
								
				//Traitement du flux XML
//				alert(trim(doc.getElementsByTagName("valide").item(0).firstChild.data));
				if(trim(doc.getElementsByTagName("valide").item(0).firstChild.data) == 1) {
					try{
						//retour = trim(doc.getElementsByTagName(field).item(0).firstChild.data);
						$(htmlListId).options.length=0;
						var i = 0;
						while(doc.getElementsByTagName(valueField).item(i)){
							var element = doc.getElementsByTagName(textField).item(i);
							var elementValue = doc.getElementsByTagName(valueField).item(i);
							$(htmlListId).options[i+1] = new Option(element.firstChild.data, elementValue.firstChild.data);
							i++;
						}
//						alert(i);
					}
					catch(err){/*alert(err.description);*/}
				}
			}
		}
	}
}
