/**
 * Librairie javascript commune
 *
 * @author		Julie Tétard <julie@2jstudio.com> 
 * @version		2.1
 * @package		Ecog
 * @subpackage 	javascript
 * @category 	commun
 */
 


/**
 * Attache événements
 */

ECOG_smartAttachEvent(window, 'load', ECOG_initMenu, false);
loading = false;

/**
 * Fonctions d'initalisation
 */

	/**
	 * Fonction attachant un les événements aux éléments du menu
	 *
	 * @return		-
	 */
	function ECOG_initMenu()
	{
		// Attache chargement ville à partir des cp
		ECOG_smartAttachEvent(document.getElementById('libreBut'), 'click', ECOG_catalog_loadFreeSearch, false);
		ECOG_smartAttachEvent(document.getElementById('libreBut2'), 'click', ECOG_catalog_loadFreeSearch, false);
		// Attache chargement ville à partir des départements
		ECOG_smartAttachEvent(document.getElementById('departements'), 'change', ECOG_catalog_loadGuidedSearch, false);
		// Cas où on recharge une session existante 
		var mode = '';
		for(i = 0 ; i < document.getElementById('localisation').getElementsByTagName('input').length ; i++) {
			if (document.getElementById('localisation').getElementsByTagName('input')[i].type == 'radio') {
				if (document.getElementById('localisation').getElementsByTagName('input')[i].checked == true) {
					mode = document.getElementById('localisation').getElementsByTagName('input')[i].value;
				}
			}
		}
		if (mode == 'libre') {
			var filled = false;
			for(i = 1 ; i < 6 ; i++) {
				if (document.getElementById('cp' + i).value != '') {
					filled = true;
				}
			}
			if (filled == true) {
				document.getElementById('libreBut').click();
			}
		} else if (mode == 'guide' && document.getElementById('departements').selectedIndex != 0) {
			ECOG_catalog_execGuidedSearch(document.getElementById('departements'));
		}
	} 


