if(console === undefined) {
	var console = {
		log: function() {
			
		}
	};
}

/**
* The PC By Surcouf main Application.
* The Site object init the different components that
* are used in the website by invoquing its start function
* on the DOMReady event.
* 
* The Site object also contains some method that are related tof
* the entire application such as freezing options.
*/
var Site = {
	/**
	 * Invoqued by the DOMReady Event.
	 * Initialise the differents components used
	 * in the website. By convention, each component
	 * is initialised by calling its init method.
	 * The init methods register the required event and
	 * set the interface on a inative state.
	 */
	start: function(){
    Accordion.init();
		
		$("#selection-slide a.previous, #services-slide a.previous").click(Accordion.previous);
		$("#selection-slide a.next, #services-slide a.next").click(Accordion.next);
	
        if ($('#PC-selection').hasClass('configurator')){
            CustomFields.init('radio', '#PC-selection', CustomFields.onChange);
            CustomFields.init('checkbox', '#PC-selection', CustomFields.onChange);
        }
        else{
            CustomFields.init('radio', '#PC-selection', AssociatedQuantity.open);
            CustomFields.init('checkbox', '#PC-selection', AssociatedQuantity.open);
        }
        
        if($('#form_newsletter').size() > 0)
            CustomFields.init('checkbox', '#form_newsletter', CustomFields.onChange);
        else
            CustomFields.init('checkbox', '.form', null, '#av-activation');
      
		CustomFields.init('radio', '.form', null, '.cart-avantage-confirm');
		CustomFields.init('radio', '#cart-avantage-popin', AvantagesActivation.toggle);
		CustomFields.init('checkbox', '#command-list h2 fieldset');
		
		CustomFields.init('checkbox', '#shoppingbag', null, '#av-activation');
		//A REVOIR	
		//CustomFields.init('checkbox', '.form', null, '#av-activation');
		
		CustomFields.init('checkbox', '.cartcell.avantages', AvantagesActivation.open);
		
		CustomFields.init('select', '.form', null, ".changeVisual");
		CustomFields.init('select', '#PC-selection');
		CustomFields.init('select', '#multi-select-card', DisplaySelectedCard.open);


        // on initialise l'objet CreationProfil que dans le cas ou le formulaire a "form-register" comme nom
        if ($("form").attr('name') == "form-register")
            CreationProfil.init();
    
		AssociatedQuantity.init();
		Login.init();
		Panier.init();
		ChoixAdressesCMD.init();
    Paiement.init();
    ConfirmCMD.init();
		Configurator.init();
		MainNavigation.init();
		BubbleTips.init();
		QuantityField.init();
		CartDetail.init();
		MiniCart.init();
		if ($("form.withvalidation").size()>0) FormValidation.init();
		ListeSegment.init();
		WishList.init();
		AddressForm.init();
		AvantagesForm.init();
		FoldableContent.init();
		if ($("ul.accordion-like").size()>0) AccordionNavigation.init();
		// implementation examples
		Cart.init();
		CgvAcceptation.init();
	},
	
	testRadio: function(){alert("onChange")},
	
	/**
	 * Create a freeze layer and make it appear.
	 * The freeze layer catch every mouse action on the application
	 * preventing user to fire multiple event at the same time.
	 * Visually, the freeze layer is a black semi opaque veil that cover
	 * the entire application
	 */
	createFreeze:function(){
		$("#freeze").height(document.documentElement.scrollHeight);
		$("#freeze").show();
		$("#freeze").unbind();
		$("#freeze").removeClass("hidden");
		$("#freeze").click(function(){});
		return $("#freeze")
	},
	
	/**
	 * Destroy the freeze layer that is currently on stage
	 */
	destroyFreeze:function(){
		$("#freeze").hide();
		$("#freeze").addClass("hidden");
		$("#freeze").unbind();
	},
	
	/**
	 * Make the application loader to appear
	 */
	showLoader:function(){
		Site.createFreeze();
		$("#loader").removeClass("hidden");
	},
	
	/**
	 * Make the application loader to dissappear
	 */
	hideLoader:function(){
		Site.destroyFreeze();
		$("#loader").addClass("hidden");
	}
};

/**
 * <p>
 * The FormValidation Object is used to validate forms before its submission.
 * The FormValidation will be activated for every form
 * that has the "withvalidation" class on it.
 * </p>
 * 
 * <p>
 * Each field is checked with a specific rules specified in the non-regular "validation" attribute,
 * for instance :
 * <input type="text" validation="required" />
 * </p>
 * 
 * <p>
 * the different rules and associated error messages are stored in two objects : errorMsg and functions.
 * Some differents validations keyword may have the same rule but different error message. for example, the
 * required and emailrequired validation type may use the "isRequired" rule, but the emailrequired associated
 * message will be more specific (ie: "mandatory field" versus "You must type in your email address".
 * </p>
 * 
 * <p>
 * Many validation type can be used on the same field. Each rule will be tested in the order they are given,
 * the first that isn't correct will fire the error message. This is oviousely usefull to fire different error
 * message for the same field validation.
 * </p>
 * 
 * <p>
 * For instance : <br />
 * We have a email input, and an isEmail rules that match the field content with a regex pattern.
 * <input type="text" validation="email" />
 * The associated error message might be "your email address isn't correct".
 * But this message will also be fired if the field is blank. We can use two rules to
 * previously check that the field isn't blank before matching the regex pattern, doing :
 * <input type="text" validation="required email" />
 * This will fire the "mandatory field" error message if the field is blank. If the first rules is verified, then
 * the second one is checked, etc...
 * </p>
 */
var FormValidation = {
	
	errorMsg:undefined,
	functions:undefined,
	retourPage:"",
	
	/**
	 * The init function register the onSubmit event on every form.withvalidation DOM elements
	 * and initialise both functions and errorMsg configuration objects.
	 */
	init:function() {
	
		if ($("form#form-identification").size()>0 )
			if ($("#MsgInfosPersos").val() != "")
				System.alert($("#MsgInfosPersos").val(), null, null);

		$("form.withvalidation").submit(FormValidation.validate);
		
		/**
		 * The associated error messages
		 */
		FormValidation.errorMsg = {
			'required':'Champs obligatoire',
			'numeric':'Champs numérique',
			'postcode':"Le code postal n'est pas valide",
			'notDomTom':"Attention, la livraison n'est possible qu'en France métropolitaine, Corse et Monaco.",
			'pattern':"pattern incorrect",
			'date':"La date n'est pas correcte",
			'email':"L'email n'est pas correct",
			'passwordEqual':"La confirmation du mot de passe est incorrecte. Veuillez entrer de nouveau votre mot de passe.",
			'passwordTaille':"Mot de passe trop court (6 caractères minimum)", 
			'newEmailCompteSurcouf':"L'e-mail que vous avez choisi est déjà utilisé. Veuillez choisir un autre e-mail.",
			'newEmailCompteSurcoufModif':"L'e-mail que vous avez choisi est déjà utilisé Veuillez choisir un autre e-mail.",
			'newEmailGeneral':"L'adresse email que vous avez renseignée est déjà inscrite à nos newsletters. Si vous souhaitez modifier vos préfèrences, merci d'ouvrir un compte sur Surcouf.com",
			'mobile':"Le numéro de mobile est incorrect (il doit comporter 10 chiffres et commencer par 06)",
			'telephone':"Le numéro de téléphone est incorrect (il doit comporter 10 chiffres)",
			'mobileFormat':"Le numéro de mobile est incorrect, merci d'utiliser le champ de saisie 'Fixe' pour les N° ne commençant pas par 06",
			'telephoneFormat':"Le numéro de téléphone est incorrect, merci d'utiliser le champ de saisie 'Mobile' pour les N° commençant par 06.",
			'oldGoodPassword':"Votre ancien mot de passe est incorrect.",
			'oldPasswordEntre':"Vous n'avez pas renseigné l'ancien mot de passe.",
			'newPasswordEntre':"Vous n'avez pas renseigné le nouveau mot de passe.",
			'passwordTailleModif':"Mot de passe trop court (6 caractéres minimum)",
			'recupEmailOK':"L'e-mail saisi n'existe pas dans notre base de données",
			'loginPasswordOK':"L'identification a échoué, veuillez recommencer",
			'selectionNewsletter':"Vous n'avez pas sélectionné de lettres d'informations",
			'newSociete': "Le nom de la société que vous avez choisi est déjà utilisé.",
			'newSocieteModification': "Le nom de la société que vous avez choisi est déjà utilisé.",
			'numericCrypto': "Le cryptogramme visuel de votre carte n'est pas reconnu. Veuillez renouveler la saisie.",
			'cryptoTaille': "Le cryptogramme visuel comprend 3 chiffres",
			'numCBTaille': "Le N° de carte doit comporter 19 chiffres",
			'numericNumCB': "Le numéro de carte que vous venez de saisir n'est pas correct. Merci de le saisir de la manière suivante : 49722001.."
		};
		
		/**
		 * The associated validation rules
		 */
		FormValidation.functions = {
			"required":FormValidation.isRequired,
			"pattern":FormValidation.isPattern,
			"date":FormValidation.isDate,
			"postcode":FormValidation.isPostCode,
			"notDomTom":FormValidation.isNotDomTom,
			"numeric":FormValidation.isnumeric,
			"email":FormValidation.isEmail,
			"passwordEqual":FormValidation.isPasswordEqual,
			"passwordTaille":FormValidation.isPasswordTaille,   
			"newEmailCompteSurcouf":FormValidation.isNewEmailCompteSurcouf,
			"newEmailCompteSurcoufModif":FormValidation.isNewEmailCompteSurcoufModif,
			"newEmailGeneral":FormValidation.isNewEmailGeneral,
			"mobile":FormValidation.isMobile,
			"telephone":FormValidation.isTelephone,
			"mobileFormat":FormValidation.isMobileFormat,
			"telephoneFormat":FormValidation.isTelephoneFormat,
			"oldGoodPassword":FormValidation.isOldGoodPassword,
			"oldPasswordEntre":FormValidation.isOldPasswordEntre,
			"newPasswordEntre":FormValidation.isNewPasswordEntre,
			"passwordTailleModif":FormValidation.isPasswordTailleModif,
			"recupEmailOK":FormValidation.isRecupEmailOK,
			"loginPasswordOK":FormValidation.isLoginPasswordOK,
			"selectionNewsletter":FormValidation.isSelectionNewsletter,
			"newSociete":FormValidation.isNewSociete,
			"newSocieteModification":FormValidation.isNewSocieteModification,
			'numericCrypto': FormValidation.isnumericCrypto,
			'cryptoTaille': FormValidation.isCryptoTaille,
			'numCBTaille': FormValidation.isnumCBTaille,
			'numericNumCB': FormValidation.isnumericNumCB
		};
	},
	
	/**ÃƒÂ 
	 * Invoqued when the onSubmit event is fired.
	 * Execute the validation rules on each field.
	 * @return false if the form isn't correct according to the specified rules, which stop the form submission.
	 */
	validate: function() {
	 	var els = $('input, checkbox, select', this);
		var validForm = true;
		var firstError = null;
		// cas spécial pour les checkbox de la newsletter
		$.each($("span.errorMessage"), function() {
				if($(this).html()=="Vous n'avez pas sélectionné de lettres d'informations"){
				  $(this).remove();
			 }
		});
		
		for (var i=0;i<els.length;i++) {
			var req = els[i].getAttribute('validation');
			if (!req) continue;
			var reqs = req.split(' ');
			if (els[i].getAttribute('pattern'))
				reqs[reqs.length] = 'pattern';
			for (var j=0;j<reqs.length;j++) {
				if (!FormValidation.functions[reqs[j]])
					FormValidation.Functions[reqs[j]] = emptyFunction;
				var OK = FormValidation.functions[reqs[j]](els[i]);	
				if (OK != true) {
					var errorMessage = OK || FormValidation.errorMsg[reqs[j]];
					FormValidation.writeError(els[i],errorMessage)
					validForm = false;
					if (!firstError)
						firstError = els[i];
					break;
				}
			}
		}
		if (validForm) {
		  if($("form#form-register").size()>0){
        if ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape1') == 0){
            CreationProfil.EnregistrerCookiesEtape1();
            Accordion.next();
            return false;
        }
        else if ($(Accordion.currentSubItem).attr("id") == "MenuGaucheEtape2_B2C"){
            CreationProfil.EnregistrerCookiesEtape2_B2C();
            Accordion.next();
            return false;
        }
        else if ($(Accordion.currentSubItem).attr("id") == "MenuGaucheEtape2_B2B"){
            CreationProfil.EnregistrerCookiesEtape2_B2B();
            Accordion.next();
            return false;
        }
        else if ($(Accordion.currentSubItem).attr("id") == "MenuGaucheEtape3_B2C"){
            Site.showLoader();             
            CreationProfil.EnregistrerCookiesEtape3();
            var retour = CreationProfil.CreerCompte_B2C();
            return false;
        }
        else if ($(Accordion.currentSubItem).attr("id") == "MenuGaucheEtape3_B2B"){
            CreationProfil.EnregistrerCookiesEtape3();
            var retour = CreationProfil.CreerCompte_B2B();
            return false;
        }
      }
      else if($("form#form-modifier-B2C").size()>0){
      	ModificationProfil.ModifierCompte_B2C();
      	return false;
      }
      else if($("form#form-modifier-B2B").size()>0){
      	ModificationProfil.ModifierCompte_B2B();
      	return false;
      }
      else if($("form#form-modifier-Newsletter").size()>0){
      	ModificationProfil.ModifierCompte_Newsletter();
      	return false;
      }
      //cas où on est dans la page "identification.aspx" en mode "login"
      else if ($("form#form-identification").size()>0 && this.id == "form-identification"){
          if (FormValidation.retourPage != "")
              FormValidation.retourPage = FormValidation.retourPage.replace(/_XXX_/g,"&");
              // on crée un cookies pour éviter le F5 sur la page de retour vers le configurateur
              if(FormValidation.retourPage.indexOf("configurateur.aspx") > -1 && FormValidation.retourPage.indexOf("act=save") > -1){
                  GestionCookies.SetCookie('tempsave', "1", null, "/");
                  }
              document.location.href = FormValidation.retourPage;
          return false;
      }
      //cas où on est dans la page "identification.aspx" en mode "récupération du mot de passe"
      else if ($("form#form-recupMotDePasse").size()>0 && this.id == "form-recupMotDePasse"){
        //la récupération du mot de passe s'est bien passée, on affiche le layer correspondant
  		  Login.lostPwdConfirm();
        return false;
      }
      else if ($("#add-shipping-form").size()>0 && $("#add-shipping-form").css("display")=="block"){
        // modif ship
        if(AddressForm.currentAddress == undefined){
          AddressForm.CreationAdresseLivraison();
        }
        else{
  		  // modif
  		    AddressForm.ModificationAdresseLivraison();
  		  }
        return false;
      }
       else if ($("#add-payment-form").size()>0 && $("#add-payment-form").css("display")=="block"){
        // modif pay
        if(AddressForm.currentAddress == undefined){
          AddressForm.CreationAdresseFacturation();
        }
        else{
  		  // modif
  		    AddressForm.ModificationAdresseFacturation();
  		  }
        return false;
      }
      else if($("#payment").size()>0){
          if($("#submit").hasClass("cheque")){
            Site.showLoader();
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementNonCarte",
  			      type: "POST",
  			      data:"typeDePaiment=10",
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          else if($("#submit").hasClass("kadeos")){
            Site.showLoader();
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementNonCarte",
  			      type: "POST",
  			      data:"typeDePaiment=11",
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          else if($("#submit").hasClass("administratif")){
            Site.showLoader();
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementNonCarte",
  			      type: "POST",
  			      data:"typeDePaiment=12",
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          else if($("#submit").hasClass("entreprise")){
            Site.showLoader();
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementNonCarte",
  			      type: "POST",
  			      data:"typeDePaiment=21",
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          else if($("#submit").hasClass("cb")){
            Site.showLoader();
            var cryptoValue = ""
            if($("#cardType").val() != "4")
              cryptoValue = $("#crypto").val();
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementCarte",
  			      type: "POST",
  			      data:"typeDePaiment="+$("#cardType").val()+"&numCarte="+$("#cardNum").val()+"&cryptoCode="+cryptoValue+"&dateAnnee="+$("#cardEndYear").val()+"&dateMois="+$("#cardEndMonth").val(),
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          else if($("#submit").hasClass("partenaire")){
            Site.showLoader();
            var anneeValue = ""
            var moisValue = ""
            if($("#cardTypePartenaire").val() == "6"){
              anneeValue = $("#cardEndYear").val();
              moisValue = $("#cardEndMonth").val();
            }
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementCarte",
  			      type: "POST",
  			      data:"typeDePaiment="+$("#cardTypePartenaire").val()+"&numCarte="+$("#cardNum").val()+"&cryptoCode=&dateAnnee="+anneeValue+"&dateMois="+moisValue,
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          else if($("#submit").hasClass("avantage")){
            Site.showLoader();
            var carteValue = ""
            var numValue = ""
            var opeValue = ""
            // quand nouvelle carte:
            //    pas de numéro de carte
            //    valeurCarte=15
            if($("#paiement_avantage").hasClass("newCard"))
              carteValue="15";
            else{
              carteValue=$("#cardType").val();
              numValue=$("#cardNum").val();
            }
            // recherche de ope sélectionné
            $("fieldset.form").children("div.ope").each(
             function (i) {
               if($(this).children("div").children("div").hasClass("checked"))
               opeValue = $(this).children("input").attr("id").substring("paymentMethod-".length,$(this).children("input").attr("id").length);
                }
              );
            $.ajax({
              url: "PaiementWS.asmx/ProcessusPaiementCarteFID",
  			      type: "POST",
  			      data:"typeDePaiment="+carteValue+"&numCarte="+numValue+"&os_code="+opeValue,
              success: function(html){
                if($("statut",html).text()=='OK')
                  window.location.href=$("redirect",html).text();
                else{
                  if($("messageLayer",html).text()!=''){
                     Site.hideLoader();
                     System.alert($("messageLayer",html).text());
                     }
                  else
                    window.location.href=$("redirect",html).text();
                }        
              },
				      error : function(html){
				        Site.hideLoader();
						    System.alert("Une erreur s'est produite", null, false);
			       	}
            });
          }
          
          return false;
      }
    }	
		return validForm;
	},
	
	/**
	 * Test a pattern on a field
	 * @param {Object} formField The field on which to execute the validation rule
	 * @param {Object} pattern The pattern that the field might match
	 * @return returns true is the field match the pattern, else returns false
	 */
	isPattern:function (formField,pattern) {
		var pattern = pattern || formField.getAttribute('pattern');
		var regExp = new RegExp("^"+pattern+"$","i");
		var correct = regExp.test(formField.value);
		if (!correct && formField.getAttribute('patternDesc'))
			correct = formField.getAttribute('patternDesc');
		return correct;
	},
	
	/**
	 * Test if a field have been filled, or if a value has been selected on a radio button list / a select box
	 * @param {Object} formField The field on which to execute the validation rule
	 * @return returns true if the field have been filled else returns false
	 */
	isRequired:function(formField) {
		switch (formField.type) {
			case 'text':
			case 'textarea':
			case 'password':
			case 'select-one':
				var ExpreReg = new RegExp("( )", "g");
				if ((formField.value).replace(ExpreReg,""))
					return true;
				return false;
			case 'radio':
				var radios = formField.form[formField.name];
				for (var i=0;i<radios.length;i++) {
					if (radios[i].checked) return true;
				}
				return false;
			case 'checkbox':
				return formField.checked;
		}	
	},
	
	/**
	 * Test permettant de vérifer si le mot de passe et la confirmation de mot de passe sont les mêmes
	 */	 
	isPasswordEqual:function(formField){
	   return($("#TB_MotDePasse").val() == $(formField).val())
  },
  
  isOldGoodPassword:function(formField){
  if($(formField).val().length > 0){
  	var retour = false;
  	$.ajax({
  	    async: false,
        timeout: 5000,
  			url: "profilWS.asmx/VerifOldPassword",
  			type: "POST",
  			data: "oldpassword="+$(formField).val(),
  			success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
  				  retour = true;
  			else
  					retour = false;
  			},
  			error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
  	  })
  		return retour;
	 }
	 else return true;
	},
  
  isOldPasswordEntre:function(formField){
     if($("#TB_MotDePasse").val() != "")
      return ($("#oldmdp").val().length > 0);
    else
      return true;
  },
  
  isNewPasswordEntre:function(formField){
    if($("#oldmdp").val() != "")
      return ($("#TB_MotDePasse").val().length > 0);
    else
      return true;
  },

  
  isPasswordTaille:function(formField){
	   return($(formField).val().length > 5)
  },
  
  isCryptoTaille:function(formField){
	   return($(formField).val().length == 3)
  },
  
  isnumCBTaille:function(formField){
	   return($(formField).val().length  <= 19)
  },
  
  isPasswordTailleModif:function(formField){
    if($(formField).val().length > 0)
	   return($(formField).val().length > 5)
	  else
	   return true;
  },
  
  isMobile:function(formField){
      if(formField.value == ""){ 
        return true;
  	  }
	   return FormValidation.isPattern(formField,"0\\d{9}");
  },
  
  isMobileFormat:function(formField){
      if(formField.value == ""){ 
        return true;
  	  }
	   return FormValidation.isPattern(formField,"06\\d{8}");
  },
  
  isTelephone:function(formField){
      if(formField.value == ""){ 
        return true;
  	  }
	   return FormValidation.isPattern(formField,"0\\d{9}");
  },
  
  isTelephoneFormat:function(formField){
      if(formField.value == ""){ 
        return true;
  	  }
	   return FormValidation.isPattern(formField,"0[12345789]{1}\\d{8}");
  },
  
	/**
	 * Test if a form field value is a postal code (5 digits)
	 * @param {Object} formField The field on which to execute the validation rule
	 * @return returns true if the field is matching the postal code regexps
	 */
	isPostCode:function (formField) {
		if(formField.value == ""){ 
			return true;
		}
		var retour = false;
		if (FormValidation.isPattern(formField,"\\d{5}")){
			// Test nonexistent postal codes
			var regExp1 = new RegExp("^00","");
			var regExp2 = new RegExp("^96","");
			var regExp3 = new RegExp("^99","");
			if (!regExp1.test(formField.value) && !regExp2.test(formField.value) && !regExp3.test(formField.value))
				retour = true;
		}
		return retour;
	},
	
	/**
	 * Test if a form field value is not a Dom-Tom postal code
	 * @param {Object} formField The field on which to execute the validation rule
	 * @return returns true if the field isn't matching the Dom-Tom postal code regexps
	 */
	isNotDomTom:function (formField) {
		if(formField.value == ""){ 
			return true;
		}
		var retour = false;
		var regExpGuadeloupe = new RegExp("^971","");
		var regExpMartinique = new RegExp("^972","");
		var regExpGuyane = new RegExp("^973","");
		var regExpLaReunion = new RegExp("^974","");
		var regExpSaintPierreEtMiquelon = new RegExp("^975","");
		var regExpMayotte = new RegExp("^976","");
		var regExpTerresAustralesEtAntarctiques = new RegExp("^984","");
		var regExpWallisEtFutuna = new RegExp("^986","");
		var regExpPolynesieFrancaise = new RegExp("^987","");
		var regExpNouvelleCaledonie = new RegExp("^988","");
		
		if (!regExpGuadeloupe.test(formField.value) &&
			!regExpMartinique.test(formField.value) &&
			!regExpGuyane.test(formField.value) &&
			!regExpLaReunion.test(formField.value) &&
			!regExpSaintPierreEtMiquelon.test(formField.value) &&
			!regExpMayotte.test(formField.value) &&
			!regExpTerresAustralesEtAntarctiques.test(formField.value) &&
			!regExpWallisEtFutuna.test(formField.value) &&
			!regExpPolynesieFrancaise.test(formField.value) &&
			!regExpNouvelleCaledonie.test(formField.value)) {
			retour = true;		
		}
		return retour;
	},
	
	/**
	 * Test if a form field value is a date (jj/mm/aaaa)
	 * @param {Object} formField The field on which to execute the validation rule
	 * @return returns true if the field is matching the date regexp
	 */
	isDate:function (formField) {
		if(formField.value == ""){ 
			return true;
		}
		return FormValidation.isPattern(formField,"\\d{2}/\\d{2}/\\d{4}");
	},
	
	
	/**
	 * Test if a form field value only contains digits
	 * @param {Object} formField The field on which to execute the validation rule
	 * @return returns true if the field only contains digits
	 */
	isnumeric:function (formField) {
		return FormValidation.isPattern(formField,"\\d+");
	},
	
	
	isnumericCrypto:function (formField) {
		return FormValidation.isPattern(formField,"\\d+");
	},
	
	isnumericNumCB:function (formField) {
		return FormValidation.isPattern(formField,"\\d+");
	},
	/**
	 * Test if a form field value is an email
	 * @param {Object} formField The field on which to execute the validation rule
	 * @return returns true if the field is matching the email regexp
	 */
	isEmail:function (formField) {
		return FormValidation.isPattern(formField,"[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-z]{2,7}")
	},
	
	
	isNewEmailCompteSurcouf:function (formField){
	 var retour = false;
	 $.ajax({
	    async: false,
      timeout: 5000,
			url: "profilWS.asmx/VerifEmail",
			type: "POST",
			data: "email="+$(formField).val()+"&restrictionCompteSurcouf=true",// true car on fait une restriction sur les comptes Surcouf uniquement
			success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
				    retour = true;
				else
					retour = false;
			},
			error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
	   })
	   return retour;
	},
	
	isRecupEmailOK : function(formField){
      var retour = false;
      //on lance le traitement en webservice
      $.ajax({
        async: false,
        timeout: 5000,
    		url: "profilWS.asmx/RecuperationMotDePasse",
    		type: "POST",
    		data: "email="+$(formField).val(),
    		success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
    			    retour = true;
    			else
    				retour = false;
    		},
    		error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
        });
        return retour;
	},
	
	isNewEmailCompteSurcoufModif:function (formField){
	 var retour = false;
	 $.ajax({
	    async: false,
      timeout: 5000,
			url: "profilWS.asmx/VerifEmailPourModification",
			type: "POST",
			data: "email="+$(formField).val()+"&restrictionCompteSurcouf=true",// true car on fait une restriction sur les comptes Surcouf uniquement
			success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
				  retour = true;
				else
					retour = false;
			},
			error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
	  })
		return retour;
	},
	
	isNewEmailGeneral : function(formField){
    var retour = false;
    $.ajax({
	    async: false,
        timeout: 5000,
			url: "profilWS.asmx/VerifEmail",
			type: "POST",
			data: "email="+$(formField).val()+"&restrictionCompteSurcouf=false",// false car on fait une recherche sans restriction
			success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
				    retour = true;
				else
					retour = false;
			},
			error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
        })
        return retour;
	},
	
	
	isNewSociete: function(formField){
    var retour = false;
    $.ajax({
	    async: false,
      timeout: 5000,
			url: "profilWS.asmx/VerifSociete",
			type: "POST",
			data: "nomSociete="+$(formField).val(),// false car on fait une recherche sans restriction
			success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
				    retour = true;
				else
					retour = false;
			},
			error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
        })
        return retour;
	},
	
	isNewSocieteModification: function(formField){
    var retour = false;
    $.ajax({
	    async: false,
      timeout: 5000,
			url: "profilWS.asmx/VerifSocieteModification",
			type: "POST",
			data: "nomSociete="+$(formField).val(),// false car on fait une recherche sans restriction
			success: function(VerifOk){
				if ($("boolean",VerifOk).text() == "true")
				    retour = true;
				else
					retour = false;
			},
			error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
        })
        return retour;
	},
	
	isLoginPasswordOK : function(formField){
    	var retour = false;
    	$.ajax({
            async: false,
            timeout: 5000,
			url: "profilWS.asmx/VerifIdentification",
			type: "POST",
			data: "email="+$("#email").val()+"&motdepasse="+$(formField).val()+"&urlretour="+$("#UrlRetour").val(),
			success: function(retourWS){
				if ($("string", retourWS).text() == "erreur")
				    retour = false;
				else if ($("string", retourWS).text() == "")
				    retour = true;
				else{
				    FormValidation.retourPage = $("string", retourWS).text();
					retour = true;
				}
			}
        })
    	return retour;
	},
	
	isSelectionNewsletter : function(formField){
        if ($("#CB_Newsletter").next().children("div").hasClass("checked") || $("#CB_NewsEditos").next().children("div").hasClass("checked") || $("#CB_NewsAccepter").next().children("div").hasClass("checked"))
            return true;
        else
            return false;
	},
					
	/**
	 * Workaround for the fields that does not need any validation
	 * @return always returns true.
	 */
	emptyFunction:function () {
		return true;
	},
	
	/**
	 * Write the given error message after the given form object and switch the field
	 * in an error state (CSS class). register the onChange listener
	 * on this object to clear the error message when the user will change the value.
	 * @param {Object} obj The form object that contains an error
	 * @param {Object} message The message to write
	 */
	writeError:function (obj,message) {
	   // cas spécial pour les checkbox de la newsletter
	  if(message=="Vous n'avez pas sélectionné de lettres d'informations"){
	   	obj.errorMessage = null;
			obj.parentNode.errorMessage = null;
    }
    //********************
		obj.className += ' errorMessage';
		obj.onchange = FormValidation.removeError;
		if (obj.errorMessage || obj.parentNode.errorMessage) return;
		var errorMessage = document.createElement('span');
		errorMessage.className = 'errorMessage';
		errorMessage.appendChild(document.createTextNode(message));
		obj.parentNode.parentNode.appendChild(errorMessage);
		obj.errorMessage = errorMessage;
		obj.parentNode.errorMessage = errorMessage;
	},
	
	/**
	 * Clear the error message and the error state of a field.
	 */
	removeError:function () {
		this.className = this.className.replace(/errorMessage/,'');
		if (this.errorMessage) {
			this.parentNode.parentNode.removeChild(this.errorMessage);
			this.errorMessage = null;
			this.parentNode.errorMessage = null;
		}
		this.onchange = null;
	}
};

