/*******************************************************************************************************************************************************************
 * Permet l'affichage d'une boite d'alerte modale customisable
 *******************************************************************************************************************************************************************
 * Params : width = largeur de la boite d'alerte
 *           left = position horizontale (par defaut la boite est centree horizontalement)
 *            top = position verticale (par defaut la boite est centree verticalement)
 *     btnCaption = libellé affiché dans le bouton de validation
 *         onShow = fonction de callback appelee a l'affichage de la boite
 *         onHide = fonction de callback appelee a la fermeture de la boite
 *        onValid = fonction de callback appelee a la validation de la boite (par le bouton par defaut)
 *******************************************************************************************************************************************************************/
var SimpleAlert = new Class(
{
	options:
	{
		width: 300,
		left: -1,
		top: -1,
		btnCaption: "OK",
		onShow: null,
		onHide: Class.empty,
		onValid: null
	},
	initialize: function(options) 
	{
		this.setOptions(options);

		if (this.options.left == -1)
		{
			this.options.left = (window.getWidth() - this.options.width) / 2;
		}
	},
	show: function(title, text, alertContent)
	{
		this._uniqueId = $time();
		
		// calcul du z-index de base pour gerer l'affichage de plusieurs alertes
		// les unes par dessus les autres (_mask + _container)
		var zIndex = parseInt((this._uniqueId + "").substring(4));

		// creation du mask permettant de gerer l'effet modal
		this._mask = new Element("div", { id: "alertMask" + this._uniqueId, "class": "alertMask" });
		this._mask.setStyle("z-index", zIndex);
		this._mask.setStyle("height", (window.getHeight() > window.getScrollHeight()) ? window.getHeight() : window.getScrollHeight());
		this._mask.inject($(document.body));

		// creation du container d'alerte
		this._container = new Element("div", { id: "alertContainer" + this._uniqueId, "class": "alertContainer" });
		this._container.setStyle("z-index", zIndex+1);
		
		// titre de l'alerte
		this._title = new Element("h1", { "html" : title }).inject(this._container);
		// bouton de fermeture
		this._close = new Element("a").inject(this._title);
		this._close.setAttribute("href", "javascript:void(0)");
		this._close.addEvent("click", this.hide.bind(this));

		// message de l'alerte	
		if (text != "")
		{
			new Element("p", { "class": "alertMessage", "html" : text }).inject(this._container);
		}

		// creation du footer
		this._footer = new Element("p", { "class": "alertFooter" }).inject(this._container);

		// creation du container de boutons qui va permettre leur centrage
		this._buttonContainer = new Element("div").inject(this._footer);
	
		// creation du bouton par defaut
		this._button = this.createButton(this.options.btnCaption);
		
		// affectation de l'evenement par defaut au default button (fermeture de l'alerte)
		if (!$defined(this.options.onValid))
		{
			this._button.addEvent("click", this.hide.bind(this));
		}
		// affectation d'un eventuel evenement de validation au default button
		else
		{
			this._button.addEvent("click", this.valid.bind(this));
		}

		// on fixe la largeur et la hauteur de l'alerte
		this._container.setStyle("width", this.options.width + "px");
		this._container.setStyle("left", this.options.left);
		this._container.inject($(document.body));

		// contenu custom affiché en dessous du message
		if ($defined(alertContent) && alertContent != "")
		{
			// il s'agit d'un contenu texte
			if (!alertContent.type)
			{
				new Element("div", { "class": "alertContent", "html" : alertContent }).inject(this._footer, "before");
			}
			// il s'agit d'un contenu "objet" (uniquement iframe pour le moment)
			else
			{
				if (alertContent.type == "iframe")
				{
					var contentIframe = new Element("iframe", { "id": alertContent.id }).inject(this._footer, "before");

					contentIframe.setAttribute("scrolling", "no");
					contentIframe.setAttribute("border", "0");
					contentIframe.setAttribute("frameBorder", "0");
					contentIframe.contentWindow.document.location  = alertContent.location;
					
					contentIframe.addEvent("load", function()
					{
						contentIframe.contentWindow.document.body.setStyle("background-color", "transparent");
					});
				}
			}
		}


		// si le parametre top n'est pas renseigné
		// => centrage verticale de l'alerte
		if (this.options.top == -1)
		{
			var containerH = parseInt(this._container.getStyle("height").replace("px", ""));
			var containerTop = (window.getHeight() - containerH) / 2;
			
			containerTop += window.getScrollTop() - 20;
	
			this._container.setStyle("top", containerTop);
		}

		// permet de gerer le declenchement ou le non declenchement de l'evenement
		// onHide au masquage de l'alerte
		this._noEvent = false;

		// affichage de la boite d'alerte	
		this._container.addClass("visible");

		// appel de la fonction onShow si elle a ete declaree au niveau des options
		if ($defined(this.options.onShow)) this.options.onShow.call();
	},
	createButton: function(aCaption, aPosition)
	{
		// le tmpDiv permet de calculer la largeur du bouton (et au final permettra le centrage du / des bouton(s))
		var tmpDiv = new Element("div", { id : "tmpDiv" }).inject($(document.body));
		tmpDiv.setStyles({ "position": "absolute", "float" : "left", "width" : "auto" });

		// creation du bouton
		var newButton = new Element("a", { "class": "alertButton " + ($defined(aPosition) ? aPosition : "") }).inject(tmpDiv);
		newButton.setAttribute("href", "javascript:void(0)");

		// creation du libelle du bouton
		new Element("span", { "html" : aCaption }).inject(newButton);

		// recuperation de la largeur du _buttonContainer et affectation de la nouvelle largeur
		// pour permettre un bon centrage du / des bouton(s)
		var bcWidth = this._buttonContainer.getStyle("width").replace("px", "");
		if (bcWidth == "" || bcWidth == "auto") bcWidth = 0;

		// affectation de la nouvelle largeur au container de boutons	
		this._buttonContainer.setStyle("width", parseInt(bcWidth) + tmpDiv.offsetWidth + 3);

		// bouton par defaut
		if (!$defined(aPosition))
		{
			newButton.inject(this._buttonContainer);
		}
		// bouton supplementaire
		else
		{
			if (aPosition == "before") { newButton.addClass("before"); newButton.inject(this._button, "before"); }
			if (aPosition == "after") { newButton.addClass("after"); newButton.inject(this._button, "after"); }
		}

		tmpDiv.destroy();

		return newButton;
	},
	addButton: function(aCaption, aPosition, aEvent)
	{
		var newButton = this.createButton(aCaption, aPosition);
		if ($defined(aEvent)) newButton.addEvent("click", aEvent);
	},
	hide: function()
	{
		// appel de la fonction onHide
		if (!this._noEvent && $defined(this.options.onHide)) this.options.onHide.call();

		// suppression du mask permettant de gerer l'effet modal
		if ($("alertMask" + this._uniqueId) != null)
		{
		    $("alertMask" + this._uniqueId).destroy();
		}

		// suppression du container de l'alerte
		if ($("alertContainer" + this._uniqueId) != null)
		{
		    $("alertContainer" + this._uniqueId).destroy();
		}
	},
	hideNoEvent: function()
	{
		this._noEvent = true;
		this.hide();
		this._noEvent = false;
	},
	valid: function()
	{
		this.options.onValid.call();
	}
});
SimpleAlert.implement(new Options);

