// Détection de la présence 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;
  }
}


//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}$/));},
		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
		},
		numbers:function(field){if (field.value=="") return true; return !!field.value.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 erron\u00E9",
		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",
		requiredexclusif:"Vous devez remplir au moins un des champs"
	},
	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) {
		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"}))  {
				a[i].onclick = function() {
					tabs.change(this);
					return false;
				};
			};
			tabs.size(a[i], ul);
		};
	},
	size : function(a, ul) {
		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;
		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);
	}
};

/*********
* 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:"head"});
		var line = getParent(elm, {nodeName:"div", className:"line"});
		var aToggle = getNode(head, {nodeName:"a", className:"toggle"});
		
		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 (a)
			a.onclick = function() {
				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 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 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 (blocks.length>1) size(blocks.getLast(), line.offsetHeight-unit.offsetHeight);
		});
	});
};

/***************
* 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(){
	if($('player')){
		var ratio = $('player').getAttribute('ratio');
		var width = $('player').offsetWidth;
		var reg = new RegExp('(.*)/(.*)','gi');
		var resultat = reg.exec(ratio);
		var ratioV = RegExp.$1;
		var ratioH = RegExp.$2;
		return ((width/ratioV)*ratioH).toInt() + 20;//20 correspond a la hauteur de la barre doutils du player
	};
};
/* 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.loadFile({file: 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);
	};
};

/* Fonction appelant la listes des modeles en colonne de Droite */

/**  FONCTION TEST  ---- par Romain ------------------------------------------------------------------------------

var modelesList2 = new Class({

// INITIALISATION DE L'OBJET
	initialize: function() {

	// Selection du lien de controle
		this.oA = $$('p.modeles a')[0];
		if(!this.oA) return alert('Manque le bouton de controle');
	
	// Selection de la liste des modeles
		this.oList = $$('div.listeModeles')[0];
		if(!this.oList) return alert('Manque la liste de modeles');

	// Parametres
		this.initOpak = 0;
		this.finishOpak = 100;
		this.initHeight = 0;
		this.finishHeight = this.oList.getStyle('height');

	// Deplacement de la liste
		this.moveList();

	// Instance d'effet
		this.myFx = new Fx.Styles(this.oList, {
			duration: 500,
			transition: Fx.Transitions.linear
		});

	// Affectation des gestionnaires d'evenements
		this.initFx();
	},

// DEPLACEMENT DE LA LISTE
	moveList: function() {
		this.oList.injectInside('page');
		this.oList.setStyles({
			'width': '160px',
			'margin-top': '169px',
			'margin-left': '620px'
		});
	},

// AFFECTATION DES GESTIONNAIRES D'EVENEMENTS
	initFx: function() {

	// Initialisation et ouverture de la liste de modeles
		this.openList = this.openList.bind(this);
		this.oA.addEvent('click', this.openList);

	// Initialisation et fermeture de la liste de modeles
		this.closeList = this.closeList.bind(this);
		this.oList.addEvent('mouseleave', this.closeList);

	// Initialisation et fermeture de la liste de modeles
		this.standList = this.standList.bind(this);
		this.oList.addEvent('mouseover', this.standList);

	// Initialisation et fermeture de la liste de modeles
		this.standList = this.standList.bind(this);
		this.oList.addEvent('mouseout', this.standList);
	},

// OUVERTURE DE LA LISTE
	openList: function(e) {

	// Annulation de l'action normale du lien
		e = new Event(e);
		e.stop();

	// Ouverture
		this.myFx.start({
			'opacity': [this.initOpak, this.finishOpak],
			'height': [this.initHeight, this.finishHeight]
		});
	},
	
	standList: function(e) {
		e = new Event(e);
		e.stop();
		if(e.type == 'mouseover') this.stand = true;
		if(e.type == 'mouseout') this.stand = null;
	},

// FERMETURE DE LA LISTE
	closeList: function() {

	// Fermeture
		this.fnClose = function() {
			if(this.stand == true) return;
			this.myFx.start({
				'opacity': [this.finishOpak, this.initOpak],
				'height': [this.finishHeight, this.initHeight]
			});
		};
		this.fnClose = this.fnClose.bind(this);
		this.fnClose().delay(500);
	}
});

// CREATION D'UNE INSTANCE MODELESLIST2 AU CHARGEMENT DE LA PAGE
window.addEvent('domready', function() { return new modelesList2; });

* ----------------------------------------------------------------------------------  FIN DE LA FONCTION TEST  */

