document.write('<script type="text/javascript" src="/js/LayerPopIn.js"></script>');

var cufonSiteLocal = cufonSiteLocal ? cufonSiteLocal : "";
localCyrillic  = [
	"hr_HR",
	"cs_CZ",
	"sk_SK",
	"hu_HU",
	"sl_SI"
];


// Notifier
var Notifier = new Class({
	initialize: function (){}
});
Notifier.implement(new Events)
// Singleton
Notifier = new Notifier;


(function (){
	//gestion Resize
	var timerResize;
	window.addEvent('resize', function (){
		$clear(timerResize);
		timerResize = (function(){
			Notifier.fireEvent("onLayoutChangedAndStable");
		}).delay(500);
		Notifier.fireEvent("onLayoutChanged");
	});
})();


Element.extend({
	store : function(sKey, o){
		if (!this.__register) this.__register = {};
		this.__register[sKey] = o;
		return o;
	},
	retrieve : function(sKey){
		return this.__register[sKey];
	},
	// renvoie la css reelement appliquee a l'element (useless ?)
	getCSS: function(sCssRule, btoInt) {
		var strValue = "";
		if(document.defaultView && document.defaultView.getComputedStyle) {
			try{
				strValue = document.defaultView.getComputedStyle(this, null).getPropertyValue(sCssRule);
			}
			catch(e) { strValue = ""; }
		}
		else if(this.currentStyle) {
			try{
				sCssRule = sCssRule.replace(/\-(\w)/g, function (strMatch, p1){
					return p1.toUpperCase();
				});
				strValue = this.currentStyle[sCssRule];
			} catch(e) {
				strValue = "";
			}
		}
		return btoInt ? parseInt(strValue) : strValue;
	},
	
	// permet de facilement recuperer un parametre passe dans l'attribut class sous la form param:'value'
	// si le param est omis, renvoie un hash de tous les param/value present
	// les quotes sont supprimees
	// <div class="msg:'du texte' pos:'first'" id="test"></div>
	// $("test").getCssParam('msg') --> "du texte" 
	// $("test").getCssParam() --> {"msg":"du texte", "pos":"first"} 
	getCssParam: function (param){
		var o = {}, sp;
		this.className.split(" ").each(function (el, i){
			if(/:/.test(el)) {
				sp = el.split(":");
				o[sp[0]] = sp[1].replace(/^'|'$/g, "");
			}
		})
		return param ? o[param] : o;
	},
	
	// pour un element de formulaire renvoie le label imbrique ou associe via l'attribut for, false si pas de label 
	getLabel : function (){ 
		if(!this.form) return false;
		// si element imbrique dans un <label>
		if(this.getParent('label')) return this.getParent('label');
		// 
		var labs = this.form.getElementsByTagName('label');
		for(var i = 0 ; i < labs.length; i++){
			var theFor = labs[i].getAttribute('for') || labs[i].getAttribute('htmlFor');
			if(theFor == this.id) {
				return labs[i];
			}
		}
		return false;
	},
	
	// est-ce que l'element est fils de container?
	isChildrenOf: function(container) {
		if(!container) return;
		for(var n = this; n && n != container; n = n.parentNode);
		return n != null ? true : false;
	},
	
	// renvoie les "Hstyles"
	getHStyle : function(elm) {
		var hStyle = 
			this.getStyle("padding-left").toInt() +
			this.getStyle("padding-right").toInt() +
			this.getStyle("border-left-width").toInt() +
			this.getStyle("border-right-width").toInt();
		return F6.isQuirks ? 0 : hStyle;
	},
	
	// renvoie les "Vstyles"
	getVStyle : function() {
		var vStyle = 
			this.getStyle("padding-bottom").toInt() +
			this.getStyle("padding-top").toInt() +
			this.getStyle("border-top-width").toInt() +
			this.getStyle("border-bottom-width").toInt();
		return F6.isQuirks ? 0 : vStyle;
	},
	
	aria: function (){
		switch(arguments.length){
			case 1: // obj
				for(var r in arguments[0]){
					if(!/role|tabindex/.test(r)) attr = "aria-"+r;
					else attr = r;
					this.setAttribute(attr, arguments[0][r]);
				}
				break;
			case 2: // key, value
				if(!/role|tabindex/.test(arguments[0])) attr = "aria-"+arguments[0];
				else attr = arguments[0];
				this.setAttribute(attr, arguments[1])
				break;
		};
		return this;
	}
});

String.extend({
	substitute: function(object, regexp){
		return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
			if (match.charAt(0) == '\\') return match.slice(1);
			return (object[name] != undefined) ? object[name] : '';
		});
	},
	removeacc: function(){
		// A OPTMISER
		var torem = this;
		torem = torem.split('');
		toremout = new Array();
		toremlen = torem.length;
		var sec = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
		var rep = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
		for (var y = 0; y < toremlen; y++){
			if (sec.indexOf(torem[y]) != -1){
				toremout[y] = rep[sec.indexOf(torem[y])];
			}else{
				toremout[y] = torem[y];
			}
		}
		toascout = toremout.join('');
		return toascout;
	},
	removeponct : function(){
		// A OPTMISER
		var torem = this;
		torem = torem.split('');
		toremout = new Array();
		toremlen = torem.length;
		var sec = ' .-_²';
		var rep = ['','','','',''];
		for (var y = 0; y < toremlen; y++){
			if (sec.indexOf(torem[y]) != -1){
				toremout[y] = rep[sec.indexOf(torem[y])];
			}else{
				toremout[y] = torem[y];
			}
		}
		toascout = toremout.join('');
		return toascout;
	}

});

/* 	Fonction sendTracker pour analytics
*
*	sendTracker(categorie, action, opt_label, opt_value)
*	appelle la fonction gaq_push(['_trackEvent',category, action, opt_label, opt_value)
*	pour les statistiques de visite
*
*	Detail des parametres :
*	category (obligatoire)
*	Cet attribut représente le niveau de regroupement 0 des événements.
*
*	action (obligatoire)
*	Cet attribut est destiné à identifier le type d’action auditée.
*
*	label (optionnel)
*	Cet attribut est destiné à identifier précisément l’action auditée.
*
*	value (optionnel)
*	Cet attribut est destiné à recevoir une valeur à imputer à chaque appel pour les
*	critères précédents.
*
*	Reduit les params en lowercase
*/
function sendTracker(category, action, label, value){
	// On passe tout en lowercase
	var categorie = ""+category || "";
	var options = ""+action || "";
	
	var catPush = categorie.removeacc().toLowerCase();
	var actPush = options.removeacc().toLowerCase();
	
	var optlabPush = "";
	if(label){
		optlabPush = label.removeacc().toLowerCase();
	}
	
	var optvalPush = null;
	if(value){
		if(typeof(value)!='undefined'){
			optvalPush = value;
		}
	}
	if(optvalPush != null && optvalPush != ""){
		if(typeof(optvalPush)!='undefined'){
			optlabPush += " "+optvalPush;
		}
	}

	// On envoie les statistiques
	if(typeof(google_analytics_site_id)!='undefined') {
		//console.log('_trackEvent', catPush, actPush, optlabPush, optvalPush, google_analytics_site_id, _gaq);
		// _gaq push ne prend pas de value : donc on concatene le label avec la value quand elle existe
		_gaq.push(['_trackEvent', catPush, actPush, optlabPush]);
	} else if(typeof netstat_countername != 'undefined') {
		if(netstat_countername.split(".")[1]=="dws") {
			_gaq.push(['_trackEvent', catPush, actPush, optlabPush]);
		}
	}
}

function sendGA(params){
    // On envoie les statistiques
    for(i=1; i<params.length;i++){
    	params[i]=params[i].toLowerCase();
    } 
    _gaq.push(params);
}
// sendTracker avec recuperation de value depuis un elem
function trackCompare(action, label, elem, child, type){
	var children = child || "";
	var typeRecup = type || "innerHTML";
	if(children == ""){
		if(type == "innerHTML"){
			var value = document.getElementById(elem).innerHTML;
		}else{
			var value = document.getElementById(elem).value;
		}
	}else{
		if(type == "innerHTML"){
			var value = document.getElementById(elem).childNodes[children].innerHTML;
		}else{
			var value = document.getElementById(elem).childNodes[children].value;
		}
	}
	sendTracker(action, label, value, "");
}

function trackSearch(action, elem, child, type){
	var children = child || "";
	var typeRecup = type || "innerHTML";
	var value = "";
	if(children == ""){
		if(type == "innerHTML"){
			value = document.getElementById(elem).innerHTML;
		}else{
			value = document.getElementById(elem).value;
		}
	}else{
		if(type == "innerHTML"){
			value = document.getElementById(elem).childNodes[children].innerHTML;
		}else{
			value = document.getElementById(elem).childNodes[children].value;
		}
	}
	sendTracker(action, value, "", "");
}

function executeLocation(link){
	var href = link.href;
	setTimeout(function(){
		document.location = href;
	},250);
}

function sendTrackerHotspot(category, actionfirst, actionlast, label){
	if(typeof customCarVars != "undefined"){
		if(customCarVars && customCarVars.GASubCateg){
			category = category.replace("range-", customCarVars.GASubCateg+"-");
		}
	}
	
	var labelTabsLink = $(document.body).getElements(".blockTabsLinks .tabslink li.current a");
	var labelInter = "";
	if(labelTabsLink.length != 0){
		labelInter += ""+labelTabsLink[0].innerHTML;
	}
	labelInter = "-"+labelInter.trim();
	//console.log("+"+labelInter+"+", labelTabsLink[0]);
	var action = actionfirst+labelInter+"-"+actionlast;
	sendTracker(category, action, label, "");
}

function trackHotspot(category, action, label){
	if(typeof customCarVars != "undefined"){
		if(customCarVars && customCarVars.GASubCateg){
			category = category.replace("range-", customCarVars.GASubCateg+"-");
		}
	}
	sendTracker(category, action, label, "");
}

function sendTracker2(url){
	//console.log(url)
	var vehicule = netstat_countername.split(".")[4];
	var category = "range-"+vehicule;
	var action = "gallery-"+vehicule;
	var label = ""+url;
	
	sendTracker(category, action, label, "");
}

function getCategoryBlocName(){
	if(netstat_countername.split(".")[1]=="dws"){
	    return "car dealer";
	}else{
	    return "corporate";
	}
}

function getConfigContext(){
	if(typeof(modePgr)!='undefined'){
		if(modePgr){
			return "pgr";
		}else{
			return "corporate";
		}
	}
	return "corporate";
}

function sendTrackPrintBtnConfig(modele, text){
	var context = getConfigContext();
	sendGA(['_trackEvent','Configurator-'+modele+'-'+context+'','version-'+modele,text]);
}

function webformSendTrackOpen(nameform, carname){
	var docreferer = document.referrer;
	if(docreferer == "") docreferer = "undefined";
	var url = document.URL;
	var component_list = url.split('/');
	var document_filename = component_list[component_list.length-1];
	var document_filename_splited = document_filename.split('.');
	var filename = document_filename_splited[0];
	filename += (carname && carname != "null") ? carname : "";
	
	var prettyCarName = (carname && carname != "null") ? "-"+carname : "";
//	var namecookie = "webform"+nameform.removeponct()+filename.removeponct();
//	if(!Cookie.get(namecookie)){
//		Cookie.set(namecookie, "viewed", {duration: 0.0035});
		sendTracker('Webforms','Call '+nameform+prettyCarName,docreferer);
//	}
}

function webformSendTrackValid(nameform, carname, referer){
	if(referer && referer != "" && referer != "null"){
		var docreferer = referer;
	}else{
		var docreferer = document.location.pathname;
		if(docreferer == "") docreferer = "undefined";
	}
	/*
	var url = document.URL;
	var component_list = url.split('/');
	var document_filename = component_list[component_list.length-1];
	var document_filename_splited = document_filename.split('.');
	var filename = document_filename_splited[0];
	filename += (carname && carname != "null") ? carname : "";
	*/
	
	var prettyCarName = (carname && carname != "null") ? "-"+carname : "";
	//var namecookie = "webformValidation"+nameform.removeponct()+filename.removeponct();
	//if(!Cookie.get(namecookie)){
		//Cookie.set(namecookie, "viewed", {duration: 0.0035});
		sendTracker('Webforms','Validate  '+nameform+carName,docreferer);
	//}
}

// Detection de la presence du plugin flash
function detectFlash(){
  if( navigator.mimeTypes.length > 0 ){
      return navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin != null;
  }
  else if( window.ActiveXObject ){
      try {
          new ActiveXObject( "ShockwaveFlash.ShockwaveFlash" );
          return true;
      }
      catch( oError ){
          return false;
      }
  }
  else{
      return false;
  }
}

function resetInput(input){
	input.theDefaultValue = input.getAttribute('value');
	input.onfocus = function() {
		if (this.value==this.theDefaultValue) {
			this.value='';
		}
	};
	input.onblur = function() {
		if (this.value=='') {
			this.value=this.theDefaultValue;
		}
	}
	input.onfocus();
}

//Librairie FullSIX adaptee mootools plus fonctions FullSIX
Array.extend({
  reduce : function(fun /*, initial*/) {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    // no value to return if no initial value and an empty array
    if (len == 0 && arguments.length == 1)
      throw new TypeError();

    var i = 0;
    if (arguments.length >= 2)
    {
      var rv = arguments[1];
    }
    else
    {
      do
      {
        if (i in this)
        {
          rv = this[i++];
          break;
        }

        // if array contains no values, no initial value to return
        if (++i >= len)
          throw new TypeError();
      }
      while (true);
    }

    for (; i < len; i++)
    {
      if (i in this)
        rv = fun.call(null, rv, this[i], i, this);
    }

    return rv;
  },
	eachInv: function(fn, bind){
		for (var i=this.length-1;i>=0;i--) fn.call(bind, this[i], i, this);
	}
});

/****
 Global vars
*******/
var IS_IE = document.all && window.print && !window.opera && ( !document.compatMode || /MSIE 6/.test(navigator.userAgent) || (document.compatMode && document.compatMode=="BackCompat"));
var IE_NG = document.all && window.print && !window.opera && /MSIE [7-9]/.test(navigator.userAgent) && document.compatMode && document.compatMode!="BackCompat"; //variable pour IE7 et + si besoin.
var IS_quirks = IS_IE && document.compatMode && document.compatMode=="BackCompat"; // variable qui declare le quirksmode seulement utile pour IE
var heightPropertyToUse = IS_IE ? "height" : "minHeight"; //variable utilisee pour l'alignement en hauteur des elements.
var IS_Webkit = /Konqueror|Safari|KHTML/.test(navigator.userAgent); 

//ajoute la classe hasJS si le JS est active sur le navigateur
document.documentElement.className+=" hasJS";
if (IS_IE) document.documentElement.className+=" IS_IE";


/*******
* Framework : 
* Fonctions necessaires au fonctionnement general. Elles apportent une aide supplementaire pour le developpement d'autres fonctions. Ces fonction sont utilisees par toutes les autres.
*********/
/*function addEvent(elm, event, fn) {
	elm.addEvent(event, fn);
}

function removeEvent(elm, event, fn) {
	elm.removeEvent(event, fn);
}
*/
/* domReadyAddFuncs */
var beforeDomReadyFuncs = [];
function addBeforeDomReady(fn) { beforeDomReadyFuncs.push(fn); }
window.addEvent('domready', function() {
	beforeDomReadyFuncs.each(function(fn) {fn()});
});
var beforeLoadFuncs = [];
function addBeforeLoad(fn) { beforeLoadFuncs.push(fn); }


/* supprime la propagation du click sur un &eacute;l&eacute;ment (le click n'est pas r&eacute;percut&eacute; sur les autres &eacute;l&eacute;ments en dessous du block en question) */
cancelClick = function(e){
	if (window.event){
		window.event.cancelBubble = true;
		return;
	}
	if (e){
		if (e.stopPropagation) {
			e.stopPropagation();
		}
	}
};

function getElementsByClassName(oElm, sTagName, sClassName){
	var aElements = (sTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(sTagName);
	var aReturnElements = new Array();
	sClassName = sClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + sClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i < aElements.length; i++){
		oElement = aElements[i];
		if(oRegExp.test(oElement.className))
			aReturnElements.push(oElement);
	}
	return aReturnElements
};

// getStyle : retourne la valeur d'une propriete CSS appliquee a un element
function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle) {
		try{ 
			strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue(strCssRule); 
		}
		catch(e) { strValue = ""; }
	}
	else if(oElm.currentStyle) {
		try{
			strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
				return p1.toUpperCase();
			});
			strValue = oElm.currentStyle[strCssRule];
		} catch(e) {
			strValue = "";
		}
	}
	return strValue;
};

/*retourne la valeur entiere d'un style*/
function intStyle(oElm, strCSSRule) {
	var val = parseInt(getStyle(oElm, strCSSRule));
	if (isNaN(val)) val=0;
	return val;
};

/* retourne la somme de tous les styles verticaux appliques (border-width+padding) */ 
function getVStyles(elm) {
	return IS_quirks ? 0 : intStyle(elm, "border-top-width")+intStyle(elm, "border-bottom-width")+intStyle(elm, "padding-top")+intStyle(elm, "padding-bottom");
};
function getVMargins(elm) {
	return intStyle(elm, "margin-top")+intStyle(elm, "margin-bottom");
};
function getBMargins(elm) {
	return intStyle(elm, "margin-bottom");
};
function getHStyles(elm) {
	return IS_quirks ? 0 : intStyle(elm, "border-left-width")+intStyle(elm, "border-right-width")+intStyle(elm, "padding-left")+intStyle(elm, "padding-right");
};
//removeClass
function removeClass(element, className) {
	element.className = element.className.replace(new RegExp("\\b"+className+"\\b","g"),"");
};

//addClass
function addClass(element, className) {
	element.className += " " + className;
};

//toggleClass
function toggleClass(element, className, classNameReplace) {
	element.className = element.className.replace(new RegExp("\\b"+className+"\\b","g"), classNameReplace);
};

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		};
	};
	return [curleft,curtop];
};

/* openclose */
function openclose(elm) {
	var par = getParent(elm, {className:"content(show|hide)"});
	par.className.match(/contenthide/) ? toggleClass(par, "contenthide", "contentshow") : toggleClass(par, "contentshow", "contenthide");
	fixColumns();
};

/**********
* $n : objet de parcours du DOM, facile. Les fonctions ne font que les nodes HTML
***********/
var $nodes= {
	/* 	hasAttributes : retourne true si l'element passe en parametre correspond a tous les attributs passes, on peut aussi donner des attributs que l'on ne veut pas, afin de filtrer tous les &eacute;lements
		ex : if (hasAttributes(div, {nodeName:"div", className:"foobar"), {className:"idontwant"} ) doStuff();
		ici on recherche tous les DIV qui on la classe "foobar", mais on ne prend pas ceux qui ont la classe "idontwant" ex : <div class="foobar idontwant"> ne sera pas recupere.
	*/
	hasAttr : function(n, a, not) {
		var re, at;
		if (n.nodeType!=1) return false;
		function check(attr) {
			for (var i in attr) {
				at = (typeof n[i]) !="undefined" ? n[i] : n.getAttribute(i);
				re = attr[i] instanceof RegExp ? re : new RegExp("\\b" + attr[i] + "\\b","i");
				if (!at || !re.test(at)) 
					return false;
			};
			return true;
		};
		if (not && check(not))	return false;
		if (check(a)) return true;
		return false;
	},
	/* getByTagName : equivalent a element.getElementsByTagName, mais compatible avec IE5 et IE5.5 pour l'histoire du "*" */
	getByTagName : function(n, tag) {
		return  (tag=="*") ? (n.all ? n.all : n.getElementsByTagName("*")) : n.getElementsByTagName(tag);
	},
	/* fonction qui retourne le premier element correspondant aux attributs donnes */
	node : function(n, a, not) {
		return $nodes.nodes(n, a, not, true);
	},
	/* fonction qui retourne tous les elements correspondant selon "a" */
	nodes : function(n, a, not, oneNode, arrElms) {
		var aRetElms=[];
		if (!a) a = {};
		if (typeof a == "string") a = {nodeName:a}; //si une chaine de caract&egrave;res pass&eacute;e en param&egrave;tre, cela signifie qu'on ne veut que r&eacute;cup&eacute;rer des tags
		if (a.nodeName && a.nodeName=="*") delete a.nodeName;
		var elms = arrElms || $nodes.getByTagName(n, (a.nodeName || "*"));
		for (var i=0; i<elms.length; i++) {
			var x = elms[i];
			if ($nodes.hasAttr(x, a, not)) {
				if (oneNode) return x;
				else aRetElms.push(x);
			}
		}
		if (oneNode) return null;
		return aRetElms;
	},
	/* childs : retourne tous les noeuds enfants de l'element  */
	childs : function(n, a, not) {
		return $nodes.nodes(n, a, not, false, n.childNodes);
	},
	firstChild : function(n, a, not) {
		return $nodes.nodes(n, a, not, true, n.childNodes);
	},
	lastChild : function(n, a, not) {
		var node = $nodes.nodes(n, a, not, false, n.childNodes);
		return node[node.length-1];
	},
	move : function(n, a, not, action) {
		do {
			n = n[action]; 
			if (n && $nodes.hasAttr(n, a, not)) return n;
		} while (n) 
		return null;
	},
	after : function(n, a, not) { 
		return $nodes.move(n, a, not, "nextSibling");
	},
	before : function(n, a, not) {
		return $nodes.move(n, a, not, "previousSibling");
	},
	parent : function(n, a, not) {
		return $nodes.move(n, a, not, "parentNode");
	}
};
/* fonctions raccourcis */
var getNode = $nodes.node,
	getNodes = $nodes.nodes,
	getChildNodes = $nodes.childs,
	getNextSibling = $nodes.after,
	getPreviousSibling = $nodes.before,
	getParent = $nodes.parent,
	hasAttributes = $nodes.hasAttr,
	getElementsByTagName = $nodes.getByTagName;