/**
* The CustomFields component uses the Faux Field factory to
* replace the system radio button, checkboxes and selectboxes
* within a search context with custom ones
*/
Site.fields = {};
var CustomFields = {
	/**
	 * Start the routine that replace the real radio
	 * buttons with the custom one.
	 * @param {Object} replaceContext The context that restrict the search for the radio buttons.
	 */
	 
	 // old
	/*init: function(type, replaceContext, callBack){
		Site.fields[replaceContext + ' ' + type] = FauxFields.Factory({context: replaceContext, field: type});*/
	// new 10 juillet
	init: function(type, replaceContext, callBack, filterOut){
		Site.fields[replaceContext + ' ' + type] = FauxFields.Factory({filterOut:filterOut, context: replaceContext, field: type});
	// fin new
		if(callBack != undefined){
			$.each(Site.fields[replaceContext + ' ' + type].collection, function() {
				this.addListener('change', callBack);
			});
		}
	},
	
  /* ********************* *
   * FUTURE IMPLEMENTATION *
   * ********************* */

  /**
   * Called each time a radiolist selection is changed,
   * aka each time a radio button is clicked.
   * The event fired this given in parameter. The clicked
   * radio can be accessed within this function by using "this"
   * @param {Object} e The fired Event
   */
   
  onChangeConfigateur:function(e, element){
      var recalculePrix = true;
      var inputCur = $(element.field)
      var minitext = inputCur.parent().children("label").children("span").html();
      var action="UPD"
      // dans le cas des checkbox on ne recalcule pas les prix
      
      if(inputCur.attr("type") == "checkbox") {
        recalculePrix = false;
        if (inputCur.attr("checked"))
          action="ADD"
        else
          action="DEL"
      }
      
		       
  	  Site.showLoader();
  	  var currentID = $(Accordion.currentSubItem).attr("id").replace("cat-","");
  		$.ajax({
        url: "configurateurWS.asmx/SelectionComposant",
        type: "POST",
         data: "idconfig="+ $("#editorial div").attr("idconfig").replace("Conf_","") +"&action="+action+"&typeConfig="+ $("#editorial div").attr("typeconfig") + "&souscatID=" + currentID + "&ref="+element.field.value,
         success: function(html){ 
          if ($("typeMAJ",html).text() == "droite"){
            // mise ÃƒÆ’Ã‚Â  jour de la partie droite
            $("#PC-price").remove();
            $("form").append($("resultHTML",html).text());
          }
          else{
            // mise a joure de la partie centrale + droite
            $("form").html($("resultHTML",html).text());
            CustomFields.init('radio', '#PC-selection', CustomFields.onChange);
            CustomFields.init('checkbox', '#PC-selection', CustomFields.onChange);        	
          	$("#selection-slide a.previous").click(Accordion.previous);
    	      $("#selection-slide a.next").click(Accordion.next);
          }
          // mise ÃƒÂ  jour de l'image centrale
          $("#selection-list").css("background-image","url(" + $("imageGrand",html).text() + ")");    
          //$("#PC-price #price-information").children("img").attr("src", $("#PC-selection").attr("imgdroite"))
          $("#PC-price #price-information > img").attr("src",$("imageFilaire",html).text());
          //changement du prix a cotÃƒÂ© de aucun
          // on change le prix seulement si on a 1 Element sÃƒÂ©lectionner
          // sinon en ÃƒÂ  rien choisir et on rreste ÃƒÂ  0 ou on est pas sur des radio bouton
          if ($("nbElement",html).text()=="1"){
            if ($("ImageProduit",html).text().trim()!=""){
              $("#selection-list").css("background-image","url(" + $("ImageProduit",html).text() + ")");                
            }
          }
          
          // mise ÃƒÂ  jour du menu
          if(($("categorieOblig",html).text()=="True") && ($("nbElement",html).text()=="0")){
              $(Accordion.currentSubItem).addClass("mandatory");
          }
          else if(($("categorieOblig",html).text()=="True") && ($("nbElement",html).text()!="0")){
              if ($(Accordion.currentSubItem).hasClass("mandatory")){
                $(Accordion.currentSubItem).removeClass("mandatory");
              }
          }
          Configurator.onPanierBtnClick();  
          //Configurator.onPanierBtnClick(($("ComfigComplete",html).text()=="False"));
          
           
          // dans le cas des radio on recalcule les prix
          if(recalculePrix){
            //$(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html(minitext);
            var prixSelectionne = inputCur.next().next().children("span:nth-child(2)").html().replace(/&nbsp;/g,"").replace(/ /g,"");
            prixSelectionne = prixSelectionne.substring(0,prixSelectionne.length - 1);
            prixSelectionne = parseFloat(prixSelectionne.replace(",","."));
            $("#PC-selection").children("div").children("div").children("fieldset").children("div").each(
          	function (i) {
          	  // mise ÃƒÂ  jour des prix des autres composants
              var prixCourrant = $(this).children("label").children("span:nth-child(2)").html().replace(/&nbsp;/g,"").replace(/ /g,"");
              prixCourrant = prixCourrant.substring(0,prixCourrant.length - 1);
              prixCourrant = parseFloat(prixCourrant.replace(",","."));
              var signe = "+"
              if (prixCourrant-prixSelectionne < 0) {signe = "-";}
                $(this).children("label").children("span:nth-child(2)").html(signe+" "+(Math.abs(prixCourrant-prixSelectionne)).formatMoney(2,","," ")+" &euro;");
              }
            );
          }
            switch($("nbElement",html).text())
            {
              case "0":
                if ($(Accordion.currentSubItem).hasClass("mandatory")){
                  $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html("A sélectionner...");
                }
                else{
                  $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html("Aucun");
                }
                break;  
              case "1":
                $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html($("NomElement",html).text());
                break;
              default:
                $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html("Choix Multiple");
                break;
            }
          $(Accordion.accSubItems).each(function(){
              var curcat = $(this);
              if ($(this).hasClass("need")) {
                 if(curcat.children("p").children("a:nth-child(2)").html() == "A sélectionner..."){curcat.addClass("mandatory");}
                 if(curcat.children("p").children("a:nth-child(2)").html() == "Intégré"){curcat.addClass("mandatory");}
              }
             
             if(curcat.children("p").children("a:nth-child(2)").html() == "Intégré"){
                if (curcat.hasClass("mandatory")){
                   curcat.children("p").children("a:nth-child(2)").html("A sélectionner...");
                 }
                else{
                    curcat.children("p").children("a:nth-child(2)").html("Aucun");
                }              
              }
            
             $("souscatID",html).each(function(){
               if(curcat.attr("id") == 'cat-'+$(this).text()){
                  if(curcat.hasClass("mandatory")){curcat.removeClass("mandatory");}
                  if(curcat.children("p").children("a:nth-child(2)").html() == "Aucun"){curcat.children("p").children("a:nth-child(2)").html("Intégré");}
                  if(curcat.children("p").children("a:nth-child(2)").html() == "A sélectionner..."){curcat.children("p").children("a:nth-child(2)").html("Intégré");}
                }
             });
              
			     });
			     
          SC.fixPNG.init();	
          Site.hideLoader();
          BubbleTips.init();
          SaveConf.init();
        },
        error : function(html){
			System.alert("Une erreur s'est produite...", null, null);
		}
      });
  },
  
  onChangeRegister: function(e, element){
    if(element.field.id == "Achat_Tous"){
      if(element.field.checked){	
          $("#CB_Newsletter").next().children("div").addClass("checked");
					$("#Achat_Ordi_Portables").next().children("div").addClass("checked");
					$("#Achat_Ordi_Bureau").next().children("div").addClass("checked");
					$("#Achat_Ecran_Periph").next().children("div").addClass("checked");
					$("#Achat_Composants_Connectiques").next().children("div").addClass("checked");
					$("#Achat_Reseaux_Wifi").next().children("div").addClass("checked");
					$("#Achat_Logiciels").next().children("div").addClass("checked");
					$("#Achat_PDA_GPS_Telephonie").next().children("div").addClass("checked");
					$("#Achat_MP3_Musiques").next().children("div").addClass("checked");
					$("#Achat_Photo_Camescopes").next().children("div").addClass("checked");
					$("#Achat_TV_HomeCinema").next().children("div").addClass("checked");
					$("#Achat_Films_JeuxVideos").next().children("div").addClass("checked");
					$("#Achat_Accessoires_Consommables").next().children("div").addClass("checked");
					$("#Achat_Destockages").next().children("div").addClass("checked");
					}
				else{
					$("#Achat_Ordi_Portables").next().children("div").removeClass("checked");
					$("#Achat_Ordi_Bureau").next().children("div").removeClass("checked");
					$("#Achat_Ecran_Periph").next().children("div").removeClass("checked");
					$("#Achat_Composants_Connectiques").next().children("div").removeClass("checked");
					$("#Achat_Reseaux_Wifi").next().children("div").removeClass("checked");
					$("#Achat_Logiciels").next().children("div").removeClass("checked");
					$("#Achat_PDA_GPS_Telephonie").next().children("div").removeClass("checked");
					$("#Achat_MP3_Musiques").next().children("div").removeClass("checked");
					$("#Achat_Photo_Camescopes").next().children("div").removeClass("checked");
					$("#Achat_TV_HomeCinema").next().children("div").removeClass("checked");
					$("#Achat_Films_JeuxVideos").next().children("div").removeClass("checked");
					$("#Achat_Accessoires_Consommables").next().children("div").removeClass("checked");
					$("#Achat_Destockages").next().children("div").removeClass("checked");
				}
    }
    
  
    if((element.field.id.indexOf("Achat_") == 0) && element.field.checked && (!$("#CB_Newsletter").next().children("div").hasClass("checked")))
        $("#CB_Newsletter").next().children("div").addClass("checked");
  },
  
  
    onChangeFiltreCommande: function(e, element){
      if(element.field.checked)
    		$("tr.commande_nonpcbs").each(function(){
    			content = $(this);
    			content.hide();
    		});
      else
    		$("tr.commande_nonpcbs").each(function(){
    			content = $(this);
    			content.show();
    		});
    },
  
 
  onChange: function(e){
      // on enleve les espaces
       if ($("form").attr("name") == "form-register" || $("form").attr("name") == "form_newsletter"){
        CustomFields.onChangeRegister(e, this);
      }
      else if($("form").attr("name") == "form-configuration"){
        CustomFields.onChangeConfigateur(e,this);     
      }
      else if($("#filter").size() > 0){
        CustomFields.onChangeFiltreCommande(e,this);
      }
      else if($("form#form-modifier-Newsletter").size()>0){
        CustomFields.onChangeRegister(e,this);
      }
    }		
  };

/**
 * The associatedQuantity Object provide a way to make the quantity field of some
 * component option to appear when the component is chosen (radio button selected).
 */
var AssociatedQuantity = {
	
	current:undefined,
	
	/**
	 * Hide the unchecked radio associated field to put the form on it's initial state.
	 */
	init: function(){
		$("#selection-list input[type=radio]:not(:checked), #PC-selection input[type=checkbox]:not(:checked)").siblings(".associated-quantity").hide();
		$("#selection-list input[type=radio]:checked, #PC-selection input[type=checkbox]:checked").parent("div").css("zIndex", 50);
	},
	
	/**
	 * Called by the onchange event on radio button (register by the CustomField Object).
	 * Open the radio button associated field and hide all others.
	 */
	open: function() {
		AssociatedQuantity.close();
		AssociatedQuantity.current = $(this.field)
		$(this.field).siblings(".associated-quantity").show();
		$(this.field).parent("div").css("zIndex", 50);
	},
	
	/**
	 * Hide all quantity field.
	 */
	close: function() {
		$(AssociatedQuantity.current).parent("div").css("zIndex", 20);
		$("#selection-list input[type=radio], #PC-selection input[type=checkbox]").siblings(".associated-quantity").hide();
	}
};

/**
* The Login component is used to hide the label that override the two login fields
* when the focus is given to these fields. On the blur event, when the focus is lost,
* the label will be displayed again only if the field is blank.
*/
var Login = {
	/**
	 * Initiate the login component by registering the onFocus and onBlur events on login form field
	 */
	init: function(){
		$("#login input[type=text], #login input[type=password]").focus(Login.focus).blur(Login.blur).each(function(){
			if(this.value != "") $(this).siblings("label").hide();
		});
		
		$("#login a.login-form").click(Login.showLostPwdForm)
		$("#login a.pwd-form").click(Login.showLoginForm)
	},
	
	showLostPwdForm: function() {
		$("#login .pwd-form").show();
		$("#login .login-form").hide();
	},
	
	showLoginForm: function() {
		$("#login .pwd-form").hide();
		$("#login .login-form").show();
	},
	
	/**
	 * Called on the onFocus event. Hide the  label to allows text typing.
	 */
	focus: function(){
		$(this).siblings("label").hide();
	},
	
	/**
	 * Called on the onBlur event. re-show the label if the field is still blank
	 */
	blur: function() {
		if(this.value == "") $(this).siblings("label").show();
	},
	
	lostPwdConfirm: function() {
		if($("#login-lostpwd-confirm")){
			$("#login-lostpwd-confirm a.close").click(Login.closeConfirm);
			$("#login-lostpwd-confirm a.connect").click(function(){
				Login.showLoginForm();
				Login.closeConfirm();
			});
			
			var offset = $("#login").offset();
			var left = offset.left + 30;
			var top = offset.top + 40;
			$("#login-lostpwd-confirm").css("left", left);
			$("#login-lostpwd-confirm").css("top", top);
			
			Site.createFreeze();
			$("#login-lostpwd-confirm").fadeIn();
		}
	},
	
	closeConfirm: function() {
		$("#login-lostpwd-confirm").fadeOut("normal", Site.destroyFreeze);
	}
};

