/**
 * Librairie javascript commune � tout l'ecog
 *
 * @author		Julie T�tard <julie@2jstudio.com> 
 * @version		E-cog 3.0
 * @package		shared
 * @subpackage	shared
 * @category	js
 * @internal	last modified
 */



/**
 * Fonctions de manipulation des �v�nements
 */

	
	



/**
 * Fonctions de formulaire
 */
	
	/**
	 * Fonction remplissant les champs d'un page au chargement
	 *
	 * @param		object		nodeName		nom du noeud de restriction
	 * @return		-
	 */
	function ECOG_inputSetBlank(nodeName) {
		// Si non d�fini
		if (!nodeName || nodeName.type) {
			nodeName = '';
		} 
		// Si pas de noeud ou si noeud existe bien : on continue
		if (nodeName == '' || $(nodeName)) {
			// On d�finit l'appel si existe noeud
			if (nodeName != '') {
				nodeName = '#' + nodeName + ' ';
			}
			// On passe en revue tous les inputs
			for (i = 0 ; i < $$(nodeName + 'input').length ; i++) {
				var input = $$(nodeName + 'input')[i];
				
				// Si input texte + existe un title
				if ((input.type == 'text' || input.type == 'password') && input.title && input.title != '') {
					// Si la valeur est vide, on la remplit avec le title
					if (input.value == '') {
						input.value = input.title;
					}
					// Si value = title : on rajoute le blank dans la classe
					if (input.value == input.title) {
						input.className += ' e_blank';
					}
					// Attache
					ECOG_smartAttachEvent(input, 'focus', ECOG_fieldAutoFill, false);
					ECOG_smartAttachEvent(input, 'blur', ECOG_fieldAutoFill, false);
				}
				
			}
			// On passe en revue tous les textarea
			for (i = 0 ; i < $$(nodeName + 'textarea').length ; i++) {
				var textarea = $$(nodeName + 'textarea')[i];
				// Si input texte + existe un title
				if (textarea.title && textarea.title != '') {
					// Si existe un title et que value vide
					if (textarea.value == '' && textarea.title && textarea.title != '') {
						textarea.value = textarea.title;
					}
					// Si value = title : on rajoute le blank dans la classe
					if (textarea.value == textarea.title) {
						textarea.className += ' e_blank';
					}
					// Attache
					ECOG_smartAttachEvent(textarea, 'focus', ECOG_fieldAutoFill, false);
					ECOG_smartAttachEvent(textarea, 'blur', ECOG_fieldAutoFill, false);
				}
			}
		}
		
	}
	
	/**
	 * Fonction permettant de vider un champ et de le reremplir
	 *
	 * @param		object		event		Objet �venement
	 * @return		-
	 */
	function ECOG_fieldAutoFill(event) 
	{ 
		// Recup target
		var target = ECOG_smartGetTarget(event);
		// Si �venement focus et que value = title : on vide le champ
		if (event.type == 'focus' && target.value == target.title) {
			target.value = '';
		// Si �venement blur
		} else if (event.type == 'blur') {
			// Si valeur vide => remplissage avec title
			if (target.value == '') {
				target.value = target.title;
			}
			// Si valeur = title et qu'il n'y a pas de blank dans la class : on le rajoute
			if (target.value == target.title && target.className.indexOf(' e_blank') == -1) {
				target.className += ' e_blank';
			}
		}
	} 
	
	
	
	/**
	 * Fonction assignant l'highlight des champs de formulaires
	 *
	 * @param		object		nodeName		nom du noeud de restriction
	 * @return		-
	 */
	function ECOG_inputSetFocusBlur(nodeName) {
		// Si non d�fini
		if (!nodeName || nodeName.type) {
			nodeName = '';
		} 
		// Si pas de noeud ou si noeud existe bien : on continue
		if (nodeName == '' || $(nodeName)) {
			// On d�finit l'appel si existe noeud
			if (nodeName != '') {
				nodeName = '#' + nodeName + ' ';
			}
			
			// Attache actions sur champ recherche
			$$(nodeName + 'input').each(
				function(input) {
					ECOG_smartAttachEvent(input, 'focus', ECOG_fieldFocus, false);
					ECOG_smartAttachEvent(input, 'blur', ECOG_fieldBlur, false);
				}
			);
			$$(nodeName + 'select').each(
				function(input) {
					ECOG_smartAttachEvent(input, 'focus', ECOG_fieldFocus, false);
					ECOG_smartAttachEvent(input, 'blur', ECOG_fieldBlur, false);
				}
			);
			$$(nodeName + 'textarea').each(
				function(input) {
					ECOG_smartAttachEvent(input, 'focus', ECOG_fieldFocus, false);
					ECOG_smartAttachEvent(input, 'blur', ECOG_fieldBlur, false);
				}
			);
		}
	}
	
	/**
	 * Fonction permettant d'highlighter un champ
	 *
	 * @param		object		event		Objet �venement
	 * @return		-
	 */
	function ECOG_fieldFocus() 
	{ 
		// On vire le blank �ventuel
		$(this).removeClass('e_blank');
		// On vire les warn
		$(this).removeClass('e_warn');
		// On rajoute le focus 
		$(this).addClass('e_focus');	
	} 

	/**
	 * Fonction permettant d'enlever l'highlight sir un champ
	 *
	 * @param		object		event		Objet �venement
	 * @return		-
	 */
	function ECOG_fieldBlur(event) 
	{ 
		// On vire le focus �ventuel
		$(this).removeClass('e_focus');
	} 
	
	/**
	 * Fonction permettant d'enlever l'highlight sir un champ
	 *
	 * @param		object		event		Objet �venement
	 * @return		-
	 */
	function ECOG_fieldSetValue(objectId, objectValue) 
	{ 
		document.getElementById(objectId) = objectValue;
	} 
	
	/**
	 * Fonction validant le formulaire parent en stockant l'id de l'�l�ment cliqu�
	 *
	 * Attache l'hidden qui stocke l'id s'il 'nexiste pas
	 * @param		object	event		Objet �venement
	 * @return		-
	 * @uses		ECOG_smartGetTarget()
	 */
	function ECOG_formSubmitWithId(object)
	{
		// R�cup�re la cible
		if (typeof(object.target) != 'undefined' || typeof(object.srcElement) != 'undefined') {
			object = this;
		} 
		while($(object).attr('id') == '' && $(object).attr('nodeName') != 'body') {
			object = object.parent();
		}
		// R�cup�re le formulaire parent
		if ($('#' + curForm).length > 0) {
			objForm = $('#' + curForm);
		} else {
			objForm = $('#body form');
		}
		// S'il n'existe pas d'hidden, on en attache un
		if ($('#submitId').length == 0) {
			objForm.append('<input type="hidden" id="submitId" name="submitId" class="inputHidden">');
		}
		// Assigne id de l'�l�ment cliqu� au champs cach�
		$('#submitId').val($(object).attr('id'));
		//alert($('#submitId').val());
		// Valide le formulaire parent
		objForm.submit();		
	}
	
	/**
	 * Fonction validant le formulaire parent en stockant la valeur de l'�l�ment cliqu�
	 *
	 * Attache l'hidden qui stocke l'id s'il 'nexiste pas
	 * @param		object	event		Objet �venement
	 * @return		-
	 */
	function ECOG_formSubmitWithValue(object)
	{
		if (typeof(object.target) != 'undefined' || typeof(object.srcElement) != 'undefined') {
			object = this;
		} 
		// R�cup�re le formulaire parent
		objForm = $('#' + curForm);
		// S'il n'existe pas d'hidden, on en attache un
		if ($('#submitId').length > 0) {
			objForm.append('<input type="hidden" id="submitId" name="submitId" class="inputHidden" />');
		}
		// Assigne id de l'�l�ment cliqu� au champs cach�
		$('#submitId').val($(object).val());
		// Valide le formulaire parent
		objForm.submit();
	}
	
	/**
	 * Fonction empechant la validation d'un formulaire
	 *
	 * @param		object	event		Objet �venement
	 * @return		-
	 */
	function ECOG_formStopSubmit(event)
	{
		// On empeche la propagation si on peut
		if (event.preventDefault) {
		   event.preventDefault();
		}
		// On retourne false
		event.returnValue = false;	
	}
	
	/**
	 * Fonction r�cup�rant la valeur d'un groupe de bouton radion / checkbox
	 *
	 * @param		string		formId		id du formulaire
	 * @param		string		inputType	type des inputs
	 * @param		string		radioName	nom du group de bouton radio
	 * @return		mixed		valeur du bouton radio
	 */
	function ECOG_inputSetGetValue(inputName, inputType)
	{
		// On r�cup�re les bouton radio + la valeur � false
		var value = false;
		$('input[name="' + inputName + '"]').each( 
			function (){ 
				// S'il est ch�ck�, on r�cup�re la valeur
				if ($(this).is(':checked')) {
					if (inputType == 'checkbox') {
						if (!value) {
							value = Array();
						}
						value.push($(this).val());
					} else {
						value = $(this).val();
					}
				}
			}
		);
		// Retour
		return value;
	}
	
	/**
	 * Fonction d�selectionnant un set de checkbox
	 *
	 * @param		string		formId		id du formulaire
	 * @param		string		inputType	type des inputs
	 * @param		string		radioName	nom du group de bouton radio
	 * @param		bool		value		valeur du checked
	 * @return		-
	 */
	function ECOG_inputSetUpdate(inputType, inputName, value)
	{
		$('input[name=' + inputName + ']').each( 
			function (){ 
				// S'il est ch�ck�, on r�cup�re la valeur
				if ($(this).val == value) {
					$(this).attr('checked', true);
				}
			}
		);
	}
	
	/**
	 * Fake select Init
	 *
	 * @param		object		event		Event Objet
	 */
	function ECOG_selectInit() {
		/*$('.selectLikeTop').each( 
			function () {
				var id = $(this).attr('id').substr(0, $(this).attr('id').length - 3);
				$(this).find('p:first').click(ECOG_selectSlideByEvent);
				$('#' + id + 'Arrow').click(ECOG_selectSlideByEvent);
				$('#' + id + 'Arrow').mouseover(ECOG_rollOver);
				$('#' + id + 'Arrow').mouseout(ECOG_rollOut);
			}
		);*/
	}
	
	/**
	 * Fonction permettant d'afficher ou r�tracter le faux select en cliquant dessus
	 *
	 * @param		object		event		Objet �venement
	 * @return		-
	 */
	function ECOG_selectSlideByEvent() {
		if ($(this).attr('nodeName').toLowerCase() == 'img') {
			var id = $(this).attr('id').substr(0, $(this).attr('id').length - 5);
		} else {
			var id = $(this).parent().attr('id').substr(0, $(this).parent().attr('id').length - 3);
		}
		ECOG_selectSlide(id);
	}
	
	/**
	 * Fonction permettant d'afficher ou r�tracter le faux select
	 *
	 * @param		string		objId		id de l'objet concern�
	 * @return		-
	 */
	function ECOG_selectSlide(objId) {
		if ($('#' + objId + 'Div').css('display')  == 'none') {
			$('.selectLikeTop').each( 
				function () {
					var id = $(this).attr('id').substr(0, $(this).attr('id').length - 3);					
					if (objId != id) {
						$('#' + id + 'Div').hide();
					}
				}
			);
			$('#' + objId + 'Div').show();
		} else {
			$('#' + objId + 'Div').hide();
		}
	}
	

