/**
*
*	Fonctions pour MS
*
*/
var ie = document.all?true:false;
var ie6 = (/MSIE\s6/.test(navigator.appVersion))?true:false;
var ie7 = (/MSIE\s7/.test(navigator.appVersion))?true:false;
var ie8 = (/MSIE\s8/.test(navigator.appVersion))?true:false;
var opera = (navigator.appName == "Opera")?true:false;

var global = this;

var popupOpen = false;
var popupBeingClose = false;
var timeRedimensionne;
var maxopamessage;
var maxopacadre;

var aLayersHeights = {};

var aCorb = new Array();
var sCorb = "";

if (typeof Class != 'undefined') {
	var appelAjaxObjet = Class.create();

	appelAjaxObjet.prototype = {

		// Constructeur
		initialize: function(url,layercible,parametres,typeretour,retourMultiple,cibleRetourDemande) {

			this.divRetour = layercible;
			this.typeRetour = typeretour;
			if(cibleRetourDemande) this.cibleRetour = cibleRetourDemande;
			var oAfficheAjax = new Ajax(url,this);  
			if(parametres) {
				var reg= new RegExp("&", "g");
				var tableau = parametres.split(reg);
				if(tableau.length > 0) {
				  for (var i=0; i<tableau.length; i++) {
					  var regIn=new RegExp("[=]+", "g");
					  var tableauIn = tableau[i].split(regIn);
					  if(tableauIn[0].substr(0,4) == "amp;") tableauIn[0] = tableauIn[0].substr(4);
					  oAfficheAjax.ajoute(tableauIn[0], tableauIn[1]);
				  }
				} else {
				   var regIn=new RegExp("[=]+", "g");
				   var tableauIn=tableau[i].split(regIn);
				   oAfficheAjax.ajoute(tableauIn[0], tableauIn[1]); 
				}
			}

			// On ajoute l'idpage en cours si la variable existe
			/*if(me_id_page_en_cours) {
				oAfficheAjax.ajoute("me_id_page_en_cours", me_id_page_en_cours); 
			}*/
			if(retourMultiple != null && retourMultiple != false) oAfficheAjax.envoie(retourAjaxMultiple);  
			else oAfficheAjax.envoie(retourAppelAjax); 
		}

	};	
	var MsJs = Class.create();
	MsJs.prototype = {

		initialize: function(arg) {
		 
		},

		include: function(element, pattern) {
			return element.indexOf(pattern) > -1;
		},

		camelize: function(element) {
			return element.replace(/-+(.)?/g, function(match, chr) {
			  return chr ? chr.toUpperCase() : '';
			});
		},

		getStyle: function(element, style) {
			element = this.isElement(element)?element:$(element);
			style = style == 'float' ? 'cssFloat' : this.camelize(style);
			var value = element.style[style];
			if (!value || value == 'auto') {
			  if (element.currentStyle) {
				 value = element.currentStyle[style] ? element.currentStyle[style] : null;
			  } else if (window.getComputedStyle) {
				 var css = document.defaultView.getComputedStyle(element, null);
				 value = css ? css[style] : null;
			  }
			}
			if (style == 'opacity') return value ? parseFloat(value) : 1.0;
			return value == 'auto' ? null : value;
		},

		getOpacity: function(element) {
			return this.getStyle(element,'opacity');
		},

		setStyle: function(element, styles) {
			element = this.isElement(element)?element:$(element);
			var elementStyle = element.style, match;
			if (this.isString(styles)) {
			  element.style.cssText += ';' + styles;
			  return this.include(styles,'opacity') ?
				this.setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
			}
			for (var property in styles)
			  if (property == 'opacity') this.setOpacity(element, styles[property]);
			  else
				elementStyle[(property == 'float' || property == 'cssFloat') ?
				  (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
					property] = styles[property];

			return element;
		},

		setOpacity: function(element, value) {
			element = this.isElement(element)?element:$(element);
			element.style.opacity = (value == 1 || value === '') ? '' :
			  (value < 0.00001) ? 0 : value;
			return element;
		},

		isElement: function(object) {
			return !!(object && object.nodeType == 1);
		},

		isArray: function(object) {
			return Object.prototype.toString.call(object) === '[object Array]';
		},

		isHash: function(object) {
			return object instanceof Hash;
		},

		isFunction: function(object) {
			return typeof object === "function";
		},

		isString: function(object) {
			return Object.prototype.toString.call(object) === '[object String]';
		},

		isNumber: function(object) {
			return Object.prototype.toString.call(object) === '[object Number]';
		},

		isUndefined: function(object) {
			return typeof object === "undefined";
		}

	};
	var oMsJs = new MsJs();
}

// Fonction d'appel à la création d'une requête ajax
var dernierAppelAjax = new Array();
function appelAjax(url,layercible,parametres,typeretour,retourMultiple,cibleRetourDemande,verifieDerniereRequete) {
	var autoriseEnvoi = false;
	// On test si que la dernière requête envoyée n'est pas la même que celle-ci.
	if(verifieDerniereRequete) {
		if(dernierAppelAjax.length >= 1) {
			if(dernierAppelAjax[(dernierAppelAjax.length - 1)] != '|url::'+url+'|parametres::'+parametres+'|typeretour::'+typeretour+'|retourMultiple::'+retourMultiple+'|cibleRetourDemande::'+cibleRetourDemande+'') {
				autoriseEnvoi = true;
				dernierAppelAjax = new Array();
			}
		} else {
			autoriseEnvoi = true;
		}
		dernierAppelAjax.push('|url::'+url+'|parametres::'+parametres+'|typeretour::'+typeretour+'|retourMultiple::'+retourMultiple+'|cibleRetourDemande::'+cibleRetourDemande);
	} else {
		autoriseEnvoi = true;
	}
	if(autoriseEnvoi) {
		new appelAjaxObjet(url,layercible,parametres,typeretour,retourMultiple,cibleRetourDemande);
	}
};

// On met à jour le contenu suite à une requête ajax
var retourAppelAjax = function(e) {	

	  var navigateurIE = null;
	  var layerRetour = $(this.divRetour);
	  var Even = window;
	  if(this.cibleRetour == "parent") {
		  layerRetour = window.parent.$(this.divRetour);
		  var Even = window.parent;
	  }
	  if(this.typeRetour == "inner") {
		if(e != "") {
			var sauveRetour = e;
			layerRetour.innerHTML = "<div style=\"position:absolute;top:-100px;left:-100px;\" >&#160;</div>"+e; // Sur IE il ne fait pas de inner HTML si on a que des balises scripts en retour
			var javascript = layerRetour.getElementsByTagName("script");
			for (var i = 0; i < javascript.length; i++){
				global.eval(javascript[i].text);
			}
			layerRetour.innerHTML = e;
			ms_appelFonctionsApresChargementAjax();
			if(maxopamessage && maxopacadre && layerRetour.offsetHeight && layerRetour.offsetWidth) {
				ouvrePopup(layerRetour.offsetWidth,layerRetour.offsetHeight,maxopamessage,maxopacadre,navigateurIE);
				timeRedimensionne = setTimeout("redimensionnePopupMessage();",600);
				timeRedimensionne = setTimeout("redimensionnePopupMessage();",1000);
				timeRedimensionne = setTimeout("redimensionnePopupMessage();",2000);
				timeRedimensionne = setTimeout("redimensionnePopupMessage();",5000);
				maxopamessage = null;
				maxopacadre = null;
				navigateurIE = null;
			}
		}
	  }
	  else {
		if(e != "") {
			if(layerRetour) {
				var sauveHtml = layerRetour.innerHTML;
				layerRetour.innerHTML = e;
				var javascript = layerRetour.getElementsByTagName("script");
				for (var i = 0; i < javascript.length; i++){
					global.eval(javascript[i].text);
				} 	
				layerRetour.innerHTML = sauveHtml;
				ms_appelFonctionsApresChargementAjax();
				if(maxopamessage && maxopacadre && layerRetour.offsetHeight && layerRetour.offsetWidth) {
					ouvrePopup(layerRetour.offsetWidth,layerRetour.offsetHeight,maxopamessage,maxopacadre,navigateurIE);
					maxopamessage = null;
					maxopacadre = null;
					navigateurIE = null;
				}
			} else {
				global.eval(e);
			}
		}
	  }


	  this.typeRetour = "";
	  this.divRetour = "";
	  this.cibleRetour = "";

};

// On met à jour plusieurs layer suite au retour de la requête ajax
var retourAjaxMultiple = function(e) {

	var reg=new RegExp("~#~", "g");
    var tableau=e.split(reg);
    if(tableau.length > 0) {
		for (var a = 0; a < tableau.length; a++) {		
			if(a%2 == 0) {
			  var re = tableau[a];
			  var contenu = "";
			} else {
			  var contenu = tableau[a];
			}

			if(contenu && re && $(re)) {
				
				var sauveRetour = contenu;
				$(re).innerHTML = "<div style=\"position:absolute;top:-100px;left:-100px;\" >&#160;</div>"+contenu; // Sur IE il ne fait pas de inner HTML si on a que des balises scripts en retour
				var javascript = $(re).getElementsByTagName("script");
				for (var i = 0; i < javascript.length; i++){
					global.eval(javascript[i].text);
				}
				$(re).innerHTML = contenu;
				/*$(re).innerHTML = contenu;
				var javascript = $(re).getElementsByTagName("script");
				var global = this; //dans un contexte global
				for (var i = 0; i < javascript.length; i++){
					global.eval(javascript[i].text);
				}*/
			}
		}
	}
};

var valeursChamp = '';
function champsSelect(separateur) {
  valeursChamp = '';
  for (var i=0; i< $('champs').options.length; i++)
  {
    if ($('champs').options[i].selected && $('champs').options[i].value != 0)
    valeursChamp += $('champs').options[i].value+separateur;
  }
};

var valeursDossier = '';
function dossierSelect(separateur) {
  valeursDossier = '';
  for (var i=0; i< $('dossiers').options.length; i++)
  {
    if ($('dossiers').options[i].selected && $('dossiers').options[i].value != 0)
    valeursDossier += $('dossiers').options[i].value+separateur;
  }
};

// Ajouter un produit au panier
function ajouteAuPanier(listeId,nomBase,lienRetour,valide,nomFichier,idGabarit,idUnivers,cle) {
	
	if(!nomFichier) nomFichier = "btq_affiche_donnee_panier.php";

	var listeTags = document.getElementsByTagName('input');
	var listeId = listeId.split('-');
	var produitAAjouter = false;
	var listeTags = document.getElementsByTagName('input');
	var listeTags2 = document.getElementsByTagName('select');
	var retour = true;
	var bonRetour = false;
	for(var a = 0; a < listeId.length ; a++ ) {
		var idProduit = listeId[a];
		var tableauRetour1 = envoiAuPanier(idProduit,nomBase,listeTags,valide,cle);
		var tableauRetour2 = envoiAuPanier(idProduit,nomBase,listeTags2,valide,cle);
		var retour1 = true;
		for(nomChamp in tableauRetour1) { if(tableauRetour1[nomChamp] == false && nomChamp != "") { retour1 = false; } else { bonRetour = true; } }
		var retour2 = true;
		for(nomChamp in tableauRetour2) { if(tableauRetour2[nomChamp] == false && nomChamp != "") { retour2 = false; } else { bonRetour = true; } }
		if(retour1 == false || retour2 == false) var retour = false;
		if(retour == true) {
			//appelAjax('../medias/includes/btq_affiche_donnee_panier.php','no-reply','ajax=1&ajoutPanier=Oui&idProduitAjout='+idProduit+'&info=valide&typeAjout='+nomBase+'&valeur='+((valide)?valide:""),'inner'); 
			aCorb.push('idProduitAjout='+idProduit+'&info=valide&typeAjout='+nomBase+'&valeur='+((valide)?valide:"")+((cle)?'&cleInc='+cle:'') );
		}
	}

	sCorb = base64_encode(serialize(aCorb));
	if(listeId.length) {
		appelAjax('../medias/includes/'+nomFichier,'popup_message','ajax=1&ajoutPanierv2=Oui&listeAjout='+sCorb+((idGabarit > 0)?'&idGabarit='+idGabarit:'')+((idUnivers > 0)?'&idUnivers='+idUnivers:''),'inner'); 			
	}
	
	aCorb = new Array();

	return ((listeId.length > 1)?bonRetour:retour);
};

function supprimeDuPanier(listeId,nomBase,lienRetour,nomFichier,idGabarit,idUnivers,cle) {

	if(!nomFichier) nomFichier = "btq_affiche_donnee_panier.php";
	var listeId = listeId.split('-');
	var produitAAjouter = false;
	for(var a = 0; a < listeId.length ; a++ ) {
		var idProduit = listeId[a];
		appelAjax('../medias/includes/'+nomFichier,'popup_message','ajax=1&supprimePanier=Oui&idProduitSuppr='+idProduit+'&typeAjout='+nomBase+((idGabarit > 0)?'&idGabarit='+idGabarit:'')+((idUnivers > 0)?'&idUnivers='+idUnivers:'')+((cle)?'&cleInc='+cle:''),'inner');
	}
};

function envoiAuPanier(idProduit,nomBase,response,valide) {

	var retour = new Array();
	for(var i=0 ; i < response.length ; i++) { 
		var idChamp = response[i].id.toString();
		var nomChamp = response[i].name.toString();
		if(idChamp.match("ms-info-panier")) {
			if(!retour[nomChamp]) retour[nomChamp] = false;
			var reg = new RegExp("[\-]+", "g");
			var tableau = idChamp.split(reg);
			var tableau2 = nomChamp.split(reg);
			var info = tableau2[4];
			var produit = tableau2[5]; 
			var declinaison = tableau[6];
			var univers = tableau[7];
			var cle = tableau[8];
			var incremente = tableau[9];
			var element = document.getElementById(idChamp);		
			if(element) {
				var valeur = "";
				var typeChamp = document.getElementById(idChamp).type;
				var autoriseEnvoi = false;
				if(typeChamp == "text" || typeChamp=="textarea" || typeChamp == "hidden" ) { 
					// Test si valeur de min et de max
					valeur = document.getElementById(idChamp).value; if(valeur != "") { autoriseEnvoi = true; } 
				}
				else if (typeChamp == "select-one" ) { 
					var nombreOptions = document.getElementById(idChamp).options.length;
					for(var e = 0; e < nombreOptions ; e++) {
						if(document.getElementById(idChamp).options[e].selected) { 
							valeur = document.getElementById(idChamp).options[e].value;
							autoriseEnvoi = true;
						}
					}
				}
				else if (typeChamp == "radio" ) { if(document.getElementById(idChamp).checked) { valeur = document.getElementById(idChamp).value; autoriseEnvoi = true; } }
				else if (typeChamp == "checkbox" ) { if(document.getElementById(idChamp).checked) {  valeur = document.getElementById(idChamp).value; autoriseEnvoi = true; } }
				if(autoriseEnvoi) retour[nomChamp] = true;
				if(produit == idProduit && (info != "" || info != "undefined" ) ) { 
					var idMaitre = false;
					if(declinaison != null && declinaison != "null" && declinaison != "undefined" ) { var idMaitre = produit; produit = declinaison; }
					if(!idMaitre && autoriseEnvoi) {
						//appelAjax('../medias/includes/btq_affiche_donnee_panier.php','no-reply','ajax=1&ajoutPanier=Oui&idProduitAjout='+idProduit+'&info='+info+'&typeAjout='+nomBase+'&valeur='+valeur,'inner');
						aCorb.push('idProduitAjout='+idProduit+'&info='+info+'&typeAjout='+nomBase+'&valeur='+valeur+((univers)?'&univers='+univers:'')+((cle)?'&cleInc='+cle:'') );
					} 
					if(idMaitre && autoriseEnvoi) {
						//appelAjax('../medias/includes/btq_affiche_donnee_panier.php','no-reply','ajax=1&ajoutPanier=Oui&idProduitAjout='+idProduit+'&info=idDeclinaison&typeAjout='+nomBase+'&valeur='+valeur,'inner');
						aCorb.push('idProduitAjout='+idProduit+'&info=idDeclinaison&typeAjout='+nomBase+'&valeur='+valeur+((univers)?'&univers='+univers:'')+((cle)?'&cleInc='+cle:''));
					}
				}
			}
		}
	}	
	return retour;

};

function rechargeLayers(listeLayerAMaj,parametres,idPage,latence,affichePopupPanier,retour) {
	var listeTexte = serialize(listeLayerAMaj);
	if(latence != null) {
		setTimeout("appelAjax('../medias/fonctions/rechargeContenuLayer.php','','ajax=1&listeLayers="+listeTexte+"&parametres="+parametres+"&idPage="+idPage+"','inner','1');",latence);
	} else {
		appelAjax('../medias/fonctions/rechargeContenuLayer.php','','ajax=1&listeLayers='+listeTexte+'&parametres='+parametres+'&idPage='+idPage,'inner','1');
	}
	if(affichePopupPanier) {
		if($('ms_popup_resume_panier')) { 
			if($('ms_popup_resume_panier').style.display == 'none' || $('ms_popup_resume_panier').style.display == '') {
				if(latence != null) {
					setTimeout("positionnePopupPanier('ms_popup_resume_panier');",latence);
				} else {
					positionnePopupPanier('ms_popup_resume_panier');	
				}
			}
		}
	}
};

// Positionne la fenêtre au centre (future ancienne fonction)
function positionnePopupPanier(layer) {
	$(layer).style.display = 'block';
	$(layer).style.zIndex = 10;
	// On repositionne le layer
	var largeurFenetre = document.documentElement.clientWidth;
	var hauteurFenetre = document.documentElement.clientHeight;
	var scrollTop = document.documentElement.scrollTop;
	var scrollLeft = document.documentElement.scrollLeft;
	var largeurPanier = $('ms_popup_resume_panier').style.width;
	var hauteurPanier = $('ms_popup_resume_panier').style.height;
	var posCadrePanierX = Math.round( ((largeurFenetre/2) - (largeurPanier/2) + scrollLeft) );
	var posCadrePanierY = Math.round( ((hauteurFenetre/2) - (hauteurPanier/2) + scrollTop) );
	$(layer).style.left = posCadrePanierX+"px";
	$(layer).style.top = posCadrePanierY+"px";
};

var getDocumentSize = function () {

	// Mozilla
	var height = document.documentElement.scrollHeight;
	var width = document.documentElement.scrollWidth;

	// IE et opéra
	if(document.documentElement.clientHeight > height) {
		height = document.documentElement.clientHeight;
	}
	if(document.documentElement.clientWidth > width) {
		width = document.documentElement.clientWidth;
	}

	// Safari
	if(document.body.scrollHeight > height) {
		height = document.body.scrollHeight;
	}
	if(document.body.scrollWidth > width) {
		width = document.body.scrollWidth;
	}

	return new Array(width,height);

};

var getDisplaySize = function () {

	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return new Array(myWidth,myHeight);

};

// ============================================================================
// récupère le top de la zone visible du document
function ms_getDocumentTop(){
    if (typeof(window.pageYOffset) != 'undefined'){
     return window.pageYOffset;
    }else if (typeof(document.documentElement.scrollTop) != 'undefined' && document.documentElement.scrollTop > 0){
     return document.documentElement.scrollTop;
    }else if (typeof(document.body.scrollTop) != 'undefined'){
     return document.body.scrollTop;
    }
};

// ============================================================================
// récupère le left de la zone visible du document
function ms_getDocumentLeft(){
    if (typeof(window.pageYOffset) != 'undefined'){
     return window.pageXOffset;
    }else if (typeof(document.documentElement.scrollLeft) != 'undefined' && document.documentElement.scrollLeft > 0){
     return document.documentElement.scrollLeft;
    }else if (typeof(document.body.scrollLeft) != 'undefined'){
     return document.body.scrollLeft;
    }
};

var redimensionnePopupMessage = function () {

	if(!popupBeingClose) {

		// On récupère les dimensions du document
		var tailleDocument = getDocumentSize();
		var largeurEcran = tailleDocument[0];
		var hauteurEcran = tailleDocument[1];
		// On calcul les dimension des scrolls
		var decalageX = (document.documentElement.scrollLeft)?document.documentElement.scrollLeft:document.body.scrollLeft;
		var decalageY = (document.documentElement.scrollTop)?document.documentElement.scrollTop:document.body.scrollTop;

		// *************************************//
		// Popup
		var layer = $('popup_message');
		oMsJs.setStyle(layer,'display:block;');

		// On initialise les dimensions pour éviter les petits bug liés aux navigateurs
		layer.style.height = '';
		layer.style.width = '';
		
		// On récupère les informations de taille de la zone d'affichage
		var tailleAffichage = getDisplaySize();

		// On positionne le layer à 50% en top et left
		layer.style.left = ( tailleAffichage[0] / 2)+decalageX+"px";
		layer.style.top = ( tailleAffichage[1] / 2)+decalageY+"px";

		// On récupère la taille du layer (suite au innerHTML)
		hauteur = layer.offsetHeight;
		largeur = layer.offsetWidth;

		// Si la largeur est plus grande que la largeur de la fenêtre on réduit la taille
		if(largeur > (largeurEcran - decalageX) ) { largeur = (largeurEcran - decalageX) - 150; }
		// Si la hauteur est plus grande que la hauteur de la fenêtre on réduit la taille
		if(hauteur > (hauteurEcran - decalageY)) { hauteur = (hauteurEcran - decalageY) - ((decalageY)?20:0) - 150; }

		// On calcul les marges pour positionner le layer au centre
		var margeTop = (((hauteur)/2)-((decalageY)?20:0));
		var margeLeft = (((largeur)/2)-((decalageX)?20:0));

		// Si la marge est supérieur au positionnement du layer, le layer va sortir de l'écran, il faut donc le repositionner
		if(margeTop > layer.style.top) margeTop = margeTop - (layer.style.top - margeTop) - 20;
		if(margeLeft > layer.style.left) margeLeft = margeLeft - (layer.style.left - margeLeft) - 20;

		// On applique les marges
		layer.style.marginTop = "-"+margeTop+"px";
		layer.style.marginLeft = "-"+margeLeft+"px";
		
		// On applique la dimensions au layer
		layer.style.height = (hauteur)+'px';
		layer.style.width = (largeur)+'px';

	}

};

var ouvrePopup = function(largeur,hauteur,maxopamessage,maxopacadre,ie) {

	// On récupère les dimensions du document
	var tailleDocument = getDocumentSize();
	var largeurEcran = tailleDocument[0];
	var hauteurEcran = tailleDocument[1];
	// On calcul les dimension des scrolls
	var decalageX = (document.documentElement.scrollLeft)?document.documentElement.scrollLeft:document.body.scrollLeft;
	var decalageY = (document.documentElement.scrollTop)?document.documentElement.scrollTop:document.body.scrollTop;

	// *************************************//
	// Popup
	var layer = $('popup_message');

	// On initialise les dimensions pour éviter les petits bug liés aux navigateurs
	layer.style.height = '';
	layer.style.width = '';
	
	// On récupère les informations de taille de la zone d'affichage
	var tailleAffichage = getDisplaySize();

	// On positionne le layer à 50% en top et left
	layer.style.left = ( tailleAffichage[0] / 2)+decalageX+"px";
	layer.style.top = ( tailleAffichage[1] / 2)+decalageY+"px";

	// On récupère la taille du layer (suite au innerHTML)
	hauteur = layer.offsetHeight;
	largeur = layer.offsetWidth;

	// Si la largeur est plus grande que la largeur de la fenêtre on réduit la taille
	if(largeur > (largeurEcran - decalageX) ) { largeur = (largeurEcran - decalageX) - 150; }
	// Si la hauteur est plus grande que la hauteur de la fenêtre on réduit la taille
	if(hauteur > (hauteurEcran - decalageY)) { hauteur = (hauteurEcran - decalageY) - ((decalageY)?20:0) - 150; }

	// On calcul les marges pour positionner le layer au centre
	var margeTop = (((hauteur)/2)-((decalageY)?20:0));
	var margeLeft = (((largeur)/2)-((decalageX)?20:0));

	// Si la marge est supérieur au positionnement du layer, le layer va sortir de l'écran, il faut donc le repositionner
	if(margeTop > layer.style.top) margeTop = margeTop - (layer.style.top - margeTop) - 20;
	if(margeLeft > layer.style.left) margeLeft = margeLeft - (layer.style.left - margeLeft) - 20;

	// On applique les marges
	layer.style.marginTop = "-"+margeTop+"px";
	layer.style.marginLeft = "-"+margeLeft+"px";
	
	// On applique la dimensions au layer
	layer.style.height = (hauteur)+'px';
	layer.style.width = (largeur)+'px';

	// On place le layer devant le voile
	layer.style.zIndex = 1001;
	// Si pas IE6 et < ou si la fenetre n'est pas ouverte, on l'ouvre en fondu
	if(!popupOpen) {
		var opacityTween = new OpacityTween($('popup_message'),Tween.strongEaseIn, 0, 100, 0.3);
		opacityTween.start();
	}


	// *************************************//
	// Voile

	var layer = $('popup_voile');
	// On le place en haut à gauche
	layer.style.top = "0px";
	layer.style.left = "0px";
	// On l'étire sur tout la longueur de la page
	layer.style.width =  largeurEcran+decalageX+"px";;
	layer.style.height = hauteurEcran+decalageY+"px";
	// On lui applique une couleur de fond si elle n'existe pas
	//if(layer.style.backgroundColor == "") layer.style.backgroundColor = "black";
	// On le place sous la popup
	layer.style.zIndex = 1000;
	// Si la fenetre n'est pas ouverte, on l'ouvre en fondu

	if(!popupOpen) {	
		var opacityTween = new OpacityTween($('popup_voile'),Tween.strongEaseIn, 0, 70, 0.3);
		opacityTween.start();
		popupOpen = true;
	}

	popupBeingClose = false;

};


/* Obselette depuis ms v2 */
var opacifie = function(sId, nPourcentage) {
	var calque = $(sId).style;
	calque.opacity = (nPourcentage / 100);
	calque.MozOpacity = (nPourcentage / 100);
	calque.KhtmlOpacity = (nPourcentage / 100);
	calque.filter = "alpha(opacity=" + nPourcentage + ")";
};

/* Obselette depuis ms v2 */
var retournOpacity = function(sId) {
	var calque = $(sId).style;
	if(calque.opacity) return calque.opacity*100;
    else if(calque.MozOpacity) return calque.MozOpacity*100;
	else if(calque.KhtmlOpacity) return calque.KhtmlOpacity*100;
	else if(calque.filters.item("DXImageTransform.Microsoft.Alpha").Opacity) return calque.filters.item("DXImageTransform.Microsoft.Alpha").Opacity;
};

/* Obselette depuis ms v2 */
var apparitionPopup = function(layer,opacity,opacityFin,vitesse,cadence,palier) {
	if(!palier) palier = 10;
	opacity = Math.round( ( (Math.log(palier)-1) / (Math.log(opacityFin)-1) ) * 100);
	if(opacityFin >= opacity) {
		opacifie(layer, opacity);
		eval("tPopup = setTimeout(\"apparitionPopup('"+layer+"', "+opacity+", "+opacityFin+", "+vitesse+", "+cadence+", "+(palier+(10/cadence))+")\", "+vitesse+")");
	} else {
		$(layer).style.display = "block";
		opacifie(layer, opacityFin);
		popupOpen = true;
	}
};

/* Obselette depuis ms v2 */
var disparitionPopup = function(layer,opacity,opacityFin,vitesse,cadence,palier) {
	if(!palier) palier = opacity/10;
	opacity = Math.round(Math.exp( (palier * (4.6/10)) ));
	if(opacity > 1) {
		opacifie(layer, opacity);
		eval("tPopup = setTimeout(\"disparitionPopup('"+layer+"', "+opacity+", "+opacityFin+", "+vitesse+", "+cadence+", "+(palier-(10/cadence))+")\", "+vitesse+")");
	} else {
		opacifie(layer, 0);
		$(layer).style.left = "-4000px";
		popupOpen = false;
	}
};

var fermePopupFondu = function() {

	popupBeingClose = true;
	clearTimeout(timeRedimensionne);
	
	// Disparition du popup message
	var opacityTween = new OpacityTween($('popup_message'),Tween.strongEaseIn, 100, 0, 0.3);
	opacityTween.onMotionFinished = function() { oMsJs.setStyle($('popup_message'),'top:-4000px;'); popupOpen = false; };
	opacityTween.start();

	// Disparition du popup voile
	var opacityTween = new OpacityTween($('popup_voile'),Tween.strongEaseIn, 70, 0, 0.3);
	opacityTween.onMotionFinished = function(){ oMsJs.setStyle($('popup_voile'),'top:-4000px;'); popupOpen = false; };
	opacityTween.start();

};

var fermePopup = function() {

	popupBeingClose = true;
	clearTimeout(timeRedimensionne);
	oMsJs.setStyle($('popup_message'),'top:-4000px;');
	oMsJs.setStyle($('popup_voile'),'top:-4000px;');

};

// Serialisation des données 
function serialize( mixed_value ) {

    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

// Encodage en base64 // ancienne fonction (reste en place pour retrocompatibilité)
function base64_encode( data ) {

	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
	if (!data) {
		return data;
	}
	do { 
		// pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);
		bits = o1<<16 | o2<<8 | o3;
		h1 = bits>>18 & 0x3f;
		h2 = bits>>12 & 0x3f;
		h3 = bits>>6 & 0x3f;
		h4 = bits & 0x3f;
 		// use hexets to index into b64, and append result to encoded string
		tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	enc = tmp_arr.join('');
	switch( data.length % 3 ){
		case 1: enc = enc.slice(0, -2) + '=='; break;
		case 2: enc = enc.slice(0, -1) + '='; break;
	}
	return enc;

}

var writeCookie = function (nom, valeur) {

	var argv=writeCookie.arguments;
	var argc=writeCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");

};


var listeAdresse = new Object([1]);

function Gmap_vers(i) {
	document.getElementById("toAddress").value = listeAdresse[i].adresse;
	document.getElementById("toAddress").style.backgroundColor = "#FFFFFF";
	document.getElementById("fromAddress").value = "";
	document.getElementById("fromAddress").style.backgroundColor = "#AFAFAF";
	document.getElementById("fromAddress").focus();
}

function Gmap_depuis(i) {
	document.getElementById("fromAddress").value = listeAdresse[i].adresse;
	document.getElementById("fromAddress").style.backgroundColor = "#FFFFFF";
	document.getElementById("toAddress").value = "";
	document.getElementById("toAddress").style.backgroundColor = "#AFAFAF";
	document.getElementById("toAddress").focus();
}

function Gmap_initialize(listeAdresse,zoom,notInitCadre,noAlert) {

	if (GBrowserIsCompatible()) {
		map = new GMap2($("map_canvas"));
		map.setCenter(new GLatLng(46.935261, 1.88), zoom?zoom:10 );
		map.setUIToDefault();			

		gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "load", Gmap_onGDirectionsLoad);
		GEvent.addListener(gdir, "error", Gmap_handleErrors);
		
		geocoder = new GClientGeocoder();

		icone = new GIcon(G_DEFAULT_ICON);
		icone.iconSize = new GSize(17, 24);
		icone.shadowSize = new GSize(25, 20);
		markerOptions = { icon:icone };
		
		nbAdresse = listeAdresse.length;
		for (nb = 0; nb < nbAdresse; nb++) {
			if (listeAdresse[nb].longitude!="" && listeAdresse[nb].latitude!="") {
				var latlng = new GLatLng(listeAdresse[nb].longitude, listeAdresse[nb].latitude);
				map.setCenter(latlng, zoom?zoom:6 );
				Gmap_showAddress(latlng, listeAdresse[nb],notInitCadre);
			} else {
				Gmap_rechercheAddress(listeAdresse[nb],zoom,notInitCadre,noAlert);					
			}
		}
	}
}

function Gmap_rechercheAddress(address,zoom,notInitCadre) {
	if (geocoder) {
		geocoder.getLatLng(address.adresse, function(point) {
				if (!point) {
					if(!noAlert) alert("L'adresse \""+address.adresse+"\" est introuvable !");
					//document.write(address.adresse)+"<br />\n";
				} else {
					map.setCenter(point, zoom?zoom:6 );
					Gmap_showAddress(point, address, notInitCadre);
				}
			}
		);
	}
}

function Gmap_showAddress(point, address, notInitCadre) {
	var marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);
	GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(address.contenu+"<br style='clear:both' />");
	});
	if(!notInitCadre) marker.openInfoWindowHtml(address.contenu+"<br style='clear:both' />");
}