/*  ifrlayer : 
	Cette fonction corrige un probleme sous IE6 lorsqu'un layer passe par dessus un select, le select sera toujours au dessus. Pour corriger ce probl&egrave;me.
	ex : 	
		- afficher un bloc : 
			myBlock.style.display='block';
			ifrlayer.make(myBlock); //genere ou affiche l'iframe
		- cacher un bloc :
			myBlock.style.display='none';
			ifrlayer.hide(myBlock); //cache l'iframe associee au bloc
		-deplacer un bloc : 
			myBlock.style.left = "100px";
			ifrlayer.move(myBlock); // deplace l'iframe associee au bloc
*/
var ifrlayer = {
   ie : document.all && window.print && document.getElementById && /MSIE [56]/.test(navigator.userAgent),
   $:function(obj) { return (typeof(obj)=="string" ? document.getElementById(obj) : obj) },
   make:function(obj) {
       obj = ifrlayer.$(obj);
       if(!obj) return;
       if(ifrlayer.ie && !obj.iframelayer) {
           if(obj.parentNode && !obj.iframelayer) var ifr = obj.parentNode.insertBefore(document.createElement("iframe"), obj);
           ifr.src = "javascript:false";
           if(obj.currentStyle.zIndex != "" && parseInt(obj.currentStyle.zIndex)>1 ) {
               ifr.style.zIndex = parseInt(obj.currentStyle.zIndex)-1;
           };
           with(ifr.style) {
               filter = "mask()";
               position = "absolute";
           };
           obj.iframelayer = ifr;
       }
       if (obj.iframelayer) {
           obj.iframelayer.style.visibility = "visible";
           ifrlayer.move(obj,true);
       };
   },
   hide:function(obj){
       obj = ifrlayer.$(obj);
       if(obj && obj.iframelayer) obj.iframelayer.style.visibility="hidden";
   },
   kill:function(obj){
       obj = ifrlayer.$(obj);
       if(obj && obj.iframelayer) {
           obj.iframelayer.parentNode.removeChild(obj.iframelayer);
       };
   },
   move:function(obj, size) {
       obj = ifrlayer.$(obj);
       if(obj && obj.iframelayer) {
           with(obj.iframelayer.style) {
               top = obj.offsetTop+"px";
               left = obj.offsetLeft+"px";
               if (size) {
                   width  =  obj.offsetWidth+"px";
                   height =  obj.offsetHeight+"px";
               };
           };
       };
   }
};
/*css right*/
function cssRight(elm) {
	if (elm.currentStyle.right!="auto") {
		elm.style.right = (parseInt(elm.currentStyle.right)-(elm.parentNode.offsetWidth%2))+"px";
	} else {
		elm.style.right = "auto";
	};
};
/*  addHover :
   Cette fonction ajoute le fonctionnement de la pseudo classe hover en CSS, et seulement pour IE
   Elle se base sur les evenement propres a IE qui sont les evenements qui ont le comportement le plus proche du :hover en CSS.
   Pour utiliser cette fonction il faut le faire en CSS, on peut en plus ajouter en parametre la classe CSS qui sera ajoutee en CSS
   ex :
       #menu ul li {behavior:expression(addHover(this))}
       #menu ul li {behavior:expression(addHover(this, "maclassehover"))}
       Afin de ne pas prendre en compte IE7 en mode strict il suffit de placer la classe .IS_IE avant, cette classe est ajoutee pendant le chargement de la page.
       .IS_IE #menu ul li {behavior:expression(addHover(this))}
*/
function addHover(elm, className, iframeTag) {
	className = className || "hover";
	elm.style.behavior = " "; //reecriture du style behavior
	elm.hoverClassName = className;
	if (iframeTag) {
		elm.iframeElm = getNode(elm, iframeTag);
	};
	elm.onmouseenter = function() {
	   this.className+= ' ' + this.hoverClassName;
	   if (this.iframeElm) ifrlayer.make(this.iframeElm);
	};
	elm.onmouseleave = function() {
	   this.className = this.className.replace(new RegExp("\\b" + this.hoverClassName + "\\b", "g"),"");
	   if (this.iframeElm) ifrlayer.hide(this.iframeElm);
	};
};