/**
 * Fonctions de conversion HTML
 */

	/**
	 * Fonction affichant un lien dans une nouvelle fenetre
	 *
	 * @param		object	event		Objet �venement
	 */
	function ECOG_openLinkInNewWindow(event)
	{
		// On r�cupere la cible et l'url de son lien
		var target = ECOG_smartGetTarget(event);
		// Remonte jusqu'au a
		var node = target.nodeName;
		while(node.toLowerCase() != 'a' && node.toLowerCase() != 'body') {
			target = target.parentNode;
			node = target.nodeName;
		}
		// On execute le lien en javascript
		if (node.toLowerCase() == 'a') {
			window.open(target.name, '_blank');
		}
	}


/**
 * Fonctions d'interaction
 */

	/**
	 * Fonction r�cup�rant le nom de l'image source d'un �l�ment
	 *
	 * @param		object		object		objet concern�
	 * @return		string		nom de l'image source
	 */
	function ECOG_getPixName(object) 
	{
		var srcTab = object.attr('src').split('/');
		return srcTab[srcTab.length - 1];
		
	}
	
	/**
	 * Fonction chnageant le nom de l'image source d'un �l�ment
	 *
	 * @param		object		object		objet concern�
	 * @param		string		newName		nouveau nom de l'image source de l'objet concern�
	 * @return		-
	 */
	function ECOG_setPixName(object, newName) 
	{
		var srcTab = object.attr('src').split('/');
		srcTab[srcTab.length - 1] = newName;
		object.attr('src', srcTab.join('/'));
	}
	
	/**
	 * Fonction affichant le rollover de l'image principale
	 *
	 * @param		object		menuObj			l'objet cible
	 * @return		-
	 */
	function ECOG_rollOver(event)
	{
		/* On explose la source de l'image en tableau */
		var imgName = ECOG_getPixName($(this));
		/* Si l'image n'est d�j� pas en rollover, on la change */
		if (imgName.substr(imgName.length - 7, 3) != '_f2') {
			/* On lui rajoute le _f2 et on recolle avec l'extension */
			ECOG_setPixName($(this), imgName.substr(0, imgName.length - 4) + '_f2' + imgName.substr(imgName.length - 4));
		}
		if (navigator.userAgent.indexOf('MSIE 6') != -1 && imgName.substr(imgName.length - 3) == 'png') {
			object.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + object.src + "');" ;
		}
	}
	
	/**
	 * Fonction affichant le rollout de l'image principale
	 *
	 * @param		object		menuObj			l'objet cible
	 * @return		-
	 */
	function ECOG_rollOut(event)
	{
		/* On explose la source de l'image en tableau */
		var imgName = ECOG_getPixName($(this));
		/* Si l'image est bien en rollover, on la change */
		if (imgName.substr(imgName.length - 7, 3) == '_f2') {
			/* On enl�ve le _f2 final */
			ECOG_setPixName($(this), imgName.substr(0, imgName.length - 7) + imgName.substr(imgName.length - 4));
		}
		if (navigator.userAgent.indexOf('MSIE 6') != -1 && imgName.substr(imgName.length - 3) == 'png') {
			object.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + object.src + "');" ;
		}
	}

	
	/**
	 * Fonction ins�rant un loader
	 *
	 * @param		string		loaderParentId		id du noeud parent du loader
	 * @param		string		loaderId			id du loader
	 * @param		string		loaderAlt			alt du loader
	 * @return		-
	 * @uses		Prototype >= 1.6.0.2
	 */
	function ECOG_loaderInsert(loaderParentId, loaderPosition, loaderId, loaderAlt, loaderSrc) {
		// Valeurs par d�faut
		if (typeof(loaderId) == 'undefined') {
			loaderId = 'loader';
		}
		if (typeof(loaderAlt) == 'undefined') {
			loaderAlt = 'Chargement en cours';
		}
		if (typeof(loaderPosition) == 'undefined') {
			loaderPosition = 'bottom';
		}
		if (typeof(loaderSrc) == 'undefined') {
			loaderSrc = 'pix/load.gif';
		}
		// Si loader n'existe pas d�j�
		if ($('#' + loaderId).length == 0) {
			// Cr�e l'image
			var loader = '<img id="' + loaderId + '" src="' + loaderSrc + '" alt="' + loaderAlt + '" title="' + loaderAlt + '" class="loader" />';
			// Insert it
			if (loaderPosition == 'top') {
				$(loaderParentId).prepend(loader);
			} else if (loaderPosition == 'bottom') {
				$(loaderParentId).append(loader);
			} else if (loaderPosition == 'after') {
				$(loaderParentId).after(loader);
			} if (loaderPosition == 'before') {
				$(loaderParentId).before(loader);
			} 
		}
	}
	
	function loaderInsert(parent, position, id, alt, src) {
		// Valeurs par d�faut
		if (typeof(id) == 'undefined') {
			Id = 'ajax-loader';
		}
		if (typeof(alt) == 'undefined') {
			alt = 'Chargement en cours...';
		}
		if (typeof(position) == 'undefined') {
			position = 'after';
		}
		if (typeof(src) == 'undefined') {
			src = 'param/pix/loader.gif';
		}
		// Si loader n'existe pas d�j�
		if ($('#' + id).length == 0) {
			// Cr�e l'image
			var loader = '<img id="' + id + '" src="' + src + '" alt="' + alt + '" title="' + alt + '" class="ajax-loader" />';
			// Insert it
			if (position == 'top') {
				$(parent).prepend(loader);
			} else if (position == 'bottom') {
				$(parent).append(loader);
			} else if (position == 'after') {
				$(parent).after(loader);
			} if (position == 'before') {
				$(parent).before(loader);
			} 
		}
	}
	
	/**
	 * Fonction ins�rant un loader
	 *
	 * @param		string		loaderId			id du loader
	 * @return		-
	 * @uses		Prototype >= 1.6.0.2
	 */
	function ECOG_loaderRemove(loaderId) {
		// Valeurs par d�faut
		if (typeof(loaderId) == 'undefined') {
			loaderId = 'ajax-loader';
		} else if (typeof(loaderId) == 'object') {
			loaderId = ECOG_ajax_requestIdGet(loaderId) + 'Loader';
		}
		// Remove
		if (loaderId == '') {
			$('.ajax-loader').remove();
		} else {
			$(loaderId).remove();
		}
	}