function Gmap_majBase(idProduit, coordonnees) {

	
	var infoArticle = new Ajax("../medias/includes/me_google_maps.php");
	infoArticle.ajoute('action', "modifCoordonnees");
	infoArticle.ajoute('idProduit', idProduit);
	infoArticle.ajoute('coordonnees', coordonnees);

	infoArticle.envoie();

}

function Gmap_setDirections(fromAddress, toAddress, locale) {
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function Gmap_handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	 alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	 alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	 alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	 
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	 alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	 alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	
   else alert("An unknown error occurred.");
   
}

function Gmap_onGDirectionsLoad(){ 
  // Use this function to access information about the latest load()
  // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

function ms_verifieConnexion() {
	  var login = $('connexion_login').value;
	  var pass = $('connexion_pass').value;
	  var formulaire = $('connexion_formulaire');
	  if( login != 'login' && login != '' && pass != 'pass' && pass != '' ) {
		 formulaire.submit();
	  }
	  else {
		 alert('Veuillez compléter le champ login et mot de passe !');
	  }
};

function ms_verifieConnexionAjax(nomFichier,nomBase,idGabarit,idGabaritOk,listeLayers,prefixe,pR) {
	  if(!prefixe) prefixe = "";
	  if(!pR) pR = "";
	  var login = $(prefixe+'connexion_login').value;
	  var pass = $(prefixe+'connexion_pass').value;
	  var souvenir = $(prefixe+'connexion_souvenir').checked?$(prefixe+'connexion_souvenir').value:0;
	  var formulaire = $(prefixe+'connexion_formulaire');
	  if( login != 'login' && login != '' && pass != 'pass' && pass != '' ) {
		 appelAjax('../medias/fonctions/'+nomFichier,'popup_message','ajax=1&b='+nomBase+'&connexion_login='+login+'&connexion_pass='+pass+'&idGabarit='+idGabarit+'&idGabaritOk='+idGabaritOk+'&layers='+listeLayers+'&souvenir='+souvenir+'&prefixe='+prefixe+'&pR='+pR,'inner');
	  }
	  else {
		 alert('Veuillez compléter le champ login et mot de passe !');
	  }
};

function ms_verifiePreInscriptionAjax(nomFichier,nomBase,idGabarit,listeLayers,prefixe) {
	  if(!prefixe) prefixe = "";
	  var email = $(prefixe+'preinscription_login').value;
	  var pass = $(prefixe+'preinscription_pass').value;
	  var formulaire = $(prefixe+'preinscription_formulaire');
	  if( email != '' && pass != '' ) {
		 appelAjax('../medias/fonctions/'+nomFichier,'popup_message','ajax=1&amp;b='+nomBase+'&amp;preinscription_login='+email+'&amp;preinscription_pass='+pass+'&amp;idGabarit='+idGabarit+'&amp;layers='+listeLayers+'&amp;prefixe='+prefixe,'inner');
	  }
	  else {
		 alert('Veuillez compléter le champ email et mot de passe !');
	  }
};


// Déclaration des évènement au chargmeent de la page
mev5_addEvent(window,'load',function(event,index) {
	// Déclaration d'un évènement pour gérer la fermeture du voile au click
	if($('popup_voile')) {
		mev5_addEvent($('popup_voile'),'click',function(event,index) {
			fermePopupFondu();
		});
		$('popup_voile').style.filter = "Alpha(opacity=100)";
		$('popup_voile').style.top = "-8000px";
		$('popup_voile').style.left = "0px";
	}
	if($('popup_message')) {
		$('popup_message').style.filter = "Alpha(opacity=100)";
		$('popup_message').style.top = "-8000px";
		$('popup_message').style.left = "0px";
	}
});

// Method d'encode et de décode base64
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
};