/****************
* Validation de formulaires
******************/
var formval={
	defaultErrorMessage:"Ce champ est erron\u00E9",
	defaultPosition:"beforefield",
	globalErrorMsg : "",
	callbackfunctions : function() {
		//fixColumns();
		if (popLayer.pop) popLayer.resize();
	},
	lineInput : {nodeName:"(div|p|li)"},
	validationFunc:{
		required:function(field) {
			var returnMessage=true;
			switch(field.type) {
				case "text":
				case "file":
				case "password":
				case "textarea":
					if (field.value=="") returnMessage="text";
					break;
				case "checkbox":
				case "radio":
					var sameElt = formval.getSameElements(field);
					var onecheck=false;
					for (var i=0; i<sameElt.length; i++) {
						if (sameElt[i].checked)
							onecheck=true;
					}
					if (!onecheck) returnMessage=field.type;
					break;
				case "select-one":
				case "select-multiple":
					if(field.selectedIndex==0) 
						returnMessage="select";
					break;
			}
			return returnMessage;
		},
		email:function(field) {return (field.value=="" || !!field.value.match(/^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}$/));},
		validateNvehicule:function(field) {return (field.value=="" || !!field.value.toUpperCase().match(/^[a-zA-Z]{2}[a-zA-Z0-9]{15}$/));},
		nspecialcharacters:function(field) {return (field.value=="" || !!field.value.match(/^[a-zA-Z0-9]+$/));},
		name:function(field) {return (field.value=="" || !!field.value.match(/^([a-zA-Z]|\s|\'|\.|\-)+$/));},
		pseudo:function(field) {return !!field.value.match(/^[a-zA-Z0-9_\-]{3,20}$/);},
		image:function(field) {return (field.value=="" || !!field.value.match(/^.+\.(gif|jpe?g|png)$/));},
		codepostal:function(field){return !!field.value.match(/\d{5}/);},
		cpordep:function(field){if (field.value=="") return true; return !!field.value.match(/\d{2}(\d{3})?/);},
		phonenumber:function(field){if (field.value=="") return true; return !!field.value.match(/^\d{10}$/);},
		phonenumber2:function(field){
			var val = field.value;
			if (val=="") return true; 
			var cleanNum = val.match(/(\+)?\d+/g)
			if (!cleanNum) return false;
			cleanNum = cleanNum.join(""); //on recupere le numero de telephone en version nettoyee.
			if (!cleanNum.match(/^\+?(33|033|0033)0?[1-9]\d{8}$/)) return false; //on checke reelement le numero de telephone
			return !!val.match(/^(\d|\s|-|\.|\\|\/|_|\+)+$/); //on check si des caract&egrave;res autres que chiffes,-,+,.,_,/,\  sont pr&eacute;sents
		},
		date:function(field) {
			if (field.value=='') return;
			var dateSplit = field.value.split('/');
			var date = new Date(dateSplit[2], parseInt(dateSplit[1])-1, dateSplit[0]);
			if (date.getDate()!=dateSplit[0] || date.getMonth()!=parseInt(dateSplit[1])-1 || date.getFullYear()!=dateSplit[2]) {
				return false;
			}
			return true;
		},
		dateMax:function(field) {
			if (field.value=='') return;
			var dateSplit = field.value.split('/');
			var date = new Date(dateSplit[2], parseInt(dateSplit[1])-1, dateSplit[0]);
			return !(date.getTime()>new Date().getTime())
		},
		dateMin:function(field) {
			if (field.value=='') return;
			var dateSplit = field.value.split('/');
			var date = new Date(dateSplit[2], parseInt(dateSplit[1])-1, dateSplit[0]);
			var currentDate = new Date();
			if (date.getMonth()==currentDate.getMonth() && date.getDate()==currentDate.getDate())
				return true;
			return (date.getTime()>new Date().getTime())
		},
		dateNaissanceSeparate : function(field) {
			if (field.value=='') return;
			var day = field.value;
			var month = $(field.getAttribute('dateNaissanceSeparate_month')).value;
			var year = $(field.getAttribute('dateNaissanceSeparate_year')).value;
			var date = new Date(year, month-1, day);
			if (date.getDate()!=day ||  date.getMonth()!=month-1 ||  date.getFullYear()!=year)
				return false;
			else 
				return true;
		},
		numbers:function(field){if (field.value=="") return true; return !!field.value.match(/^\d+$/);},
		kilometers:function(field){
			var val = field.value.replace(/ /g, '');
			if (val=="") return true; return !!val.match(/^\d+$/);
		},
		decimal:function(field){if (field.value=="") return true; return !!field.value.match(/^\d+([.,]\d+)?$/);},
		equalsto:function(field) {
			var equalsFieldId = field.getAttribute("equalsto");
			var equalsField = document.getElementById(equalsFieldId);
			return (field.value==equalsField.value);
		},
		minimum:function(field) {
			if (field.nodeName!="FIELDSET") return true;
			var minNum = field.getAttribute("minimum_num") || 1;
			var properties = field.getAttribute("minimum_field") || "text,femail";
			var properties = properties.split(/,/g);
			var inputs = field.getElementsByTagName("input");
			var counter = 0;
			for (var i=0; i<inputs.length; i++) {
				var x=inputs[i];
				if (x.type==properties[0] && new RegExp(properties[1]).test(x.name) && x.offsetHeight>0) {
					if (formval.validationFunc["required"](x)===true) {
						counter++;
					};
				};
			};
			return counter<minNum ? ([false,minNum]) : true;
		},
		requiredexclusif:function(field) {
			var reqExclusifField = document.getElementById(field.getAttribute("reqexclusiffield"));
			if (!reqExclusifField) {
				alert("Vous n'avez pas associe le bon champ, verifiez l'attribut reqexclusif");
				return false;
			};
			if (field.getAttribute("requiredexclusifcondition")) {
				if (field.getAttribute("requiredexclusifcondition")=="noempty") {
					if (field.value!="" || reqExclusifField.value!="") return true;
					else return false;
				};
			} else 
				if ((field.value=="" && reqExclusifField.value=="") || (field.value!="" && reqExclusifField.value!="") ) return false;
		}
	},
	errorMessages:{
		required:{
			checkbox:"Cette case doit \u00EAtre coch\u00E9e",
			radio:"Vous devez s\u00E9lectionner une de ces options",
			text:"Attention, ce champ est obligatoire",
			select:"Vous devez s\u00E9lectionner l'objet de votre demande"
			
		},
		requiredoptional:this.required,
		email:"Cette adresse e-mail est erron\u00E9e",
		name:"Ce champ ne doit comporter que des lettres, et les caract&egrave;res suivants : '-",
		numbers:"Ce champ ne doit comporter que des chiffres",
		decimal:"Ce champ ne doit comporter que des chiffres",
		phonenumber:"Ce champ ne doit comporter que des chiffres",
		phonenumber2:"Veuillez v\u00E9rifier votre num\u00E9ro de t\u00E9l\u00E9phone",
		equalsto:"Ce champ doit &ecirc;tre identique au pr&eacute;c&eacute;dent",
		codepostal:"Ce code postal est invalide",
		cpordep:"Vous ne pouvez mettre qu'un num\u00E9ro de d\u00E9partement ou un code portal",
		pseudo:'Attention, votre pseudo doit contenir uniquement 20 caract&egrave;res, des lettres et des num\u00E9ros et les signes "_" et "-"',
		image:"Votre fichier n'est pas au bon format",
		minimum:"Vous devez remplir au moins ## champ",
		date:"La date est erron\u00E9e ou n'est pas au format JJ/MM/AAAA",
		dateMax:"La date doit &ecirc;tre inf&eacute;rieure &agrave; la date en cours",
		requiredexclusif:"Vous devez remplir au moins un des champs",
		dateNaissanceSeparate:"La date est invalide",
		nspecialcharacters:"Ce champ est invalide",
		validateNvehicule:"Ce champ est invalide"
	},
	getMessagePosition:function(field){
		var element=field;
		var position="";
		if (field.getAttribute("position")) {
			var position = field.getAttribute("position");
			if (!position.match(/^(before|after)(label|parentnode|field)$/)) {
			 	position = formval.defaultPosition;
			}
			var arrPos = position.match(/^(before|after)(label|parentnode|field)$/);
			switch(arrPos[2]) {
				case "label" : 
					var node = field;
					while(node.nodeName!="LABEL") {
						node=node.previousSibling;
					};
					if (node.nodeName=="LABEL") element=node;
					break;
				case "parentnode" : 
					var parentPos = field.getAttribute("parentnode_pos") ? parseInt(field.getAttribute("parentnode_pos")) : 1;
					var element=field;
					for (var i=0; i<parentPos; i++) {
						element=element.parentNode;
					};
					break;
			};
			return [arrPos[1],element];
		} else {
			return [formval.defaultPosition.match(/(before|after)(label|parentnode|field)/)[1],element]
		};
	},
	getSameElements:function(field) { //return an array of elements in form who have same nodeName, name and type
		var aReturnElements=[];
		var elt=field.form.elements;
		for (var i=0; i<elt.length; i++) {
			if (elt[i].nodeName==field.nodeName && elt[i].name==field.name && elt[i].type==field.type) {
				aReturnElements.push(elt[i]);
			};
		};
		return aReturnElements;
	},
	check:function(theForm, showOnlyOneMessage, otherReturnValues) {
		formval.globalErrorMsg = "";
		var scrollTop = document.body.scrollTop;
		var finalErrorMessage="";
		var hasError=false;
		var elm = theForm.elements;
		for (var i=0; i<elm.length; i++) {
			var x=elm[i];
			if (x.getAttribute("validation") && x.offsetHeight && x.offsetHeight>0) {
				var validOptions = x.getAttribute("validation").split(/\s+/g);
				finalErrorMessage="";
				for (var j=validOptions.length-1; j>=0; j--) {
					if (typeof(formval.validationFunc[validOptions[j]])=="function") {
						var returnMessage = formval.validationFunc[validOptions[j]](x);
						var quantity = typeof(returnMessage)=="object" && returnMessage.length ? returnMessage[1] : 0;
						returnMessage = typeof(returnMessage)=="object" && returnMessage.length ? returnMessage[0] : returnMessage;
						if (returnMessage==false || typeof(returnMessage)=="string") { //si message erreur ou index de tableau associatif
							hasError=true;
							if (x.getAttribute(validOptions[j]+"_em")!=null) { //si le champ possede un message personnalis&eacute; pour l'erreur alors on affihce
								finalErrorMessage=x.getAttribute(validOptions[j]+"_em");
							} else { //sinon
								if (typeof(returnMessage)=="string") { //si le message d'erreur est un index de tableau associatif
									finalErrorMessage=formval.errorMessages[validOptions[j]][returnMessage]; //on va chercher le message associ&eacute; &agrave; cet index
								} else {
									if (formval.errorMessages[validOptions[j]] && typeof(formval.errorMessages[validOptions[j]])=="string") { //si le message d'error est false
										finalErrorMessage=formval.errorMessages[validOptions[j]]; //alors on retourne le message d'erreur associ&eacute;
										if (quantity>0) finalErrorMessage=finalErrorMessage.replace(/\#\#/g,quantity);
									}
									else finalErrorMessage=formval.defaultErrorMessage; //sinon on affiche le message d'erreur par d&eacute;faut pour tout champ
								};
							};
						} else {
							formval.clearMessage(x);
						};
					};
				};
				if (finalErrorMessage!="") formval.showMessage(x, finalErrorMessage);
			};
		};
		document.body.scrollTop=scrollTop;
		var secondErrorValue=false;
		if (otherReturnValues!=null) {
			if(typeof(otherReturnValues)=="boolean") {
				secondErrorValue=!otherReturnValues;
			} else {
				for (var i=0; i<otherReturnValues.length; i++) {
					if (!otherReturnValues[i]) secondErrorValue = true;
				};
			};
		};
		
		hasError = hasError || secondErrorValue;
		if (showOnlyOneMessage) {
			if (showOnlyOneMessage==true) {
				elm = null;
			} else {
				var elm = document.getElementById(showOnlyOneMessage);
			}
			if (hasError) {
				//elm.className+=" errorAlertShow";
				alert(formval.globalErrorMsg);
			} else {
				if (elm) elm.className=elm.className.replace(/\berrorAlertShow\b/g,"");
			};
		};
		formval.callbackfunctions();
		//popLayer.fixSize();
		return (!hasError); //return true si aucune erreur sinon false;
	},
	checkIfErrorMessageBefore:function(field) {
		var node = field;
		var i=0;
		while(node.previousSibling && i<=2) {
			if (node.nodeType==1 && node.className.match(/\berrormsg\b/))
				return node;
			node=node.previousSibling;
			i++;
		};
		return null;
	},
	clearMessage:function(field) {
		if (field.getAttribute("typemessage") && field.getAttribute("typemessage")=="aspect") {
			if (field.getAttribute("rel") && field.getAttribute("rel")!="") {
				var elm = document.getElementById(field.getAttribute("rel"));
				elm.className = elm.className.replace(/\berror\b/g,"");
			};
		} else {
			if (field.associatedErrorMessage) {
				field.associatedErrorMessage.style.display="none";
			};
		};
	},
	insertAfter:function(parent, nodeToInsert, nodeInDom) {
		var node = parent.insertBefore(nodeToInsert, nodeInDom);
		parent.insertBefore(nodeInDom, nodeToInsert);
		return nodeToInsert;
	},
	showMessage:function(field, msg) {
		formval.globalErrorMsg += "- " + msg + "\n";
		if (field.getAttribute("typemessage") && field.getAttribute("typemessage")=="aspect") {
			if (field.getAttribute("rel") && field.getAttribute("rel")!="") {
				var elm = document.getElementById(field.getAttribute("rel"));
				elm.className+=" error";
			}
		} else {
			if (!field.associatedErrorMessage) {
				if (!formval.checkIfErrorMessageBefore(field)) {
					var pos = formval.getMessagePosition(field);
					var parentField = getParent(field, formval.lineInput);
					var msgField = formval.insertAfter(parentField.parentNode, document.createElement("span"),parentField);
					
					/*if (pos[0]=="before") {
						var msgField = pos[1].parentNode.insertBefore(document.createElement("span"),pos[1]);
					} else {
						var msgField = formval.insertAfter(pos[1].parentNode,document.createElement("span"),pos[1]);
					}*/
					msgField.className="errormsg";
					field.associatedErrorMessage=msgField;
				} else {
					field.associatedErrorMessage = formval.checkIfErrorMessageBefore(field);
				};
			};
			field.associatedErrorMessage.innerHTML=msg;
			field.associatedErrorMessage.style.display="";	
			//<span class="errormsg">Attention, ce champ est obligatoire</span>
		};
	}
};

/* addFormActions */

/* Add maxlength on textareas */
function maxLengthOntextarea() {
	var container = document.body;
	var textareas = container.getElementsByTagName("textarea");
	for (var i=0; i<textareas.length; i++) {
		var x= textareas[i];
		if (x.getAttribute("maxlength")) {
			$(x).addEvent("keyup", checkMaxlength);
			$(x).addEvent("keydown", checkMaxlength);
			$(x).addEvent("blur", checkMaxlength);
		};
	};
};
function checkMaxlength(e) {
	var maxL = parseInt(this.getAttribute("maxlength"));
	if (this.value.length>maxL) {
		this.value=this.value.substr(0,maxL);
		this.scrollTop = this.scrollHeight;
	};
};
/* /maxlength */


function formInput(inputId, attributes) {
	var inp = document.getElementById(inputId);
	if (!inp) return;
	for (var i in attributes) {
		inp.setAttribute(i,attributes[i]);
	};
};

//function initFormInputs() {
/*
	formInput("champemail", { validation : "required email", email_em : "Cette email n'est pas bon", type_message : aspect};
	formInput("champ", { validation : "required"};
*/
//}
//addEvent(window, "load", initFormInputs);


/* inputValue : function
	Permet de mettre le texte par defaut d'un champ de type texte.
*/ 
function inputValue(elm, state) {
	elm.oldValue=elm.value;
	elm.onfocus=function() {
		if (!this.isChecking && this.value==this.oldValue) this.value='';			
	}
	elm.onblur=function() {
		if(this.value=='') this.value=this.oldValue;
	}
	if (!elm.isChecking) elm.onfocus();
};

function forceCheck(elm, linkedInput) {
	linkedInput = typeof linkedInput=="string" ? document.getElementById(linkedInput) : linkedInput;
	linkedInput.checked = elm.checked;
};

/* generates corners and others elements if needed */
function generateElements(parent, stringClasses) {
	var i, x;
	parent = (typeof parent == "string") ? document.getElementById(parent) : parent;
	var content = parent || document.body;
	var div = content.getElementsByTagName("div");
	
	//recupere un node avec la class blockInsideParDefaut
	function getIsd(node, className) { return getNode(node, {className: (className || "blockInside")})};
	
	// fonction de creation d'un coin (b avec className) 
	function nc(clN) {var b = document.createElement("b");b.className=clN;return b;};
	
	//ajoute un element ou une liste d'elements (c) sur l'element x
	function add(x, c) {
		var i=0; if (!x) return; 
		if (c.length) for (i=0; i<c.length; i++) x.appendChild(c[i].cloneNode(true));
		else x.appendChild(c.cloneNode(true));
	};
	
	//-- creation des elements qui seronts clones --
	var corners = [nc("tl"), nc("tr"), nc("bl"), nc("br")]; //corners 
	var shadow = nc("specialShadow"); add(shadow, [nc("lt"), nc("rt"), nc("trame")]); // specialShadow
	var overtl = nc("overtl"); // overtl : coin arrodis supplementaire pour les blocks avec des bordures speciales
	
	// -- creation des coins ou autres elements -- 
	// parcours des divs pour leur rajouter les corners
	for (i=div.length-1; i>=0; i--) {
		x=div[i];
		if (!x.alreadyProcessed) {
			x.alreadyProcessed = true;	
			initOtherBlocks(x); // fonction d'initialisation d'autres blocks
		}
	}
	//fixColumns();
};
/* initOtherBlocks() : fonction rajoute d'autres fonctionnalites sur differents blocks  (toggle, onglets),
   Cette fonction est forcement lancee depuis generateElements, et cela evite de faire une deuxieme passe sur les divs de la page
 */
function initOtherBlocks(x) {
	// block a onglets
	if (x.className.match(/\bblockTabs(Sub)?\b/)) //block d'onglets en general (gere tous types d'onglets).
		tabs.init(x);
	if (x.className.indexOf("blockToggle")!=-1) //block ouvert/ferme
		toggleBlock.init(x);
	if (x.className.indexOf("scrollH")!=-1)  //block de scroll horizontal
		scroll.init(x);
	if (x.className.match(/\bline\b/)) //si ligne de block, on la stocke dans un tableau
		linesOfBlocks.push(x);
};

/******* 
* Tabs
 *******/
var tabs = {
	init : function(elm) {
		if ($(elm).hasClass("preventTabBehavior")) {
			return;
		}
		var ul = getNode(elm, {nodeName:"ul"});
		if (!ul) return;
		var a = ul.getElementsByTagName("a");
		for (var i=0; i<a.length; i++) {
			if (!hasAttributes(a[i], {className:"nochange"}))  {
				var exonclick = a[i].onclick || function(){};
				$(a[i]).exOnclick = exonclick;
				a[i].onclick = function() {
					$(this).exOnclick();
					tabs.change(this);
					return false;
				};
			};
			tabs.size(a[i], ul);
		};
	},
	size : function(a, ul) {
		if ($(ul).hasClass("noresize")) return;
		a.style[heightPropertyToUse] = a.offsetHeight + (ul.offsetHeight-a.offsetHeight) - getVStyles(a) - getVMargins(a) - getVMargins(a.parentNode) - getVStyles(a.parentNode)+ "px";
	},
	change : function(elm) {
		var i, n, tabs, ul, li, body, tabCtns, current=0, block, onclick="";
		ul = getParent(elm, {nodeName:"ul", className:"tabs(Big|Sub)?"});
		li = getParent(elm, {nodeName:"li"});
		tabs = ul.getElementsByTagName("li");
		block = getParent(ul, {nodeName:"div", className:"blockTabs(Sub)?"});
		
		// get What is the index of the new Tab and remove otherClass "current"
		for (i=0; i<tabs.length; i++) {
			if (tabs[i]==li) {
				current = i;
				addClass(li, "current");
			} else 
				removeClass(tabs[i], "current");
		};
		//get the tabCtn blocks, and show the contentTab that is match with clicked tab
		body = getNode(block, {nodeName:"div", className:"body"});
		tabCtns = getChildNodes(body, {nodeName:"div", className:"tabCtn"});
		for (i=0; i<tabs.length; i++) {
			n = tabCtns[i];
			removeClass(n, "tabCurrent");
			if (i==current) {
				addClass(n ,"tabCurrent");
			};
		};
		fixHeights(block);
		sizeBlocks(block);
		galleryScroller();
		
	}
};

/*********
* pngTrans :  affichage de png transparents
ex:
.monImage{ background:no-repeat left top; etc; etc; filter:expression(pngTrans(this))  }
**********/
function pngTrans(elm) {
   if (/MSIE [56]/.test(navigator.userAgent)) {
       var imgurl = elm.currentStyle.backgroundImage.match(/url\((.*)\)/);
       if (imgurl) {
            imgurl = imgurl[1].replace(/[\"\']/g,"");
			elm.style.backgroundImage="none";
			elm.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='crop' enabled='true',src='"+imgurl+"')";
       } else {
           elm.style.filter=" ";
       }
   } else {
       elm.style.filter=" ";
   }
};
/*********
recuperer les hauteurs et largeurs naturelles des images 
**********/
function getNaturalHeight(img) {
     if( img.naturalHeight ) {
         return img.naturalHeight;
     } else {
         lgi = new Image();
         lgi.src = img.src;
         return lgi.height;
     };
 };
function getNaturalWidth(img) {
     if( img.naturalWidth ) {
         return img.naturalWidth;
     } else {
         lgi = new Image();
         lgi.src = img.src;
         return lgi.width;
     };
 };
/*********
* ToggleBlock :  block qui s'ouvre et qui se ferme
**********/
var toggleBlock = {
	init : function(elm) {
		var head = getNode(elm, {className:"templateHead"}) || getNode(elm, {className:"head"});
		var line = getParent(elm, {nodeName:"div", className:"line"});
		var aToggle = getNode(head, {nodeName:"a", className:"toggle"});
		var divToggleHead = getNode(head, {nodeName:"div", className:"toggleHead"});
		
		var toggles = $$('.blockToggle');
		// test d'un parametre togl=x dans l'url afin de forcer l'ouverture d'un toggle en particulier et de refermer ceux qui sont ouverts dans la jsp
		var qString = document.location.search;
		var toUse = qString.substr(1,qString.length);
		var duos = toUse.split('&');
		var number = 0;
		var param = false;
		duos.each(function(duo){
			var array = duo.split('=');
			if (array[0]=='togl'){
				param = true;
				number = array[1].toInt();
			}
		});
		number = number - 1;
		if ((number > 0 || number < toggles.length) && param){
			toggles.addClass('toggleClosed');
			toggles[number].removeClass('toggleClosed');
		}
		
		if (head){
			if( line && ($(line).hasClass('escHome') || aToggle )){
				var a = aToggle;
			}else{
				var a = getNode(head, {nodeName:"a"});
			}
		}
		
		if (divToggleHead){
			var a = divToggleHead;
		}
		
		if (a)
			$(a).prevOnclick = a.onclick || "null";
			a.onclick = function() {
				if($(this).prevOnclick != "null")
					$(this).prevOnclick();
				toggleBlock.toggle(this);
				return false;
			}
	},
	// ajout les fonctionnalites du open/close (toggle);
	toggle : function(elm) {
		elm.blur();
		var scrollTop = document.body.scrollTop;
		var block = getParent(elm, {nodeName:"div", className:"blockToggle"});
		window[(hasAttributes(block, {className:"toggleClosed"}) ? "remove" : "add")+"Class"](block, "toggleClosed"); //addClass or RemoveClass
		fixHeights(block); //fixColumns();
		document.body.scrollTop = scrollTop;
	}
};


/**************
* sizeBlocks : alignement des blocks en hauteurs
**************/
 var setGradient = function(unit){
	var getGradient = function(block){
		var height = parseInt(block.offsetHeight);
		if (height > 50 && height < 200){
			return 'Small';
		}else if (height > 200 && height < 300){
			return 'Large';
		}else {
			return 'Medium';
		}
	}
	var blocks = $(unit).getElements('.block');
	blocks.each(function(block){
		if (block.hasClass('blockFilledUniverse'))
			block.addClass('gradient' + getGradient(block));
	})
}



var linesOfBlocks=[];
function sizeBlocks(parentBlock) {
	function size(block, size){
		if (block){
			var blockMargins = 0;
			var body = block.className.match(/\bblock\b/) ? getNode(block, {nodeName:"div", className:"body"}) : block; //si on a une line ou bien un block
			if (body){
				var total = body.offsetHeight + size - getVStyles(body) - blockMargins;
				body.style[heightPropertyToUse] = total>0?total+"px":0+"px";
			};
		};
	};
	linesOfBlocks.eachInv(function (line) { //les lignes fournies sont
		var units = getChildNodes(line, {className:"unit"});
		units.each(function(unit) {
			var blocks = getChildNodes(unit, {className:"block"}, {className:"(noresize|clientRightBox)"});
			var blockFilledUniverse = getChildNodes(unit, {className:"block"}, {className:"(blockFilledUniverse)"});
			var sizeToApply = line.offsetHeight-unit.offsetHeight;
			var sizePerBlock = parseInt(sizeToApply/blocks.length);
			blocks.each(function(block) {
				size(block, sizePerBlock, (blocks.getLast()==block) );
			});
			//sur une division on tombe parfois sur un calcul pas precis, on resize le dernier element d'un unit, afin que le calcul soit correct
				if($(unit).getElement('.block') && !$(unit).getElement('.block').hasClass('blockFilledUniverse')) return; 
				if (blocks.length>1) size(blocks.getLast(), line.offsetHeight-unit.offsetHeight);
				setGradient(unit);
		});
	});
};



/***************
/* Height des blocks (ajout class gradient) 
****************/




/***************
* fixColumns()
****************/



function fixHeights(block) {
	if (IS_IE) {
		var array = block ? getNodes(block, {nodeName:"b", className:"tr|bl"}) : CSSHeightCorners;
		array.eachInv(function() {
			this.style.height="";
		});
	}
};



function showAndHide(field) {
	var allFields = getNodes(field.form, {name:field.name}, null, false, field.form.elements);
	allFields.each(function(field) {
		var elm = document.getElementById(field.value);
		elm.style.display = this.checked ? "block" : "none";
	});
	fixHeights(field);
};

/***********
* Init
************/
/* Fonction d'initialisation des couleurs */
function createColorSteps(color,steps){
	    function colorStep(color,steps)  {
            var originalColor = new Color(color);
            var brighterColor = getBrighterColor(originalColor);
				var rTable = [];
				steps = steps-1;
				
            function getBrighterColor(hexColor) {
                var c = new Color(hexColor);
                c = c.setSaturation(10);
                c = c.setBrightness(95);
                return c;
            }
            function setNow(index,i) {
                    return Math.round((originalColor[index]*i+(steps-i)*brighterColor[index])/steps);
            }
            steps.times(function(i) {
                rTable.push([setNow(0,i),setNow(1,i),setNow(2,i)]);
            });
				rTable.push(originalColor);
            return rTable;
    }
    //First argument is the color you start with
    //Second argument is the number of steps you want
	var uls = $$('ul.universList');
	if(uls[0]) {
		uls.each(function(ul){
			var lis = ul.getElements('li.gradient');
			if(lis.length == 0){
				return;
			};
			lis[0].setStyle('background-color', '')
			var gradient = colorStep(lis[0].getStyle('background-color'),lis.length);
			lis.each(function(item,index) {
				item.setStyle('backgroundColor',gradient[index]);
			});
		});
	};
};


/* Fonction d'accordeon sur liste */

function accordeon(){
	var equipement = $('equipement');
	if (equipement){
	
	
		var links = equipement.getElements('a.atStart').addEvent('click',function(e) {
			new Event(e).stop();
		});
	
		var lis = $(equipement).getElements('ul.universList li');
		var divs = $(equipement).getElements('div.precisions');
		var qString = document.location.search;
		var toUse = qString.substr(1,qString.length);
		var duos = toUse.split('&');
		var number = 0;
		duos.each(function(duo){
			var array = duo.split('=');
			if (array[0]=='eqpt'){
				array[1].toInt() > 0 && array[1].toInt() <= lis.length ? number = array[1].toInt() - 1 : number = 0;
			}
		});

		new Accordion('a.atStart', 'div.atStart', {
			opacity: false,
			display: number,
			onActive: function(toggler, element){
				toggler.getParent().addClass('open');
				lis.each(function(li, i){
					if(li == toggler.getParent()){
						divs[i].addClass('selected');
					}else{
						divs[i].removeClass('selected');
					}
				})
			},
			onBackground: function(toggler, element){
				toggler.getParent().removeClass('open');
			}
		}, $(equipement));
	};
};

//fonction slidingNav
var slidingNav = new Class({
	initialize : function(element){
		this.bool = false;
		this.effectDuration = 300;
		this.closingDelay = 2000;
		this.base = $('page');
		this.container = $('body');
		this.element = element;
		//this.mode2 = 
		
		
		this.clone = this.createEnhancedClone();
		this.element.remove();
		this.element = this.clone;
		
		this.target = $('slidingNav'); // Safari 2 ne d�tecte pas cet �l�ment...
		if(!this.target) return; // donc juste pour lui, on annule le script en attendant de trouver une solution...
		this.children = this.target.getChildren();
		if (this.target.getAttribute('stayOpenMode')){
			this.mode2= this.target.getAttribute('stayOpenMode');
		}
		this.title = this.createNavTitle();
		this.title.injectBefore(this.target);
		this.createFixture();
		this.createEvents();
	},
	
	createEnhancedClone : function(){
		var navCoord = this.element.getCoordinates();
		navCoord.top += this.container.getStyle('border-top-width').toInt();
		
		return this.element.clone()
		.setStyles(extend(navCoord,{'position':'absolute', 'left':0, 'overflow':'hidden'}))
		.inject(this.base);
	},
	
	createFixture : function(){
		this.removeIEtoolbar.attempt();
		this.changeLayout();
		this.createEffect();
	},
	
	removeIEtoolbar : function(){
		$('flash').getElement('img').setAttribute("galleryimg","no");
	},
	
	createNavTitle : function(){
		return new Element('h3')
		.addClass('titreSlidingNav boutonUnivers')
		.setText(' ');
	},
	
	changeLayout : function(){
		this.element.setStyle('height', this.target.offsetHeight + this.title.offsetHeight);
		this.container.setStyle('padding-left', this.element.offsetWidth +this.element.getStyle('margin-right').toInt());
		
		this.children[0].setStyle('margin-top', 0);
		this.children[0].getElement('a').setStyle('border-top', 'none');
		
		this.children.setStyles({'left': -this.children[0].offsetWidth,'opacity':0});
		//je modifie la marge de navigation afin que le mainInside ait toujours la meme largeur
		$('navigation').setStyle('margin-right',36);//36 car 18x2
	},
	
	createEffect : function(){
		var self = this;
		this.maxWidth = -this.children[0].offsetWidth;
		this.effect = this.children.map(function(li, i){
			 return new Fx.Styles(li, {
				wait:false,
				transition:Fx.Transitions.Quad.easeOut,
				duration:self.effectDuration,
				onComplete:function(){
					if (i == self.children.length - 1 && li.getStyle('left').toInt() == 0){
						//on change un booleen
						self.bool = true;
					}else{
						self.bool = false;
					}
				}
			});
		})
		
	},
	
	open : function(){
		var self = this;
		var objFx = {'left' : [self.maxWidth, 0], 'opacity' : [0, 1]};
		this.effect.each(function(fx, index){		
			fx.start.delay(this.effectDuration/2 * index, fx, objFx);
		},this)
		
	},
	
	close : function(){
		var self = this;
		var objFx = {'left' : self.maxWidth, 'opacity' : 0};
		// j'inverse le sens du tableau parceque un reverse agit par reference et non par copie
		this.effect.copy().reverse().each(function(fx, index){
			fx.start.delay(this.effectDuration/2 * index, fx, objFx);
		},this);
	},
	
	createEvents : function(){
		var timer, timer2;
		this.title.addEvent('click',function(){
			if (this.children[0].getStyle('left').toInt() == this.maxWidth) {
				this.open();
			}
		}.bind(this));
		this.element.addEvent('mouseleave',function(e){
			new Event(e).stop();
			timer = (function(){
				if (this.bool == true && !this.mode2) {
					timer2 = this.close.delay(this.closingDelay, this);
					$clear(timer);
				}
			}).periodical(100, this);
		}.bind(this));
		
		this.element.addEvent('mouseenter',function(e){
			new Event(e).stop();
			$clear(timer);
			$clear(timer2);
		}.bind(this));
	}
});

/* Fonction de la pge overview qui permet d'afficher des zooms sur une image mappee */
function presOverview(){
	var pres_overviews = document.getElements('div.presentation_overview');
	/*on teste si le bloc existe*/
	if(pres_overviews.length == 0) return;
	pres_overviews.addClass('hidden');
	pres_overviews[0].removeClass('hidden');
	/*on remonte au bloc pour recuperer les liens */
	var block = getParent(pres_overviews[0], {nodeName:"div", className:"block"});
	var gal_overview = $(block).getElement('div.gallery_overview');
	eachPres(pres_overviews[0]);
	/*on teste si le bloc existe*/
	if (gal_overview){
		var link_overviews = gal_overview.getElements('a');
		/*alignement en hauteur gallerie a l'init*/
		gal_overview.setStyle('height', getNaturalHeight(pres_overviews[0].getElement('.visu')));
		/*on ajoute sur les liens un evenement permettant le changement de pres_overview*/
		link_overviews.each(function(a, i){
			link_overviews[0].addClass('current');
			a.addEvent('click', function(e){
				var e = new Event(e);
				e.stop();
				this.blur();
				link_overviews.removeClass('current');
				link_overviews[i].addClass('current');
				/*alignement en hauteur gallerie*/
				gal_overview.setStyle('height', getNaturalHeight(pres_overviews[i].getElement('.visu')));
				pres_overviews.addClass('hidden');
				pres_overviews[i].removeClass('hidden');
				eachPres(pres_overviews[i]);
			});
		});
	};
	function eachPres(pres_overview){
		pres_overview.setProperties({
			alt: '',
			title: ''
		});/*pour enlever les title et les alt au rollover*/
		var as = pres_overview.getElements('a.zone');
		var pres = pres_overview.getElements('div.pres');
		pres.setStyle('visibility', 'visible');
		pres.addClass('notVisible');
		pres_overview.getElement('.visu').addEvent('click',function(e){
			new Event(e).stop;
			pres.addClass('notVisible');
		});
		/*on prevoit le positionnement meme si nous n'avons pas la gallerie de lien dans le cas ou il n'y a qu'un seul pres_overview*/
		galSize = gal_overview ? gal_overview.offsetWidth : 0;
		var middle = (getNaturalWidth($(pres_overview).getElement('img.visu')) - galSize) /2;
		pres.each(function(elm, i){
			var mainImgNatSize = getNaturalHeight($(pres_overview).getElement('img.visu'));
			/*on centre en hauteur le layer zoom*/
			var elmNatSize = $(elm).offsetHeight;
			$(elm).setStyle('top', (mainImgNatSize - elmNatSize)/2);
			as.each(function(a){a.blur()})
			as[i].setText('clic');//sous ie, les 'a' vides son in-eventable
			as[i].addEvents({
				'click':function(e){
					new Event(e).preventDefault();
					/* on positionne en largeur le layer zoom au clic */
					(this.getPosition().x - pres_overview.getPosition().x) > middle ? elm.style.left = 30+'px' : elm.style.right = 30 + galSize +'px';
					pres.addClass('notVisible');
					$(elm).removeClass('notVisible');
					return false;
				},
				'mouseenter':function(e){
					this.addClass('zoneCurrent');
				},
				'mouseleave':function(e){
					new Event(e).stop;
					this.removeClass('zoneCurrent');
				}
			});
			/*effet sur over sur zoom_txt dans pres_overview*/
			var zoom =$(elm).getElement('.zoom_txt');
			
			if (!zoom.getAttribute('onclick') == ""){
				zoom.setStyle('cursor','pointer');
				zoom.addEvent('mouseenter',function(){
					this.setStyle('background-color', '#000');
				});
				zoom.addEvent('mouseleave',function(){
					this.setStyle('background-color', 'transparent');
				});
			}else{
				zoom.setStyle('cursor','default');
			}
			
			
			$(elm).getElement('a.close').onclick = function(e){
				$(elm).addClass('notVisible');
				return false;
			};
		});
	}
	/*pour chaque pres_overview, on set la position et la taille des zones en mode zoom*/
/*	
	pres_overviews.each(function(pres_overview){
		
	});
*/
};

/*get ratio for player in galleryScroller*/
function ratioSizing(sizeH){
	if($('player')){
		var ratio = $('player').getAttribute('ratio');
		if (sizeH){
			var width = sizeH;
		}else{
			var width = $('player').offsetWidth;
		}
		var reg = new RegExp('(.*)/(.*)','gi');
		var resultat = reg.exec(ratio);
		var ratioV = RegExp.$1;
		var ratioH = RegExp.$2;
		var heightRatio = ((width/ratioV)*ratioH).toInt() + 20;//20 correspond a la hauteur de la barre doutils du player
		if(heightRatio == 20){
			heightRatio = 221 + 20;
		}
		return heightRatio;
	};
};
/* fonction de scroll vertical adaptee aux pages du showroom */
function galleryScroller(){
	var bloc = document.getElement('div.mediaScrollerCtn');
	if (bloc){
		var returnButton = bloc.getElement('a.return');
		var followButton = bloc.getElement('a.follow');
		var lis = bloc.getElements('div.mediaScroller li');
		var i=0;
		if(bloc.hasClass('gallerieOccasion')){
			var media = bloc.getElement('div.media div.show img');
			var blocWidth = media.getSize().size.x - (bloc.getElements('a.arrow')[0].getSize().size.x)*2;
			/* init scroller Width */
			bloc.getElement('div.mediaScroller').setStyle('width', media.getSize().size.x );
			/* init hScroll Width */
			bloc.getElement('div.hScroll').setStyle('width', blocWidth);
			/* init UL Width */
			bloc.getElement('div.mediaScroller ul').setStyle('width', lis[i].getSize().size.x * lis.length);
			
			var scroll = new Fx.Scroll(bloc.getElement('div.hScroll'), {
				wait: false,
				duration: 500
			});
			var butee = Math.round((bloc.getElement('div.mediaScroller div.hScroll').getSize().size.x)/(lis[0].getSize().size.x));
		}
		if(!bloc.hasClass('gallerieOccasion')){
			var scroll = new Fx.Scroll(bloc.getElement('div.mediaScroller ul'), {
				wait: false,
				duration: 500
			});
			var butee = Math.round((bloc.getElement('div.mediaScroller ul').getSize().size.y)/(lis[0].getSize().size.y));
		}
		
		var neutralize = function(e){
			e = new Event(e).stop();
			e.stopPropagation();
			e.preventDefault();
		}
		followButton.addEvent('click', function(e) {
			neutralize(e);

			if (i<lis.length-butee){
				i++;
			};
			scroll.toElement(lis[i]);
		});
		returnButton.addEvent('click', function(e) {
			neutralize(e);
			if (i>0){
				i--;
			};
			scroll.toElement(lis[i]);
		});
		
		if($('player')){
			/* changement de source de flv */
			var as = bloc.getElements('div.mediaScroller li a');
			as.each(function(a){
				a.addEvent('click',function(e){
					new Event(e).stop();
					s1.sendEvent('load',a.href);
				});
			});

			
		}
		/* gestion layers SSI ils existent */
		if(bloc.getParent().getElement('div.layersMediaScroller')){
			var layers = bloc.getParent().getElement('div.layersMediaScroller').getElements('div.layer');
			var as = bloc.getElements('div.mediaScroller li a');
			as.each(function(a, i){
				a.onclick = function(e){
					var e = new Event(e);
					e.stopPropagation();
					e.preventDefault();
					layers.addClass('hidden');
					layers[i].removeClass('hidden');
				};
			});
		}
		/* gestion photoGallery SSI ils existent */
		if(bloc.hasClass('photoGallery')||bloc.hasClass('gallerieOccasion')){
			var medias = bloc.getElements('div.show img');
			var linkMedias = bloc.getElements('div.mediaScroller li a');
			medias.addClass('hidden');
			medias[0].removeClass('hidden');
			linkMedias.each(function(a, i){
				a.onclick = function(e){
					var e = new Event(e);
					e.stopPropagation();
					e.preventDefault();
					medias.addClass('hidden');
					medias[i].removeClass('hidden');
				};
			});
			//resize du body pour eviter blanc sur ie
			bloc.getParent().setStyle('height','auto');
		}
		
		var blocHeight = bloc.getSize().size.y - (bloc.getElements('a.arrow')[0].getSize().size.y)*2;
		if(!bloc.hasClass('gallerieOccasion')) bloc.getElement('div.mediaScroller ul').setStyle('height', blocHeight);
	};
};

window.addEvent('load', function() {

    resizePrehome();
    toggleSelect();

	var bloc = document.getElements('div.slider');
	var blocCtn = document.getElements('div.sliderCtn');
	var lastChanged;
	if(bloc.length == 0) return;
	bloc.each(function(bloc){
		var increment = $(bloc).getProperty('increment') != null ? $(bloc).getProperty('increment').toInt() : 100;
		var prixMin = $(bloc).getProperty('minPrice') != null ? $(bloc).getProperty('minPrice').toInt() : 0;
		var prixMax = $(bloc).getProperty('maxPrice') - prixMin;
		var initial = $(bloc).getProperty('initial') != null ? $(bloc).getProperty('initial').toInt() : prixMax/2;
		var mySlide = new Slider(bloc.getElement('div.sliderBox'), bloc.getElement('div.curseur'), {
			steps: prixMax /increment,
			initialize : function(pos){
				this.updater = bloc.getElement('p.upd');
				this.zoner = bloc.getElement('div.zone');
				this.zoner.setStyle('left',- (200 - Math.round((this.toPosition(prixMax/2) + this.knob.offsetWidth/2))));
			},
			onChange: function(step){
				this.zoner.setStyle(this.p,- (200 - ((this.knob.getLeft() - this.element.getLeft()) + this.knob.offsetWidth/2)));
				this.updater.setHTML(step*increment + prixMin);
				
			},
			onTick: function(pos){
				this.knob.setStyle(this.p, pos);
				this.zoner.setStyle(this.p,- (200 - ((this.knob.getLeft() - this.element.getLeft()) + this.knob.offsetWidth/2)));
			}
		}).set(initial/increment);
		var bouton = bloc.getParent().getElement('a.bouton');
		if (bouton){
 			bouton.addEvent('click',function() {
				lastChanged = getParent(bloc, {className:'sliderCtn'});
			})
		}else{
			mySlide.addEvent('onChange',function() {
				lastChanged = getParent(bloc, {className:'sliderCtn'});
			})
		}
		
	});
	var populateHidden = function(oBloc){
		var aInputs = oBloc.getElements('input[type=hidden]');
		for (var i=0; i < aInputs.length; i++) {
			aInputs[i].value = $(aInputs[i].name).innerHTML;
		};
	}
	var emptyHidden = function(oBloc){
		var aInputs = oBloc.getElements('input[type=hidden]');
		for (var i=0; i < aInputs.length; i++) {
			aInputs[i].value = '';
		};
	}
	var updateAll = function(aBloc, oBloc){
		//var inputs = aBloc.getElements('input[type=hidden]');
		for (var i=0; i < aBloc.length; i++) {
			if (aBloc[i] != oBloc){
				emptyHidden(aBloc[i]);
			}else{
				populateHidden(oBloc);
			}
		};
	}
	
	blocCtn.each(function(bloc, i){
		//test case 1
		bloc.modeRefresh = bloc.className.match(/\bsliderCtnRefreshable\b/) ? true : false;
		var bouton = bloc.getElement('a.bouton');
		if (bouton){
			bouton.addEvent('click',function(){
				blocCtn.removeClass('sliderBoxUniver');
				bloc.addClass('sliderBoxUniver');
				if (bloc.hasClass('budget')){
					//var zoneActive = 'budget';
					//var budget = $('middlePrice').getText();
					//fonctionDonnees(zoneActive, budget, null, null);
				}else if (bloc.hasClass('financement')){
					//var zoneActive = 'financement';
					//var apport = $('deposit').getText();
					//var mensualite = $('monthly').getText();
					//fonctionDonnees(zoneActive, null, apport, mensualite);
				}
				
			});
			bloc.addEvents({
				'mouseenter' : function(){
					blocCtn.removeClass('sliderBoxUniver');
					bloc.addClass('sliderBoxUniver');
				},
				'mouseleave' : function(){
					blocCtn.removeClass('sliderBoxUniver');
					
					if(lastChanged) lastChanged.addClass('sliderBoxUniver')
				}
			})
		}else{
			bloc.addEvents({
				'mouseenter' : function(){
					blocCtn.removeClass('sliderBoxUniver');
					bloc.addClass('sliderBoxUniver');
				},
				'mouseleave' : function(){
					blocCtn.removeClass('sliderBoxUniver');
					if(lastChanged){
						lastChanged.addClass('sliderBoxUniver');
						if (bloc.modeRefresh) updateAll(blocCtn, bloc);
					}
				}
			})
		}
	});
});

function toggleSelect(){
	if($("selectPays")){
		var linkHover = $("selectPays").getElement('a.linkSelectPays');
		var blkHover = $("selectPays").getElement('div.choiceLang');
		//var linkBlk = $(blkHover).getElement('a');

		var timer;

		function afficher() {
			clearTimeout(timer);
			$(blkHover).set({
				styles:{
					display: 'block'
				}
			});
		}

		function cacher() {
			timer = setTimeout(function() {
				$(blkHover).set({
					styles:{
						display: 'none'
					}
				});
			}, 1000);
		}

		linkHover.addEvent('mouseenter', afficher);
		blkHover.addEvent('mouseenter', afficher);

		linkHover.addEvent('mouseleave', cacher);
		blkHover.addEvent('mouseleave', cacher);

		blkHover.getElements('li a').addEvent('click', function(){
			linkHover.innerHTML = this.innerHTML;
		});
	}
}

function resizePrehome()
{
    var page = $("page"),
        bgPreHome = $("bgPreHome");
		
	if(bgPreHome) 
	{
		var bgPreHomeImg = bgPreHome.getElement('img');

		function setsizePrehome(){
			clientHeight = document.documentElement.clientHeight;
			page.setStyles({"height": clientHeight});
			bgPreHome.setStyles({"height": clientHeight});
			if(bgPreHomeImg.offsetHeight<bgPreHome.offsetHeight) {
				bgPreHomeImg.style.height = "110%"; //check in the CSS there a margin-top:-10%;
				bgPreHomeImg.style.width = 'auto';
			} else {
				if(bgPreHomeImg.offsetWidth<bgPreHome.offsetWidth) {
					bgPreHomeImg.style.height = 'auto';
					bgPreHomeImg.style.width = '100%';
				}
			}
		};

		setsizePrehome();
		Notifier.addEvent("onLayoutChangedAndStable", function(){
			setsizePrehome();
		});
	}
}


function rightNavEsc(){
	var togglers = document.getElements('.clientRightBox .head');
	togglers.each(function(toggler){
		if(window.ie7)toggler.setStyle('height',10)
		var toggled = false;
		var togglerCtt = getNextSibling(toggler, {nodeName:"div", className:"body"});
		var heightToUse = togglerCtt.offsetHeight;
		var tog = $(togglerCtt).effect('height', {
			duration: 400,
			onComplete : function(){
				if (!toggled){
					togglerCtt.setStyle('height','auto');
					toggler.removeClass('headClosed');
				}else{
					toggler.addClass('headClosed');
				}
			}
		});
		/* initialisation des pickers */
		toggler.addEvent('click', function(e){
			if (toggled){
				tog.start(heightToUse);
			} else {
				tog.start(heightToUse, 0);
			};
			toggled = !toggled;
		});
		
		var as = toggler.getParent().getElements('ul.links li.sub a.subLink');
		as.each(function(a){
			a.addEvent('click', function(e){
				e = new Event(e);
				if(!a.getParent().hasClass('open')){
					a.getParent().addClass('open');
				}else{
					a.getParent().removeClass('open');
				};
				heightToUse = togglerCtt.offsetHeight;
				e.stop();
			});
		});		
	});
	
	
};



var MediaScroll = new Class({

	// Initialisation de l'objet
	initialize: function() {
		this.makeScroller();
		this.dimMediaBox();
	},
	
	// Insertion de la liste de vignettes et masquage des blocs
	makeScroller: function() {
		$$('.accessories').each(function(oCont) {
			if(oCont.getElement('.accessScroller')) return;
			oCont.setStyle('opacity','0');
			var aPs = oCont.getElements('.media'), iP = 0;
			var sScroller = '<div class="accessScroller bMargin"><p class="arrow return"><a class="bkgUniverse" href="#">left</a></p><div class="hScroll"><ul>';
			aPs.each(function(oP) {
				sScroller += '<li><a href="#">' + oP.innerHTML + '</a></li>';
				oP.addClass('hidden');
				if(iP > 0 && !aPs[iP].getParent().getParent().hasClass('hidden'))
					aPs[iP].getParent().getParent().addClass('hidden');
				return ++iP;
			});
			sScroller += '</ul></div><p class="arrow follow"><a class="bkgUniverse" href="#">right</a></p></div>';
			
			oCont.setHTML(sScroller + oCont.innerHTML);
			oCont.effect('opacity',{duration:1000}).start(1);
		});
	},
	
	// Initialisation du mediascroller et ajout des gestionnaires d'evenement sur ses liens
	addBehaviour: function(oBox) {
		// On affecte les gestionnaires d'evenement
		var aDivs = $$('.accessories .text');
		var aAs = oBox.getElements('a');
		var iCountUl = oBox.iCount;
		var iA = 0;
		var iCount = aAs.length;
		
		while(iA < iCount) {
			aAs[iA].getParent().addEvent('mouseover', this.toolTip(aAs, iA));
			aAs[iA].getElement('img').addEvent('mousemove', this.toolTip(aAs, iA));
			aAs[iA].getParent().addEvent('mouseleave', this.initOpacity(aAs));
			if(iA < iCountUl) aAs[iA].addEvent('click', this.changeText(aDivs, iA));
			else if(iA < iCountUl * 2) aAs[iA].addEvent('click', this.changeText(aDivs, iA - iCountUl));
			else if(iA < iCountUl * 3) aAs[iA].addEvent('click', this.changeText(aDivs, iA - iCountUl * 2));
			iA++;
		}
	},
	
	// Initialisation de l'opacite des liens et masquage de la tooltip 
	initOpacity: function(aAs) {
		return function(e) {
			$('page').getElement('.ToolTips').setStyle('display', 'none');
			aAs.each(function(oA) {
				oA.setStyle('opacity', '1');
			});
			return new Event(e).stop();
		};
	},
	
	// Variation d'opacite et apparition d'une tooltip au survol d'une vignette
	toolTip: function(aAs, iA) {
		// Insertion de la toolTip dans le li si elle n'existe pas
		if(!$('page').getElement('.ToolTips'))
			$('page').adopt(
				new Element('p', {
					'class': 'ToolTips bkgUniverse',
					'styles': {'display':'none', 'opacity':'.95'}
				}).setText($E('img', aAs[0]).getAttribute('alt'))
			);

		// Selection de la toolTip
		var oToolTip = $('page').getElement('.ToolTips');
		
		// Affichage de la toolTip et modification de l'opacite des autres vignettes au survol d'une d'entre elles
		return function(e) {
			var aLinks = aAs, iLink = aLinks.length, iCurrent = iA;
			var oSource = e.target || e.srcElement;
			var iDim = oSource.getCoordinates();
			e = new Event(e);
			switch(e.type) {
				case 'mouseover':
					while(iLink-- > 0)
						iLink != iCurrent ?
							aLinks[iLink].setStyle('opacity', '0.4') :
							oToolTip.setText($E('img', aLinks[iLink]).getAttribute('alt')).setStyles({
								'display':'block',
								'top': e.page.y - 40 + 'px',
								'left': e.page.x - $('page').getPosition().x + 40 + 'px'
							});
				break;
				case 'mouseout':
					while(iLink-- > 0)
						iLink != iCurrent ? aLinks[iLink].setStyle('opacity', '1') : 
						oToolTip.setText($E('img', aLinks[iLink]).getAttribute('alt')).setStyle('display', 'none');
				break;
				case 'mousemove':
					while(iLink-- > 0)
						if(iLink == iCurrent)
							oToolTip.setText($E('img', aLinks[iLink]).getAttribute('alt')).setStyles({
								'display':'block',
								'top': e.page.y - 40 + 'px',
								'left': e.page.x - $('page').getPosition().x + 40 + 'px'
							});
				break;
			}
			return e.stop();
		};
	},
	
	// Changement des blocs texte au clic sur chaque vignette
	changeText: function(aDivs, iA) {
		var iCurrent = iA;
		return function(e) {
			var iDiv = aDivs.length;
			while(iDiv-- > 0)
				if(aDivs[iDiv] == aDivs[iCurrent]) {
					if(aDivs[iDiv].hasClass('hidden')) aDivs[iDiv].removeClass('hidden');
				}
				else if(!aDivs[iDiv].hasClass('hidden')) aDivs[iDiv].addClass('hidden');
			return new Event(e).stop();
		};
	},
	
	// Dimensionnement des vignettes et de leur marges en fonction de l'espace disponible
	dimMediaBox: function() {
		var scrollBoxes = $$('.accessories .accessScroller .hScroll');
		
		// Pour chaque scrollBoxes,
		scrollBoxes.each(function(oBox) {
			
			// Nombre de vignettes a afficher
			var sClass = oBox.className, iNbre = /display/.test(sClass) ?
				sClass.substring(sClass.indexOf('display') + 7, sClass.indexOf('display') + 8).toInt():
				'nodisplay';
			
			// Taille disponible
			var iWidthBox = oBox.getStyle('width').toInt();
			
			// Largeur des vignettes
			var iWidthLi = oBox.getElement('li').getStyle('width').toInt();

			// Si aucune demande n'est faite, on adapte les marges entre chaque vignette du bloc
			if(iNbre == 'nodisplay') {
				var iNbreAffich = parseInt(iWidthBox / iWidthLi);
				var iStandPadding = ((iWidthBox % iWidthLi) / iNbreAffich).toInt();
				var iOffset = iWidthLi + iStandPadding;
				
				// Controle des fleches precedente / suivante
				var oUl = oBox.getElement('ul');

				// Creation d'une nouvelle liste avec ajout en amont et en aval d'autant d'elements qu'il faut pour retrouver l'affichage d'origine
				var aLis = oUl.getElements('li');
				var aAfter = [], aBefore = [];
				var iLi = 0;
				var iCount = aLis.length;
				oBox.iCount = iCount;
				while(iLi < iCount) {
				
					// Ajout des marges 'droite' sur chaque li
					aLis[iLi].setStyle('padding-right', iStandPadding);
					
					if(iLi < iNbreAffich) aAfter.push(aLis[iLi].clone());
					aBefore.push(aLis[iLi++].clone());
				}
				var aTot = aBefore.concat(aLis).concat(aAfter);
				var iTot = 0;
				var oNewUl = new Element('ul');
				while(iTot < aTot.length) oNewUl.adopt(aTot[iTot++]);
				oUl.replaceWith(oNewUl);
				oUl = oBox.getElement('ul');
				oUl.setStyle('margin-left', -(iOffset * iCount));

				// Gere l'alternance gauche / droite des tooltips
				var posToolTip = function() {
					var myFx = new Fx.Styles(oUl, {
						duration: 100,
						transition: Fx.Transitions.Quad.easeOut,
						onComplete: function(oUl) {
							if(oUl.clic == 0 || oUl.clic == oUl.getElements('li').length - iNbreAffich) {
								oUl.setStyle('margin-left', -(iOffset * iCount));
								oUl.clic = iCount;
							}
						}
					});
					return function(e) {
						var aAs = oUl.getElements('a');
						var iA = aAs.length;
						var iMarginLeft = oUl.getStyle('margin-left').toInt();
						if(this.hasClass('return')) {
							--oUl.clic;
							var iWalk = iMarginLeft + iOffset;
							myFx.start({'margin-left': [iMarginLeft, iWalk]});
						}
						else if(this.hasClass('follow')) {
							var iWalk = iMarginLeft - iOffset;
							++oUl.clic;
							myFx.start({'margin-left': [iMarginLeft, iWalk]});
						}
						return new Event(e).stop();
					};
				};
				oUl.clic = iCount;
				if(oBox.getScrollLeft != 0) oBox.scrollLeft = 0;
				oBox.getPrevious().addEvent('click', posToolTip());
				oBox.getNext().addEvent('click', posToolTip());
				
				// Ajout d'une marge 'gauche' sur le premier li
				oBox.getElement('li').setStyle(
					'padding-left',
					window.attachEvent && typeof XMLHttpRequest == 'undefined' ?
						parseInt(iStandPadding / 2) :
						iStandPadding
				);
			}
			
			return this.addBehaviour(oBox);
		}, this);
	}
});


function tipBox(elm, size, position){
	if(!position){
		position="auto";
	}
	var layer = getNextSibling(elm, {nodeName:"div", className:"tipBoxLayer"}),
		bloc = getParent(elm, {nodeName:"div", className:"block"}),
		clone = $(layer).clone();
	clone.injectInside($('page'));
	clone.addClass('clonedTipBoxLayer');
	if(size){
		clone.setStyle('width', size);
	}
	
	
	clone.setStyles({
		top : $(elm).getTop(),
		opacity:0,
		display:'block'
	});
	if (clone.getCoordinates().bottom >= document.documentElement.clientHeight) clone.setStyle('top', $(elm).getCoordinates().bottom - clone.offsetHeight);
	
	if(position == "auto"){	
		if($(bloc).getLeft() < clone.offsetWidth){
			clone.setStyle('left', $(elm).getCoordinates().right - $('page').getLeft())
		}else{
			clone.setStyle('left', $(elm).getCoordinates().left - clone.offsetWidth - $('page').getLeft())
		}
	}else if(position == "right"){
		clone.setStyle('left', $(elm).getCoordinates().right - $('page').getLeft())
	}else{
		clone.setStyle('left', $(elm).getCoordinates().left - clone.offsetWidth - $('page').getLeft())
	}
	
	var opac = new Fx.Styles(clone, {duration: 200, transition: Fx.Transitions.linear});
	opac.start({
	    'opacity': [0, 1]	
	});
	
	elm.addEvent('mouseout', function() {
		clone.remove();
		elm.removeEvents('mouseout');
   });
};


function setStepHeadingLength() {
	var headings = document.getElements('.stepHeading');
	if (!headings) return;
	headings.each(function(heading) {
		
		var totalSize = heading.offsetWidth;
		var lis = heading.getElements('li');
		if (lis.length == 1){
			lis[0].setStyles({
				'text-align':'left',
				'float':'none'
			});
			return;
		}
		var totalLis = 0;
		lis.each(function(li){
			totalLis += li.offsetWidth;
		});
		var lisToSize = getNodes(heading, {nodeName:'li'},{nodeName:'li', className:'first'});
		
		lisToSize.each(function(liToSize){
			liToSize.setStyle('padding-left', ((totalSize - totalLis) / lisToSize.length).toInt());
		});
		/* check modulo de l'operation precedente pour eventuellement ajouter du padding sur le dernier*/
		lisToSize.getLast().setStyle('padding-right', lisToSize.getLast().getStyle('padding-right').toInt() + (totalSize - totalLis) % lisToSize.length);
		//optim, affichage de l'element apres calculs /si suppression, voir aussi default.css line : 671 et supprimer visibility hidden
		heading.effect('opacity', {duration: 1000, transition: Fx.Transitions.linear}).start(0, 1);
	});
}


function popLayer(){
	if (window.event) {window.event.cancelBubble = true;}
	
	this.$tmp = {};
	// var url;
	// var popId = document.getElement('div.blockToPop');
	// var width;
	// var shadow;
	
	var url = "";
	var popId = "";
	var width = 0;
	var shadow = "";
	
	//on teste les parametres
	for (i=0; i<arguments.length;i++){
		arg = arguments[i];
		if (arg.constructor == String){
			if (arg.match(/^id\w*/m)){
				popId = arg.match(/id(\w*)/)[1];
			}else{
				url = arg ? arg : false;
			}
		}else if (arg.constructor == Number){
			width = arg ? arg : 'auto';
		}else if (arg.nodeType == 1){
			shadow = arg ? arg : $('body');
		}
	}
	
	/* --------------------------------------------- */
	/* --------------------------------------------- */
	/* ---- Changement popLayer pour LayerPopIn ---- */
	/* --------------------------------------------- */
	/* --------------------------------------------- */
	
	//on enregistre l'id pour la fermeture du layer
	// this.$tmp.popId = popId;
	
	if(url != ""){
		this.$tmp.popId = new LayerPopIn({
			iframeSrc: url,
			template : '<div id="FOG-CONTENT"></div>',
			ifrstyles: {
				height: width
			}
		});
	}else{
		//console.log(popId)
		var objParams = {content: $(popId)}
		if(width != 0){
			objParams = {
				content: $(popId),
				widthLayer : width
			}
		}
		//console.log(objParams)
		this.$tmp.popId = new LayerPopIn(objParams);
	}
	
	/*
	var windowSize = window.getSize();
	var layerToPop = new Element('div', {'class': 'layerToPop'});
	var blockToPop = $(popId);
	if (shadow){
		if (shadow.nodeName.toLowerCase() == 'html'){
			layerToPop.setStyles({
				'width':windowSize.scrollSize.x,
				'height':windowSize.scrollSize.y,
				'top':0,
				'bottom':0,
				'left':0,
				'right':0,
				'position':'absolute'
			});
		}else{
			layerToPop.setStyles(shadow.getCoordinates());
		}
	}else{
		layerToPop.setStyles($('body').getCoordinates());
	}
	
	layerToPop.setStyle('z-index', 9998);
	//on positionne la popups
	if (blockToPop) blockToPop.removeClass('hidden');
	var top = (document.documentElement.clientHeight - blockToPop.offsetHeight)/2
	blockToPop.setStyles({
		'top': top > 0 ? top : 0 ,
		'left': (document.documentElement.clientWidth - blockToPop.offsetWidth)/2,
		'z-index': 9999
	});
	if (width) {
		blockToPop.setStyles({
			'width' : width,
			'left': (document.documentElement.clientWidth - width)/2});
	}
	blockToPop.addClass($('page').className);
	
	
	
	if (url) {
		var iframe = blockToPop.getElement('iframe');
		iframe.src = url;
	}
	
	
	layerToPop.injectInside($E('body'));
	blockToPop.injectInside($E('body')).addClass($('page').className);
	
	var _h =  blockToPop.offsetHeight;
	var _docH = document.documentElement.clientHeight;
	
	if (_h > _docH){
		var _nH = _docH - 100;
		blockToPop.setStyles({
			'height': _nH,
			'overflow' : 'auto',
			'overflow-y' : 'auto',
			'top' : 50 + document.documentElement.scrollTop
		})
	}
	ifrlayer.make(blockToPop);
	ifrlayer.make(layerToPop);
	
	*/
	
};

function releaseLayer(){
	if (window.event) {window.event.cancelBubble = true;}
	
	
	/* --------------------------------------------- */
	/* --------------------------------------------- */
	/* ---- Changement popLayer pour LayerPopIn ---- */
	/* --------------------------------------------- */
	/* --------------------------------------------- */
	
	if (this.$tmp && this.$tmp.popId) var popId = this.$tmp.popId;
	
	popId.close();
	
	/*
	
	var layerToPop = document.getElement('div.layerToPop');
	var blockToPop = popId ? $(popId) : document.getElement('div.blockToPop');
	
	//clean popup before close it
	
	var fields = blockToPop.getElements('ul.line ');
	while (fields.length>2){
		
		fields.pop().remove()
	}
	if ($('ajoutDest')) $('ajoutDest').style.display = 'block';
	
	var formsElms = blockToPop.getElements('input');
	
	formsElms.push(blockToPop.getElement('textarea'));
	formsElms.each(function(formElm){
	    if(formElm) {
		formElm.value ='';
	    }
	});
	
	blockToPop.addClass('hidden');
	layerToPop.remove();
	ifrlayer.hide(blockToPop);
	ifrlayer.hide(layerToPop);
	
	*/
};


var SelectLinks = new Class({
	initialize : function(){
		this.element = $('selectLinks');
		if (!this.element) return;
		this.onchange();
	},
	onchange: function(){
		this.element.addEvent('change', (function(){
			this.option = this.options[this.selectedIndex];
			if ($(this.option).hasClass('_blank')){
				window.open(this.option.value,target="_blank")
			}else{
				document.location = this.option.value;
			}
		}).bind(this.element));
	}
})

/**
	@Name :
	@Description : Evebt wrapper for Ajax requests
*/

var Remote = new Class({
	initialize : function(callable,options) {
		this.succeed = 0;
		this.requests = {};
		this.callable = new Hash(callable);
		this.setOptions(options);
		this.send();
	},
	send : function() {
		var _this = this;
		this.callable.each(function(url,name) {
			var xhr = new Ajax(url+'?nocache='+Math.random(),{'method':'get'});
				xhr.addEvent('onFailure',this.fireEvent.bind(this,['onFailure']));
				
				/*
				xhr.addEvent('onSuccess',this.setSucceed.bind(this,[name,xhr]))
				*/
				xhr.addEvent('onSuccess',function() {
					_this.setSucceed(name,xhr);
				});
				
				
				
				xhr.request();
		},this);
	},
	setSucceed : function(name,xhr) {
		this.requests[name] = xhr.response;
		
		this.succeed += 1;
		if(this.succeed == this.callable.length) {
			this.fireEvent('onComplete');
		}
	}
});
Remote.implement(new Options,new Events);


/**
	@name:
	@description: crockford's supplant method
*/
String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

var dragAndSort = new Class({
	initialize:function(handle,columns,container){
		// WebBoxes shared vars
		this.handle = handle;
		this.draggables = [];
		this.container = container;
		this.webBoxMarker = new Element('div').addClass('webBoxMarker Bspace').setStyles({'display': 'none'}).injectInside(this.container);
		this.webBoxCols = columns;
		
		this.webBoxCols.each(function(el, i){
			el.column = i;
		});
		
		// WebBoxes drag behavior for each
		this.addEvent('update',function(draggables){//draggables = {blocks:[elm1,elm2,...]}
			this.draggables.merge(draggables.blocks);
			draggables.blocks.each(function(el){
				// Make each webBox draggable using the handle
				var drag = el.makeDraggable({
					'onBeforeStart': function() {
						// Introduce the marking box, change the draging box to absolute
						// The order the next 4 lines seems to be important for it to work right in Firefox
						this.webBoxMarker.injectAfter(el).setStyles({'display': 'block', 'height': el.getStyle('height')});
						var containerCoor = drag.container.getCoordinates();
						var elCoor = el.getCoordinates();
						el.setStyles({'opacity': '0.55', 'z-index': '9999', 'width': el.getStyle('width'), 'position': 'absolute'});
						el.injectInside(this.container);
						el.setStyles({'top': elCoor.top-containerCoor.top, 'left': elCoor.left-containerCoor.left});
						if (this.webBoxCols[this.webBoxCols.length-1].getChildren().length==0){
							this.webBoxCols[this.webBoxCols.length-1].setStyle('float','none');
						}else{
							this.webBoxCols[this.webBoxCols.length-1].setStyle('float','');
						}
						
						if (el.beforeStartFunction) el.beforeStartFunction();
					}.bind(this),
					'onComplete': function() {
						// Replace the draging webBox
						el.injectBefore(this.webBoxMarker).setStyles({'opacity': '1', 'z-index': '1', 'position': 'relative', 'top': '0', 'left': '0'});
						
						// Remove the marking box
						this.webBoxMarker.injectInside(this.container).setStyles({'display': 'none'});
						
						if (this.webBoxCols[this.webBoxCols.length-1].getChildren().length==0){
							this.webBoxCols[this.webBoxCols.length-1].setStyle('float','none');
						}else{
							this.webBoxCols[this.webBoxCols.length-1].setStyle('float','');
						}
						
						if (el.completeFunction) el.completeFunction();
						
						//this.webBoxCols.setStyle('height',this.webBoxCols[0].getParent().getSize().size.y);
					}.bind(this),
					'onDrag': function() {
						this.setColumn(el,drag.mouse.now);
						if (el.dragFunction) el.dragFunction();
					}.bind(this),
					container:this.container
				},this);
				el.removeEvents();
				el.getElement(this.handle).addEvents({
					'mousedown':function(e){
						e = new Event(e);
						e.stop();
						drag.start(e);
					},
					'click':function(e){
						new Event(e).stop();
					}
				});
			},this);
		}.bind(this));
	},
	setColumn : function(elem,mouse) {
		//var mouseX = mouse.x; var mouseY = mouse.y;
		var posX = (elem.getPosition().x+(elem.offsetWidth/2)); var posY = mouse.y;
		
		webBoxTargetCol = this.webBoxCols[0];
		webBoxTargetDiv = null;
		 
		// X - Which column?
		this.webBoxCols.each(function(el, i){
			//if (mouseX > el.getCoordinates().left) webBoxTargetCol = el;
			if (posX > el.getCoordinates().left) webBoxTargetCol = el;
			
			maxHeight = el.getParent().getSize().size.y;
			if (el.getElements('.block').length<1){
				el.setStyle('height',maxHeight);
			}else{
				el.setStyle('height','auto');
			}
		},this.webBoxCols);
		 
		 // Y - If we're half way or more past this webBox then insert it after this one
		webBoxTargetCol.getChildren().each(function(el, i){
			//if (mouseY > (el.getCoordinates().top + Math.round(el.getCoordinates().height / 2))) webBoxTargetDiv = el;
			if (posY > (el.getCoordinates().top + Math.round(el.getCoordinates().height / 2))) webBoxTargetDiv = el;
		});
		
;		// Place the marker
		if (webBoxTargetDiv == null){
			// On top
			if (webBoxTargetCol.getElements('.block').length>0){
				if (webBoxTargetCol.getChildren()[0] != this.webBoxMarker){
					this.webBoxMarker.injectBefore(webBoxTargetCol.getChildren()[0]);
				}
			}else{
				this.webBoxMarker.injectInside(webBoxTargetCol);
			}
		}else{
			// Or after a webBox
			if ((webBoxTargetDiv != this.webBoxMarker) && (webBoxTargetDiv != this.webBoxMarker.getPrevious())) this.webBoxMarker.injectAfter(webBoxTargetDiv);
		}
	},
	setDraggables:function(draggables){
		//this.draggables = draggables;
		this.fireEvent('update',draggables);
	}
});
dragAndSort.implement(new Events);

var setCufonMenu = function(){
	if($('menu') || $('menuVitaf')){
        if($('menu')){
            var $menu = $('menu');
        }
        if($('menuVitaf')){
            var $menu = $('menuVitaf');
        }
		var menuChildren = $menu.getChildren();
		menuChildren.each( function(el){
			var spans = el.getElements("span");
			if (!localCyrillic.contains(cufonSiteLocal)){
				Cufon.replace(spans);
			}else{
				Cufon.set("fontFamily","Helvetica Neue LT Pro").replace(spans);
			}
		});
	}
    if($('submenu')){
		var menuChildren = $('submenu').getChildren();
		menuChildren.each( function(el){
			var spans = el.getElements("span");
			if (!localCyrillic.contains(cufonSiteLocal)){
				Cufon.replace(spans);
			}else{
				Cufon.set("fontFamily","Helvetica Neue LT Pro").replace(spans);
			}
		});
	}
}

function setCufonPopin(form){
	var elemCufonize = $(form).getElements('.cufonize'); 
	
	var arrayOfElms = [];
	for(var i=0; i<elemCufonize.length; i++){
		arrayOfElms.push(elemCufonize[i]);
	}
	
	Cufon.replace(arrayOfElms);
}

var setCufon = function(){
	Cufon.now();
	var titleNav = $('titleNav'); 
	var subTitleNav = $('subTitleNav'); 
	var titleRightGeneral = $('titleRightGeneral'); 
	var pageTitle = $('pageTitle'); 
	var elemCufonize = $$('.cufonize'); 
	
	var elemCufonizeTitle11 = $$('.setCufonTitle11'); 
	var elemCufonizeTitle15 = $$('.setCufonTitle15');
	var elemCufonizeTitle22 = $$('.setCufonTitle22');
	var elemCufonizeTitle26 = $$('.setCufonTitle26');
	var elemCufonizeTitle32 = $$('.setCufonTitle32'); 
	
	var arrayOfElms = [];
	for(var i=0; i<elemCufonize.length; i++){
		arrayOfElms.push(elemCufonize[i]);
	}
	for(var ititle11=0; ititle11<elemCufonizeTitle11.length; ititle11++){
		arrayOfElms.push(elemCufonizeTitle11[ititle11]);
	}
	for(var ititle15=0; ititle15<elemCufonizeTitle15.length; ititle15++){
		arrayOfElms.push(elemCufonizeTitle15[ititle15]);
	}
    for(var ititle22=0; ititle22<elemCufonizeTitle22.length; ititle22++){
		arrayOfElms.push(elemCufonizeTitle22[ititle22]);
	}
    for(var ititle26=0; ititle26<elemCufonizeTitle26.length; ititle26++){
		arrayOfElms.push(elemCufonizeTitle26[ititle26]);
	}
	for(var ititle32=0; ititle32<elemCufonizeTitle32.length; ititle32++){
		arrayOfElms.push(elemCufonizeTitle32[ititle32]);
	}
	if(titleNav) arrayOfElms.push(titleNav);
	if(subTitleNav) arrayOfElms.push(subTitleNav);
	if(titleRightGeneral) arrayOfElms.push(titleRightGeneral);
	if(!$("page").hasClass("printPage"))
		if(pageTitle) arrayOfElms.push(pageTitle);
	
	if (!localCyrillic.contains(cufonSiteLocal)){
		Cufon.replace(arrayOfElms);
	}else{
		Cufon.set("fontFamily","Helvetica Neue LT Pro").replace(arrayOfElms);
	}
	
}



/** LISTES DEROULANTES POUR HEADER ET FOOTER */

function toggleScript() {
	$$('.toggleList2').each(function(oDiv) {
		var oTemp = false;
		var fnHide = function() {
			if(oTemp == true) return;
			this.getLast().addClass('hidden');
			this.getFirst().getFirst().getFirst().src = this.hasClass('haut') ?
				'/css/skin/fleche_haut.gif' :
				'/css/skin/fleche_bas.gif';
			return oTemp = false;
		};
		oDiv.addEvent('mouseover', function() { return oTemp = true;});
		oDiv.addEvent('mouseout', function() { return oTemp = false;});
		oDiv.addEvent('mouseleave', function() { return (fnHide).delay(1000, this);});
		var oTitle = oDiv.getFirst();
		if(!oTitle) return;
		oTitle.innerHTML = '<a href="#">' + oDiv.getFirst().innerHTML + (
			oDiv.hasClass('haut') ?
				' <img src="/css/skin/fleche_haut.gif" alt="" /></a>' :
				' <img src="/css/skin/fleche_bas.gif" alt="" /></a>'
		);
		oTitle.getFirst().getFirst().setStyles({'width': '.8em', 'height': '.8em'});
		var oUl = oDiv.getLast();
	
		oUl.addClass('hidden');
		var oA = oDiv.getFirst().getFirst();
		oA.addEvent('click', function(e) {
			var oEvent = new Event(e);
			oEvent.stop();
			var oDiv = this.getParent().getParent();
			var oUl = oDiv.getLast();
			var oTitle = oDiv.getFirst();
			var oImg = oTitle.getFirst().getFirst();
			if(oUl.hasClass('hidden')) {
				var iDivWidth = oDiv.getStyle('width');
				oUl.setStyle('width', iDivWidth);
				if(window.attachEvent && typeof XMLHttpRequest == 'undefined')
					$$(oUl.getElementsByTagName('a')).each(function(oA) {
						oA.setStyle('width', parseInt(iDivWidth) - 10 + 'px');
					});
				oUl.removeClass('hidden');
				oImg.src = oDiv.hasClass('haut') ?
					'/css/skin/fleche_bas.gif' :
					'/css/skin/fleche_haut.gif';
				oTemp = true;
			}
			else {
				oUl.addClass('hidden');
				oImg.src = oDiv.hasClass('haut') ?
					'/css/skin/fleche_haut.gif' :
					'/css/skin/fleche_bas.gif';
			}
			return true;
		});
	});
};


try { window.addEvent('domready', toggleScript); } catch(e) { window.addEvent('load', toggleScript); }


/* Serialize a string dictionnary.
 * kvsep is used as a separator between keys and values.
 * sep is used as a separator between each pair.
 * keys and values are passed through an optionnal filter function.
 * kvsep defaults to ":", sep defaults to ","
 * default filter is a noop.
 */
function $hashJoin(obj, kvsep, sep, filter) {
   kvsep = $pick(kvsep, ":");
   sep = $pick(sep, ",");
   filter = $pick(filter, function(a) {return a;});
   var ret = "";
   for (key in obj) {
      ret += filter(key)+kvsep+filter(obj[key])+sep;
   }
   return ret.slice(0, ret.length-sep.length);
}

/* A simplified version of swfobject 
 * Missing:
 *   - express install
 *   - version check
 * Example: 
 *   new FlashObject('file.swf',
 *      {width:300, height:200, allowScriptingAccess: 'always'},
 *      {foo:bar},
 *      $('flashzone'));
 * inserts a 300x200 flash into the element with the id "flashzone",
 * foo is passed as a flashvar with the value "bar".
 *
 * WARNING : object and embeds can't be extended like other elements.
 * Same constraint apply for FlashObject, don't try to use $() or any
 * of the Element method on them.
 */
var FlashObject = new Class({
   initialize: function(file, options, flashvars, target) {
      options = $pick(options, {});
      if(!options.id) options.id = 'flashid_'+new Date().getTime();
      flashvars = $pick(flashvars, {});
      var escapedVars = $hashJoin(flashvars, "=", "&", escape);
      if ($defined(window.ie) || $defined(window.opera)) {
			/* We can't use Element constructor for object tag */
         var obj = document.createElement('object');
         options.movie = file;
         options.flashvars = escapedVars;
         for (var item in options) {
				if (!['width', 'height', 'id'].contains(item)) {
					obj.appendChild(new Element('param', {name:item, value:options[item]}));
				}
         }
      } else {
			/* We can't use Element constructor for embed tag */
         var obj = document.createElement('embed');
         obj.setAttribute('type', 'application/x-shockwave-flash');
         for (var item in options) {
            obj.setAttribute(item, options[item]);
         }
         obj.setAttribute('src', file);
         obj.setAttribute('FlashVars', escapedVars);
      }
		target.empty();
		target.appendChild(obj);
		if ($defined(window.ie) ||$defined(window.opera)) {
         obj.setAttribute('classid', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000');
         for (var item in options) {
				if (['width', 'height', 'id'].contains(item)) {
					obj.setAttribute(item, options[item]);
				} 
			}
		}

      return target.firstChild;
   }
});

var Font = new Class({
   	initialize: function (cible, marginTop){
			this.cible = cible;
			if(!marginTop){marginTop = 0;}
			if(cible.getChildren().length == 0 ){
				this.fontIt('-3');
			}
			else{
				var chld = cible.getChildren();
				chld.each(function(elm, i){
					var ELM = elm.clone();
					// checker la recup des CSS 
					var css = elm.getStyles('font-size','color', 'text-indent', 'font-weight', 'text-align', 'letter-spacing', 'white-space','display');
					var css2 = cible.getStyles('backgroundColor', 'margin', 'padding', 'float', 'height');
					var div = new Element('div');
					var size = cible.getCoordinates();
					var CIBLE = cible.clone();
					//
					div.setStyle("width", size.width);
					elm.setStyle("width", size.width);
					//div.setStyle("height", size.height);
					div.setStyles(css2);
					ELM.setStyles(css);
					cible.setStyles({'margin':0,'padding':0,'height':'1em','min-height':'1em'});
				//	cible.setStyle("padding", '0');
					//
					ELM.injectAfter(cible);
					elm.remove();
					div.injectBefore(cible);
					div.adopt(cible);
					div.adopt(ELM);
					new Font(cible, '-10');
					new Font(ELM, '-20');
					})
			}
		},
    fontIt: function(marginTop){
		cible = this.cible;
		if(!cible.id){cible.id = "h"+Math.round(Math.random()*100000)}; //id obligatoire
		var fSize = cible.getStyle('fontSize');
		fSize = parseInt(fSize);
		var fColor = cible.getStyle('color');
		var fAlign = cible.getStyle('textAlign');
		new FlashObject("/swf/myFont.swf",{width:cible.offsetWidth, height:cible.offsetHeight, allowScriptingAccess: 'always','wmode':'transparent'},{FontSize:fSize, FontColor:fColor,elmHeight:parseInt(cible.offsetHeight),elmWidth:parseInt(cible.offsetWidth),alignment:fAlign,marginTop:marginTop,Text:cible.innerHTML.toUpperCase()},$(cible.id));
		}
	}
);
/*
window.addEvent('domready',function(){
	//	new Font($('titleInFlash'));
	//	new Font($('pageTitle'));
	//	new Font(document.getElement('.productTitle'));
});
*/


var NavTop = {
	init : function() {
		//if (document.all && window.print && !window.opera) return;
		var menu = $('menu');
		if (!menu) return;
		setTimeout(function() {
			//var applets = document.getElementsByTagName('applet');
			//if (applets.length==0) return;
			
			menu.getElements('li').each(function(li) {
				var ul = li.getElement('ul');
				if (ul && ul.parentNode==li) {
					var ifr = new Element('iframe', {
						'src' : 'javascript:false',
						'frameborder' : 0,
						'border' : 0,
						styles : {
							'position' : 'absolute',
							'display': 'none',
							'z-index' : ul.getStyle('z-index').toInt()-1
						}
					})
					ifr.style.filter = ('alpha(opacity=0)');
					ifr.style.opacity = 0;
					li.iframe = li.appendChild($(ifr));
					li.ul = ul;
					li.addEvent('mouseenter', NavTop.mouseenter.bind(li));
					li.addEvent('mouseleave', NavTop.mouseleave.bind(li));
				}
			});
		}, 100);
	},
	
	mouseenter : function() {
		var self = this;
		(function() {
			self.iframe.setStyles(self.ul.getStyles('top','left'));
			self.iframe.setStyles({
				'display':'block',
				'width' : self.ul.getSize().size.x,
				'height' : self.ul.getSize().size.y
			});
		}).delay(2);
	}, 
	
	mouseleave : function() {
		this.iframe.setStyle('display', 'none');
	}

}
/*window.addEvent('domready', NavTop.init);*/

function openPrintVersion() {
    var currentUrl = document.location.href;
    openPrintVersionUrl(currentUrl);
}

function openPrintVersionUrl(url){
    var printUrl="";
    if (url.indexOf("?") != -1) {
       printUrl=url+"&print=true";
    } else {
       printUrl=url+"?print=true";
    }
    window.open(printUrl, '', 'width=1001,height=700,scrollbars=yes');
}
function renderVarsC2A(frm) {
  for (var i=0 ; i<C2A_name.length ; i++) {
    $(frm).adopt(new Element('input', {type:"hidden", name:C2A_name[i], value:C2A_value[i]}));
  }
  frm.submit();
}

function renderVarsC2A_popup(url, width, height) {
	width = width ? width : 500;
	height = height ? height : 500;
	var params = [];
	for (var i=0 ; i<C2A_name.length ; i++) {
		params.push(C2A_name[i] + '=' + C2A_value[i]);
	}
	window.open(url + '?' +params.join('&'), 'popup', 'width='+ width +',height='+ height + ',scrollbars=yes,resizable=yes');
}

var LayerAjax = new Class({
	initialize : function(){
		var _self = this;
		this.layerWidth = 700;
		
		this.createMask();
		this.createLayer();
		
		//effect on open
		this.theFXOpen = new Fx.Styles(_self.layer, {
			duration: 400
		});
		//effect on close
		this.theFXClose = new Fx.Styles(_self.layer, {
			duration: 300,
			onComplete : function(){
				_self.layer.remove();
			}
		});
		
	},
	createMask : function(){
		var _self = this;
		this.mask = new Element('div');
		this.mask.setStyles({
			'height' : document.documentElement.clientHeight + 'px',
			'width' : document.documentElement.clientWidth + 'px',
			'position' : 'absolute',
			'left' : 0,
			'top' :0,
			'background' : '#000000 url(/css/skin/ajax-loader-big.gif) no-repeat center center',
			'opacity' : 0.6,
			'z-index' : 10000
		});
		this.mask.id='maskLayer';
		this.mask.onclick = function(){
			_self.closeLayer();
		}
	},
	createLayer : function(){
		var _self = this;
		this.layer = new Element('div');
		this.layer.setStyles({
			'width' : _self.layerWidth,
			'height' : 0,
			'min-height' : 0,
			'overflow' : 'hidden',
			'position' : 'absolute',
			'opacity':'0',
			'top' : 0,
			'z-index' : 10001
		});
	},
	open : function(url){
		var _self = this;
		this.url = url;
		this.remoteUrl();
		
		//affichage elements cr��s
		document.body.appendChild(this.mask);
		ifrlayer.make(this.mask);
	},
	closeLayer : function(){
		var _self = this;
		this.mask.remove();
		ifrlayer.hide(this.mask);
		this.theFXClose.start({
			'top' : [_self.layerTop - 100],
			'left' : [_self.layerLeft + 100],
			'opacity' : 0
		});
		
		
	},
	remoteUrl : function(url){
		var _self = this;
		this.url = url ? url : this.url;
		if (url){
			this.theFXTranslate = new Fx.Styles(_self.layer, {
				duration: 300,
				onComplete : function(){
					var xhr = new Ajax(_self.url,{
						'method':'get',
						'onSuccess' : function(xhr){
							_self.response = xhr;
						},
						'onComplete' : function(){
							//populate layer
							_self.populateAndShow();
							//position layer
							_self.positionning();
						}
					}).request();
				}
			}).start({
				'top' : [_self.layerTop - 100],
				'left' : [_self.layerLeft + 100],
				'opacity' : 0
			});
		}else{
			var xhr = new Ajax(this.url,{
				'method':'get',
				'onSuccess' : function(xhr){
					_self.response = xhr;
				},
				'onComplete' : function(){
					//populate layer
					_self.populateAndShow();
					//position layer
					_self.positionning();
				}
			}).request();
		}
	},
	populateAndShow : function(){
		var _self = this;
		this.layer.innerHTML = this.response;
		document.body.appendChild(this.layer);
		
		
		//ajout evenement Close
		this.layer.getElements('.closeIt').each(function(close){
			close.addEvent('click',function(e){
				new Event(e).stop();
				_self.closeLayer();
			})
		})
	},
	positionning : function(){
		var _self = this;
		var mid = (document.documentElement.clientHeight / 2);
		var child = _self.layer.getElement('div');
		this.layer.setStyle('left', (document.documentElement.clientWidth / 2) - (_self.layerWidth / 2));
		
		//effect on open
		
		this.theFXOpen.start({
		    'height': [0, child.offsetHeight],
			'top' : [mid, mid - (child.offsetHeight / 2) ],
			'opacity' : 1
		});
		
		
		this.layerLeft = this.layer.getLeft();
		this.layerTop = this.layer.getTop();
		
	}
})

var setUrlParam = function(sPrice){
	var sOtherPrice = sPrice == 'TTC' ? 'HT' : 'TTC';
	var sAnd = document.location.search.match(/\?/) ? '&' : '?';
	if (!document.location.search.match(/userPriceType/)){
		document.location = document.location.href + sAnd + 'userPriceType=' + sPrice;
	}else{
		document.location.href = document.location.href.replace('userPriceType='+sOtherPrice, 'userPriceType=' + sPrice);
	}
	
}

var layerPopin = null;

function sendToAFriend(){
	var currentLocation = document.location.pathname;
	layerPopin = new LayerPopIn({
		ajaxText: '/includes/sendToAFriendLayerContent.jsp' + '?pageUrl=' + currentLocation
	}) 
	/*
	thepopupAjax = new LayerAjax();
	//on passe location en parametre
	var currentLocation = document.location.pathname;
	thepopupAjax.open('/includes/sendToAFriendLayerContent.jsp' + '?pageUrl=' + currentLocation);
	/**/
	if(typeof google_analytics_site_id != "undefined"){
		var pathname = currentLocation;
		if(pathname.substring(pathname.length-9) == "index.jsp"){
			pathname = pathname.substring(0,pathname.length-9);
		}
		sendGA(['_trackPageview',pathname+'Send to friend page']);
	}
}


function validLayerSendToAFriend(elm){
	var url = elm.action;
	url += '?'+ $(elm).toQueryString();
	
	//on passe location en parametre
	layerPopin.close();
	//thepopupAjax.remoteUrl(url);
	layerPopin = new LayerPopIn({
		ajaxText: url
	}) 
	
	
	/* on lance le sendtracker pour affichage de la popin de confirmation */
	if(typeof google_analytics_site_id != "undefined")
		sendGA(['_trackPageview',window.location.pathname+'/Send to friend confirmation page']);
		
	return false;
}


/***** code sendTOAFriend *****/
function ajoutDestinataire()
{

    dest1 = $('destinataire1');
    dest2 = dest1.clone();
    dest2.id = 'destinataire2';
    dest2.injectAfter(dest1);
    inputs = $$('#destinataire2 input');
    labels = $$('#destinataire2 label');
    inputs[0].name = "dest2Name";
    inputs[1].name = "dest2Email";
    inputs[0].value = "";
    inputs[1].value = "";
    labels[0].setProperty('for', 'dest2Name');
    labels[1].setProperty('for', 'dest2Email');
    if ($('destinataire2')) $('ajoutDest').style.display = "none";
}

function sendToAFriend_limitTextLength(field, limit) {
    if (field.value.length >= limit) {
        field.value = field.value.substring(0, limit);
    }
}


/** MASQUAGE D'ELEMENTS ET LIAISON AVEC BOUTONS DE CONTROLE D'AFFICHAGE */

function toggleElem() {
	// On boucle sur tous les elements ayant la classe "togEl"
	$$('.togEl').each(function(oCtrl) {
		var oEl = $$('.' + oCtrl.id), iHeight = oEl[0].offsetHeight + 10;
		// On cache l'element ayant pour classe l'id du bouton de controle
		oEl.setStyles({
			'overflow': 'hidden',
			'height': oCtrl.checked ? iHeight : 0
		});
		// On ajoute un gestionnaire d'evenement
		oCtrl.addEvent('click', function() {
			this.checked ?
				$$('.' + this.id).each(function(oElm) { new Fx.Style(oElm, 'height').start(0, iHeight); }):
				$$('.' + this.id).each(function(oElm) { new Fx.Style(oElm, 'height').start(iHeight, 0); });
		});
	});
}

//try { window.addEvent('domready', toggleElem); } catch(e) { connect(window, 'load', toggleElem);}

/** CORRECTION CSS POUR FIREFOX 3.0 MAC : configurateur */

var CorrectifFx3Mac = new Class({
	initialize: function() {
		if(navigator.userAgent.match(/Firefox\/3/g)) {
			if(navigator.platform.match(/Mac/i)) {
				var oUl;
				if($('CarConfigurator') && (oUl = document.getElement('ul.stepHeading')))
					oUl.getElements('li').each(function(oLi) { oLi.style.paddingRight = oLi.style.paddingRight.toInt() - 1 + 'px'; });
			}
		}
	}
});

/** FONCTION VIDE NECESSAIRE SUR FINANCE */

var ReloadTipBox = new Class({
	initialize: function() {		
	}
});

function mySkinnedFormElements() {
	//Selects skinned 
	var mySkinnedSelect = $(document.body).getElements(".skinnedSelect");
	if(mySkinnedSelect.length != 0){
		mySkinnedSelect.each(function(el){
		//console.log(el.id)
			if(!($(el).hasClass("skinnedSelect2"))){
				new elSelect( {container : ""+el.id} );
			}else{
				new elSelect2( {container : ""+el.id} );	
			}			
		});
	}
	
	//Checkbox skinned 
	var mySkinnedCheck = new elRadioCheck({element : 'skinnedCheck', activeClass : 'skinnedCheckActive'});
	//Radio skinned 
	var mySkinnedCheck = new elRadioCheck({element : 'skinnedRadio', activeClass : 'skinnedRadioActive'});
	
}

window.addEvent('load', function() { new CorrectifFx3Mac; });
window.addEvent('domready', mySkinnedFormElements);


/*
 * pngFix
 */


function pngFix(elm, scale, noOverflow) {

	elm.style.filter = ' ';
	if (!(document.all && window.print && /MSIE [56]/.test(navigator.userAgent))) return;
	var exec = (function(elm, noOverflow) {
		return function() {


			var options = { noOverflow:noOverflow};
			var repeat = elm.currentStyle.backgroundRepeat.toLowerCase()=='repeat';
			elm.style.filter = ' ';
				// si l'élément est un tag img, on va en faire creer une balise qui encadrera cette image et ensuite traiter la balise comme si c'etait un élément qui avait une image de fond
				if (elm.nodeName.match(/^(IMG|INPUT)$/)) {
					if (!elm.src.match(/.*\.png$/)) return;

					elm.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+ elm.src + "')";

					elm.width = elm.offsetWidth;
					elm.height = elm.offsetHeight;

					/* recuperation de l'url du pixel transparent */
					var url = elm.currentStyle.backgroundImage.match(/^url\(["'](.*\.gif)["']\)$/); //seulement les .png
					elm.src = url[1];
					elm.className = elm.className.replace(/pngFix/g,'');

				}
				else {
					if (elm.currentStyle.backgroundImage == "" || elm.currentStyle.backgroundImage == "url()") return;
					var url = elm.currentStyle.backgroundImage.match(/^url\(["'](.*\.png)["']\)$/); //seulement les .png
					if (!url || url.length<2) return;
					var pngLayer = document.createElement('i'); // on genere un <i> en position:absolute (layer), qui viendra se placer sous le contenu du div  qui avait besoin du style.
					with(pngLayer.style) {
						if (options.noOverflow) {
							width = elm.offsetWidth + 'px';
							height = elm.offsetHeight + 'px';
						} else {
						 	width = '32000px';
							height = '32000px'; 
						}
						position = 'absolute';
						zIndex = -1;
						fontSize = '1%';
						filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='" + (options.noOverflow ? 'crop' : 'image') + "', src='"+url[1]+"')";
						background = 'none'; //forcing car parfois il peut arriver qu'on ai une CSS qui vienne rajouter des images / couleurs de fond
						/* positionnement de l'image en fonction du background-position sur l'element */
						if (!repeat) {
							switch((elm.currentStyle.backgroundPositionX+'').toLowerCase()) {
								case 'left' : left=0; break; 
								case 'right' : right = 0; break;
								case 'center' : 
									left='50%'; 
									setTimeout(function(pngLayer) {
										return function() {
											pngLayer.style.marginLeft = -(pngLayer.offsetWidth/2)+'px'; 
										}
									}(pngLayer), 50);
									break;
								default : 
									left = elm.currentStyle.backgroundPositionX; 
							}

							switch((elm.currentStyle.backgroundPositionY+'').toLowerCase()) {
								case 'top' : top = 0; break;
								case 'bottom' : bottom = 0; break;
								case 'center' : 
									top='50%'; 
									setTimeout(function(pngLayer) {
										return function() {
											pngLayer.style.marginTop=-(pngLayer.offsetHeight/2)+'px'; 
										}
									}(pngLayer), 100);
									break;
								default : 
									top = elm.currentStyle.backgroundPositionY || 0; 
							}
						} else {
							left = 0; //elm.currentStyle.backgroundPositionX +'';
							top = 0; //elm.currentStyle.backgroundPositionY +'';
						}
					} 


						/* gestion automatique du sizingMethod='scale' ou sizingMethod='image', ne pouvant pas tester le backgroundRepeat correctement, on passe par une methode un peu plus tricky */
						setTimeout(function(elmN, pngLayerN, repeatN) {
							return function() {

								if (!elmN || !elmN.parentNode || !pngLayerN || !pngLayerN.parentNode) return;
								if (pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod=='image') {
									if (pngLayerN.offsetWidth<elmN.offsetWidth && repeatN) {
										pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod='scale';
									} else if (pngLayerN.offsetWidth>elmN.offsetWidth && elm.currentStyle.backgroundPositionX.match(/^(left|0%|0px|0)$/) || elm.currentStyle.backgroundPositionY.match(/^(top|0%|0px|0)$/)){
										pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod='crop';
									}
								} else {
									pngLayerN.sizingMethod = 'image';
								}
								if (elm.currentStyle.width.match(/^(0|[12](%|px)?)$/)) {
									pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod='image';
								}
								if (pngLayerN.style.right != 'auto' && pngLayerN.style.right !='')
									setTimeout(function() {
										pngLayerN.style.right = parseInt(pngLayerN.style.right) - (elm.offsetWidth%2 ? 1 : 0) + 'px';
									}, 50)
							}
						}(elm, pngLayer, repeat), 200);

					with (elm.style) {
						position = elm.currentStyle.position=="static" || elm.currentStyle.position=="" ? 'relative' : position;
						if (elm.currentStyle.overflow!='auto' && elm.currentStyle.overflow!='hidden') overflow = options.noOverflow ? 'visible' : (elm.currentStyle.width.match(/^(0|[12](%|px)?)$/) ? 'visible' : 'hidden');
						backgroundImage = 'none';
					}
					elm.appendChild(pngLayer);

			}
		}
	})(elm, noOverflow);
	try{
		pngFixLoader.useOnload ? pngFixLoader.addFunc(exec) : exec();
	} catch(e) {};
}



/* pngFixLoader 
	@unction 		:	objet pour permet le lancement des modifications des png via pngFix en décalé sur le onload de la page.
							cela permet de contourner un bug d'internet explorer qui affiche un message d'erreur si le DOM est modifié pendant le chargement de la page.
*/
var pngFixLoader = {
	useOnload : true, // true : active l'execution du fixPng sur le load, et false, execute le fixPng dès qu'il est appelé par la CSS
	functions : [], // toutes les fonctions à éxécuter sur le onload de la page
	addFunc : function(func) {
		pngFixLoader.functions.push(func);
	},
	launch : function() {
			pngFixLoader.useOnload = false; //une fois la page chargée, il faut laisser s'executer automatiquement la fonction pour d'autres actions (ex : ouverture layer)
			var counter = 1;
			while(pngFixLoader.functions.length>0) {
				//setTimeout(pngFixLoader.functions.pop(), 20*counter);
				pngFixLoader.functions.pop()();
				counter++;
			}
	},
	init : function() {
		if (pngFixLoader.useOnload && window.attachEvent && document.all) {
			window.attachEvent('onload', function() {
				setTimeout(pngFixLoader.launch, 100);
			});
		}
	}
}
pngFixLoader.init();

// Fonction qui gere les hover des boutons à partir d'une classe spécifique
var boutonsHoverManagement = new Class({
   	initialize: function (classe){
		this.myElements = $$("."+classe);
		this.myElements.addEvent("mouseover",function(){
			this.addClass(classe+'hover');
		});
		this.myElements.addEvent("mouseout",function(){
			this.removeClass(classe+'hover');
		});
	}
});

window.addEvent('load', function() {
	new boutonsHoverManagement("bouton");
})



/* loader ultra générique */
var Loader = new Class({
	delayId : null,
	options : {
		fog : false,
		container : null
	},
	initialize : function(options){
		this.setOptions(options);
		this.doc = $(document.body);
		this.container = $(this.options.container) || this.doc;
		
		this.domMaker();
		
		//this.show();
	},
	domMaker : function(){
		this.loader = new Element('div', {'class' : 'loaderSimple'});
		this.doc.adopt(this.loader);
	},
	updateContainerPosition : function(){
		var _c = this.container.getCoordinates();
		if (this.loader)this.loader.setStyles(this.container.getCoordinates());
		this.loader.setStyles({
			'left' : _c.left,
			'top' : _c.top,
			'width': _c.width,
			'height' : _c.height
		})
	},
	show : function(options){
		this.updateContainerPosition();
		if(this.options.fog){
			this.fogAdd();
		}
		
		this.delayId = this.updateContainerPosition.delay(1000, this);
		
	},
	hide : function(){
		if (this.delayId) {
			clearTimeout(this.delayId);
		}
		this.loader.setStyles({
			'left' : -10000,
			'top' : -10000
		})
		if(this.options.fog){
			this.fogHide();
		}
	},
	fogAdd : function(){
		ifrlayer.make(this.loader); //genere ou affiche l'iframe
		
		this.loader.addClass('loaderSimpleActiveFogged');
	},
	fogHide : function(){
		
		ifrlayer.hide(this.loader);
	}
})
Loader.implement(new Options, new Events);



/**
	TODO 
		inject loading structure
		wait (bool)
*/

var FogManager = new Class({

	options: {
		onStartOpen: function(){}, // au lancement de l'ouverture
		onCompleteOpen: function(){}, // a l'ouverture complete
		onStartClose: function(){}, // au lancement de la fermeture
		onCompleteClose: function(){}, // a la fermeture complete
		duration: 200, // duree anim
		styles: false, // objet de style pour le fog
		locked: false, // a tres, empeche la fermeture du layer au clic 
		noAnimation: false, // n'effectue pas d'effet de fondu,
		setTo: null, // element sur lequel positionner le layer , defaut <body>
		loading: false, 
		keepClose: false, // ne pas ouvrir le layer (pour une ouverture manuelle)
		name : "", // nom de l'element, sert dans FogBox.js
		ie6FixedPosition: true, // simule le position:fixed sur ie (gourmand setInterval)
		content: null, // node | string html
		iframeSrc: null,
		ajaxText: null,
		ajaxJSON: null,
		template: null, // template a utliser substitute avec JSON replace __CONTENT__ avec HTML
		ajaxNoCache: false,
		ajaxOptions: null // option de l'object Request a utiliser, ne pas modifier le onComplete ou le onSuccess
	},
	
	setContent: function (content){
		//console.trace();
		this.contentType = $type(content);
		switch(this.contentType){
			case "element":
				if(this.options.template){
					var d = new Element("div", {"html": this.options.template});
					$(document.body).adopt(d);
					$('FOG-CONTENT').adopt(content);
					this.ctnElement = d;
				}
				else {
					this.ctnElement = content;
					$(document.body).adopt(this.ctnElement);
				}
				break;
			case "object":
				this.ctnElement = new Element("div", {"html": this.options.template.substitute(content)});
				$(document.body).adopt(this.ctnElement);
				break;
			case "string":
				if(this.options.template){
					this.ctnElement = new Element("div").setHTML(this.options.template.replace(/__FOGCONTENT__/, content));
				}
				else {
					this.ctnElement = new Element("div").setHTML(content);
				}
				$(document.body).adopt(this.ctnElement);
				break;
				
		}
		//console.log('here')
		if(!this.ctnElement.hasClass("layer") && !this.ctnElement.getElement(".layer")) this.ctnElement.addClass("layer");
		if(!this.options.keepClose) this.open();
		//console.log('here2');

	},
	
	initialize : function (options){
		this.setOptions(options)
		
		// ferme par defaut
		this.isOpen = false;
		this.onDom = false;
		// creation de la structure
		this.elm = new Element("div", {'class': 'fog hidden'});
		this.elm.store("FogManager", this);
		// ifr pour ie6
		if(window.ie6){
			this.ifr = new Element('iframe');
			this.ifr.src = "javascript:false";
			$(document.body).adopt(this.ifr);
		}
		$(document.body).adopt(this.elm);
		this.get_CSS_style();
		this.elm.setStyles(this.options.styles);
		
		// recuperation du contenu
		switch(true){
			case this.options.ajaxText != null:
				new Request({
					url: this.options.ajaxText, 
					noCache: this.options.ajaxNoCache,
					onSuccess: 	
						function (oSelf){
							return function(responseText, responseXML){
								oSelf.setContent(responseText);
							}
						}(this)
					}).send();
				break;
			case this.options.ajaxJSON != null:
				new Request.JSON({
					url: this.options.ajaxJSON, 
					noCache: this.options.ajaxNoCache,
					onSuccess: 	
						function (oSelf){
							return function(responseJSON, responseText){
								oSelf.setContent(responseJSON);
							}
						}(this)
					}).send();
				break;
			case this.options.content != null:
				if($type(this.options.content) == "element") {
					this.onDom = true;
					this.options.template = null;
				}
				//console.log('test');
				this.setContent(this.options.content);
				//console.log('testAfter');
				break;
			case this.options.iframeSrc != null:
				this.setContent(new Element('iframe', {'src': this.options.iframeSrc}));
				break;
			default:
				if(this.options.loading) this.wait(true);
				this.onDom = true;
				this.open();
		}
		
		
		// au resize, on repositionne
		Notifier.addEvent("onLayoutChanged", function (){
			this.setToElm(this.lastElm);
		}.bind(this))
		
		window.addEvent("resize", function (){
			this.setToElm(this.lastElm);
		}.bind(this))
		
		// fermeture definitive
		this.addEvent('onCompleteClose', 
			function (){
				// destruction
				if(!this.elm) return;
				this.isOpen = false;
				this.elm.dispose();
				if(!this.onDom) this.ctnElement.dispose();
				if(this.interval) clearInterval(this.interval);
				if(this.ifr) this.ifr.dispose();
			}
		)
		
		if(!this.options.locked) this.elm.addEvent('click', function (){this.close();}.bind(this));
	},
	
	get_CSS_style: function (){
		if(!this.options.styles) this.options.styles = {};
		if(!this.options.styles.backgroundColor) this.options.styles.backgroundColor = this.elm.getStyle("backgroundColor");
		if(!this.options.styles.opacity) this.options.styles.opacity = this.elm.getStyle('opacity');
	},
    
  toggle: function(){
		this.isOpen == true ? this.close() : this.open();
  },
    
  open: function (){
		this.fireEvent("onStartOpen", this.elm, $(this.options.setTo));
		this.setToElm();
		//console.log('open')
		if(this.options.noAnimation) {
			this.elm.removeClass('hidden');
			this.ctnElement.removeClass('hidden');
			this.ctnElement.setStyle("marginLeft", -this.ctnElement.offsetWidth/2)
			this.ctnElement.setStyle("marginTop", -this.ctnElement.offsetHeight/2)
			this.ctnElement.setStyle("opacity", "1")
			this.ctnElement.getElements(".layerClose").addEvent("click", function (e){e.stop();this.close();}.bind(this))
			this.fireEvent("onCompleteOpen", this.elm, $(this.options.setTo));
			return;
		}
		//console.log(this.ctnElement)
		if(this.ctnElement){
			elm = $(this.ctnElement);
			
			try {elm.getElements(".layerClose").addEvent("click", function (e){e.stop();this.close();}.bind(this))}
			catch(e){}
			
			// ajout de l'anim sur le ctn
			this.currentContent = elm;
			var myFx2 = new Fx.Style(elm, "opacity", {
				onStart: function (){
					this.element.removeClass("hidden");
					this.element.setStyle("marginLeft", -this.element.offsetWidth/2);
					this.element.setStyle("marginTop", -this.element.offsetHeight/2);
				},
				duration: this.options.duration
			});
			//console.log(myFx2)
			myFx2.start(0, 1);
			this.fixTopPosition();
		}
		else {
			this.currentContent = null;
		}
		//console.log('test3');
		var _self = this;
		// ouverture du fog
		var myFx = new Fx.Style(this.elm, "opacity", {
			onStart: function (){
				
				this.elm.removeClass("hidden");
				
			}.bind(this),
			onComplete: function (){
				this.fireEvent("onCompleteOpen", this.elm, $(this.options.setTo));
				this.isOpen = true;
				//this.createIfr();
			}.bind(this),
			duration: this.options.duration
		});
		myFx.start(0, this.options.styles.opacity);
		//console.log('test5');
	},
	
	close: function (){
		this.wait(false);
		
		if(this.options.noAnimation) {
			this.fireEvent("onCompleteClose", this.elm, $(this.options.setTo));
			return;
		}
		
		// fermeture du fog
		var myFx = new Fx.Style(this.elm, "opacity", {
			onStart: function (){
				this.fireEvent("onStartClose", this.elm, $(this.options.setTo));
			}.bind(this),
			onComplete: function (){
				this.fireEvent("onCompleteClose", this.elm, $(this.options.setTo));
			}.bind(this),
			duration: this.options.duration + 10
		});
		
		myFx.start(this.options.styles.opacity, 0);
		
		if(this.ctnElement){
			var myFx2 = new Fx.Style($(this.ctnElement), {
				onStart: function (){}.bind(this),
				onComplete: function (){
				}.bind(this),
				duration: this.options.duration
			});
			myFx2.set("opacity", "1");
			myFx2.start("opacity", "0");
		}
	},
	
	setToElm: function (){
		
		if(this.options.setTo && $(this.options.setTo)){
			var coo = $(this.options.setTo).getCoordinates();
			this.elm.setStyles({
				"width": coo.width,
				"height": coo.height,
				"top": coo.top,
				"left": coo.left
			})
		}
		else {
			var w = Math.max(document.body.scrollWidth, document.documentElement.clientWidth);
			var h = Math.max(document.body.scrollHeight, document.documentElement.clientHeight);
			if(!this.options.styles.width || !this.options.styles.width === 0) this.elm.setStyle('width', w)
			if(!this.options.styles.height ||!this.options.styles.height === 0) this.elm.setStyle('height', h)
			if(!this.options.styles.top ||!this.options.styles.top === 0) this.elm.setStyle('top', 0)
			if(!this.options.styles.left ||!this.options.styles.left === 0) this.elm.setStyle('left', 0)
		}
		if(window.ie6){
			this.ifr.setStyles({
				"width": document.body.scrollWidth,
				"height": document.body.scrollHeight,
				"top": 0,
				"left": 0,
				"zIndex": 998,
				"position": "absolute",
				"filter": "mask()",
				"visibility": "visible"
				})
		}
	},
	
	fixTopPosition: function (){
		//console.log('before in Fix To POsition')
		if(window.ie6){
			var wHeight = document.documentElement.clientHeight;
			this.interval = setInterval(function (oSelf){
				return function (){
					
						oSelf.currentContent.setStyle("marginTop", document.documentElement.scrollTop + (wHeight / 2) - (oSelf.currentContent.offsetHeight/2))
				}
			}(this), 1);
		}
		//console.log('in Fix To POsition')
	},
	
	strToNode: function (str){
		var div = new Element('div', {"html": str});
		return div.getFirst();
	},
	
	wait: function (bool){
		if(bool){
			this.elm.adopt(new Element('div', {'class': 'fogSpinner'}));
		}
		else {
			this.elm.getElements('.fogSpinner').each(function (el){
				el.remove();
			})
		}
		return this;
	}
});
FogManager.implement(new Options, new Events);




var ShareManager = new Class({
       options : {
               elId : null, // String : id of element wher we'll insert script tag
               urlLink : null, // String : Url of the link to call
               urlScript : null, // String : Url of script to call
               libelle : null, // String : label of share
               delay : 500 // Integer : delay to set
       },
       template : [
               '<div class="addthis_toolbox addthis_default_style">',
                       '<a class="addthis_button_facebook"></a>',
                       '<a class="addthis_button_favorites"></a>',
                       '<span class="addthis_separator">|</span>',
                       '<a class="addthis_button_expanded" href="{urlLink}">{libelle}</a>',
               '</div>'
       ].join(''),
       template_br_BR : [
               '<div class="addthis_toolbox addthis_default_style">',
                       '<a class="addthis_button_orkut"></a>',
                       '<a class="addthis_button_favorites"></a>',
                       '<span class="addthis_separator">|</span>',
                       '<a class="addthis_button_expanded" href="{urlLink}">{libelle}</a>',
               '</div>'
       ].join(''),
       template_ru_RU : [
               '<div class="addthis_toolbox addthis_default_style">',
                       '<a class="addthis_button_facebook"></a>',
                       '<a class="addthis_button_vk"></a>',
                       '<a class="addthis_button_favorites"></a>',
                       '<span class="addthis_separator">|</span>',
                       '<a class="addthis_button_expanded" href="{urlLink}">{libelle}</a>',
               '</div>'
       ].join(''),
       initialize : function(options){
               this.setOptions(options);
               if (!this.options.elId || !this.options.urlLink || !this.options.urlScript || !this.options.libelle){
                       return;
               }
               this._el = $(this.options.elId);
               this._el.setOpacity(0);
               this._el.setStyle('display', 'none');
               this.generateHTML();
               this.initScript.delay(this.options.delay, this);
       },
       getTemplate : function(){
               return this['template_'+ cufonSiteLocal] || this.template;
       },
       generateHTML : function(){
               var _s = this.getTemplate().substitute({
                       'urlLink' : this.options.urlLink,
                       'libelle' : this.options.libelle
               })
               this._el.innerHTML = _s;

               var script = new Element('script');
           script.src =  this.options.urlScript;
               $(document.body).adopt(script);
       },
       initScript : function(){

               addthis.init();
               this._el.setStyle('display', 'block');
               this._el.effect('opacity').start(1);
			   setTimeout(function(){
					generateTracksShareBox();
				},500);
       }
})
ShareManager.implement(new Options);


function trackToggle(source,target){
	sendGA(['_trackEvent',window.location.pathname,source,target]);
}




function generateOutboundsClick(){
	$(document.body).addEvent("click", function(e){
		var target = e.target || e.srcElement;
		var parentone = $(target).getParent();
		if(parentone.nodeName != "HTML"){
			var parenttwo = $(target).getParent().getParent() || $(document.body);
		}else{
			var parenttwo = parentone;
		}
		if(parenttwo.nodeName != "HTML"){
			var parentthree = $(target).getParent().getParent().getParent();
		}else{
			var parentthree = parentone;
		}

		if(target.nodeName == "A"){
			outBoundClick(target, e);
		}else if(parentone && parentone.nodeName == "A"){
			outBoundClick(parentone, e);
		}else if(parenttwo && parenttwo.nodeName == "A"){
			outBoundClick(parenttwo, e);
		}else if(parentthree && parentthree.nodeName == "A"){
			outBoundClick(parentthree, e);
		}
	});
}

function outBoundClick(elem,e){

	var reg=new RegExp("[/]+", "g");
	var href= elem.href.split(reg);
	var documentLoc = window.location.hostname.split(reg);
	
	if(href[0] == "http:" && href[1] != documentLoc && href[1] != "www.addthis.com"){
		if(elem.target && elem.target == "_blank"){
			sendTracker("Outbound links","Goto "+elem.href,window.location.href);
		}else{
			new Event(e).stop();
			sendTracker("Outbound links","Goto "+elem.href,window.location.href);
			setTimeout(function(){
				window.location.href=elem.href;
			},300);
		}
	}
}

function generateTracksShareBox(){

	var sharethis = $(document.body).getElements("div.addThis a");

	if(sharethis.length != 0){
		sharethis.each(function(elem){
			if($(elem).hasClass("addthis_button_facebook")){
				elem.trackevent = ['_trackEvent','Social networks','Share Facebook',window.location.href];
			}else if($(elem).hasClass("addthis_button_favorites")){
				elem.trackevent = ['_trackEvent','Bookmark','Bookmark page',window.location.href];
			}else if($(elem).hasClass("addthis_button_expanded")){
				elem.trackevent = ['_trackEvent','Social networks','Share addthis',window.location.href];
			}
			$(elem).addEvent("click", function(){
				// balancer trackEvent
				sendGA(this.trackevent);

				if($(this).hasClass("addthis_button_expanded")){
					//sendGA(['_trackPageview',window.location.pathname+'/Share page']);
					setTimeout(function(){generateOnclickSharePage();},500);
				}
			});

		});
	}
}
function generateOnclickSharePage(){
	var atitem = $(document.body).getElements("div.at_item");
	if(atitem.length != 0){
		atitem.addEvent("click",function(){
			var action = this.id.replace("ati_","");
			// send tracker
			sendGA(['_trackEvent','Social networks',action,window.location.href]);
		})
	}
}

function generateClicksActionButtons(){
	var abuttons = $(document.body).getElements("div.PageTitleBlock .actionButtons a");
	if(abuttons.length != 0){
		abuttons.addEvent('click',function(){
			if($(this).hasClass("print")){
				if($("page").hasClass("bodyPopup")){
					//sendGA(['_trackPageview',window.location.pathname+'/Print page']);	
				}else{
					sendGA(['_trackEvent','Print page','Print',window.location.href]);
				}
			}else if($(this).hasClass("send")){
				sendTracker('send to friend','click on send button',""+document.location.href);
			}
		})
	}
}



function executeTimeout(array){
	setTimeout(function(){
		if(array.length != 0){
			for(var i =0; i< array.length; i++){
				var fonction = array[i][0];
				var params = array[i][1];
				var self = array[i][2];

				var paramsEval = "";
				//console.log(params)
				for(var j=0; j< params.length; j++){

					var paramTopass = "";
					if(params[j] == 'self'){
						paramTopass = 'self';
					}else if(params[j] == true || params[j] == false){
						paramTopass = params[j];
					}else{
						paramTopass = "'"+params[j]+"'"
					}


					if(j != 0){
						paramsEval += ","+paramTopass+"";
					}else{
						paramsEval += ""+paramTopass+"";
					}
				}

				//console.log(fonction, paramsEval);
				//console.log(fonction+"("+paramsEval+");")
				eval(fonction+"("+paramsEval+");");

			}
		}
	},400);
}

function trackToggle(source,target,carname){
	if(typeof customCarVars != "undefined"){
		if(customCarVars && customCarVars.GASubCateg){
			source = customCarVars.GASubCateg;
			sendGA(['_trackEvent',source,target,window.location.pathname]);
		}
	}
}

function submitTimeout(input){

	setTimeout(function(){
		if(typeof input == "string"){
			$(input).submit();
		}else{
			input.form.submit();
		}
	},300)
}


/* Fonction generique d envoi de stats */
function sendGen(object){
	/* on base les envois sur le paramTracker qui se decompose de la maniere suivante :
		paramTracker = {
			'sys' : typedusysteme,				avec typedusysteme "GA" ou "55"
			'test' : boolean					indique si on est en local ou pas
		}
		
		object recu : exemple:
		{
			"55":{
				"d":"sfsdfsdfsd",
				"fc":[4,"data","name"]
			},
			"GA":["_trackEvent", "data", "name", "value"]
		}
	*/
	
	if(typeof paramTracker != 'undefined' && object[paramTracker.sys]) {
		if(paramTracker.test){
			// on envoie au systeme de test local
            try {
                var localRemote = new Json.Remote(paramTracker.url + '?' + paramTracker.sys  + '=' + object[paramTracker.sys], {
                    onComplete: function(reponse){}
                }).send();
            } catch (e) {
				/*if (console && console.log) {
					console.log("XMLHttpRequest failed because of CrossDomain request.\r Sending " + paramTracker.sys  + '=' + object[paramTracker.sys]);
				} else {
					alert("XMLHttpRequest failed because of CrossDomain request.\r Sending " + paramTracker.sys  + '=' + object[paramTracker.sys]);
				}*/
            }
        }else{
			// on envoie au systeme de tracking approprie
			switch(paramTracker.sys){
				case "GA":
					if(typeof(_gaq) != 'undefined'){
						var objtosend = [];
						for(var i=0; i<object[paramTracker.sys].length; i++){
							var tmpVar = object[paramTracker.sys][i].removeacc().toLowerCase();
							objtosend[i] = tmpVar;
						}
						_gaq.push(object[paramTracker.sys]);
					}
					break;
				case "55":
					for(j in object[paramTracker.sys]){
						tracker55[j]= object[paramTracker.sys][j];
					}
					break;
				default:
					break;
			}
		}
	}
	
	if (object['link']) {
		setTimeout('document.location = "' + object['link'] + '"', 100);
	}
}

function getSiteStructure() {
	var pathname = window.location.pathname;
	return pathname.substring(0, pathname.lastIndexOf('/'));
}


//fonction lancee pendant le chargement de la page
window.addEvent('domready', function() {
	setCufonMenu();
	toggleElem();
	maxLengthOntextarea();
	generateElements();
	generateOutboundsClick();
	generateClicksActionButtons();
	generateLabelHover();
//	if(window.khtml||window.ie) sizeBlocks();
});
//fonction lancee une fois toute la page chargee
window.addEvent('load', function () {
	setCufon();
	sizeBlocks();	
	rightNavEsc();
	galleryScroller();
	accordeon();
	createColorSteps();
	reposBlocks();
	
	/// F6 DEBUG sizingBody();
	new SelectLinks;
	new MediaScroll;
	
	var headsLinear = document.getElements('.stepHeadLinear');
	if (headsLinear && headsLinear.length != 0)
		setStepHeadingLength();
});

function reposBlocks(){
	var myReposBlocks = $$(".reposBlock");
	if(myReposBlocks.length != 0){
		myReposBlocks.each(function(elem){
			var blockHeight = $(elem).offsetHeight;
			var elemRepo = $(elem).getElement(".reposElement");
			var elemHeight = $(elemRepo).offsetHeight;
			
			if(elemHeight<blockHeight){
				var padding = (blockHeight-elemHeight)/2;
				$(elemRepo).setStyles({
					"padding-top":padding,
					"padding-bottom":padding
				});
			}
			
		})
	}
}


function generateLabelHover(){
	var labelBlocksHover = $$(".labelHoverLine");
	if(labelBlocksHover.length != 0){
		labelBlocksHover.each(function(elem){
			var myLabelHover = new LabelHover(elem, labelBlocksHover);
		});
	}
}

var LabelHover = new Class({
	options : {},
	initialize : function(block, blocks, options){
		this.blocks = blocks;
		this.label = $(block).getElement("label.labelHover");
		
		this.input = $(block).getElement("input.text");
		
		$(this.input).addEvent("focus",function(){
			//console.log("focus ", this.input.name);
			$(this.label).addClass("hidden");
		}.bind(this))
		
		$(this.input).addEvent("change",function(){
			//console.log("change ", this.input.name);
			this.checkFields();
		}.bind(this));
		
		$(this.input).addEvent("blur",function(){
			//console.log("blur ", this.input.name);
			this.checkFields();
		}.bind(this))
	},
	checkFields : function(){
		this.blocks.each(function(elem, index){
			this.checkField(elem);
		}.bind(this));
	},
	checkField : function(elem){
		var labelelem = $(elem).getElement("label.labelHover");
		var inputelem = $(elem).getElement("input.text");
		
		if(inputelem.value != ""){
			$(labelelem).addClass("hidden");
		}else{
			$(labelelem).removeClass("hidden");
		}
	}
});



/**
 * Name: AutoComplete
 * Date: 04/05/11
 */

//window.addEvent('load', function(){
//	var localisation = new AutoComplete({
//		element : 'localisation', //ID sur lequelle on declare l'autocomplete
//		url: 'http://renault.berseron.f6.fr:8081/pages/dealerLocator/dealer.json', // URL du webservice
//		lengthBeforeSearch : 2 //Nombre de caractere a partir du quel l'autocomplete s'execute
//	});
//});



var AutoComplete = new Class({
	/**
	 * @property {Object} Implement options / events gestion on that class
	 */
	dropdown : null,
	result : [], //the ajax result
	hasFocus : false,
	enabled : true,
	options : {
		mode : 'autocomplete', //mode : "autocomplete" for default mode, or can be "displaylist" for only displaylist action
		className:'rt_dropdown',
		customClass: '',
		element : null,
		alwaysontop : false,
		showLabelTwo : true,
		triggerEvent : 'keyup',
		url : '', //url of the service
		triggerDelay : 200,
		lengthBeforeSearch : 2,  //number of chars before start search
		ajaxCall : function(thisp, query) {
			return thisp.ajaxCall(query);
		},
		ajaxSuccess : function(thisp, result) {
			return thisp.ajaxCallOnSuccess(result);
		},
		ajaxError : function(thisp, result) {
			return thisp.ajaxCallError(result);
		},
		parseDataFunction : function(thisp, data) {
			var dealersResult = eval('(' + data + ')');
//			console.info(dealersResult)

			var aReturn = [];

			for (var i = 0; i < dealersResult.length; i++) {
				var obj = dealersResult[i];
				aReturn.push(dealersResult[i]);
			}

			return aReturn;
		},
		onChoice : function() {
			//trigged when choice is made
		},
		onBeforeDropdownShow : function() {

		},
		onAfterDropdownHide : function() {

		},
		onKeyboardChar : function(event) {

		}
	},

	initialize : function(options) {
		var _this = this;
		options = options || {};

		this.setOptions(options);

		this.element = $(this.options.element);

		if (!this.element) {
		//	alert('no element found');
			return;
		}

		this.element.setAttribute('autocomplete', 'off');

		// bind the trigger event by a reset function cause it bugs
		this.element.addEvent('focus', function() {
			_this.hasFocus = true;
			//_this.resetElementEvent();
		});

		this.element.addEvent('focusout', function() {
			_this.hideDropdownTimer = setTimeout(function() {
				if(!_this.isDropdownOpened()) _this.hideDropDown();
			}, 200);
			_this.hasFocus = false;
		});
		this.addElementTriggerEvent();

		this.element.addEvent('keydown', function(e) {
			_this.elementKeyDownHandler(e);
		});
	},

	//====================================
	// ELEMENT ACTION
	//====================================

	addElementTriggerEvent : function() {
		var _this = this;
		this.element.addEvent(this.options.triggerEvent,
				function() {
					_this.triggerHandler();
				});
	},

	triggerTimer : null,
	triggerHandler : function() {
		var	_this = this,
			val = this.element.getValue();

		if (this.options.mode == 'autocomplete') {
			if (this.query != val) {
				if (this.triggerTimer) clearTimeout(this.triggerTimer);
				if (val.length == 0) {
					this.query = val;
					this.hideDropDown();
				} else {
					if (val.length >= this.options.lengthBeforeSearch) {
						this.triggerTimer = setTimeout(function() {
							_this.triggerTimerEnd();
						}, this.options.triggerDelay);
					}
				}
			}
		} else {
			if (!this.isDropdownOpened()) {
				this.showDropDown();
				//this.dropDownOpened = false;
			}
		}
	},

	triggerTimerEnd : function() {
		this.doAjax(this.element.getValue());
	},

	doAjax : function(value) {
		if (value != this.query) {
			this.query = value;
			if (this.enabled) {
				this.options.ajaxCall(this, value);
			}
		}
	},

	//====================================
	// DROPDOWN ACTION
	//====================================

	dropdownClickHandler : function(e) {
		var target = new Event(e).target;
		while (target.parentNode && target.nodeName != 'LI') {
			target = $(target).getParent();
		}
		new Event(e).stop();
		if (!$(target).getParent()) {
			return;
		}
		this.fillElement(target.getAttribute('original'));
		this.createParamsHandler(target.getAttribute('rel'));
		this.hideDropDown();
		//this.dropDownOpened = true;
//		this.element.focus();
		//return false;
	},
	createParamsHandler : function(index){
		var objParams = this.originalResults[index];
		var formElem = this.element.form;
		if(objParams.params){
			for(var i in objParams.params){
				if(formElem[i]){
					var elem = formElem[i];
					elem.value = objParams.params[i];
				}else{
					$(formElem).adopt(new Element("input",{'type':'hidden', 'name':i, 'id':i, 'value':objParams.params[i]}));
				}
			}
		}
	},
	createDropdown : function() {
		var _this = this;
		if (!this.dropdown) {
			this.dropdown = new Element('div', {'class':this.options.className});
			if(this.options.customClass != ""){
				this.dropdown.addClass(this.options.customClass);
			}
			this.dropdown.innerHTML = '<ul class="dpcontent"></ul>';
			this.dropdown.addEvent('click', function(e) {
				_this.dropdownClickHandler(e);
			});
			this.dropdown.addEvent('keydown', function(e) {
				_this.dropdownKeyDownHandler(e);
			});
			this.dropdown.addEvent('focusout', function(e) {
				_this.hideDropdownTimer = setTimeout(function() {
					if (!_this.hasFocus) {
						_this.hideDropDown();
					}
				}, 100);
			});
			this.dropdown.addEvent('focusin', function(e) {
				clearTimeout(_this.hideDropdownTimer);
			});
			this.dropdown.setStyles({
				'visibility' : 'hidden',
				'position' : 'absolute',
				'top' : -5000,
				'left' : -5000
			});
			$(document.body).adopt(this.dropdown);
		}
	},

	showDropDown : function() {
		if (this.enabled && this.hasFocus && this.result.length > 0) {
			this.fireEvent('onBeforeDropdownShow', [this]);
			this.createDropdown();
			this.dropdown.setStyles({
				visibility: 'hidden'
			});
			this.setDropDownSizeAndPosition();
			this.dropdown.setStyles({
				visibility: 'visible'
			});
		}
	},

	hideDropDown : function() {
		if (this.dropdown) {
			this.dropdown.setStyles({
				visibility: 'hidden'
			});
			//this.dropDownOpened = false;
			this.fireEvent('onAfterDropdownHide', [this]);

			if(this.fixiframe) {
				this.fixiframe.style.display = 'none';
			}
		}
	},

	isDropdownOpened : function() {
		return this.dropdown ? this.dropdown.offsetHeight > 0 : false;
	},
	setDropDownSizeAndPosition : function() {
		var position = this.element.getCoordinates();
		
		var documentHeight = $(document.body).offsetHeight;
		var positionDropDown = position.top + position.height;
		
		var positionDropDownFinal = positionDropDown + this.dropdown.offsetHeight;
		if(positionDropDownFinal >= documentHeight || this.options.alwaysontop){
			positionDropDown = position.top - this.dropdown.offsetHeight;
		}
		
		this.dropdown.setStyles({
			position : 'absolute',
			left: position.left,
			top: positionDropDown,
			width : position.width,
			zIndex :1000
		});

		var el = this.dropdown;
		if (!this.fixiframe && document.all && window.print && /MSIE [567]/.test(navigator.userAgent)) {
			var iframeStr = '<iframe src="javascript:;" style="filter:alpha(opacity=0); height:'+el.offsetHeight+'px;width:'+el.offsetWidth+'px;left:'+el.currentStyle.left+';top:'+el.currentStyle.top+';z-index:'+(el.currentStyle.zIndex-1)+';position:absolute;"></iframe>';
			this.fixiframe = document.createElement(iframeStr);
			document.body.appendChild(this.fixiframe);
		}

		if(this.fixiframe) {
			with({s:this.fixiframe.style, es:el.currentStyle}) {
				s.display = 'block';
				s.left = es.left;
				s.top = es.top;
				s.height = el.offsetHeight+'px';
				s.width = el.offsetWidth+'px';
			}
		}
	},

	//====================================
	// AJAX Methods
	//====================================

	ajaxCall : function(query) {
		var data = 'q=' + query;
		var _this = this;

		var myAjax = new Ajax(this.options.url, {
			method : 'POST',
			data : data,
			onComplete : function(request) {
				_this.options.ajaxSuccess(_this, request);
			},
			onError : function() { /** error */
				_this.options.ajaxError(_this, arguments);
			}
		}).request();
	},

	ajaxCallOnSuccess : function(result) {
		this.showResult(result);
	},

	ajaxCallError : function() {
		//console.error('ajax Error');
	},

	showResult : function(result) {
		this.originalResults = eval(result);
		this.result = this.options.parseDataFunction(this, result);
		var html = this.dataToHTML(this.result);
		this.createDropdown();
		this.dropdown.getElement('.dpcontent').innerHTML = html;

		if (this.options.mode == 'autocomplete' || (this.hasFocus && this.options.mode == 'displaylist' && this.element.getValue() == '')) {
			this.showDropDown();
		}
	},

	dataToHTML : function(list) {

		for (var i = 0; i < list.length; i++) {
			var labelToShow = list[i].label1;
			if(this.options.showLabelTwo){
				labelToShow += ' [' + list[i].label2 + ']';
			}
			list[i] = '<li original="'+ labelToShow +'" rel="'+i+'"><a href="#"><span class="town">' + list[i].label1 + '</span><span class="cp">' + list[i].label2 + '</span></a></li>';
		}

//		for (var i = 0; i < list.dealer.length; i++) {
//			list[i] = '<li original="' + list[i] + '"><a href="#">' +
//					list[i].replace(new RegExp('(' + this.query.replace(/([\-])/g, '\$1') + ')', 'gi'), '<strong>$1</strong>') +
//					'</a></li>';
//		}

		return list.join('');
	},

	// =====================
	// keyboard management
	// =====================
	/**
	 *
	 * @param {Event} e
	 */
	elementKeyDownHandler : function(e) {
		var key = e.keyCode || e.which;
		switch (key) {
			case 13 : // ENTER
				new Event(e).stop();
				break;
			case 40 : // DOWN ARROW
				if (this.element.getValue().length >= this.options.lengthBeforeSearch && !this.isDropdownOpened()) {
					this.showDropDown();
				}
				this.gotoDropdown();
				new Event(e).stop();
				break;
			case 9 : // TAB
				if (this.isDropdownOpened()) {
					this.gotoDropdown();
					new Event(e).stop();
				}
				break;
			case 27 :
				this.hideDropDown();
				break;
			default :
				this.fireEvent('onKeyboardChar', e);
				break;
		}
	},

	currentFocusedElement : 0,
	gotoDropdown : function() {
		this.dropdownFocusElement(0);
	},

	dropdownFocusElement : function(value) {
		if (!this.dropdown) return;

		var links = this.dropdown.getElements('li');
		if (value < 0) {
			value = 0;
		} else if (value > links.length - 1) {
			value = links.length - 1;
		}
		//console.log(links, value);
		links[this.currentFocusedElement].removeClass('focus');
		this.currentFocusedElement = value;
		var item = links[value];
		item.getElement('a').focus();
		item.addClass('focus');
	},

	dropdownKeyDownHandler : function(e) {
		var key = e.keyCode || e.which;
		switch (key) {
			case 38 : // UP ARROW
				if (this.currentFocusedElement == 0) {
					this.element.focus();
				} else {
					this.dropdownFocusElement(this.currentFocusedElement - 1);
				}
				new Event(e).stop();
				break;
			case 40 : // DOWN ARROW
				this.dropdownFocusElement(this.currentFocusedElement + 1);
				new Event(e).stop();
				break;
			case 9 : // TAB
				if (e.shiftKey) {
					if (this.currentFocusedElement == 0) {
						this.element.focus();
					} else {
						this.dropdownFocusElement(this.currentFocusedElement - 1);
					}
				} else {
					this.dropdownFocusElement(this.currentFocusedElement + 1);
				}
				new Event(e).stop();
				break;
			case 27 :
				this.element.focus();
				this.hideDropDown();
		}
	},

	//=====================
	// others
	//=====================
	fillElement : function(value) {
		this.element.setProperty('value', value);
		this.query = value;
		this.fireEvent('choice');
	}
});

AutoComplete.implement(new Options, new Events);
	//=====================
	// for GA : send pathname to flash player.
	//=====================
function getWindowPathForFlash(){
		var theMovie;
		if (navigator.appName.indexOf("Microsoft") != -1) {
			theMovie =  window["blockFlashHome"];
		} else {
			theMovie = document["blockFlashHome"];
		}
		theMovie.sendTracker(window.location.pathname);
}

function getSubCategForFlash(){
	var subreturn = "";
	if(typeof customCarVars != "undefined"){
		if(customCarVars && customCarVars.GASubCateg){
			subreturn = customCarVars.GASubCateg;
		}
	}
	
	$('bgSize').getSubCateg(subreturn);
	
}



/* Popin contact */
var LabelHover = new Class({
	options : {},
	initialize : function(block, blocks, options){
		this.blocks = blocks;
		this.label = $(block).getElement("label.labelHover");
		this.input = $(block).getElement("input.text");
		
		$(this.label).addEvent("click",function(){
			$(this.input).focus();
		}.bind(this))
		
		$(this.input).addEvent("focus",function(){
			$(this.label).addClass("hidden");
		}.bind(this))
		
		$(this.input).addEvent("change",function(){
			//console.log("change ", this.input.name);
			this.checkFields();
		}.bind(this));
		
		$(this.input).addEvent("blur",function(){
			//console.log("blur ", this.input.name);
			this.checkFields();
		}.bind(this))
	},
	checkFields : function(){
		this.blocks.each(function(elem, index){
			this.checkField(elem);
		}.bind(this));
	},
	checkField : function(elem){
		var labelelem = $(elem).getElement("label.labelHover");
		var inputelem = $(elem).getElement("input.text");
		
		if(inputelem.value != ""){
			$(labelelem).addClass("hidden");
		}else{
			$(labelelem).removeClass("hidden");
		}
	}
});

function layerPopinOnComplete(form){

	var labelBlocksHover = $(form).getElements(".labelHoverLine");
	if(labelBlocksHover.length != 0){
		//console.log(labelBlocksHover)
		labelBlocksHover.each(function(elem){
			var myLabelHover = new LabelHover(elem, labelBlocksHover);
		});
	}

}

var iframes_GA; // For client tracking
if((typeof(_gaq) != 'undefined')){
    /* GA iframes */
    window.addEvent('domready', function() {
        iframes_GA = $$('iframe[rel=GA]');
        _gaq.push(['_setDomainName','none']);
        _gaq.push(['_setAllowLinker',true]);
        for(var i=0;i<iframes_GA.length;i++)
        {    
             _gaq.push(function() {
                var pageTracker = _gat._getTrackerByName();
                var iframe_src = iframes_GA[i].getAttribute('rel_ga');
                iframes_GA[i].src = pageTracker._getLinkerUrl(iframe_src);
            });
        }
    });
}



/* APV :: MENU */
window.addEvent('domready', function() {
    
    var reno_apv_block_menu_length = $$('.reno_apv_block_menu').length;
   $$('.reno_apv_block_menu').each(function($reno_apv_block_menu,i){
        //Set z-index for IE
        $reno_apv_block_menu.setStyle('z-index',reno_apv_block_menu_length - i);
        $reno_apv_block_menu.addEvent('mouseover',function(){
            this.addClass('reno_apv_block_menuOpened');
        });
        $reno_apv_block_menu.addEvent('mouseout',function(){
            this.removeClass('reno_apv_block_menuOpened');
        });
        $ES('.navAnchor',$reno_apv_block_menu).addEvent('click',function(e){
            new Event(e).preventDefault();
        });
   });
});


/* Set same height on fluid blocks */
// Extend array method
Array.prototype.max = function(){
	return Math.max.apply({},this);
}
window.addEvent('load', function() {
   var elm_cols = $$('.colsSetSameHeight');
    elm_cols.each(function(elm){
        setSameHeightOnCols(elm);
    });
});

function setSameHeightOnCols(elm_cols)
{
    var new_height = getMaxHeightOnCol(elm_cols);
    if(elm_cols.hasClass('colsSetSameHeight2') && !window.ie7) {
       new_height = new_height - 10;
    }
    elm_cols.style.height = new_height+'px';
}
function getMaxHeightOnCol(elm_cols)
{
    var sizes = new Array();
    var max_height = 0;
    $ES('.cb_col',elm_cols).each(function(elm_col) {
        var size = elm_col.getCoordinates();
        sizes.push(size.height);
    });
    max_height = sizes.max();
    return Math.round(max_height);
}


/* blocks :: webforms */
window.addEvent('domready', function() {
   var anchor_regex = new RegExp(/#/);
   var hasSubGroupError = false;    
   var isSubmit = false;
   //Dirty patch
   var isGettingForm = true;
   
       
    if($$('#mainInside .reno_blocks_forms')) {     
    
        var webforms_loader = new Loader({         
            fog : true,         
            container : 'mainInside'     
        });
        /*
        <style type="text/css">
        .loaderSimple {
            background-position: 50% 150px !important;
        }

        </style>
        */
    
       function getAnchor(attr_href)
       {
            var anchor = attr_href.split(anchor_regex);
            return anchor[1];
       }
       
       function getWebForm($form)
       {
            $$('.formWrapper').empty();
            var $formWrapper = $E('.formWrapper',$form);
            var url = $formWrapper.id;
            var webform = new Ajax(url, {method: 'get',update:$formWrapper,evalScripts:true,
                onComplete: function(request) {    
                setWebformEvents($formWrapper);
                isGettingForm = false;
                 //Evoid js error when clicking too speed because of css effect.
                setTimeout(function(){
                   webforms_loader.hide();
                },1500);
              },
                onRequest:function()
                {   
                    webforms_loader.show();
                    isGettingForm = true;
                }
            }).request();
            return webform;
       }
       
       function postForm($form) 
       {
            $form_form = $E('form',$form); //#webform
            var url = $form_form.getAttribute('action');
            var webform = new Ajax(url, {data:$form_form, method: 'post',update:$form,evalScripts:true,
                onComplete: function(request) {
                    webforms_loader.hide();
                    setWebformEvents($form);
                    checkState($form,request);
                    isSubmit = false;
                },
                onRequest:function()
                {   
                    $form.empty();
                    webforms_loader.show();
                    isSubmit = true;
                }
            }).request();
            return webform;
       }
       
       function checkState($form,request){
         if($('success') || $('error')){
            $('mainInside').setHTML(request);
         }
       }
       
       function setWebformEvents($form){
            //js code from webform callback (dealers)
            if(typeof(init) == 'function' && $("WEBFORM_DEALER_ID")){
               init();
            }
            if($E('button[type=submit]',$form)){
                $E('button[type=submit]',$form).addEvent('click',function(e){
                    new Event(e).stop();
                    if(!isSubmit) { 
                        postForm($form);
                    }
                });
            }
       }
   
       // Hide all forms
       $$('#mainInside .reno_blocks_forms .reno_block_form').each(function($form) {
            $form.style.display = 'none';
            if($form.getElements('fieldset .error').length) {
                $form.style.display = 'block';
                if(!$form.getParent().hasClass('reno_block_formGroup')) {
                    $form.toggleClass('reno_block_form_opened');
                }
                var form_id = $form.id;
                if($('link_'+form_id)) $('link_'+form_id).getParent().toggleClass('opened');
                if($form.getParent().hasClass('reno_block_formGroup')) {
                    form_id = form_id.slice(0,-5);
                    $(form_id).checked = true;   
                }   
            }   
       });
       $$('#mainInside .reno_blocks_forms .reno_block_formGroup').each(function($form) {
            $form.style.display = 'none';
            if($form.getElements('fieldset .error').length) {
                $form.style.display = 'block';
                $form.toggleClass('reno_block_form_opened');
                var form_id = $form.id;
                if($('link_'+form_id)) $('link_'+form_id).getParent().toggleClass('opened');      
                hasSubGroupError = true;
            }
       });
       
       if(!hasSubGroupError){
           // Show the first form from sub group
           $$('#mainInside .reno_block_formGroup').each(function($form) 
           {
                $E('.reno_block_form',$form).style.display = 'block';
           });
       }
       
       //Add links Events
       $$('#mainInside .blockForm_anchors a').each(function($lnk) {
            $lnk.addEvent('click',function(e) {
                new Event(e).stop();
                var that = this;
                $$('#mainInside .blockForm_anchors .opened a').each(function($lnk) {
                    var anchor = getAnchor($lnk.href);
                    if(that != $lnk) {
                        $($lnk).getParent().removeClass('opened');
                        $(anchor).removeClass('reno_block_form_opened');
                        $(anchor).style.display = 'none';
                    }
               });
                var anchor = getAnchor(this.href);
                this.getParent().toggleClass('opened');
                $(anchor).toggleClass('reno_block_form_opened');
                $(anchor).style.display = 'none';
                getWebForm($(anchor));
            });
       });
       
        function showTestDriveForm(){
            $form = $('form_fromConfigurator');
            $block_form = $form.getParent().getParent();
            $block_form.style.display = 'block';
            $block_form.addClass('reno_block_form_opened');
            block_form_id = $block_form.id;
            $('link_'+block_form_id).getParent().addClass('opened');
            setWebformEvents($form);
       }

        //Add buttons Events
        $$('#mainInside .reno_block_formGroup').each(function($form) {
             $ES('.blockForm_inputs input',$form).each(function($field) {
                 $field.addEvent('click',function(e) {
                    $field.checked = true;
                    var id = $field.id;
                    $ES('input',this.getParent().getParent()).each(function($field) {
                        var id = $field.id;
                        $(id+'_form').style.display = 'none';
                   });
                   $(id+'_form').style.display = 'block';
                    if(!isGettingForm){
                        getWebForm($(id+'_form'));
                    }
                });
            });
            $ES('.blockForm_inputs label',$form).each(function($label) {
                 $label.addEvent('click',function(e) {
                   $label.getPrevious().fireEvent('click');
                });
            });
            if(!hasSubGroupError) {
                $E('.blockForm_inputs input',$form).checked = true;
                $E('.blockForm_inputs input',$form).fireEvent('click');
             }
       }); 
       if($('price')){
            if($('price').value != '') {
               showTestDriveForm();
            }
       }
        if($$('label[for=price]')[0]){
            if($$('label[for=price]')[0].getNext().getText() != '') {
               showTestDriveForm();
            }
       }
       

   }
});