/**
 * Fonctions de liens et de redirection
 */
	
	/**
	 * Fonction r�cup�rant l'id de la session en cours � partir de l'url de la page courrante
	 *
	 * @return		-
	 */
	function ECOG_getSesId()
	{
		// Recup url courrant
		var locationTab = document.location.href.split('?');
		// S'il y a bien des arguments
		var sesId = false;
		if (locationTab.length == 2) {
			// On les passe tous en revue
			var argsTab = locationTab[1].split('&');
			for (i = 0 ; i < argsTab.length ; i++) {
				argTab = argsTab[i].split('=');
				// S'il y en a un qui d�finit la sessions courrant, on l'assigne
				if (argTab[0].toLowerCase() == 'phpsessid') {
					sesId = argsTab[i];
				}
			}
		}
		// Retour
		return sesId;
	}
	
	/**
	 * Fonction r�cup�rant l'id de la session en cours � partir de l'url de la page courrante
	 *
	 * @return		-
	 */
	function ECOG_getSesIdBis()
	{
		// Recup url courrant
		var locationTab = document.location.href.split('?');
		// S'il y a bien des arguments
		var sesId = false;
		if (locationTab.length == 2) {
			// On les passe tous en revue
			var argsTab = locationTab[1].split('&');
			for (i = 0 ; i < argsTab.length ; i++) {
				argTab = argsTab[i].split('=');
				// S'il y en a un qui d�finit la sessions courrant, on l'assigne
				if (argTab[0].toLowerCase() == 'phpsessid') {
					sesId = argTab[1];
				}
			}
		}
		// Retour
		return sesId;
	}
	
	/**
	 * Fonction r�cup�rant l'id de la session en cours � partir de l'url de la page courrante
	 *
	 * @return		-
	 */
	function ECOG_getParentSesId()
	{
		// Recup url courrant
		var locationH = document.location.href.split('?');
		// S'il y a bien des arguments
		var sesId = false;
		if (locationH.length == 2) {
			// On les passe tous en revue
			var argsH = locationH[1].split('&');
			for (i = 0 ; i < argsH.length ; i++) {
				argH = argsH[i].split('=');
				// S'il y en a un qui définit la sessions courrant, on l'assigne
				if (argH[0].toLowerCase() == 'phpsessid') {
					sesId = argH[1];
				}
			}
		}
		// Retour
		return sesId;
	}
	
	/**
	 * Fonction permettant d'atteindre une url absolue
	 *
	 * @param  		string		url			url de l'adresse relative � atteindre
	 * @return		-
	 * @uses		ECOG_getSesId()
	 */
	function ECOG_goToFullUrl(url)
	{
		// On r�cup�re l'id de la session
		//var sesId = ECOG_getSesId();
		// Si elle existe et qu'il y a bien un tag base
		if ($('base')) {
			// On redirige en ajoutant l'id de session
			this.location = $('base').attr('href') + url;
		}
	}
	
	/**
	 * Fonction permettant de construire une url absolue avec la session
	 *
	 * @param  		string		url			url de l'adresse relative � atteindre
	 * @return		mixed		url compl�te si trouv� �l�ments needed sinon false
	 * @uses		ECOG_getSesId()
	 */
	function ECOG_makeFullUrl(url)
	{
		// On r�cup�re l'id de la session
		//var sesId = ECOG_getSesId();
		// Si elle existe et qu'il y a bien un tag base
		urlH = url.split(document.getElementsByTagName('base')[0].href);
		url = urlH.join('');
		if (document.getElementsByTagName('base')) {
			// On construit l'url en ajoutant l'id de session
			return document.getElementsByTagName('base')[0].href + url;
		} else {
			return false;
		}
	}
	
	/**
	 * Fonction permettant de construire une url absolue
	 *
	 * @param  		string		url			url de l'adresse relative � atteindre
	 * @return		mixed		url compl�te si trouv� �l�ments needed sinon false
	 */
	function ECOG_makeAbsUrl(url)
	{
		// Si elle existe et qu'il y a bien un tag base
		if (document.getElementsByTagName('base')) {
			// On construit l'url en ajoutant l'id de session
			return document.getElementsByTagName('base')[0].href + url;
		} else {
			return false;
		}
	}
	
	/**
	 * Fonction permettant de construire une url absolue
	 *
	 * @param  		string		url			url de l'adresse relative � atteindre
	 * @return		mixed		url compl�te si trouv� �l�ments needed sinon false
	 */
	function ECOG_makePublicUrl(url)
	{
		// On construit l'url en ajoutant l'id de session
		return $('meta[name=identifier-url]').attr('content') + url;
	}
	