// Retourne la position de la souris
var ms_posSourisX = 0;
var ms_posSourisY = 0;
var ms_move = function (evt) {
	if(!evt) evt = window.event;
	if (document.all) {
		x = event.clientX+document.body.scrollLeft;
		y = event.clientY+document.body.scrollTop;
	} else if (document.layers) {
		x = evt.x;
		y = evt.y;
	} else if (document.getElementById) {
		x = evt.pageX;
		y = evt.pageY;
	}
	ms_posSourisX = x;
	ms_posSourisY = y;
};

// Gestion de l'InfoBulle MS
var ms_Bulle = function (sourceExec) {
	
	var self = this;
	this.mouvementBulle = false;
	this.sourceExec = sourceExec;

	// On commence par chercher tous les layer div qui on un attribut rel
	this.listeDIV = $('body').getElementsByTagName("div");
	for(var i = 0; i < this.listeDIV.length; i++) {
		var rel = this.listeDIV[ i ].getAttribute("id");
		if(rel != "undefined" && rel ) {
			// Activation
			mev5_addEvent(this.listeDIV[ i ],'mouseover',function(event,index){
				// On décrypte les paramètres !
				var idDiv = index.getAttribute("id");
				var rel = Base64.decode(idDiv.replace("-","="));//Base64.decode();
				var infoRel = rel.split("|");
				if(infoRel[0] == "bulle") {
					var file = infoRel[1];
					var params = infoRel[2];
					// On active l'infoBulle !
					if(!$('ms_bulle')) {
						var bulle = document.createElement('div');
						bulle.setAttribute("id","ms_bulle");
						bulle.setAttribute("style","");
						$('body').appendChild(bulle);
						$('ms_bulle').style.zIndex = '10000';
						$('ms_bulle').style.position = 'absolute';
						$('ms_bulle').style.display = 'none';
						//$('ms_bulle').style.backgroundColor = '#fff';
						//$('ms_bulle').style.margin = '0';
						//$('ms_bulle').style.padding = '5px';
						$('ms_bulle').style.top = '0px';
						$('ms_bulle').style.left = '0px';
						//$('ms_bulle').style.border = '1px solid #ccc';
					}
					if($('ms_bulle')) {
						if(file && params) {
							appelAjax(file,'ms_bulle',params,'inner',false,false,true); // On envoi la requête ajax
						} else if (file) {
							$('ms_bulle').innerHTML = file; // Sinon on écrit directement le contenu
						}
						// On fait suivre l'infobulle avec la souris
						self.mouvementBulle = true;
						$('ms_bulle').style.display = 'block'; // On rend la bulle invisible
					}
				}
			},this.listeDIV[ i ]);	
			// Désactivation de l'infobulle
			mev5_addEvent(this.listeDIV[ i ],'mouseout',function(event,index){
				// On décrypte les paramètres !
				var rel = Base64.decode(index.getAttribute("id"));//Base64.decode();
				var infoRel = rel.split("|");
				if(infoRel[0] == "bulle") {
					if($('ms_bulle')) {
						// On fait suivre l'infobulle avec la souris
						$('ms_bulle').style.display = 'none'; // On rend la bulle invisible
						self.mouvementBulle = false;
					}
				}
			},this.listeDIV[ i ]);
			// Déplacement souris
			if(this.sourceExec != 'ajax') {
				mev5_addEvent(document,'mousemove',function(event,index) {
					if(self.mouvementBulle) {
						ms_move(event);
						$('ms_bulle').style.top = parseInt(ms_posSourisY+15)+'px';
						$('ms_bulle').style.left = parseInt(ms_posSourisX+15)+'px';
					}
				});
			}
			
		}
		
	}

};

