/*
 * Formatage en euro d'un montant
 * @see js paiementjs, panier.js et relais_colis.js
 */
function formatCurrency(num) {
	num = isNaN(num) || num == '' || num == null ? 0.00 : num;
	return parseFloat(num).toFixed(2).replace ('.', ',') + " &euro;";
}

/*
 * Création de compte, layer adresse et identification pendant la commande
 * Rempli le liste des civilité en fonction du type de compte sélectionné (particulier / professionnel)
 * Masque / affichage l'avatar, le prénom et le numéro SIRET
 */
var civiliteParticulier=new Array("Mme","Mr","Melle");
var civiliteParticulierLibelle=new Array("Madame","Monsieur","Mademoiselle");
var civilitePro=new Array("Eurl", "Sarl", "Sa", "Scp", "Snc", "Soc");
var elt;

function fillCivilite (isProfessional) {
	elt = jQuery("#selectCivilite")[0];
	elt.options.length = 0;
	if (isProfessional) {
		
		for (var i=0; i<civilitePro.length;i++) {
			var option=new Option(civilitePro[i],civilitePro[i]);
			elt.options[i] = option;
		}
	} else {
		for (var i=0; i<civiliteParticulier.length;i++) {
			var option=new Option(civiliteParticulier[i],civiliteParticulierLibelle[i]);
			elt.options[i] = option;
		}
		
	}
	
	if(isProfessional) {
		jQuery("#ligne_avatar").hide();
		jQuery("#ligne_prenom").hide();
		jQuery("#ligne_siret").show();
	} else {
		jQuery("#ligne_avatar").show();
		jQuery("#ligne_prenom").show();
		jQuery("#ligne_siret").hide();
	}
	
}

/*
 * Création de compte, layer adresse et identification pendant la commande
 * Présélection de la civilité au chargement de la page (si l'info est déjà présente en session)
 */
function setOption (isProfessional, civilite) {
	if (isProfessional) {
		for (var i=0; i<civilitePro.length;i++) {
			if (civilite==civilitePro[i]) {
				elt.options[i].selected=true;
			}
		}
	} else {
		switch(civilite) {
			case "Madame":elt.options[0].selected=true;break;
			case "Monsieur":elt.options[1].selected=true;break;
			case "Mademoiselle":elt.options[2].selected=true;break;
		}
	}
}

/*
 * Debut fonctions page suivre commande
 */
function openColissimo(numero) {
	if (numero == undefined) {
		numero = document.formsuivitcom.numeroColissimo.value;
	}
	if (!testNumero(numero)) return;
		openPopScroll("http://www.coliposte.net/particulier/suivi_particulier.jsp?colispart="+numero,"Colissimo",760,500);
}

function openChronopost() {
	numero = document.formsuivitcom.numeroChronopost.value;
	if (!testNumero(numero)) return;
	openPopScroll("http://www.fr.chronopost.com/web/fr/tracking/suivi_inter.jsp?listeNumeros="+numero,"Chronopost",790,500);
}

function testNumero(numero){
	if (numero.length<13){
		afficheAlert (Translator.translate('probleme.numero.colis'), numRayon);
		return false;
	}
	return true;
}
// fin fonctions page suivre commande

/*
 * Renvoie true si le mail est correcte, false sinon
 * Si le mail est faux une alert est affichée
 */
function isEmailOk( email){
	return new RegExp("^[\\w\\-]+(\\.[\\w\\-]+)*@[\\w\\-]+(\\.[\\w\\-]+)*\\.[\\w\\-]{2,}$", "i").test(email);
}

/*
 * Mot de passe oublié
 * @see compte_login.jsp, identification.jsp
 */
function pertemotdepasse(form) {
	if(form.login.value == "") {
		jQuery("#contenu_alerte").html(Translator.translate('compteLogin.saisiMail'));
		jQuery("#layer_alerte").show();
		return;
	}else if (!isEmailOk(form.login.value)) {
		jQuery("#contenu_alerte").html(Translator.translate('contact.saisiEmail') + " (" + document.form_compte.login.value+ ") " + Translator.translate('contact.emailNonValid') + ".<br>" + Translator.translate('contact.nouvSaisi'));
		jQuery("#layer_alerte").show();
		return;
	}else {				
		form.Destination.value = "sendPassword";
		form.submit();
	}
}

/*
 * Compte client commande, affiche le layer commentaires gsell / client
 * TODO bug: afficher un layer
 */
function afficheLayerCommentaires(num) {
	
	jQuery.get(
		"/maroquinerie_valise_bagages_sac.gnc",
		"Destination=affPopupCommentairesCommandeClient&numCommande=" + num,
		function(data, textStatus, jqXHR) {
			
		}
	)
	
}

/*
 * Affiche le layer de message d'alerte
 */
function afficheAlert (message) {
	jQuery("#layer_alerte").show();
	jQuery("#contenu_alerte").html(message);
}

/*
 * Layer envoyer à un ami : reset et validation
 */
function effaceCommentaires(id) {
	jQuery(id)[0].commentaires.value = "";
}

/*
 * Page produit : envoyer à un ami
 */
function submitEnvoyerAmi(numArticle) {
	var formTmp = document.getElementById('envoyerAmiForm');
	if (!isEmailOk(formTmp.email.value)) {
		hideElement('layer_envoi_ami');
		afficheAlert (Translator.translate('contact.saisiEmail')+ " (" +formTmp.email.value+ ") " + Translator.translate('contact.emailNonValid') +".<br>" + Translator.translate('contact.nouvSaisi'));
		return;
	}
	jQuery("#contenu_layer_ami").load(jQuery("#envoyerAmiForm").attr("action"), jQuery("#envoyerAmiForm").serialize());

}

/*
 * Validation du formulaire de contact
 */