/**
 * Fonctions sur les cha�nes
 */

	/**
	 * Fonction enlevant les espaces gauches et droites d'un chaine
	 *
	 * @param		string		string		la cha�ne d'origine
	 * @return		string		chaine nettoy�e
	 */
	function ECOG_trim(string) 
	{
		return string.replace(/^\s+/, '').replace(/\s+$/, '');
	} 
	
	/**
	 * Fonction nettoyant une chaine d'erreur pour un affichage alert
	 *
	 * @param		string		string		la cha�ne d'origine
	 * @return		string		chaine nettoy�e
	 */
	function ECOG_cleanErrorMsg(string) 
	{
		var tagsTab = Array('p', 'em', 'b', 'ul');
		for(i = 0 ; i < tagsTab.length ; i++) {
			while(string.indexOf('<' + tagsTab[i] + '>') != -1) {
				string = string.replace('<' + tagsTab[i] + '>', '');
			}
			while(string.indexOf('</' + tagsTab[i] + '>') != -1) {
				string = string.replace('</' + tagsTab[i] + '>', '');
			}
		}
		var tagsTab = Array('li');
		for(i = 0 ; i < tagsTab.length ; i++) {
			while(string.indexOf('<' + tagsTab[i] + '>') != -1) {
				string = string.replace('<' + tagsTab[i] + '>', '\n - ');
			}
			while(string.indexOf('</' + tagsTab[i] + '>') != -1) {
				string = string.replace('</' + tagsTab[i] + '>', '');
			}
		}
		while(string.indexOf('<br />') != -1) {
			string = string.replace('<br />', '\n');
		}
		while(string.indexOf('<br>') != -1) {
			string = string.replace('<br>', '\n');
		}
		while(string.indexOf('&quot;') != -1) {
			string = string.replace('&quot;', '"');
		}
		while(string.indexOf('&egrave;') != -1) {
			string = string.replace('&egrave;', '�');
		}
		while(string.indexOf('&eacute;') != -1) {
			string = string.replace('&eacute;', '�');
		}
		while(string.indexOf('&ecirc;') != -1) {
			string = string.replace('&ecirc;', '�');
		}
		return ECOG_trim(string);
	} 

	/**
	 * Fonction tronqaunt une chaine
	 *
	 * @param 		string		string			cha�ne � tronquer
	 * @param 		integer		length			taille maximum de la chaine
	 * @param 		string		cropCar		caract�re(s) � ajouter en fin de chaine
	 * @return		string		cha�ne trpnqu�e
	 */
	function ECOG_strCrop(string, len, cropCar)
	{
		if (string.length > len) {
			string = string.substr(0, len) + cropCar;
		}
		return string;
	}
	
	function ECOG_ajax_error(request, x, e) {	
		// Début phrase avec id requete
		var sentence = 'La requête ' + ECOG_ajax_requestIdGet(request) + ' a échoué.\n';
		// Construction message en fonction du code erreur
		if (x.status == 0) {
			sentence += 'Vous êtes déconnecté !!\nMerci de vérifier votre connexion.';
		} else if (x.status == 404) {
			sentence += 'La page demandée est introuvable.';
		} else if (x.status == 500) {
			sentence += 'Erreur interne au serveur.';
		} else if (e == 'parsererror') {
			if (x.responseText.toLowerCase().indexOf('error') == -1) {
				sentence += 'La réponse n\'est pas au format JSON.\n\nMessage original :\n' + x.responseText;
			} else {
				sentence += 'La réponse comporte une erreur.\n\nMessage original :\n' + ECOG_ajax_cleanHtml(x.responseText);
			}
		} else if (e == 'timeout') {
			sentence += 'Le délai de réponse a expiré.';
		} else {
			sentence += 'Erreur inconnue.\n\nMessage original :\n' + ECOG_ajax_cleanHtml(x.responseText);
		}
		// Alerte
		alert(sentence);
	}

	function ECOG_ajax_requestIdGet(request) {
		
		//
		if (request.data) {
			// Découpe la chaine de params
			var dataOldH = request.data.split('&');
			var dataNewH = Array();
			$(dataOldH).each(function(){
				var tmpH = this.split('=');
				dataNewH[tmpH[0]] = tmpH[1];
			});
			// Retour
			if (dataNewH['ajaxId']) {
				return dataNewH['ajaxId'];
			} else {
				return '';
			}
		}
		else {
			return request;
		}
	}
	
	/**
	 * Fonction nettoyant le code html
	 *
	 * @param		string		msg			message d'erreur à nettoyer
	 * @return		string		message d'erreur nettoyé
	 */
	function ECOG_ajax_cleanHtml(msg) {
		// Nettoyage html
		var tagsTab = Array('p', 'em', 'b', 'ul');
		for(i = 0 ; i < tagsTab.length ; i++) {
			while(msg.indexOf('<' + tagsTab[i] + '>') != -1) {
				msg = msg.replace('<' + tagsTab[i] + '>', '');
			}
			while(msg.indexOf('</' + tagsTab[i] + '>') != -1) {
				msg = msg.replace('</' + tagsTab[i] + '>', '');
			}
		}
		var tagsTab = Array('li');
		for(i = 0 ; i < tagsTab.length ; i++) {
			while(msg.indexOf('<' + tagsTab[i] + '>') != -1) {
				msg = msg.replace('<' + tagsTab[i] + '>', '\n - ');
			}
			while(msg.indexOf('</' + tagsTab[i] + '>') != -1) {
				msg = msg.replace('</' + tagsTab[i] + '>', '');
			}
		}
		while(msg.indexOf('<br />') != -1) {
			msg = msg.replace('<br />', '\n');
		}
		while(msg.indexOf('<br>') != -1) {
			msg = msg.replace('<br>', '\n');
		}
		while(msg.indexOf('\r\n') != -1) {
			msg = msg.replace('\r\n', '');
		}
		while(msg.indexOf('	') != -1) {
			msg = msg.replace('	', ' ');
		}
		while(msg.indexOf('  ') != -1) {
			msg = msg.replace('  ', ' ');
		}
		msg = msg.replace('&egrave;', 'è');
		msg = msg.replace('&agrave;', 'à');
		msg = msg.replace('&eacute;', 'é');
		msg = msg.replace('&ecirc;', 'ê');
		msg = msg.replace(/^\s+/, '').replace(/\s+$/, '');
		// Retour
		return msg;
	}
	
	/* Hide it onload if exists */
	function contactPanel(buttons) {	
		
		$(buttons).removeAttr('href');
		
		/* Enable the panel */
		$(buttons).click(function(){
			
			if ($('#contact-overlay').length == 0) {
				// Overlay creation
				$('body').append('<div id="contact-overlay" style="position:fixed;z-index:30;top:0;left:0;height:100%;width:100%;background:#000;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;"></div>');
				contactPanel('#contact-overlay');
				// Panel creation + filling
				$('body').append('<div id="contact-panel" style="position:fixed;z-index:40;top:0;left:center;display:none;"></div>');
				$('#contact-panel').load(ECOG_makeFullUrl('ajax/contact.php'), function(){
					$('#contact-form').submit(function() {
						return false;
					});
					$('#submit').click(function() {
						var validation = formValidate('#contact-form');
						if (validation === true) {
							loaderInsert('#contact-panel-close', 'after', 'contact-panel-loader', 'Envoi en cours...');
							var arr =  $('#contact-form').serializeArray();
							var submitArr = new Array();
							submitArr['name'] = 'submit';
							submitArr['value'] = 'Envoyer'; 
							arr.push(submitArr);
							$('#contact-panel').load(ECOG_makeFullUrl('ajax/contact.php'), arr, function(data) {
								ECOG_loaderRemove('#contact-panel-loader');
								// 
								$('#contact-panel .return-msg').append('<a id="contact-panel-close">fermer</a>')
								contactPanel('#contact-panel-close');
								// Callback onReturn
								if(typeof(contactPanelReturn) == 'function') {
									contactPanelReturn();
								}
							});							
						}
					});
					contactPanel('#contact-panel-close');
					// Callback onload
					if(typeof(contactPanelLoad) == 'function') {
						contactPanelLoad();
					}
				});
				
				// Show
				$('#contact-overlay').show().animate({
					opacity: 0.5
				}, 200, function(){
					$("#contact-panel").slideToggle(500);
				});
				
			} else {
				$("#contact-panel").slideToggle(500);
				$("#contact-overlay").animate({
					opacity: 0
				}, 400, function() {
					//alert($(this).attr('id'));
					$(this).remove();
					$("#contact-panel").remove();
				});
				// Callback onClose
				if(typeof(contactPanelClose) == 'function') {
					contactPanelClose();
				}
			}
			
			
			
			// Panel display 
			
			// Panel 
			
			/*
			
			$("#contact-panel").hide();
			$('#overlay').css('opacity', '0').hide();
			
			// Remove existing href
			if ($(this).attr('href') != 'undefined') {
				$(this).removeAttr('href');
			}
			// Bind events
			var overlay = $("#overlay");
			if (overlay.css("opacity") != 0.5) {
				overlay.show().animate({
					opacity: 0.5
				}, 200, function(){
					$("#contact-panel").slideToggle(500);
				});
			} else {
				$("#contact-panel").slideToggle(500);
				overlay.animate({
					opacity: 0
				}, 400, function(){
					$(this).hide();
				});
			}*/
		});
	}
	
	