// Déclaration des évènement au chargmeent de la page | Activation de l'infobulle
mev5_addEvent(window,'load',function(event,index) {
	ms_Bulle();
});

var ms_appelFonctionsApresChargementAjax = function () {
	ms_Bulle('ajax');
};


// Gestion de slider prix
var ms_gestionSlidePrix = Class.create();
ms_gestionSlidePrix.prototype =  {
	
	initialize : function(prixMin, prixMax, sPrix, file, layer, params, initLMin, initLMax, idModule) {
	
		var self = this;
		this.prixMin = parseFloat(prixMin);
		this.prixMax = parseFloat(prixMax);
		this.idModule = idModule;
		this.sPrix = sPrix;
		this.file = file;
		this.layer = layer;
		this.params = params;
		this.initLMin = initLMin;
		this.initLMax = initLMax;
		this.cMin = $('cMin'+this.idModule);
		this.cMax = $('cMax'+this.idModule);
		this.autoriseDeplacement = false;
		this.cibleDeplacement = false;
		this.croisement = false;
		this.testCroisement = false;
		this.posInitC = 0;
		this.posInitS = 0;
		this.largeurSlider = parseInt($('ms_slider'+this.idModule).style.width);
		this.timer = false;
		this.action = true;
		this.prixInf = parseFloat(0);
		this.prixSup = parseFloat(100000);
		this.mousePos = false;

		// Construction du tableau des paliers des prix
		var aPrix = sPrix.split(";");
		this.aPaliers = new Array();
		this.aPaliersReverse = new Array();
		for(var a = 0; a < aPrix.length; a++) {
			sPalier = aPrix[a].split(":");
			this.aPaliers[sPalier[0]] = sPalier[1];
			this.aPaliersReverse[sPalier[0]] = sPalier[1];
		}
		this.aPaliersReverse.reverse();

		// On évènement sur le mousedown du cMin
		mev5_addEvent(this.cMin,'mousedown',function(event,index) {
			if(self.timer) clearTimeout(self.timer);
			if(self.action) {
				self.cibleDeplacement = $(index);
				self.idDeplacement = index;
				self.croisement = parseInt($('cMax'+self.idModule).style.left);
				self.testCroisement = 's';
				self.autoriseDeplacement = true;
				self.posInitC = parseInt(self.cibleDeplacement.style.left);
				self.posInitS = ms_posSourisX;
				$('cMax'+self.idModule).style.zIndex = 50;
				$('cMin'+self.idModule).style.zIndex = 100;
				return false;
			}
		}, 'cMin'+this.idModule);

		// On évènement sur le mousedown du cMax
		mev5_addEvent(this.cMax,'mousedown',function(event,index) {
			if(self.timer) clearTimeout(self.timer);
			if(self.action) {
				self.cibleDeplacement = $(index);
				self.idDeplacement = index;
				self.croisement = parseInt($('cMin'+self.idModule).style.left);
				self.testCroisement = 'i';
				self.autoriseDeplacement = true;
				self.posInitC = parseInt(self.cibleDeplacement.style.left);
				self.posInitS = parseInt(ms_posSourisX);
				$('cMin'+self.idModule).style.zIndex = 50;
				$('cMax'+self.idModule).style.zIndex = 100;
				return false;
			}
		}, 'cMax'+this.idModule);

		// On évènement sur le mousedown 
		mev5_addEvent(document,'mouseup',function(event,index) {
			if(index.autoriseDeplacement) {
				index.autoriseDeplacement = false;
				index.timer = setTimeout(function() {
					var result = index.retourneNombreResultat(true,index);
					if(result > 0) {
						// On lance l'envoi ajax
						var prixMin = index.calculPrix(parseInt($('cMin'+index.idModule).style.left),'cMin',true,index); 
						var prixMax = index.calculPrix(parseInt($('cMax'+index.idModule).style.left),'cMax',true,index); 
						index.action = false; // On bloque le slider
						$('ms_slider_load'+index.idModule).style.backgroundImage = $('ms_slider_load'+index.idModule).style.backgroundImage.replace("_actif.gif\")","_load.gif\")");
						appelAjax(index.file,index.layer,index.params+"&slPrixMin="+prixMin+"&slPrixMax="+prixMax+"&slsPrix="+index.sPrix+"&slQte="+result+"&slPrixInitMin="+index.prixMin+"&slPrixInitMax="+index.prixMax+"&changeSlPrix=Oui&slZindexMin="+$('cMin'+index.idModule).style.zIndex+"&slZindexMax="+$('cMax'+index.idModule).style.zIndex,"inner");
					}
				},1000);
			}
		}, this);

		// Mouvement du déplacement de la souris
		mev5_addEvent(document,'mousemove',function(event,index) {
			if(index.autoriseDeplacement) {
				ms_move(event);
				var leftDeplace = parseInt(ms_posSourisX)-index.posInitS;

				if(index.mousePos === false) { index.mousePos = ms_posSourisX; }
				if(index.mousePos >= ms_posSourisX) var sens = "l";
				else { var sens = "r"; }
				index.mousePos = ms_posSourisX;

				var leftC = (index.posInitC+leftDeplace);
				// Mur à gauche
				if(leftC < 0) leftC = 0;
				// Mur à droite
				if(leftC > index.largeurSlider) leftC = index.largeurSlider;

				// Protection anti croisement des curseurs
				if(index.testCroisement == 'i') {
					if(leftC < index.croisement) leftC = index.croisement;
				} else {
					if(leftC > index.croisement) leftC = index.croisement;
				}
				
				var r = index.calculPrixPalier(leftC,sens,index); // On calcul le prix palier (pour les quantité)
				leftC = r[0];
				index.retourneNombreResultat(null,index); // Affichage du nombre de résultat
				
				index.calculPrix(leftC,null,null,index); // On affiche le nouveau prix réel

				// On enregistre le décalage
				index.cibleDeplacement.style.left = leftC+'px';

				var decalagebouton = (parseInt($('cMin'+index.idModule).style.width))/2;
				$('ms_slider_load'+index.idModule).style.left = (parseInt($('cMin'+index.idModule).style.left)+decalagebouton)+"px";
				$('ms_slider_load'+index.idModule).style.width = (parseInt($('cMax'+index.idModule).style.left)-parseInt($('cMin'+index.idModule).style.left))+"px";
			} else {
				ms_move(event);
			}
			return false;
		}, this);

		this.calculPrixPalier = function(leftC,sens,index) {
			
			// On récupère le prix actuel		
			var prixActuel = index.calculPrix(leftC,null,null,index);
			//document.title = leftDeplace;
			if(sens == "l") {
				var tab = index.aPaliersReverse;
			} else {
				var tab = index.aPaliers;
			}

			// On ensuite on recherche le prix inférieur et supérieur au prix actuel le plus proche parmis tous les paliers
			for(var prix in tab) {
				prix = parseFloat(prix);
				if(prixActuel <= prix) {
					if(sens == "r") {
						if(prix < index.prixSup || index.prixSup <= index.prixInf ) index.prixSup = prix;
					} else {
						if(prix < index.prixSup) index.prixSup = prix;
						
					}
				}
				if(prixActuel > prix) {
					if(sens == "r") {
						if(prix > index.prixInf) index.prixInf = prix;
					} else {
						if(prix < index.prixInf || index.prixSup >= index.prixInf ) index.prixInf = prix;
						
					}
				}
			}
			
			if(index.idDeplacement == "cMin") {
				prixAutreCurseur = index.calculPrix(parseInt($('cMax'+index.idModule).style.left),null,null,index);
			} else {
				prixAutreCurseur = index.calculPrix(parseInt($('cMin'+index.idModule).style.left),null,null,index);
			}
			

			// Si la différence entre le prix sup et le prix actuel est moins élevée que celle entre le prix inférieur et le prix actuel, on se déplace le prochain palier
			if( ((index.prixSup-prixActuel) <= (prixActuel-index.prixInf)) ) { // On va au palier supérieur
				// On récupère le prix de l'autre curseur, et si c'est le même on ne l'attribut pas
				if(prixAutreCurseur != index.prixSup) {
					prixActuel = index.prixSup;
				}
			} else { // Sinon on va au palier inférieur
				if(prixAutreCurseur != index.prixInf) {
					prixActuel = index.prixInf;
				}
			}

			//leftC = index.calculLeft(prixActuel); // On force l'affichage du curseur au prochain palier
			return new Array(leftC,prixActuel);

		};

		this.calculPrix = function(left,cible,out,index) {

			if(!cible && index.idDeplacement) cible = index.idDeplacement;

			var ratioLargeur = ((left*100)/index.largeurSlider);
			var p = (( (index.prixMax-index.prixMin) *ratioLargeur)/100) + index.prixMin;
			p = (Math.round(p*100)/100).toString().replace(".",",");
			psplit = p.split(",");
			if(psplit.length == 1) { p = p+",00"; psplit = p.split(","); }
			if(psplit.length == 2 && !out && cible) {
				if( psplit[1].length == 1) p = psplit[0]+","+psplit[1]+"0";
				$('p'+cible+index.idModule).innerHTML = p;
			}
			return p.replace(",",".");
		};

		this.calculLeft = function(prix,index) {
			
			var ratioLargeur = ( ( (prix - index.prixMin) *100 ) / (index.prixMax-index.prixMin) );
			var left = ((ratioLargeur*index.largeurSlider)/100);
			return left;
			
		};

		this.retourneNombreResultat = function(out,index) {
			var quantite = 0;
			var a = 0;
			var prixMin = index.calculPrix(parseInt($('cMin'+index.idModule).style.left),false,out,index);
			var prixMax = index.calculPrix(parseInt($('cMax'+index.idModule).style.left),false,out,index);
			
			for(var prix in index.aPaliers) {
				prix = parseFloat(prix);
				if(prix >= prixMin && prix <= prixMax) quantite = quantite + parseInt(index.aPaliers[prix]);
			}
			$('ms_slide_nb_resultat'+index.idModule).innerHTML = "("+quantite+")";
			return quantite;
		};

		// Initialisation des curseurs suite au rechargement
		if(this.initLMin) {
			$('cMin'+this.idModule).style.left = this.calculLeft(this.initLMin,this)+"px";
		}
		if(this.initLMax) {
			$('cMax'+this.idModule).style.left = this.calculLeft(this.initLMax,this)+"px";
		}

		// Au chargement on initialise les prix
		if(!this.initLMax && !this.initLMin) {
			this.calculPrix(parseInt($('cMin'+this.idModule).style.left),'cMin',null,this);
			this.calculPrix(parseInt($('cMax'+this.idModule).style.left),'cMax',null,this);
			this.retourneNombreResultat(null,this);
		}
		var decalagebouton = (parseInt($('cMin'+this.idModule).style.width))/2;
		$('ms_slider_load'+this.idModule).style.left = (parseInt($('cMin'+this.idModule).style.left)+decalagebouton)+"px";
		$('ms_slider_load'+this.idModule).style.width = (parseInt($('cMax'+this.idModule).style.left)-parseInt($('cMin'+this.idModule).style.left))+"px";

		$('ms_ctn_slider_prix'+this.idModule).style.display = 'block';

	}

};

