/**
 * Fonction : Event Handlers
 * Description : Fonction permettant d'attacher des actions (fonctions Javascript) à des évènements.
 * Cette fonction a été créée à partir de celles de Scott Andrew LePera (http://www.scottandrew.com/weblog/articles/cbs-events),
 * Simon Willison (http://simon.incutio.com/archive/2004/05/26/addLoadEvent) et du commentaire 
 * de Mark Wubben (http://simon.incutio.com/archive/2004/05/26/addLoadEvent#comment2)
 * Les techniques de chacun des auteurs ont été adaptées afin de fonctionner de façon homogène et d'assurer la compatibilité
 * avec un maximum de navigateur (style W3C / netscape mozilla, Internet Explorer, et autres).
 
 @author : Julien Fredon @ imaginance
*/
function addEvent(obj, evType, fn, useCapture)
{
	/* Attachement d'évènements standard w3c dom (netscape / mozilla / safari 1.2) */
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, useCapture);
		return true;
	}
	else 
	{
		/* Attachement d'évènements Internet Explorer */
		if (obj.attachEvent)
		{
			var r = obj.attachEvent("on" + evType, fn);
			return r;
		}
		else 
		{
			/* Attachement d'évènements navigateurs non compatibles (safari 1.0, etc.) */
			var buffer = obj["on" + evType];
			if (typeof buffer != "function") {
				obj["on" +evType] = fn;
			}
			else
			{
				obj["on" +evType] = function() {
										buffer();
										fn();
									};
			}
		}
	}
};/**
 * Applique la class css sClassName sur les lignes de donnÃ©es (contenues dans un tbody) impaires d'un tableau.
 @author : Julien Fredon @ imaginance
 */
function DrawTable()
{
    var sClassName      =   "altern";
    var oTableBodies    =   document.getElementsByTagName("tbody");
    // Parcours des balises tbody.
    for (var i = 0; i < oTableBodies.length; i ++) {
        // Parcours des balises tr.
        var oTableRows  =   oTableBodies.item(i).getElementsByTagName("tr");
        for(var j = 0; j < oTableRows.length; j ++) {
            if(j % 2 != 0) {
                oTableRows.item(j).className    =   oTableRows.item(j).className + " " + sClassName;
            }
        }
    }
}
addEvent(window, 'load', DrawTable);/**
 * Objet de gestion de Cookie Imaginance.
 * @author : Julien Fredon @ imaginance
 *
 * Utilisation : 
 * 	var oCookieExemple	=	new iCookie('identification'); // Déclaration d'un cookie nommé identification
 * 	oCookieExemple->SetLifespan(100); 		// Définition de la durée de vie du cookie à 100 jours (valeur par défaut : 31)
 * 	oCookieExemple->Set('Hello World'); 	// Écriture du cookie avec la valeur "Hello world" sur le poste de l'internaute.
 * 	oCookieExemple->Get(); 					// Récupération de la valeur du cookie.
 *  oCookieExemple->Debug(); 				// Affiche les informations du cookie.
 * 	oCookieExemple->Delete(); 				// Suppression du cookie.
 */