function modelesList(){
	var right = $('rightColumn');
	if (!right) return;
	var bouton = right.getElement('div.body p.modeles a');
	if (!bouton) return;
	var modelPicker = right.getElement('div.listeModeles');
	var heightToUse = 0;
	if (bouton && modelPicker){
		/* sizing right colum pour accueillir le model picker si trop petit */
		var clone = modelPicker.clone();
		clone.injectInside($('page'));
		clone.addClass('listeModeles')
		clone.setStyles(modelPicker.getCoordinates());
		clone.setStyles({
			'left': modelPicker.getLeft() - $('body').getLeft(),
			'width': modelPicker.offsetWidth +2
		});
		modelPicker.addClass('hidden');
		/* recup hauteur totale des blocs de la colonne de droite sans le modelPicker */
		var excludeListofDivs = getNodes(right, {nodeName:'div', className:'block'},{nodeName:'div', className:'listeModeles'});
		excludeListofDivs.each(function(excludeListofDiv){
			heightToUse += excludeListofDiv.offsetHeight;
		});
		function opac(){
		
			/*var toOpacity;
			if (sliding.to == 0){
				toOpacity = 0.3;
			}else if(sliding.to != 0){
				toOpacity = 1;
			} */
			
			/** ** On remplace le code ci-dessus mis en commentaire par le code
				suivant, le problème étant que sliding.to n'existe pas à l'origine,
				ce qui pause problème à Safari 2 (alias kikoolol) : *** */
			var toOpacity = !sliding.to ? 0.3 : 1;
			/** ** Fin modif *** */
			
			excludeListofDivs.each(function(div){
				$(div).effect('opacity').start(toOpacity);
			});
		}
		/* init de l'effet */
		var sliding = new Fx.Style(clone, 'margin-top', {
			onStart: opac,
			duration: 600,
			wait: false,
			transition: Fx.Transitions.Quad.easeOut
		}).set(- (clone.offsetHeight + heightToUse));
		
		bouton.addEvent('click',function(e){
			clone.setStyle('opacity', 1)
			new Event(e).stop();
			sliding.start(0);
		});
		clone.addEvent('mouseleave', function() {
			this.timer = (function(){
				sliding.start(-(clone.offsetHeight + heightToUse));
			}).delay(500);
		});
		clone.addEvent('mouseenter', function() {
			sliding.start(0);
			$clear(this.timer);
		});
	}
}
function pageRange() {
	var elms = $$('div.categorieVoitures');
	if (elms.length > 0){
		$('body').setStyle('visibility','hidden');
	}
	elms.each(function(elm, clone){
		formatLayout(elm);
		apparition(elm);
		//gestion layers
		var lis = elm.getElements('li.full');
		lis.each(function(li){
			li.setStyle('cursor','pointer');
			li.addEvent('mouseenter', function(e){
				var e = new Event(e);
				e.stop();
				//delai d'affichage d'un layer = 1000
				this.showTime = (function(){
					li.addClass('active');
					elm.layer = cloneLayer(this);
					elm.layer.li = this;
				}.delay(300, this));
				
				//suppression title de l'image et enregistrement
				
				li.img = new Array();
				
				li.getElements('img').each(function(img){
					li.img.push(img.alt);
					img.alt = '';
				});
				
			}.bind(li));
			li.addEvent('mouseleave', function(){
				//clear delai d'affichage d'un layer
				$clear(this.showTime);
				if (!elm.layer) return;
				elm.layer.timer = closeLayer.delay(150, li, [elm.layer]);
				elm.layer.addEvent('mouseenter', function (e) {
					//entering layer
					$clear(this.timer);
				});
				elm.layer.addEvent('mouseleave', function (e) {
					//exiting layer
					$clear(this.timer);
					this.timer = closeLayer.delay(150, li, [this]);
				});
				
				//recuperation du title
				li.getElements('img')[0].alt = li.img[0];
				li.getElements('img')[1].alt = li.img[1];
				
			});
		});
		
	});
	//fonction permettant de faire apparaitre les elments proprement
	function apparition(elm){
		$('body').setStyle('visibility','visible');
		
		if(window.ie6){
			elm.setStyle('visibility','visible');
		}else {
			elm.effect('opacity',{duration:2000}).start(0, 1);
		}
	}
	
	function formatLayout(elm){
		var size = elm.offsetWidth,
		cols = elm.getElements('.col');
		max = cols.length;
		maxHHeight = 0;
		if(max == 1){
			cols[0].getParent().addClass('inlineCategorieVoitures');
			var lis = cols[0].getElement('ul').getChildren();
			var lisParLigne = (cols[0].offsetWidth / lis[1].offsetWidth).toInt();
			/*suppression de la marge si on est sur le dernier li pour que tout s'adapte */
			var surp = 0;
			if (lis.length > lisParLigne){
				surp = lisParLigne - (lis.length % lisParLigne);
				if (surp == 5) surp = 0;
			}
			for (i = 0; i < surp; i++){
				cols[0].getElement('ul').adopt(new Element('li').addClass('empty'));
			}
			/*on vire la marge sur les derniers lis de chaque ligne*/
			lis = cols[0].getElement('ul').getChildren();
			lis.each(function(li, index){
				if((index + 1) % 5 == 0){
					li.setStyle('margin-right',0)
				}
			});
		}
		cols.each(function(col, i){
			/* recup des titres */
			var h = col.getElement('h3');
			/* gestion largeur des colonnes */
			if (i == max)return;
			cols[i].setStyle('width', (size / max).toInt());
			/* recup hauteur pour les h3 apres mise à jour de la largeur */
			var heightToUse = h.offsetHeight - h.getStyle('padding-top').toInt()*2;
			heightToUse > maxHHeight ? maxHHeight = heightToUse : maxHHeight = maxHHeight;
		});
		/* application hauteur h3 */
		cols.getElement('h3').setStyle('height', maxHHeight);
		if (max == 2){
			cols[0].getParent().addClass('categorieVoituresDual');
			var biggerLength = 0;
			var lisParLigne = 0;
			var width = 0;
			cols.each(function(col){
				var lis = col.getElement('ul').getChildren();
				width = col.offsetWidth;
				lisParLigne = (col.offsetWidth / lis[0].offsetWidth).toInt();
				var surp = lisParLigne - (lis.length % lisParLigne);
				/*on comble les blancs*/
				for (i = 0; i < surp; i++){
					col.getElement('ul').adopt(new Element('li').addClass('empty'));
				}
				lis = col.getElement('ul').getChildren();
				lis.setStyle('width', (width/2).toInt());
				biggerLength < lis.length ? biggerLength = lis.length : biggerLength = biggerLength;
			});
			/*on comble la ligne manquante*/
			cols.each(function(col){
				var lis = col.getElement('ul').getChildren();
				if (lis.length < biggerLength){
					var d = biggerLength - lis.length;
					for (i = 0; i < d; i++){
						col.getElement('ul').adopt(new Element('li').addClass('empty'));
						lis = col.getElement('ul').getChildren();
						lis.setStyle('width', (width/2).toInt());
					};
				}
			});
		}
	};
	function cloneLayer(elm){
		var layer = elm.getElement('div.layer');
		layer.getChildren().addClass('categorieVoituresInside');
		var clone = layer.clone();
		var bloc = getParent(elm, {nodeName:"div", className:"categorieVoitures"});
		$('page').adopt(clone);
		clone.addClass('categorieVoituresLayer');
		clone.style.top = elm.getTop() + 'px';
		//positionnement layer
		var elmPos = elm.getCoordinates();
		var bodyLeft = $('body').getLeft();
			//pos hauteur
		if (elmPos.top + clone.offsetHeight > document.documentElement.clientHeight){
			clone.setStyle('top', elmPos.top - clone.offsetHeight + elmPos.height);
		}
			//pos largeur
		if (elmPos.left + elmPos.width + clone.offsetWidth > document.documentElement.clientWidth){
			clone.setStyle('left', elmPos.left - clone.offsetWidth - bodyLeft);
		}else{
			clone.setStyle('left', elmPos.left + elmPos.width - bodyLeft);
		}
		var opac = new Fx.Style(clone, 'opacity', {duration: 200, transition: Fx.Transitions.linear});
		opac.start(0, 1);
		return clone;
		
	};
	function closeLayer(layer){
		this.removeClass('active');
		var opac = new Fx.Style(layer, 'opacity', {
			onComplete:(function(){
				if (layer && layer.parentNode) layer.remove();
			}) ,
			duration: 100,
			transition: Fx.Transitions.linear
		});
		opac.start(0);
	};
}