var ms_produitsConsultes = Class.create();
ms_produitsConsultes.prototype =  {
	
	initialize : function(position, taille, statutFenetre) {
		
		// Récupération des layers
		this.layer = 'popup_consultes'; this.domLayer = $('popup_consultes'); if(!this.domLayer) return false;
		this.layerPdt = 'ms_consultes_pdt'; this.domLayerPdt = $('ms_consultes_pdt'); if(!this.domLayerPdt) return false;
		this.layerPdtCtn = 'ms_consultes_pdt_ctn'; this.domLayerPdtCtn = $('ms_consultes_pdt_ctn'); if(!this.domLayerPdtCtn) return false;
		this.layerPdtScroll = 'ms_consultes_pdt_ctn_scroll'; this.domLayerPdtScroll = $('ms_consultes_pdt_ctn_scroll'); if(!this.domLayerPdtScroll) return false;
		this.bouton = 'ms_consultes_bt'; this.domBouton = $('ms_consultes_bt'); if(!this.domBouton) return false;
		this.boutonUp = 'ms_consultes_bt_up'; this.domBoutonUp = $('ms_consultes_bt_up'); if(!this.domBoutonUp) return false;
		this.boutonUp2 = 'ms_consultes_bt_up2'; this.domBoutonUp2 = $('ms_consultes_bt_up2'); if(!this.domBoutonUp2) return false;
		this.boutonDo = 'ms_consultes_bt_down'; this.domBoutonDo = $('ms_consultes_bt_down'); if(!this.domBoutonDo) return false;
		this.boutonDo2 = 'ms_consultes_bt_down2'; this.domBoutonDo2 = $('ms_consultes_bt_down2'); if(!this.domBoutonDo2) return false;
		// On cache les layers à l'initialisation
		this.domLayer.style.display = this.domLayerPdt.style.display = "none";
		// Paramètres
		this.position = position; if(!this.position) this.position = "right";
		this.taille = taille; // Taille de la zone
		this.statutFenetre = statutFenetre;
		// Infos document et fenêtre
		var tailleDocument = getDocumentSize(); this.largeurDoc = tailleDocument[0]; this.hauteurDoc = tailleDocument[1];
		var tailleWindow = getDisplaySize(); this.largeurWindow = tailleWindow[0]; this.hauteurWindow = tailleWindow[1];
		// Autorisation d'ouverture et fermeture du panneau
		this.bloqueClique = false;
		this.bloqueScroll = true;
		this.animationScroll = false;
		
		// On commence par positionner les layers, selon la conf de la position
		// Fonction de positionnement
		this.gestionPositionnement = function(index, action) {
			switch(index.position) {
				case 'right': 
					var scrollLeft = ms_getDocumentLeft();
					index.domLayer.style.zIndex = "900";
					index.domLayer.style.top = "0px"; index.domLayerPdt.style.top = "0px";
					var inc = (action != "redim")?1:0;
					if(index.statutFenetre == "ouvert" && action == "scroll") {
						index.domLayer.style.right = (((scrollLeft*(-1))+inc)+parseInt(index.taille))+"px";
					} else {
						index.domLayer.style.right = ((scrollLeft*(-1))+inc)+"px";
					}
					index.domLayerPdt.style.right = ""; index.domLayerPdt.style.left = parseInt(index.domBouton.style.width)+"px";
					index.domLayer.style.width = (parseInt(index.domBouton.style.width))+"px"; index.domLayerPdt.style.width = index.taille+"px";
					index.domLayer.style.height = index.hauteurDoc+"px"; index.domLayerPdt.style.height = index.hauteurDoc+"px";
					index.domBouton.style.right = "0px"; index.domBouton.style.left = "1px";
					index.domBouton.style.top = ( (parseInt(index.hauteurWindow)/2) - (parseInt(index.domBouton.style.height)/2) )+"px";
					index.domBoutonUp.style.marginTop = index.domBoutonUp2.style.marginTop = "10px"; index.domBoutonUp.style.zIndex = index.domBoutonUp2.style.zIndex = "901";
					index.domBoutonDo.style.marginTop = index.domBoutonDo.style.marginTop = "0px"; index.domBoutonDo.style.zIndex = index.domBoutonDo.style.zIndex = "901";
					index.domLayerPdtCtn.style.marginTop = "10px";
					index.domLayerPdtCtn.style.height = ((parseInt(index.domLayerPdt.style.height) - ( (parseInt(index.domBoutonUp.style.height)*2) + (parseInt(index.domBoutonDo.style.height)*2) )) - 30)+"px";
				break;
				default :
					alert('Position '+index.position+' non gérée !');
				break;
			}
		};
		this.gestionPositionnement(this);

		// On affiche le tout (seulement le bouton ouverture s'affiche) en bordure de fenêtre
		this.domLayer.style.display = "block";
		
		// Les effets animés seront désactivés sur IE6 et IE7 et opéra
		this.navNok = ( (/MSIE\s7/.test(navigator.appVersion)) || (/MSIE\s6/.test(navigator.appVersion)) || navigator.appName == "Opera" )?true:false;
		
		// Si à l'init on doit ouvrir le panneau
		if(this.statutFenetre == "ouvert") {
			this.domBouton.style.backgroundPosition = "-"+parseInt(this.domBouton.style.width)+"px 0px";	
			this.domLayer.style.right = (parseInt(this.domLayer.style.right)-1)+"px";
			this.domLayerPdt.style.display = "block";
			this.domLayer.style.width = (parseInt(this.taille)+parseInt(this.domBouton.style.width))+"px";
		}
		
		// Evenement sur le bouton d'ouverture/fermeture
		mev5_addEvent(this.domBouton,'click',function(event,index) {
			index.gestionPositionnement(index,"redim");
			var scrollLeft = ms_getDocumentLeft();
			var inc = scrollLeft?1:0;
			if(!index.bloqueClique) {
				// On laffiche le tout
				if(index.statutFenetre == "ouvert") {
					if(!index.navNok) {
						index.bloqueClique = true;
						index.domBouton.style.backgroundPosition = "0px 0px";
						var animation = new Tween(index.domLayer.style,'width',Tween.bounceEaseOut,(parseInt(index.taille)+parseInt(index.domBouton.style.width)),(parseInt(index.domBouton.style.width)),1.5,'px');
						animation.onMotionFinished = function(){
							index.statutFenetre = "ferme";
							index.domLayerPdt.style.display = "none";
							appelAjax('../medias/fonctions/ms_traitement_ajax.php','popup_message','ajax=Oui&ms_etat_panneau_consultes='+index.statutFenetre,'inner');
							index.bloqueClique = false;
							index.domLayer.style.right = (parseInt(index.domLayer.style.right)+1)+"px";
						}; animation.start();
					} else {
						index.domBouton.style.backgroundPosition = "0px 0px";
						index.statutFenetre = "ferme";
						index.domLayerPdt.style.display = "none";
						index.domLayer.style.width = (parseInt(index.domBouton.style.width))+"px";
						appelAjax('../medias/fonctions/ms_traitement_ajax.php','popup_message','ajax=Oui&ms_etat_panneau_consultes='+index.statutFenetre,'inner');
					}
				} else {
					index.domLayer.style.right = (parseInt(index.domLayer.style.right)-1)+"px";
					if(!index.navNok) {
						index.bloqueClique = true;
						index.domBouton.style.backgroundPosition = "-"+parseInt(index.domBouton.style.width)+"px 0px";
						var animation = new Tween(index.domLayer.style,'width',Tween.strongEaseOut,(parseInt(index.domBouton.style.width)),(parseInt(index.taille)+parseInt(index.domBouton.style.width)),1,'px');
						animation.onMotionFinished = function(){
							index.statutFenetre = "ouvert";
							appelAjax('../medias/fonctions/ms_traitement_ajax.php','popup_message','ajax=Oui&ms_etat_panneau_consultes='+index.statutFenetre,'inner');
							index.bloqueClique = false;
						}; index.domLayerPdt.style.display = "block"; animation.start();
					} else {
						index.domBouton.style.backgroundPosition = "-"+parseInt(index.domBouton.style.width)+"px 0px";	
						index.statutFenetre = "ouvert";
						index.domLayerPdt.style.display = "block";
						appelAjax('../medias/fonctions/ms_traitement_ajax.php','popup_message','ajax=Oui&ms_etat_panneau_consultes='+index.statutFenetre,'inner');
					}
				}
				
			}
		}, this);

		

		// Evenement sur le bouton de scroll up
		this.gestionScrollUp = function(index) {
			this.statutFleche(index);
			if(!index.bloqueClique) {
				// Si le layer des produits est plus que celui de la page
				var hauteurPdt = parseInt(index.domLayerPdtScroll.offsetHeight);
				var hauteurZone = parseInt(index.domLayerPdtCtn.style.height);
				if( hauteurZone > hauteurPdt ) {
					// On bloque le scroll
					index.bloqueScroll = true;
				} else {
					// On active le scroll
					index.bloqueScroll = false;
				}
				if(!index.bloqueScroll) {
					var d = parseInt(index.domLayerPdtScroll.style.top);
					if(d < 0) {
						if(index.animationScroll) index.animationScroll.stop();
						index.animationScroll = new Tween(index.domLayerPdtScroll.style,'top',Tween.regularEaseInOut,d,0,1.5,'px');
						index.animationScroll.onMotionFinished = function(){
							index.statutFleche(index);
						};
						index.animationScroll.start();
						index.domBoutonUp.style.backgroundPosition = index.domBoutonUp2.style.backgroundPosition = "0px "+((parseInt(index.domBoutonUp.style.height))*(-2))+"px";
					} else {

					}
				}
			}
		};

		mev5_addEvent(this.domBoutonUp,'mouseover',function(event,index) {
			index.gestionScrollUp(index);
		}, this);
		mev5_addEvent(this.domBoutonUp2,'mouseover',function(event,index) {
			index.gestionScrollUp(index);
		}, this);

		mev5_addEvent(this.domBoutonUp,'mouseout',function(event,index) {
			index.animationScroll.stop();
			index.statutFleche(index);
		}, this);
		mev5_addEvent(this.domBoutonUp2,'mouseout',function(event,index) {
			index.animationScroll.stop();
			index.statutFleche(index);
		}, this);

		// Evenement sur le bouton de scroll down
		this.gestionScrollDo = function(index) {
			this.statutFleche(this);
			if(!index.bloqueClique) {
				// Si le layer des produits est plus que celui de la page
				var hauteurPdt = parseInt(index.domLayerPdtScroll.offsetHeight);
				var hauteurZone = parseInt(index.domLayerPdtCtn.style.height);
				if( hauteurZone > hauteurPdt ) {
					// On bloque le scroll
					index.bloqueScroll = true;
				} else {
					// On active le scroll
					index.bloqueScroll = false;
				}
				if(!index.bloqueScroll) {
					var d = parseInt(index.domLayerPdtScroll.style.top);
					var a = ((hauteurPdt - hauteurZone)*(-1));
					if(a < hauteurPdt) {
						if(index.animationScroll) index.animationScroll.stop();
						index.animationScroll = new Tween(index.domLayerPdtScroll.style,'top',Tween.regularEaseInOut,d,a,1.5,'px');
						index.animationScroll.onMotionFinished = function(){
							index.statutFleche(index);
						};
						index.animationScroll.start();
						index.domBoutonDo.style.backgroundPosition = index.domBoutonDo2.style.backgroundPosition = "0px "+((parseInt(index.domBoutonDo.style.height))*(-2))+"px";
					}
				}
			}
		};

		mev5_addEvent(this.domBoutonDo,'mouseover',function(event,index) {
			index.gestionScrollDo(index);
		}, this);
		mev5_addEvent(this.domBoutonDo2,'mouseover',function(event,index) {
			index.gestionScrollDo(index);
		}, this);

		mev5_addEvent(this.domBoutonDo,'mouseout',function(event,index) {
			index.animationScroll.stop();
			index.statutFleche(index);
		}, this);
		mev5_addEvent(this.domBoutonDo2,'mouseout',function(event,index) {
			index.animationScroll.stop();
			index.statutFleche(index);
		}, this);

		this.statutFleche = function(index) {
			var hauteurPdt = parseInt(index.domLayerPdtScroll.offsetHeight);
			var hauteurZone = parseInt(index.domLayerPdtCtn.style.height);
			if( hauteurZone > hauteurPdt ) {
				index.domBoutonUp.style.backgroundPosition = index.domBoutonUp2.style.backgroundPosition = "0px 0px";
				index.domBoutonDo.style.backgroundPosition = index.domBoutonDo2.style.backgroundPosition = "0px 0px";
			} else {
				var d = parseInt(index.domLayerPdtScroll.style.top);
				if(d < 0) {
					index.domBoutonUp.style.backgroundPosition = index.domBoutonUp2.style.backgroundPosition = "0px "+((parseInt(index.domBoutonUp.style.height))*(-1))+"px";
				} else {
					index.domBoutonUp.style.backgroundPosition = index.domBoutonUp2.style.backgroundPosition = "0px 0px";
				}
				
				var a = ((hauteurPdt - hauteurZone)*(-1));
				if(a < hauteurPdt && d != a) {
					index.domBoutonDo.style.backgroundPosition = index.domBoutonDo2.style.backgroundPosition = "0px "+((parseInt(index.domBoutonDo.style.height))*(-1))+"px";
				} else {
					index.domBoutonDo.style.backgroundPosition = index.domBoutonDo2.style.backgroundPosition = "0px 0px";
				}
			}
		};
		this.statutFleche(this);

		mev5_addEvent(window,'scroll',function(event,index) {
			index.gestionPositionnement(index,'scroll');
			//index.domLayer.style.top = ms_getDocumentTop()+"px";
		}, this);

		mev5_addEvent(window,'resize',function(event,index) {
			index.gestionPositionnement(index,'scroll');
		}, this);

	}

};