function envoyermessage() {
	var objform = document.forms.formmessage;
	// test de la validité de l'email
	if(objform.email.value!=""){
		if (!isEmailOk(objform.email.value)) {
			afficheAlert (Translator.translate('contact.saisiEmail')+ " (" +objform.email.value+ ") " + Translator.translate('contact.emailNonValid') +".<br>" + Translator.translate('contact.nouvSaisi'));
			
			return;
		}
	}
	//test du champs obligatoire
	var oblig = "";
	if (objform.numMotif) {
		if (objform.numMotif.value == "") oblig += "<br> - Motif";	
	}
	if (objform.nom.value=="") oblig += "<br> - Nom";		
	if (objform.email.value=="") oblig += "<br> - E-mail";		
	if (objform.message.value=="") oblig += "<br> - Message";		
	if (oblig==""){
		objform.Destination.value="validNousContacter";
		objform.submit();                                                                                   
	} else {
		oblig = Translator.translate('contact.champsObligatoires') + oblig;
		jQuery("#contenu_alerte").html(oblig);
		jQuery("#layer_alerte").show();
	}		
}

/*
 * Suppression de tous les articles du comparateur
 * exclusivement depuis le layer
 */
function viderComparateur() {
	jQuery.post(
		"/catComparateur.do",
		"method=supprime&vider=true&numa=&affichage=layer",
		function(data, textStatus, jqXHR) {
			setTimeout(comparateur, 1000);
			setTimeout(function() {
				jQuery("#layer_comparateur").html(data);
			}, 2000);
		}
	);
}

/*
 *  Ouverture des partages facebook dans une popup
 */
function popupFacebook(page){
	var h = 400;
	var w = 500;
	var LeftPosition = (screen.width-w)/2;
	var TopPosition = (screen.height-h)/2;
	var settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+', scrollbars=no,resizable=no, menubar=no';
	window.open(page,"Facebook",settings) ;
}

/*
 * Dom loaded
 * Tous les scripts nécésitant un chargement complet du dom
 * devraient se trouver ici.
 */
jQuery(function() {

	/*
	 * Fermeture des layers #conteneur_layer_infos au clic
	 * sur le reste de la page
	 */
	jQuery("#layer").live("click", function(event) {
		if(event.target === this)
			eval(jQuery(this).find(".fermer").attr("href"));
	});
	
	/*
	 * Page produit : état miniature sélectionnée
	 * @gsell/bagages
	 */
	jQuery(".vignettes a").click(function() {
		if(!jQuery(this).hasClass("vignette360")) {
			jQuery(".MagicZoomPlus").show(); // Affichage du zoom
				jQuery("#container360").hide(); // On cache le 360
				if(!jQuery("#container360").parent().hasClass("image_produit")) { // et son wrapper automatique
					jQuery("#container360").parent().hide();
				}
			
			jQuery(".threesixtyEnabled").remove(); // Suppression du graphisme sous le 360
		}
		jQuery(".vignettes a").removeClass("selected select");
		jQuery(this).addClass("selected select");
	});
	
	/*
	 * Page produit : état couleur sélectionnée
	 * @gsell
	 */
	jQuery(".carre_couleur").click(function() {
		jQuery(".carre_couleur").removeClass("selected");
		jQuery(this).addClass("selected");
	});
	
	/*
	 * Minie fiche : état couleur sélectionnée
	 * @gsell
	 */
	jQuery("#quickcouleur a").mouseover(function() {
		jQuery("#quickcouleur a").removeClass("selected");
		jQuery(this).addClass("selected");
	});
	
	/*
	 * Menu horizontale : insertion des sous menus dans leur menu parent
	 */
	jQuery("div.titre_rayon").each(function(index, element) {
		jQuery("#" + jQuery(element).attr("rel")).show().wrap("<div class=\"liste\" id=\"" + jQuery(element).attr("rel") + "\" />").insertAfter(jQuery(element));
	});
	
	/*
	 * Initialisation des champs texte
	 */
	jQuery("input[type=text].initinput").fields();

});

/*
 * Plugin jQuery d'initilisation des valeurs par défaut sur les champs texte
 * Au clic, si le champ contient la valeur par défaut, celui-ci est vidé.
 * Quand on quitte le champ, si celui-ci est vide, on remet la valeur par défaut.
 */
jQuery.fn.fields = function() {
	this.each(function(index, element) {
		jQuery(element).data("defaultValue", jQuery(element).val());
		jQuery(element).click(function() {
			if(jQuery(this).val() == jQuery(this).data("defaultValue")) {
				jQuery(this).val("");
			}
		}).blur(function() {
			if(jQuery(this).val() == "") {
				jQuery(this).val(jQuery(this).data("defaultValue"));
			}
		});
	});
};

/*
 * Affiche le layer d'inscription à la newsletter
 */
function afficheLayerNewsletter(objetForm) {
	
	var valid = new Validation(objetForm);
	if (valid.validate()){
		jQuery("#contenu_newsletter").load(
			"/maroquinerie_valise_bagages_sac.gnc?Destination=newsletterSubscribe&email=" + objetForm.email.value,
			function() {
				showElement("layer_newsletter");
			}
		);
	}
	
}

/*
 * Validation du layer d'inscription à la newsletter
 */
function valideNewsletter(objetForm) {
	objetForm.Destination.value="validNewsLetter";
	objetForm.submit();
}

/*
 * Les fonctions qui appellent alerteSurcharge doivent être surchargées dans le fichier modele.js du site
 * car ces fonctions sont liées à la structure html du site en question
 */
function alerteSurcharge() {
	alert(Translator.translate('methode.surcharge'));
}
function successLayer() {alerteSurcharge();}

/*
 * fonction générique pour afficher un layer
 */