var iCookie	=	function(cookieName)
{
	// Propriétés du cookie.
	this.name			=	cookieName;
	this.value			=	"";
	this.path			=	"/";
	this.expirationDate	=	"";

	this.Constructor	=	function()
	{
		// Initialisation de la durée de vie par défaut.
		this.SetLifespan(31);
	}

	// Création du cookie avec une valeur.
	this.Set	=	function(cookieValue)
	{
		this.value		=	cookieValue;
		document.cookie	=	this.name + "=" + escape(this.value) + "; expires=" + this.expirationDate.toGMTString() + "; path=" + this.path;
	}

	// Récupération de la valeur d'un cookie.
	this.Get	=	function()
	{
		var cookieStart	=	document.cookie.indexOf(this.name + "=");

		if (cookieStart == -1)
		{
	    	var cookieValue	=	null;
		}
		else
		{
			var valueStart	=	cookieStart + this.name.length + 1
			var valueStop	=	(document.cookie.indexOf(";", valueStart) != -1) ? document.cookie.indexOf(";", valueStart) : document.cookie.length ;
			var cookieValue	=	document.cookie.substring(valueStart, valueStop);
			cookieValue		=	unescape(cookieValue);
		}
		this.value		=	 cookieValue;
		return this.value;
	}

	// Suppression d'un cookie.
	this.Delete	=	function()
	{
		document.cookie = this.name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/";
	}

	// Initialisation de la date durée de vie (en jour) du cookie.
	this.SetLifespan	=	function(daysNumber)
	{
		var expirationDate	=	new Date();
		expirationDate.setTime(expirationDate.getTime() + (1000 * 3600 * 24 * daysNumber));
		this.expirationDate	=	expirationDate;
	}

	// Méthode de débugage.
	this.Debug	=	function()
	{
		alert("cookie name : " + this.name + "\n" 
				+ "Valeur : " + this.Get() + "\n" 
				+ "Date d'expiration : " + this.expirationDate + "\n" 
				+ "Chemin : " + this.path);
	}

	// Appel la méthode contructeur
	return this.Constructor();
}/**
 * Fonction de mise en place du comportement des liens :
 * - liens internes -> ouverture dans la même fenêtre de navigation ;
 * - liens externes -> ouverture dans une nouveau fenêtre.
 * @author : Julien Fredon - imaginance
 */
function linkToButton() {
	
	// Si la fonction createElementNS existe pas, on l'émule.
    if(!document.createElementNS)
    {
        document.createElementNS = function(ns,elt) {
            return document.createElement(elt);
        }
	}

	
	// Parcours des liens du site pour modifier le comportement (ouverture d'un nouveau navigateur)
	// de ceux pointant vers des sites externes.
	var aLinks 	= 	document.getElementsByTagName('a');
	for (var i = 0 ; i < aLinks.length ; i ++) {
		if (aLinks.item(i).className.indexOf('linkToButton') > -1) {
			// Ajout du bouton.
			var XHTMLNS			=	"http://www.w3.org/1999/xhtml";
			var oButton			=	document.createElementNS(XHTMLNS, "input");
			oButton.setAttribute('type','button');
			oButton.setAttribute('value',aLinks.item(i).childNodes.item(0).data);
			oButton.setAttribute('link', aLinks.item(i).href);
			oButton.className	= aLinks.item(i).className;
			if (aLinks.item(i).onclick)
			{
				oButton.onclick		=	aLinks.item(i).onclick;
			}
			var href			=	aLinks.item(i).href;
			
			if (! oButton.onclick)
			{
				oButton.onclick		=	function() {document.location = this.getAttribute('link');};
			}
			

			aLinks.item(i).parentNode.insertBefore(oButton, aLinks.item(i));
					
			// Suppression du lien.
			aLinks.item(i).parentNode.removeChild(aLinks.item(i));
			i	= i - 1;
		}
	}
}
/**
 * Fonction d'ouverture d'un popup centré sur la fenêtre du navigateur (et non par rapport à l'écran !)
 * @author : Julien Fredon @ imaginance
 */