/**********************************************************************
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright (c) 2001 Robert Penner
JavaScript version copyright (C) 2006 by Philippe Maegerman
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
   * Neither the name of the author nor the names of contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*****************************************/
function Delegate() {}
Delegate.create = function (o, f) {
	var a = new Array() ;
	var l = arguments.length ;
	for(var i = 2 ; i < l ; i++) a[i - 2] = arguments[i] ;
	return function() {
		var aP = [].concat(arguments, a) ;
		f.apply(o, aP);
	}
};

Tween = function(obj, prop, func, begin, finish, duration, suffixe){
	this.init(obj, prop, func, begin, finish, duration, suffixe)
};
var t = Tween.prototype;

t.obj = new Object();
t.prop='';
t.func = function (t, b, c, d) { return c*t/d + b; };
t.begin = 0;
t.change = 0;
t.prevTime = 0;
t.prevPos = 0;
t.looping = false;
t._duration = 0;
t._time = 0;
t._pos = 0;
t._position = 0;
t._startTime = 0;
t._finish = 0;
t.name = '';
t.suffixe = '';
t._listeners = new Array();	
t.setTime = function(t){
	this.prevTime = this._time;
	if (t > this.getDuration()) {
		if (this.looping) {
			this.rewind (t - this._duration);
			this.update();
			this.broadcastMessage('onMotionLooped',{target:this,type:'onMotionLooped'});
		} else {
			this._time = this._duration;
			this.update();
			this.stop();
			this.broadcastMessage('onMotionFinished',{target:this,type:'onMotionFinished'});
		}
	} else if (t < 0) {
		this.rewind();
		this.update();
	} else {
		this._time = t;
		this.update();
	}
};
t.getTime = function(){
	return this._time;
};
t.setDuration = function(d){
	this._duration = (d == null || d <= 0) ? 100000 : d;
};
t.getDuration = function(){
	return this._duration;
};
t.setPosition = function(p){
	this.prevPos = this._pos;
	var a = this.suffixe != '' ? this.suffixe : '';
	this.obj[this.prop] = Math.round(p) + a;
	this._pos = p;
	this.broadcastMessage('onMotionChanged',{target:this,type:'onMotionChanged'});
};
t.getPosition = function(t){
	if (t == undefined) t = this._time;
	return this.func(t, this.begin, this.change, this._duration);
};
t.setFinish = function(f){
	this.change = f - this.begin;
};
t.geFinish = function(){
	return this.begin + this.change;
};
t.init = function(obj, prop, func, begin, finish, duration, suffixe){
	if (!arguments.length) return;
	this._listeners = new Array();
	this.addListener(this);
	if(suffixe) this.suffixe = suffixe;
	this.obj = obj;
	this.prop = prop;
	this.begin = begin;
	this._pos = begin;
	this.setDuration(duration);
	if (func!=null && func!='') {
		this.func = func;
	}
	this.setFinish(finish);
};
t.start = function(){
	this.rewind();
	this.startEnterFrame();
	this.broadcastMessage('onMotionStarted',{target:this,type:'onMotionStarted'});
	//alert('in');
};
t.rewind = function(t){
	this.stop();
	this._time = (t == undefined) ? 0 : t;
	this.fixTime();
	this.update();
};
t.fforward = function(){
	this._time = this._duration;
	this.fixTime();
	this.update();
};
t.update = function(){
	this.setPosition(this.getPosition(this._time));
	};