/**
 * Fonctions d'exécution
 */
 	
	/**
	 * Fonction affichant les résultats de la recherche libre
	 *
	 * @return		-
	 */
	function ECOG_catalog_loadFreeSearch(event) {
		/* On récupère le nom du bouton cliqué */
		var target = ECOG_smartGetTarget(event);
		/* On sélectionne le bon mode */
		ECOG_catalog_checkMode('libre');
		document.getElementById('departements').selectedIndex = 0;
		/* On abort l'xmlhttp actuel s'il existe */
		ECOG_catalog_xmlhttpAbort();
		/* On supprime les éléments de la recherche guidée si existent */
		ECOG_catalog_removeElem('guideVilleResultats');
		ECOG_catalog_removeElem('guideSecteurResultats');
		
		/* Si rien de renseigné : erreur */
		var status = true;
		if (target.id == 'libreBut') {
			/* On récupère les codes postaux renseignés */
			var cpTab = Array();
			for(i = 1 ; i < 6 ; i++) {
				var valTmp = document.getElementById('cp' + i).value;
				if (valTmp != '') {
					cpTab.push(valTmp);
				}
			}
			if (cpTab.length == 0) {
				alert('Vous devez renseigner au moins un code postal.');
				status = false;
			}
		/* Si au moins un renseigné */
		} else if (target.id == 'libreBut2' && document.getElementById('ville').value == '') {
			alert('Vous devez renseigner un nom de ville');
			status = false;
		}
		
		/* Si au moins un renseigné */
		if (status == true) {
			/* Définition*/
			loadName = 'libre';
			if (target.id == 'libreBut') {
				/* Consitution de la liste */
				var cpList = cpTab.join('_');
				/* Création de l'objet HttpRequest */
				ECOG_catalog_xmlhttpExec('mode=libre&cpList=' + cpList + '&id=' + document.getElementById('id').value);		
			} else {
				/* Création de l'objet HttpRequest */
				ECOG_catalog_xmlhttpExec('mode=libreVille&ville=' + document.getElementById('ville').value + '&id=' + document.getElementById('id').value);	
			}
		}
	}
	
	function ECOG_catalog_loadGuidedSearch(event) {
		/* On récupère la cible */
		var target = ECOG_smartGetTarget(event);
		ECOG_catalog_execGuidedSearch(target)
	}
	
	/**
	 * Fonction affichant les résultats de la recherche guidée
	 *
	 * @param		object		event		Objet évenement
	 * @return		-
	 */
	function ECOG_catalog_execGuidedSearch(target) {
		/* On sélectionne le bon mode */
		ECOG_catalog_checkMode('guide');
		/* On abort l'xmlhttp actuel s'il existe */
		ECOG_catalog_xmlhttpAbort();
		/* On supprime les éléments de la recherche guidée si existent */
		ECOG_catalog_removeElem('libreResultats');
		ECOG_catalog_removeElem('guideSecteurResultats');
		/* Cas 1 : Chargement localité */
		if (target.id == 'departements') {
			/* On supprime les éléments de la recherche guidée si existent */
			ECOG_catalog_removeElem('guideVilleResultats');
			/* On récupère le département sélectionné */
			var code = document.getElementById('departements').options[document.getElementById('departements').selectedIndex].value;
			/* Si rien de renseigné : erreur */
			if (code != '') {
				/* Définition*/
				loadName = 'guideVille';
				/* Création de l'objet HttpRequest */
				ECOG_catalog_xmlhttpExec('mode=guideVille&code=' + code + '&id=' + document.getElementById('id').value);
			}
		} else {
			/* On récupère le département sélectionné */
			var localite = document.getElementById('guideVille').options[document.getElementById('guideVille').selectedIndex].value;
			/* Si rien de renseigné : erreur */
			if (localite != '' && document.getElementById(localite) && document.getElementById(localite).value > 1) {
				/* Définition*/
				loadName = 'guideSecteur';
				/* Création de l'objet HttpRequest */
				ECOG_catalog_xmlhttpExec('mode=guideSecteur&localite=' + localite + '&id=' + document.getElementById('id').value);
			}
		}
	}

	/**
	 * Fonction gérant le réponse de l'objet xmlhttp
	 *
	 * @return		-
	 */
	function ATA_catalog_handleHttpResponse() {
		/* Si etat pas encore prêt : on attache un message d'attente */
		if (xmlhttp.readyState < 4) {
			/* Variable déterminant si ajax en cours */
			loading = true;
			/* Vire les résultats qui existent déjà */
			ECOG_catalog_removeElem(loadName + 'Resultats');
			/* Attache message attente */
			if(!document.getElementById(loadName + 'Wait')) {
				var node = document.createElement('div');
				node.id = loadName + 'Wait';
				node.className = 'ajaxWait';
				var img = document.createElement('img');
				img.src = 'images/commun/load.gif';
				node.appendChild(img);
				var txt = document.createTextNode('Chargement en cours...');
				node.appendChild(txt);
				document.getElementById(loadName.substr(0,5)).appendChild(node);
			}
		// Si etat prêt : on attache résultat ou erreur
		} else if (xmlhttp.readyState == 4) {
			loading = false;
			if (xmlhttp.status == 200) {
				/* On supprime la div d'attente */
				ECOG_catalog_removeElem(loadName + 'Wait');
				/* On récupère la réponse ajax et on la met dans le conteneur du tableau de contenu */
				results = xmlhttp.responseText;
				if (!document.getElementById(loadName + 'Resultats')) {
					var node = document.createElement('div');
					node.id = loadName + 'Resultats';
					document.getElementById(loadName.substr(0,5)).appendChild(node);
				}
				document.getElementById(loadName + 'Resultats').innerHTML = results;	
				/* Attache événements spés */
				if (loadName == 'libre') {
					ECOG_catalog_attachCheckAll();
					ECOG_catalog_checkCp('libre');
				} else if (loadName == 'guideVille') {
					ECOG_smartAttachEvent(document.getElementById('guideVille'), 'change', ECOG_catalog_loadGuidedSearch, false);
					/* Dans le cas ou rechargement : on sélectionne la bonne ville */
					if (document.getElementById('hid_guideVille').value != '') {
						document.getElementById('guideVille').value = document.getElementById('hid_guideVille').value;
						ECOG_catalog_execGuidedSearch(document.getElementById('guideVille'));
					}
				} else if (loadName == 'guideSecteur') {
					ECOG_catalog_checkCp('guide');
				}
			} else {
				document.getElementById(loadName + 'Wait').innerHTML = '<p class="warn">ERREUR : la liste n\'a pas pu être chargée.</p>';
			}
		}
	}
	
	/**
	 * Fonction supprimant un élément
	 *
	 * @param		string		elemName		Nom de l'élément à supprimer
	 * @return		-
	 */
	function ECOG_catalog_removeElem(elemName) {
		if (document.getElementById(elemName)) {
			document.getElementById(elemName).parentNode.removeChild(document.getElementById(elemName));
		}
	}
	
	/**
	 * Fonction avortant une requete ajax
	 *
	 * @return		-
	 */
	function ECOG_catalog_xmlhttpAbort() {
		if(loading) {
			xmlhttp.abort();
			document.getElementById(loadName + 'Wait').parentNode.removeChild(document.getElementById(loadName + 'Wait'));
		}
	}
	
	/**
	 * Fonction exécutant une requete ajax
	 *
	 * @param		string		arg		liste arguments de la requete
	 * @return		-
	 */
	function ECOG_catalog_xmlhttpExec(arg) {
		if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();     //  Firefox, Safari, ...
		} else if (window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   // Internet Explorer < 7
		}
		/* Préparation d'une requête asynchrone de type POST : */
		xmlhttp.open('POST', 'ajax/catalogue.ajax.php', true);
		/* Effectue la requête en envoyant les données */
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.onreadystatechange = ATA_catalog_handleHttpResponse;
		xmlhttp.send(arg);
	}
	
	/**
	 * Fonction sélectionnant le bon mode
	 *
	 * @param		string		arg		valeur du mode
	 * @return		-
	 */
	function ECOG_catalog_checkMode(arg) {
		
		for(i = 0 ; i < document.getElementsByTagName('input').length ; i++) {
			if (document.getElementsByTagName('input')[i].type == 'radio') {
				if (document.getElementsByTagName('input')[i].value == arg) {
					document.getElementsByTagName('input')[i].checked = true;
				} else {
					document.getElementsByTagName('input')[i].checked = false;
				}
			}
		}
	}
	
	/**
	 * Fonction attachant la sélection des enfants aux checkbox principaux
	 *
	 * @return		-
	 */
	function ECOG_catalog_attachCheckAll() {
		var inputTab = document.getElementById('libreResultats').getElementsByTagName('input');
		for(i = 0 ; i < inputTab.length ; i++) {
			if (inputTab[i].id == 'localite[]') {
				ECOG_smartAttachEvent(inputTab[i], 'click', ECOG_catalog_checkAll, false);
			}
		}
	}

	/**
	 * Fonction sélectionnant les input enfants
	 *
	 * @param		object		event		Objet évenement
	 * @return		-
	 */
	function ECOG_catalog_checkAll(event) {
		/* On récupère la cible */
		var target = ECOG_smartGetTarget(event);
		var val = target.checked;
		var inputTab = target.parentNode.getElementsByTagName('input');
		for(i = 0 ; i < inputTab.length ; i++) {
			inputTab[i].checked = val;
		}
	}
	
	/**
	 * Fonction sélectionnant les input enfants
	 *
	 * @param		object		event		Objet évenement
	 * @return		-
	 */
	function ECOG_catalog_checkCp(mode) {
		/* Dans le cas ou rechargement : on sélectionne les bons cp */
		if (document.getElementById('hid_cp').value != '') {
			/* On récupère la cible */
			var cpTab = document.getElementById('hid_cp').value.split(';');
			var inputTab = document.getElementById(mode).getElementsByTagName('input');
			for(i = 0 ; i < inputTab.length ; i++) {
				if(inputTab[i].type == 'checkbox') {
					var found = false;
					for(j = 0 ; j < cpTab.length ; j++) {
						if (inputTab[i].value == cpTab[j]) {
							var found = true;
						}
					}
					inputTab[i].checked = found;
				}
			}
		}		
	}