function popupThis(link, iWidth, iHeight, sOptions)
{
	// Récupération de l'url spécifié dans le href du lien.
	sUrl	=	link;
	if (typeof link == "object")
	{
		sUrl	=	link.href;
	}


    // Calcul de la position du popup (centré)
    var screenX;
    var screenY;
    var popupWidth      =   iWidth;
    var popupHeight     =   iHeight;
    if (sOptions == undefined || sOptions == "")
    {
    	sOptions	=	"resizable=yes,scrollbars=yes"
    }
    var options         =   sOptions;

	// Calcul de la position de la fenêtre du navigateur.
    if (window.screenX)	// Pour Mozilla & Co.
    {
        screenX =   window.screenX;
        screenY =   window.screenY;
        screenY =   screenY + 80;
    }
    else // Pour IE & Co.
    {
        screenX =   window.screenLeft;
        screenY =   window.screenTop;
    }

	// Calcul de la position du popup.
    popupTop    =   parseInt((document.documentElement.clientHeight / 2) - (popupHeight / 2) + screenY);
    popupLeft   =   parseInt((document.documentElement.clientWidth / 2) - (popupWidth / 2) + screenX);

	// Spécial Opéra qui considère clientHeight comme la hauteur total du document et non de la fenêtre.
	if (navigator.userAgent.indexOf("Opera") > -1)
	{
		popupTop    =   50 + screenY;
	    popupLeft   =   parseInt((document.documentElement.offsetWidth / 2) - (popupWidth / 2) + screenX);
	}

	// Ajout du parametre renderMode=plopup à l'url
	sUrl		=	sUrl + ((sUrl.indexOf("?") > -1) ? '&' : '?') + "layout=popup";


    // Ouverture du popup.
    oPopup      =   window.open(sUrl, "", "top=" + popupTop + ",left=" + popupLeft + ",width=" + popupWidth + ",height=" + popupHeight + "," + options);
    return false;
}/**
 * ----------------------------------------------------------------------
 * Fonction de validation de formulaire.
 */
var FormValidatorElements	=	new Array();