window.addEvent('load', function() {
	var bloc = document.getElements('div.slider');
	var blocCtn = document.getElements('div.sliderCtn');
	var lastChanged;
	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 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);
			
/** En prevision d'un futur cas... s'il y a lieu
			// Marge droite des vignettes
			var iMarginRLi = $E('li', oBox).getStyle('margin-right').toInt();

			// Nombre de vignettes total
			var iLi = oBox.getElements('li').length;

			// Taille des vignettes pour un bon affichage et marge droite a appliquer sur la derniere vignette
			var iStandWidth = ((iWidthBox - iNbreAffich * iMarginRLi) / iNbreAffich).toInt(), iRest = iWidthBox % iNbreAffich;

			// Facteur d'echelle a appliquer sur chaque vignette
			var iRatio = iStandWidth / iWidthLi;

			// Hauteur des vignettes
			var iStandHeight = ($E('img', oBox).getStyle('height').toInt() * iRatio).toInt();

			// Redimensionnement de la largeur des vignettes
			oBox.getFirst().getElements('li a').each(function(oA) {
				var oImg = oA.getElement('img');
				return oImg.setStyles({
					'width': iStandWidth,
					'height': iStandHeight
				});
			});

			// Redimensionnement des hauteurs des fleches de controle et des conteneurs
			var iContHeight = iStandHeight + $E('img', oBox).getStyle('margin-top').toInt() + $E('li', oBox).getStyle('margin-bottom').toInt();

			oBox.getPrevious().setStyle('height', iContHeight);
			oBox.getNext().setStyle('height', iContHeight);
			oBox.getParent().setStyle('height', iContHeight);
			oBox.setStyle('height', iContHeight);

			return this.addBehaviour(oBox);
*/
		}, this);
	}
});