function showElement(element) {
	jQuery("#" + element).show();
}

/*
 * fonction générique pour cacher un layer
 */
function hideElement(element){
	jQuery("#" + element).hide();
}

/*
 * fonction générique pour soumettre un formulaire créé à la volée
 */
function doPost(params, url){
	if (!url){
		url='/maroquinerie_valise_bagages_sac.gnc';
	}
	var myForm = jQuery("<form action=\"" + url + "\" method=\"post\" />");
	jQuery.each(params, function(index, value){
		myForm.append("<input type=\"hidden\" name=\"" + index + "\" value=\"" + value + "\" />");
		
	});
	myForm.appendTo("body").submit();
	
}

/*
 * Affichage du layer comparateur
 */
function comparateur() {
	
	jQuery("#comparateur").slideToggle();
	jQuery("#layer_comparateur1").toggleClass("on");
	
}

/*
 * Ajout au comparateur depuis les derniesr produits vus
 */
function ajouteAuComparateur()  {
	
	params = "method=ajoute&affichage=page&"
	
	i = 1;
	jQuery("#dernier_produits input:checked").each(function(index, element) {
		params += "num" + (index + 1) + "=" + jQuery(element).val() + "&";
		i++;
	});
	
	if (i == 2) {
		params = params.concat("numa=&num2=&num3=&num4");
	}
	if (i == 3) {
		params = params.concat("numa=&num3=&num4");
	}
	if (i == 4) {
		params = params.concat("numa=&num4");
	}
	if (i == 5) {
		params = params.concat("numa");
	}
	
	if ((i > 5) || (i == 1)){
		alert(Translator.translate('comparateur.nombre.limite'));
		return;
	}
	
	document.location.href = "/catComparateur.do?" + params;
	
}



/**
 * Ici sont définies les fonctions et Objets javascript utilisées ou nécéssaires sur 
 * toutes les pages, ou bien sur un grand nombre de pages,  
 * Ces fonctions sont communes à tous les sites (Gsell, Bagages) 
 */

/** fonctions d'initialisation appellées après le chargement du DOM  **/
jQuery(function() {

	

/** Messages d'erreur lors des validation des formulaires (utilisation de validation.js) **/
Validation.addAllThese([
                       	['required', Translator.translate('formulaire.champ.absent'), 
                     		function(v) {
                     			return !Validation.get('IsEmpty').test(v);
                     		}
                     	],
            			//['required-email', 'Veuillez saisir votre adresse email (ex:jean-pierre.dupond@gsell.fr)', 
                     	['required-email', Translator.translate('newsletter.email.absent'), 
                    		function(v) {
                    			return !Validation.get('IsEmpty').test(v);
                    		}
                    	],
            			//['validate-email', 'Veuillez saisir un email valide (ex:fred@domain.com)', 
                    	['validate-email', Translator.translate('newsletter.email.format'), 
                    		function (v) {
	                    		if(v != null){
	//                				var re = new RegExp("[àéèùç]");
	//                    			if(v.match(re) != null){
	//                    				return false;
	//                    			}
	                				for(var i=0;i< v.length;i++){
	                					if(v.charCodeAt(i) > 127){
	                						return false;
	                					}
	                				}
	                			}
                    			return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
                    		}
                    	],
                		['validate-password', 'Votre mot de passe doit être de plus de 5 caractères et ne peut pas être le même que votre nom', {
                			minLength : 6,
                			notOneOf : ['password','PASSWORD','1234567','0123456'],
                			notEqualToField : 'nom'
                		}],
                		['validate-password-confirm', 'Your confirmation password does not match your first password, please try again.', {
                			equalToField : 'password'
                		}],
            			//['required-telephone', Translator.translate('compteClient.valid.telephone'), function(value){
                		['required-telephone', 'Veuillez saisir au moins un numéro de téléphone domicile ou portable', function(value){
                			return (!Validation.get('IsEmpty').test(jQuery("#telDomicile").val()) ||
                					!Validation.get('IsEmpty').test(jQuery("#telPortable").val()));
                		}],
                		['validate-telephone', 'Veuillez saisir un numéro de téléphone valide', 
                			function(v) {
                				var isValid = true;
                				if (jQuery("#codePays").val() == 'FR') {		
                					isValid =  Validation.get('IsEmpty').test(v) || /^0\d{9}$/.test(v);
                				} else {
                					isValid =  Validation.get('IsEmpty').test(v) || !isNaN(v);
                				}
                				return isValid;
                			}
                		],
                		['validate-telephone-portable', 'Veuillez saisir un numéro de téléphone portable valide', 
                			function(v) {
                				var isValid = true;
                				if (jQuery("#codePays").val() == 'FR') {
                					isValid =  Validation.get('IsEmpty').test(v) || (/^0(6|7)\d{8}$/.test(v) && !(/^0(6|7)(0{8}|1{8}|2{8}|3{8}|4{8}|5{8}|6{8}|7{8}|8{8}|9{8}|12345678)$/.test(v)));
                				} else {
                					isValid = Validation.get('IsEmpty').test(v) || !isNaN(v);
                				}
                				
                				return isValid;
                			}
                		],
            			//['validate-number', Translator.translate('compteClient.valid.nombre'), function(v) {
            			['validate-number', 'Entrez s\'il vous plaît un nombre valable.', function(v) {
            				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
            			}],
    					[ 'required-numCarte',
    					  Translator.translate('paiement.numcarte.obligatoire'),
    							function(v) {
    								return !Validation.get('IsEmpty').test(v);
    							} ],
    					[ 'validate-numberCarte',
    					  Translator.translate('paiement.numcarte.enchiffres'),
    							function(v) {
    								return !isNaN(v);
    							} ],
    					[ 'validate-numCart-type',
    							Translator.translate('paiement.invalid.numcarte'),
    							function(v) {
    								switch (jQuery("#typeCarte").val()) {
    								case 'VISA':
    									return v.length == 13 || v.length == 16;
    								case 'MasterCard':
    									return v.length == 16;
    								case 'American Express':
    									return v.length == 15;
    								case 'Aurore':
    									return v.length <= 19;
    								}
    							} ],
    					[ 'required-cryptogramme',
    					  Translator.translate('paiement.codesecurite.obligatoire'),
    							function(v) {
    								switch (jQuery("#typeCarte").val()) {
    								case 'VISA':
    								case 'MasterCard':
    								case 'American Express':
    									return !Validation.get('IsEmpty').test(v);
    								default:
    									return true;
    								}
    							} ],
    					[ 'validate-cryptogramme',
    							Translator.translate('paiement.invalid.codesecurite'),
    							function(v) {
    								switch (jQuery("#typeCarte").val()) {
    								case 'VISA':
    								case 'MasterCard':
    									return v.length == 3;
    								case 'American Express':
    									return v.length == 4;
    								default:
    									return true;
    								}
    							} ],
    					[ 'validate-dateNaissance',
    							Translator.translate('paiement.invalid.datenaissance'),
    							function(v) {
    								switch (jQuery("#typeCarte").val()) {
    								case 'Aurore':
    									return Validation
    											.get('validate-date-au')
    											.test(
    													jQuery("#dateNaissanceJour").val()
    															+ "/"
    															+ jQuery("#dateNaissanceMois").val()
    															+ "/"
    															+ jQuery("#dateNaissanceAnnee").val());
    								default:
    									return true;
    								}
    							} ]
                    ]);

});