var FormValidator = {

	// Initialisation du système.
	init:
	function()
	{
		var formsList		=	document.getElementsByTagName("form");
		for (var i = 0; i < formsList.length; i ++) {
    		if (Element.hasClassName(formsList.item(i), "FormValidator"))
			{
				formsList.item(i).onsubmit  =   function() { return FormValidator.validate(this); };
			}
		}
	},

	// Vérification des champs.
	validate:
	function(oForm)
	{
		// Booléen à false si aucune erreur n'a été trouvée dans le formulaire.
		var isError		=	false;

		// Booléen à false si aucun champ n'a pris le focus.
		var isFocus		=	false;

		// Liste des champs traités.
        var fieldsList  =   '';

		// Recherche de tous les champs cachés dont le nom est "FormValidator[]".
		var elementsList  =   oForm.getElementsByTagName("input");
		for(var i = 0; i < elementsList.length; i ++)
		{
            if (elementsList.item(i).getAttribute("type") == "hidden" && elementsList.item(i).getAttribute("name") == 'FormValidator[]')
			{
                var oValidator          =    eval('(' + $F(elementsList.item(i)) + ')');    // JSON roxor
                var validatorFunction   =    eval('this.' + oValidator.check_type);

                if (fieldsList.indexOf('#' + oValidator.field + '#') > -1) {
                    continue;
                }
                fieldsList              =   fieldsList + '#' + oValidator.field + '#';
				FormValidator.cleanError(oValidator);
				if (! $(oValidator.field).disabled && ! validatorFunction(oValidator))
				{
					isError				=	true;
					if (! isFocus) {
						isFocus			=	true;
						try {
						  new Field.focus(oValidator.field);
						  new Field.select(oValidator.field);
						}
						catch(error) {}
					}
					FormValidator.showError(oValidator);
				}
			}
		}
		//document.location.hash	=	"#";     // On se position en haut de page.
		// Aucune erreur : lancement de la fonction FormValidator.onSuccess() si elle existe.
		if (! isError && typeof FormValidator.onSuccess == 'function') {
            FormValidator.onSuccess();
		}
		return (! isError);
	},

	cleanError: function(oValidator)
	{
		// ----------------------------------------------------------------------
		// Remise à "blanc" de l'affichage.
		// ----------------------------------------------------------------------
		// Recherche du conteneur parent pour la suppression du style "error".
		var oParagrapheParent	=	$(oValidator.field).parentNode;
		/*
		while (oParagrapheParent && oParagrapheParent.tagName != 'P') {
			oParagrapheParent	=	oParagrapheParent.parentNode;
		}
		*/
		Element.removeClassName(oParagrapheParent, 'error');

		// Suppression du message d'erreur si celui-ci existe.
		if (oErrorElement = $("FormValidatorError_" + oValidator.field)) {
			Element.remove(oErrorElement);
		}
	},

	// execute
	showError: function(oValidator)
	{
		// Message d'erreur par défault. (deprecated)
		if (oValidator.error_msg == undefined)
		{
			oValidator.error_msg =   "Attention, ce champ est obligatoire et n'a pas été renseigné correctement.";
		}

		// ----------------------------------------------------------------------
		// Mise en avant des erreurs de sasie.
		// Le paragraphe sera mis en avant avec la classe CSS error.
		// Un message d'erreur apparaitra sous le champs.
		// ----------------------------------------------------------------------
		var oParagrapheParent	=	$(oValidator.field).parentNode;
		/*
		while (oParagrapheParent && oParagrapheParent.tagName != 'P') {
			oParagrapheParent	=	oParagrapheParent.parentNode;
		}
		*/
		if (oValidator.error_msg != "")
		{
			new Insertion.Bottom(oParagrapheParent, "<div id=\"FormValidatorError_" + oValidator.field + "\" class=\"error\">" + oValidator.error_msg + "</div>");
 			new Element.addClassName(oParagrapheParent, 'error');
		}
	},


	// ----------------------------------------------------------------------
	// Fonctions "plug-ins"
	// ----------------------------------------------------------------------

	// Validation d'une adresse email.
	isEmail: function(oValidator)
	{
		var fieldValue    =   $F(oValidator.field);
		var oRegExp       =   /^[-_A-Za-z0-9]+(\.[-_A-Za-z0-9]+)*@[-A-Za-z0-9]+(\.[-A-Za-z0-9]+)+$/;
		return oRegExp.test(fieldValue);
	},

	// Validation d'un texte.
	isText: function(oValidator)
	{

	    fieldValue    =   $F(oValidator.field);
	    //alert("#" + oValidator.field + "=" + $F(oValidator.field) + "#" + (fieldValue != ""));
		if (fieldValue != "") {
            return true;
		}
		return false;
	},

	// Validation d'un texte.
	isIdem: function(oValidator)
	{
        field1Value     =   $F(oValidator.field);
        field2Value     =   $F(oValidator.field_comparison);
        if (field1Value != '' && field1Value == field2Value) {
            return true;
        }
		return false;
	},

	// Validation d'une date : format français.
	isDateFr: function(oValidator)
	{
        var fieldValue  =   $F(oValidator.field);
        var oRegExp     =   /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
	    return oRegExp.test(fieldValue);
	},

	// Validation d'un alpha numérique.
	isAlphaNum: function(oValidator)
	{
        var fieldValue  =   $F(oValidator.field);
        var oRegExp     =   /^[0-9a-zA-Z]+$/;
        return oRegExp.test(fieldValue);
	},

	// Validation d'un entier.
	isInteger: function(oValidator)
	{
        var fieldValue  =   $F(oValidator.field);
        var oRegExp     =   /^[0-9]+$/;
	    return oRegExp.test(fieldValue);
	},

	isChecked: function(oValidator)
	{
	    return $(oValidator.field).checked;
	}

}

addEvent(window, "load", FormValidator.init);/**
 * Positionne le libellé d'un champ de formulaire dans le champ en question.
 * Cette fonction ne prend en charge que les champs "input text" et les "textarea".
 * Nécessite la bibliothèque Prototype.
 */