t.startEnterFrame = function(){
	this.stopEnterFrame();
	this.isPlaying = true;
	this.onEnterFrame();
};
t.onEnterFrame = function(){
	if(this.isPlaying) {
		this.nextFrame();
		setTimeout(Delegate.create(this, this.onEnterFrame), 0);
	}
};
t.nextFrame = function(){
	this.setTime((this.getTimer() - this._startTime) / 1000);
	};
t.stop = function(){
	this.stopEnterFrame();
	this.broadcastMessage('onMotionStopped',{target:this,type:'onMotionStopped'});
};
t.stopEnterFrame = function(){
	this.isPlaying = false;
};

t.continueTo = function(finish, duration){
	this.begin = this._pos;
	this.setFinish(finish);
	if (this._duration != undefined)
		this.setDuration(duration);
	this.start();
};
t.resume = function(){
	this.fixTime();
	this.startEnterFrame();
	this.broadcastMessage('onMotionResumed',{target:this,type:'onMotionResumed'});
};
t.yoyo = function (){
	this.continueTo(this.begin,this._time);
};

t.addListener = function(o){
	this.removeListener (o);
	return this._listeners.push(o);
};
t.removeListener = function(o){
	var a = this._listeners;	
	var i = a.length;
	while (i--) {
		if (a[i] == o) {
			a.splice (i, 1);
			return true;
		}
	}
	return false;
};
t.broadcastMessage = function(){
	var arr = new Array();
	for(var i = 0; i < arguments.length; i++){
		arr.push(arguments[i])
	}
	var e = arr.shift();
	var a = this._listeners;
	var l = a.length;
	for (var i=0; i<l; i++){
		if(a[i][e])
		a[i][e].apply(a[i], arr);
	}
};
t.fixTime = function(){
	this._startTime = this.getTimer() - this._time * 1000;
};
t.getTimer = function(){
	return new Date().getTime() - this._time;
};
Tween.backEaseIn = function(t,b,c,d,a,p){
	if (s == undefined) var s = 1.70158;
	return c*(t/=d)*t*((s+1)*t - s) + b;
};
Tween.backEaseOut = function(t,b,c,d,a,p){
	if (s == undefined) var s = 1.70158;
	return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
};
Tween.backEaseInOut = function(t,b,c,d,a,p){
	if (s == undefined) var s = 1.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
};
Tween.elasticEaseIn = function(t,b,c,d,a,p){
		if (t==0) return b;  
		if ((t/=d)==1) return b+c;  
		if (!p) p=d*.3;
		if (!a || a < Math.abs(c)) {
			a=c; var s=p/4;
		}
		else 
			var s = p/(2*Math.PI) * Math.asin (c/a);
		
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	
};
Tween.elasticEaseOut = function (t,b,c,d,a,p){
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
	};