function formValidate(form) {
	
	var exFn = false;
	if (typeof $(form).attr('id') == 'string') {
		var fn = $(form).attr('id').replace('-', '_') + 'CustomValidate';
		eval('var checkFn = typeof ' + fn + ';');
		if (checkFn == 'function') {
			eval($(form).attr('id').replace('-', '_') + 'CustomValidate' + '(form);');
			exFn = true;
		}
	} 
	if (exFn === false) {
		var fn = 'customValidate';
		eval('var checkFn = typeof ' + fn + ';');
		if (checkFn == 'function') {
			customValidate(form);
		}
	}
	
	$(form).find('.required,.date,.email,.equal').each(function() {
		var formId = $(form).attr('id');
		if ($(this).get(0).nodeName.toLowerCase() == 'input' || $(this).get(0).nodeName.toLowerCase() == 'textarea'  || 
			$(this).get(0).nodeName.toLowerCase() == 'select' ) {
			var msg = '';
			var nameH = $(this).attr('id').split('-');
			nameH.splice(nameH.length - 1);
			// Value
			if ($(this).hasClass('tree')) {
				var val = ECOG_inputSetGetValue($(this).attr('id'), $(this).find('input').attr('type'));
				val = (val === false ? '' : val);
			} else {
				var val = $(this).val();
			}
			
			// Required
			if ($(this).hasClass('required') && val == '') {
				msg = 'required';
			// Date
			} else if ($(this).hasClass('date') && val != '' && !dateCheck(val)) {
				msg = 'date';
			// Email
			} else if ($(this).hasClass('email') && val != '' && !emailCheck(val)) {
				msg = 'email';
			// Equal
			} else if ($(this).hasClass('equal') && val != $('#' + nameH.join('-')).val()) {
				msg = 'equal';
			} 
			elementValidate($(this), msg, formId);
		}
		
	});

	
	if ($(form).find('input.failed,textarea.failed,select.failed,div.failed').length > 0) {
		$(form).find('input.failed,textarea.failed,select.failed,div.failed')[0].focus();
		alert('Le formulaire comporte des erreurs.');
		return false;
	}
	return true;

}