function tipBox(elm, size){
	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($(bloc).getLeft() < clone.offsetWidth){
		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;
	//on teste les parametres
	for (i=0; i<arguments.length;i++){
		arg = arguments[i];
		if (arg.constructor == String){
			if (arg.match(/id\w*/)){
				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');
		}
	}
	
	//on enregistre l'id pour la fermeture du layer
	this.$tmp.popId = popId;
	
	
	var layerToPop = new Element('div', {'class': 'layerToPop'});
	var blockToPop = $(popId);
	if (shadow){
		if (shadow.nodeName.toLowerCase() == 'html'){
			layerToPop.setStyles({
				'width':document.documentElement.clientWidth,
				'height':document.documentElement.clientHeight,
				'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');
	blockToPop.setStyles({
		'top': (document.documentElement.clientHeight - blockToPop.offsetHeight)/2,
		'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);
	ifrlayer.make(blockToPop);
	ifrlayer.make(layerToPop);
};

function releaseLayer(){
	if (window.event) {window.event.cancelBubble = true;}
	
	if (this.$tmp && this.$tmp.popId) var popId = this.$tmp.popId;
	
	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){
		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() {
		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.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);
//fonction en test pour ajuster la hauteur du template --- a supprimer si bug recense
function sizingBody(){
	if($('flash')){
		if (!window.ie6){
			$('body').setStyle('min-height', $('flash').offsetHeight - $('body').getStyle('padding-top').toInt()*2);
		}else{
			$('body').setStyle('height', $('flash').offsetHeight - $('body').getStyle('padding-top').toInt()*2);			
		}
	}
}



//fonction lancee pendant le chargement de la page
window.addEvent('domready', function() {
	pageRange();
	toggleElem();
	maxLengthOntextarea();
	generateElements();
	if(window.khtml||window.ie) sizeBlocks();
	if ($('slidingNav')) new slidingNav($('navigation'));
})
//fonction lancee une fois toute la page chargee
window.addEvent('load', function () {
	sizeBlocks();	
	modelesList();
	rightNavEsc();
	galleryScroller();
	presOverview();
	accordeon();
	createColorSteps();
	setStepHeadingLength();
	sizingBody();
	new SelectLinks;
	new MediaScroll;
	
	
	
	
})

/* 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, {});
      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.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 thepopupAjax = null;

function sendToAFriend(){
	thepopupAjax = new LayerAjax();
	//on passe location en parametre
	var currentLocation = document.location.pathname;
	thepopupAjax.open('../includes/sendToAFriendLayerContent.html' + '?pageUrl=' + currentLocation);
}
function validLayerSendToAFriend(elm){
	var url = elm.action;
	url += '?'+ $(elm).toQueryString();
	
	//on passe location en parametre
	thepopupAjax.remoteUrl(url);
	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);
    }
}

/** 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;
		});
	});
};

var connect = function(oElem, sEvType, fn, bCapture) {
	return document.addEventListener ?
		oElem.addEventListener(sEvType, fn, bCapture || false):
		oElem.attachEvent ?
			oElem.attachEvent('on' + sEvType, fn):
			false;
};

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



/** 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() {		
	}
});

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