Tween.elasticEaseInOut = function (t,b,c,d,a,p){
	if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) var p=d*(.3*1.5);
	if (!a || a < Math.abs(c)) {var a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
};

Tween.bounceEaseOut = function(t,b,c,d){
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
};
Tween.bounceEaseIn = function(t,b,c,d){
	return c - Tween.bounceEaseOut (d-t, 0, c, d) + b;
	};
Tween.bounceEaseInOut = function(t,b,c,d){
	if (t < d/2) return Tween.bounceEaseIn (t*2, 0, c, d) * .5 + b;
	else return Tween.bounceEaseOut (t*2-d, 0, c, d) * .5 + c*.5 + b;
	};

Tween.strongEaseInOut = function(t,b,c,d){
	return c*(t/=d)*t*t*t*t + b;
	};

Tween.regularEaseIn = function(t,b,c,d){
	return c*(t/=d)*t + b;
	};
Tween.regularEaseOut = function(t,b,c,d){
	return -c *(t/=d)*(t-2) + b;
	};

Tween.regularEaseInOut = function(t,b,c,d){
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
	};
Tween.strongEaseIn = function(t,b,c,d){
	return c*(t/=d)*t*t*t*t + b;
	};
Tween.strongEaseOut = function(t,b,c,d){
	return c*((t=t/d-1)*t*t*t*t + 1) + b;
	};

Tween.strongEaseInOut = function(t,b,c,d){
	if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
	return c/2*((t-=2)*t*t*t*t + 2) + b;
	};
OpacityTween.prototype = new Tween();
OpacityTween.prototype.constructor = Tween;
OpacityTween.superclass = Tween.prototype;

function OpacityTween(obj,func,fromOpacity,toOpacity,duration){
	this.targetObject = obj;
	this.init(new Object(),'x',func,fromOpacity,toOpacity,duration);
};
var o = OpacityTween.prototype;
o.targetObject = {};
o.onMotionChanged = function(evt){
	var v = evt.target._pos;
	var t = this.targetObject;
	t.style['opacity'] = v / 100;
	t.style['-moz-opacity'] = v / 100;
	if(t.filters) t.filters.alpha['opacity'] = v;
};