function labelInField(labelId)
{
    // Récupération du libellé et de sa valeur.
    var oLabel  =   $(labelId);
    var sLabel  =   oLabel.firstChild.nodeValue;

    // Récupération du champ de formulaire grace à l'attribut "for" du libellé.
    if (null != oLabel.getAttribute('for')) {
        var oField  =   $(oLabel.getAttribute('for'));
    }
    else if (null != oLabel.getAttribute('htmlFor')) {
        var oField  =   $(oLabel.getAttribute('htmlFor'));  // Bidouille pour IE ... encore
    }
    else {
        return false;
    }

    // Initialisation de la valeur par défaut du champ (c'est le contenu de la l'élément label associé).
    if ($F(oField) == '') {
        oField.value    =   sLabel;
        new Element.addClassName(oField, 'labelIn');
    }

    new Element.hide(oLabel);

    // Sur le focus du champs, on supprime la sélection si c'est le texte initilialisé plus haut.
    oField.onfocus      =   (function(sLabel) { return function() {
        if (this.value == sLabel)    {
            this.value = '';
            new Element.removeClassName(oField, 'labelIn');
        }
    }})(sLabel);

    // Sur la perte du focus, on affiche le label si il n'y a rien de saisi.
    oField.onblur   =   (function(sLabel) { return function() {
        if (this.value == '')    {
            this.value = sLabel;
            new Element.addClassName(oField, 'labelIn');
        }
    }})(sLabel);
}
function onlyJavascript() {
	var aElements	=	document.getElementsByClassName('onlyJavascript');

	for(var i = 0; i < aElements.length; i ++)
	{
		Element.show(aElements[i]);
		aElements[i].style.display	=	'block';
	}
}
addEvent(window, 'load', onlyJavascript);/**
 * ------------------------------------
 * Fonction de pré-chargement d'images.
 * ------------------------------------
 * Pré-charge les images qui sont passées en paramètres.
 * Exemple d'utilisation :
 * preloadImages("/images/img1.jpg", "/images/img2.gif", "http://www.imaginance/logo.png");
 */
function preloadImages()
{
	var aImages			=	new Array();
	for (var i=0; i < preloadImages.arguments.length; i++)
	{
		aImages[i]		= new Image();
		aImages[i].src	= preloadImages.arguments[i];
	}
}/**
 * Fonction de mise en place du comportement des liens :
 * - liens internes -> ouverture dans la même fenêtre de navigation ;
 * - liens externes -> ouverture dans une nouveau fenêtre.
 @author : Julien Fredon @ imaginance
 */
function setLinksBehavior() {
    // Récupération de l'URL du site.
	var urlLocal   =   document.location.protocol + "//" + document.location.host;
	var urlLocal   =   "http://www.allhtml.com";
	var urlLocal2  =   "http://emplois.allhtml.com";
	var urlLocal3  =   "http://formations.allhtml.com";
	var urlLocal4  =   "http://all-html.keljob.com";
	var urlLocal5  =   "http://all-html.kelformation.com";

	// Parcours des liens pour en modifier le comportement (ouverture d'un nouveau navigateur si le lien renvoie sur un autre site web).
	var aLinks 	= 	document.getElementsByTagName('a');
	for (var i = 0 ; i < aLinks.length ; i ++) {
		if (aLinks.item(i).href.substr(0, 7) == "http://" && aLinks.item(i).href.substr(0, urlLocal.length) != urlLocal && aLinks.item(i).href.substr(0, urlLocal2.length) != urlLocal2 && aLinks.item(i).href.substr(0, urlLocal3.length) != urlLocal3  && aLinks.item(i).href.substr(0, urlLocal4.length) != urlLocal4  && aLinks.item(i).href.substr(0, urlLocal5.length) != urlLocal5) {
			aLinks.item(i).onclick   =   function() {
                window.open(this.getAttribute('href'));
                return false;
            };
		}
	}
}
// Exectution de la fonction après le chargement de la page.
addEvent(window, 'load', setLinksBehavior);

// Ne fonctionne qu'avec Mozilla pour le moment.
function experimental_setLinksBehavior() {
    try {
        var externalsLinks      =   document.evaluate('//a[contains(@class,"external")]', document, null, 0, null);
        var link;
        while (link = externalsLinks.iterateNext()) {
            link.onclick        =   function() {
                window.open(this.getAttribute('href'));
                return false;
            };
    	}
    }
    catch(error) {}
}

addEvent(window, 'load', experimental_setLinksBehavior);