/**
* The Accordion object allows the construction of accordion type menu.
* It supports the rollover effect on subitem, the automatic panel opening and closing
* and the navigation by "previous" and "next" buttons that will make the
* accordion to highlight the correct subitem and to open the according panel.
*/
var Accordion = {	
	/**
	 * PROPERTIES
	 */
	
	// selecteurs
	currentItem:undefined,
	currentSubItem:undefined,
	
	// collections et accesseurs
	accItems:undefined,
	accSubItems:undefined,
	
	// options
	// lite:undefined, -- For future enhancement
	
	/**
	 * The init method register the required listener on the different observable elements,
	 * and then hide the two menus
	 */
	init : function(){
		if ($("div.accordion").hasClass("accordion")) {
			// getting the items collections
			// Accordion.lite = $("div.accordion").hasClass("lite"); -- For future enhancement
			Accordion.accItems = $("div.accordion ul li a.main-link");
			if($("div.accordion").hasClass("register"))
			 Accordion.accSubItems = $("div.accordion ul li ul li").hover(Accordion.onSubItemOverRegister, Accordion.onSubItemsOut);
			else
			 Accordion.accSubItems = $("div.accordion ul li ul li").hover(Accordion.onSubItemOver, Accordion.onSubItemsOut);
			
			// collapse the entire accordion by default...
			Accordion.accItems.next("ul").hide();
			//Accordion.accItems.removeClass("on")
			
			// clear the class style of all subItems
			//Accordion.accSubItems.removeClass("on");

			// then select the first one
			if ($("div.accordion ul li a.active-panel").length > 0) {
				Accordion.iSelect($($("div.accordion ul li a.active-panel").get(0)));
			}
			else {
				Accordion.iSelect($(Accordion.accItems.get(0)));
			}
				
			if($("div.accordion").hasClass("register")){
				Accordion.accItems.click(Accordion.onItemReleaseRegister);
				Accordion.accSubItems.click(Accordion.onSubItemReleaseRegister);
			}
			else {
				Accordion.accItems.click(Accordion.onItemRelease);
				Accordion.accSubItems.click(Accordion.onSubItemRelease);
			}
				
		}
	},
	
	/**
	 * Select the next Sub Items in the whole list, even in another Accordion panel.
	 * Calls the onSubItemSelect callback and eventually, the onItemSelect if
	 * necessary.
	 */
	next : function() {
		if($(Accordion.currentSubItem).next("li").length){ // there is a next subitem in the current panel
			Accordion.siSelect($(Accordion.currentSubItem).next("li"));
		} else if($(Accordion.currentItem).parent().next("li").length){ // else, there is a next panel
			Accordion.iSelect($(Accordion.currentItem).parent().next("li").children("a").get(0));
		} // else....
		
		return false;
	},
	
	/**
	 * Select the previous sub item in the whole list, even in another Accordion panel.
	 * Calls the onSubItemSelect callback and eventually, the onItemSelect if
	 * necessary.
	 */
	previous : function() {
		if($(Accordion.currentSubItem).prev("li").length){ // there is a previous subitem in the current panel
			Accordion.siSelect($(Accordion.currentSubItem).prev("li"));
		} else if($(Accordion.currentItem).parent().prev("li").length){ // else there is a previous panel
			Accordion.iSelectLast($(Accordion.currentItem).parent().prev("li").children("a").get(0));
		} // else....
		
		return false;
	},
	
	/* ************** *
	 * EVENT CALLBACK *
	 * ************** */
	/**
	 * Called by the onClick listener registered on items
	 */
	onItemRelease : function(e) {
		Accordion.iSelect(this);
		this.blur();  // retire le focus pour eviter les effets de cadre gris
		return false; // Le navigateur ne suit pas le lien
	},
	
	onItemReleaseRegister : function(e) {
	 if(($(Accordion.currentItem).attr("id") != $(this).attr("id")) || ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape4') == 0)){
      if ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape1') == 0)
  		  CreationProfil.EnregistrerCookiesEtape1();
      else if($(Accordion.currentSubItem).attr("id") == 'MenuGaucheEtape2_B2C')
  		  CreationProfil.EnregistrerCookiesEtape2_B2C();
      else if($(Accordion.currentSubItem).attr("id") == 'MenuGaucheEtape2_B2B')
  		  CreationProfil.EnregistrerCookiesEtape2_B2B();
      else if($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape3') == 0)
  		  CreationProfil.EnregistrerCookiesEtape3();
  
  		Accordion.iSelect(this);
  		this.blur();  // retire le focus pour eviter les effets de cadre gris
		}
		return false; // Le navigateur ne suit pas le lien
	},
	
	/**
	 * Called by the onClick listener registered on subitems
	 */
	onSubItemRelease : function() {
		Accordion.siSelect(this);
		this.blur();  // retire le focus pour eviter les effets de cadre gris
		return false; // Le navigateur ne suit pas le lien
	},
	
	/**
	 * Called by the onClick listener registered on subitems
	 */
	onSubItemReleaseRegister : function() {
	 if (!(
      ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape1') == 0) ||
	   (($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape2') == 0) && ($(this).attr("id").indexOf('MenuGaucheEtape2') == 0 || $(this).attr("id").indexOf('MenuGaucheEtape3') == 0 || $(this).attr("id").indexOf('MenuGaucheEtape4') == 0)) ||
	   (($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape3') == 0) && ($(this).attr("id").indexOf('MenuGaucheEtape3') == 0 ||$(this).attr("id").indexOf('MenuGaucheEtape4') == 0)) ||
	   ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape4') == 0)
     ))
   {
  		Accordion.siSelect(this);
  		this.blur();  // retire le focus pour eviter les effets de cadre gris
  		return false; // Le navigateur ne suit pas le lien
	 }
	},
	
	/**
	 * Called by the onRollOver listener registered on subitems
	 */
	onSubItemOver : function() {
		Accordion.siHighlight(this);
	},
	
	/**
	* Called by the onRollOver listener registered on subitems
	*/
	onSubItemOverRegister : function() {
		 if (!(
      ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape1') == 0) ||
	   (($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape2') == 0) && ($(this).attr("id").indexOf('MenuGaucheEtape2') == 0 || $(this).attr("id").indexOf('MenuGaucheEtape3') == 0 || $(this).attr("id").indexOf('MenuGaucheEtape4') == 0)) ||
	   (($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape3') == 0) && ($(this).attr("id").indexOf('MenuGaucheEtape3') == 0 ||$(this).attr("id").indexOf('MenuGaucheEtape4') == 0)) ||
	   ($(Accordion.currentSubItem).attr("id").indexOf('MenuGaucheEtape4') == 0)
     ))
		    Accordion.siHighlight(this);
	},
	
	/**
	 * Called by the onRollOut listener registered on subitems
	 */
	onSubItemsOut : function() {
		if(this != Accordion.currentSubItem && $(this) != $(Accordion.currentSubItem)){
			Accordion.siOutlight(this);
		}
	},
	
	
	
	/* ********************* *
	 * FUTURE IMPLEMENTATION *
	 * ********************* */
	 
	 	selectFirstMandatory: function(){ 
      if ($("li.mandatory:first").parent().parent().children("a").hasClass("on")){
          Accordion.siSelect($("li.mandatory:first"));
      }
      else{
          Accordion.iSelect($("li.mandatory:first").parent().parent().children("a").get(0));
          Accordion.siSelect($("li.mandatory:first"));
      }  
  },
	 
	/**
	 * Called each time an accordion item is selected
	 * no matter the way it was selected
	 * @param {Object} target The item that was selected
	 */
	onItemSelect : function(target){
		// when clicking on an accordion item
		//Site.showLoader();
	},
	
	/**
	 * Called each time an accordion subitem is selected
	 * no matter the way it was selected
	 * @param {Object} target The subitems that was selected
	 */
	onSubItemSelect : function(target){
		// when clicking on an accordion subItem
		
		if ($("div.accordion").hasClass("configurator") && !$("div.accordion").hasClass("off")){
		  Accordion.onComponentSelect(target);
		}
		else if($("div.accordion").hasClass("register")){
		  Accordion.onRegisterSelect(target);
		}
		else if($("div.accordion").hasClass("services")){
		  Accordion.onServicesSelect(target);
		}
	},
  
  
  MAJCursorAccordion : function(idSubItem){
    if(idSubItem.indexOf('MenuGaucheEtape1') == 0){
    		$("#MenuGaucheEtape2_B2C").css("cursor", "default");
		    $("#MenuGaucheEtape2_B2B").css("cursor", "default");
		    $("#MenuGaucheEtape3_B2C").css("cursor", "default");
		    $("#MenuGaucheEtape3_B2B").css("cursor", "default");
		    $("#MenuGaucheEtape4_B2C").css("cursor", "default");
		    $("#MenuGaucheEtape4_B2B").css("cursor", "default");
    }
    else if (idSubItem.indexOf('MenuGaucheEtape2') == 0){
        $("#MenuGaucheEtape1_B2C").css("cursor", "pointer");
		    $("#MenuGaucheEtape1_B2B").css("cursor", "pointer");
		    $("#MenuGaucheEtape3_B2C").css("cursor", "default");
		    $("#MenuGaucheEtape3_B2B").css("cursor", "default");
		    $("#MenuGaucheEtape4_B2C").css("cursor", "default");
		    $("#MenuGaucheEtape4_B2B").css("cursor", "default");
    }
    else if (idSubItem.indexOf('MenuGaucheEtape3') == 0){
        $("#MenuGaucheEtape1_B2C").css("cursor", "pointer");
		    $("#MenuGaucheEtape1_B2B").css("cursor", "pointer");
		    $("#MenuGaucheEtape2_B2C").css("cursor", "pointer");
		    $("#MenuGaucheEtape2_B2B").css("cursor", "pointer");
		    $("#MenuGaucheEtape4_B2C").css("cursor", "default");
		    $("#MenuGaucheEtape4_B2B").css("cursor", "default");
    }
    else if (idSubItem.indexOf('MenuGaucheEtape4') == 0){
        $("#MenuGaucheEtape1_B2C").css("cursor", "pointer");
		    $("#MenuGaucheEtape1_B2B").css("cursor", "pointer");
		    $("#MenuGaucheEtape2_B2C").css("cursor", "pointer");
		    $("#MenuGaucheEtape2_B2B").css("cursor", "pointer");
		    $("#MenuGaucheEtape3_B2C").css("cursor", "pointer");
		    $("#MenuGaucheEtape3_B2B").css("cursor", "pointer");
    }
  },
  
  onServicesSelect : function(target){
    if ($(target).attr("id") == 'CartePage1'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/8pc_UnJour.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
    else if($(target).attr("id") == 'CartePage2'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Offres_Avantages.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
    else if($(target).attr("id") == 'CartePage3'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Mode_Emploi.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
    else if($(target).attr("id") == 'CartePage4'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Examen_Gratuit.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
    else if($(target).attr("id") == 'CartePage5'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Votre_Rythme.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
    else if($(target).attr("id") == 'CartePage6'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Cumul_Avantages.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
  			 System.alert("Une erreur s'est produite...", null, null);
  		  }
      });
    }
    else if($(target).attr("id") == 'CartePage7'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Ma_Carte.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
    else if($(target).attr("id") == 'CartePage8'){
        Site.showLoader();
        $.ajax({
        url: "../html/EspaceCarte/avantages/Conversion.html",
        cache: false,
        success: function(html){
          $("#ajah-container").html(html);
           Site.hideLoader();
        },
        error : function(html){
    			System.alert("Une erreur s'est produite...", null, null);
    		}
      });
    }
  },
  
  onRegisterSelect : function(target){
    Accordion.MAJCursorAccordion($(target).attr("id"));
    if ($(target).attr("id").indexOf('MenuGaucheEtape1') == 0){
        Site.showLoader();
        $.ajax({
        url: "../xsl/etape1.html",
        cache: false,
        success: function(html){
          $("#register-form").html(html);
          
          CreationProfil.ChargerCookiesEtape1();

		      CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange);
          CustomFields.init('select', '#register-form');
		      
          CreationProfil.init_Etape1();
           Site.hideLoader();
        },
        error : function(html){
			System.alert("Une erreur s'est produite...", null, null);
		}
      });
    }
    else if($(target).attr("id") == 'MenuGaucheEtape2_B2C'){
      Site.showLoader();
      $.ajax({
        url: "../xsl/etape2_B2C.html",
        cache: false,
        success: function(html){
          var contenuListMagasin = "<option value='0'>Sélectionnez</option>"
          // appel du WS qui permet de récuperer la liste des magasins
          $.ajax({
            url: "profilWS.asmx/ChargementMagasin",
            type: "POST",
            async: false,
            success: function(listmagasin){
                contenuListMagasin = $('string', listmagasin).text()
            },
            error : function(html){
				System.alert("Une erreur s'est produite...", null, null);
			}
          });
          $("#register-form").html(html);
          $("#Freq_B2C_Magasin").html(contenuListMagasin);  
          // je charge les cookies suivants en dehors de la méthode ChargerCookiesEtape2_B2C
          // pour éviter au maximum les "freeze"
          $("#Freq_B2C_Magasin").val(GestionCookies.GetCookie('magasin'));
          $("#DL_B2C_Civilite").val(GestionCookies.GetCookie('civilite'));    
          CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange); 
          CustomFields.init('select', '#register-form'); 
            
          CreationProfil.ChargerCookiesEtape2_B2C();  
          CreationProfil.init_Etape2_B2C();   
          Site.hideLoader();
        }
      });
    }
    else if($(target).attr("id") == 'MenuGaucheEtape2_B2B'){
        Site.showLoader();
        $.ajax({
        url: "../xsl/etape2_B2B.html",
        cache: false,
        success: function(html){
          var contenuListMagasin = "<option value='0'>Sélectionnez</option>"
           // appel du WS qui permet de récuperer la liste des magasins
          $.ajax({
          url: "profilWS.asmx/ChargementMagasin",
          async: false,
  			  type: "POST",
          success: function(listmagasin){
              contenuListMagasin = $('string', listmagasin).text()
              }
          });
          
          $("#register-form").html(html);
          // je charge les cookies suivants en dehors de la méthode ChargerCookiesEtape2_B2B
          // pour éviter au maximum les "freeze"
          $("#Freq_B2B_Magasin").html(contenuListMagasin);
          $("#Freq_B2B_Magasin").val(GestionCookies.GetCookie('magasin'));
          $("#DL_B2B_Civilite").val(GestionCookies.GetCookie('civilite'));
          
          // 4 par défaut
          var curEntreprise = "4"
          if(GestionCookies.GetCookie('typeEntreprise') != null)
            curEntreprise = GestionCookies.GetCookie('typeEntreprise')
          $("#RB_B2B_Type").children("#"+curEntreprise).attr("checked","checked");
          CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange);
          CustomFields.init('select', '#register-form');  

          CreationProfil.ChargerCookiesEtape2_B2B()  
          CreationProfil.init_Etape2_B2B(); 
          Site.hideLoader();
        }
      });
    }
    else if($(target).attr("id") == 'MenuGaucheEtape3_B2C'){
      Site.showLoader();
        $.ajax({
        url: "../xsl/etape3_B2C.html",
        cache: false,
        success: function(html){
          $("#register-form").html(html);
          
          CreationProfil.ChargerCookiesEtape3()   
          
          CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange);
          Site.hideLoader();
        }
      });
    }
    else if($(target).attr("id") == 'MenuGaucheEtape3_B2B'){
      Site.showLoader();
        $.ajax({
        url: "../xsl/etape3_B2B.html",
        cache: false,
        success: function(html){
          $("#register-form").html(html);
          
          CreationProfil.ChargerCookiesEtape3()   
          
          CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange);
          Site.hideLoader();
        }
      });
    }
   else if($(target).attr("id") == 'MenuGaucheEtape4_B2C'){
        Site.showLoader();
        $.ajax({
        url: "../xsl/enteteConnecte.html",
        cache: false,
        success: function(html){
          $("#header").html(html);
          SC.fixPNG.init();	
          MiniCart.init();
          }
        });
        $.ajax({
        url: "../xsl/etape4_B2C.html",
        cache: false,
        success: function(html){
          $("#register-form").html(html);
          $("#email").html(GestionCookies.GetCookie('email'));
          CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange);
          Site.hideLoader();
        },
        error : function(html){
            Site.hideLoader();
			System.alert("Une erreur s'est produite...", null, null);
		}
      });
    }
    else if($(target).attr("id") == 'MenuGaucheEtape4_B2B'){
        Site.showLoader();
        $.ajax({
        url: "../xsl/enteteConnecte.html",
        cache: false,
        success: function(html){
          $("#header").html(html);
          SC.fixPNG.init();	
          MiniCart.init();
          }
        });
        $.ajax({
        url: "../xsl/etape4_B2B.html",
        cache: false,
        success: function(html){
          $("#register-form").html(html);
          $("#email").html(GestionCookies.GetCookie('email'));
          CustomFields.init('radio', '#register-form', CustomFields.onChange);
          CustomFields.init('checkbox', '#register-form', CustomFields.onChange);
          Site.hideLoader();
        },
        error : function(html){
            Site.hideLoader();
			System.alert("Une erreur s'est produite...", null, null);
		}
      });
    }
  },	
  
  
	
	onComponentSelect : function(target){
		  var isModif=false;
		  var init=false;
		  if ($("#PC-price #price-information div.btns a.btn-big:eq(1)").hasClass("btn-big")) {
	      if ( !$("#PC-price #price-information div.btns a.btn-big:eq(1)").hasClass("off")){
	      	isModif=true;
				  }
			 }
			           
    	if ($("#PC-price #price-information div.btns a.btn-big:eq(1)").hasClass("btn-big")) {
    	 if ( $("#PC-price #price-information div.btns a.btn-big:eq(1)").hasClass("init")){
        init=true;
    		}
    	}
		
  		Site.showLoader();
  		var currentID = $(target).attr("id").replace("cat-","");
  		$.ajax({
        url: "configurateurWS.asmx/RemplirChoix",
        type: "POST",
        data: "isModif="+isModif+"&idconfig=" + $("#editorial div").attr("idconfig").replace("Conf_","") + "&typeConfig="+$("#editorial div").attr("typeconfig")+"&name="+currentID,
        success: function(html){
          // remplicage de la partie centrale
          $("form").html($("resultHTML",html).text());
          $("souscatID",html).each(function(){
            if(($(this).text() == currentID) && ($("div#selection-list div fieldset div span:first").html() == "Aucun")){
              $("div#selection-list div fieldset div span:first").html("Intégré");
            }
          });          
          $("#selection-list").css("background-image","url(" + $("imageGrand",html).text() + ")");    
          //$("#PC-price #price-information").children("img").attr("src", $("#PC-selection").attr("imgdroite"))
          $("#PC-price #price-information > img").attr("src",$("imageFilaire",html).text());
          //changement du prix a cotÃƒÂ© de aucun
          // on change le prix seulement si on a 1 Element sÃƒÂ©lectionner
          // sinon en ÃƒÂ  rien choisir et on rreste ÃƒÂ  0 ou on est pas sur des radio bouton
          if ($("nbElement",html).text()=="1"){
            if ($("#selection-list fieldset input:first").attr("type") == "radio"){
                var prixCourrant = parseFloat($("PrixElement",html).text().replace(",","."))
                $("#selection-list fieldset label span.selection-price:first").html("- "+prixCourrant.formatMoney(2,","," ")+" &euro;")
            }
            //mise en place de l'image representant le composant selection
            if ($("ImageProduit",html).text().trim()!=""){
              $("#selection-list").css("background-image","url(" + $("ImageProduit",html).text() + ")");                
            }
          }
          
          Configurator.onPanierBtnClick();

          $(Accordion.accSubItems).each(function(){   
              var curcat = $(this); 
              if ($(this).hasClass("need")) {
                 if(curcat.children("p").children("a:nth-child(2)").html() == "Aucun"){curcat.addClass("mandatory");}
                 if(curcat.children("p").children("a:nth-child(2)").html() == "Intégré"){
                 curcat.addClass("mandatory");}
              }

             if(curcat.children("p").children("a:nth-child(2)").html() == "Intégré"){
                if  (curcat.hasClass("mandatory")){curcat.children("p").children("a:nth-child(2)").html("A sélectionner...");}
                else  {curcat.children("p").children("a:nth-child(2)").html("Aucun");}              
            }
              
             $("souscatID",html).each(function(){
                if(curcat.attr("id") == 'cat-'+$(this).text()){
                    if(curcat.hasClass("mandatory")){curcat.removeClass("mandatory");}
                    if(curcat.children("p").children("a:nth-child(2)").html() == "Aucun"){curcat.children("p").children("a:nth-child(2)").html("Intégré");}
                    if(curcat.children("p").children("a:nth-child(2)").html() == "A sélectionner..."){curcat.children("p").children("a:nth-child(2)").html("Intégré");}
                }
             });
              
			     });

          
      		CustomFields.init('radio', '#PC-selection', CustomFields.onChange);
          CustomFields.init('checkbox', '#PC-selection', CustomFields.onChange);        	
        	$("#selection-slide a.previous").click(Accordion.previous);
  	      $("#selection-slide a.next").click(Accordion.next);
  			  SC.fixPNG.init();	
          Site.hideLoader();
          BubbleTips.init();
          SaveConf.init();
          
          if ($("ComfigModif",html).text()=="True"){
            //modification du texte de sous/catégorie
            switch($("nbElement",html).text())
            {
              case "0":
                if ($(Accordion.currentSubItem).hasClass("mandatory")){
                  $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html("A sélectionner...");
                }
                else{
                  $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html("Aucun");
                }
                break;  
              case "1":
                $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html($("NomElement",html).text());
                break;
              default:
                $(Accordion.currentSubItem).children("p").children("a:nth-child(2)").html("Choix Multiple");
                break;
            }
            if(($("categorieOblig",html).text()=="True") && ($("nbElement",html).text()=="0")){
                $(Accordion.currentSubItem).addClass("mandatory");
            }       
            //modification état bouton enregister
            $("#PC-price #price-information div.btns a.btn-big:eq(1)").removeClass("off");
            System.alert("Certains éléments de la configuration ne sont plus disponibles.");
          } 
          //gestion alerte mise a jour auto config
          if (init && isModif){
            System.alert("Certains éléments de la configuration ne sont plus disponibles.");
          }
        }
      });
   },	
	
	/* ******* *
	 * PRIVATE *
	 * ******* */		
	// ITEMS /////////////////////
	/**
	 * Select an Item (= a panel) and select its FIRST subItem.
	 * Both onItemSelect and onSubItemSelect callbacks are fired.
	 * @param {DOM Element} target The Item to select
	 */
	iSelect : function(target) {
		// Si le sous-menu ÃƒÂ©tait dÃƒÂ©jÃƒÂ  ouvert, on le referme :
	    if ($(target).next("ul:visible").length != 0) {
	        $(target).next("ul").slideUp("normal");
			$(target).removeClass("on");
			Accordion.clearSubItems();
			Accordion.currentItem = undefined;
	    }
	    // Si le sous-menu est cachÃƒÂ©, on ferme les autres et on l'affiche :
	    else {
	        $(Accordion.accItems).next("ul").slideUp("normal");
			$(Accordion.accItems).removeClass("on");
			Accordion.currentItem = target;
	        $(Accordion.currentItem).next("ul").slideDown("normal");
			$(Accordion.currentItem).addClass("on");
			
			if($("div.accordion").hasClass("services")){ //pour la page service carte avantage init accordéon champ actif
		
				var TblLiAccordion = $(target).next("ul").children("li");
			
				for(i = 0; i < TblLiAccordion.length; i++){

					if(TblLiAccordion[i].className == "on"){
						Accordion.siSelect(TblLiAccordion[i]);
						break;
					}
				}
			}
			else
				Accordion.siSelect($(target).next("ul").children("li").get(0));
	    }
		Accordion.onItemSelect(target);
	},
	
	/**
	 * Select and Item (= a panel) and select its LAST subitem.
	 * Both onItemSelect and onSubItemSelect callbacks are fired.
	 * @param {DOM Element} target The Item to select
	 */
	iSelectLast : function(target) {
		// Si le sous-menu ÃƒÂ©tait dÃƒÂ©jÃƒÂ  ouvert, on le referme :
	    if ($(target).next("ul:visible").length != 0) {
	        $(target).next("ul").slideUp("normal");
			$(target).removeClass("on");
			Accordion.clearSubItems();
			Accordion.currentItem = undefined;
	    }
	    // Si le sous-menu est cachÃƒÂ©, on ferme les autres et on l'affiche :
	    else {
	        $(Accordion.accItems).next("ul").slideUp("normal");
			$(Accordion.accItems).removeClass("on");
			Accordion.currentItem = target;
	        $(Accordion.currentItem).next("ul").slideDown("normal");
			$(Accordion.currentItem).addClass("on");
			Accordion.siSelect($(target).next("ul").children("li:last"));
	    }
		
		Accordion.onItemSelect(target);
	},
	
	// SUB ITEMS /////////////////////
	/**
	 * Make a sub item to enter its highlight state
	 * @param {DOM Element} target The subItem to highlight
	 */
	siHighlight : function(target) {
		$(target).addClass("on");
	},
	
	/**
	 * Make a sub item to leave its highlight state
	 * @param {DOM Element} target The subItem to outlight
	 */
	siOutlight : function(target) {
		$(target).removeClass("on");
	},
	
	/**
	 * Select a subitem
	 * @param {DOM Element} target the subItem to select
	 */
	siSelect : function(target) {
		Accordion.clearSubItems();
		Accordion.currentSubItem = target;
		$(Accordion.currentSubItem).addClass("on");
		// callback for future implementation
		Accordion.onSubItemSelect(target);
	},
	
	/**
	 * Remove hilight state on all subItems
	 */
	clearSubItems : function() {
		Accordion.accSubItems.removeClass("on");
		Accordion.currentSubItem = undefined;
	}
};
/**
* The Accordion object allows the construction of accordion type menu.
* It supports the rollover effect on subitem, the automatic panel opening and closing
* and the navigation by "previous" and "next" buttons that will make the
* accordion to highlight the correct subitem and to open the according panel.
*/
var AccordionNavigation = {	
	
	accItems:undefined,
	currentItem:undefined,
	/**
	 * The init method register the required listener on the different observable elements,
	 * and then hide the two menus
	 */
	init : function(){
		if ($("ul.accordion-like")) {
			AccordionNavigation.accItems = $("ul.accordion-like li").hover(AccordionNavigation.onSubItemOver, AccordionNavigation.onSubItemsOut);
			AccordionNavigation.accItems.click(AccordionNavigation.onItemRelease);
			AccordionNavigation.currentItem = $("ul.accordion-like  li.on");
			AccordionNavigation.onItemSelect(AccordionNavigation.currentItem);
		}
	},
  
  	/**
	 * Called by the onClick listener registered on items
	 */
	onItemRelease : function() {
		AccordionNavigation.accItems.removeClass("on");
		AccordionNavigation.currentItem = this;
		AccordionNavigation.siHighlight(this);
		// action du click
		AccordionNavigation.onItemSelect(this);
		this.blur();  // retire le focus pour eviter les effets de cadre gris
		return false; // Le navigateur ne suit pas le lien
	},	
	
	
	/**
	 * Called by the onRollOver listener registered on subitems
	 */
	onSubItemOver : function() {
		AccordionNavigation.siHighlight(this);
	},
	
	/**
	 * Called by the onRollOut listener registered on subitems
	 */
	onSubItemsOut : function() {
	  if($(this).html() != $(AccordionNavigation.currentItem).html()){
			AccordionNavigation.siOutlight(this);
		}
	},
	
	
	
	/* ********************* *
	 * FUTURE IMPLEMENTATION *
	 * ********************* */
	/**
	 * Called each time an accordion item is selected
	 * no matter the way it was selected
	 * @param {Object} target The item that was selected
	 */
	onItemSelect : function(target){
	 if($(target).attr("id") == "mes_commandes"){
	   		$.ajax({
				url: "profilWS.asmx/ChargementInformationCompte",
				type: "POST",
				data: "type=mes_commandes",
				beforeSend: function(){
	        Site.showLoader();
				},
        success: function(html){
          $("#member-space-info").html($("resultHTML",html).text());
          FoldableContent.init();
          ListeCommande.init();
					$(".modifybtn").click( function(){
    			  $("ul.accordion-like  #mes_infos").click();
    			  return false;
          });
          CustomFields.init('checkbox', '#filterzone', CustomFields.onChange); 
          Site.hideLoader();	
					},
		error : function(html){
            Site.hideLoader();
			System.alert("Une erreur s'est produite...", null, null);
		}
				});
				
   }
   else if($(target).attr("id") == "mes_infos"){
        if ($("#MsgInfosPersos").val() != "")
            System.alert($("#MsgInfosPersos").val(), null, null);
      	$.ajax({
				url: "profilWS.asmx/ChargementInformationCompte",
				type: "POST",
				data: "type=mes_infos",
				beforeSend: function(){
	        Site.showLoader();
				},
        success: function(html){
          $("#member-space-info").html($("resultHTML",html).text());
					CustomFields.init('radio', '#member-space', CustomFields.onChange);
          CustomFields.init('checkbox', '#member-space', CustomFields.onChange); 
          CustomFields.init('select', '#member-space'); 
          $("#nom").focus();
          FormValidation.init();
					Site.hideLoader();
					},
		error : function(html){
            Site.hideLoader();
			System.alert("Une erreur s'est produite...", null, null);
		}
				});
   }
    else if($(target).attr("id") == "mes_adresses"){
      
      var url = document.location.href;	
	  url = url.toLowerCase();

	  if((url.indexOf("erreur", 0) >= 0) && (url.indexOf("adr", 0) >= 0)){
	     System.alert("Vous devez avoir au moins une adresse de livraison et une adresse de facturation sélectionnées"); 
	     }
	     
      AddressForm.ReloadAddress();
   }
   
    else if($(target).attr("id") == "mes_avantages"){
        $.ajax({
            url: "profilWS.asmx/ChargementAvantages",
            type: "POST",
			beforeSend: function(){
                Site.showLoader();
		    },
            success: function(html){
                $("#member-space-info").html($("resultHTML",html).text());
    			CustomFields.init('radio', '#member-space', CustomFields.onChange);
                CustomFields.init('checkbox', '#member-space', CustomFields.onChange); 
                CustomFields.init('select', '#member-space'); 
                FormValidation.init();
                AvantagesForm.init();
    			Site.hideLoader();
    		},
    		error : function(html){
                Site.hideLoader();
    			System.alert("Une erreur s'est produite...", null, null);
    		}
		});
    }
   
    else if($(target).attr("id") == "mes_contacts"){
      Site.showLoader();
      $.ajax({
        url: "../xsl/compte_contact.html",
        cache: false,
        success: function(html){
          $("#member-space-info").html(html);
					Site.hideLoader();
					}
				});
      }
      
    else if($(target).attr("id") == "mes_abonnements"){
      $.ajax({
          url: "profilWS.asmx/ChargementInformationNewsletter",
          type: "POST",
			    beforeSend: function(){
             Site.showLoader();
		      },
          success: function(html){
            $("#member-space-info").html($("resultHTML",html).text());
    			  CustomFields.init('radio', '#member-space', CustomFields.onChange);
            CustomFields.init('checkbox', '#member-space', CustomFields.onChange); 
            CustomFields.init('select', '#member-space'); 
            FormValidation.init();
    			  Site.hideLoader();
    		  },
      		error : function(html){
             Site.hideLoader();
      			 System.alert("Une erreur s'est produite...", null, null);
    		  }
		});
      }
  // pour le paiement    
    else if($(target).attr("id") == "paiement_avantage"){
       Site.showLoader();
      $.ajax({
        url: "PaiementWS.asmx/ChargePaiementCarteFID",
        cache: false,
        type: "POST",
        data: "prixTTCcache="+$("#prixTTCcache").html(),
        success: function(html){
          $("#payment").html($("resultHTML",html).text());
          if($("#paiement_avantage").hasClass("newCard"))
            $("#select-card").html("Vous avez souscrit à la Carte @vantages avec option &#171;facilités de paiement&#187;.<br/>Sous réserve d'acceptation de votre demande par notre partenaire financier, vous pouvez régler en plusieurs fois votre commande d'aujourd'hui.");
          FormValidation.init();
          $("a.description").click(Paiement.voirDescriptionFinaref);
          //CustomFields.init('select', '#multi-select-card', DisplaySelectedCard.open);
          CustomFields.init('radio', '#payment', CustomFields.onChange);
          CustomFields.init('checkbox', '#payment', CustomFields.onChange); 
          CustomFields.init('select', '#payment'); 
					Site.hideLoader();
					},
		error : function(html){
            Site.hideLoader();
			System.alert("Une erreur s'est produite...", null, null);
		}
				});
      }
    else if($(target).attr("id") == "paiement_cb"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_cb.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          $("#cardEndYear").html(Paiement.listeAnneeCarte);
          FormValidation.init(); 
          $("#cardType").change(Paiement.changeCarte);
          CustomFields.init('radio', '#payment', CustomFields.onChange);
          CustomFields.init('checkbox', '#payment', CustomFields.onChange); 
          //CustomFields.init('select', '#payment');  
          CustomFields.init('select', '#payment', DisplaySelectedCard.open);
					Site.hideLoader();
					}
				});
      }
    else if($(target).attr("id") == "paiement_partenaire"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_partenaire.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          $("#cardEndYear").html(Paiement.listeAnneeCarte);
          FormValidation.init();
          $("#cardTypePartenaire").change(Paiement.changeCartePartenaire);
          CustomFields.init('radio', '#payment', CustomFields.onChange);
          CustomFields.init('checkbox', '#payment', CustomFields.onChange); 
          //CustomFields.init('select', '#payment');  
          CustomFields.init('select', '#payment', DisplaySelectedCard.open);
					Site.hideLoader();
					}
				});
      }
    else if($(target).attr("id") == "paiement_kadeos"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_kadeos.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          FormValidation.init(); 
					Site.hideLoader();
					}
				});
      }
    else if($(target).attr("id") == "paiement_cheque"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_cheque.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          FormValidation.init();
					Site.hideLoader();
					}
				});
      }
    else if($(target).attr("id") == "paiement_administratif"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_administratif.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          FormValidation.init();
					Site.hideLoader();
					}
				});
      }
    else if($(target).attr("id") == "paiement_entreprise"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_entreprise.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          FormValidation.init();
					Site.hideLoader();
					}
				});
      }
    else if($(target).attr("id") == "paiement_entrepriseNew"){
       Site.showLoader();
      $.ajax({
        url: "../xsl/paiement_entrepriseNew.html",
        cache: false,
        success: function(html){
          $("#payment").html(html);
          FormValidation.init();
					Site.hideLoader();
					}
				});
      }
	},	
	
	/* ******* *
	 * PRIVATE *
	 * ******* */		
	
	// SUB ITEMS /////////////////////
	/**
	 * Make a sub item to enter its highlight state
	 * @param {DOM Element} target The subItem to highlight
	 */
	siHighlight : function(target) {
		$(target).addClass("on");
	},
	
	/**
	 * Make a sub item to leave its highlight state
	 * @param {DOM Element} target The subItem to outlight
	 */
	siOutlight : function(target) {
		$(target).removeClass("on");
	}
};