/**
 * Objet javascript ArticleAffichage : utilisé dans les vignettes produit, la page produit
 * et qui permet de gérer le changement de couleur, l'ajout au panier, etc ...
 */
var ArticleAffichage = function(namespace, json, urlServeurStatic) {
    	
	jQuery.extend(this, json);
    	
	this.namespace = namespace;       
	this.urlServeurStatic = urlServeurStatic;
	this.lot = "";
	this.urlArticleLot = "";
       
	if (this.listeCouleursJSON && this.listeCouleursJSON.length > 0) {
	this.numCouleurSelected = this.listeCouleursJSON[0].numCouleur;
	}
       
	this.numDetailSelected = 0; // -1 : 369 // 0 : imageMoyenne // 1 : detail1 // 2 : detail2 // etc ...
	this.isinitilized360 = false;
	this.initilize360running = false;
       
	if (true) { // TODO : if loupe
		//this.loupe = loupe;
    	   
	
    	   
		// on est sur une page produit, et c'est l'article principal :
		// on sélectionne la couleur définie dans l'ancre de l'URL
		ancre = document.location.hash;
		ancre = ancre.substring(1,ancre.length);
		for(var i = 0; i < this.listeCouleursJSON.length; i++) {
			articleCouleurJson = this.listeCouleursJSON[i];
			if (ancre.charAt(0) == 'f') {
				numCouleurMere = ancre.substring(1, ancre.length);
				if (articleCouleurJson.numCouleurMere == numCouleurMere) {
					this.changeCouleur(articleCouleurJson.numCouleur);
					break;
				}
			} else {
				codeCouleur = ancre;
				if (articleCouleurJson.codeCouleur == codeCouleur) {
					this.changeCouleur(articleCouleurJson.numCouleur);
					break;
				}
			}
		}
	}
}

ArticleAffichage.prototype.init360 = function() {

    	if (this.initilize360running) {
    		return;
    	}

    	this.initilize360running=true;

    	// on sélectionne la couleur à utiliser dans le nom de l'image
    	var couleur = "";
		var couleurSelected = this.getCouleurSelected();
		if (couleurSelected.image360) { 
			couleur = "~" + couleurSelected.codeCouleur;
		}

		if(this.isinitilized360 == true && jQuery("#moyenImage_"+this.num).size() > 0) {
			// on teste si on change de couleur sur le 360, si c'est le cas on le détruit avant de la reconstruire avec la bonne couleur
			var img = jQuery("#moyenImage_"+this.num).attr("src");
			expr = this.urlServeurStatic + "/images/imftp/article/360/" + this.reference + couleur +"-[0-9]{1,2}.jpg";
			if (img.match(expr) == null) {
				this.destruct360();
			}
    	}

		//on initialise le 360 si il ne l'est pas déjà
		if(this.isinitilized360 == false) {
			
    		this.numDetailSelected = -1;
    		
    		var images = new Array();
    		for(var i=0; i<16; i++) {
    			images[i] = this.urlServeurStatic + "/images/imftp/article/360/" + this.reference + couleur + "-"  + i + ".jpg";
    		}
    		jQuery("#container360").threesixty({images: images, method: 'mousemove', sensibility: 1, cycle: 2, direction: 'backward'});
    		jQuery(".image_produit").append('<div class="threesixtyEnabled"></div>');	

    		this.isinitilized360=true;
    	}
		
		jQuery("#container360").show().parent().show(); // on affiche le 360
		jQuery(".MagicZoomPlus").hide(); // et on cache le zoom
		
    	this.initilize360running=false;
    	
    }

/*
 * Destruction du plugin 360
 */
ArticleAffichage.prototype.destruct360 = function() {
		if (this.isinitilized360 == true) {
			jQuery("#container360").unwrap(); // parce que chaque appelle à threesixty englobe #container360 dans un div
			jQuery(".threesixtyEnabled").remove(); // graphisme des flèches sous le 360
			this.isinitilized360=false;
		}
    }



ArticleAffichage.prototype.changeCouleur = function(numCouleur) {
	this.numCouleurSelected = numCouleur;
	this.changeCouleurUI();
}