/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
function SHA1(s)
{
	return binb2hex(core_sha1(str2binb(s),s.length * 8));
}
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 : (t < 60) ? -1894007588 : -899497514;
}
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << 8) - 1;
  for(var i = 0; i < str.length * 8; i += 8) bin[i>>5] |= (str.charCodeAt(i / 8) & mask) << (32 - 8 - i%32);
  return bin;
}
function binb2str(bin)
{
  var str = "";
  var mask = (1 << 8) - 1;
  for(var i = 0; i < bin.length * 32; i += 8) str += String.fromCharCode((bin[i>>5] >>> (32 - 8 - i%32)) & mask);
  return str;
}
function binb2hex(binarray)
{
  var hex_tab = "0123456789ABCDEF";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}
function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);

    for(var j = 0; j < 4; j++)
    {
		if(i * 8 + j * 6 > binarray.length * 32) str += "";
		else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
function CheckNumericData(evt)
{
	var aEvent = evt || window.event;
	var key = aEvent.keyCode || aEvent.which;
	var code = aEvent.keyCode;
	key = String.fromCharCode(key);

	var regex = /[0-9]/;

	var quote = (key == "'");
	if (quote)
	{
		quote = (code == 39);
		if (typeof(aEvent.which) != 'undefined')
		{
			quote = (code == 0 && aEvent.which == 39)
		}
	}
	var dot = (key == '.');
	if (dot)
	{
		dot = (code == 46);
		if (typeof(aEvent.which) != 'undefined')
		{
			dot = (code == 0 && aEvent.which == 46)
		}
	}

	if ((!regex.test(key) && code != 8 && code != 9 && code != 35 && code != 36 && code != 37 && code != 39 && code != 46) || dot || quote)
	{
		if (aEvent.stopPropagation)
		{
			aEvent.stopPropagation();
		}
		else
		{
			aEvent.cancelBubble = true;
		}
		if (aEvent.preventDefault)
		{
			aEvent.preventDefault();
		}
		else
		{
			aEvent.returnValue = false;
		}
	}
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
function GetCookieValue(aCookieName, aKeyName)
{
	var cookieValues = Cookie.read(aCookieName).split("&");
	for (var i = 0; i < cookieValues.length; i++)
	{
		var valueData = cookieValues[i].split("=");
		if (valueData[0] == aKeyName)
		{
			return valueData[1];
			break;
		}
	}
	return "";
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
function IsSet(aVar)
{
	return(typeof(window[aVar]) != "undefined");
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
// ajout d'une fonction de formatage sur l'object String
// similaire dans l'utilisation (dans les grandes lignes) a la fonction .NET
String.format = function()
{
    if (arguments.length == 0)
    {
        return null;
    }

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++)
    {
        var re = new RegExp('\\{' + (i-1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    
    return str;
}
// ajout d'une fonction pour savoir si une chaine de caracteres peut etre consideree
// comme une valeur numerique
String.prototype.isNumeric = function()
{
	var regex = /^\d+$/;
	return regex.test(this);
}

// ajout d'une fonction de troncage (troncature ? :)) sur l'object String
// permet de tronquer n caracteres situes en fin de string
String.prototype.trunc = function()
{
    if (arguments.length == 0)
    {
        return this;
    }
    return this.substring(0, this.length - arguments[0]);
}
// fonction trim (gauche et droite)
String.prototype.trim = function()
{
	return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
// fonction pour hexa encoder une string
String.prototype.hexaencode = function()
{
	var strEnc = "";
	for (var i = 0; i < this.length; i++)
	{
		strEnc += this.charCodeAt(i).toString(16);
	}
	return strEnc;
}
// fonction pour hexa decoder une string
String.prototype.hexadecode = function()
{
	var strDec = "";
	for (var i = 0; i < this.length / 2; i++)
	{
		var asciiCode = parseInt(this.substr(i*2, 2), 16);
		strDec += String.fromCharCode(asciiCode);
	}
	return strDec;
}
// cryptage d'une string en md5
String.prototype.toSHA1 = function()
{
	return SHA1(this);
}
// fonction right classique
String.prototype.right = function()
{
    if (arguments.length == 0 || (arguments.length == 1 && arguments[0] > this.length))
    {
        return this;
    }
	var strLength = this.length;
	
	return this.substring(strLength, strLength - arguments[0]);
}

/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
function GetQueryStringValue(aKey)
{
	aKey = aKey.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]" + aKey + "=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if (qs != null)
	{
		return qs[1];
	}
	return "";
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
/* ---------------------- Functions to scramble links --------------------- */
function selflink()
{
    var l = '';
    for (i = 0; i < arguments.length; i++)
    {
        if (typeof(arguments[i]) == 'string')
        {
            l += arguments[i];
        }
        else if (typeof(arguments[i]) == 'number')
        {
            l += String.fromCharCode(arguments[i]);
        }
    }
    window.location.href = specialescape(l);
}
function selflink_blank()
{
    var l = '';
    for (i = 0; i < arguments.length; i++)
    {
        if (typeof(arguments[i]) == 'string')
        {
            l += arguments[i];
        }
        else if (typeof(arguments[i]) == 'number')
        {
            l += String.fromCharCode(arguments[i]);
        }
    }
    window.open(l);
}
function specialescape(s)
{
    if (s.indexOf('?') == -1)
    {
        var sDomain = "";
        var sQuery = s; // Strip off domain if exists (else we would encode the ':') // There might be port numbers ("http://some.domain.com:8080")! 
        if (s.indexOf("://") != -1) {// 1st slash after the domain = beginning of query string 
        var n = s.indexOf("/", s.indexOf("://")+2);
        if (n > -1)
        {
            sDomain = s.substring(0, n); sQuery = s.substring(n);
        }
    } 
    // Unescape (does nothing if it wasn't escaped, but if it was, we avoid double escaping) 
    /*sQuery = unescape(sQuery); // Escape, so we don't rely on the browser to do this (some IE versions don't!) 
    sQuery = escape(sQuery);*/ // Rejoin with eventual domain 
    s = sDomain + sQuery;
    }
    return s;
} 
/* -------------------------- End scramble functions ------------------------- */
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
function unscramble(aUrl)
{
	newUrl = aUrl;
	if (aUrl.indexOf("javascript:") != -1)
	{
		aUrl = aUrl.substr(aUrl.indexOf('(')+1);
		aUrl = aUrl.substr(0, aUrl.indexOf(')'));
		aUrl = aUrl.replace(/\'/g, "");

		var urlData = aUrl.split(',');
		var newUrl = "";
		for (var i = 0; i < urlData.length; i++)
		{
			if (isNaN(parseInt(urlData[i])))
			{
				newUrl += urlData[i];
			}
			else
			{
				if (urlData[i].length == 2)
				{
					newUrl += String.fromCharCode(urlData[i]);
				}
				else
				{
					newUrl += urlData[i];
				}
			}
		}
	}
	return newUrl;
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
 function RemoveSearchCookie()
{
	document.cookie = "MIXADSEARCH=; path=/; expires=Fri, 02-Jan-1970 00:00:00 GMT";
}
/*******************************************************************************************************************************************************************
 *
 *
 *
 *******************************************************************************************************************************************************************/
 function RemovePostCookie()
{
	document.cookie = "MIXADPOST=; path=/; expires=Fri, 02-Jan-1970 00:00:00 GMT";
}

/********************************************** FORMULAIRE CONTACT AIDE ******************************************************/
function CheckAideContactForm()
{
	var ccForm = $("mxdAideContactForm");

	var ccCivilite = ccForm.cc_civilite;
	var ccEmail = $("ac_email");
	var ccSujet = $("ac_sujet");
	var ccMessage = $("ac_message");

	var emptyField = null;
	var sendForm = true;

	simpleAlert = new SimpleAlert(
	{
		btnCaption: "OK",
		"onValid": function() { simpleAlert.hide(); emptyField.focus(); } 
	});

	// l'adresse e-mail saisie est-elle correcte ?
	if (sendForm)
	{
		var email = ccEmail.value.trim();
		var goodEmail = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/.test(email);
		if (email == "" || !goodEmail)
		{
			sendForm = false;
			emptyField = ccEmail;
			simpleAlert.show("Formulaire de contact", "Merci de vérifier votre adresse email.");
		}
	}

	// un sujet a-t-il etait saisi ?
	if (sendForm && ccSujet.value.trim() == "")
	{
		sendForm = false;
		emptyField = ccSujet;
		simpleAlert.show("Formulaire de contact", "Veuillez renseigner un sujet.");
	}

	// un message a-t-il etait saisi ?
	if (sendForm && ccMessage.value.trim() == "")
	{
		sendForm = false;
		emptyField = ccMessage;
		simpleAlert.show("Formulaire de contact", "Veuillez écrire un message.");
	}

	// tout est ok on peut poster les informations
	if (sendForm)
	{
		return true;
	}
	else
	{
	    return false;
	}
}