/**
* The QuantityField is used on the shopping bag page. It allow the icrementation
* or the decrementation of a textfield numeric value.
*/
var QuantityField = {
		
	/**
	 * The init method register the click event on the plus and minus buttons
	 * and register the keypress event on the textfield to prevent typing some
	 * non numerical character. The fields must has the "quantity" css class, and
	 * the buttons must have the quantityplus or quantityminus css class.
	 */
	init: function(){
		$("input.quantity").keyup(function(event){QuantityField.watch(event, this);});//attention propre au panier
		$("a.quantityplus").click(QuantityField.increment);
		$("a.quantityminus").click(QuantityField.decrement);
	},
	
	/**
	 * Watch the value of the field to delete all non-numerical
	 * character that are typed on the field.
	 */
	watch: function(e, element) {
		var restrict = "0123456789";
		var w = "";
		for (i=0; i < element.value.length; i++) {
			x = element.value.charAt(i);
			if (restrict.indexOf(x,0) != -1)
				w += x;
			}
		element.value = w;
		
		/*appel recalcul du panier*/
		if(e.keyCode == 13){
			Panier.valideEnterRecalcul();
		}
	},
	
	/**
	 * Increment the value of the field. If the field is blank, the next value will be 1.
	 */
	increment: function() {
		var input = $(this).siblings("input.quantity").get(0)
		if(input.value != ""){input.value++;}
		else {input.value=1};
		
		return false; // ne pas suivre le lien
	},
	
	/**
	 * Decrement the value of the field. if the field is blank, the next value will be 1.
	 * The decrement function won't decrement to negatives values.
	 */
	decrement: function() {
		var input = $(this).siblings("input.quantity").get(0)
		if(input.value != "" ){
			if(input.value > 0)	input.value--;
		}
		else {input.value=1;}
		
		return false; // ne pas suivre le lien
	}
};


/**
 * The Cart Object implements an example of the System.confirm functionality utilisation.
 */
var Cart = {
	init: function() {
		$(".cartcell a.deletebtn").click(Cart.onDeleteBtnClick);
	},
	
	onDeleteBtnClick: function() {
		System.confirm("Voulez vous supprimer cet article", Cart.onValidate, Cart.onCancel);
		//System.alert("Cet article va Ãªtre supprimé", Cart.onValidate);
	},
	
	onValidate: function(){
		alert("validé");
	},
	
	onCancel: function(){
		alert("annulé");
	}
};

/**
* The Cart Detail is a small popin that pops in a product
* cell of the global shopping bag page.
* The init function register the event
*/
var CartDetail = {
	/**
	 * The init function register the click event
	 * on the detail buttons and on the close buttons
	 */
	init: function() {
		$("a.details").click(CartDetail.open);
		$("div.details").hide();
		$("div.details a.close, div.details a.details").click(CartDetail.close);
	},
	
	/** PRIVATE **/
	/**
	 * Make the Cart Detail popin to appear
	 */
	open: function() {
		$($(this).siblings("div.details").get(0)).height($($(this).parent("div.cartcell").get(0)).get(0).offsetHeight);
		$($(this).siblings("div.details").get(0)).fadeIn();
		return false;
	},
	
	/**
	 * Make the CartDetail popin to dissapear.
	 */
	close: function() {
		$($(this).parent("div.details").get(0)).fadeOut();
		return false;
	}
};


/**
* The Cart Detail is a small popin that pops in a product
* cell of the global shopping bag page.
* The init function register the event
*/
var AvantagesActivation = {
	
	selected:undefined,
	
	/** PRIVATE **/
	/**
	 * Make the Cart Detail popin to appear
	 */
	open: function() {
		if ($("#av-activation:checked").length >= 1) {
			$("#cart-avantage-popin a.close").click(AvantagesActivation.onClose);
			$("#cart-avantage-popin form").submit(AvantagesActivation.onSubmit);
			
			Site.fields['#cart-avantage-popin radio'].collection["yes"].check(null, true)
			
			var offset = $("#av-activation").offset();
			var top = offset.top - 100;
			$("#cart-avantage-popin").css("top", top);
			
			Site.createFreeze();
			
			$("#cart-avantage-popin").fadeIn();
		}
		return false;
	},
	
	/**
	 * Make the CartDetail popin to dissapear.
	 */
	close: function(bdestroyFreeze) {
		if(bdestroyFreeze)
			$("#cart-avantage-popin").fadeOut("normal", Site.destroyFreeze);
		else
			$("#cart-avantage-popin").fadeOut("normal", null);
	
		$("#av-activation").next().children("div").removeClass("checked");

		return false;
	},
	
	/**
	 * Make the CartDetail popin to dissapear.
	 */
	onClose: function() {
		$.each(Site.fields['.cartcell.avantages checkbox'].collection, function() {
			this.setValue(false);
		});
	
		AvantagesActivation.close(true);
		
		return false;
	},
	
	/**
	 * Make the CartDetail popin to dissapear.
	 */
	onSubmit: function() {
		console.log(AvantagesActivation.selected);
		if(AvantagesActivation.selected == "yes"){
			$.each(Site.fields['.cartcell.avantages checkbox'].collection, function() {
				this.setValue(true);
			});
			
			Panier.ActivationDiscountDay();
			
			AvantagesActivation.close(false);
			
		} else {
			$.each(Site.fields['.cartcell.avantages checkbox'].collection, function() {
				this.setValue(false);
			});
			
			AvantagesActivation.close(true);
		}
		

		return false;
	},
	
	toggle: function(){
		AvantagesActivation.selected = $($(this)[0].field).attr("id")
	}
};

/**
* CONFIGURATEUR
*/
/**
* The configurator Object has some usefull method that allows to change the graphical 
* state to pre-config or made to mesure page. Also controls the otherviews functionnality.
*/
var Configurator = {
	/**
	 * register the different listener that make the configurator
	 * page to switch to one state to another.
	 */
	init: function() {
		$("#preconfig-btn").click(Configurator.onPreconfigRelease);
		$("#config-btn").click(Configurator.onConfigRelease);
		$("#price-information .otherviews").click(Configurator.onViewRelease);
		$("#price-information .zoom-btn").click(PopinZoomedView.open);
		$("form.configurator").submit(Configurator.checkForm);
		if (($("#preconfig-btn").length > 0) && (!$("#preconfig-btn").parent().parent().hasClass("nodisplay")) &&  (!$("#preconfig-btn").hasClass("off"))){
      Configurator.toPreconfig();
    };
    if (($("#premonte-btn").length > 0) && (!$("#premonte-btn").parent().parent().hasClass("nodisplay"))){
      Configurator.getInfoProduit();
    };
	},
	
	
	/* ************** *
	 * EVENT CALLBACK *
	 * ************** */
	/**
	 * registered callback on the product detail button.
	 */
	onPreconfigRelease: function() {
	   if ($(this).hasClass("off")){
		    Configurator.toPreconfig();
		}
		return false; 	// Le navigateur ne suit pas le lien
	},
	
	/**
	 * registered callback on the configurator button
	 */
	onConfigRelease: function() {
	 if ($(this).hasClass("off")){
		Configurator.ValidToConfig();
		}
		return false;	// le navigateur ne suit pas le lien
	},
	
	/**
	 * Registered callback on an otherview thumbnail click
	 */
	onViewRelease: function() {
		Configurator.switchView(this);
		return false;	// le navigateur ne suit pas le lien
	},
	
	/**
	 * Prevent the configurator form from being submitted in case the
	 * configuration isn't conform. The test only consist on a verification
	 * of the class of the submit button, which mean you can desactivate
	 * the form by adding the class "off" to the submit button.
	 */
	checkForm: function() {
		return !$("#price-validation input").hasClass("off");
	},
	
	
	/* ******* *
	 * PRIVATE *
	 * ******* */
	
	/**
	 * add / remove some blocks classes to switch on the product detail state
	 */
	toPreconfig: function(){
		$("#config-surmesure").addClass("off")
		$("#preconfig-btn").removeClass("off");
		$("#config-btn").addClass("off");
		$("#editorial").removeClass("modificationsurmesure");
		var idconfig= $("#editorial div").attr("idsave");
    $("#editorial div").attr("idconfig",idconfig);
		//chargement de la déscription
		Configurator.getInfoProduit();
	},
	
	/**
	 * add / remove some blocks classes to switch on the configurator state
	 */
	toConfig: function(){
		$("#config-surmesure").removeClass("off")
		$("#config-btn").removeClass("off");
		$("#preconfig-btn").addClass("off");
		$("#editorial").addClass("modificationsurmesure");
		var idconfig= $("#editorial div").attr("idconfig");
    $("#editorial div").attr("idsave",idconfig);
	  if ($("#PC-price #price-information div.btns a.btn-big:eq(1)").hasClass("btn-big")) {
      $("#PC-price #price-information div.btns a.btn-big:eq(1)").addClass("off");
		} 
		Configurator.chargeConfig();
		//Accordion.init();
		
	},
	
	/**
	 * Called each time an otherview thumbnail is clicked
	 * @param {DOM Element} target The clicked thumbnail
	 */
	switchView: function(target){
		// swith the view of the pc
		ns =  $(target).attr("href");
		ls =  $(target).attr("href").replace(/NL/, "XL");
		$("#currentView").get(0).src = ns;						// L'image courante
		$("#price-information .zoom-btn").get(0).href = ls;		// Le lien du bouton agrandir pour l'image grande taille
		// new
		SC.fixPNG.init();
	},
	
	/* ********************* *
   * FUTURE IMPLEMENTATION *
   * ********************* */
    
    ValidToConfig : function(){
    	System.confirm("Attention, vous risquez de perdre les avantages liés à la configuration préconfigurée.", function (){Configurator.toConfig()}, function(){}, true);
    },
    
    chargeConfig : function (){
      var idconfig=$("#editorial div").attr("idconfig").replace("Conf_", "")
      var typeConfig=$("#editorial div").attr("typeconfig")
      Site.showLoader();
      //initialisation de tous les libellé
      $("#config-surmesure ul li ul li").each( function (){
        if ( $(this).hasClass("need")){
            $("p a:eq(1)",this).html("A sélectionner...");
            $(this).addClass("mandatory");
        }
        else
            $("p a:eq(1)",this).html("Aucun");
        
      });
      
      $.ajax({
        url: "../configurateur/configurateurWS.asmx/ChargeConfiguration",
        type: "GET",  
        data: "typeConfig="+ typeConfig + "&idconfig="+ idconfig,
        async: false,
        timeout: 5000,
        dataType: "xml",
        success: function(xml){
          // remplissage de la partie centrale
          $("Table1",xml).each(function (){
              var libelle=$("PROD_LIBELLE_PCBS",this).text();
              var categorie=$("COMPOSANTSOUSCAT_ID",this).text();
              var selection= "#cat-"+ categorie
              var element=$(selection).children("p").children("a:nth-child(2)")
              if (element.html()!=libelle){
                if ((element.html()=="A sélectionner...")|| (element.html()=="Aucun")){
                    element.html(libelle);
                }
                 else{
                   element.html("Choix Multiple");
                 }
                $(selection).removeClass("mandatory");
              }
            }
          );
          Accordion.init();    
        },
        error : function(html){
            System.alert("Une erreur s'est produite...", null, null);
        }
      })
    },
    
    getInfoProduit : function (){
      
      var idconfig=$("#editorial div").attr("idconfig").replace("Conf_","");
      var typeConfig=$("#editorial div").attr("typeconfig")
      
      var isPremonte=0;
      if (!$("#premonte-btn").parent().parent().hasClass("nodisplay")) isPremonte=1;
        
      
      Site.showLoader();
      $.ajax({
        url: "../configurateur/configurateurWS.asmx/GetInfoConfiguration",
        type: "GET",  
        data: "typeConfig="+ typeConfig + "&idconfig="+ idconfig + "&isPremonte=" + isPremonte,
        success: function(html){
          // remplicage de la partie centrale
          $("form").html($("resultHTML",html).text());
          SC.fixPNG.init();
          BubbleTips.init();	
          SaveConf.init();
          Configurator.onPanierBtnClick();
          $("#price-information .otherviews").click(Configurator.onViewRelease);
    		  $("#price-information .zoom-btn").click(PopinZoomedView.open);
          Site.hideLoader();          
        },
        error : function(html){
            System.alert("Une erreur s'est produite...", null, null);
        }
      })
    },
    
    
    VerifConfigEtAjoutPanier : function(idconfig, ref){
        Site.showLoader();
  		$.ajax({
        //url: "configurateurWS.asmx/VerifConfigurationTemp",
        url: "../Panier/PanierWS.asmx/VerifConfigurationAjoutPanier",
        type: "POST",
        data: "typeConfig="+ $("#editorial div").attr("typeconfig")+"&idconfig="+idconfig+"&ref="+ref,
        success: function(html){
        //alert ($("codePanier",html).text());
        if (($("codePanier",html).text()=="PANIER_AJOUT_OK") || ($("codePanier",html).text()=="PANIER_OK")) {
        
			//infos mini panier
			$("#Entete_LB_Nb_Article").html($("NbArticles", html).text());
			$("#Entete_LB_Total_Panier").html($("TotalBasket", html).text());
			$("#minicart p").html($("AvantagesPanier", html).text());
        
            System.alert("Votre configuration a été ajoutée au panier.<br/><br/><a href='../Panier/Panier.aspx'><img src='../img/components/minicart-detailbtn.gif' alt='Voir le d&eacute;tail' /></a>", null , false);
        }
        else if ($("codePanier",html).text() != ""){
            if ($("messagePanier",html).text() != "")
                System.alert($("messagePanier",html).text(),Accordion.init);
            else
                System.alert("Un problème est survenu lors de la mise au panier.",Accordion.init);
        }
        else{
            if ($("configComplete",html).text()=="False")
              System.alert("Tous les éléments obligatoires de la configuration n'ont pas été sélectionnés.",Accordion.init);
            else if (($("composantIndisponible",html).text()=="True"))
               System.alert("Certains éléments sélectionnés sont indisponibles, et ont été supprimés de la configuration.",Accordion.init);
            else if ($("composantIncompat",html).text()=="True")
               System.alert("Les éléments que vous avez choisis ne sont pas compatibles entre eux.",Accordion.init);
            else if ($("consomeSupPropose",html).text()=="True") {
              if ($("messageErreur",html).text()!="")
                System.alert($("messageErreur",html).text(),Accordion.init);
              else
                System.alert("Un problème est survenu lors de la mise au panier.",Accordion.init);
            }
            else
              System.alert("Un problème est survenu lors de la mise au panier.",Accordion.init);
            //gestion des catégories modifiés
            $("CatModif",html).each (function (){
		            //modification du texte de sous/catégorie
		            //switch($("nbElement",this).text())
		            //gestion du nom			            
		            switch($(this).children("NbComposant").text())
		            {
		              case "0":
		                $("#cat-"+$(this).children("COMPOSANTSOUSCAT_ID").text()).children("p").children("a:nth-child(2)").html("Aucun");
		                break;  
		              case "1":
		                $("#cat-"+$(this).children("COMPOSANTSOUSCAT_ID").text()).children("p").children("a:nth-child(2)").html($(this).children("NomComposant").text());
		                break;
		              default:
		                $("#cat-"+$(this).children("COMPOSANTSOUSCAT_ID").text()).children("p").children("a:nth-child(2)").html("Choix Multiple");
		                break;
		            }
		            //gestion de la class
		            if(($(this).children("CONFIGLIGNE_COMPOSANTINDISSOCIABLE").text()=="1") && ($(this).children("NbComposant").text()=="0")){
		                $("#cat-"+$(this).children("COMPOSANTSOUSCAT_ID").text()).addClass("mandatory");
		            }       
		          });                                    
          }
        },
        error : function(html){
            System.alert("Une erreur s'est produite...", null, null);
		}
        });
    },
    
	onPanierBtnClick: function(){
        
        $("form").submit( function() { return false;} );
        
        $("#price-submit").click(function(){
            //on teste si on est sur une configuaration predef ou non
            var idconfig= $("#editorial div").attr("idconfig").replace("Conf_","");
            if (($("#premonte-btn").length > 0) && ($("#premonte-btn").parent().parent().hasClass("nodisplay"))){
            	if (($("#preconfig-btn").length > 0)&&(!$("#preconfig-btn").parent().parent().hasClass("nodisplay"))&&(!$("#editorial").hasClass("modificationsurmesure"))){
  							Configurator.VerifConfigEtAjoutPanier(idconfig,-1);
            	}
            	else{
	              // on a cliqué sur le bouton d'ajout au panier, on va d'abord vérifier si le montage a été sélectionné dans la configuration
		            var OSSelectionne = true;
		            $("#config-surmesure").children("ul:first").children("li:first").children("ul:first").children("li").each(function(){
		                var curcat = $(this);
		                if (curcat.children("p:first").children("a:first").children("strong:first").html() == "Système d'exploitation")
		                    if (curcat.children("p:first").children("a:nth-child(2)").html() == "Aucun")
		                        OSSelectionne = false;
		            });	              
	              var MontageSelectionne = true;
	              $("#config-surmesure").children("ul:first").children("li:first").children("ul:first").children("li").each(function(){
	                  var curcat = $(this);
	                  if (curcat.children("p:first").children("a:first").children("strong:first").html().substr(0, 15) == "Montage et test")
	                      if (curcat.children("p:first").children("a:nth-child(2)").html() == "Aucun")
	                          MontageSelectionne = false;
	              });
	              
		            if (!OSSelectionne && !MontageSelectionne)
		                //le système d'exploitation et le montage n'ont pas été sélectionnés ==> on demande une confirmation à l'utilisateur
		                System.confirm("Vous avez sélectionné ni montage ni système d'exploitation. Votre configuration vous sera donc livrée en pièces détachées. Etes-vous sûr de vouloir ajouter cette configuration au panier ?", function (){Configurator.VerifConfigEtAjoutPanier(-1,-1);}, function(){}, true);
		            
		            else if (!OSSelectionne)
		                //le système d'exploitation n'a pas été sélectionné ==> on demande une confirmation à l'utilisateur
		                System.confirm("Vous n'avez pas sélectionné de système d'exploitation. Etes-vous sûr de vouloir ajouter cette configuration au panier ?", function (){Configurator.VerifConfigEtAjoutPanier(-1,-1);}, function(){}, true);
		            
		            else if (!MontageSelectionne)
		                // le montage n'a pas été sélectionné ==> on demande une confirmation à l'utilisateur
		                System.confirm("Vous n'avez pas sélectionné de montage, les éléments sélectionnés vous seront livrée en pièces détachées. Etes-vous sûr de vouloir ajouter cette configuration au panier ?", function (){Configurator.VerifConfigEtAjoutPanier(-1,-1);}, function(){}, true);
		            
		            else
		                // le systÃ¨me d'exploitation et le montage ont Ã©tÃ© sÃ©lectionnÃ©s ==> on ajoute la configuration au panier sans demande de confirmation
		                Configurator.VerifConfigEtAjoutPanier(-1,-1);
	            }
	          }
            else{
             		Configurator.VerifConfigEtAjoutPanier(-1,idconfig);
            }
        });
        
    }
    
};


/**
* POPIN ZOOMED VIEW
*/
var PopinZoomedView = {
	/**
	 * Make the zoomed view popin to appear.
	 * Must be called by a link wich href attributes is actually
	 * pointing toward a image that will be used to display
	 * in the popin
	 */
	open: function() {
		Site.createFreeze();

		$("#popin a.close").click(PopinZoomedView.close);			
		$("#freeze").click(PopinZoomedView.close);
		
		$("#popin img").get(0).src = $(this).get(0).href;
		
		
		var offset = $("#PC-selection").offset();
		var left = offset.left;
		var top = offset.top;
		$("#popin").css("left", left);
		$("#popin").css("top", top);
		
		$("#popin").fadeIn();
		
		return false;
	},
	
	/**
	 * Make the zoomed view popin to dissapear
	 */
	close: function() {
		$("#popin").fadeOut("normal", Site.destroyFreeze);
		return false;
	}
};


/**
* BUBBLE TIPS
* The bubbletips component can be shown on rollover or click events.
* The bubbletips is populated by the content related to the DOM object
* that asked the bubble tips to open. Can be a <a>, or a <dfn> tag, or even a
* tag that has the ".help-btn" class on.
*/
var BubbleTips = {
	/**
	 * Register the events that will make the diffÃƒÂ©rents bubble tips to appear
	 */
	init: function(){
		$(".help-btn").click(BubbleTips.open);
		$("dfn").hover(BubbleTips.open, BubbleTips.close);
		// new
		$("#cart .options a").hover(BubbleTips.open, BubbleTips.close);
		// old $("#cart .options a").hover(BubbleTips.open, BubbleTips.close);
		$("#small-popin a.close").click(BubbleTips.close);
		$("#small-popin").addClass("hidden");
	},
	
	/**
	 * Copy the content of a "help-btn" div group if the bubbletips and make it appear.
	 */
	open: function() {
		// targetting
		var popin = $("#small-popin");
		
		// content
		if ($(this).children("div.help-title").length != 0) {
			var title = $(this).children("div.help-title").get(0).innerHTML;
		} else var title = "Aide";
		
		if (this.nodeName.toLowerCase() == "dfn") {
			$("#small-popin a.close").hide();
			var content = $(this).attr("title");
			popin.children().children("p").get(0).innerHTML = content;
			popin.children().children("strong").get(0).innerHTML = title;
			
			var offset = $(this).offset();
			var left = offset.left - 30;
			var top = offset.top + 14;
			popin.css("left", left);
			popin.css("top", top);
			
		} else {
		  $("#small-popin a.close").show();
			var content = $(this).children("div.help-content").get(0).innerHTML;
			
			if (this.nodeName.toLowerCase() == "a"){
				var offset = $(this).offset();
				var left = offset.left - 15;
				var top = offset.top + 15;
				title = "Détails";
			} else {
				var offset = $(this).offset();
				var left = offset.left - popin.width() - 30;
				var top = offset.top - 14;
			}
			
			popin.children().children("p").get(0).innerHTML = content;
			popin.children().children("strong").get(0).innerHTML = title;
			popin.css("left", left);
			popin.css("top", top);
		}
		// new
		$(this).blur();
		// apparition
		popin.show();
		return false;
	}, 
	
	/**
	 * Hide the bubbletips
	 */
	close: function() {
	//			$("#small-popin").fadeOut();
		$("#small-popin").hide();
		return false;
	}
};