ArticleAffichage.prototype.changeCouleurUI = function() { alerteSurcharge(); }

ArticleAffichage.prototype.getCouleurSelected = function() {
	if (this.listeCouleursJSON) {
		for(var i=0;i<this.listeCouleursJSON.length;i++){
			if (this.numCouleurSelected==this.listeCouleursJSON[i].numCouleur) {
				return this.listeCouleursJSON[i];
			}
		}
	}
	return null;
}

/*
 * Change la vue principale sur la fiche produit
 * suite à un changement de couleur
 * concerve la vignette sélectionnée
 */
ArticleAffichage.prototype.changePhotosDetail = function(numDetail) {
	
	var selectedCouleur = this.getCouleurSelected();

	this.numDetailSelected = numDetail;
	
	if (this.numDetailSelected == -1) {
		this.init360();
	} else {
		this.destruct360();
		
		var imageMoyenne, imageGrande;
		
		if (this.numDetailSelected == 0){
			imageMoyenne = "moyenne/" + selectedCouleur.imageMoyenne;
			imageGrande = "grande/" +selectedCouleur.imageGrande;
		}else if (this.numDetailSelected == 1) {
			imageMoyenne = "detailZ/" + selectedCouleur.imageD1Zoom;
			imageGrande = "detailZ/" + selectedCouleur.imageD1Zoom;
		}else if (this.numDetailSelected == 2){
			imageMoyenne = "detailZ/" + selectedCouleur.imageD2Zoom;
			imageGrande = "detailZ/" + selectedCouleur.imageD2Zoom;
		}else if (this.numDetailSelected == 3){
			imageMoyenne = "detailZ/" + selectedCouleur.imageD3Zoom;
			imageGrande = "detailZ/" + selectedCouleur.imageD3Zoom;
		}else if (this.numDetailSelected == 4){
			imageMoyenne = "detailZ/" + selectedCouleur.imageD4Zoom;
			imageGrande = "detailZ/" + selectedCouleur.imageD4Zoom;
		}else if (this.numDetailSelected == 5){
			imageMoyenne = "detailZ/" + selectedCouleur.imageD5Zoom;
			imageGrande = "detailZ/" + selectedCouleur.imageD5Zoom;
		}

		// vu principale sur la fiche produit
		jQuery("#moyenImage_" + this.num).attr("src", this.urlServeurStatic + '/images/imftp/article/' + imageMoyenne);
		jQuery("#zoom1").attr("href", this.urlServeurStatic + '/images/imftp/article/' + imageGrande);
		// Mise à jour du zoom
		try {
			MagicZoomPlus.refresh();
		} catch(e) {}
		
		// sur la vue quickview (bagages)
		jQuery("#quickimg_" + this.num).attr("src", this.urlServeurStatic + '/images/imftp/article/' + imageMoyenne);

	}
	
}

ArticleAffichage.prototype.ajoutePanier = function() {
	
	var originalArticleAffichage = this;
	
	var data = "Destination=ajoutArticle&oldcouleur=0&addcross=0" +
				"&numa=" + this.num +
				"&couleur=" + this.numCouleurSelected +
				"&qte=1" +
				"&lot=" + this.lot +
				"&affichage=page" +
				"&urlArticleLot=" + this.urlArticleLot;
		
	jQuery.post("/maroquinerie_valise_bagages_sac.gnc", data, function(data, textStatus, jqXHR) {
		originalArticleAffichage.successAjoutePanier(data);
	});

}

ArticleAffichage.prototype.successAjoutePanier = function(transport) { alert(Translator.translate('methode.surcharge')); }

ArticleAffichage.prototype.ajouteComparateur = function() {
	
	if (jQuery("#layer_comparateur").size() > 0) {
		jQuery.get(
			"/catComparateur.do",
			"method=ajoute&numa=" + this.num + "&affichage=layer&num1=&num2=&num3=&num4",
			function(data, textStatus, jqXHR) {
				jQuery("#layer_comparateur").html(data);
				if(jQuery("#alerte").html() != "") {
					afficheAlert(jQuery("#alerte").html());
				}
				jQuery("#layer_comparateur").show();
			}
		);
	} else {
		doPost({method : 'ajoute', numa : this.num, affichage : 'page'},'catComparateur.do');
	}
	
}

ArticleAffichage.prototype.supprimeComparateur = function(typeSuppression) {
		
	if ( confirm( Translator.translate('comparateur.suppression.confirm') ) )	{
		
		if(typeSuppression == 0) {
			doPost({method : 'supprime', numa : this.num,  affichage : 'page', vider : 'false'},'catComparateur.do');
		} else {
			jQuery.post(
				"/catComparateur.do",
				"method=supprime&numa=" + this.num + "&vider=false" +"&affichage=layer",
				function(data, textStatus, jqXHR) {
					setTimeout(comparateur, 4000);
					setTimeout(function() {
						jQuery("#layer_comparateur").html(data);
					}, 1000);
				}
			);
		}
	}
}

ArticleAffichage.prototype.afficherListesAchat = function (clientId, options) {
		
	var num = this.num;
	var namespace = this.namespace;
	if (clientId > 0) {	
		jQuery.post(
			"/maroquinerie_valise_bagages_sac.gnc",
			"Destination=afficherListesAchat&ajaxlogin=true&articleJS="+namespace,
			function(data, textStatus, jqXHR) {
				
				// client identifie, on affiche le layer avec la liste des listes d'achat
				jQuery("#layer_liste_achats_" + num + " .listes").html(data);
				
				showElement('layer_liste_achats_' + num);
				showElement('creer_liste');
				showElement('message_choix');
				showElement('layer_liste_achats');
			}
		);
	} else {
		showElement("layer_login_article");
		var artnum = null;
		var popuptarget = 'afficherListesAchat';
		if(options){
			artnum = options['artnum'];
			popuptarget += '--'+artnum;
		}
		jQuery('#popupTarget').val(popuptarget);
	}
}