function elementValidate(element, msg, formId) {
	if (element.hasClass('failed') && msg == '') {
		element.removeClass('failed');
		element.next('.alert').remove();
		element.prev('label').removeClass('failed');
	} else if (!element.hasClass('failed') && msg != '') {
		element.addClass('failed');
		element.prev('label').addClass('failed');
		element.after('<p class="alert">' + $('#' + msg + 'Msg-'+formId).val() + '</p>');
	} else if (element.hasClass('failed') && msg != '') {
		element.next('.alert').html($('#' + msg + 'Msg-'+formId).val());
	}	
}

function dateCheck(date) {
	// Replace all planned separators
	var carH = new Array('.', ' ', '-');
	var dateNew = ''; 
	$.each(function(key, val) {
		dateH = date.split(val);
		dateNew = dateH.join('/');
	});
	date = dateNew;
	
	// Explode string in array
	dateH = date.split('/');
	
	// Must have 3 cells
	if (dateH.length != 3) {
		return false;
	} else {
		// Create variables
		var day 	= $dateH[0];
		var month 	= Math.round($dateH[1]);
		var year 	= $dateH[2];
		
		// Check year
		if (!isNaN(year) || year.length != 4) {
			return false;
		}
		// Check if bisextile 
		var bisextile = (year / 4 == Math.floor(year / 4) ? true : false); 
		var bigMonthList = array(1,3,5,7,8,10,12);
		var smallMonthList = array(4,6,9,11);
					
		// Check month
		if (!isNaN(month) || month < 1 || month > 12) {
			return false;
		}
		
		// Check day
		if (!isNaN(day) || day < 1 || (month == 2 && bisextile === true && day > 28) ||
			(month == 2 && bisextile === false && day > 27) || (bigMonthList.indexOf(month) != -1 && day > 31) ||
			(smallMonthList.indexOf(month) != -1 && day > 30)) {
			return false;
		} 
	}
	return true;
}

function emailCheck(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) === false) {
		return false;
	}
	return true;
}
	


	