/**
* The main navigation of the PC By Surcouf website.
* Just provide the rollover and rollout effects
*/
var MainNavigation = {
	/**
	 * Register the rollover and rollout events on the concerned images
	 */
	init: function() {
		$("#navigation ul li").hover(MainNavigation.onLinkHover, MainNavigation.onLinkOut);
		$("#navigation ul li.on, #navigation ul li#logo").unbind();
	},
	
	/**
	 * switch the img.src attributes to make the rollover effect
	 */
	onLinkHover: function() {
	 // pour le lot alpha
	  if ($(this).children("a").size()>0){
  		var img = $(this).children("a").children("img").get(0);
  		
  		if(img.runtimeStyle != null && img.runtimeStyle.filter != ""){
  			var path = img.runtimeStyle.filter;
  			img.runtimeStyle.filter = path.replace(/\.(gif|png)/i, "-on.$1");
  		} else {
  			var path = img.src;
  			img.src = path.replace(/\.(gif|png)/i, "-on.$1");
  		}
		}
	},
	
	/**
	 * switch back the original img.src attributes to make the rollout effect
	 */
	onLinkOut: function() {
		 // pour le lot alpha
		if ($(this).children("a").size()>0){
  		var img = $(this).children("a").children("img").get(0);
  		
  		if(img.runtimeStyle != null && img.runtimeStyle.filter != ""){
  			var path = img.runtimeStyle.filter;
  			img.runtimeStyle.filter = path.replace(/-on\.(gif|png)/i, ".$1");
  		} else {
  			var path = img.src;
  			img.src = path.replace(/-on\.(gif|png)/i, ".$1");
  		}
  	}
	}
};

/**
* The minicart is a small popin that is on everypage and that sumup the content
* of the shoppingbag and it it's total amount.
*/
var MiniCart = {
	/**
	 * Register the click event on the cart button.
	 */
	init: function(){
		$("#minicart").hide();
		
		var url = document.location.href;	
		url = url.toLowerCase();
		
		if((url.indexOf("panier.aspx", 0) < 0) && (url.indexOf("choixadresses.aspx", 0) < 0) && (url.indexOf("paiement.aspx", 0) < 0) && (url.indexOf("confirm.aspx", 0) < 0))
			$("#minicartbtn").hover(MiniCart.open, MiniCart.close);
	},
	
	/**
	 * make the minicart to appear
	 */
	open: function(){
		var cart = $("#minicart");
	
		cart.show();
		
		cart.parent("li").addClass("on");
		
		var imgs = $(this).children("a").children("img");
		for (i=0; i<imgs.length; i++){
			var img = imgs[i];			
			if(img.runtimeStyle != null && img.runtimeStyle.filter != ""){
				var path = img.runtimeStyle.filter;
				img.runtimeStyle.filter = path.replace(/\.(gif|png)/i, "-on.$1");
			} else {
				var path = img.src;
				img.src = path.replace(/\.(gif|png)/i, "-on.$1");
			}		
		}
		
		return false;
	},
	
	/**
	 * Make the minicart to dissapear
	 */
	close: function(){
		var cart = $("#minicart");
	
		cart.hide();
		
		cart.parent("li").removeClass("on");
		
		var imgs = $(this).children("a").children("img");
		for (i=0; i<imgs.length; i++){
			var img = imgs[i];			
			if(img.runtimeStyle != null && img.runtimeStyle.filter != ""){
				var path = img.runtimeStyle.filter;
				img.runtimeStyle.filter = path.replace(/-on\.(gif|png)/i, ".$1");
			} else {
				var path = img.src;
				img.src = path.replace(/-on\.(gif|png)/i, ".$1");
			}		
		}
		
		return false;
	}
};

var ListeSegment = {
    
    init: function (){
		  $("#segments ul li").click(ListeSegment.getContent);
    },
    
    getContent: function (){
		  if($(this).children("a").attr("isSurmesure").replace("#","") == 1){
			window.location.href="../Configurateur/configurateur.aspx?idNoeud="+$(this).children("a").attr("idNoeud").replace("#","");
		 }
		 else{
			$.ajax({
				url: "catalogueWS.asmx/SelectionSegment",
				type: "POST",
				data: "idNoeud="+$(this).children("a").attr("idNoeud").replace("#","")+"&idSegment="+$(this).children("a").attr("segment").replace("#",""),
				success: function(html){
					$("#segments").html(html.getElementsByTagName("result")[0].firstChild.nodeValue);
					$("#editorial").hide();
					$("#editorial").show();	
					SC.fixPNG.init();	
					ListeSegment.init();
					},
				error : function(html){
                    System.alert("Une erreur s'est produite...", null, null);
        		}
				});
			}
		}
};

var SaveConf = {
 	
 		init : function (){
			$("#PC-price #price-information div.btns a.save").click(SaveConf.Enregistre);
			$("#PC-price #price-information div.btns a.savenew").click(SaveConf.Sauvegarde);
			$("#PC-price #price-information div.btns a.adapte").click(SaveConf.Adapte);
			if(GestionCookies.GetCookie('tempsave') == "1"){
        SaveConf.Sauvegarde();
        GestionCookies.SetCookie('tempsave', "0", null, "/");
        //GestionCookies.DeleteCookie('tempsave')	; 
      }
		},
		
		Adapte : function(){
      Configurator.ValidToConfig();
      return false;
    },

  	Enregistre :	function (){
			var idconfig= $("#editorial div").attr("idconfig").replace("Conf_","");
			var typeConfig= $("#editorial div").attr("typeconfig");
			SaveConf.SaveConfiguration(typeConfig,"-1",idconfig)
		}	,

  	Sauvegarde :	function (){
			var idconfig=$("#editorial div").attr("idconfig").replace("Conf_","");
			var typeConfig=$("#editorial div").attr("typeconfig");
      /*si configuration sur mesure*/	
      if ($("#config-surmesure").hasClass("off")){
        SaveConf.SaveConfiguration(typeConfig,idconfig,"-1")
      }
      else{
			   SaveConf.SaveConfiguration(typeConfig,"-1","-1")
			}
		},		

		SaveConfiguration : function (templateId,idconfigsrc,idconfigdest) {
			$.ajax({
				url: "../configurateur/configurateurWS.asmx/SaveConfiguration",
				type: "POST",
				datatype: "xml",
				data: "templateId="+templateId+"&idconfigsrc="+idconfigsrc+"&idconfigdest="+idconfigdest,
				success: function(html){
				    if (!$("#config-surmesure").hasClass("off")){
              $("#editorial div").attr("idconfig","Conf_"+$("string",html).text());
            }
            
						$("#PC-price #price-information div.btns a.save").addClass("off");
						System.alert("Votre configuration a bien été sauvegardée", null, false);
        },
				error : function(html){
						System.alert("Votre configuration n'a pas pu être sauvegardée", null, false);
				}
			});
		}
		
};


var WishList = {
 	
 		init : function (){
			$("#segments .config .suppression").click(WishList.onDeleteBtnClick);
			$("#segments .config .url").click(WishList.onPartageBtnClick);
		},

    onPartageBtnClick: function() {
  	  var mondiv= $(this);
  		
      $.clipboardReady(function(){          
      if ($.clipboard(mondiv.parent().children("div").children("a").attr("href")))
        System.alert("L'adresse de votre configuration a été copiée dans votre presse papier.");
      else
        System.alert("L'adresse de votre configuration n'a pu être copiée. Elle est la suivante :<br/>" + mondiv.parent().children("div").children("a").attr("href"));
      return false;
      } , { swfpath: "../JS/jquery.clipboard.swf", debug: false } ); 
  	},

  	onDeleteBtnClick: function() {
  	var mondiv= $(this);
  		System.confirm("Voulez vous supprimer cette configuration ?", function (){WishList.suppressionConfig(mondiv)}, function(){});
  	},


  	suppressionConfig :	function (mondiv){ 			
        mondiv.parent().addClass("segcellToDelete");		
  			/* appel ajax*/
  			$.ajax({
				url: "../configurateur/configurateurWS.asmx/DeleteConfiguration",
				type: "POST",
				dataType: "xml",
				data: "ref="+mondiv.parent().attr("id").replace("PC",""),
				success: function(html){
					if ($("string",html).text()=="true"){
						$(".segcellToDelete").removeClass("segcell");
						$(".segcellToDelete").remove();
						$("#segments .spacer").removeClass("spacer");
						$("#segments .segcell:even").addClass("spacer");
					}
					else {
						alert("suppression echoué!");
						$(".segcellToDelete").removeClass("segcellToDelete");
					}
				},
				error : function(html){
					alert("suppréssion echoué!");
					$(".segcellToDelete").removeClass("segcellToDelete");
				}
			});
		}		
};