ArticleAffichage.prototype.ajouterListeAchat = function() {
	jQuery('#layer_liste_achats_' + this.num + ' .listes').load("/maroquinerie_valise_bagages_sac.gnc?Destination=createListeAchatAjax&articleJS="+this.namespace);
}

ArticleAffichage.prototype.ajoutArticleListeAchat = function(numListe) {
	var num = this.num;
	var namespace = this.namespace;
	
	jQuery.get(
		"/maroquinerie_valise_bagages_sac.gnc",
		"Destination=ajoutArticleListeAchat&ajaxlogin=true" + "&numArticle=" + this.num + "&numCouleur=" + this.numCouleurSelected + "&numListe=" + numListe + "&articleJS="+namespace,
		function(response) {
			if(response.length > 200) { //cas de l'article correctement ajoute
				hideElement('layer_liste_achats_' + num);
				afficheAlert(Translator.translate('article.ajoute.selection.ok'));
			} else { // cas de l'article deja ajoute
				jQuery('#layer_liste_achats_' + num + ' .listes').html(response);
				hideElement('creer_liste');
				hideElement('message_choix');
				afficheAlert(Translator.translate('article.deja.ajoute.selection'));
			}
		}
	);
}

ArticleAffichage.prototype.alerteBaissePrix = function(clientId, options) {
	var num = this.num;
	
	if (clientId > 0) {
		jQuery.get(
			"/maroquinerie_valise_bagages_sac.gnc",
			"Destination=alerteBaissePrix&ajaxlogin=true" + "&numArticle=" + num + "&numCouleur=" + this.numCouleurSelected + "&prixInitial=" + this.prixApplicable,
			function(response) {
				showElement('layer_baisse_prix_' + num)
			}
		);
	} else {
		showElement('layer_login_article');
		var artnum = null;
		var popuptarget = 'alerteBaissePrix';
		if(options){
			artnum = options['artnum'];
			popuptarget += '--'+artnum;
		}
		jQuery('#popupTarget').val(popuptarget);
	}
}

ArticleAffichage.prototype.quickview = function() {
	var url = '/maroquinerie_valise_bagages_sac.gnc?Destination=affQuickLookArticle&numa=' + this.num;
	if (this.getCouleurSelected()) {
		url = url + '&couleur=' + this.getCouleurSelected().codeCouleur;
	}
	jQuery.get(
		url,
		function(response) {
			successLayer(response, 'quickview');
		}
	);
}

ArticleAffichage.prototype.afficheLayerEnvoyerAmi = function() {
	jQuery.get(
		"/maroquinerie_valise_bagages_sac.gnc?Destination=affPageAmi&numa=" + this.num,
		function(response) {
			successLayer(response, 'envoyerami');
		}
	);
}

ArticleAffichage.prototype.layerZoom = function() {
	var url = '/maroquinerie_valise_bagages_sac.gnc?Destination=affImagesArticle&numa=' + this.num;
	if (this.getCouleurSelected()) {
		url = url + '&type=gd&requestedColor=' + this.getCouleurSelected().codeCouleur;
	}
	jQuery.get(
		url,
		function(response) {
			successLayer(response, 'zoom');
    	}
	);
}


/** fonction générique soumet le formulaire de recherche qu'on peut trouver sur de nombreuses pages  **/
function rechercher(formName){
	
	if (formName == null) {
		formName = "frecherche";
	}
	var objform = document.forms[formName];
	
	var valeurMarque = objform.marque.value;
	
	if(valeurMarque.indexOf("M")!=-1){
		objform.numm.value = valeurMarque.substring(1,valeurMarque.length) ;
		objform.numl.value = "";
	}else if(valeurMarque.indexOf("L")!=-1){
		objform.numl.value = valeurMarque.substring(1,valeurMarque.length);
		objform.numm.value = "";
	}else if(valeurMarque.indexOf("T")!=-1){
		objform.numl.value = "";
		objform.numm.value = "";
	}else{
		objform.numl.value = "";
		objform.numm.value = "";
	}
	
	var valeurrayon =  objform.rayon.value;
	if(valeurrayon.indexOf("R")!=-1){
		objform.numr.value = valeurrayon.substring(1,valeurrayon.length) ;
		objform.numf.value = "";
		objform.numsf.value = "";
	}else if(valeurrayon.indexOf("F")!=-1){
		objform.numf.value = valeurrayon.substring(1,valeurrayon.length);
		objform.numr.value = "";
		objform.numsf.value = "";
	}else if(valeurrayon.indexOf("S")!=-1){
		objform.numr.value = "";
		objform.numf.value = "";
		objform.numsf.value = valeurrayon.substring(1,valeurrayon.length);
	}else{
		objform.numsf.value = "";
		objform.numr.value = "";
		objform.numf.value = "";
	}	
	if(objform.texte.value == objform.texte.defaultValue){
		objform.texte.value="";
	}
	objform.isRechercheAvancee.value = false;
	objform.submit();
	return false;
}






  /********************************/
 /* ANCIENNEMENT jsdyn/site_g.js */
/********************************/

/**
 * Ouverture d'une popup sans décoration
 */ 
function openPop(url, nom, largeur, hauteur) {
  newWindow = open(url, nom, "width="+largeur+",height="+hauteur+",toolbar=no,scrollbars=no,resizable=no,titlebar=yes")
  newWindow.moveTo( (parseInt(screen.width)-largeur)/2 ,(parseInt(screen.height)-hauteur)/2 );
  newWindow.focus();
}