var ModificationProfil = {
  init_B2C : function(){
	},// end function
	
	init_B2B : function(){
	},// end function
	
	ModifierCompte_B2C : function(){
	 //on construit la chaÃ®ne de paramêtres	
            
        		var params = "email=" + $("#email").val();   
            params = params + "&newmotdepasse=" + $("#TB_MotDePasse").val();
            params = params + "&oldmotdepasse=" + $("#oldmdp").val();      
            if ($("#autoconnect").attr("checked") == true)
        			params = params + "&autoident=true"
        		else
        			params = params + "&autoident=false"
        		params = params + "&civilite=" + $("#civilite").val();   
            params = params + "&nom=" + $("#nom").val();   
            params = params + "&prenom=" + $("#prenom").val();   
        		params = params + "&magasin=" + $("#magasin").val();
        		params = params + "&numerotelephone=" + $("#tel").val();   
        		params = params + "&numeromobile=" + $("#cell").val();
        		params = params + "&datedenaissance=" + $("#birth").val();   
        		
        		//var async = false;
        		$.ajax({
        			url: "profilWS.asmx/ModifierProfil_B2C",
        			type: "POST",
        			data: params,
        			beforeSend: function(statut){
                        Site.showLoader();
                    },
        			success: function(xmlResultat){
                        Site.hideLoader();
                        if ($("ModificationCompteOk", xmlResultat).text() == "True"){
                            $("#member").html("<strong>Bienvenue :</strong>"+ $("#civilite").val() +" "+ $("#nom").val() +" !");
                            
                   			if ($("#UrlRetour").val() != "")
								document.location.href = $("#UrlRetour").val();
							else
								System.alert("Nous vous remercions d'avoir mis à jour votre profil et nous vous confirmons que vos modifications ont bien été enregistrées", null , false);
                        }
                        else
                            System.alert($("MsgErreurModification", xmlResultat).text(), null , false);
        			},
        			error : function(statut){
        				Site.hideLoader();
        				System.alert("La modification du profil a échoué", null , false);
        			}
        		});
  },
  
  ModifierCompte_B2B : function(){
  	 //on construit la chaÃ®ne de paramêtres	
            
        		var params = "societe=" + $("#soc").val(); 
        		params = params + "&siret=" + $("#siret").val(); 
        		params = params + "&ape=" + $("#ape").val(); 
        		params = params + "&service=" + $("#serv").val(); 
             var idTypeEntreprise = 4;
             $("#RB_B2B_Type").children("input").each(
             function (i) {
               if($(this).next("div").children("div").hasClass("checked"))
                idTypeEntreprise = $(this).attr("id");
                }
              );
            params = params + "&typeOrga=" + idTypeEntreprise;  
            params = params + "&email=" + $("#email").val(); 
            params = params + "&newmotdepasse=" + $("#TB_MotDePasse").val();
            params = params + "&oldmotdepasse=" + $("#oldmdp").val();      
            if ($("#autoconnect").attr("checked") == true)
        			params = params + "&autoident=true"
        		else
        			params = params + "&autoident=false"
        		params = params + "&civilite=" + $("#civilite").val();   
            params = params + "&nom=" + $("#nom").val();   
            params = params + "&prenom=" + $("#prenom").val();   
        		params = params + "&magasin=" + $("#magasin").val();
        		params = params + "&numerotelephone=" + $("#tel").val();   
        		params = params + "&numeromobile=" + $("#cell").val();
        		params = params + "&numerofax=" + $("#fax").val();   
        		//var async = false;
        		$.ajax({
        			url: "profilWS.asmx/ModifierProfil_B2B",
        			type: "POST",
        			data: params,
        			beforeSend: function(statut){
                        Site.showLoader();
                    },
        			success: function(xmlResultat){
                        Site.hideLoader();
                        if ($("ModificationCompteOk", xmlResultat).text() == "True"){
                            $("#member").html("<strong>Bienvenue :</strong>"+ $("#civilite").val() +" "+ $("#nom").val() +" !");
                            
                            if ($("#UrlRetour").val() != "")
								document.location.href = $("#UrlRetour").val();
							else
	                            System.alert("Nous vous remercions d'avoir mis à jour votre profil et nous vous confirmons que vos modifications ont bien été enregistrées", null , false);
                        }
                        else
                            System.alert($("MsgErreurModification", xmlResultat).text(), null , false);
        			},
        			error : function(statut){
        				Site.hideLoader();
        				System.alert("La modification du profil a échoué", null , false);
        			}
        		});
  },
  
  ModifierCompte_Newsletter : function(){
  	 //on construit la chaÃ®ne de paramêtres	
  	        var params = ""
            if ($("#Achat_Ordi_Portables").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Ordi_Portables=true"
        		else
        			params = params + "&bAchat_Ordi_Portables=false"
        			
        		 if ($("#Achat_Ordi_Bureau").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Ordi_Bureau=true"
        		else
        			params = params + "&bAchat_Ordi_Bureau=false"
        			
            if ($("#Achat_Ecran_Periph").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Ecran_Periph=true"
        		else
        			params = params + "&bAchat_Ecran_Periph=false"
        			
        		if ($("#Achat_Composants_Connectiques").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Composants_Connectiques=true"
        		else
        			params = params + "&bAchat_Composants_Connectiques=false"
        			
        		if ($("#Achat_Reseaux_Wifi").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Reseaux_Wifi=true"
        		else
        			params = params + "&bAchat_Reseaux_Wifi=false"
        			
        		if ($("#Achat_Logiciels").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Logiciels=true"
        		else
        			params = params + "&bAchat_Logiciels=false"
        			
        		if ($("#Achat_PDA_GPS_Telephonie").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_PDA_GPS_Telephonie=true"
        		else
        			params = params + "&bAchat_PDA_GPS_Telephonie=false"
        			
        		if ($("#Achat_MP3_Musiques").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_MP3_Musiques=true"
        		else
        			params = params + "&bAchat_MP3_Musiques=false"
        			
        		if ($("#Achat_Photo_Camescopes").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Photo_Camescopes=true"
        		else
        			params = params + "&bAchat_Photo_Camescopes=false"
        			
        			
        		if ($("#Achat_TV_HomeCinema").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_TV_HomeCinema=true"
        		else
        			params = params + "&bAchat_TV_HomeCinema=false"
        			
        			
        		if ($("#Achat_Films_JeuxVideos").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Films_JeuxVideos=true"
        		else
        			params = params + "&bAchat_Films_JeuxVideos=false"
        			
        			
        		if ($("#Achat_Accessoires_Consommables").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Accessoires_Consommables=true"
        		else
        			params = params + "&bAchat_Accessoires_Consommables=false"
        			
        			
        		if ($("#Achat_Destockages").next().children("div").hasClass("checked"))
        			params = params + "&bAchat_Destockages=true"
        		else
        			params = params + "&bAchat_Destockages=false"
        			
        			
        		if ($("#CB_Newsletter").next().children("div").hasClass("checked"))
        			params = params + "&bCB_Newsletter=true"
        		else
        			params = params + "&bCB_Newsletter=false"
        			
        			
        		if ($("#CB_NewsEditos").next().children("div").hasClass("checked"))
        			params = params + "&bCB_NewsEditos=true"
        		else
        			params = params + "&bCB_NewsEditos=false"
        			
        		if ($("#CB_NewsAccepter").next().children("div").hasClass("checked"))
        			params = params + "&bCB_NewsAccepter=true"
        		else
        			params = params + "&bCB_NewsAccepter=false"
        		$.ajax({
        			url: "profilWS.asmx/ModifierAbonnementNewsletter",
        			type: "POST",
        			data: params,
        			beforeSend: function(statut){
                        Site.showLoader();
                    },
        			success: function(result){
                Site.hideLoader();
        				if ($("boolean",result).text() == "true")
          				  System.alert("Nous vous remercions d'avoir mis à jour vos abonnements et nous vous confirmons que vos modifications ont bien été enregistrées", null , false);
          			else
          					System.alert("La modification des abonnements aux newsletters a échoué", null , false);
        			},
        			error : function(statut){
        				Site.hideLoader();
        				System.alert("La modification des abonnements aux newsletters a échoué", null , false);
        			}
        		});
  }
}

var CreationProfil = {

    init : function(){  
		//on initialise en mode B2C par défaut
		//CreationProfil.init_B2C();
		CreationProfil.init_Cookies();
	},// end function
	
  init_Etape1 : function(){
    
		//on associe le bouton de validation pour l'appui sur la touche entrée de chaque champ du formulaire
		/*$("#TB_Email").keypress(Tools.clickButton);
		$("#TB_MotDePasse").keypress(Tools.clickButton);
		$("#TB_ConfMotDePasse").keypress(Tools.clickButton);*/
		//focus
		$("#TB_Email").focus();
	},// end function
	
	
	init_Etape2_B2C : function(){
		
		//on associe le bouton de validation pour l'appui sur la touche entrée de chaque champ du formulaire
		/*$("#DL_B2C_Civilite").keypress(Tools.clickButton);
		$("#TB_B2C_Nom").keypress(Tools.clickButton);
		$("#TB_B2C_Prenom").keypress(Tools.clickButton);
		$("#TB_B2C_AdresseL1").keypress(Tools.clickButton);
		$("#TB_B2C_CP").keypress(Tools.clickButton);
		$("#TB_B2C_AdresseL2").keypress(Tools.clickButton);
		$("#TB_B2C_Ville").keypress(Tools.clickButton);
		$("#TB_B2C_Ville").keypress(Tools.clickButton);
		$("#TB_MotDePasse").keypress(Tools.clickButton);
		$("#Freq_B2C_Magasin").keypress(Tools.clickButton);
		$("#TB_B2C_Consigne-infos").keypress(Tools.clickButton);
		$("#TB_B2C_Telephone").keypress(Tools.clickButton);
		$("#TB_B2C_Mobile").keypress(Tools.clickButton);
		$("#TB_B2C_DateNaissance").keypress(Tools.clickButton);*/
		
		//focus
		$("#TB_B2C_Nom").focus();
	},// end function
	
	
	init_Etape2_B2B : function(){
		
		//on associe le bouton de validation pour l'appui sur la touche entrée de chaque champ du formulaire
		/*$("#DL_B2B_Civilite").keypress(Tools.clickButton);
		$("#TB_B2B_Societe").keypress(Tools.clickButton);
		$("#TB_B2B_Siret").keypress(Tools.clickButton);
		$("#TB_B2B_Service").keypress(Tools.clickButton);
		$("#TB_B2B_Ape").keypress(Tools.clickButton);
		$("#TB_B2B_AdresseL1").keypress(Tools.clickButton);
		$("#TB_B2B_CP").keypress(Tools.clickButton);
		$("#TB_B2B_AdresseL2").keypress(Tools.clickButton);
		$("#TB_B2B_Ville").keypress(Tools.clickButton);
		$("#TB_B2B_AdresseL3").keypress(Tools.clickButton);
		$("#Freq_B2B_Magasin").keypress(Tools.clickButton);
		$("#TB_B2B_Nom").keypress(Tools.clickButton);
		$("#TB_B2B_Prenom").keypress(Tools.clickButton);
		$("#TB_B2B_Telephone").keypress(Tools.clickButton);
		$("#TB_B2B_Mobile").keypress(Tools.clickButton);
		$("#TB_B2B_Fax").keypress(Tools.clickButton);*/
		
		//focus
		$("#TB_B2B_Societe").focus();
	},// end function
	
	init_Cookies : function(){  
		
		GestionCookies.SetCookie('email', '');
		GestionCookies.SetCookie('motdepasse', '');
		GestionCookies.SetCookie('autoident', true);
		GestionCookies.SetCookie('civilite', '');
		GestionCookies.SetCookie('nom', '');
		GestionCookies.SetCookie('prenom', '');
		GestionCookies.SetCookie('adresse1', '');
		GestionCookies.SetCookie('adresse2', '');
		GestionCookies.SetCookie('adresse3', '');
		GestionCookies.SetCookie('codepostal', '');
		GestionCookies.SetCookie('ville', '');
		GestionCookies.SetCookie('consignes', '');
		GestionCookies.SetCookie('datedenaissance', '');
		GestionCookies.SetCookie('mobile', '');
		GestionCookies.SetCookie('telephone', '');
		GestionCookies.SetCookie('magasin', '');

		GestionCookies.SetCookie('societe', '');
		GestionCookies.SetCookie('siret', '');
		GestionCookies.SetCookie('service', '');
		GestionCookies.SetCookie('ape', '');
		GestionCookies.SetCookie('fax', '');
		
		GestionCookies.SetCookie('CB_Newsletter', "false");
		GestionCookies.SetCookie('CB_NewsEditos', "false");
		GestionCookies.SetCookie('CB_NewsAccepter', "false");
		
		GestionCookies.SetCookie('Achat_Ordi_Portables', "false");
		GestionCookies.SetCookie('Achat_Ordi_Bureau', "false");
		GestionCookies.SetCookie('Achat_Ecran_Periph', "false");
		GestionCookies.SetCookie('Achat_Composants_Connectiques', "false");
		GestionCookies.SetCookie('Achat_Reseaux_Wifi', "false");
		GestionCookies.SetCookie('Achat_Logiciels', "false");
		GestionCookies.SetCookie('Achat_PDA_GPS_Telephonie', "false");
		GestionCookies.SetCookie('Achat_MP3_Musiques', "false");
		GestionCookies.SetCookie('Achat_Photo_Camescopes', "false");
		GestionCookies.SetCookie('Achat_TV_HomeCinema', "false");
		GestionCookies.SetCookie('Achat_Films_JeuxVideos', "false");
		GestionCookies.SetCookie('Achat_Accessoires_Consommables', "false");
		GestionCookies.SetCookie('Achat_Destockages', "false");
		GestionCookies.SetCookie('Achat_Tous', "false");
		
	},
		
	CreerCompte_B2C : function(){  
    //on construit la chaÃ®ne de paramÃ¨tres	
    
		var params = "email=" + ((GestionCookies.GetCookie('email') == null) ? "" : GestionCookies.GetCookie('email')) + "&motdepasse=" + ((GestionCookies.GetCookie('motdepasse') == null) ? "" : GestionCookies.GetCookie('motdepasse')) + "&autoident=" + GestionCookies.GetCookie('autoident');
		params = params + "&civilite=" + GestionCookies.GetCookie('civilite') + "&nom=" + ((GestionCookies.GetCookie('nom') == null) ? "" : GestionCookies.GetCookie('nom')) + "&prenom=" + ((GestionCookies.GetCookie('prenom') == null) ? "" : GestionCookies.GetCookie('prenom'));
		params = params + "&adresse1=" + ((GestionCookies.GetCookie('adresse1') == null) ? "" : GestionCookies.GetCookie('adresse1')) + "&codepostal=" + ((GestionCookies.GetCookie('codepostal') == null) ? "" : GestionCookies.GetCookie('codepostal'));
		params = params + "&adresse2=" + ((GestionCookies.GetCookie('adresse2') == null) ? "" : GestionCookies.GetCookie('adresse2')) + "&ville=" + ((GestionCookies.GetCookie('ville') == null) ? "" : GestionCookies.GetCookie('ville'));
		params = params + "&adresse3=" + ((GestionCookies.GetCookie('adresse3') == null) ? "" : GestionCookies.GetCookie('adresse3')) + "&magasin=" + GestionCookies.GetCookie('magasin');
		params = params + "&consignes=" + ((GestionCookies.GetCookie('consignes') == null) ? "" : GestionCookies.GetCookie('consignes')) + "&numerotelephone=" + ((GestionCookies.GetCookie('telephone') == null) ? "" : GestionCookies.GetCookie('telephone'));
		params = params + "&numeromobile=" + ((GestionCookies.GetCookie('mobile') == null) ? "" : GestionCookies.GetCookie('mobile'));
		// on ne prend pas en compte la carte fidelite pour le moment
		params = params + "&fideliteoui=false"
    params = params + "&cartefidelite=";
		params = params + "&datedenaissance=" + ((GestionCookies.GetCookie('datedenaissance') == null) ? "" : GestionCookies.GetCookie('datedenaissance'));
		//params = params + "&isDemandeCarteOrAdherent=" + $("#IsDemandeCarteOrAdherent").val();    
        		
		params = params + "&cocheNewsletter=" + ((GestionCookies.GetCookie('CB_Newsletter') == "true") ? "true" : "false");
		params = params + "&cocheNewsEditos=" + ((GestionCookies.GetCookie('CB_NewsEditos') == "true") ? "true" : "false");
		params = params + "&cocheNewsAccepter=" + ((GestionCookies.GetCookie('CB_NewsAccepter') == "true") ? "true" : "false");
		
		params = params + "&coche_Ordi_Portables=" + ((GestionCookies.GetCookie('Achat_Ordi_Portables') == "true") ? "true" : "false");
		params = params + "&coche_Ordi_Bureau=" + ((GestionCookies.GetCookie('Achat_Ordi_Bureau') == "true") ? "true" : "false");
		params = params + "&coche_Ecran_Periph=" + ((GestionCookies.GetCookie('Achat_Ecran_Periph') == "true") ? "true" : "false");
		params = params + "&coche_Composants_Connectiques=" + ((GestionCookies.GetCookie('Achat_Composants_Connectiques') == "true") ? "true" : "false");
		params = params + "&coche_Accessoires_Consommables=" + ((GestionCookies.GetCookie('Achat_Accessoires_Consommables') == "true") ? "true" : "false");
		params = params + "&coche_Reseaux_Wifi=" + ((GestionCookies.GetCookie('Achat_Reseaux_Wifi') == "true") ? "true" : "false");
		params = params + "&coche_Logiciels=" + ((GestionCookies.GetCookie('Achat_Logiciels') == "true") ? "true" : "false");
		params = params + "&coche_MP3_Musiques=" + ((GestionCookies.GetCookie('Achat_MP3_Musiques') == "true") ? "true" : "false");
		params = params + "&coche_PDA_GPS_Telephonie=" + ((GestionCookies.GetCookie('Achat_PDA_GPS_Telephonie') == "true") ? "true" : "false");
		params = params + "&coche_Films_JeuxVideos=" + ((GestionCookies.GetCookie('Achat_Films_JeuxVideos') == "true") ? "true" : "false");
		params = params + "&coche_TV_HomeCinema=" + ((GestionCookies.GetCookie('Achat_TV_HomeCinema') == "true") ? "true" : "false");
		params = params + "&coche_Photo_Camescopes=" + ((GestionCookies.GetCookie('Achat_Photo_Camescopes') == "true") ? "true" : "false");
		params = params + "&coche_Destockages=" + ((GestionCookies.GetCookie('Achat_Destockages') == "true") ? "true" : "false");
		
		//var async = false;
		var retourStatut = -1;
		$.ajax({
			url: "profilWS.asmx/EnregistrerEnBDD_B2C",
			type: "POST",
			data: params,
			beforeSend: function(statut){
                Site.showLoader();
            },
			success: function(xmlResultat){
                if ($("CreationCompteOk", xmlResultat).text() == "True")
                    Accordion.next();
                else
                    System.alert($("MsgErreurCreation", xmlResultat).text(), null , false);
			},
			error : function(statut){
				System.alert("Une erreur est apparue durant la création du compte", null , false);
			}
		});
		return retourStatut;
	},// end function
	
	CreerCompte_B2B : function(){
	   //on construit la chaÃ®ne de paramÃ¨tres	
		var params = "societe=" + ((GestionCookies.GetCookie('societe') == null) ? "" : GestionCookies.GetCookie('societe')) + "&siret=" + ((GestionCookies.GetCookie('siret') == null) ? "" : GestionCookies.GetCookie('siret'))
		params = params +"&ape=" + ((GestionCookies.GetCookie('ape') == null) ? "" : GestionCookies.GetCookie('ape')) + "&service=" + ((GestionCookies.GetCookie('service') == null) ? "" : GestionCookies.GetCookie('service'))
		params = params +"&typeOrga=" + ((GestionCookies.GetCookie('typeEntreprise') == null) ? "4" : GestionCookies.GetCookie('typeEntreprise'))
		
    params = params +"&email=" + ((GestionCookies.GetCookie('email') == null) ? "" : GestionCookies.GetCookie('email')) + "&motdepasse=" + ((GestionCookies.GetCookie('motdepasse') == null) ? "" : GestionCookies.GetCookie('motdepasse')) + "&autoident=" + GestionCookies.GetCookie('autoident');
		params = params + "&civilite=" + GestionCookies.GetCookie('civilite') + "&nom=" + ((GestionCookies.GetCookie('nom') == null) ? "" : GestionCookies.GetCookie('nom')) + "&prenom=" + ((GestionCookies.GetCookie('prenom') == null) ? "" : GestionCookies.GetCookie('prenom'));
		params = params + "&adresse1=" + ((GestionCookies.GetCookie('adresse1') == null) ? "" : GestionCookies.GetCookie('adresse1')) + "&codepostal=" + ((GestionCookies.GetCookie('codepostal') == null) ? "" : GestionCookies.GetCookie('codepostal'));
		params = params + "&adresse2=" + ((GestionCookies.GetCookie('adresse2') == null) ? "" : GestionCookies.GetCookie('adresse2')) + "&ville=" + ((GestionCookies.GetCookie('ville') == null) ? "" : GestionCookies.GetCookie('ville'));
		params = params + "&adresse3=" + ((GestionCookies.GetCookie('adresse3') == null) ? "" : GestionCookies.GetCookie('adresse3')) + "&magasin=" + GestionCookies.GetCookie('magasin');
		params = params + "&numerotelephone=" + ((GestionCookies.GetCookie('telephone') == null) ? "" : GestionCookies.GetCookie('telephone'));
		params = params + "&numeromobile=" + ((GestionCookies.GetCookie('mobile') == null) ? "" : GestionCookies.GetCookie('mobile')) + "&numerofax=" + ((GestionCookies.GetCookie('fax') == null) ? "" : GestionCookies.GetCookie('fax'));;
		// on ne prend pas en compte la carte fidelite pour le moment
		params = params + "&fideliteoui=false"
    params = params + "&cartefidelite=";
		//params = params + "&isDemandeCarteOrAdherent=" + $("#IsDemandeCarteOrAdherent").val();    
        		
		params = params + "&cocheNewsletter=" + ((GestionCookies.GetCookie('CB_Newsletter') == "true") ? "true" : "false");
		params = params + "&cocheNewsEditos=" + ((GestionCookies.GetCookie('CB_NewsEditos') == "true") ? "true" : "false");
		params = params + "&cocheNewsAccepter=" + ((GestionCookies.GetCookie('CB_NewsAccepter') == "true") ? "true" : "false");
		
		params = params + "&coche_Ordi_Portables=" + ((GestionCookies.GetCookie('Achat_Ordi_Portables') == "true") ? "true" : "false");
		params = params + "&coche_Ordi_Bureau=" + ((GestionCookies.GetCookie('Achat_Ordi_Bureau') == "true") ? "true" : "false");
		params = params + "&coche_Ecran_Periph=" + ((GestionCookies.GetCookie('Achat_Ecran_Periph') == "true") ? "true" : "false");
		params = params + "&coche_Composants_Connectiques=" + ((GestionCookies.GetCookie('Achat_Composants_Connectiques') == "true") ? "true" : "false");
		params = params + "&coche_Accessoires_Consommables=" + ((GestionCookies.GetCookie('Achat_Accessoires_Consommables') == "true") ? "true" : "false");
		params = params + "&coche_Reseaux_Wifi=" + ((GestionCookies.GetCookie('Achat_Reseaux_Wifi') == "true") ? "true" : "false");
		params = params + "&coche_Logiciels=" + ((GestionCookies.GetCookie('Achat_Logiciels') == "true") ? "true" : "false");
		params = params + "&coche_MP3_Musiques=" + ((GestionCookies.GetCookie('Achat_MP3_Musiques') == "true") ? "true" : "false");
		params = params + "&coche_PDA_GPS_Telephonie=" + ((GestionCookies.GetCookie('Achat_PDA_GPS_Telephonie') == "true") ? "true" : "false");
		params = params + "&coche_Films_JeuxVideos=" + ((GestionCookies.GetCookie('Achat_Films_JeuxVideos') == "true") ? "true" : "false");
		params = params + "&coche_TV_HomeCinema=" + ((GestionCookies.GetCookie('Achat_TV_HomeCinema') == "true") ? "true" : "false");
		params = params + "&coche_Photo_Camescopes=" + ((GestionCookies.GetCookie('Achat_Photo_Camescopes') == "true") ? "true" : "false");
		params = params + "&coche_Destockages=" + ((GestionCookies.GetCookie('Achat_Destockages') == "true") ? "true" : "false");
		
		var retourStatut = -1;
		$.ajax({
			url: "profilWS.asmx/EnregistrerEnBDD_B2B",
			type: "POST",
			data: params,
            beforeSend: function(statut){
                Site.showLoader();
            },
			success: function(xmlResultat){
                if ($("CreationCompteOk", xmlResultat).text() == "True")
                    Accordion.next();
                else
                    System.alert($("MsgErreurCreation", xmlResultat).text(), null , false);
			},
			error : function(statut){
				System.alert("Une erreur est apparue durant la création du compte", null , false);
			}
		});
		
	},// end function
	
    	
	EnregistrerCookiesEtape1 : function(){
		//e-mail
		GestionCookies.SetCookie('email', $("#TB_Email").val());
		
		//mot de passe
		GestionCookies.SetCookie('motdepasse', $("#TB_MotDePasse").val());
		//auto-identification
		if ($("#CB_AutoIdent").attr("checked") == true)
			GestionCookies.SetCookie('autoident', true);
		else
			GestionCookies.SetCookie('autoident', false);
	},// end function
	
		ChargerCookiesEtape1 : function(){
        $("#TB_Email").val(GestionCookies.GetCookie('email')) ;
        $("#TB_MotDePasse").val(GestionCookies.GetCookie('motdepasse'));
        $("#TB_ConfMotDePasse").val(GestionCookies.GetCookie('motdepasse'));
		    if(GestionCookies.GetCookie('autoident') == "true") $("#CB_AutoIdent").attr("checked", "checked");		
	},// end function
	
	
	EnregistrerCookiesEtape2_B2C : function(){
		//civilité (attention, pour la civilité on doit passer par une variable car si on passe la valeur directement Ã§a ne marche pas !!!)
		var civ = $("#DL_B2C_Civilite").val();
		GestionCookies.SetCookie('civilite', civ);
		
		//nom
		GestionCookies.SetCookie('nom', $("#TB_B2C_Nom").val());
		
		//prénom
		GestionCookies.SetCookie('prenom', $("#TB_B2C_Prenom").val());
		
		//adresse1
		GestionCookies.SetCookie('adresse1', $("#TB_B2C_AdresseL1").val());
		
		//code postal
		GestionCookies.SetCookie('codepostal', $("#TB_B2C_CP").val());
        	
		//adresse2
		GestionCookies.SetCookie('adresse2', $("#TB_B2C_AdresseL2").val());
		
		//ville
		GestionCookies.SetCookie('ville', $("#TB_B2C_Ville").val());
		
		//adresse3
		GestionCookies.SetCookie('adresse3', $("#TB_B2C_AdresseL3").val());
		
		//magasin\n
		GestionCookies.SetCookie('magasin', $("#Freq_B2C_Magasin").val());
		
		//consignes de livraison (champ spécifique B2C)
		GestionCookies.SetCookie('consignes', $("#TB_B2C_Consigne-infos").val());
		
		//téléphone
		GestionCookies.SetCookie('telephone', $("#TB_B2C_Telephone").val());
		
		//mobile
		GestionCookies.SetCookie('mobile', $("#TB_B2C_Mobile").val());
		
		//date de naissance (champ spécifique B2C)
		GestionCookies.SetCookie('datedenaissance', $("#TB_B2C_DateNaissance").val());
	},// end function
	
	  ChargerCookiesEtape2_B2C : function(){
          $("#DL_B2C_Civilite").val(GestionCookies.GetCookie('civilite'));
          $("#TB_B2C_Nom").val(GestionCookies.GetCookie('nom')) ;
          $("#TB_B2C_Prenom").val(GestionCookies.GetCookie('prenom'));
          $("#TB_B2C_AdresseL1").val(GestionCookies.GetCookie('adresse1'));
          $("#TB_B2C_AdresseL2").val(GestionCookies.GetCookie('adresse2')) ;
          $("#TB_B2C_AdresseL3").val(GestionCookies.GetCookie('adresse3'));
          $("#TB_B2C_CP").val(GestionCookies.GetCookie('codepostal'));
          $("#TB_B2C_Ville").val(GestionCookies.GetCookie('ville')) ;
          $("#TB_B2C_Consigne-infos").val(GestionCookies.GetCookie('consignes'));
          $("#TB_B2C_DateNaissance").val(GestionCookies.GetCookie('datedenaissance'));
          $("#TB_B2C_Mobile").val(GestionCookies.GetCookie('mobile'));
          $("#TB_B2C_Telephone").val(GestionCookies.GetCookie('telephone'));				
	},// end function
	
	EnregistrerCookiesEtape2_B2B : function(){
     var idTypeEntreprise = 4;
     $("#RB_B2B_Type").children("input").each(
     function (i) {
       if($(this).next("div").children("div").hasClass("checked"))
        idTypeEntreprise = $(this).attr("id");
        }
      );
      GestionCookies.SetCookie('typeEntreprise', idTypeEntreprise); 
    
		//société (champ spécifique B2B)
		GestionCookies.SetCookie('societe', $("#TB_B2B_Societe").val());
		
		//nÂ° siret (champ spécifique B2B)
		GestionCookies.SetCookie('siret', $("#TB_B2B_Siret").val());
		
		//service (champ spécifique B2B)
		GestionCookies.SetCookie('service', $("#TB_B2B_Service").val());
		
		//nÂ° APE (champ spécifique B2B)
		GestionCookies.SetCookie('ape', $("#TB_B2B_Ape").val());
		
		//adresse1
		GestionCookies.SetCookie('adresse1', $("#TB_B2B_AdresseL1").val());
		
		//code postal
		GestionCookies.SetCookie('codepostal', $("#TB_B2B_CP").val());
		
		//adresse2
		GestionCookies.SetCookie('adresse2', $("#TB_B2B_AdresseL2").val());
		
		//ville
		GestionCookies.SetCookie('ville', $("#TB_B2B_Ville").val());
		
		//adresse3
		GestionCookies.SetCookie('adresse3', $("#TB_B2B_AdresseL3").val());
		
		//magasin
		GestionCookies.SetCookie('magasin', $("#Freq_B2B_Magasin").val());
		
		//civilité
		var civ = $("#DL_B2B_Civilite").val();
		GestionCookies.SetCookie('civilite', civ);
		
		//nom
		GestionCookies.SetCookie('nom', $("#TB_B2B_Nom").val());
		
		//prénom
		GestionCookies.SetCookie('prenom', $("#TB_B2B_Prenom").val());
		
		//téléphone
		GestionCookies.SetCookie('telephone', $("#TB_B2B_Telephone").val());
		
		//mobile
		GestionCookies.SetCookie('mobile', $("#TB_B2B_Mobile").val());
		
		//fax (champ spécifique B2B)
		GestionCookies.SetCookie('fax', $("#TB_B2B_Fax").val());			
	},// end function
	
		ChargerCookiesEtape2_B2B : function(){
          $("#DL_B2B_Civilite").val(GestionCookies.GetCookie('civilite'));
          $("#TB_B2B_Nom").val(GestionCookies.GetCookie('nom')) ;
          $("#TB_B2B_Prenom").val(GestionCookies.GetCookie('prenom'));
          $("#TB_B2B_AdresseL1").val(GestionCookies.GetCookie('adresse1'));
          $("#TB_B2B_AdresseL2").val(GestionCookies.GetCookie('adresse2')) ;
          $("#TB_B2B_AdresseL3").val(GestionCookies.GetCookie('adresse3'));
          $("#TB_B2B_CP").val(GestionCookies.GetCookie('codepostal'));
          $("#TB_B2B_Ville").val(GestionCookies.GetCookie('ville')) ;
          $("#TB_B2B_DateNaissance").val(GestionCookies.GetCookie('datedenaissance'));
          $("#TB_B2B_Mobile").val(GestionCookies.GetCookie('mobile'));
          $("#TB_B2B_Telephone").val(GestionCookies.GetCookie('telephone'));
          
          //société (champ spécifique B2B)
          $("#TB_B2B_Societe").val(GestionCookies.GetCookie('societe'));
          $("#TB_B2B_Siret").val(GestionCookies.GetCookie('siret'));
          $("#TB_B2B_Service").val(GestionCookies.GetCookie('service'));
          $("#TB_B2B_Ape").val(GestionCookies.GetCookie('ape'));
          $("#TB_B2B_Fax").val(GestionCookies.GetCookie('fax'));			
	},// end function
	
		EnregistrerCookiesEtape3 : function(){
//Site.showLoader();
		      GestionCookies.SetCookie('CB_Newsletter', $("#CB_Newsletter").next().children("div").hasClass("checked"));
		      GestionCookies.SetCookie('CB_NewsEditos', $("#CB_NewsEditos").next().children("div").hasClass("checked"));
		      GestionCookies.SetCookie('CB_NewsAccepter', $("#CB_NewsAccepter").next().children("div").hasClass("checked"));
          GestionCookies.SetCookie('Achat_Ordi_Portables', $("#Achat_Ordi_Portables").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Ordi_Bureau', $("#Achat_Ordi_Bureau").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Ecran_Periph', $("#Achat_Ecran_Periph").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Composants_Connectiques', $("#Achat_Composants_Connectiques").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Reseaux_Wifi', $("#Achat_Reseaux_Wifi").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Logiciels', $("#Achat_Logiciels").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_PDA_GPS_Telephonie', $("#Achat_PDA_GPS_Telephonie").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_MP3_Musiques', $("#Achat_MP3_Musiques").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Photo_Camescopes', $("#Achat_Photo_Camescopes").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_TV_HomeCinema', $("#Achat_TV_HomeCinema").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Films_JeuxVideos', $("#Achat_Films_JeuxVideos").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Accessoires_Consommables', $("#Achat_Accessoires_Consommables").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Destockages', $("#Achat_Destockages").next().children("div").hasClass("checked"));
					GestionCookies.SetCookie('Achat_Tous', $("#Achat_Tous").next().children("div").hasClass("checked"));				
	},// end function
	
	ChargerCookiesEtape3 : function(){
          if(GestionCookies.GetCookie('CB_Newsletter') == "true") $("#CB_Newsletter").attr("checked", "checked");
          if(GestionCookies.GetCookie('CB_NewsEditos') == "true") $("#CB_NewsEditos").attr("checked", "checked");
          if(GestionCookies.GetCookie('CB_NewsAccepter') == "true") $("#CB_NewsAccepter").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Ordi_Portables') == "true") $("#Achat_Ordi_Portables").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Ordi_Bureau') == "true") $("#Achat_Ordi_Bureau").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Ecran_Periph') == "true") $("#Achat_Ecran_Periph").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Composants_Connectiques') == "true") $("#Achat_Composants_Connectiques").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Reseaux_Wifi') == "true") $("#Achat_Reseaux_Wifi").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Logiciels') == "true") $("#Achat_Logiciels").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_PDA_GPS_Telephonie') == "true") $("#Achat_PDA_GPS_Telephonie").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_MP3_Musiques') == "true") $("#Achat_MP3_Musiques").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Photo_Camescopes') == "true") $("#Achat_Photo_Camescopes").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_TV_HomeCinema') == "true") $("#Achat_TV_HomeCinema").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Films_JeuxVideos') == "true") $("#Achat_Films_JeuxVideos").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Accessoires_Consommables') == "true") $("#Achat_Accessoires_Consommables").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Destockages') == "true") $("#Achat_Destockages").attr("checked", "checked");
          if(GestionCookies.GetCookie('Achat_Tous') == "true") $("#Achat_Tous").attr("checked", "checked");   			
	}
	
};