/**
 * Ouverture d'une popup avec scroll bars
 */ 
function openPopScroll(url, nom, largeur, hauteur) {
  newWindow = open(url, nom, "width="+largeur+",height="+hauteur+",toolbar=no,scrollbars=yes,resizable=yes,menubar=no,location=no,status=no,titlebar=no");
  newWindow.moveTo( (parseInt(screen.width)-largeur)/2 ,(parseInt(screen.height)-hauteur)/2 );
  newWindow.focus();
}

/**
 * Ouverture d'une popup avec scroll bars et une barre d'outil
 */ 
function openPopScrollToolbar(url, nom, largeur, hauteur) {
  newWindow = open(url, nom, "width="+largeur+",height="+hauteur+",toolbar=yes,scrollbars=yes,resizable=yes,titlebar=yes")
  newWindow.moveTo( (parseInt(screen.width)-largeur)/2 ,(parseInt(screen.height)-hauteur)/2 );
  newWindow.focus();
}

/**
 * Popups GénieCube
 */ 
function imgPopup(nomPop,img,fond,txt,css){
   imgPop = window.open("",nomPop,"scrollbars=yes,width=700,height=550");
   imgPop.document.write("<html>\n\n");
   imgPop.document.write("<head><title>" + Translator.translate('image.voir')+ "</title></head>\n\n");
   imgPop.document.write("<body bgcolor=\""+fond+"\">\n");
   imgPop.document.write("  <table border=\"0\" cellpadding=\"0\" cellspacing=\"2\" width=\"100%\">\n");
   imgPop.document.write("    <tr><td align=\"center\"><img src=\"ressources/"+img+"\"></td></tr>\n");
   imgPop.document.write("    <tr><td align=\"center\">\n");
   imgPop.document.write("      <table border=\"0\" cellpadding=\"0\" cellspacing=\"2\">\n");
   imgPop.document.write("        <tr><td><span style=\""+css+"\">"+txt+"</span></td></tr>\n");
   imgPop.document.write("      </table>\n");
   imgPop.document.write("    </td></tr>\n");
   imgPop.document.write("  </table>\n");
   imgPop.document.write("</body>\n\n");
   imgPop.document.write("</html>");
}


// fonction modifiée pour prendre en compte la génération des pages dans un sous répertoire
function popup(adr,nompop,larg,haut,res){
  window.open("maroquinerie_valise_bagages_sac.gnc?Destination=affGCAutrePopup&key="+adr,nompop,'width='+larg+',height='+haut+',scrollbars=1,toolbar=0,location=0,status=0,menubar=0,resizable='+res);
}


function is_VariableImg(nom){
	if(typeof(eval("window."+nom))=="object"){
		return eval("window."+nom);
	}
	return false;
}





function getOffsetLeft(elementReference, decalage){
	//alert(document.getElementById(elementReference).offsetLeft);
	return parseInt(document.getElementById(elementReference).offsetLeft) + decalage;
}

//fin fonction valide()
function validerRechercheHome(){
	var objform = document.forms.frecherche;
	var valeurMarque = objform.marque.value;
	
	if(valeurMarque.indexOf("M")!=-1){
		objform.numm.value = valeurMarque.substring(1,valeurMarque.length) ;
		objform.numl.value = "";
	}else if(valeurMarque.indexOf("L")!=-1){
		objform.numl.value = valeurMarque.substring(1,valeurMarque.length);
		objform.numm.value = "";
	}else if(valeurMarque.indexOf("T")!=-1){
		objform.numl.value = "";
		objform.numm.value = "";
	}else{
		objform.numl.value = "";
		objform.numm.value = "";
	}
	
	var valeurrayon =  objform.rayon.value;
	if(valeurrayon.indexOf("R")!=-1){
		objform.numr.value = valeurrayon.substring(1,valeurrayon.length) ;
		objform.numf.value = "";
		objform.numsf.value = "";
	}else if(valeurrayon.indexOf("F")!=-1){
		objform.numf.value = valeurrayon.substring(1,valeurrayon.length);
		objform.numr.value = "";
		objform.numsf.value = "";
	}else if(valeurrayon.indexOf("S")!=-1){
		objform.numr.value = "";
		objform.numf.value = "";
		objform.numsf.value = valeurrayon.substring(1,valeurrayon.length);
	}else{
		objform.numsf.value = "";
		objform.numr.value = "";
		objform.numf.value = "";
	}	
		
	if((objform.texte.value).indexOf("l'aide d'un mot cl")!=-1){
		objform.texte.value="";
	}
	objform.isRechercheAvancee.value = false;
	objform.submit()
}

function validerRechercheAvancee(){
	var objform = document.forms.frecherche;
	objform.isRechercheAvancee.value = true;
	if((objform.texte.value).indexOf("l'aide d'un mot cl")!=-1){
		objform.texte.value="";
	}
	objform.submit()
}

function validerechercheSinple(){
document.forms.formrecherchetext.submit();
}


function favoris() { 
      if ( navigator.appName != 'Microsoft Internet Explorer' ){ 
          window.sidebar.addPanel(Translator.translate('favoris.titre'),"http://www.gsell.fr/",""); 
      } 
      else { 
          window.external.AddFavorite("http://www.gsell.fr/",Translator.translate('favoris.titre')); 
      } 
} 

function initImput(objInput){
	if(objInput.value==""){
		objInput.value=objInput.defaultValue;
	}
}

/*
 * TODO evol: si non utilisé supprimer
 */
function fermerElement(nom){
	jQuery("#nom").hide();
}
dmcUtils = new Object();
dmcUtils.getBody = function (){
		return (!window.opera && document.compatMode && document.compatMode!="BackCompat") ? document.documentElement:document.body;
};
function getEcranX(){
	
	if (dmcUtils.getBody().clientWidth){
		return parseInt(dmcUtils.getBody().clientWidth);
	}else if (window.innerWidth != null){
		return parseInt(window.innerWidth);
	}
	return (0);
}