var Tools = {
 clickButton : function(e){
				if (e.keyCode == 13){
						//$(this).parents("form").submit();
						return false; 
				}
	}
};
/**
* AddressForm
*/
var AddressForm = {
	
	currentForm:undefined,
	currentAddress:undefined,
	
	init: function() {
		if($("#add-shipping-form") && $("#add-payment-form")){
			$("a.add-address, a.modify-address").click(AddressForm.open);
			$("#add-shipping-form a.close").click(AddressForm.close);
			$("#add-payment-form a.close").click(AddressForm.close);
			$("a.mkdefaultbtn").click(AddressForm.ChangeAdresseDefaut);
      $("a.deletebtn").click(AddressForm.DemmandeSuppressionAddresse);
		}
	},
	
	/**
	 * Make the form to appear.
	 * If the clicked link contains an URI with GET like parameters matching the fields name on the 
	 * form, the form will be automatically filled in
	 */
	open: function() {
		
		if($(this).hasClass("ispayment")){
			AddressForm.currentForm = $("#add-payment-form");
			
			if($(this).hasClass("addbtn")){//c'est une création init titre
				$("#add-payment-form h2").html("Créer une adresse de facturation");
			}
			else {
				$("#add-payment-form h2").html("Modifier l'adresse de facturation");
			}
		} 
		else {
			AddressForm.currentForm = $("#add-shipping-form");
			
			if($(this).hasClass("addbtn")){ //c'est une création init titre
				$("#add-shipping-form h2").html("Créer une adresse de livraison");
			}
			else {
				$("#add-shipping-form h2").html("Modifier l'adresse de livraison");
			}
		}
		
		//init messages erreur
	 	var elementsAdr = $('input, checkbox, select', AddressForm.currentForm);
		
		for (var i=0;i<elementsAdr.length;i++) {
			elementsAdr[i].className = elementsAdr[i].className.replace(/errorMessage/,'');
			
			if (elementsAdr[i].errorMessage) {
				elementsAdr[i].parentNode.parentNode.removeChild(elementsAdr[i].errorMessage);
				elementsAdr[i].errorMessage = null;
				elementsAdr[i].parentNode.errorMessage = null;
			}
			elementsAdr[i].onchange = null;
		}

		$("input, select, textarea", AddressForm.currentForm).val("");
		
		$.each(Site.fields['.form select'].collection, function() {
			this.setIndex(0);
		});
		
		$.each(Site.fields['.form checkbox'].collection, function() {
			this.setValue(false);
		});

		AddressForm.currentAddress = undefined;

		if($(this).attr("href").indexOf("?") != -1){
			href = $(this).attr("href");
			fullargs = href.split("?")[1];
			args = fullargs.split("&");
			for(i=0; i< args.length; i++){
				key = args[i].split("=")[0];
				val = args[i].split("=")[1];
				
				if($("#"+key)){
				  if(key=='id-address') AddressForm.currentAddress=val;
					else if(Site.fields['.form select'].collection[key] != undefined) Site.fields['.form select'].collection[key].setValue(val);
					else if(Site.fields['.form checkbox'].collection[key] != undefined) Site.fields['.form checkbox'].collection[key].setValue(val);
					else $("#"+key).val(val);
				}
			}
		}
		
		var offset = $(this).offset();
		var top = offset.top - 200;
		AddressForm.currentForm.css("top", top);
		Site.createFreeze();
		AddressForm.currentForm.fadeIn();			
		$("#freeze").click(AddressForm.close);
			
		return false;
	},
	
	/**
	 * Make the form to dissappear
	 */
	close: function() {
		AddressForm.currentForm.fadeOut("normal", Site.destroyFreeze);
		AddressForm.currentAddress = undefined;
		return false;
	},
	
	closeOnlyForm: function() {
		AddressForm.currentForm.fadeOut("normal");
		AddressForm.currentAddress = undefined;
		return false;
	},
	
	ChangeAdresseDefaut: function() {
	    var guidaddress = undefined;
	    var type = undefined;
  	 	if($(this).attr("href").indexOf("?") != -1){
  			href = $(this).attr("href");
  			fullargs = href.split("?")[1];
  			args = fullargs.split("&");
  			for(i=0; i< args.length; i++){
  				key = args[i].split("=")[0];
  				val = args[i].split("=")[1];
  				if($("#"+key)){
  				  if(key=='id-address') guidaddress=val;
  				  if(key=='type') type=val;
  				}
  			}
  		}
  		if(!(guidaddress == undefined || type == undefined)){

    		$.ajax({
    		  type: "POST",
    			url: "../Profil/profilWS.asmx/ModifierAdresseParDefaut",
    			data: "guidAddress=" + guidaddress + "&type=" + type,
    			beforeSend: function(statut){
            Site.showLoader();
          },
    			success: function(statut){
    			 if( $('int', statut).text() == "0"){
    			     System.alert("Cette adresse est maintenant votre adresse par défaut", AddressForm.ReloadAddress , true, true);
    			  }
    			  else{
    			    Site.hideLoader();
    			    System.alert("Nous n'avons pas pu modifier l'adresse par défaut", null , false, false);
    			  }
    			},
    			error : function(statut){
    				Site.hideLoader();
    				System.alert("Nous n'avons pas pu modifier l'adresse par défaut", null , false, false);
    			}
    		});
      }
      else
        System.alert("Nous n'avons pas pu modifier l'adresse par défaut", null , false, false);
      return false; 
  },
  
  	DemmandeSuppressionAddresse: function() {
	    var guidaddress = undefined;
	    var type = undefined;
  	 	if($(this).attr("href").indexOf("?") != -1){
  			href = $(this).attr("href");
  			fullargs = href.split("?")[1];
  			args = fullargs.split("&");
  			for(i=0; i< args.length; i++){
  				key = args[i].split("=")[0];
  				val = args[i].split("=")[1];
  				if($("#"+key))
  				  if(key=='id-address') guidaddress=val;
  			}
  		}
  		if(guidaddress != undefined)
    	 System.confirm("Voulez vous supprimer cette adresse ?", function (){AddressForm.SuppressionAddresse(guidaddress)}, function(){});
      else
        System.alert("Nous n'avons pas pu supprimer cette adresse", null , false, false);
      return false; 
  },
  
  
  	SuppressionAddresse: function(guidaddress) {
    		$.ajax({
    		  type: "POST",
    			url: "../Profil/profilWS.asmx/SupprimerAdresse",
    			data: "guidAddress=" + guidaddress,
    			beforeSend: function(statut){
            Site.showLoader();
          },
    			success: function(statut){
    			 if( $('int', statut).text() == "0"){
    			     AddressForm.ReloadAddress();
    			  }
    			  else{
    			    Site.hideLoader();
    			    System.alert("Nous n'avons pas pu supprimer cette adresse", null , false, false);
    			  }
    			},
    			error : function(statut){
    				Site.hideLoader();
    				System.alert("Nous n'avons pas pu supprimer cette adresse", null , false, false);
    			}
    		});
      },
	
	
	CreationAdresseLivraison: function() {
	   //on construit la chaÃ®ne de paramêtres	
		var params  = "type=livraison"
    params = params + "&nomAdresse=" + $("#ship-nom-adresse").val();
    params = params + "&civilite=" + $("#ship-civilite").val();  
    params = params + "&nom=" + $("#ship-nom").val();    
    params = params + "&prenom=" + $("#ship-prenom").val();    
    params = params + "&adresse1=" + $("#ship-adresse").val();    
    params = params + "&codepostal=" + $("#ship-cp").val();    
    params = params + "&adresse2=" + $("#ship-adresse2").val();      
    params = params + "&ville=" + $("#ship-ville").val();    
    params = params + "&adresse3=" + $("#ship-adresse3").val();    
    params = params + "&consignes=" + $("#ship-infos").val();    
    params = params + "&numerotelephone=" + $("#ship-tel").val();    
    params = params + "&numeromobile=" + $("#ship-cell").val();  
    if($("#ship-societe").css("display")=="block")
      params = params + "&nomEntreprise=" + $("#ship-societe").val(); 
    else
      params = params + "&nomEntreprise="; 
    params = params + "&addressIdent=false";

		$.ajax({
			url: "../Profil/profilWS.asmx/CreerAdresse",
			type: "POST",
			data: params,
			beforeSend: function(statut){
			  AddressForm.closeOnlyForm();
        Site.showLoader();
      },
			success: function(statut){
			  if( $('int', statut).text() == "0"){
			     System.alert("Votre nouvelle adresse a bien été enregistrée. Merci et bonne visite sur notre site", AddressForm.ReloadAddress , true, true);
			  }
			  else{
			     Site.hideLoader();
			     System.alert("La création d'adresse a échoué", null , false, false);
          }
			},
			error : function(statut){
				Site.hideLoader();
				System.alert("La création d'adresse a échoué", null , false, false);
			}
		});
	},
	
	CreationAdresseFacturation: function() {
	   //on construit la chaÃ®ne de paramêtres	
		var params  = "type=facturation"
    params = params + "&nomAdresse=" + $("#pay-nom-adresse").val();
    params = params + "&civilite=" + $("#pay-civilite").val();  
    params = params + "&nom=" + $("#pay-nom").val();    
    params = params + "&prenom=" + $("#pay-prenom").val();    
    params = params + "&adresse1=" + $("#pay-adresse").val();    
    params = params + "&codepostal=" + $("#pay-cp").val();    
    params = params + "&adresse2=" + $("#pay-adresse2").val();      
    params = params + "&ville=" + $("#pay-ville").val();    
    params = params + "&adresse3=" + $("#pay-adresse3").val();    
    params = params + "&consignes=";    
    params = params + "&numerotelephone=" + $("#pay-tel").val();    
    params = params + "&numeromobile=" + $("#pay-cell").val();  
    if($("#pay-societe").css("display")=="block")
      params = params + "&nomEntreprise=" + $("#pay-societe").val(); 
    else
      params = params + "&nomEntreprise="; 

    if ($("#pay-copyship").attr("checked") == true)
			params = params + "&addressIdent=true";
		else
			params = params + "&addressIdent=false"; 
	
		$.ajax({
			url: "../Profil/profilWS.asmx/CreerAdresse",
			type: "POST",
			data: params,
			beforeSend: function(statut){
			  AddressForm.closeOnlyForm();
        Site.showLoader();
      },
			success: function(statut){
			  if( $('int', statut).text() == "0"){
    			System.alert("Votre nouvelle adresse a bien été enregistrée. Merci et bonne visite sur notre site", AddressForm.ReloadAddress , true, true);
			  }
			  else{
			     Site.hideLoader();
			     System.alert("La création d'adresse a échoué", null , false, false);
			    }
			},
			error : function(statut){
				System.alert("La création d'adresse a échoué", null , false, false);
			}
		});
	},
	
	ModificationAdresseLivraison: function() {
	   //on construit la chaÃ®ne de paramêtres	
		var params  = "guidAddress=" + AddressForm.currentAddress
    params = params + "&type=livraison"
    params = params + "&nomAdresse=" + $("#ship-nom-adresse").val();
    params = params + "&civilite=" + $("#ship-civilite").val();  
    params = params + "&nom=" + $("#ship-nom").val();    
    params = params + "&prenom=" + $("#ship-prenom").val();    
    params = params + "&adresse1=" + $("#ship-adresse").val();    
    params = params + "&codepostal=" + $("#ship-cp").val();    
    params = params + "&adresse2=" + $("#ship-adresse2").val();      
    params = params + "&ville=" + $("#ship-ville").val();    
    params = params + "&adresse3=" + $("#ship-adresse3").val();    
    params = params + "&consignes=" + $("#ship-infos").val();    
    params = params + "&numerotelephone=" + $("#ship-tel").val();    
    params = params + "&numeromobile=" + $("#ship-cell").val();  
    if($("#ship-societe").css("display")=="block" || $("#ship-societe").css("display")=="inline")
      params = params + "&nomEntreprise=" + $("#ship-societe").val(); 
    else
      params = params + "&nomEntreprise="; 
    params = params + "&addressIdent=false";
    /*if ($("#autoconnect").attr("checked") == true)
			params = params + "&addressIdent=true";
		else
			params = params + "&addressIdent=false"; 
		*/
		$.ajax({
			url: "../Profil/profilWS.asmx/ModifierAdresse",
			type: "POST",
			data: params,
			beforeSend: function(statut){
			  AddressForm.closeOnlyForm();
        Site.showLoader();
      },
			success: function(statut){
			  if( $('int', statut).text() == "0")
			   	System.alert("Nous vous remercions d'avoir modifié cette adresse et nous vous confirmons que celle-ci a bien été modifiée", AddressForm.ReloadAddress , true, true);
			  else{
			    Site.hideLoader();
			    System.alert("La modification d'adresse a échoué", null , false, false);
			  }

			},
			error : function(statut){
				Site.hideLoader();
				System.alert("La modification d'adresse a échoué", null , false, false);
			}
		});
	},
	
	ModificationAdresseFacturation: function() {
	   //on construit la chaÃ®ne de paramêtres	
	  var params  = "guidAddress=" + AddressForm.currentAddress
    params = params + "&type=facturation"
    params = params + "&nomAdresse=" + $("#pay-nom-adresse").val();
    params = params + "&civilite=" + $("#pay-civilite").val();  
    params = params + "&nom=" + $("#pay-nom").val();    
    params = params + "&prenom=" + $("#pay-prenom").val();    
    params = params + "&adresse1=" + $("#pay-adresse").val();    
    params = params + "&codepostal=" + $("#pay-cp").val();    
    params = params + "&adresse2=" + $("#pay-adresse2").val();      
    params = params + "&ville=" + $("#pay-ville").val();    
    params = params + "&adresse3=" + $("#pay-adresse3").val();    
    params = params + "&consignes=";    
    params = params + "&numerotelephone=" + $("#pay-tel").val();    
    params = params + "&numeromobile=" + $("#pay-cell").val();  
    if($("#pay-societe").css("display")=="block")
      params = params + "&nomEntreprise=" + $("#pay-societe").val(); 
    else
      params = params + "&nomEntreprise="; 

    if ($("#pay-copyship").attr("checked") == true)
			params = params + "&addressIdent=true";
		else
			params = params + "&addressIdent=false"; 
	
		$.ajax({
			url: "../Profil/profilWS.asmx/ModifierAdresse",
			type: "POST",
			data: params,
			beforeSend: function(statut){
			  AddressForm.closeOnlyForm();
        Site.showLoader();
      },
			success: function(statut){
			  if( $('int', statut).text() == "0"){
			     System.alert("Nous vous remercions d'avoir modifié cette adresse et nous vous confirmons que celle-ci a bien été modifiée", AddressForm.ReloadAddress , true, true);
			  }
			  else{
			    Site.hideLoader();
			    System.alert("La modification d'adresse a échoué", null , false, false);
			  }
			},
			error : function(statut){
				Site.hideLoader();
				System.alert("La modification d'adresse a échoué", null , false, false);
			}
		});
	},
	
	ReloadAddress: function() {
	
			if ($("#ChoixAdresse-member-space-info").html() != null){ //détermine si page ChoixAdresse.aspx 
				sUrl = "PanierWS.asmx/ChargementInformationAdresseCMD";
				sData = "iShippingCodeServ=" + iShippingCodeServ; ////Variable init dans aspx
			}
			else {
				sUrl = "profilWS.asmx/ChargementInformationAdresse";
				sData = "";
			}

			$.ajax({
			url: sUrl,
			type: "POST",
			dataType: "xml",
			data: sData,
			beforeSend: function(){
			Site.showLoader();
			},
			success: function(html){
				if ($("#ChoixAdresse-member-space-info").html() != null){ //détermine si page ChoixAdresse.aspx 
					$("#ChoixAdresse-member-space-info").html($("resultHTML",html).text());			
					if ($("Message", html).text() != ""){
						System.alert($("Message", html).text(), null, null);
					}

					if($("Code", html).text() == "PANIER_INVALIDE"){
						$("a.continue").hide();
					}
					
					if($("ValeurTotalCommande", html).text() != ""){
						$("div.amount").html($("ValeurTotalCommande", html).text());
					}
				}
				else {
					$("#member-space-info").html($("resultHTML",html).text());
				}
				
				CustomFields.init('radio', '#member-space', CustomFields.onChange);
				CustomFields.init('checkbox', '#member-space', CustomFields.onChange); 
				CustomFields.init('select', '#member-space'); 
				AddressForm.init();
				FormValidation.init();
				Site.hideLoader();
			},
			error : function(html){
                Site.hideLoader();
                System.alert("Une erreur s'est produite...", null, null);
        	}
		});  
	}
	
};


/**
* AvantagesForm
*/
var AvantagesForm = {
	
	
	init: function() {
        $("#avantages #avantage-star .submit").click(AvantagesForm.submitCarteAvantages);
        $("#avantage-form .submit").click(AvantagesForm.submitCarteAvantages);
        $("#avantage-star p.ProfilIncompatible").hide();
	},
	
	submitCarteAvantages : function(){
        /* appel ajax */
		$.ajax({
			url: "profilWS.asmx/RattachementCarte",
			type: "POST",
			dataType: "xml",
			data: "numeroCarte=" + $("#cardnumber").val() + "&nom=" + $("#nom").val() + "&prenom=" + $("#prenom").val() + "&codePostal=" + $("#codepostal").val(),
			success: function(xmlResultat){
                //on teste d'abord la redirection
                if ($("UrlRedirection", xmlResultat).text() != "")
                    document.location.href = $("UrlRedirection", xmlResultat).text();
                else{
                    //on affiche l'éventuel message d'erreur
                    $(".error").html($("MsgErreur", xmlResultat).text());
                    
                    //on teste l'affichage du pavé de saisie du numéro de carte
                    if ($("AffichagePaveCarte", xmlResultat).text() == "True"){
                        $("#avantage-star p.ProfilIncompatible").hide();
                        $("#avantage-star p.ProfilCompatible").show();
                        $("#avantage-star fieldset").show();
                        $("#avantage-star input").show();
                        
                        //on teste l'affichage du pavé de saisie des infos personnelles
                        if ($("AffichagePaveInfosPersos", xmlResultat).text() == "True"){
                            //on initialise les champs de saisie des infos personnelles...
                            $("#nom").val($("Nom", xmlResultat).text());
                            $("#prenom").val($("Prenom", xmlResultat).text());
                            $("#codepostal").val($("CodePostal", xmlResultat).text());
                            
                            //... et on ouvre le layer contenant ces champs
                            AvantagesForm.open();
                        }
                                                
                    }
                    else{
                        $("#avantage-star p.ProfilIncompatible").show();
                        $("#avantage-star p.ProfilCompatible").hide();
                        $("#avantage-star fieldset").hide();
                        $("#avantage-star input").hide();
                    }
                }
			},
			error: function(html){
                System.alert("Un problème est survenu pendant le rattachement, veuillez ré-essayer plus tard", null, null);
			}
		});
    },
	
	/**
	 * Make the form to appear.
	 */
	open: function() {		
		if($("#avantage-form")){
			Site.createFreeze();
			$("#avantage-form").fadeIn();
			$("#avantage-form a.close").click(AvantagesForm.close);
			$("#freeze").click(AvantagesForm.close);
		}

		return false;
	},
	
	/**
	 * Make the form to dissappear
	 */
	close: function() {
		$("#avantage-form").fadeOut("normal", Site.destroyFreeze);
		return false;
	}
};

/**
 * The Foldable Content object manage some
 * foldable content bloc like the shipping history.
 * 
 * The init function register the required event. The toggle function
 * open or close the content regarding to the actual state
 */
var FoldableContent = {
	init: function() {
		$("a.foldingbtn").click(FoldableContent.toggle);
	},
	
	toggle: function(){
		content = $(this).siblings(".foldable");
		if($(this).siblings(".foldable:visible").length != 0){
			content.slideUp();
			$(this).removeClass("down");
		} else {
			content.slideDown();
			$(this).addClass("down");
		}
		this.blur();
		return false;
	}
};

var GestionCookies = {
  SetCookie : function(name, value) {
		var argv=GestionCookies.SetCookie.arguments;
		var argc=GestionCookies.SetCookie.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=name+"="+escape(value)+
			((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
			((path==null) ? "" : ("; path="+path))+
			((domain==null) ? "" : ("; domain="+domain))+
			((secure==true) ? "; secure" : "");
	},// end function
	
	
	getCookieVal : function(offset) {
		var endstr=document.cookie.indexOf (";", offset);
		if (endstr==-1)
  				endstr=document.cookie.length;
		return unescape(document.cookie.substring(offset, endstr));
	},// end function
	
	GetCookie : function(name) {
		var arg=name+"=";
		var alen=arg.length;
		var clen=document.cookie.length;
		var i=0;
		while (i<clen) {
			var j=i+alen;
			if (document.cookie.substring(i, j)==arg)
							return GestionCookies.getCookieVal (j);
					i=document.cookie.indexOf(" ",i)+1;
							if (i==0) break;}
		return null;
	},
	
	DeleteCookie : function(name) {
    var exp=new Date();
    exp.setTime (exp.getTime() - 100000);
    var cval=GestionCookies.GetCookie(name);
    document.cookie=name+"="+cval+"; expires="+exp.toGMTString();
  } 
};

/**
 * The System object emulate some javascript native functions like confirm or alert.
 */
var System = {
		noFreeze:false,
	/**
	 * Try to make the customised confirm box to appear with the specified message
	 * When hitting OK, the validateCallBack will be executed. When hiting cancel, the cancelCallBack will be executed.
	 * If the custom confirm box can't be found in the page's DOM, the default one is use instead
	 * @param {String} message
	 * @param {Function} validateCallBack
	 * @param {Function} cancelCallBack
	 */
	confirm: function(message, validateCallBack, cancelCallBack, keepFreezeAfterValide) {
		if($("#system-popin").length > 0){
			$("#system-popin #system-popin-content p").html(message);
			
			$("#system-popin a").unbind();
			$("#system-popin a.validate").click(function(){
			  if(keepFreezeAfterValide) 
          System.closeConfirmOnly();
        else
          System.closeConfirm();
				if(jQuery.isFunction(validateCallBack))validateCallBack();
			});
			$("#system-popin a.cancel").click(function(){
				if(jQuery.isFunction(cancelCallBack))cancelCallBack();
				System.closeConfirm();
			});
			
			if($("#freeze:visible").length == 0){
				Site.createFreeze();
			} else {
				System.noFreeze = true;
			}
			$("#system-popin").fadeIn();			
		} else {
			// if the HTML implementation is wrong, we use the default confirm box
			if(confirm(message)){
				if(jQuery.isFunction(validateCallBack))validateCallBack();
			} else {
				if(jQuery.isFunction(cancelCallBack))cancelCallBack();
			}
		}
	},
	
	/**
	 * Try to make the customised alert box to appear with the specified message
	 * When hitting OK, the validateCallBack will be executed.
	 * If the custom alert box can't be found in the page's DOM, the default one is use instead
	 * @param {String} message
	 * @param {Function} validateCallBack
	 * @param {Boolean} noFreze If specified and equals to true, the freeze layer won't be displayed. Default is set to false
	 */
	alert: function(message, validateCallBack, noFreeze, keepFreezeAfter) {
		if($("#alert-popin").length > 0){
		  if(!($("#loader").hasClass("hidden"))) $("#loader").addClass("hidden");
			$("#alert-popin #alert-popin-content p").html(message);
			
			$("#alert-popin a").unbind();
			$("#alert-popin a.close").click(function(){
			  if(keepFreezeAfter) 
          System.closeAlertOnly();
        else
          System.closeAlert();
				if(jQuery.isFunction(validateCallBack))validateCallBack();
			});
			
			if(!noFreeze) Site.createFreeze();
			$("#alert-popin").fadeIn();			
		} else {
			// if the HTML implementation is wrong, we use the default confirm box
			alert(message);
			if(jQuery.isFunction(validateCallBack))validateCallBack();
		}
	},
	
	/**
	 * Called whenever the ok button nor the cancel button is clicked
	 */
	closeConfirm: function() {
		if (System.noFreeze == false) {
			$("#system-popin").fadeOut("normal", Site.destroyFreeze);
		} else {
			$("#system-popin").fadeOut("normal");
		}
		
		System.noFreeze = false;
	},
	
	closeConfirmOnly: function() {
			$("#system-popin").fadeOut("normal");
			Site.showLoader();
	},
	
	/**
	 * Quand il y a un traitement qui continue on appelle closeAlertOnly
	 * Le traitement s'occupera d'enlever le voile	 
	 */
	closeAlertOnly: function() {
			$("#alert-popin").fadeOut("normal");
			Site.showLoader();
	},
	
	closeAlert: function() {
		if (System.noFreeze == false) {
			$("#alert-popin").fadeOut("normal", Site.destroyFreeze);
		} else {
			$("#alert-popin").fadeOut("normal");
		}
		
		System.noFreeze = false;
	}
};


/**
 * The DisplaySelectedCard Object provide a way to display the selected card
 */
var DisplaySelectedCard = {

	/**
	 * Called by the onchange event on select element (register by the CustomField Object).
	 * Change the visual and display the selected card
	 */
	open: function() {
	  var libelleImg = ""
	  switch (this.field.value)
    {
    case '1': libelleImg = "visa"; break;
    case '2': libelleImg = "mastercard"; break;
    case '3': libelleImg = "cb"; break;
    case '4': libelleImg = "american-expr"; break;
    case '6': libelleImg = "fnac"; break;
    case '7': libelleImg = "printemps"; break;
    case '9': libelleImg = "cyrillus"; break;
    } 
		if((this.field.id=="cardType") || (this.field.id=="cardTypePartenaire")) {
			if(typeof document.body.style.maxHeight != 'undefined') {
				// For credit card
				if($("#visual").hasClass("credit-card")) $("#payment .credit-card").css("background-image", 'url(../img/payment-visual-'+libelleImg+'.png)');
				// For partner card
				else $("#payment .partner-card").css("background-image", 'url(../img/payment-visual-'+libelleImg+'.png)');
			}
			// For IE6
			else {
				document.getElementById("visual").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/payment-visual-"+libelleImg+".png',sizingMethod='scale')";
				//document.getElementById("visual").style.background = "url(img/payment-visual-"+this.field.value+".png)";
			}
			
			SC.fixPNG.init();
		}
	}
};

/*********PANIER***************/
var Panier = {
	
	//initialisation panier
 	init : function (){
 		
 		if ($("#DetailPanier").html() != null){ //détermine si page panier
 			
 			if(sFidErreur == ""){  //init dans page aspx
				Panier.PerformActionAndLoadBasket("", "", "", "true");
			}
			else {
				Panier.PerformActionAndLoadBasket("FIDRecalculerTout", "", "", "true");
				System.alert("Vous pouvez passer votre commande mais vos avantages sont désactivés.", null, null);
			}
			if (sPUP != ""){
				System.alert(sPUP, null, null);
			}
		}
		
	},
	
	initLivraison : function(){
        $("#RB_choixModeDomicile").click(Panier.clickDomicile);
        $("#RB_choixModeMagasin").click(Panier.clickMagasin);
        $("#SL_choixDomicile").change(Panier.recalculLivraisonTypeDomicile);
        $("#SL_choixMagasin").change(Panier.recalculLivraisonTypeMagasin);
        if ($("#RB_choixModeDomicile").attr("checked") > 0)
            Panier.visualiseModesDomicile();
        if ($("#RB_choixModeMagasin").attr("checked") > 0)
            Panier.visualiseModesMagasin();
        CgvAcceptation.init();
        $("#orderbtn").click(Panier.verifAcceptationCGV);
    },
    clickDomicile : function(){
        Panier.visualiseModesDomicile();
        Panier.recalculLivraisonTypeDomicile();
    },
    clickMagasin : function(){
        Panier.visualiseModesMagasin();
        Panier.recalculLivraisonTypeMagasin();
    },
    visualiseModesDomicile : function(){
        $("#SL_choixDomicile").show();
        $("#SL_choixDomicile").next().show();
        $("#SL_choixMagasin").hide();
        $("#SL_choixMagasin").next().hide();
    },
    visualiseModesMagasin : function(){
        $("#SL_choixDomicile").hide();
        $("#SL_choixDomicile").next().hide();
        $("#SL_choixMagasin").show();
        $("#SL_choixMagasin").next().show();
    },
    recalculLivraisonTypeDomicile : function(){
        var codeChoisiDomicile = Panier.recupereChoixLivraisonDomicile();
//alert("codeChoisiDomicile = " + codeChoisiDomicile);
        Panier.RecalculerFraisDePort(codeChoisiDomicile, $("#RB_choixModeDomicile").val());
    },
    recalculLivraisonTypeMagasin : function(){
        var codeChoisiMagasin = Panier.recupereChoixLivraisonMagasin();
//alert("codeChoisiMagasin = " + codeChoisiMagasin);
        Panier.RecalculerFraisDePort(codeChoisiMagasin, $("#RB_choixModeMagasin").val());
    },
    recupereChoixLivraisonDomicile : function(){
        var libChoisi = $("#SL_choixDomicile").next().children("span:first").html();
        var tab = $("#SL_choixDomicile").children("option");
        var i;
        
        for (i = 0; i < tab.length; i++){
            if ($(tab[i]).html() == libChoisi)
                return $(tab[i]).val();
        }
    },
    recupereChoixLivraisonMagasin : function(){
        var libChoisi = $("#SL_choixMagasin").next().children("span:first").html();
        var tab = $("#SL_choixMagasin").children("option");
        var i;
        
        for (i = 0; i < tab.length; i++){
            if ($(tab[i]).html() == libChoisi)
                return $(tab[i]).val();
        }
    },
    verifAcceptationCGV : function(){
    
        if ($("#cb_cgv_site").next().children("div").hasClass("checked")){

			var bValidePage = false;
			var TblInputCheckBox = $("#cb_cgv_carte");
	
			if(TblInputCheckBox.length > 0){  //test si case ?ocher acceptation carte @avantage pr?nt
			
				if(TblInputCheckBox[0].checked)
					bValidePage = true;
				else{
					//on positionne le pop-up d'erreur légèrement au-dessus de la case à cocher des CGV
					var offset = $("#cb_cgv_site").offset();
					var top = offset.top - 100;
					$("#alert-popin").css("top", top);
					System.alert("Vous devez auparavant valider les conditions g&eacute;n&eacute;rales de la Carte @vantages pour continuer la commande", null, null);
				}
			}
			else{
				bValidePage = true;
			}
			
			if(bValidePage) //infos page OK, page suivante
				document.location.href = $("#orderbtn").val();
		}
        else{
            //on positionne le pop-up d'erreur légèrement au-dessus de la case à cocher des CGV
			var offset = $("#cb_cgv_site").offset();
			var top = offset.top - 100;
			$("#alert-popin").css("top", top);
			System.alert("Vous devez auparavant valider les conditions g&eacute;n&eacute;rales de vente pour continuer la commande", null, null);
        }
    },
    /********************************************************************************
    '********************************************************************************
    ' Nom Fonction: appel web service fonction PerformActionAndLoadBasket
    ' Description:  gestion du panier appel combascket
    '    
    ' IN: sTypeAction, action à réaliser sur le panier, pour pcbysurcouf "ADDPCBYSURCOUF" 
    '					les anciennes actions sont toujours valable
    '       sRefSurcouf, ref du ou des produits  exemple "999999_88888_55555"
    '					  dans le cas de PCbysurcouf la dernière ref est la config
    '       sQuantites, quantités produit exemple "4_5_6" dans le cas d'une mise au panier
    '					et dans le cas de pcbysurcouf la quantité de la config sera Ã  1 quelque soit la valeur, 
    '					si valeurs pas présentes tout est fixé Ã  1. 
    '                   pour recalcul la quantité est de la forme "4|2|6" et dans l'ordre des quantités dans combasket
    '       bDetailPanier, renvoi ou pas le contenu du panier
    '********************************************************************************
    '********************************************************************************/

  	PerformActionAndLoadBasket :	function (sTypeAction, sRefSurcouf, sQuantites, bDetailPanier){
        Site.showLoader();
        var codeChoisi;
        var typeLivraisonChoisi;
        if ($("#RB_choixModeDomicile").attr("checked") > 0){
            codeChoisi = Panier.recupereChoixLivraisonDomicile();
            typeLivraisonChoisi = $("#RB_choixModeDomicile").val();
        }
        else if ($("#RB_choixModeMagasin").attr("checked") > 0){
            codeChoisi = Panier.recupereChoixLivraisonMagasin();
            typeLivraisonChoisi = $("#RB_choixModeMagasin").val();
        }
        else{
            codeChoisi = "-1";
            typeLivraisonChoisi = "";
        }
        
  			/* appel ajax*/
  			$.ajax({
				url: "PanierWS.asmx/PerformActionAndLoadBasket",
				type: "POST",
				dataType: "xml",
				data: "sTypeAction=" + sTypeAction + "&sRefSurcouf=" + sRefSurcouf + "&sQuantites=" + sQuantites + "&bDetailPanier=" + bDetailPanier + "&shippingCode=" + codeChoisi + "&typeLivraison=" + typeLivraisonChoisi,

				success: function(html){
						/*init bloc*/
						if ($("Message", html).text() != ""){
							System.alert($("Message", html).text(), null, null);
						}
												
						//infos mini panier
						$("#Entete_LB_Nb_Article").html($("NbArticles", html).text());
						$("#Entete_LB_Total_Panier").html($("TotalBasket", html).text());
						$("#minicart p").html($("AvantagesPanier", html).text());
						
						//init infos sur layer de validation discountday
						var sAffichageDiscountDay  =  "<li>une remise de " ;
				        
						sAffichageDiscountDay += $("PourcentageRemiseAvDiscountDayActif", html).text() + "% sur cette commande, en &euro;-@vantages utilisables pour un prochain achat</li>";
						sAffichageDiscountDay += "<li>Soit " + $("MontantRemiseAvDiscountDayActif", html).text() + "&euro;, correspondant &agrave; ";
						sAffichageDiscountDay += $("EurosAvantagesDiscountDayActif", html).text() + "&euro; utilisables pour un prochain achat et ";
						sAffichageDiscountDay += $("PointsDiscountDayActif", html).text() + " points restants.</li>";

						$("#cart-avantage-content ul").html(sAffichageDiscountDay);
	
						var TblTd = $("#cart-avantage-content td");
						
						if(TblTd.length > 1){
							TblTd[0].innerHTML = $("EurosAvantagesDiscountDayActif", html).text();
							TblTd[1].innerHTML = $("PointsDiscountDayActif", html).text();
						}

						if ($("LivraisonCodeErreur", html).text() != 0){
  							if ($("LivraisonCodeErreur", html).text() == -2)
  								//on gère le cas spécifique du code -2
  								document.location.href = "../profil/listeadresse.aspx?returnURL=../panier/livraison.aspx&Erreur=ADR";
  							else
  								//on gère les autres cas par un rechergement de la page Panier.aspx
  								document.location.href = "panier.aspx";
  				    
  							//c'est un cas d'erreur, on sort de la fonction
  							return;
						}  
						
						$(".cartcell.shipping.overall").show();
						
						if (($("Code", html).text() == "PANIER_OK") || ($("Code", html).text() == "PANIER_INVALIDE") 
							|| ($("Code", html).text() == "PANIER_VIDE")){
							
							$("#DetailPanier").html($("DetailPanier", html).text());
							$("#SousTotal").html($("SousTotal", html).text());
							$("#Totalpromo").html($("Totalpromo", html).text());
							$("#TotalCommande").html($("TotalCommande", html).text());
							
							$("#CarteAvantagePanier").html($("CarteAvantagePanier", html).text());
							$("#AvantagesCarteAvantage").html($("AvantagesCarteAvantage", html).text());
							
							//carte avantage mise au panier
							if($("CarteAvantagePanier", html).text() != ""){

								$("#CarteAvantagePanier").addClass("cartcell shipping overall");
   								
   								//even sur carte avantage au panier
								$("#CarteAvantagePanier").click(Panier.clickCarteAvantagePanier);
							}
							else {
								$("#CarteAvantagePanier").removeClass("cartcell shipping overall");
   							}
							
							//avantages carte avantage page panier
							if($("AvantagesCarteAvantage", html).text() != ""){
							
   								$("#AvantagesCarteAvantage").addClass("cartcell avantages");
								//even sur avantages carte avantage
								$(".cartcell.avantages").click(AvantagesActivation.open);
							}
							else {
   								$("#AvantagesCarteAvantage").removeClass("cartcell avantages");
   							}

							//on affiche le pavé Livraison
							$("#Livraison").html($("PaveLivraison", html).text());
                            
							//on affiche le pavé Validation
							$("#order").html($("PaveValidation", html).text());
							
							FormatLabelProduit();
                            					
							/*association event aux éléments*/
							QuantityField.init(); //init fonction incrementation décrémentation
							CartDetail.init(); //init fonction event détail config
							$(".cartcell a.deletebtn").click(Panier.onDeleteBtnClick);
							$("a.submitFormRecalc").click(Panier.valideEnterRecalcul);
							$("div.promo a").click(Panier.submitFormCodeAvantage);
							$("#codepromo").keyup(function(event){Panier.valideEnterCA(event);});
							
							CustomFields.init('radio', '#FormCaddie', CustomFields.onChange, '.hide');
							CustomFields.init('checkbox', '#FormCaddie', CustomFields.onChange, '.hide');
							CustomFields.init('select', '#FormCaddie');

                            
							//on ré-initialise les liens entre le HTML généré et les fonctions JavaScript associées
							Panier.initLivraison();;
                            
							if(($("Code", html).text() == "PANIER_VIDE") || ($("Code", html).text() == "PANIER_INVALIDE")){
								//on adapte l'affichage de la zone Livraison en cas de panier vide ou invalide
								$("#Livraison").removeClass("cartcell");
                                
								if ($("Code", html).text() == "PANIER_VIDE"){
    								//on adapte l'affichage des différentes zones en cas de panier vide
    								$("#SousTotal").removeClass("cartcell");
    								$("#SousTotal").removeClass("grey");
    								$("#Totalpromo").removeClass("cartcell");
    								$("#TotalCommande").removeClass("detailled-amount");
    							}
    							else{
									//on adapte l'affichage des différentes zones en cas de panier invalide
									$("#SousTotal").addClass("cartcell");
    								$("#SousTotal").addClass("grey");
    								$("#Totalpromo").addClass("cartcell");
    								$("#TotalCommande").addClass("detailled-amount");
								}
							}
							else{
								//le panier est OK ==> on adapte l'affichage des différentes zones
								$("#SousTotal").addClass("cartcell");
								$("#SousTotal").addClass("grey");
								$("#Totalpromo").addClass("cartcell");
								$("#TotalCommande").addClass("detailled-amount");
								
								if ($("PaveLivraison", html).text() == ""){
									//le pavé Livraison est vide ==> il n'y a pas de mode de livraison disponible ==> on cache le bouton qui permet de poursuivre sur la page suivante et on adapte l'affichage de la zone Livraison
									$("#orderbtn").hide();
									$("#Livraison").removeClass("cartcell");
								}
								else{
									//le pavé Livraison existe ==> on adapte l'affichage de la zone Livraison
									$("#Livraison").addClass("cartcell");
                      
									//on affiche le montant total et les frais de port dans le pavé TotalCommande
									var TblInfosCommande = $("#TotalCommande .amount");

      								if(TblInfosCommande.length > 3){
										TblInfosCommande[0].innerHTML = $("MontantTotal", html).text();
           								TblInfosCommande[2].innerHTML = $("TVA", html).text();
										TblInfosCommande[3].innerHTML = $("MontantFraisPort", html).text();
										
										if((TblInfosCommande.length > 4) && ($("MontantTotalTTC", html).text() != "")){ //dans le cas d'un compte B2B
											TblInfosCommande[4].innerHTML = $("MontantTotalTTC", html).text();
											}
									}

									//$("#TotalCommande .amount:first").html($("MontantTotal", html).text());
									//$("#TotalCommande .amount:last").html($("MontantFraisPort", html).text());
                      
									//et on ré-initialise le lien vers la page ChoixAdresses.aspx avec le bon shippingCode en paramêtre
									//$("#orderbtn").attr("href", "../panier/choixadresses.aspx?iShippingCodeServ=" + $("CodeServSelectionne", html).text());
									$("#orderbtn").val("../panier/choixadresses.aspx?iShippingCodeServ=" + $("CodeServSelectionne", html).text());
								}
							}						
						}
						else{
							//cas  PB profil pas authentifi?u compte B2B ou pas date de naissance
							//on redirige sur page compte pour le control et affichage message
							//Dim URLAbsolue As String = Request.Url.AbsolutePath
                            //Response.Redirect("../profil/profil.aspx?Compte=ADH&ReturnUrl=" & URLAbsolue)
							if (($("Code", html).text() == "USER_PB_PROFIL")){
								
								document.location.href = "../Profil/compte.aspx?page=modif_XXX_compte=ADH_XXX_ReturnUrl=../Panier/panier.aspx";
							}
							else 
								if(sTypeAction == "ADDREFCARTE"){
									$("#sans-financement").next().children("div").removeClass("checked");
									$("#avec-financement").next().children("div").removeClass("checked");
								}
						}

						SC.fixPNG.init();	
						Site.hideLoader();

				},
				error : function(html){
					System.alert("Action panier échouée!", null, null);
				}
			});
	},
	
	//fonction mise au panier carte avantage
	clickCarteAvantagePanier : function(){

		if ($("#sans-financement").next().children("div").hasClass("checked")){

				// 1 sans financement option
				$(".cartcell.shipping.overall").hide();

				$("#sans-financement").next().children("div").removeClass("checked");
				$("#avec-financement").next().children("div").removeClass("checked");

				Panier.PerformActionAndLoadBasket("ADDREFCARTE", "1", "", "true"); 
		}
		else if ($("#avec-financement").next().children("div").hasClass("checked")){

				// 2 avec financement option
				$(".cartcell.shipping.overall").hide();

				$("#sans-financement").next().children("div").removeClass("checked");
				$("#avec-financement").next().children("div").removeClass("checked");
 
				Panier.PerformActionAndLoadBasket("ADDREFCARTE", "2", "", "true"); 
		}
	},
	
	//fonction activation discount day
	ActivationDiscountDay : function(){

		Panier.PerformActionAndLoadBasket("ACTIVEDISCOUNTDAY", "", "", "true"); 
	},

	RecalculerFraisDePort : function(shippingCode, typeLivraison){
        Site.showLoader();
		/* appel ajax*/
		$.ajax({
			url: "PanierWS.asmx/RecalculerFraisDePort",
			type: "POST",
			dataType: "xml",
			data: "shippingCode=" + shippingCode + "&typeLivraison=" + typeLivraison,

			success: function(html){
                //on affiche le message d'erreur s'il existe
                if ($("MsgErreur", html).text() != ""){
        				    System.alert($("MsgErreur", html).text(), null, null);
        				}
        				
        				if ($("LivraisonCodeErreur", html).text() != 0){
        				    if ($("LivraisonCodeErreur", html).text() == -2)
        				        //on gère le cas spécifique du code -2
        				        document.location.href = "../profil/listeadresse.aspx?returnURL=../panier/livraison.aspx&Erreur=ADR";
        				    else
        				        //on gère les autres cas par un rechergement de la page Panier.aspx
        				        document.location.href = "panier.aspx";
        				    
        				    //c'est un cas d'erreur, on sort de la fonction
        				    return;
                }
        				
                //on affiche le pavé Livraison
                $("#Livraison").html($("PaveLivraison", html).text());
                
                //on affiche le pavé Validation
                $("#order").html($("PaveValidation", html).text())
                
                if ($("PaveLivraison", html).text() == ""){
                    //le pavé Livraison est vide ==> il n'y a pas de mode de livraison disponible ==> on cache le bouton qui permet de poursuivre sur la page suivante et on adapte l'affichage de la zone Livraison
                    $("#orderbtn").hide();
                    $("#Livraison").removeClass("cartcell");
                }
                else{
                     //le pavé Livraison existe ==> on adapte l'affichage de la zone Livraison
                    $("#Livraison").addClass("cartcell");
                    
                    //on affiche le montant total et les frais de port dans le pavé TotalCommande
              		var TblInfosCommande = $("#TotalCommande .amount");
              		
              		if(TblInfosCommande.length > 3){
        				TblInfosCommande[0].innerHTML = $("MontantTotal", html).text();
                   		TblInfosCommande[2].innerHTML = $("TVA", html).text();
        				TblInfosCommande[3].innerHTML = $("MontantFraisPort", html).text();
        				
        				if((TblInfosCommande.length > 4) && ($("MontantTotalTTC", html).text() != "")) //dans le cas d'un compte B2B
        					TblInfosCommande[4].innerHTML = $("MontantTotalTTC", html).text();
        			}
                    
                    
                    //et on ré-initialise le lien vers la page ChoixAdresses.aspx avec le bon shippingCode en paramètre
                    //$("#orderbtn").attr("href", "../panier/choixadresses.aspx?iShippingCodeServ=" + $("CodeServSelectionne", html).text());
                    $("#orderbtn").val("../panier/choixadresses.aspx?iShippingCodeServ=" + $("CodeServSelectionne", html).text());
                }
                		
                CustomFields.init('radio', '#FormCaddie', CustomFields.onChange, '.hide');
                CustomFields.init('checkbox', '#FormCaddie', CustomFields.onChange, '.hide');
                CustomFields.init('select', '#FormCaddie');
                Panier.initLivraison();
                CartDetail.init();
                				
				Site.hideLoader();
			},
			error : function(html){
				System.alert("Action recalcul des frais de port échouée!", null, null);
			}
		});
    },
	
	//event supp produit
	onDeleteBtnClick: function() {
		var RefSurcouf = $(this).attr("ref");
		System.confirm("Voulez vous supprimer cet article ?",  function (){Panier.onSupprimeRef(RefSurcouf)}, null, true);
	},
	
	//supp produit
	onSupprimeRef : function (sRef){
		Panier.PerformActionAndLoadBasket("REMREF", sRef, "", "true");
	}, 
	
	//recalcul le panier en fonction des quantités dans l'ordre name=quantiteNÂ°ligneCombasket
	valideEnterRecalcul : function (){
	
		var sQuantitePipes = "";
		var iCptQt = 0;
		var iNumQuantite = 1;
		var TblInputQuantites = $("input.quantity");
		var sNumQuantite = "" ;
		var bValideProduit = false;
	
		if(TblInputQuantites.length > 0){
			
			while (iCptQt >= 0) {	
			
				sNumQuantite = "quantite" + iNumQuantite;
				bValideProduit = false;
				
				for(i = 0; i < TblInputQuantites.length; i++){
					
					if(TblInputQuantites[i].name == sNumQuantite){
						if (sQuantitePipes != "") {
							sQuantitePipes = sQuantitePipes + "|"; //ajout séparateur
						}
						
						sQuantitePipes = sQuantitePipes + TblInputQuantites[i].value; //ajout quantité
						
						bValideProduit = true; //produit réel
						iCptQt = iCptQt + 1;
					}
				}
				
				iNumQuantite = iNumQuantite + 1;
				
				if(! bValideProduit){
				//sinon si n'existe pas dans le tableau des éléments il y a des éléments de config quantité non prise en compte par le comBasket mais recalculé par rapport Ã  la quantité de config
				//mais une quantité fictive doit Ãªtre présente
						if (sQuantitePipes != "") {
							sQuantitePipes = sQuantitePipes + "|"; //ajout séparateur
						}
						
						sQuantitePipes = sQuantitePipes + "1"; //ajout quantité
						
				}
				
				if(TblInputQuantites.length <= iCptQt){ //tous les éléments du tableau ont été pris en compte on sort du while
					iCptQt = -1
				}
			}
		}
		
		//alert(sQuantitePipes);

		Panier.PerformActionAndLoadBasket("RECALC", "", sQuantitePipes, "true"); //appel combasket
	},
	//ajout code avantage par la touche enter
	valideEnterCA : function(e) {

		if(e.keyCode == 13){
			Panier.submitFormCodeAvantage();
		}
	},

	//ajout code avantage
	submitFormCodeAvantage : function (){
		var sCodeAvantage = ""
		
		if($("#codepromo").length>0){
			sCodeAvantage = $("#codepromo")[0].value;
	
			//alert(sCodeAvantage);

			Panier.PerformActionAndLoadBasket("ADDCAV", sCodeAvantage, "", "true"); //appel combasket
		}
	}



};
/*********FIN PANIER***************/

/*********CHOIX ADRESSES CMD*******************/
var	iShippingCodeServ = 0;

var ChoixAdressesCMD = {

	init : function(){
		if ($("#ChoixAdresse-member-space-info").html() != null){ //détermine si page ChoixAdresse.aspx
		  	iShippingCodeServ = $("#ShippingCodeServ")[0].value; // init variable global utilisée par d'autre object
			AddressForm.ReloadAddress();
		}
	}
};
/*********FIN CHOIX ADRESSES CMD*******************/

/*********CONFIRMATION CMD*******************/

var ConfirmCMD = {

	init : function(){
	
		if ($("#Confirm-member-space-info").html() != null){ //détermine si page confirm.aspx
		
			var sFlagCarteFid = $("#FlagCarteFid")[0].value; // init variable
			FormatLabelProduit();
			
			if(sFlagCarteFid == "1")
			{
				window.open('http://www.cartesurcouf.com/'); //page de finaref
			}
		}
	}
};

/*********CONFIRMATION CMD*******************/


var ListeCommande = {
	// collections et accesseurs
	accItems:undefined,
	
	// options
	// lite:undefined, -- For future enhancement
	
	/**
	 * The init method register the required listener on the different observable elements,
	 * and then hide the two menus
	 */
	init : function(){
			ListeCommande.accItems = $("div.commands div.content table tr");
			$(ListeCommande.accItems).children("td").children("a").click(ListeCommande.onItemDetailCommande);
	},

	
	onItemDetailCommande : function(e) {
	    numCommande= $(this).parents("tr").children("td").children("a").html();
	  	$.ajax({
        url: "profilWS.asmx/ChargementDetailCommande",
        type: "POST",
        data: "orderNumber="+numCommande,
        beforeSend: function(){
          Site.showLoader(); 
  			},
        success: function(html){
    			$("#member-space-info").html($("resultHTML",html).text());
          FoldableContent.init();
          CartDetail.init();
          FormatLabelProduit();
          $(AccordionNavigation.currentItem).removeClass("on");
          AccordionNavigation.currentItem = undefined;
					$(".retourliste").click( function(){
    			  $("ul.accordion-like  #mes_commandes").click();
    			  return false;
          });
          SC.fixPNG.init();	
          Site.hideLoader();	
  			},
  		error : function(html){
            Site.hideLoader();
            System.alert("Une erreur s'est produite...", null, null);
    	}
  	  });
		return false; // Le navigateur ne suit pas le lien
	}
};


var CgvAcceptation = {

	/**
	 * Initialisation
	 */
	init: function() {
			$("#btn_cgv_site").click(CgvAcceptation.openCGV);
			$("#btn_cgv_carte").click(CgvAcceptation.openCarte);
	},
	
	/**
	 * Make the form to appear.
	 */
	openCGV: function() {
		if ($("#information-popin").length > 0)
		{
			$("#information-popin a.close").click(CgvAcceptation.close);
			var offset = $("#btn_cgv_site").offset();
			var top = offset.top - 100;
			$("#information-popin").css("top", top);
			Site.createFreeze();
			$.get("../HTML/CGV/cgv.html", {parametre_get:"valeur_param_get_1"}, 
				function(data) {
					$("#information-popin #information-popin-content").html(data);
					}
				);
			$("#information-popin").fadeIn();
		}
		return false;
	
	},

	openCarte: function() {
		if ($("#information-popin").length > 0)
		{
			$("#information-popin a.close").click(CgvAcceptation.close);
			var offset = $("#btn_cgv_site").offset();
			var top = offset.top - 100;
			$("#information-popin").css("top", top);
			Site.createFreeze();
			$.get("../HTML/CGV/carte.html", {parametre_get:"valeur_param_get_1"}, 
				function(data) {
					$("#information-popin #information-popin-content").html(data);
					}
				);
			$("#information-popin").fadeIn();
		}
		return false;
	
	},	
	/**
	 * Make the form to dissappear
	 */
	close: function() {
		if (System.noFreeze == false) {
			$("#information-popin").fadeOut("normal", Site.destroyFreeze);
		} else {
			$("#information-popin").fadeOut("normal");
		}
		return false;
	}

};



var Paiement = {
	// collections et accesseurs
	accItems:undefined,
	listeAnneeCarte:undefined,
	
	// options
	// lite:undefined, -- For future enhancement
	
	/**
	 * The init method register the required listener on the different observable elements,
	 * and then hide the two menus
	 */
	init : function(){
	    var time=new Date();
      var yearCurrent=time.getYear();
      if (yearCurrent < 300) 
        yearCurrent+=1900
      Paiement.listeAnneeCarte = "<option value='"+yearCurrent+"'>"+yearCurrent+"</option>"
      Paiement.listeAnneeCarte += "<option value='"+(yearCurrent+1)+"'>"+(yearCurrent+1)+"</option>"
      Paiement.listeAnneeCarte += "<option value='"+(yearCurrent+2)+"'>"+(yearCurrent+2)+"</option>"
      Paiement.listeAnneeCarte += "<option value='"+(yearCurrent+3)+"'>"+(yearCurrent+3)+"</option>"
			ListeCommande.accItems = $("div.commands div.content table tr");
			$(ListeCommande.accItems).children("td").children("a").click(ListeCommande.onItemDetailCommande);
	},
	
	changeCarte : function(e) {
	 if($(this).val() == "4"){
	  $("#crypto").removeAttr("validation");
	  $("#zonecrypto").hide();
	  }
	 else{
	  $("#crypto").attr("validation","required numericCrypto cryptoTaille");
    $("#zonecrypto").show();
    }
  },
  
  changeCartePartenaire : function(e) {
	 if($(this).val() == "6"){
  	  $("#zonemois").show();
      $("#zoneannee").show(); 
    }
	 else{
  	  $("#zonemois").hide();
  	  $("#zoneannee").hide();
    }
  },

	
	onItemDetailCommande : function(e) {
	    numCommande= $(this).parents("tr").children("td").children("a").html();
	  	$.ajax({
        url: "profilWS.asmx/ChargementDetailCommande",
        type: "POST",
        data: "orderNumber="+numCommande,
        beforeSend: function(){
          Site.showLoader(); 
  			},
        success: function(html){
    			$("#member-space-info").html($("resultHTML",html).text());
          FoldableContent.init();
          CartDetail.init();
          $(AccordionNavigation.currentItem).removeClass("on");
          AccordionNavigation.currentItem = undefined;
					$(".retourliste").click( function(){
    			  $("ul.accordion-like  #mes_commandes").click();
    			  return false;
          });
          Site.hideLoader();	
  			},
  		error : function(html){
            Site.hideLoader();
            System.alert("Une erreur s'est produite...", null, null);
    	}
  	  });
		return false; // Le navigateur ne suit pas le lien
	},
	
	voirDescriptionFinaref : function() {
	   $.ajax({
        url: "PaiementWS.asmx/ChargeDescriptifFinaref",
	      type: "POST",
	      data:"oscode="+$(this).attr("id"),
        success: function(html){
          //if($("statut",html).text()=='OK')
            $("#finaref-form-description").html($("string", html).text());
            $("#desc-finaref-form a.close").click(Paiement.closeDescriptionFinaref);
	   	      $("#cardTypeREP").hide();
		        Site.createFreeze();
		        $("#desc-finaref-form").fadeIn();
		        $("#freeze").click(Paiement.closeDescriptionFinaref);
		        $("#desc-finaref-form").css("top", top);
		      },
		error : function(html){
            System.alert("Une erreur s'est produite...", null, null);
    	}
      });
	
		return false;
	},
	
	/**
	 * Make the form to dissappear
	 */
	closeDescriptionFinaref: function() {
		$("#desc-finaref-form").fadeOut("normal", Site.destroyFreeze);
		$("#cardTypeREP").fadeIn();
		return false;
	}
	
};

//format label produits
function FormatLabelProduit(){
	//test
	var TblNomProduit = $("div.cartcell div.content div.infos strong");
	var sLabelProduit = "";
	var ExpreReg = new RegExp("(\n)", "g");  //recherche retour chariot
						
	for(i = 0; i < TblNomProduit.length; i++){
		sLabelProduit = TblNomProduit[i].innerHTML;
		sLabelProduit = sLabelProduit.replace(ExpreReg, " "); //remplacement retour chariot
					
		if (sLabelProduit.length > 30) //nb carractères
			TblNomProduit[i].innerHTML = sLabelProduit.substr(0, 30) + "...:";
	}
}

//fonction appelée par flash finaref
function conditionsCredit(quel)
 {
	if(quel=='standard')
	{
		window.open("../Infos/services.aspx?page=Offres");
	}
	  else if(quel=='special')
	{
		window.open("../Infos/services.aspx?page=Offres"); 
	}
}

/**
* Register the DOMReady listener to launch the application initialisation when the entire DOM is available
*/
$(document).ready(Site.start);

Number.prototype.formatMoney = function(c, d, t){
  var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

String.prototype.trim = function(){
  return this.replace(/^\s+/, "").replace(/\s+$/, "");
}