function getEcranY(){
	if (window.innerHeight != null){
		return parseInt(window.innerHeight);
	}
	if (dmcUtils.getBody().clientHeight != null){
		return parseInt(dmcUtils.getBody().clientHeight);
	}
	return (0);
}

function setOpacity (objet,valeur) {
if(objet==null || valeur==null){return };
 if(valeur < 0.00001) valeur = 0;
  if(objet.attachEvent){
	objet.style.filter = objet.style.filter.replace(/alpha\([^\)]*\)/gi,'') + 'alpha(opacity='+valeur*100+')';
  }
objet.style["opacity"] = valeur;
};
	
function centreElement(ele){
		
	if(ele){
		var posyy=(dmcUtils.getBody().scrollTop != undefined)?  parseInt(dmcUtils.getBody().scrollTop) : window.pageYOffset;
			var posx=((getEcranX()-parseInt(ele.clientWidth))/2);
			
			var posy=(Number((getEcranY()-parseInt(ele.clientHeight))/2)+posyy);
			ele.style.left=posx+"px";
			ele.style.top=(posy<=0)? "0px" : posy+"px";
		
	}
}


function changeResultats(){
	document.form1.Destination.value = "changeResultats";
	document.form1.submit();
}









/* 0 occurrence dans le projet */
function sleep(time){
   d=new Date();
   diff=0;
    while(diff < time)
    {
      n=new Date();
      diff=n-d;
     } 
}



/**********************************************************************************************/
/**********************************************************************************************/
/*-------------------- Fonctions de transfert entre 2 listes multiples -----------------------*/
 
 var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

 function addOption(theSel, theText, theValue) {
   var newOpt = new Option(theText, theValue);
   var selLength = theSel.length;
   theSel.options[selLength] = newOpt;
 }

 function deleteOption(theSel, theIndex) { 
   var selLength = theSel.length;
   if(selLength>0) {
     theSel.options[theIndex] = null;
   }
 }

 function moveOptions(theSelFrom, theSelTo) {
   
   var selLength = theSelFrom.length;
   var selectedText = new Array();
   var selectedValues = new Array();
   var selectedCount = 0;
   
   var i;
   
   // Find the selected Options in reverse order
   // and delete them from the 'from' Select.
   for(i=selLength-1; i>=0; i--) {
     if(theSelFrom.options[i].selected) {
       selectedText[selectedCount] = theSelFrom.options[i].text;
       selectedValues[selectedCount] = theSelFrom.options[i].value;
       deleteOption(theSelFrom, i);
       selectedCount++;
     }
   }
   
   // Add the selected text/values in reverse order.
   // This will add the Options to the 'to' Select
   // in the same order as they were in the 'from' Select.
   for(i=selectedCount-1; i>=0; i--) {
     addOption(theSelTo, selectedText[i], selectedValues[i]);
   }
   
   updateBoutons(document.form_centres_interet.all_marques, document.form_centres_interet.marques_ci)
   
   if(NS4) history.go(0);
 }
 
 //pour les boutons "ajouter toutes les marques" et "supprimer ma liste"
 function transfertTotal(theSelFrom, theSelTo) {
   
   var selLength = theSelFrom.length;
   var selectedText = new Array();
   var selectedValues = new Array();
   var selectedCount = 0;
   
   var i;
   
   for(i=selLength-1; i>=0; i--) {     
       selectedText[selectedCount] = theSelFrom.options[i].text;
       selectedValues[selectedCount] = theSelFrom.options[i].value;
       deleteOption(theSelFrom, i);
       selectedCount++;
   }

   for(i=selectedCount-1; i>=0; i--) {
     addOption(theSelTo, selectedText[i], selectedValues[i]);
   }
   
   updateBoutons(document.form_centres_interet.all_marques, document.form_centres_interet.marques_ci);
   if(NS4) history.go(0);
 }
 
 //supprime les marques centres d'interet de la liste de toutes les marques
 function initialiserToutesMarques(listeToutesMarques, listeCentresInteret) {

	 var ciLength = listeCentresInteret.length;
	 var marquesLength = listeToutesMarques.length;

	 var i, j;

	 for(i=ciLength-1; i>=0; i--) {
		 for(j=marquesLength-1; j>=0; j--) {  
			 if(listeToutesMarques.options[j].value==listeCentresInteret.options[i].value)  {
				 deleteOption(listeToutesMarques, j);
				 marquesLength--;
			 }
		 }
	 }
	 updateBoutons(listeToutesMarques, listeCentresInteret);
	 if(NS4) history.go(0);
 }
 
 
/*
 * Compte premium, centres d'intêret : état des boutons (enabled ou disabled)
 */ 
function updateBoutons(listeToutesMarques, listeCentresInteret) {

	var ciLength = listeCentresInteret.length;
	var marquesLength = listeToutesMarques.length;

	if(ciLength > 0) {
		jQuery("#supp_liste").removeClass();
	} else {
		jQuery("#supp_liste").addClass("noslected");
	}
	
	if(marquesLength > 0) {
		jQuery("#ajout_liste").removeClass();
	} else {
		jQuery("#ajout_liste").addClass("noslected");
	}

}
 
 
 //selectionne tous les centres d'interet avant le submit
 function selectCentresInterets(listeCentresInteret) {

	 var ciLength = listeCentresInteret.length;
	 var i;

	 for(i=ciLength-1; i>=0; i--) {
		 listeCentresInteret.options[i].selected = true;
	 }
 }
 
 /**********************************************************************************************/
 /**********************************************************************************************/
 /**********************************************************************************************/

