/*********************************************************/
/***** ANCIEN CONTENU fonctions                       ****/
/*********************************************************/

var lightBoxName='';

/* Fonction de redirection selon choix fait dans la lightbox lb4 */
function choix_catalogue() {
	if (document.getElementById('radionon').checked==true) { 
		lightbox('lb7'); 
	} else if (document.getElementById('radiooui').checked==true) { 
		lightbox('lb5'); 
	}
}

/* VSN Fonction de redirection selon choix fait dans la lightbox lb4 avec parametre */
function choix_catalogueWithParam(arg) {
	if (document.getElementById('radionon').checked==true) { 
		lightboxWithParam('lb7',arg); 
	} else if (document.getElementById('radiooui').checked==true) { 
		lightboxWithParam('lb5',arg); 
	}
}

/* Fonction de redirection selon saisie faite dans la lightbox lb5 */
function saisie_numclient() {
	var num_client = document.getElementById('num_client_v');
	var nom_client = document.getElementById('nom_client_v');
	var erreur = 0;
	if(verfi_vide(nom_client.value)){
		alert('Veuillez saisir votre nom');
		document.getElementById('nom_client_v').focus();
	}else{
		if(verfi_vide(num_client.value)){
			alert('Veuillez saisir votre numero de client');
			document.getElementById('num_client_v').focus();
		}else{
			if(!verif_numerique(num_client.value)){
				alert('Le code client doit etre numérique');
				document.getElementById('num_client_v').focus();
			}else{
				Ajax_Call("/VAD/VerificationCompte?nom="+nom_client.value+"&code="+num_client.value);
			}
		}
	}
}

/* VSN duplication avec param d'entree  : Fonction de redirection selon saisie faite dans la lightbox lb5 */
function saisie_numclientWithParam(arg) {
	//alert('saise num client arg = '+arg);
	var num_client = document.getElementById('num_client_v');
	var nom_client = document.getElementById('nom_client_v');
	var erreur = 0;
	if(verfi_vide(nom_client.value)){
		alert('Veuillez saisir votre nom');
		document.getElementById('nom_client_v').focus();
	}else{
		if(verfi_vide(num_client.value)){
			alert('Veuillez saisir votre numero de client');
			document.getElementById('num_client_v').focus();
		}else{
			if(!verif_numerique(num_client.value)){
				alert('Le code client doit etre numérique');
				document.getElementById('num_client_v').focus();
			}else{
				Ajax_Call("/VAD/VerificationCompte?nom="+nom_client.value+"&code="+num_client.value+"&arg="+arg);
			}
		}
	}
}
/* fin VSN */

/* Fonction de redirection selon saisie faite dans la lightbox lb5 */
function saisie_numclient2() {
	var num_client = document.getElementById('num_client_v2');
	var nom_client = document.getElementById('nom_client_v2');
	var erreur = 0;
	if(verfi_vide(nom_client.value)){
		alert('Veuillez saisir votre nom');
		document.getElementById('nom_client_v').focus();
	}else{
		if(verfi_vide(num_client.value)){
			alert('Veuillez saisir votre numero de client');
			document.getElementById('num_client_v').focus();
		}else{
			if(!verif_numerique(num_client.value)){
				alert('Le code client doit etre numérique');
				document.getElementById('num_client_v').focus();
			}else{
				Ajax_Call("/VAD/VerificationCompte?nom="+nom_client.value+"&code="+num_client.value);
			}
		}
	}
}

/* Fonction de redirection selon saisie faite dans la lightbox lb5 */
function saisie_numclient2WithParam(arg) {
	var num_client = document.getElementById('num_client_v2');
	var nom_client = document.getElementById('nom_client_v2');
	var erreur = 0;
	if(verfi_vide(nom_client.value)){
		alert('Veuillez saisir votre nom');
		document.getElementById('nom_client_v').focus();
	}else{
		if(verfi_vide(num_client.value)){
			alert('Veuillez saisir votre numero de client');
			document.getElementById('num_client_v').focus();
		}else{
			if(!verif_numerique(num_client.value)){
				alert('Le code client doit etre numérique');
				document.getElementById('num_client_v').focus();
			}else{
				Ajax_Call("/VAD/VerificationCompte?nom="+nom_client.value+"&code="+num_client.value+"&arg="+arg);
			}
		}
	}
}

/* Fonction de recuperation du parametre 'param' en URL */
function getParamValue(param) {
	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+param+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}

/* Fonctions appelees au chargement de la page */
$(document).ready(function() {
	//SEO lot 2
	//chargement du menu complet en Ajax
	loadMenu();
	//SEO lot 2
	
	$(".plus").toggle(function(){
		$(this).removeClass("plus").addClass("moins");
		$("#" + $(this).attr("req")).slideDown('slow');
	},function(){
		$(this).removeClass("moins").addClass("plus");
		$("#" + $(this).attr("req")).slideUp('slow');
	});
	if (getParamValue("page")=="accueil") {
		$("#contenu_espace1").hide();
		$("#contenu_espace2").hide();
		$("#contenu_espace3").hide();
		$("#contenu_espace4").hide();
		$("#contenu_espace5").hide();
		$("#contenu_espace0").show(); 

		if (getParamValue("item")!='') { 	
			$("#contenu_espace0").hide(); 
			$("#contenu_espace" + getParamValue("item")).show();
			$("#bouton_plus" + getParamValue("item")).removeClass("bouton_plus").addClass("bouton_moins");
		}
	}
	if (getParamValue("codeErreurCof4E")!='') {	
		// cofidis hors contexte achat
		// message erreur retour hors contexte
		lightbox('lbcof' + getParamValue("codeErreurCof4E"));
	}
	if (getParamValue("item")!='') {	
		// modif
		$("#contenu_espace0").hide(); 
		$("#contenu_espace" + getParamValue("item")).show();
		$("#bouton_plus" + getParamValue("item")).removeClass("bouton_plus").addClass("bouton_moins");
	}
	$("#calqueSortieMenu").mouseover( function() {
		$('.menuimg').each(function() { $(this).attr('src',$(this).attr('srcOff')) });
		$('.niveau3').hide();
		$('.niveau2link').removeClass('linkon');
		$('.niveau2').hide();
		$(this).hide();
		//VSN : fonction 	setMenuOn(); définie dans le template remet en subrillance l'univers courant selectionné
		setMenuOn();
	});
	//SEO lot2
	$("#princImg").removeAttr("alt");
	//FIN SEO lot2
});

/* Fonction : creation LightBox */
function lightbox (id_lb) {
	lightbox (id_lb, true);
}

function lightbox (id_lb, cacheActive) {
	//Verification de l'existence d'une lightbox.
	if($("div.modale").length==0 && $("div.modalev1").length==0 && $("div.modalebig").length==0) {	
		//Insertion de la blackbox
		$("body").prepend('<div class="black_box" style="filter: alpha(opacity=40);"></div>');
		// Insertion du receptacle
		$("body").prepend('<div class="receptacle"></div>');
	} // Dans le cas ou la lightbox encore active est le moulin, on affiche quand meme la nouvelle lightbox
	else if ($("div.modale").attr("id")=='moulin') {
		$("body").prepend('<div class="black_box" style="filter: alpha(opacity=40);"></div>');
		// Insertion du receptacle
		$("body").prepend('<div class="receptacle"></div>');
	}
	//Appel Ajax
	var param = {"idBox": id_lb};
	if(arguments.length == 2){
		param = $.extend(param, {"arg": arguments[1]});
	}
	//ajax vers /VAD/Lightbox suivi des params
	//append dans receptacle
	var url = '/VAD/Lightbox';
	 $.ajax({
		   type: "GET",
		   cache:cacheActive,
		   url: url,
		   data: param,
		   success: function(msg){
		 		$(".receptacle").empty();
		 		$(".receptacle").append(msg);
		 		//Centre le contenu
				centre_lightbox($("#"+id_lb));
				//DEBUT VSN DI 999 [C] emplacement de la fenêtre de création de compte
				if (id_lb == 'lb7') {
					set_lightbox_onTop($("#"+id_lb));
				}
				if (id_lb == 'lb7bis') {
					set_lightbox_onTop($("#"+id_lb));
				}
				//FIN VSN DI 999 [C] emplacement de la fenêtre de création de compte
				//Hack Dropdownliste IE6
				$(".black_box").bgiframe();
				//Apparition
				$('.black_box')
				.css({width: $(window).width(), height: $(document).height()})
				.fadeIn("slow",function(){$("#"+id_lb).fadeIn("slow");});
		   }
		 });
}

/* Fonction : creation LightBox */
function lightboxbis (id_lb, functionafter) {
	//Verification de l'existence d'une lightbox.
	if($("div.modale").length==0 && $("div.modalev1").length==0 && $("div.modalebig").length==0) {	
		//alert("premiere modale");
		//Insertion de la blackbox
		$("body").prepend('<div class="black_box" style="filter: alpha(opacity=40);"></div>');
		// Insertion du receptacle
		$("body").prepend('<div class="receptacle"></div>');
	}
	//Appel Ajax
	var param = {"idBox": id_lb};
	if(arguments.length == 2){
		param = $.extend(param, {"arg": arguments[1]});
	}
	//append dans receptacle
	var url = '/VAD/Lightbox';
	 $.ajax({
		   type: "GET",
		   cache:true,
		   url: url,
		   data: param,
		   success: function(msg){
		 		$(".receptacle").empty();
		 		$(".receptacle").append(msg);
		 		//Centre le contenu
				centre_lightbox($("#"+id_lb));
				//DEBUT VSN DI 999 [C] emplacement de la fenêtre de création de compte
				if (id_lb == 'lb7') {
					set_lightbox_onTop($("#"+id_lb));
				}
				if (id_lb == 'lb7bis') {
					set_lightbox_onTop($("#"+id_lb));
				}
				//FIN VSN DI 999 [C] emplacement de la fenêtre de création de compte
				//Hack Dropdownliste IE6
				$(".black_box").bgiframe();
				//Apparition
				$('.black_box')
				.css({width: $(window).width(), height: $(document).height()})
				.fadeIn("slow",function(){$("#"+id_lb).fadeIn("slow");});
				eval(functionafter); 
		   }
		 });
}

function lightboxError(msg){
	lightbox('lb99', msg);
}

/* Fonction : creation LightBox avec parametre */
function lightboxWithParam(id_lb, arg) {
	lightboxWithParam(id_lb, arg, true);
}

/* Fonction qui ouvre une lightbox avec en parametre un tableau de clef:valeur pour les paremetres de la requete*/
function lightboxWithParams(id_lb, arg, cacheActive) {
    if(arg!=null && arg!="") {
          //Verification de l'existence d'une lightbox.
          if($("div.modale").length==0 && $("div.modalev1").length==0 && $("div.modalebig").length==0) {    
                //Insertion de la blackbox
                $("body").prepend('<div class="black_box" style="filter: alpha(opacity=40);"></div>');
                // Insertion du receptacle
                $("body").prepend('<div class="receptacle"></div>');
          }
          //Appel Ajax
          //append dans receptacle
          //Appel Ajax
          param = arg;
          param = $.extend(param, {"idBox": id_lb});
          var url = '/VAD/Lightbox';
          $.ajax({
                   type: "GET",
                   cache:cacheActive,
                   url: url,
                   data: param,
                   success: function(msg){
                            $(".receptacle").empty();
                            $(".receptacle").append(msg);
                            //Centre le contenu
                           centre_lightbox($("#"+id_lb));
	       					//DEBUT VSN DI 999 [C] emplacement de la fenêtre de création de compte
	       					if (id_lb == 'lb7') {
	       						set_lightbox_onTop($("#"+id_lb));
	       					}
	       					if (id_lb == 'lb7bis') {
	       						set_lightbox_onTop($("#"+id_lb));
	       					}
	       					//FIN VSN DI 999 [C] emplacement de la fenêtre de création de compte
                           //Hack Dropdownliste IE6
                           $(".black_box").bgiframe();
                           //Apparition
                           $('.black_box')
                           .css({width: $(window).width(), height: $(document).height()})
                           .fadeIn("slow",function(){$("#"+id_lb).fadeIn("slow");});
                   }
                 });
    } else {
          alert("email invalide");
    }
}

function lightboxWithParam(id_lb, arg, cacheActive) {
	
	/* CBL 03/01/2012 : Paramètres pour récupérer la date de fin des tags GA55 */
	var date_fin_tag_ga55 = $("#date_fin_tag_ga55").val();
	if (date_fin_tag_ga55 == null || date_fin_tag_ga55 == '') {
		date_fin_tag_ga55 = '20120131';
	}
	var date_actuelle = new Date();
	var m=new Array(13);
	m[1]="01"; m[2]="02"; m[3]="03"; m[4]="04"; m[5]="05"; m[6]="06";
 	m[7]="07";	m[8]="08"; m[9]="09"; m[10]="10";	m[11]="11"; m[12]="12";
	var mois=m[date_actuelle.getMonth()+1];
	var date=date_actuelle.getDate();
	if (date<10) date = '0'+date;
	var an=date_actuelle.getYear();
	if (an<200) an=1900+an;
	date_actuelle=an+mois+date;
	//alert('date_fin = ' + date_fin + ', date actu = ' + date_actuelle);
	/* CBL 03/01/2012 : Paramètres pour récupérer la date de fin des tags GA55 */
	
	if(arg!=null && arg!="") {
		//Verification de l'existence d'une lightbox.
		if($("div.modale").length==0 && $("div.modalev1").length==0 && $("div.modalebig").length==0) {	
			//Insertion de la blackbox
			$("body").prepend('<div class="black_box" style="filter: alpha(opacity=40);"></div>');
			// Insertion du receptacle
			$("body").prepend('<div class="receptacle"></div>');
		}
		//Appel Ajax
		//append dans receptacle
		//Appel Ajax
		var param = {"idBox": id_lb};
		if(arguments.length == 2 || arguments.length == 3){
			param = $.extend(param, {"arg": arguments[1]});
		}
		/* CBL 03/01/2012 : Paramètres pour récupérer la date de fin des tags GA55 */
		param = $.extend(param, {"dateActuelle": date_actuelle});
		param = $.extend(param, {"dateFinTagGa55": date_fin_tag_ga55});
		/* CBL 03/01/2012 : Paramètres pour récupérer la date de fin des tags GA55 */
		var url = '/VAD/Lightbox';
		 $.ajax({
			   type: "GET",
			   cache:cacheActive,
			   url: url,
			   data: param,
			   success: function(msg){
			 		$(".receptacle").empty();
			 		$(".receptacle").append(msg);
			 		//Centre le contenu
					centre_lightbox($("#"+id_lb));
					//DEBUT VSN DI 999 [C] emplacement de la fenêtre de création de compte
					if (id_lb == 'lb7') {
						set_lightbox_onTop($("#"+id_lb));
					}
					if (id_lb == 'lb7bis') {
						set_lightbox_onTop($("#"+id_lb));
					}
					//FIN VSN DI 999 [C] emplacement de la fenêtre de création de compte
					//Hack Dropdownliste IE6
					$(".black_box").bgiframe();
					//Apparition
					$('.black_box')
					.css({width: $(window).width(), height: $(document).height()})
					.fadeIn("slow",function(){$("#"+id_lb).fadeIn("slow");});
			   }
			 });
	} else {
		alert("email invalide");
	}
}



/* Fonction : affichage du panneau livraison (1er niveau) */
function show_livraison(id_mode) {
	$("#lieu1").slideUp('fast');
	$("#lieu2").slideUp('fast'); 
	$("#lieu3").slideUp('fast'); 
	$("#choix1").slideUp('fast'); 
	$("#choix2").slideUp('fast'); 
	$("#lieu"+id_mode).slideDown('fast');	
}

/* Fonction : affichage du panneau livraison (2eme niveau) */
function show_choixlivraison(id_choix) {
	$("#choix1").slideUp('fast'); 
	$("#choix2").slideUp('fast'); 
	$("#choix"+id_choix).slideDown('fast');
}

/* Fonction : destruction de LightBox */
function kill_lightbox (id_lb) {
	$('#'+id_lb).fadeOut("slow",function(){
		$(".black_box").fadeOut("slow",
				function(){
			$('.receptacle, .black_box').remove();
		})
	});
}

/* Fonction : centrage de LightBox */
function centre_lightbox (el) {
	var top = $(window).scrollTop()+($(window).height()/2)-(el.height()/2);
	var left = ($(window).width()/2)-(el.width()/2);
	el.css({top: top +"px", left: left +"px"});	
}

//DEBUT VSN DI 999 [C] emplacement de la fenêtre de création de compte
function set_lightbox_onTop (el) {
	var top = $(window).scrollTop()+10;
	var left = ($(window).width()/2)-(el.width()/2);
	el.css({top: top +"px", left: left +"px"});	
}
//FIN VSN DI 999 [C] emplacement de la fenêtre de création de compte

/* Fonction : switch de menuitem (item, bouton) */
function toggle_item (it,bt) {
	if ($("#" + bt).hasClass("bouton_plus")) {
		$(".contenu_espace:visible").slideUp('slow');
		$(".bouton_moins").removeClass("bouton_moins").addClass("bouton_plus");
		$("#" + bt).removeClass("bouton_plus").addClass("bouton_moins");
		$("#" + it).slideDown('slow');
	}else{
		$(".contenu_espace:visible").slideUp('slow');
		$("#contenu_espace0").slideDown('slow');
		$("#" + bt).removeClass("bouton_moins").addClass("bouton_plus");
	}
}

/* Fonction : affichage des messages d'info dans la lightbox lb7 (creation de compte) */
function toggle_info(inf) {
	$("#infos0").slideUp('slow');
	$("#infos1").slideUp('slow');
	$("#infos2").slideUp('slow');
	$("#infos3").slideUp('slow');
	$("#infos4").slideUp('slow');
	$("#infos" + inf).slideDown('slow');
}

/* MAJ */
var Box = {
	el: null,		// box actuel
	// Config par defaut
	init:{
		idBox: null,	// id de la lightbox
		arg:  null,		// parametre envoye a la box
		show: null, 	// fonction a executer avant affichage
		close: null, 	// fonction a executer a la fermeture de box
		top: 0,			// top css de la box
		left: 0,		// left css de la box
		url: "/VAD/Lightbox",		// Url de chargement du contenu
		urldata: null,	// Parametre de Url du contenu
		killTime: null,
		showWaitProgress: false
	},

	open: function(p){
		//Verification d'une occurence / Si oui suppression
		if(this.el != null && this.el.length != 0){Box.kill(p); return false;}
		$.extend(this, this.init, p);
		// Raccourci clavier (Echap pour quitter)
		$(document).one("keydown", function (e) {
			if(e.which == 27) {Box.kill(); return false;}
		});
		//	Insertion de la blackbox
		if($(".black_box").length == 0){
			$('<div class="black_box" style="filter: alpha(opacity=40);"></div>').prependTo("body")
			.css({width: $(window).width(), height: $(document).height()});
		}
		//	Insertion du receptacle
		//R13
		if($(".receptacle").length == 0){
			$("body").prepend('<div class="receptacle"></div>');
		}
		//FIN R13
		// affichage d'un moulin avant l'affichage de la lightbox si demande
		if (Box.showWaitProgress == true) {
			$("body #waitMessage").remove();
			// creer la div
			$("body").prepend('<div id="waitMessage"><div id="moulin" class="modale" style="width:150px;"><div style="text-align:center;margin-top:25px;margin-bottom:25px;"><img src="/style1/images/commun/loading.gif"></div></div>');
			// centrer la div
			var divWaitMessage = $("body #waitMessage .modale");
			divWaitMessage.css("top", $(window).scrollTop() + ($(window).height()/2) - (divWaitMessage.height()/2));
			divWaitMessage.css("left", ($(window).width()/2) - (divWaitMessage.width()/2));			
			// afficher la blackbox
			$(".black_box").show();
		}
		var param = {"idBox": Box.idBox};
		if(Box.arg != null){
			param = $.extend(param, {"arg": Box.arg});
		}
		$.ajax({
			   type: "GET",
			   cache:false,
			   url: Box.url,
			   data: param,
			   success: function(msg){
			 		$(".receptacle").empty();
			 		$(".receptacle").append(msg);
			 		Box.el = $("#"+ Box.idBox);
					// Positionne la box au centre si non top, ou left non definit
					if(Box.top == 0 || Box.left == 0) {
						Box.top = $(window).scrollTop() + ($(window).height()/2) - (Box.el.height()/2);
						Box.left = ($(window).width()/2) - (Box.el.width()/2);
					}
					Box.el.css({top: Box.top +"px", left: Box.left +"px"});
					Box.el.bgiframe();
					// Definit le click de fermeture
					$(".close", Box.el).click(function(){Box.kill(); return false;});
					//Apparition de la blackbox
					$(".black_box").fadeIn("slow", function(){
						Box.el.fadeIn("slow", function(){
							if(Box.show){Box.show();}
						});
					});
					// masquer le moulin d'attente si present
					$("body #waitMessage").hide();
			   }
			 });
	},
	openParam: function(p){
		//Verification d'une occurence / Si oui suppression
		if(this.el != null && this.el.length != 0){Box.kill(p); return false;}
		$.extend(this, this.init, p);
		// Raccourci clavier (Echap pour quitter)
		$(document).one("keydown", function (e) {
			if(e.which == 27) {Box.kill(); return false;}
		});
		//	Insertion de la blackbox
		if($(".black_box").length == 0){
			$('<div class="black_box" style="filter: alpha(opacity=40);"></div>').prependTo("body")
			.css({width: $(window).width(), height: $(document).height()});
		}
		//	Insertion du receptacle
		$("body").prepend('<div class="receptacle"></div>');
		var param = {"idBox": Box.idBox};
		if(Box.arg != null){
			param = $.extend(param, {"arg": Box.arg});
		}
		 $.ajax({
			   type: "GET",
			   cache:true,
			   url: Box.url,
			   data: Box.urldata,
			   success: function(msg){
			 		$(".receptacle").empty();
			 		$(".receptacle").append(msg);
			 		Box.el = $("#"+ Box.idBox);
					// Positionne la box au centre si non top, ou left non definit
					if(Box.top == 0 || Box.left == 0) {
						Box.top = $(window).scrollTop() + ($(window).height()/2) - (Box.el.height()/2);
						Box.left = ($(window).width()/2) - (Box.el.width()/2);
					}
					Box.el.css({top: Box.top +"px", left: Box.left +"px"});
					Box.el.bgiframe();
					// Definit le click de fermeture
					$(".close", Box.el).click(function(){Box.kill(); return false;});
					//Apparition de la blackbox
					$(".black_box").fadeIn("slow", function(){
						Box.el.fadeIn("slow", function(){
							if(Box.show){Box.show();}
						});
					});
			   }
			 });
	},
	kill: function(reload){
		if(this.el == null){ return;}
		if(this.killTime !=  null){
			clearTimeout(this.killTime);
			this.killTime = null;
		}
		this.el.fadeOut("slow", function(){
			$('.receptacle').remove(); Box.el = null;
			if(Box.close){Box.close();}
			if(reload != null){
				Box.open(reload);
			}else{
				$(".black_box").fadeOut("slow",	function(){
					$('.black_box').remove();
				});
			}
		});	
	}
}

function omnitureOnclick(libelleRubrique){
	s.channel="Espace Client";
	s.pageName="Espace Client:" + libelleRubrique;
	s.tl();
}

function f_show_detail(id, urlParam) {
	loaded = $('#fic_' + id).is(':visible');
	if (!loaded) {
		$('#fic_' + id).show();
		$('#fic_' + id).load('/VAD/DetailProduitLight?' + urlParam);
    }
}

/*********************************************************/
/***** ANCIEN CONTENU ajax_full                       ****/
/*********************************************************/
var Messages = 
{
		"KO"                 : "Une erreur technique est survenue : veuillez nous en excuser...",
		"ERR_PANIER_DEBORDE" : "Ajout impossible : le nombre d&prime;articles différent dans le panier ne peut d&eacute;passer 20 articles",
		"ERR_REF01" 		   : "Erreur reference inexistante!",  
		"ERR_QTE_MAX" 	   : "Ajout impossible : la quantité; pour un article du panier ne peut être sup&eacute;rieure Ã  99",
		"ERR01"			   : "Erreur de connexion : identifiant inconnu",	
		"ERR02"			   : "Erreur de connexion : le mot de passe saisi n'est pas valide",
		"ERR03"			   : "Erreur de connexion : merci de renseigner votre adresse email ou numéro de client ainsi que votre mot de passe",
		"ERR0"			   : "Erreur de déconnexion suite à une erreur technique. La fermeture de votre navigateur entrainera automatique la déconnexion de votre compte."
}

//astuce pour regler les erreurs de syntaxe dans l'API ATOS, GRRR
var  KO="KO";
var  ERR_PANIER_DEBORDE="ERR_PANIER_DEBORDE";
var  ERR_REF01="ERR_REF01";
var  ERR_QTE_MAX="ERR_QTE_MAX";
var  ERR01="ERR01";
var  ERR02="ERR02";
var  ERR03="ERR03";
var  ERR0="ERR0";

function localize(str){
	var s;
	if(Messages && (s=Messages[str]) ) return s;
	return "Une erreur non identifiée est survenue...";
}

var dropdowncontent={
	delaybeforehide: 200,
	disableanchorlink: true, 
	getposOffset:function(what, offsettype){
		return (what.offsetParent)? what[offsettype]+this.getposOffset(what.offsetParent, offsettype) : what[offsettype]
	},
	isContained:function(m, e){
		var e=window.event || e
		var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement)
		while (c && c!=m)try {c=c.parentNode} catch(e){c=m}
		if (c==m)
			return true
			else
				return false
	},
	show:function(anchorobj, subobj, e){
		if (!this.isContained(anchorobj, e)){
			var horizontaloffset=(subobj.dropposition[0]=="left")? -(subobj.offsetWidth-anchorobj.offsetWidth) : 0  
			var verticaloffset=(subobj.dropposition[1]=="top")? -subobj.offsetHeight : anchorobj.offsetHeight  
			subobj.style.left="480px"
			subobj.style.top=this.getposOffset(anchorobj, "offsetTop")+verticaloffset+"px"
			subobj.style.clip=(subobj.dropposition[1]=="top")? "rect(auto auto auto 0)" : "rect(0 auto 0 0)"  
			subobj.style.visibility="visible"
			subobj.startTime=new Date().getTime()
			subobj.contentheight=parseInt(subobj.offsetHeight)
			if (typeof window["hidetimer_"+subobj.id]!="undefined")  
				clearTimeout(window["hidetimer_"+subobj.id])
			this.slideengine(subobj, (subobj.dropposition[1]=="top")? "up" : "down")
		}
	},
	curveincrement:function(percent){
		return (1-Math.cos(percent*Math.PI)) / 2  
	},
	slideengine:function(obj, direction){
		var elapsed=new Date().getTime()-obj.startTime  
		if (elapsed<obj.glidetime){  
			var distancepercent=(direction=="down")? this.curveincrement(elapsed/obj.glidetime) : 1-this.curveincrement(elapsed/obj.glidetime)
			var currentclip=(distancepercent*obj.contentheight)+"px"
			obj.style.clip=(direction=="down")? "rect(0 auto "+currentclip+" 0)" : "rect("+currentclip+" auto auto 0)"
			window["glidetimer_"+obj.id]=setTimeout(function(){dropdowncontent.slideengine(obj, direction)}, 10)
		} else{  
			obj.style.clip="rect(0 auto auto 0)"
		}
	},
	hide:function(activeobj, subobj, e){
		if (!dropdowncontent.isContained(activeobj, e)){
			window["hidetimer_"+subobj.id]=setTimeout(function(){
				subobj.style.visibility="hidden"
					subobj.style.left=subobj.style.top=0
					clearTimeout(window["glidetimer_"+subobj.id])
			}, dropdowncontent.delaybeforehide)
		}
	},
	myshow:function(anchorid) {
		var anchorobj=document.getElementById(anchorid)
		var subobj=document.getElementById(anchorobj.getAttribute("rel"))
		var horizontaloffset=(subobj.dropposition[0]=="left")? -(subobj.offsetWidth-anchorobj.offsetWidth) : 0  
		var verticaloffset=(subobj.dropposition[1]=="top")? -subobj.offsetHeight : anchorobj.offsetHeight  
		subobj.style.left="480px"
		subobj.style.top=this.getposOffset(anchorobj, "offsetTop")+verticaloffset+"px"
		subobj.style.clip=(subobj.dropposition[1]=="top")? "rect(auto auto auto 0)" : "rect(0 auto 0 0)"  
		subobj.style.visibility="visible"
		subobj.startTime=new Date().getTime()
		subobj.contentheight=parseInt(subobj.offsetHeight)
		if (typeof window["hidetimer_"+subobj.id]!="undefined")  
			clearTimeout(window["hidetimer_"+subobj.id])
		this.slideengine(subobj, (subobj.dropposition[1]=="top")? "up" : "down");
		window["glidetimer_"+subobj.id] = setTimeout( function(){
			subobj.style.visibility="hidden"
			subobj.style.left=subobj.style.top=0
			clearTimeout(window["glidetimer_"+subobj.id])
		}, 2000 );
	},
	init:function(anchorid, pos, glidetime){
		var anchorobj=document.getElementById(anchorid)
		var subobj=document.getElementById(anchorobj.getAttribute("rel"))
		subobj.dropposition=pos.split("-")
		subobj.glidetime=glidetime || 1000
		subobj.style.left=subobj.style.top=0
		anchorobj.onmouseover=function(e){dropdowncontent.show(this, subobj, e)}
		anchorobj.onmouseout=function(e){dropdowncontent.hide(subobj, subobj, e)}
		if (this.disableanchorlink) anchorobj.onclick=function(){return false}
		subobj.onmouseout=function(e){dropdowncontent.hide(this, subobj, e)}
	}
}
 
//PARAMETRAGE
sUrlApiATOS_InfoClient       = '/VAD/InfoClient';
sUrlApiATOS_AjoutArticlesVus = '/portal/portal/SiteInternet/App/Ajax/Ajax?action=2&viewId=/jsp/ajax/ajax.jsp&toInit=true&API=2&id_article=%id%&libelle_article=%lib%&prix_bas=%pv%&url_vignette=%urlimg%&url_FicheProduit=%urlfp%';
sUrlApiATOS_UnLogin          = '/VAD/Deconnexion';
sUrlApiATOS_ChangeUser       = '/VAD/Deconnexion';

//----------------------------------------------------- 
var bustcachevar=1;
var loadedobjects="";
var rootdomain="http://"+window.location.hostname;
var bustcacheparameter="";

function Ajax_DisplayNothing () {};

function Ajax_Call(url, func4print){
	var varSessionId=getSessionId();
	var varTimeStampRefresh=getTimeStamp();
	$.ajax({
		url: url,
		cache: false,
		dataType: "text",
		data : {SessionId: varSessionId, TimeStampRefresh: varTimeStampRefresh},
		success: function(data){
			traitementAjaxResult(data, func4print);
		}
	});
}

/**
* Methode d'evaluation pour l'execution
* @param data données retournee par la fonction ajax
* @param func4print Fonction à executer apres l'interpretation du retour ajax
* 
*/
function traitementAjaxResult(data,func4print){
	scriptFlow =data;
	var debut = scriptFlow.indexOf("<AJAX>");
	var fin = scriptFlow.indexOf("</AJAX>");
	scriptFlow = scriptFlow.substring(debut+6,fin);
	try {
		eval(scriptFlow); 
		if(func4print!=null)
			func4print(scriptFlow) ;
	} catch(e) {
		alert(localize('KO'));
	}
}

//Fonction lancée sur chaque page
$(function(){
	$("body").ajaxSend(function(request, settings){
		$(".ajaxLoad").show();
		$(".notAjaxLoad").hide();
	});
	$("body").ajaxStop(function(request, settings){
		$(".ajaxLoad").hide();
		$(".notAjaxLoad").show();
	});
	$.ajaxSetup({
		cache: false,
		error: function(){
			setTimeout("alert(\"L'action en cours n'a pu aboutir, merci de réessayer ultérieurement.\");"+
			"$('.ajaxLoad').hide();"+
			"$('.notAjaxLoad').show();"+
			"$('#boutonok').show();"+
			"$('#loginLoader').hide();",30000);
			//R13
			singleton=false;
			//FIn R13
		}		
	});
	$("#open_panier_link").attr("href","/VAD/Panier?"+getEnteteUrl());
	$("#direct").attr("href","/VAD/Panier?"+getEnteteUrl());
	
	Ajax_Call_InfoClient ();
});

//------------------------------------------------
//AJAX PANIER
var Ajax_Result_code=null;
var Ajax_Result_msg=null;
var Ajax_Result_host=null;

var Ajax_Panier_nbCall=0;

function result(code, message, host){
	Ajax_Result_code=code;
	Ajax_Result_msg=message;
	Ajax_Result_host=host;
}

function clearMiniPanier(){
	$(".item_mini_panier").remove();
	$("#panier_total").html("0 article");
	$("#panier_nbre_article").html("0 article");
}

function connexionAffichePass(){
	$('#pass_text').hide();
	$('#pass').show();
	$('#pass').focus();
}

/**
* 
* @param libelle
* @param quantite
* @param prix
* @param libelleCouleur
* @param libelletaille
* @param urlVignette
* @param urlFicheProduit
*/
function addLigneArticle(libelle,quantite,prix,libelleCouleur,libelletaille,urlVignette){
	var html = "<div class='item item_mini_panier'>"+
	"<img src='"+urlVignette+"' class='item_image' width='80'/>"+
	"<div class='item_text'><strong>"+libelle.replace(/\+/g,' ')+"</strong><br/>Couleur : "+libelleCouleur+
	"<br/>Taille : "+libelletaille+
	"<br/>Quantité : "+quantite+
	"<br/>Prix : "+getSomme(prix)+" €</div><div class='item_clear'></div></div>";
	$("#panier_rapide").prepend(html);
	nbreArticle = parseInt($("#panier_nbre_article").html());
	nbreArticle = nbreArticle+parseInt(quantite);
	
	if (nbreArticle > 1) {
		$("#panier_nbre_article").html(nbreArticle+" articles");
	} else {
		$("#panier_nbre_article").html(nbreArticle+" article");	
	}
	
}

/**
* Fonction qui renvoie la somme au bon format
* @param prix
* @return
*/
function getSomme(prix){
	var totLigne;
	totLigne = parseFloat(prix); 
	prix = totLigne.toFixed( 2 );
	prix = prix.replace(".",",");
	return prix;
}

function displayInfoAjoutPanierPopup () {
	Ajax_Panier_nbCall=0;
	if (Ajax_Result_code==1) {
		CacheClient_delete();
		RAZ();
		Ajax_Call_InfoClient () ;
	} else {
		alert(localize(Ajax_Result_msg));
	}
}

function Ajax_Call_AjoutArticlesvus (article_id, libelle, prix, url_img, url_FP) {
	sUrl = sUrlApiATOS_AjoutArticlesVus ;
	sUrl = sUrl.replace('%id%', encodeURI(article_id)) ;
	sUrl = sUrl.replace('%lib%', encodeURI(libelle)) ;
	sUrl = sUrl.replace('%pv%', encodeURI(prix));
	sUrl = sUrl.replace('%urlimg%', encodeURI(url_img)) ;
	sUrl = sUrl.replace('%urlfp%', encodeURI(url_FP));
	// Appel Ajax 
	Ajax_Call(sUrl, 	CacheClient_delete);
}
/* Fonction permettant d'encoder les tags GA55 */
function replaceAccent2(valeur){
	str = valeur;
	str = str.replace(/à|á|â|ä|å|ã|Ä|Å|Á|Â|À|Ã/g,"a");
	str = str.replace(/é|è|ê|ë|É|Ê|Ë|È/g,"e");
	str = str.replace(/ù|ü|û|ú|Ü|Ú|Û|Ù/g,"u");
	str = str.replace(/ô|ö|ò|ó|õ|Ö|Ø|Ó|Ô|Ò|Õ/g,"o");
	str = str.replace(/î|ï|ì|í|Î|Ï|Ì/g,"i");
	str = str.replace(/ç|Ç/g,"c");
	str = str.replace(/ñ|Ñ/g,"n");
	str = str.replace(/ /g, "_");
	return str;
}

function Ajax_Call_AjoutPanier ( niv_oper, radicalId, article_id, libelle, couleur, codtaille, libtaille, quantite, prix, url_img, url_FP, typeAjout) {
	sUrl  = '/VAD/AjoutPanier?niv_oper='+ encodeURI(niv_oper) +'&articleId=' + encodeURI(article_id) + '&radicalId=';
	sUrl += encodeURI(radicalId) + '&taille=' + encodeURI(codtaille) + '&qte=' + encodeURI(quantite) + '&typeAjout=' + typeAjout;
	
	/* CBL : Construction du parametre arbo pour les tags ga55 */
	/*alert($("div .chemin > a[class=niveau-1]").text());
	alert($("div .chemin > a[class=niveau-2]").text());
	alert($("div .chemin > span[class=niveau-3]").text());
	alert($("div .chemin > a[class=niveau-3]").text());*/
	
	univers=$("div .chemin > a[class=niveau-1]").text();
	univers = replaceAccent2(univers);
	if ($("div .chemin > span[class=niveau-2]").text()=='') {
		categorie=$("div .chemin > a[class=niveau-2]").text();
		categorie = replaceAccent2(categorie);
	} else { // Si on est en page liste
		categorie=$("div .chemin > span[class=niveau-2]").text();
		categorie=categorie.substring(categorie.lastIndexOf(">")+2, categorie.length);
		categorie = replaceAccent2(categorie);
	}
	// Si on est en page produit
	if ($("div .chemin > span[class=niveau-3]").text()=='') {
		typepro=$("div .chemin > a[class=niveau-3]").text();
		typepro = replaceAccent2(typepro);
	} else { // Si on est en page liste
		typepro=$("div .chemin > span[class=niveau-3]").text();
		typepro=typepro.substring(typepro.lastIndexOf(">")+2, typepro.length);
		typepro = replaceAccent2(typepro);
	}
	
	if ((univers=='') && (categorie=='') && (typepro=='')) {
		arbo="\"Commande_Directe\"";
	} else {
		/*arbo = "\"" + encodeURIComponent(univers) + "/" 
		+ encodeURIComponent(categorie) + "/" 
		+ encodeURIComponent(typepro) + "\"";*/
		arbo = "\"" + univers + "/" 
		+ categorie + "/" 
		+ typepro + "\"";
	}
	//alert("arbo="+arbo);
	
	sUrl += encodeURIComponent(arbo); 
	/* Fin CBL : Construction du parametre arbo pour les tags ga55 */

	// Appel Ajax 
	Ajax_Panier_nbCall++;
	Ajax_Call(sUrl, function(){
		Ajax_Call_InfoClient();
	});
}

function Ajax_Call_CrossSelling (  niv_oper, radicalId, article_id, libelle, couleur, codtaille, libtaille, quantite, prix, url_img, url_FP, typeAjout, urlParam) {
	sUrlVad  ='&niv_oper0='+ encodeURI(niv_oper) + 
	'&niv_oper='+ encodeURI(niv_oper) +
	'&articleId=' +	encodeURI(article_id) +
	'&radicalId=' + encodeURI(radicalId)  + 
	'&taille='    + encodeURI(codtaille)  + 
	'&qte=' 	  + encodeURI(quantite)   + 
	'&typeAjout=' + typeAjout;
	
	if (libelle != undefined) {
		sUrlVad = sUrlVad + '&lib_art=' + encodeURIComponent(libelle);
	}
	sUrl  = '/VAD/PanierXSelling?' +  urlParam + sUrlVad;
	Ajax_Panier_nbCall++;
	Box.open({
		idBox: 'lb70',
		showWaitProgress: true,
		url: sUrl
	});
}

/* CBL : Ajout du paramètre arbo pour les tag ga55 */
function Ajax_Call_CrossSelling (  niv_oper, radicalId, article_id, libelle, couleur, codtaille, libtaille, quantite, prix, url_img, url_FP, typeAjout, urlParam, arbo) {
	sUrlVad  ='&niv_oper0='+ encodeURI(niv_oper) + 
	'&niv_oper='+ encodeURI(niv_oper) +
	'&articleId=' +	encodeURI(article_id) +
	'&radicalId=' + encodeURI(radicalId)  + 
	'&taille='    + encodeURI(codtaille)  + 
	'&qte=' 	  + encodeURI(quantite)   + 
	'&typeAjout=' + typeAjout +
	'&arbo=' + encodeURIComponent(arbo);
	//alert("ajax_call_crossselling="+arbo);
	if (libelle != undefined) {
		sUrlVad = sUrlVad + '&lib_art=' + libelle;
	}
	sUrl  = '/VAD/PanierXSelling?' +  urlParam + sUrlVad;
	Ajax_Panier_nbCall++;
	Box.open({
		idBox: 'lb70',
		showWaitProgress: true,
		url: sUrl
	});
}
/* CBL : Ajout du paramètre arbo pour les tag ga55 */

function InfoCrossSelling(){
	$("#lb16_Cross_selling").prepend("");
}

//------------------------------------------------
//AJAX CLIENT
//Singleton Client en cours de surf
var oClient=null;

//------------------------ Definition des objet
function SeenItem(sId, sLib, sPV, sUrlImg, sUrlPage) {
	this.sId= sId;
	this.sLib = sLib;    
	this.sPV = sPV;     
	this.sUrlImg = sUrlImg;
	this.sUrlPage = sUrlPage;
}

function OrderLine (sId, sLib, sCol, sTaille, iQty, sPV, sUrlImg, sUrlPage) {
	this.sId=sId;
	this.sLib=sLib; 
	this.sCol=sCol; 
	this.sTaille=sTaille; 
	this.iQty=iQty; 
	this.sPV=sPV; 
	this.sUrlImg=sUrlImg;
	this.sUrlPage=sUrlPage;
}

function Client(bIsLogged, sNom, sPrenom, sTotPanier, sNumCli,email,civilite){
	this.bIsLogged=bIsLogged;
	this.sNom=sNom;
	this.sPrenom=sPrenom;
	this.sNumCli=sNumCli;
	this.oPanier=new Array();
	if (typeof sTotPanier=='undefined') sTotPanier=0.00;
	this.sTotPanier=sTotPanier;
	this.oArticlesVus=new Array();
	this.email=email;
	this.civilite=civilite;
};

//------------------------ Methode appele par l'ajax pour l'instanciation et le rattachement au singleton courant
function addSeenItem (sId, sLib, sPV, sUrlImg, sUrlPage) {
	var oSeenItem = new SeenItem (sId, sLib, sPV, sUrlImg, sUrlPage);
	if (oClient!=null) oClient.oArticlesVus[oClient.oArticlesVus.length]=oSeenItem;
}

function addOrderLine(sId, sLib, sCol, sTaille, iQty, sPV, sUrlImg, sUrlPage){
	var oOrderLine=new OrderLine(sId, sLib, sCol, sTaille, iQty, sPV, sUrlImg, sUrlPage);
	if (oClient!=null) oClient.oPanier[oClient.oPanier.length]=oOrderLine;
}

//---------------------------- methode appele par l'ajax pour l'instanciation du singleton
function createClient(bIsLogged, sNom, sPrenom, sTotPanier, sNumCli,email,civilite) {
	oClient = new Client(bIsLogged, sNom, sPrenom, sTotPanier, sNumCli,email,civilite) ;	
}

//------------------------------ Function Cache Client en cookie
//var CacheClient_Cname = "QuelleAjaxCache" ;
var CacheClient_Auth = "QuelleAuthValid";
var CacheClient_Cname = "QuelleInfoClient";
var CacheClient_Panier = "QuellePanier";

function CacheClient_set(sScriptFlow) {
	// set cookie to memorize the status during 20 minutes
	var expdate = new Date() ;
	expdate.setTime(expdate.getTime() + (1000*1200));
	document.cookie = CacheClient_Cname + "=" + encodeURI(sScriptFlow) + ";domain="+document.location.host+"; path=/; expires=" + expdate.toGMTString();
	document.cookie = CacheClient_Auth + "=" + encodeURI(sScriptFlow.replace("createClient(2,","createClient(1,")) + ";domain="+document.location.host+"; path=/;";
}

function CacheClient_delete() {
	document.cookie = CacheClient_Cname + "=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function CacheClient_get() {
	if (document.cookie.length>0)   {
		c_start=document.cookie.indexOf(CacheClient_Cname + "=");
		if (c_start!=-1) { 
			c_start=c_start + CacheClient_Cname.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return decodeURI(document.cookie.substring(c_start,c_end));
		}else{
			c_start=document.cookie.indexOf(CacheClient_Auth + "=");
			if (c_start!=-1) { 
				c_start=c_start + CacheClient_Auth.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return decodeURI(document.cookie.substring(c_start,c_end));
			}
		}
	}
	return null;
}

function getEnteteUrl(){
	return "SessionId="+getSessionId()+"&TimeStampRefresh="+getTimeStamp();
}

function getSessionId(){
	return  getCookie("JSESSIONID");
}

function getTimeStamp(){
	var demain=new Date();
	return  ""+demain.getDate()+demain.getMonth()+demain.getFullYear()+demain.getHours()+demain.getMinutes()+demain.getSeconds();
}

//----------------------------- Function d'affichage lancee pr recuperation des infos clients .
function displayArticlesVus(oArticlesVus) {
	if (oArticlesVus==null || oArticlesVus.length==0){return;}
	var sHTML='';
	for (i=0 ; i<oArticlesVus.length ; i++) {
		sHTML += '<div style="font-size:11px;clear:both;height:83px;border-bottom:1px ' +
		'solid #CAA9B0;padding-bottom:5px;padding-top:3px;cursor:pointer;" onclick="FicheProduit(\''+oArticlesVus[i].sUrlPage+'\');">' +
		'<img src="/'+ oArticlesVus[i].sUrlImg +'" border=0 class="header_vignette"' +
		' style="margin-right:5px;margin-left:5px;margin-top:2px;">' + 
		'<b><font style="color:#975362">' + oArticlesVus[i].sLib + '</font></b><br>'+
		'Prix : <b>' + oArticlesVus[i].sPV +' &euro;</b>'+
		'</div>' ;
	}
	sHTML='<div style="background-color:#ffffff;width:200px;">' + sHTML + 
	'<img src="/VAD/res/quelle/images/commun/1ptrans.gif" width=1 height=1 style="clear:both;"><br>' +
	'<center><a href="#" onclick="dropdowncontent.init(\'dejavuslink\', \'right-bottom\', 500);' +
	'document.getElementById(\'articlesdejavus\').style.visibility=\'hidden\';">' + 
	'<img src="/VAD/res/quelle/images/commun/up.gif" border=0></a></center>' +
	'</div>' ;
	document.getElementById("articlesdejavus").innerHTML=sHTML;
}

function displayInfoClient_R1() {
	if(oClient != null){	
		// si pas loggue on garde la mise en page du formulaire par defaut sinon affichage des infos de logins
		if (oClient.bIsLogged==2) {
			var domaine = (window.location.hostname.indexOf("quelle.fr") != -1) ? "https://" + window.location.hostname +"/VAD/" : "";	
			$("#unlogin").show();
			$("#changeUser").hide();
			$("#msg_welcome").html('Bonjour '+oClient.civilite+' <br> '+oClient.sPrenom + ' ' + oClient.sNom +' !');
			$("#msg_welcome_link").html('<a href="'+ domaine +'Client?page=accueil&'+getEnteteUrl()+'" id="creationcompte">Cliquez ici pour acc&eacute;der &agrave; votre espace personnel</a>');
			$("#loginEspace").hide();
			$("#menuHeader").attr("style","left: 456px;");
			$("#espaceClient").attr("style","width: 278px; left: 685px;");
			$("#panier").attr("rel","toppanier");
		} else {
			if (oClient.bIsLogged==1) {
				$("#unlogin").hide();
				$("#changeUser").show();
				$("#loginEspace").show();
				$("#menuHeader").removeAttr("style");
				$("#espaceClient").removeAttr("style");
				$("#msg_welcome").html('Bonjour '+oClient.civilite+' <br> '+oClient.sPrenom + ' ' + oClient.sNom +' !');
				$("#msg_welcome_link").html('Entrer votre mot de passe pour acc&eacute;der &agrave; votre espace');
				$("#login").val(oClient.email);
				$("#login").hide();
				$("#ident_mail").show();
			} else {
				$("#unlogin").hide();
				$("#changeUser").hide();
				$("#menuHeader").removeAttr("style");
				$("#espaceClient").removeAttr("style");
				$("#loginEspace").show();
				$("#ident_mail").hide();
				$("#msg_welcome").html('Vous n\'avez pas encore d\'espace ?');
				$("#msg_welcome_link").html('<a href="javascript:lightbox(\'lb4\');" id="creationcompte">Créez-le ici et profitez pleinement de Quelle !</a>');
				$("#login").show();
			}
		}
	}
	$("#ident").show();
}

function displayInfoClient() {
	if(oClient != null){
		var civilite = "Mr";
		if(oClient.civilite == "Monsieur"){
			civilite = "Mr";
		}else if(oClient.civilite == "Madame"){
			civilite = "Mme";
		}else {
			civilite = "Mlle";
		}
		// si pas loggue on garde la mise en page du formulaire par defaut sinon affichage des infos de logins
		if (oClient.bIsLogged==2) {
			// Client identifie (clientEspace)
			var domaine = (window.location.hostname.indexOf("quelle.fr") != -1) ? "https://" + window.location.hostname +"/VAD/" : "http://" + window.location.hostname +"/VAD/";
			$("#loginEspace").hide();
			$("#creationEspace").hide();
			$("#lien_moncompte").attr("href", domaine +'Client?page=accueil&'+getEnteteUrl());
			$("#moncompte").show();
			$("#pass_login").val('');
			$("#pass").val('');
			$("#part3").html('Bonjour '+oClient.sPrenom + ' ' + oClient.sNom);
			$("#links3").html('<a href="'+ domaine +'Client?page=accueil&'+getEnteteUrl()+'" class="link">Acc&eacute;dez &agrave; mon compte</a>  <a href="javascript:UnLoginProceed();" class="linkright">D&eacute;connexion</a>');
			$("#clientEspace").show();
		} else {
			// Client authentifie (loginEspace)
			if (oClient.bIsLogged==1) {
				$("#creationEspace").hide();
				$("#clientEspace").hide();
				$("#loginEspace").show();
				$("#part1").html('Bonjour '+oClient.sPrenom + ' ' + oClient.sNom);
				$("#log").show();$("#loginLoader").hide();
				$("#login").val(oClient.email);
				$("#pass_login").val('');
				$("#pass").val('');
				$("#moncompte").show();
			// Client non connu (ni identifie, ni authentifie) (creationEspace)
			} else {
				$("#loginEspace").hide();
				$("#clientEspace").hide();
				$("#creationEspace").show();
				$("#log").show();$("#loginLoader").hide();
				$("#pass_login").val('');
				$("#pass").val('');
			}
		}
	} 
}

//-------------------------------------------------------------------------------
function checkResultLogin(sScriptFlow){
	$("#loginLoader").hide();
	$("#boutonok").show();
	if (Ajax_Result_code==1) {
		// ecriture du cookie
		if (Ajax_Result_host!=null){
			var expdate = new Date() ;
			expdate.setTime(expdate.getTime() + (1000*3600*24*30));
			document.cookie = "QuelleCookie=" + oClient.sNumCli + "; expires=" + expdate.toGMTString() + "; path=/; domain=." + Ajax_Result_host;
		}
		displayInfoClient();
	} else {
		alert(localize(Ajax_Result_msg));
	}
}

function LoginProceed () {
	var passwordCrypte;
	var login =$("#login").val();
	var password = $("#pass").val();
	if (password=='') password = $("#pass_login").val();
	$("#log").hide();$("#loginLoader").show();
	if (login.length==0 || password.length==0 ){
		alert('Merci de renseigner votre adresse email ou numéro de client');
		$("#log").show();$("#loginLoader").hide();
		return false;
	}
	if(password!='') {
		passwordCrypte=password;
	} else {
		passwordCrypte='';
	}
	Ajax_Call_Login (login,passwordCrypte);
}
/* VSN : Duplication de la fonction LoginProceed  pour lui passer un param. pagesource */
function LoginProceedWithParam (pageSource) {
	var passwordCrypte;
	var login =$("#login").val();
	var password = $("#pass").val();
	if (password=='') password = $("#pass_login").val();
	$("#log").hide();$("#loginLoader").show();
	if (login.length==0 || password.length==0 ){
		alert('Merci de renseigner votre adresse email ou numéro de client');
		$("#log").show();$("#loginLoader").hide();
		return false;
	}
	if(password!='') {
		passwordCrypte=password;
	} else {
		passwordCrypte='';
	}

	Ajax_Call_Login_With_Param (login,passwordCrypte,pageSource);
}

/* Fin VSN  */


function setPrixMiniPanier(prix){
	$("#panier_total").html(getSomme(prix));
}

//----------------------------- Functions d'appel AJAX client : formatage de l'url et appel
function Ajax_Call_InfoClient () {
	var cookie  = getJsonCookie(CacheClient_Cname);
	var lancementAjax = false;
	var cookie_panier  = getJsonCookie(CacheClient_Panier);
	// Traitement du panier d'il y a moins de 4 articles
	if( cookie_panier!=null && cookie_panier.lc.length<4){
		clearMiniPanier();
		lignes = cookie_panier.lc;
		for(var i=0;i<lignes.length;i++){
			var ligne = lignes[i];
			addLigneArticle(ligne.libArt,ligne.qte,ligne.mntL,ligne.col,ligne.tai,ligne.urlVignette);
		}
		setPrixMiniPanier(cookie_panier.mntTot);
		// Pour rafraichir la vignette panier
		lancementAjax = true;
	} else {
		lancementAjax = true;
	}
	if (!lancementAjax && cookie!=null) {
		var cookie_auth  = getCookie(CacheClient_Auth);
		var isLogged=1;
		if(cookie_auth !=  null){
			var now = new Date();
			var datecook= new Date();
			datecook.setTime(datecook.getTime()+(30*60*1000));
			document.cookie =
				CacheClient_Auth+'="valide"; expires='+datecook.toGMTString()+'; path=/VAD/';
			isLogged=2;
		} else if((cookie != null) && (cookie.emLibNomCli != null) && (cookie.emLibNomCli!="")) {
			isLogged=1;
		} else {
			isLogged=0;
		}
	}
	if(cookie !=null && cookie.emLibNomCli != null && cookie.emLibNomCli != ""){
		var civilite = "Mr";
		if(cookie.emCodIdentiteCli == "1"){
			civilite = "Mr";
		}else if(cookie.emCodIdentiteCli == "2"){
			civilite = "Mme";
		}else {
			civilite = "Mlle";
		}
		tab = cookie.emLibNomCli.split("/");
		createClient(isLogged, tab[0], tab[1], 0, cookie.emId,cookie.emEmail,civilite);
	}
	//	Lancement du chargement
	if(lancementAjax){
		Ajax_Call(sUrlApiATOS_InfoClient,displayInfoClient);
	} else {
		displayInfoClient();
	}
}

function Ajax_Call_Login (login, password) {
	Ajax_Call('/VAD/Identification?login=' + encodeURI(login) + '&pass=' + encodeURI(password)+(lightBoxName==''?'':'&lb='+lightBoxName), checkResultLogin);
}

/* VSN : duplication de la fonction Ajax_Call_Login pour la passage en parametre de la var. pageSource */

function Ajax_Call_Login_With_Param (login, password, pageSource) {
	Ajax_Call('/VAD/Identification?login=' + encodeURI(login) + '&pass=' + encodeURI(password)+(lightBoxName==''?'':'&lb='+lightBoxName)+'&pageSource='+pageSource, checkResultLogin);
}

/*FIN VSN */

function UnLoginProceed () {
	Ajax_Call("/VAD/Deconnexion");
}

function ChangeUserProceed(){
	Ajax_Call("/VAD/Deconnexion?user=clear");
	clearMiniPanier();
}

function FicheProduit(url){
	eval('window.location="'+url+'"');
}

/*********************************************************/
/***** ANCIEN CONTENU client                          ****/
/*********************************************************/
//JavaScript Document for Quelle
//Version : 0.1
//Authors : Francois OLIVIER

var NOM_DIV_MSG = "divMessage";
var NOM_DIV_BOUTON = "divBouton";

/* Fonction : "switch" entre 2 div */
function switchDiv(idDiv2Hide, idDiv2Show) {
	$("." + idDiv2Hide).hide();
	$("." + idDiv2Show).show();
}

/* Fonction : "switch" automatique entre 2 div */
function switchDivAuto() {
	switchDiv(NOM_DIV_MSG, NOM_DIV_BOUTON);
	setModifAdresse();
}

/**
* Pour les contacts chargment d'un theme
*/
function contactChargementTheme(nameId){
	var id = nameId.substring(6,9);
	$("#"+id).height=950;
	$("#"+id).load("/VAD/ContactTheme?page=ssTheme&themeId="+id,function(data){
		$("#ssThemeAccordion_"+id).accordion({
			active : false,
			fillSpace: true,
			collapsible: true,
			change: function(event, ui){
				if($(ui.newHeader).html() != null){
					contactChargementSousTheme(id,$(ui.newHeader).children(".sousTheme").attr("id"));
				}
			}
		});
	});
	$("#"+id).css("height",657);
}

function contactChargementSousTheme(theme,sousTheme){
	var id = sousTheme.substring(8,11);
	$("#sousTheme_"+id+"_"+theme).load("/VAD/ContactTheme?page=rensComp&themeId="+theme+"&ssThemeId="+id,function(){
		$.datepicker.setDefaults($.datepicker.regional['fr']);
		$(".date").datepicker({
			dateFormat : 'dd/mm/y',
			changeMonth : true,
			changeYear : true
		});
	});
}

function toggle_reassurance(inf) {
	if($("#contactMenu").is(':visible')){
		 $("#contactMenu").slideUp('slow');	
	} else {
		 $("#reassurance1").slideUp('slow');
		 $("#reassurance2").slideUp('slow');
		 $("#reassurance3").slideUp('slow');
		 $("#reassurance4").slideUp('slow');
	}
	if(inf>0){
		 $("#reassurance" + inf).slideDown('slow');
	} else {
		$("#contactMenu").slideDown('slow');
	}
}

/**
* Fonction de chargement du suivi des commandes
*/
function clientChargementSuivitCommande(){
	$(".bout_chargement_suivi_cmd").show();	
	$("#contenu_espace1").load("/VAD/SuiviCommandeServlet", 
		function(){
			$("#client_derniere_commande").html($("#client_derniere_commande_result").html());
			$(".bout_chargement_suivi_cmd").hide();
		}
	);
}

/**
* Affichage du formulaire de modification d'une adresse
*/
function clientAffModif(varIdAdresse,creation,principale,niveau_oper){
	$("#cp").removeClass("code_postal");
	$("#cp").removeClass("code_postal_non_dom");
	$("#cp").removeClass("code_postal_dom");
	if(principale){
		$("#principaleOui").val("1");
		$("#cp").addClass("code_postal");
	} else {
		$("#principaleOui").val("0");
		if(niveau_oper=="O"){
			$("#cp").addClass("code_postal_dom");
		} else {
			$("#cp").addClass("code_postal_non_dom");
		}
	}
	if(principale && creation){
		$("#nom_a").attr("readOnly","readonly");
		$("#prenom_a").attr("readOnly","readonly");
		$(".creation_adresse").show();
		$(".modification_adresse").hide();
		$("#liste_adresse").fadeOut("normal",function(){
			$("#adresses_modif").fadeIn("normal");
		});
		$('#mradio').attr('disabled','disabled');
		$('#mmeradio').attr('disabled','disabled');
		$('#mlleradio').attr('disabled','disabled');
	} else {
		$('#mradio').removeAttr('disabled');
		$('#mmeradio').removeAttr('disabled');
		$('#mlleradio').removeAttr('disabled');
		$.get("/VAD/InfoAdresse",
			{adresseId : varIdAdresse},
			function(data){
				$("#adresseId").val(varIdAdresse);
				if(creation)		{
					$(".creation_adresse").show();
					$(".modification_adresse").hide();
				}else{
					$(".creation_adresse").hide();
					$(".modification_adresse").show();
				}
				if(principale ){
					$(".adresse_secondaire").hide();
				}else{
					$(".adresse_secondaire").show();
				}
				traitementAjaxResult(data);
				$("#liste_adresse").fadeOut("normal",function(){
					$("#adresses_modif").fadeIn("normal");
				});
			}
		);
	}
}

/**
* Affichage du formulaire des informations des points relais
*/
function clientAffPointRelais(){
	$("#liste_adresse").fadeOut("normal",function(){
		$("#affiche_point_relais").fadeIn("normal");
		$("#liste_adresse").hide();
	});
}

/**
* Affichage du formulaire de modification d'un point relais
* depuis l'affichage des informations d'un point relais
*/
function clientAffModifPointRelais(){
	$("#affiche_point_relais").fadeOut("normal",function(){
		$("#modif_point_relais").fadeIn("normal");
		$("#affiche_point_relais").hide();
	});
}

/**
* Affichage du fomulaire de modification d'un point relais
* depuis l'affichage de la liste des adresses
*/
function clientAffModifPointRelaisBis(){
	$("#liste_adresse").fadeOut("normal",function(){
		$("#modif_point_relais").fadeIn("normal");
		$("#liste_adresse").hide();
	});
}
	
/**
* Fonction de retour de l'affichage du carnet d'adresse
* @param refresh boolean si l'on doit rafraichir la page ou non 
* @param form Formulaire depuis lequel on fait le retour
*/
function clientRetourListAdresse(refresh,form){
	// TODO debeuguer le fede out qui ne fonctionne pas
	if(refresh){
		$("#contenu_espace2").load("/VAD/CarnetAdresse",function(){
			$("#"+form).fadeOut("normal",function(){
				$("#liste_adresse").fadeIn("normal");
				$("#"+form).hide();
			});
		});
	}else{
		$("#"+form).fadeOut("normal",function(){
			$("#liste_adresse").fadeIn("normal");
			$("#"+form).hide();
		});
	}
}

function clientInfoRetourMail(email){
	$("#info_email").fadeOut("normal",function(){
		$("#info_accueil").fadeIn("normal");
		$("#info_email").hide();
		if(email != null){
			$("#menu_info_email").html(email);
			$("#info_affichage_email").html(email);
		}
	});
}

function clientInfoAffModifEmail(){
	$("#info_accueil").fadeOut("normal",function(){
		$("#info_email").fadeIn("normal");
		$("#info_accueil").hide();
	});
}

function clientInfoAffModifMdp(){
	$("#info_accueil").fadeOut("normal",function(){
		$("#info_div_mdp").fadeIn("normal");
		$("#info_accueil").hide();
	});
}

function clientInfoRetourMdp(){
	$("#info_div_mdp").fadeOut("normal",function(){
		$("#info_accueil").fadeIn("normal");
		$("#info_div_mdp").hide();
	});
}

/* Fonction : insere un message dans une div */
function fillDivWithMsg(idDiv, msg) {
	$("." + idDiv).html("<font color=\"red\"><b><center>"+msg+"</center></b></font>");
}

/* Fonction : "switch" entre 2 div */
function addImg2Field(idField, imgContent) {
	if($("#" + idField).next("img")) {
		$("#" + idField).next("img").remove();
	}
	$("#" + idField).after(imgContent);
}

function isDate(dateStr) {
	if(dateStr == '--')
		return true;
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		return false;
	}
	month = matchArray[1]; // p@rse date into variables
	day = matchArray[3];
	year = matchArray[5];
	if (month < 1 || month > 12) { // check month range
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			return false;
		}
	}
	return true; // date is valid
}

/* Remplace un caractère par un autre */
function replaceChars(entry, field) {
	out = ";"; // replace this
	add = " "; // with this
	temp = "" + entry; // temporary holder
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	document.getElementById(field).value = temp;
}

/* Fonction : vérification des champs des formulaires */
function verifChamp(idChamp, pathImg) {
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/à|á|â|ä|å|ã|Ä|Å|Á|Â|À|Ã/g,"a"));
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/é|è|ê|ë|É|Ê|Ë|È/g,"e"));
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/ù|ü|û|ú|Ü|Ú|Û|Ù/g,"u"));
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/ô|ö|ò|ó|õ|Ö|Ø|Ó|Ô|Ò|Õ/g,"o"));
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/î|ï|ì|í|Î|Ï|Ì/g,"i"));
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/ç|Ç/g,"c"));
	$("#" + idChamp).attr("value",($("#" + idChamp).val()).replace(/ñ|Ñ/g,"n"));
	
	if (idChamp=="new_email" || idChamp=="email_client_c") {
		$("#" + idChamp).attr("value",($("#" + idChamp).val()).toLowerCase());
	} else {
		if (idChamp!="mdp" && idChamp!="old_mdp" && idChamp!="new_mdp" && idChamp!="confirm_mdp" && idChamp!="pass_client" && idChamp!="confirm_pass" && idChamp!="info_mdp" && idChamp!="info_old_mdp" && idChamp!="info_new_mdp" && idChamp!="info_confirm_mdp" && idChamp!="info_pass_client" && idChamp!="info_confirm_pass" && idChamp!="captcha") { 
			$("#" + idChamp).attr("value",($("#" + idChamp).val()).toUpperCase());
		}
	}

	switchDiv(NOM_DIV_MSG, NOM_DIV_BOUTON);
	setModifAdresse();
	var contenu_OK = "<img src=\""+pathImg+"icon_ok.gif"+"\" class=\"droite\" />";
	var contenu_KO = "<img src=\""+pathImg+"icon_ko.gif"+"\" class=\"droite\" />";

	if(idChamp=="nom_client" || idChamp=="prenom_client" || idChamp=="nom_client_c" || idChamp=="nom_a" || idChamp=="prenom_a") {
		if($("#" + idChamp).val().indexOf(';')>=0) {
			replaceChars(document.getElementById(idChamp).value, idChamp);
		}
		// CBL : Ajout RDG : Le nom doit comporter au minimum 2 caractères
		if( isStandardChaine($("#" + idChamp).val() && $("#" + idChamp).val().length >= 2) ) { 
			addImg2Field(idChamp, contenu_OK);
		} else { 
			addImg2Field(idChamp, contenu_KO);
		}
	} else if(idChamp=="jj_naissance" || idChamp=="mm_naissance" || idChamp=="aaaa_naissance") {
		var date_ok = true;
		if(isEmpty($("#jj_naissance").val()) && isEmpty($("#mm_naissance").val()) && isEmpty($("#aaaa_naissance").val())){
			date_ok = true;
		} else {
			if(isDate($("#mm_naissance").val() + '-' + $("#jj_naissance").val() + '-' + $("#aaaa_naissance").val())) {
				date_ok = true;
			} else {
				date_ok = false;
			}
			if( isEmpty($("#jj_naissance").val()) ) { 
				date_ok = false;
			}
			if( isEmpty($("#mm_naissance").val()) ) {
				date_ok = false;
			}
			if( isEmpty($("#aaaa_naissance").val()) ) {
				date_ok = false;
			}
		}
		if( date_ok ) {
			addImg2Field($("#aaaa_naissance").attr("id"), contenu_OK);
		} else { 
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field($("#aaaa_naissance").attr("id"), contenu_KO);
		}
	} else if(idChamp=="info_jj_naissance" || idChamp=="info_mm_naissance" || idChamp=="info_aaaa_naissance") {
		var date_ok = true;
		if(isEmpty($("#info_jj_naissance").val()) && isEmpty($("#info_mm_naissance").val()) && isEmpty($("#info_aaaa_naissance").val())){
			date_ok = true;
		} else {
			if(isDate($("#info_mm_naissance").val() + '-' + $("#info_jj_naissance").val() + '-' + $("#info_aaaa_naissance").val())) {
				date_ok = true;
			} else {
				date_ok = false;
			}
			if( isEmpty($("#info_jj_naissance").val()) ) { 
				date_ok = false;
			}
			if( isEmpty($("#info_mm_naissance").val()) ) {
				date_ok = false;
			}
			if( isEmpty($("#info_aaaa_naissance").val()) ) {
				date_ok = false;
			}
		}
		if( date_ok ) {
			addImg2Field($("#info_aaaa_naissance").attr("id"), contenu_OK);
		} else {
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field($("#info_aaaa_naissance").attr("id"), contenu_KO);
		}
	} else if (idChamp=="new_email" || idChamp=="email_client_c") {
		if( isStandardEmail($("#" + idChamp).val()) ) {
			addImg2Field(idChamp, contenu_OK);
			Ajax_Call("/VAD/NomDomain?champ="+idChamp+"&email="+$("#" + idChamp).val());
		} else {
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field(idChamp, contenu_KO);
		}
	} else if (idChamp=="mdp" || idChamp=="old_mdp" || idChamp=="new_mdp" || idChamp=="confirm_mdp" || idChamp=="pass_client" || idChamp=="confirm_pass") {
		var exp = new RegExp("^([a-zA-Z0-9])*$","g");
		if(exp.test($("#" + idChamp).val())){
			if( hasTheGoodSize($("#" + idChamp).val(), 6) ) { 
				addImg2Field(idChamp, contenu_OK);
			} else {
				// 	TODO : afficher le message d'erreur quand pas ko
				addImg2Field(idChamp, contenu_KO);
			}
		} else {	
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field(idChamp, contenu_KO);
		}
		if(idChamp == 'confirm_pass') {
			if(document.getElementById('confirm_pass').value == document.getElementById('pass_client').value) {
				if( hasTheGoodSize($("#" + idChamp).val(), 6) ){ 
					addImg2Field('confirm_pass', contenu_OK);
				} else {	
					// 	TODO : afficher le message d'erreur quand pas ko
					addImg2Field('confirm_pass', contenu_KO);
				}
			}
		}
	} else if (idChamp=="info_mdp" || idChamp=="info_old_mdp" || idChamp=="info_new_mdp" || idChamp=="info_confirm_mdp" || idChamp=="info_pass_client" || idChamp=="info_confirm_pass") {
		var exp = new RegExp("^([a-zA-Z0-9])*$","g");
		if(exp.test($("#" + idChamp).val())){
			if( hasTheGoodSize($("#" + idChamp).val(), 6) ){ 
				addImg2Field(idChamp, contenu_OK);
			} else {	
				// 	TODO : afficher le message d'erreur quand pas ko
				addImg2Field(idChamp, contenu_KO);
			}
		} else {	
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field(idChamp, contenu_KO);
		}
		if(idChamp == 'info_confirm_mdp') {
			if(document.getElementById('info_confirm_mdp').value == document.getElementById('info_new_mdp').value) {
				if( hasTheGoodSize($("#" + idChamp).val(), 6) ){ 
					addImg2Field('info_confirm_mdp', contenu_OK);
				} else {	
					// 	TODO : afficher le message d'erreur quand pas ko
					addImg2Field('info_confirm_mdp', contenu_KO);
				}
			} else {
				addImg2Field(idChamp, contenu_KO);
			}
		}
	} else if(idChamp=="captcha" || idChamp=="libelle_a" || idChamp=="ville") {
		if( isEmpty($("#" + idChamp).val()) ) {
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field(idChamp, contenu_KO);
		} else {
			addImg2Field(idChamp, contenu_OK);
		}
	} else if(idChamp=="adresse1") {
		if( isEmpty($("#" + idChamp).val()) ) {
			addImg2Field(idChamp, contenu_KO);
		} else {
			addImg2Field(idChamp, contenu_OK);
		}
		if($("#" + idChamp).val().indexOf(';')>=0) {
			replaceChars(document.getElementById("adresse1").value, "adresse1");
		}
	}
	/* CBL : DI 286 : Ajout du complement d'adresse en creation */
	else if(idChamp=="adresse2") {
		if( isEmpty($("#" + idChamp).val()) ) {
			addImg2Field(idChamp, contenu_KO);
		} else{
			addImg2Field(idChamp, contenu_OK);
		}
		if($("#" + idChamp).val().indexOf(';')>=0)
			replaceChars(document.getElementById("adresse2").value, "adresse2");
	}
	/* CBL : DI 286 : Ajout du complement d'adresse en creation */
	else if(idChamp=="tel") {
		if( isStandardTel($("#" + idChamp).val()) ) {
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field(idChamp, contenu_OK);
		} else {
			addImg2Field(idChamp, contenu_KO);
		}
	} else if(idChamp=="mobile") {
		if( isStandardMobile($("#" + idChamp).val()) ) { 
			// TODO : afficher le message d'erreur quand pas ko
			addImg2Field(idChamp, contenu_OK);
		} else {
			addImg2Field(idChamp, contenu_KO);
		}
	} else if(idChamp=="cp") {
		var expCp = new RegExp("^([0-9][0-9][0-9][0-9][0-9])","g");
		if(expCp.test($("#" + idChamp).val())) {
			addImg2Field(idChamp, contenu_OK);
		} else {
			addImg2Field(idChamp, contenu_KO);
		}
	}

	// CBL Ajout des nouvelles RDG sur les noms et prénoms
	/* Permet de récupérer la taille du champ nom et de modifier
	 * la taille maximale du champ prénom en fonction du nom
	 * La totalité de nom + prénom doit faire 31 caractères au total */
	if(idChamp=="nom_client_c" || idChamp=="prenom_client") {
		var nom = $("#nom_client_c").val(); 
		var tailleNom = nom.length;
		var maxPrenom = 0;
		if (tailleNom < 31) {
			// calcul de la taille maximale pour le champ prénom
			maxPrenom = 31 - tailleNom;
			// Troncature du prénom lors de la saisie
			document.getElementById("prenom_client").value = document.getElementById("prenom_client").value.substring(0, maxPrenom);
		} else if (tailleNom > 31) {
			// Le nom seul est trop grand pour le champ : on le tronque sur 31 caractères
			document.getElementById("nom_client_c").value = document.getElementById("nom_client_c").value.substring(0, 31);
		} else {
			// le prenom ne peut etre saisi car le nom fait déjà 31 caractères
			document.getElementById("prenom_client").maxlength = 0;
			document.getElementById("prenom_client").value = '';
		}
	}
	// Fin CBL Ajout des nouvelles RDG sur les noms et prénoms
}

/* Fonction : teste si une chaine est vide */
function isEmpty(chaine) {
	if( chaine == "" )
		return true;
	return false;
}

function Chr(AsciiNum) {
	return String.fromCharCode(AsciiNum)
}

/* Fonction : teste si une chaine est de type "alphabetique limitee" (=> quelques caractères supplementaires acceptes) */
function isStandardChaine(chaine) {
	//exp = "^([a-zA-ZÃ©Ã¨ÃªÃ¢Ã®Ã«Ã¤Ã¯Ã¼Ã§Ã©])*$";
	expAccent = "";
	for(i=192; i<=255; i++) {
		expAccent+= Chr(i);
	}
	expAccent+= '-';
	exp = "^([a-zA-Z "+ expAccent +"])*$";
	reg = new RegExp(exp);
	if( chaine == "" || (reg.test(chaine)==0) ) {
		return false;
	}
	return true;
}

/* Fonction : teste si une chaine est de type "email" */
function isStandardEmail(chaine) {
	exp = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
	reg = new RegExp(exp);
	if( chaine == "" || (reg.test(chaine)==0) ) {
		return false;
	}
	return true;
}

/* Fonction : teste si une chaine est de type "numéro de telephone" */
function isStandardTel(chaine) {
	exp = "^0[1-6789]([0-9]{2}){4}$";
	reg = new RegExp(exp);
	if( chaine != "" && (reg.test(chaine)==0) ) {
		return false;
	}
	return true;
}

/* Fonction : teste si une chaine est de type "numéro de telephone mobile" */
function isStandardMobile(chaine) {
	exp = "^0(6|7)([0-9]{2}){4}$";
	reg = new RegExp(exp);
	if( chaine != "" && (reg.test(chaine)==0) ) {
		return false;
	}
	return true;
}

/* Fonction : teste si une chaine a une taille requiste (taille fournie en entree */
function hasTheGoodSize(chaine, goodSize) {
	if( chaine == "" || chaine.length<goodSize) {
		return false;
	}
	return true;
}

/* Fonction : password */
function password (email) {
	$.ajax({
		type: "GET",
		url: "/VAD/SendMail?action=2&email="+email,
		async: true,
		dataType: "html",
		error:function(msg){},
		success:function(data){
			traitementAjaxResult(data);
		}
	});  
}

/* Fonction : creation de compte*/
function creationCompte(){
	expAccent = "";
	expAccent+= '-';
	exp = "^([a-zA-Z0-9 "+ expAccent +"])*$";
	
	var exp = new RegExp(exp);
	var civiliteM=document.getElementById("mradio");
	var civiliteMm=document.getElementById("mmeradio");
	var civiliteMle=document.getElementById("mlleradio");
	var nom=document.getElementById("nom_client_c");
	var prenom=document.getElementById("prenom_client");
	var jour=document.getElementById("jj_naissance");
	var mois=document.getElementById("mm_naissance");
	var annee=document.getElementById("aaaa_naissance");
	var email=document.getElementById("email_client_c");
	var pass=document.getElementById("pass_client");
	var pass_c=document.getElementById("confirm_pass");
	//var captcha=document.getElementById("captcha");
	var type=document.getElementById("type");
	var num_client=document.getElementById("num_client_v");
	var adresse1=document.getElementById("adresse1");
	/* CBL : DI 286 : Ajout d'un complement d'adresse */
	var adresse2 = document.getElementById("adresse2");
	/* Fin CBL : DI 286 : Ajout d'un complement d'adresse */
	var cp=document.getElementById("cp");
	var ville = $("#ville").val();
	var error='';
	var error_email='';

	if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked) {error+='Veuillez selectionner une civilite<br />';}
	if(nom==null || nom.value=='') {error+='Veuillez saisir votre nom<br />';}
	// CBL : Ajout RDG : Le nom doit comporter au minimum 2 caractères
	else if (nom.value.length < 2) {error+='Le nom doit comporter au minimum 2 caractères<br />';}
	// Fin CBL
	else if( ! isStandardChaine(nom.value) ) {error+='Le nom saisi n\'est pas correct<br />';}
	if(prenom==null || prenom.value=='') {error+='Veuillez saisir votre prenom<br />';}
	else if( ! isStandardChaine(prenom.value) ) {error+='Le prenom saisi n\'est pas correct<br />';}
	if((jour==null || mois==null || annee==null) || ((jour.value!='' || mois.value!='' || annee.value!='') && (jour.value=='' || mois.value=='' || annee.value==''))) {
		error+='Veuillez selectionner votre date de naissance<br />';
	} else if(!isDate($("#mm_naissance").val() + '-' + $("#jj_naissance").val() + '-' + $("#aaaa_naissance").val())) { 
		error+='La date de naissance saisie n\'est pas correcte<br />';
	}
	
	if(adresse1==null || adresse1.value=='') {error +='Veuillez saisir votre adresse<br />';}
	if(adresse1.value.indexOf(';')>=0) {error +='Le champs adresse ne doit pas contenir de point-virgule<br />';}
	if(cp==null || cp.value=='' || cp.value.length!=5) {error += 'Le code postal est invalide<br />';}
	/* Ajout de la valeur null dans les tests */
	if(ville==null || ville=='' || ville=='null') {error += 'Veuillez sélectionner une ville<br />';}
	
	if(email==null || email.value=='') {error_email+='Veuillez saisir votre email<br />';}
	else if( ! isStandardEmail(email.value) ) {error_email+='L\'email saisi n\'est pas correct<br />';}
	if(pass==null || pass.value=='') {error+='Veuillez saisir un mot de passe.<br />'; }
	else{
		if(!exp.test(pass.value)){
			error+='Le mot de passe contient des caractères spéciaux.<br />';
		}else if (pass!=null && pass.value.length<6) {
			error+='Le mot de passe n\'est pas assez long.<br />';
		}
	}
	if(pass==null || pass_c==null || pass.value!='' && pass.value!=pass_c.value){
		error+='Le mot de passe et sa confirmation doivent être identique<br />';
	}
	//if(captcha==null || captcha.value=='') error+='Veuillez copier le texte de l\'image';
	if(error_email!=''){
		fillDivWithMsg(NOM_DIV_MSG, error_email);
		switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		if(error!=''){
			fillDivWithMsg(NOM_DIV_MSG, error);
			switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
		}else{
			if(verif_email(email.value)){
				var civilite = '1';
				if(civiliteMm.checked) civilite='2';
				if(civiliteMle.checked) civilite='3';
				fillDivWithMsg(NOM_DIV_MSG, '');
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
				/* CBL : DI 286 : Ajout d'un complément d'adresse */
				if (adresse2 != null) {
					Ajax_Call("/VAD/CreationCompte?email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&type="+type.value+"&num_client="+num_client.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&adresse2="+adresse2.value+"&cp="+cp.value+"&ville="+ville,null);
				} else {
					Ajax_Call("/VAD/CreationCompte?email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&type="+type.value+"&num_client="+num_client.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&cp="+cp.value+"&ville="+ville,null);
				}
				/* Fin CBL : DI 286 : Ajout d'un complément d'adresse */
			}else{
				fillDivWithMsg(NOM_DIV_MSG, "Email incorrect");
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			}
		}
	}
}

/* CBL DI 980 : gestion de la création de compte dans le cadre d'un prospect */
function creationCompteProspect() {
	expAccent = "";
	expAccent+= '-';
	exp = "^([a-zA-Z0-9 "+ expAccent +"])*$";
	
	var exp = new RegExp(exp);
	var civiliteM=document.getElementById("mradio");
	var civiliteMm=document.getElementById("mmeradio");
	var civiliteMle=document.getElementById("mlleradio");
	var nom=document.getElementById("nom_client_c");
	var prenom=document.getElementById("prenom_client");
	var jour=document.getElementById("jj_naissance");
	var mois=document.getElementById("mm_naissance");
	var annee=document.getElementById("aaaa_naissance");
	var email=document.getElementById("email_client_c");
	var pass=document.getElementById("pass_client");
	var pass_c=document.getElementById("confirm_pass");
	var type=document.getElementById("type");
	var num_client=document.getElementById("num_client_v");
	var adresse1=document.getElementById("adresse1");
	var adresse2 = document.getElementById("adresse2");
	var cp=document.getElementById("cp");
	var clientId=document.getElementById("client_id");
	var emcodeclient=document.getElementById("emCodeClient");
	var dejaconnu=document.getElementById("dejaconnu");
	var type=document.getElementById("type");
	var ville = $("#ville").val();
	var error='';
	var error_email='';

	if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked) {error+='Veuillez selectionner une civilite<br />';}
	if(nom==null || nom.value=='') {error+='Veuillez saisir votre nom<br />';}
	else if (nom.value.length < 2) {error+='Le nom doit comporter au minimum 2 caractères<br />';}
	else if( ! isStandardChaine(nom.value) ) {error+='Le nom saisi n\'est pas correct<br />';}
	if(prenom==null || prenom.value=='') {error+='Veuillez saisir votre prenom<br />';}
	else if( ! isStandardChaine(prenom.value) ) {error+='Le prenom saisi n\'est pas correct<br />';}
	if((jour==null || mois==null || annee==null) || ((jour.value!='' || mois.value!='' || annee.value!='') && (jour.value=='' || mois.value=='' || annee.value==''))) {
		error+='Veuillez selectionner votre date de naissance<br />';
	} else if(!isDate($("#mm_naissance").val() + '-' + $("#jj_naissance").val() + '-' + $("#aaaa_naissance").val())) { 
		error+='La date de naissance saisie n\'est pas correcte<br />';
	}
	
	if(adresse1==null || adresse1.value=='') {error +='Veuillez saisir votre adresse<br />';}
	if(adresse1.value.indexOf(';')>=0) {error +='Le champs adresse ne doit pas contenir de point-virgule<br />';}
	if(cp==null || cp.value=='' || cp.value.length!=5) {error += 'Le code postal est invalide<br />';}
	if(ville==null || ville=='' || ville=='null') {error += 'Veuillez sélectionner une ville<br />';}
	if(email==null || email.value=='') {error_email+='Veuillez saisir votre email<br />';}
	else if( ! isStandardEmail(email.value) ) {error_email+='L\'email saisi n\'est pas correct<br />';}
	if(pass==null || pass.value=='') {error+='Veuillez saisir un mot de passe.<br />'; }
	else{
		if(!exp.test(pass.value)){
			error+='Le mot de passe contient des caractères spéciaux.<br />';
		}else if (pass!=null && pass.value.length<6) {
			error+='Le mot de passe n\'est pas assez long.<br />';
		}
	}
	if(pass==null || pass_c==null || pass.value!='' && pass.value!=pass_c.value){
		error+='Le mot de passe et sa confirmation doivent être identique<br />';
	}
	
	if(error!=''){
		fillDivWithMsg(NOM_DIV_MSG, error);
		switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		if(verif_email(email.value)){
			var civilite = '1';
			if(civiliteMm.checked) civilite='2';
			if(civiliteMle.checked) civilite='3';
			fillDivWithMsg(NOM_DIV_MSG, '');
			switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			if (adresse2 != null) {
				Ajax_Call("/VAD/ModificationCompte?clientId="+clientId.value+"&emCodeClient="+emcodeclient.value+"&dejaConnu="+dejaconnu.value+"&email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&adresse2="+adresse2.value+"&cp="+cp.value+"&ville="+ville+"&type="+type.value,null);
			} else {
				Ajax_Call("/VAD/ModificationCompte?clientId="+clientId.value+"&emCodeClient="+emcodeclient.value+"&dejaConnu="+dejaconnu.value+"&email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&cp="+cp.value+"&ville="+ville+"&type="+type.value,null);
			}
		}else{
			fillDivWithMsg(NOM_DIV_MSG, "Email incorrect");
			switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
		}
	}
}
/* CBL DI 980 : gestion de la création de compte dans le cadre d'un prospect */

/* VSN duplication et passage de paramatre à la Fonction : creation de compte*/
function creationCompteWithParam(arg){
	expAccent = "";
	expAccent+= '-';
	exp = "^([a-zA-Z0-9 "+ expAccent +"])*$";
	
	var exp = new RegExp(exp);
	var civiliteM=document.getElementById("mradio");
	var civiliteMm=document.getElementById("mmeradio");
	var civiliteMle=document.getElementById("mlleradio");
	var nom=document.getElementById("nom_client_c");
	var prenom=document.getElementById("prenom_client");
	var jour=document.getElementById("jj_naissance");
	var mois=document.getElementById("mm_naissance");
	var annee=document.getElementById("aaaa_naissance");
	var email=document.getElementById("email_client_c");
	var pass=document.getElementById("pass_client");
	var pass_c=document.getElementById("confirm_pass");
	//var captcha=document.getElementById("captcha");
	var type=document.getElementById("type");
	var num_client=document.getElementById("num_client_v");
	var adresse1=document.getElementById("adresse1");
	/* CBL : DI 286 : Ajout d'un complement d'adresse */
	var adresse2 = document.getElementById("adresse2");
	/* Fin CBL : DI 286 : Ajout d'un complement d'adresse */
	var cp=document.getElementById("cp");
	var ville = $("#ville").val();
	var error='';
	var error_email='';

	if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked) {error+='Veuillez selectionner une civilite<br />';}
	if(nom==null || nom.value=='') {error+='Veuillez saisir votre nom<br />';}
	// CBL : Ajout RDG : Le nom doit comporter au minimum 2 caractères
	else if (nom.value.length < 2) {error+='Le nom doit comporter au minimum 2 caractères<br />';}
	// Fin CBL
	else if( ! isStandardChaine(nom.value) ) {error+='Le nom saisi n\'est pas correct<br />';}
	if(prenom==null || prenom.value=='') {error+='Veuillez saisir votre prenom<br />';}
	else if( ! isStandardChaine(prenom.value) ) {error+='Le prenom saisi n\'est pas correct<br />';}
	if((jour==null || mois==null || annee==null) || ((jour.value!='' || mois.value!='' || annee.value!='') && (jour.value=='' || mois.value=='' || annee.value==''))) {
		error+='Veuillez selectionner votre date de naissance<br />';
	} else if(!isDate($("#mm_naissance").val() + '-' + $("#jj_naissance").val() + '-' + $("#aaaa_naissance").val())) { 
		error+='La date de naissance saisie n\'est pas correcte<br />';
	}
	
	if(adresse1==null || adresse1.value=='') {error +='Veuillez saisir votre adresse<br />';}
	if(adresse1.value.indexOf(';')>=0) {error +='Le champs adresse ne doit pas contenir de point-virgule<br />';}
	if(cp==null || cp.value=='' || cp.value.length!=5) {error += 'Le code postal est invalide<br />';}
	/* Ajout de la valeur null dans les tests */
	if(ville==null || ville=='' || ville=='null') {error += 'Veuillez sélectionner une ville<br />';}
	
	if(email==null || email.value=='') {error_email+='Veuillez saisir votre email<br />';}
	else if( ! isStandardEmail(email.value) ) {error_email+='L\'email saisi n\'est pas correct<br />';}
	if(pass==null || pass.value=='') {error+='Veuillez saisir un mot de passe.<br />'; }
	else{
		if(!exp.test(pass.value)){
			error+='Le mot de passe contient des caractères spéciaux.<br />';
		}else if (pass!=null && pass.value.length<6) {
			error+='Le mot de passe n\'est pas assez long.<br />';
		}
	}
	if(pass==null || pass_c==null || pass.value!='' && pass.value!=pass_c.value){
		error+='Le mot de passe et sa confirmation doivent être identique<br />';
	}
	//if(captcha==null || captcha.value=='') error+='Veuillez copier le texte de l\'image';
	if(error_email!=''){
		fillDivWithMsg(NOM_DIV_MSG, error_email);
		switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		if(error!=''){
			fillDivWithMsg(NOM_DIV_MSG, error);
			switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
		}else{
			if(verif_email(email.value)){
				var civilite = '1';
				if(civiliteMm.checked) civilite='2';
				if(civiliteMle.checked) civilite='3';
				fillDivWithMsg(NOM_DIV_MSG, '');
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
				/* CBL : DI 286 : Ajout d'un complément d'adresse */
				if (adresse2 != null) {
					Ajax_Call("/VAD/CreationCompte?email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&type="+type.value+"&num_client="+num_client.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&adresse2="+adresse2.value+"&cp="+cp.value+"&ville="+ville+"&arg="+arg,null);
				} else {
					Ajax_Call("/VAD/CreationCompte?email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&type="+type.value+"&num_client="+num_client.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&cp="+cp.value+"&ville="+ville+"&arg="+arg,null);
				}
				/* Fin CBL : DI 286 : Ajout d'un complément d'adresse */
			}else{
				fillDivWithMsg(NOM_DIV_MSG, "Email incorrect");
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			}
		}
	}
		
}

/* Fonction : Modification de compte*/
function modificationCompte(type) {
	var clientId=document.getElementById("clientId");
	var exp = new RegExp("^([a-zA-Z0-9\-])*$","g");
	if(clientId!=null) {
		var error='';
		var civiliteM=document.getElementById("info_mradio");
		var civiliteMm=document.getElementById("info_mmeradio");
		var civiliteMle=document.getElementById("info_mlleradio");
		var nom=document.getElementById("info_nom_client");
		var prenom=document.getElementById("info_prenom_client");
		var jour=document.getElementById("info_jj_naissance");
		var mois=document.getElementById("info_mm_naissance");
		var annee=document.getElementById("info_aaaa_naissance");

		if(type=="id") {
			if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked) error+='Veuillez selectionner une civilite<br />';
			if(nom==null || nom.value=='') error+='Veuillez saisir votre nom<br />';
			// CBL : Ajout RDG : Le nom doit comporter au minimum 2 caractères
			else if (nom.value.length < 2) error+='Le nom doit comporter au minimum 2 caractères<br />';
			// Fin CBL
			else if( ! isStandardChaine(nom.value) ) error+='Le nom saisi n\'est pas correct<br />';
			if(prenom==null || prenom.value=='') error+='Veuillez saisir votre prenom<br />';
			else if( ! isStandardChaine(prenom.value) ) error+='Le prenom saisi n\'est pas correct<br />';
			if((jour==null || mois==null || annee==null) || ((jour.value!='' || mois.value!='' || annee.value!='') && (jour.value=='' || mois.value=='' || annee.value==''))) 
			error+='Veuillez selectionner votre date de naissance<br />';
			else
			if(!isDate(mois.value + '-' + jour.value + '-' + annee.value))
			  error+='La date de naissance saisie n\'est pas correcte<br />';
			if(error!=''){
				fillDivWithMsg(NOM_DIV_MSG, error);
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			} else {
				var civilite = '1';
				if(civiliteMm.checked) civilite='2';
				if(civiliteMle.checked) civilite='3';
				Ajax_Call("/VAD/ModificationCompte?clientId="+clientId.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&type="+type,null);
			}
		} else if(type=="email") {
			var email=document.getElementById("info_new_email");
			var mdp=document.getElementById("info_mdp");

			if(email==null || email.value=='') error+='Veuillez saisir le nouvel email.<br />';
			else if( ! isStandardEmail($("#info_new_email").val()) ) error+='L\'email n\'est pas correct.<br />'; 
			if(mdp==null || mdp.value=='') error+='Veuillez saisir un mot de passe.<br />'; 
			else{
				if(!exp.test(mdp.value)){
					error+='Le mot de passe contient des caractères spéciaux.<br />';
				}else
					if (mdp!=null && mdp.value.length<6) error+='Le mot de passe n\'est pas assez long.<br />';
			}
			if(error!=''){
				fillDivWithMsg(NOM_DIV_MSG, error);
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			} else {
				Ajax_Call("/VAD/ModificationCompte?clientId="+clientId.value+"&email="+email.value+"&mdp="+mdp.value+"&type="+type,null);
			}
		} else if(type=="mdp") {
			var old_mdp=document.getElementById("info_old_mdp");
			var new_mdp=document.getElementById("info_new_mdp");
			var confirm_mdp=document.getElementById("info_confirm_mdp");
			if(old_mdp==null || old_mdp.value=='') error+='Veuillez saisir l\'ancien mot de passe.<br />';
			else if (old_mdp!=null && old_mdp.value.length<6) error+='L\'ancien mot de passe n\'est pas assez long.<br />';
			if(new_mdp==null || new_mdp.value=='') error+='Veuillez saisir le nouveau mot de passe.<br />'; 
			else{
				if(!exp.test(new_mdp.value)){
					error+='Le nouveau mot de passe contient des caractères spéciaux.<br />';
				}else
					if (new_mdp!=null && new_mdp.value.length<6) error+='Le nouveau mot de passe n\'est pas assez long.<br />';
			}
			if(confirm_mdp==null || confirm_mdp.value==''){
				error+='Veuillez saisir le mot de passe de confirmation.<br />'; 
			}else{
				if (confirm_mdp!=null && confirm_mdp.value.length<6){
					error+='Le mot de passe de confirmation n\'est pas assez long.<br />';
				}else{
					if(confirm_mdp.value!=new_mdp.value){
						error+='Le mot de passe de confirmation doit être identique au nouveau mot de passe.<br />';
					}
				}
			}
			if(error!=''){
				fillDivWithMsg(NOM_DIV_MSG, error);
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			} else {
				Ajax_Call("/VAD/ModificationCompte?clientId="+clientId.value+"&old_mdp="+old_mdp.value+"&new_mdp="+new_mdp.value+"&confirm_mdp="+confirm_mdp.value+"&new_mdpC="+hex_sha1(new_mdp.value)+"&type="+type,null);
			}
		} else if(type=="intAndNews") {
			var radiooui=document.getElementById("radiooui");
			var radiooui2=document.getElementById("radiooui2");
			var totalNews = document.getElementById("totalNews");
			var totalCentreInt = document.getElementById("totalCentreInt");
			var centres = '';
			/* TODO: radio à recuperer dynamiquement (ils sont deja generes dynamiquement dans la xsl */
			var offres_quelle = (document.getElementById("newsoui_1").checked) ? "OUI" : "NON";
			var offres_partenaires = (document.getElementById("newsoui_2").checked) ? "OUI" : "NON";
			/*for(i = 1; i<=totalCentreInt.value; i++){
				if(document.getElementById("centre_int_"+i).checked == true)
					centres+='&centre='+(document.getElementById("centre_int_"+i).value);
			}*/
			Ajax_Call("/VAD/CentreNewsletter?id_client="+clientId.value+"&modifFlag=1"+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,null);
		}
	}
}
//VSN FIN DI 982 : Nouvelle page de création de compte client-
function saveNL(clientId){
	var offres_partenaires=document.getElementById("radiooui2");
	var offres_quelle=document.getElementById("radiooui");
	var centres = '';
//	for(i = 0; i<document.centreI.centreInteret.length; i++){
//		if(document.centreI.centreInteret[i].checked == true)
//			centres+='&centre='+(document.centreI.centreInteret[i].value);
//	}
	offres_quelle = (document.getElementById("radiooui").checked) ? "OUI" : "NON";
	offres_partenaires = (document.getElementById("radiooui2").checked) ? "OUI" : "NON";
	Ajax_Call("/VAD/CentreNewsletter?action=saveNL&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle,null);
}

function saveNLWithParam(arg,clientId){

	var offres_partenaires=document.getElementById("radiooui2");
	var offres_quelle=document.getElementById("radiooui");
	var centres = '';
	for(i = 0; i<document.centreI.centreInteret.length; i++){
		if(document.centreI.centreInteret[i].checked == true)
			centres+='&centre='+(document.centreI.centreInteret[i].value);
	}
	offres_quelle = (document.getElementById("radiooui").checked) ? "OUI" : "NON";
	offres_partenaires = (document.getElementById("radiooui2").checked) ? "OUI" : "NON";
	Ajax_Call("/VAD/CentreNewsletter?action=saveNL&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres+"&arg="+arg,null);
}
//VSN FIN DI 982 : Nouvelle page de création de compte client-

/* Fonction : ajout centre interet et newsletter*/
function saveCentresNewsletter(){
	var clientId = document.getElementById("id_client");
	var offres_partenaires=document.getElementById("radiooui2");
	var offres_quelle=document.getElementById("radiooui");
	/* CBL DI 980 : gestion de la création de compte dans le cadre d'un prospect */
	var lightBoxName = document.getElementById("lb");
	/* FIN CBL DI 980 : gestion de la création de compte dans le cadre d'un prospect */
	var centres = '';
	for(i = 0; i<document.centreI.centreInteret.length; i++){
		if(document.centreI.centreInteret[i].checked == true)
			centres+='&centre='+(document.centreI.centreInteret[i].value);
	}
	offres_quelle = (document.getElementById("radiooui").checked) ? "OUI" : "NON";
	offres_partenaires = (document.getElementById("radiooui2").checked) ? "OUI" : "NON";
	/* CBL DI 980 : gestion de la création de compte dans le cadre d'un prospect */
	//Ajax_Call("/VAD/CentreNewsletter?id_client="+clientId.value+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,null);
	Ajax_Call("/VAD/CentreNewsletter?id_client="+clientId.value+"&lb="+lightBoxName.value+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,null);
	/* FIN CBL DI 980 : gestion de la création de compte dans le cadre d'un prospect */
}

/* VSN duplication avec ppassage de param. Fonction : ajout centre interet et newsletter*/
function saveCentresNewsletterWithParam(arg){
	var clientId = document.getElementById("id_client");
	var offres_partenaires=document.getElementById("radiooui2");
	var offres_quelle=document.getElementById("radiooui");
	var centres = '';
	for(i = 0; i<document.centreI.centreInteret.length; i++){
		if(document.centreI.centreInteret[i].checked == true)
			centres+='&centre='+(document.centreI.centreInteret[i].value);
	}
	offres_quelle = (document.getElementById("radiooui").checked) ? "OUI" : "NON";
	offres_partenaires = (document.getElementById("radiooui2").checked) ? "OUI" : "NON";
	Ajax_Call("/VAD/CentreNewsletter?id_client="+clientId.value+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres+"&arg="+arg,null);
}

/* Fonction : ajout adresse*/
function addAdresse(source){
	var clientId = $("#clientId").val();
	var adresseId = $("#adresseId").val();
	var libelle = $("#libelle_a").val();
	var civiliteM=document.getElementById("mradio");
	var civiliteMm=document.getElementById("mmeradio");
	var civiliteMle=document.getElementById("mlleradio");
	var nom = $("#nom_a").val();
	var prenom = $("#prenom_a").val();
	var adresse1 = $("#adresse1").val();
	var adresse2 = $("#adresse2").val();
	var adresse3  = $("#adresse3").val();
	var complement = $("#info").val();
	var cp = $("#cp").val();
	var ville = $("#ville").val();
	var tel = $("#tel").val();
	var mobile = $("#mobile").val();
	var smsOui = document.getElementById("smsOui");
	var principaleOui = document.getElementById("principaleOui");
	var panierId = 	$("#panierId").val();
	var error='';
	if(libelle==null || libelle=='') error+='Veuillez donner un nom a l\'adresse<br />';
	if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked)
		error+='Veuillez selectionner une civilite<br />';
	if(nom==null || nom=='') 
		error+='Veuillez saisir votre nom<br />';
	// CBL : Ajout RDG : Le nom doit comporter au minimum 2 caracteres
	else if (nom.length < 2) 
		error+='Le nom doit comporter au minimum 2 caractères<br />';
	// Fin CBL
	else if( ! isStandardChaine(nom) ) 
		error+='Le nom saisi n\'est pas correct<br />';
	if(prenom==null || prenom=='') 
		error+='Veuillez saisir votre prenom<br />';
	else if( ! isStandardChaine(prenom) ) 
		error+='Le prenom saisi n\'est pas correct<br />';
	if(adresse1==null || adresse1=='') 
		error+='Veuillez saisir votre adresse<br />';
	if(adresse1.indexOf(';')>=0)
		error +='Le champs adresse ne doit pas contenir de point-virgule<br />';
	if(cp==null || cp=='') 
		error+='Veuillez saisir votre code postal<br />';
	if(source!=null && source=='panierM')
		if(cp==null || cp>='97000') 
			error+='Vous devez saisir une adresse en France Métropolitaine.<br />';
	if(source!=null && source=='panierDom')
		if(cp==null || cp<'97000') 
			error+='Vous devez saisir une adresse dans les DOM.<br />';
	if(ville==null || ville=='') 
		error+='Veuillez saisir votre ville<br />';
	if( tel!=null && tel!='' && ! isStandardTel(tel) ) 
		error+='Le téléphone saisi n\'est pas correct, celui-ci doit comporter 10 chiffres.<br />';
	if( mobile!=null && mobile!='' && ! isStandardMobile(mobile) ) 
		error+='Le téléphone mobile saisi n\'est pas correct, celui-ci doit comporter 10 chiffres.';
	var civilite = '1';
	if(civiliteMm.checked) civilite='2';
	if(civiliteMle.checked) civilite='3';
	var telmob='';
	if(mobile!=null) telmob=mobile;
	var sms = '0';
	if(smsOui!=null && smsOui.checked) sms='1';
	if(sms=='1' && (mobile==null || mobile=='')) error+='Veuillez saisir votre numéro de mobile.';
	var principale = '0';
	if($("#principaleOui").val() != null && $("#principaleOui").val()!=""){
		principale = $("#principaleOui").val() ;
	}else{
		var principale = '0';
		if(principaleOui==null || principaleOui.checked) principale='1';
	}
	if(error!=''){
		fillDivWithMsg(NOM_DIV_MSG, error);
		switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		var param="libelle="+libelle;
		param+="&clientId="+clientId;
		param+="&adresseId="+adresseId;
		param+="&civilite="+civilite;
		param+="&nom="+nom;
		param+="&prenom="+prenom;
		param+="&adresse1="+adresse1;
		param+="&adresse2="+adresse2;
		param+="&adresse3="+adresse3;
		param+="&info="+complement;
		param+="&cp="+cp;
		param+="&ville="+ville;
		param+="&tel="+tel;
		param+="&mobile="+telmob;
		param+="&sms="+sms;
		param+="&principale="+principale;
		if(panierId!=null){
			var montantLivClassique = $("input[name=livraison]:checked").val();
			var montantLivComplement = $("input[name=livraison1]:checked").val();
			var modeLiv = $("input[name=modLiv]").val();
			var lieuLiv = $("input[name=lieuLiv]").val();
			var tauxLiv = $("input[name=tauxLiv]").val();
			if(montantLivClassique == undefined){
				montantLivClassique=$("input[name=livraison]").val();
			}
			if(montantLivComplement == undefined) montantLivComplement=0;
			param+="&panierId="+panierId;
			param+="&modeLiv="+modeLiv;
			param+="&lieuLiv="+lieuLiv;
			param+="&montantLivClassique="+montantLivClassique;
			param+="&montantLivComplement="+montantLivComplement;
			param+="&tauxLiv="+tauxLiv;
		}
		if(source=='lb21'){
			param+="&close=1";
			if(adresseId== null || adresseId=='' || adresseId=='0'){
				Ajax_Call("/VAD/CreationAdresse?"+param,null);
			}else{
				Ajax_Call("/VAD/UpdateAdresse?"+param,null);
			}
		}else{
			if(adresseId== null || adresseId=='' || adresseId=='0'){
				Ajax_Call("/VAD/CreationAdresse?"+param,null);
			}else{
				Ajax_Call("/VAD/UpdateAdresse?"+param,null);
			}
		}
	}
}

/* Fonction : verification adresse avant suppression*/
function verifSuppression(adresseId){
	Ajax_Call("/VAD/VerificationSuppression?adresseId="+adresseId,null);
}

/* Fonction : verification adresse avant suppression*/
function suppression(){
	var adresseId = document.getElementById("adresseId_supp");
	Ajax_Call("/VAD/SuppressionAdresse?adresseId="+adresseId.value,null);
}

/* Fonction : ouverture d'une popup pour le suivi des commandes */
function openPopupSuivi(lien) {
	window.open( lien, 'Transporteur', 'menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=800,height=600', true );
}

/* Fonction : ouverture d'une popup pour la carte privilege */
function openPopupCartePrivilege(lien) {
	window.open( lien, 'Carte_Privilege', 'menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=800,height=600', true );
}

/* Fonction : ouverture d'une popup pour la carte privilege */
function openPopupStandard(lien) {
	window.open( lien, 'Quelle', 'menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=800,height=600', true );
}

/* Fonction : verifier si un client est identifier ou non*/
function verficationIdentification(){
	Ajax_Call("/VAD/VerificationIdentification",null);
}

/**
* Validation du formulaire de contact avec le theme et le sous theme
*/
function valideContact(theme,sousTheme){
	var nameform = "#contact_"+theme+"_"+sousTheme;
	var rensSuppl = $(nameform+" input[name=rensSuppl]:checked").val();
	var message = $(nameform+" textarea[name=message]").val();
	var erreur=false;
	if(!tunnelVerifAllChamp(nameform)){
		erreur=true; 	
	}
	if($(nameform+" input[name=rensSuppl]").val()!=undefined && rensSuppl==undefined){
		$(nameform+" input[name=rensSuppl]:first").before("<a class='msgErr'> Veuillez selectionner l\'objet de votre demande <br /></a>");	
		erreur=true;
	}
	if(!erreur){
		$.post("/VAD/ValidFormContact",
				$(nameform).serialize(),
			function(data){			
				traitementAjaxResult(data);
				/*lightbox('lb19');*/
				setTimeout("f_enableBtContact()",2000);
				//f_enableBtContact();
			}
		);
	} else {
		f_enableBtContact();
	}
}

function f_enableBtContact() {
	//var allBtContact = $('img[idTheme], img[idSsTheme]');
	var allBtContact = $("img[idtheme]");
	allBtContact.unbind('click');
	allBtContact.one(
			'click', 
			function() {
				valideContact($(this).attr('idtheme'),$(this).attr('idsstheme'));
			}
		);
}

function getInfoAdresse(){
	var adresseId = document.getElementById("adresseId");
	/* si @ principale, #principaleOui="1", sinon "0" => par défaut il est à "1" */
	if (adresseId.value==$("#id_principale").val()) {
		$("#principaleOui").val("1");
	} else {
		$("#principaleOui").val("0");
	}
	Ajax_Call("/VAD/InfoAdresse?adresseId="+adresseId.value,f_displayBlocAdresse);
}

function f_displayBlocAdresse() {
	if (($("#principaleOui").val() == "1") && ($("#isCarded").val() == "1")){
		$('#mradio').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#mmeradio').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#mlleradio').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#libelle_a').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#nom_a').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#prenom_a').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#adresse1').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#adresse2').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#adresse3').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#info').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#cp').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#ville').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#tel').attr('disabled', 'true').css('background-color', '#F3F3F3');
		$('#mobile').attr('disabled', 'true').css('background-color', '#F3F3F3');
		/* On rend saisissable le code postal et la ville si la localité a une valeur null */
		if ($("#ville").val() == "null") {
			$('#cp').removeAttr('disabled').css('background-color', '');
			$('#ville').removeAttr('disabled').css('background-color', '');
		}
		if ((($("#tel").val() == "null") || ($("#tel").val() == "")) && ($("#tel").is('.required'))) {
			$('#tel').removeAttr('disabled').css('background-color', '');
		}
	} else {
		$('#mradio').removeAttr('disabled').css('background-color', '');
		$('#mmeradio').removeAttr('disabled').css('background-color', '');
		$('#mlleradio').removeAttr('disabled').css('background-color', '');
		$('#libelle_a').removeAttr('disabled').css('background-color', '');
		$('#nom_a').removeAttr('disabled').css('background-color', '');
		$('#prenom_a').removeAttr('disabled').css('background-color', '');
		$('#adresse1').removeAttr('disabled').css('background-color', '');
		$('#adresse2').removeAttr('disabled').css('background-color', '');
		$('#adresse3').removeAttr('disabled').css('background-color', '');
		$('#info').removeAttr('disabled').css('background-color', '');
		$('#cp').removeAttr('disabled').css('background-color', '');
		$('#ville').removeAttr('disabled').css('background-color', '');
		$('#tel').removeAttr('disabled').css('background-color', '');
		$('#mobile').removeAttr('disabled').css('background-color', '');
	}
}

/* Fonction : CDGP 3 Clics */
function CDGP3C () {
	$.ajax({
		type: "GET",
		url: "/VAD/CDGPValidation",
		async: true,
		dataType: "html",
		error:function(msg){},
		success:function(data){
			traitementAjaxResult(data);
		}
	});  
}

/**
* Methode de validation de la newletter
*/
function CDGP3CValidNewsLetter(){
	var cookie = getJsonCookie("QuelleInfoClient");
	var clientId = cookie.emId;
	var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
	var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
	var centres = '';
	$("#error_offres_partenaires").hide();
	$("#error_offres_quelle").hide();
	if (offres_partenaires == undefined) {
		$("#error_offres_partenaires").show();
	} 
	if (offres_quelle == undefined){
		$("#error_offres_quelle").show();
	} 
	if(offres_partenaires != undefined && offres_quelle != undefined) {
		$(".check").each(function(){
			// Récupération des centres d'interet
			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
				centres+='&centre='+$(this).val();
			}
		});
		// Soumission du formulaire des centres d'interet
		$.get("/VAD/CentreNewsletter?src=CDGP&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,
				function(data){
			traitementAjaxResult(data);
		});
	}
}

/* Fonction : verification de l'identification du client */
function verifNewsletter(){
	Ajax_Call("/VAD/VerifNewsletterControl",null);
}

//CBL : Fonction pour la validation de la demande de catalogue
function DdeCat () {
	//alert("ddecat : code bulletin = " + getParamValue("bulletin"));
	/* CBL : Récupération du code bulletin en paramètre */
	var codeBulletin = getParamValue("bulletin");
	$.ajax({
		type: "GET",
		url: "/VAD/DdeCatValidation?bulletin="+codeBulletin,
		async: true,
		dataType: "html",
		error:function(msg){},
		success:function(data){
			traitementAjaxResult(data);
		}
	});  	
}

/* CBL Fonction : modification d'adresse lors de la demande de catalogue */
function ddeCatModifAdresse(){
	/* CBL : Récupération du code bulletin en paramètre de l'url */
	var codeBulletin = getParamValue("bulletin");
	//alert("ddeCatModifAdresse : code bulletin = "+ codeBulletin);
	/* Fin CBL : Récupération du code bulletin en paramètre de l'url */
	var clientId = $("#clientId").val();
	var adresseId = $("#adresseId").val();
	var libelle = $("#libelle_a").val();
	var civiliteM=document.getElementById("mradio");
	var civiliteMm=document.getElementById("mmeradio");
	var civiliteMle=document.getElementById("mlleradio");
	var nom = $("#nom_a").val();
	var prenom = $("#prenom_a").val();
	var adresse1 = $("#adresse1").val();
	var adresse2 = $("#adresse2").val();
	var adresse3  = $("#adresse3").val();
	var complement = $("#info").val();
	var cp = $("#cp").val();
	var ville = $("#ville").val();
	var tel = $("#tel").val();
	var mobile = $("#mobile").val();
	var smsOui = document.getElementById("smsOui");
	var principaleOui = $("#principaleOui").val();
	var error = '';
	if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked)
		error += 'Veuillez selectionner une civilite<br />';
	if(nom == null || nom == '') 
		error+='Veuillez saisir votre nom<br />';
	else if (nom.length < 2) 
		error+='Le nom doit comporter au minimum 2 caractères<br />';
	else if( !isStandardChaine(nom) ) 
		error += 'Le nom saisi n\'est pas correct<br />';
	if(prenom == null || prenom == '') 
		error += 'Veuillez saisir votre prenom<br />';
	else if( !isStandardChaine(prenom) ) 
		error += 'Le prenom saisi n\'est pas correct<br />';
	if(adresse1 == null || adresse1 == '') 
		error += 'Veuillez saisir votre adresse<br />';
	if(adresse1.indexOf(';') >= 0)
		error += 'Le champs adresse ne doit pas contenir de point-virgule<br />';
	if(cp == null || cp == '') 
		error += 'Veuillez saisir votre code postal<br />';
	if(ville == null || ville == '') 
		error += 'Veuillez saisir votre ville<br />';
	if (tel != null && tel == 'null') tel = '';
	if (mobile != null && mobile == 'null') mobile = '';
	if( tel != null && tel != '' && !isStandardTel(tel) ) 
		error += 'Le téléphone saisi n\'est pas correct, celui-ci doit comporter 10 chiffres.<br />';
	if( mobile != null && mobile != '' && !isStandardMobile(mobile) ) 
		error += 'Le téléphone mobile saisi n\'est pas correct, celui-ci doit comporter 10 chiffres.';
	var civilite = '1';
	if(civiliteMm.checked) civilite='2';
	if(civiliteMle.checked) civilite='3';
	var sms = '0';
	if(smsOui != null && smsOui.checked) sms = '1';
	var telmob='';
	if(mobile!=null) telmob=mobile;
	var principale = '0';
	if($("#principaleOui").val() != null && $("#principaleOui").val()!=""){
		principale = $("#principaleOui").val() ;
	} else {
		var principale = '0';
		if(principaleOui==null || principaleOui.checked) principale='1';
	}
	if(error!=''){
		fillDivWithMsg(NOM_DIV_MSG, error);
		switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		var param = "libelle=" + libelle;
		param += "&clientId=" + clientId;
		param += "&adresseId=" + adresseId;
		param += "&civilite=" + civilite;
		param += "&nom=" + nom;
		param += "&prenom=" + prenom;
		param += "&adresse1=" + adresse1;
		param += "&adresse2=" + adresse2;
		param += "&adresse3=" + adresse3;
		param += "&info=" + complement;
		param += "&cp=" + cp;
		param += "&ville=" + ville;
		param += "&tel=" + tel;
		param += "&mobile=" + telmob;
		param += "&sms=" + sms;
		param += "&principale=" + principale;
		/* CBL : Passage du code bulletin en paramètre de l'url */
		param += "&bulletin=" + codeBulletin;
		/* CBL : Passage du code bulletin en paramètre de l'url */
		// Appel à  la servlet de modification d'adresse
		Ajax_Call("/VAD/UpdateAdresseDdeCat?"+param,null);
	}
}

/*********************************************************/
/***** ANCIEN CONTENU tunnel                          ****/
/*********************************************************/
/* Fonction : switch du panier rapide (on/off) */
function toggle_panier(pr) {
	if ($("#" + pr).is(':hidden')){
		$("#" + pr).slideDown('slow');
	} else {              
		$("#" + pr).slideUp('slow'); 
	}
}

/* AB Testing déportation des fonction check_bulletin(obj) et tunnelValidCodeBullettin() 
 * dans le fichier fonction_tunnel_20100930.js */

/**
 * Methode d'identification du compte
 * @param nomFormLogin nom du formulaire de login
 */
function CDGPAuthenticate(nomFormLogin){
	if(tunnelVerifAllChamp("."+nomFormLogin)){
		varLogin = $("#"+nomFormLogin+"_email_client").val();
		varPass = $("#"+nomFormLogin+"_pass_client").val();
		passwordCrypte= varPass;//hex_sha1(varPass);
		$("#auth_loader").show();
		$.get("/VAD/Identification",
				{login : varLogin , pass : passwordCrypte, source : 'CDGP'},
				function(data){
					$("#auth_loader").hide();
					traitementAjaxResult(data);
				}
		);	
	}
}

//---------------------------------------------------
//	Function de l'authentification
//---------------------------------------------------
/**
 * Script de validation de la creation de l'espace client
 */
function tunnelCreationEspace1(){
	var varCiv = $(".auth_creation_espace1 input[name=civilite]:checked").val();
	/* DI 990 Impossible de créer un compte web pour une cliente existante */
	var varDejaconnu = $(".auth_creation_espace1 input[name=dejaconnu]").val();
	var varType = $(".auth_creation_espace1 input[name=type]").val();
	/* FIN DI 990 Impossible de créer un compte web pour une cliente existante */
	// Verification de la civilité
	if(varCiv == undefined){
		$("#civilite_error").show();
	}else{
		$("#civilite_error").hide();
	}
	// Verification de la date de naissance
	if($("#jj_naissance").val()=="" && $("#mm_naissance").val()=="" && $("#aaaa_naissance").val()=="" || $("#jj_naissance").val()!="" && $("#mm_naissance").val()!="" && $("#aaaa_naissance").val()!=""){
		$("#naissance_error").hide();
		flagDateNaiss = true;
	} else {
		$("#naissance_error").show();
		flagDateNaiss = false;
	}
	if(tunnelVerifAllChamp(".auth_creation_espace1") && varCiv!=undefined && flagDateNaiss){
		varNom = $(".auth_creation_espace1 input[name=nom_client]").val();
		varPrenom = $(".auth_creation_espace1 input[name=prenom_client]").val();
		varJour = $(".auth_creation_espace1 select[name=jj_naissance]").val(); 
		varMois = $(".auth_creation_espace1 select[name=mm_naissance]").val(); 
		varAnnee = $(".auth_creation_espace1 select[name=aaaa_naissance]").val(); 
		varMail = $(".auth_creation_espace1 input[name=email_client]").val(); 
		varPassword = $(".auth_creation_espace1 input[name=pass_client]").val(); 
		varConfPass = $(".auth_creation_espace1 input[name=confirm_pass]").val(); 
		//varCaptcha = $(".auth_creation_espace1 input[name=captcha]").val(); 
		varNumClient = $(".auth_clientcat_num input[name=num_client]").val(); 
		varAdresse = $(".auth_creation_espace1 input[name=adresse1]").val();
		/* CBL : DI 286 : Ajout d'un complement d'adresse */
		varCplAdresse = $(".auth_creation_espace1 input[name=adresse2]").val();
		/* CBL : DI 286 : Ajout d'un complement d'adresse */
		varCp = $(".auth_creation_espace1 input[name=cp]").val();
		varVille = $(".auth_creation_espace1 select[name=ville]").val();
		$("#auth_creation_espace1_loader").show();
		/* DI 990 Impossible de créer un compte web pour une cliente existante */
		if (varType=="prospect" && varDejaconnu=="oui") {
			$.post("/VAD/ModificationCompte",
					{
					clientId : $(".auth_creation_espace1 input[name=client_id]").val(),
					emCodeClient : $(".auth_creation_espace1 input[name=emCodeClient]").val(),
					dejaConnu : varDejaconnu,
					nom : varNom , 
					prenom : varPrenom,
					email : varMail , 
					civilite : varCiv, 
					jour : varJour,
					mois : varMois,
					annee : varAnnee,
					pass : varPassword ,
					passC : hex_sha1(varPassword),
					type: varType,
					src: 'tunnel',
					num_client : varNumClient,
					adresse1 : varAdresse,
					adresse2 : varCplAdresse,
					cp : varCp,
					ville : varVille
					},
					function(data){
						$("#auth_creation_espace1_loader").hide();
						traitementAjaxResult(data);
					}
				);
		} else {
			$.post("/VAD/CreationCompte",
				{
				nom : varNom , 
				prenom : varPrenom,
				email : varMail , 
				civilite : varCiv, 
				jour : varJour,
				mois : varMois,
				annee : varAnnee,
				pass : varPassword ,
				passC : hex_sha1(varPassword),
				//captcha: varCaptcha,
				type: 'i',
				src: 'tunnel',
				num_client : varNumClient,
				adresse1 : varAdresse,
				/* CBL : DI 286 : Ajout d'un complement d'adresse */
				adresse2 : varCplAdresse,
				/* CBL : DI 286 : Ajout d'un complement d'adresse */
				cp : varCp,
				ville : varVille
				},
				function(data){
					$("#auth_creation_espace1_loader").hide();
					traitementAjaxResult(data);
				}
			);
		}
		/* FIN DI 990 Impossible de créer un compte web pour une cliente existante */
	}
}

/**
* Script de validation de la creation de l'espace client
*/
function tunnelCreationEspace1ABTesting(paramAB){
	var varCiv = $(".auth_creation_espace1 input[name=civilite]:checked").val();
	// Verification de la civilité
	if(varCiv == undefined){
		$("#civilite_error").show();
	}else{
		$("#civilite_error").hide();
	}
	// Verification de la date de naissance
	if($("#jj_naissance").val()=="" && $("#mm_naissance").val()=="" && $("#aaaa_naissance").val()=="" || $("#jj_naissance").val()!="" && $("#mm_naissance").val()!="" && $("#aaaa_naissance").val()!=""){
		$("#naissance_error").hide();
		flagDateNaiss = true;
	} else {
		$("#naissance_error").show();
		flagDateNaiss = false;
	}
	if(tunnelVerifAllChamp(".auth_creation_espace1") && varCiv!=undefined && flagDateNaiss){
		varNom = $(".auth_creation_espace1 input[name=nom_client]").val();
		varPrenom = $(".auth_creation_espace1 input[name=prenom_client]").val();
		varJour = $(".auth_creation_espace1 select[name=jj_naissance]").val(); 
		varMois = $(".auth_creation_espace1 select[name=mm_naissance]").val(); 
		varAnnee = $(".auth_creation_espace1 select[name=aaaa_naissance]").val(); 
		varMail = $(".auth_creation_espace1 input[name=email_client]").val(); 
		varPassword = $(".auth_creation_espace1 input[name=pass_client]").val(); 
		varConfPass = $(".auth_creation_espace1 input[name=confirm_pass]").val(); 
		//varCaptcha = $(".auth_creation_espace1 input[name=captcha]").val(); 
		varNumClient = $(".auth_clientcat_num input[name=num_client]").val(); 
		varAdresse = $(".auth_creation_espace1 input[name=adresse1]").val();
		/* CBL : DI 286 : Ajout d'un complement d'adresse */
		varCplAdresse = $(".auth_creation_espace1 input[name=adresse2]").val();
		/* CBL : DI 286 : Ajout d'un complement d'adresse */
		varCp = $(".auth_creation_espace1 input[name=cp]").val();
		varVille = $(".auth_creation_espace1 select[name=ville]").val();
		$("#auth_creation_espace1_loader").show();
		$.post("/VAD/CreationCompte",
			{
			nom : varNom , 
			prenom : varPrenom,
			email : varMail , 
			civilite : varCiv, 
			jour : varJour,
			mois : varMois,
			annee : varAnnee,
			pass : varPassword ,
			passC : hex_sha1(varPassword),
			//captcha: varCaptcha,
			type: 'i',
			src: 'tunnel',
			num_client : varNumClient,
			adresse1 : varAdresse,
			/* CBL : DI 286 : Ajout d'un complement d'adresse */
			adresse2 : varCplAdresse,
			/* CBL : DI 286 : Ajout d'un complement d'adresse */
			cp : varCp,
			ville : varVille,
			AB : paramAB
			},
			function(data){
				$("#auth_creation_espace1_loader").hide();
				traitementAjaxResult(data);
			}
		);		
	}
}


//VSN DEBUT DI 981 [E] - PRIORITE 1 : Nouvelle organisation des rubriques du compte client 

/**
 * Methode de validation de la newletter
 */
//function tunnelValidNewsLetter(){
//	var cookie = getJsonCookie("QuelleInfoClient");
//	var clientId = cookie.emId;
//	//var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
//	//var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
//	var centres = '';
//	//	$("#error_offres_partenaires").hide();
//	//$("#error_offres_quelle").hide();
//	//	if (offres_partenaires == undefined) {
//		//$("#error_offres_partenaires").show();
//	//	} 
//	//if (offres_quelle == undefined){
//	//	$("#error_offres_quelle").show();
//	//} 
//	//if(offres_partenaires != undefined && offres_quelle != undefined) {
//		$(".check").each(function(){
//			// Recuperation des centres d'interet
//			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
//				centres+='&centre='+$(this).val();
//			}
//		});
////		// Soumission du formulaire des centres d'interet
////		$.get("/VAD/CentreNewsletter?src=tunnel&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,
////				function(data){
////			traitementAjaxResult(data);
////		});
//		// Soumission du formulaire des centres d'interet
//		$.get("/VAD/CentreNewsletter?src=tunnel&id_client="+clientId+centres,
//				function(data){
//			traitementAjaxResult(data);
//		});
//	//}
//}

function tunnelValidNewsLetter(){
var cookie = getJsonCookie("QuelleInfoClient");
var clientId = cookie.emId;

var centres = '';

	$(".check").each(function(){
		// Recuperation des centres d'interet
		if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
			centres+='&centre='+$(this).val();
		}
	});

	$.get("/VAD/CentreNewsletter?src=tunnel&id_client="+clientId+centres,
			function(data){
		traitementAjaxResult(data);
	});
}
//VSN FIN  DI 981 [E] - PRIORITE 1 : Nouvelle organisation des rubriques du compte client 

/** VSN ABTesting duppluication et passage de parametre AB 
 * Methode de validation de la newletter
 */
function tunnelValidNewsLetterABTesting(paramAB){
	var cookie = getJsonCookie("QuelleInfoClient");
	var clientId = cookie.emId;
	var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
	var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
	var centres = '';
	$("#error_offres_partenaires").hide();
	$("#error_offres_quelle").hide();
	if (offres_partenaires == undefined) {
		$("#error_offres_partenaires").show();
	} 
	if (offres_quelle == undefined){
		$("#error_offres_quelle").show();
	} 
	if(offres_partenaires != undefined && offres_quelle != undefined) {
		$(".check").each(function(){
			// Recuperation des centres d'interet
			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
				centres+='&centre='+$(this).val();
			}
		});
		// Soumission du formulaire des centres d'interet
		$.get("/VAD/CentreNewsletter?src=tunnel&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres+"&AB="+paramAB,
				function(data){
			traitementAjaxResult(data);
		});
	}
}

/**
 * Methode de validation de la newletter
 */
function tunnelValidNewsLetterCDGP(){
	var cookie = getJsonCookie("QuelleInfoClient");
	var clientId = cookie.emId;
	var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
	var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
	var centres = '';
	$("#error_offres_partenaires").hide();
	$("#error_offres_quelle").hide();
	if (offres_partenaires == undefined) {
		$("#error_offres_partenaires").show();
	} 
	if (offres_quelle == undefined){
		$("#error_offres_quelle").show();
	} 
	if(offres_partenaires != undefined && offres_quelle != undefined) {
		$(".check").each(function(){
			// Recuperation des centres d'interet
			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
				centres+='&centre='+$(this).val();
			}
		});
		// Soumission du formulaire des centres d'interet
		$.get("/VAD/CentreNewsletter?src=CDGP&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,
				function(data){
			traitementAjaxResult(data);
		});
	}
}

/**
 * Methode d'affichage en cas de creation de compte ok
 * Elle est lancee par la creation de compte controller
 */
function tunnelNewsLettrOk(){
	$('.auth_creation_espace2').fadeOut('fast',function(){
		window.location("/VAD/ModeLivraison");
	});	
}

/** VSN duplication pour le passage en parametre du cas AB testing 
 * Methode d'affichage en cas de creation de compte ok
 * Elle est lancee par la creation de compte controller
 */
function tunnelNewsLettrOkABTesting(paramAB){
	$('.auth_creation_espace2').fadeOut('fast',function(){
		window.location("/VAD/ModeLivraison?AB="+paramAB);
	});	
}

/**
 * Fonction pour afficher le formulaire en fonction du module de paiement choisi
 * @param div
 */
function tunnelShowPaiement(div){
	// Réactivation des champs
	$("input:disabled").each(function(){
		$(this).removeAttr("disabled");
	});
	// Remise en place de l'espace carte priviliege quelle
	$("#cpq_list_option").empty();
	$("#cqp_valide_num_button").show();
	$("#cpq_valide_paiement_button").hide();	
	// Remise en place de l'espace carte bleu
	$("#cb_cpq_propect").hide();
	$("#cb_valide_button").show();
	// affichage du mode de paiement
	if($(".paiement").is(":visible")){
		$(".paiement:visible").fadeOut("fast",function(){
			$("#"+div).fadeIn("fast");
		});
	}else{
		$("#"+div).fadeIn("fast");
	}
}



/**
 * Fonction quui valide le choix dans le cas d'une prospection CPQ
 * 
 */
function tunnelValideProspectCPQ(value){
	$(".msgErr").remove();
	// récupération du choix de la prospection
	varDemandeCarte = value;
	if(varDemandeCarte == undefined){
		$("#cb_label_carte_oui").after("<a class='msgErr'><br/> Ce champ est obligatoire. </a>");
	} else {
		$.post("/VAD/CarteBancaire",
			{action : "valide_prospection_cpq", 
			demandeCarte : varDemandeCarte},
			function(data){
				traitementAjaxResult(data);
			}
		);
	}
}

/**
 * Fonction qui affiche la prospection du client 
 */
function tunnelCbAfficheProspect(){
	// Désactivation des champs du formulaire
	$("#nom_cb").attr("disabled","disabled");
	$("#num_cb").attr("disabled","disabled");
	$("#cb_mois_expiration").attr("disabled","disabled");
	$("#cb_annee_expiration").attr("disabled","disabled");
	$("#cb_crypto").attr("disabled","disabled");
	// Affichage du menu de prospection
	$("#cb_cpq_propect").slideDown("normal");
	$("#cb_valide_button").slideUp("normal");
}

/**
 * Fonction d'affichage de l'erreur sur controle de validite d'une carte
 * @param div Id ou mettre l'erreur
 * @param message Message de l'erreur
 */
function tunnelPaiementErreur(div,message){
	$("#"+div).html("<strong>"+message+"</strong>");
}

/**
 * Fonction de validation du numéro de carte privilege quelle
 * Cette méthode fait un appel ajax renvoie le message 
 * d'erreur ou la liste des omptions disponilble si le code retour est ok
 */
function tunnelPaiementValideNumCpq(){
	tunnelPaiementErreur('cpq_erreur',"");
	var num_cpq = $("#num_cpq").val();
	$.post("/VAD/CartePrivilegeQuelle",
		{action:"valide_numero",
		numero : num_cpq},
		function(data){
			traitementAjaxResult(data);
		}
	);
}

/**
 * Fonction qui valide l'option de paiement
 */
function tunnelPaiementValideOptionCpq(){
	var num_cpq = $("#num_cpq").val();
	var varOption = $("input[name=cpq_option_paiement]:checked").val();
	tunnelPaiementErreur('cpq_erreur',"");
	if(varOption == undefined){
		tunnelPaiementErreur('cpq_erreur',"Veuillez renseigner le numéro de l'option");
	}else{
		$.post("/VAD/CartePrivilegeQuelle",
			{action:"valide_paiement",
			numero : num_cpq,
			option : varOption},
			function(data){
				traitementAjaxResult(data);
			}
		);
	}
}


/**
 * Fonction qui valide l'option de paiement
 */
function tunnelPaiementValideOptionCpqSug(){
	var num_cpq = $("#num_cpq_sug").val();
	var varOption = $("input[name=cpq_option_paiement]:checked").val();
	tunnelPaiementErreur('cpq_sug_erreur',"");
	if(varOption == undefined){
		tunnelPaiementErreur('cpq_sug_erreur',"Veuillez renseigner le numéro de l'option");
	}else{
		$.post("/VAD/CartePrivilegeQuelle",
			{action:"valide_paiement",
			numero : num_cpq,
			option : varOption},
			function(data){
				traitementAjaxResult(data);
			}
		);
	}
}

/**
 * Fonction d'affichage des options de paiement
 */
function tunnelPaiementAfficheOptionCPQ(){
	$("#num_cpq").attr("disabled","disabled");
	$("#cqp_valide_num_button").slideUp("normal");
	$("#cpq_list_option").slideDown("normal",function(){
		$("#cpq_valide_paiement_button").slideDown("normal");	
	});
}

/**
 * Fonction d'affichage des options de paiement
 */
function tunnelPaiementAfficheOptionCPQSug(){
	$("#num_cpq_sug").attr("disabled","disabled");
	$("#cqp_valide_num_button").slideUp("normal");
	$("#cpq_sug_list_option").slideDown("normal",function(){
		$("#cpq_valide_paiement_button_sug").slideDown("normal");	
	});
}

/**
 * Méthode d'ajout d'une option de paiement
 * @param value valeur de l'option
 * @param libelle Libelle de l'option
 * @param enabled Option enabled ou non
 * @param message Message en cas de non disponibilité
 * 
 */
function tunnelPaiementCpqAddOption(value,libelle,enabled,message){
	var disabled ="";
	if(!enabled){
		disabled="disabled";
	}
	var html = "<div class='rowtunnel cpq_option'>"+
	"<span class='label'></span>" +
	"<span class='champ'>" +
	"<input type='radio' class='boutonradio' name='cpq_option_paiement' value=\"" +
	value + "\" "+ disabled + "/><label ><strong>"+libelle+"</strong></label>";
	if(message !=""){
		html += "<span class='rose'>("+message +")</span>";
	}
	html +="</span>	</div>";	
	$("#cpq_list_option").append(html);
}


/**
 * Méthode d'ajout d'une option de paiement
 * @param value valeur de l'option
 * @param libelle Libelle de l'option
 * @param enabled Option enabled ou non
 * @param message Message en cas de non disponibilité
 * 
 */
function tunnelPaiementCpqAddOptionSug(value,libelle,enabled,message){
	var disabled ="";
	if(!enabled){
		disabled="disabled";
	}
	var html = "<div class='rowtunnel cpq_option'>"+
	"<span class='label'></span>" +
	"<span class='champ'>" +
	"<input type='radio' class='boutonradio' name='cpq_option_paiement' value=\"" +
	value + "\" "+ disabled + "/><label ><strong>"+libelle+"</strong></label>";
	if(message !=""){
		html += "<span class='rose'>("+message +")</span>";
	}
	html +="</span>	</div>";	
	$("#cpq_sug_list_option").append(html);
}

/**
 * Méthode qui supprime les options de paiement lors de la mise
 * A jour des options de paiements
 */
function tunnelPaiementCpqClearOption(){
	$("#cpq_list_option").empty();
}

/**
 * Méthode qui supprime les options de paiement lors de la mise
 * A jour des options de paiements
 */
function tunnelPaiementCpqClearOptionSug(){
	$("#cpq_sug_list_option").empty();
}

/**
 * Fonction qui valide l'option de paiement CRBT
 */
function tunnelPaiementValideCrbt(){
	$.post("/VAD/ContreRemboursement",
		function(data){
			traitementAjaxResult(data);
		}
	);
}

/* Methode d'appel AJAX pour association d'adresse au panier */
function setAdressePanier(panierId, adresseId,montantLivClassique,montantLivComplement,lieuLiv,modeLiv,tauxLiv){
	Ajax_Call("/VAD/LivraisonAdresse?commandeId="+panierId+"&adresseId="+adresseId+"&montantLivClassique="+montantLivClassique+"&montantLivComplement="+montantLivComplement+"&lieuLiv="+lieuLiv+"&modeLiv="+modeLiv+"&tauxLiv="+tauxLiv,null);
}

/* Methode d'appel AJAX pour association d'adresse au panier (spécifique au relais colis) */
function setAdressPanier4Rel() {
	var commandeId = $("#panierId").val();
	var relaiId = $("#idPointRelaisSelected").val();
	var montantLivComplement =  $("input[name=livraison1]:checked").val();
	var adresseId = $("#adresseId").val();
	var montantLivClassique = $("input[name=livraison]:checked").val();
	var modeLiv = $("input[name=modLiv]").val();
	var lieuLiv = $("#lieuLiv").val();
	var codeId = $("#codeId").val();
	var libNom = $("#libNomPtRelais").html();
	var libVoieRel = $("#libVoieRel").html();
	var cpRel = $("#cpRel").html();
	var localiteRel = $("#localiteRel").html();
	if(libVoieRel == ""){
		alert("Veuillez sélectionner un point relais");
	}else{
		Ajax_Call("/VAD/LivraisonAdresse?modeRel=1&commandeId="+commandeId+"&montantLivClassique="+montantLivClassique+"&montantLivComplement="+montantLivComplement+"&lieuLiv="+lieuLiv+"&modeLiv="+modeLiv+"&codeId="+codeId+"&relaiId="+relaiId+"&libNom="+libNom+"&libVoieRel="+libVoieRel+"&cpRel="+cpRel+"&localiteRel="+localiteRel,null);
	}
}

/* Methode d'appel AJAX pour association d'adresse au panier (spÃ©cifique au relais colis) */
/*VSN duplication de la fonction setAdressPanier4Rel et passage d'un paramtre pour l'AB Testing*/
function setAdressPanier4RelABTesting(paramAB) {
	var commandeId = $("#panierId").val();
	var relaiId = $("#idPointRelaisSelected").val();
	var montantLivComplement =  $("input[name=livraison1]:checked").val();
	var adresseId = $("#adresseId").val();
	var montantLivClassique = $("input[name=livraison]:checked").val();
	var modeLiv = $("input[name=modLiv]").val();
	var lieuLiv = $("#lieuLiv").val();
	var codeId = $("#codeId").val();
	var libNom = $("#libNomPtRelais").html();
	var libVoieRel = $("#libVoieRel").html();
	var cpRel = $("#cpRel").html();
	var localiteRel = $("#localiteRel").html();
	if(libVoieRel == ""){
		alert("Veuillez sélectionner un point relais");
	}else{
		Ajax_Call("/VAD/LivraisonAdresse?modeRel=1&commandeId="+commandeId+"&montantLivClassique="+montantLivClassique+"&montantLivComplement="+montantLivComplement+"&lieuLiv="+lieuLiv+"&modeLiv="+modeLiv+"&codeId="+codeId+"&relaiId="+relaiId+"&libNom="+libNom+"&libVoieRel="+libVoieRel+"&cpRel="+cpRel+"&localiteRel="+localiteRel+"&AB="+paramAB,null);
	}
}

//Fonction de validation d'authentification pour la demande de catalogue
function DdeCatAuthenticate(nomFormLogin){
	if(tunnelVerifAllChamp("."+nomFormLogin)){
		varLogin = $("#"+nomFormLogin+"_email_client").val();
		varPass = $("#"+nomFormLogin+"_pass_client").val();
		passwordCrypte= varPass;//hex_sha1(varPass);
		$("#auth_loader").show();
		$.get("/VAD/Identification",
			{login : varLogin , pass : passwordCrypte, source : 'DdeCat'},
			function(data){
				$("#auth_loader").hide();
				traitementAjaxResult(data);
			}
		);	
	}
}

//Fonction de validation d'authentification pour l'inscription à la newsletter
function NLAuthenticate(nomFormLogin){
	if(tunnelVerifAllChamp("."+nomFormLogin)){
		varLogin = $("#"+nomFormLogin+"_email_client").val();
		varPass = $("#"+nomFormLogin+"_pass_client").val();
		passwordCrypte= varPass;//hex_sha1(varPass);
		$("#auth_loader").show();
		$.get("/VAD/Identification",
			{login : varLogin , pass : passwordCrypte, source : 'NL'},
			function(data){
				$("#auth_loader").hide();
				traitementAjaxResult(data);
			}
		);	
	}
}

/**
 * Méthode de récupération du numéro de client pour la demande de catalogue
 *
 */
function ddeCatValideNumClient(){
	if(tunnelVerifAllChamp(".auth_clientcat_num")){
		var varNom = $(".auth_clientcat_num input[name=nom_client]").val();
		var varCode= $(".auth_clientcat_num input[name=num_client]").val();
		$.post("/VAD/VerificationCompte",
			{nom:varNom,code:varCode,source:"ddecat"},
			function(data){
				traitementAjaxResult(data);					
			}
		);
	}
}

/**
 * Script de validation de la création de l'espace client pour la demande de catalogue
 */
function ddecatCreationEspace1(){
	$("#btn_valid").hide();
	var varCiv = $(".auth_creation_espace1 input[name=civilite]:checked").val();
	/* DI 990 Impossible de créer un compte web pour une cliente existante */
	var varDejaconnu = $(".auth_creation_espace1 input[name=dejaconnu]").val();
	var varType = $(".auth_creation_espace1 input[name=type]").val();
	/* FIN DI 990 Impossible de créer un compte web pour une cliente existante */
	// Vérification de la civilité
	if(varCiv == undefined) {
		$("#civilite_error").show();
	} else {
		$("#civilite_error").hide();
	}
	// Vérification de la date de naissance
	if($("#jj_naissance").val()=="" && $("#mm_naissance").val()=="" && $("#aaaa_naissance").val()=="" || $("#jj_naissance").val()!="" && $("#mm_naissance").val()!="" && $("#aaaa_naissance").val()!=""){
		$("#naissance_error").hide();
		flagDateNaiss = true;
	} else {
		$("#naissance_error").show();
		flagDateNaiss = false;
	}
	if(tunnelVerifAllChamp(".auth_creation_espace1") && varCiv!=undefined && flagDateNaiss){
		varNom = $(".auth_creation_espace1 input[name=nom_client]").val();
		varPrenom = $(".auth_creation_espace1 input[name=prenom_client]").val();
		varJour = $(".auth_creation_espace1 select[name=jj_naissance]").val(); 
		varMois = $(".auth_creation_espace1 select[name=mm_naissance]").val(); 
		varAnnee = $(".auth_creation_espace1 select[name=aaaa_naissance]").val(); 
		varMail = $(".auth_creation_espace1 input[name=email_client]").val(); 
		varPassword = $(".auth_creation_espace1 input[name=pass_client]").val(); 
		varConfPass = $(".auth_creation_espace1 input[name=confirm_pass]").val(); 
		//varCaptcha = $(".auth_creation_espace1 input[name=captcha]").val(); 
		varNumClient = $(".auth_clientcat_num input[name=num_client]").val(); 
		varAdresse = $(".auth_creation_espace1 input[name=adresse1]").val();
		/* CBL : DI 286 : Ajout d'un complement d'adresse */
		varCplAdresse = $(".auth_creation_espace1 input[name=adresse2]").val();
		/* CBL : DI 286 : Ajout d'un complement d'adresse */
		varCp = $(".auth_creation_espace1 input[name=cp]").val();
		varVille = $(".auth_creation_espace1 select[name=ville]").val();
		$("#auth_creation_espace1_loader").show();
		/* DI 990 Impossible de créer un compte web pour une cliente existante */
		if (varType=="prospect" && varDejaconnu=="oui") {
			$.post("/VAD/ModificationCompte",
					{
					clientId : $(".auth_creation_espace1 input[name=client_id]").val(),
					emCodeClient : $(".auth_creation_espace1 input[name=emCodeClient]").val(),
					dejaConnu : varDejaconnu,
					nom : varNom , 
					prenom : varPrenom,
					email : varMail , 
					civilite : varCiv, 
					jour : varJour,
					mois : varMois,
					annee : varAnnee,
					pass : varPassword ,
					passC : hex_sha1(varPassword),
					type: varType,
					src: 'ddecat',
					num_client : varNumClient,
					adresse1 : varAdresse,
					adresse2 : varCplAdresse,
					cp : varCp,
					ville : varVille
					},
					function(data){
						$("#auth_creation_espace1_loader").hide();
						traitementAjaxResult(data);
					}
				);
		} else {
			$.post("/VAD/CreationCompte",
				{
				nom : varNom , 
				prenom : varPrenom,
				email : varMail , 
				civilite : varCiv, 
				jour : varJour,
				mois : varMois,
				annee : varAnnee,
				pass : varPassword ,
				passC : hex_sha1(varPassword),
				//captcha: varCaptcha,
				type: 'i',
				src: 'ddecat',
				num_client : varNumClient,
				adresse1 : varAdresse,
				/* CBL : DI 286 : Ajout d'un complement d'adresse */
				adresse2 : varCplAdresse,
				/* CBL : DI 286 : Ajout d'un complement d'adresse */
				cp : varCp,
				ville : varVille
				},
				function(data){
					$("#auth_creation_espace1_loader").hide();
					traitementAjaxResult(data);
					$("#btn_valid").show();
				}
			);
		}
		/* FIN DI 990 Impossible de créer un compte web pour une cliente existante */
	} else {
		$("#btn_valid").show();
	}
}

/**
 * Méthode de validation de la newlsetter pour la demande de catalogue
 */
function ddecatValidNewsLetter(){
	var cookie = getJsonCookie("QuelleInfoClient");
	var clientId = cookie.emId;
	var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
	var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
	var centres = '';
	$("#error_offres_partenaires").hide();
	$("#error_offres_quelle").hide();
	if (offres_partenaires == undefined) {
		$("#error_offres_partenaires").show();
	} 
	if (offres_quelle == undefined){
		$("#error_offres_quelle").show();
	} 
	if(offres_partenaires != undefined && offres_quelle != undefined) {
		$(".check").each(function(){
			// Récupération des centres d'intéret
			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
				centres+='&centre='+$(this).val();
			}			
		});
		/* CBL : report de la DI 982 sur toutes les pages de création de compte */
		// Soumission du formulaire des centres d'intéret
		/*$.get("/VAD/CentreNewsletter?src=ddecat&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,
				function(data){
			traitementAjaxResult(data);
		});*/
	}
	// Soumission du formulaire des centres d'intéret
	$.get("/VAD/CentreNewsletter?src=ddecat&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,
			function(data){
		traitementAjaxResult(data);
	});
	/* Fin CBL : report de la DI 982 sur toutes les pages de création de compte */
}

/**
 * Méthode de validation de la newlsetter pour l'inscription à la NL
 */
function nlValidNewsLetter(){
	var cookie = getJsonCookie("QuelleInfoClient");
	var clientId = cookie.emId;
	var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
	var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
	var centres = '';
	$("#error_offres_partenaires").hide();
	$("#error_offres_quelle").hide();
	if (offres_partenaires == undefined) {
		$("#error_offres_partenaires").show();
	} 
	if (offres_quelle == undefined){
		$("#error_offres_quelle").show();
	} 
	if(offres_partenaires != undefined && offres_quelle != undefined) {
		$(".check").each(function(){
			// Récupération des centres d'intéret
			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
				centres+='&centre='+$(this).val();
			}			
		});
		// Soumission du formulaire des centres d'intéret
		$.get("/VAD/CentreNewsletter?src=NL&id_client="+clientId+"&offres_partenaires="+offres_partenaires+"&offres_quelle="+offres_quelle+centres,
				function(data){
			traitementAjaxResult(data);
		});
	}
}

/*********************************************************/
/***** ANCIEN CONTENU livraison                       ****/
/*********************************************************/
//JavaScript Document for Quelle
//Version : 0.1
//Authors : Francois OLIVIER

var ID_DIV_SELECTED = "divSelectedRelaisId";
var ID_DIV_2_KEEP = "selectWrapperId"; 

var SPAN_ADR_CUR = "spanAdrRelCourant";
var SPAN_HOR_CUR = "spanHorRelCourant"; 
var SPAN_ADR_SEA = "spanAdrRelSearch";
var SPAN_HOR_SEA = "spanHorRelSearch"; 

var SPAN_LIB_VOIE_CUR = "libVoieRel";
var SPAN_CP_CUR = "cpRel";
var SPAN_LOC_CUR = "localiteRel";
var SPAN_LIB_VOIE_SEA = "libVoieRelSea";
var SPAN_CP_SEA = "cpRelSea";
var SPAN_LOC_SEA = "localiteRelSea";

/**
*  Fonction : Appel ajax de récupération de la liste des points relais en fonction d'un CP 
*/

function selectListPointRelais() {
	var cp = $("#cp_ptRel").val();
	if(cp!=null && cp!=(''))
		Ajax_Call("/VAD/ListPointsRelais?cp="+cp,null);
}

/* Fonction : Appel ajax de récupération de la liste des points relais en fonction d'un CP */
function selectListPointRelaisBis(cp, selectWrapperId, divListeRelaisId, livraison) {
	if(cp!=null)
		Ajax_Call("/VAD/ListPointsRelais?cp="+cp+"&selectWrapperId="+selectWrapperId+"&divListeRelaisId="+divListeRelaisId+"&livraison=" + livraison,null);
}

/**
* Fonction qui supprime les options des relais colis
*/
function clearListPointRelais(){
	$("#select_relais").empty();
}

/**
* Fonction qui ajoute une option dans le select du relais colis
* @param value Valeur de l'option
* @param content Libellé de l'option
* @param onClick Javascript à exécuter sur click
*/
function addOptionListPointRelais(value,content, enabled){
	var textDisabled ="";
	if(enabled == false){textDisabled=" style=\"color:red;\"";}
	$("#select_relais").append("<option value=\""+value+"\""+textDisabled+">"+content+"</option>");
}

/**
* Fonction de rechargement de l'adresse de livraison
* 
*/
function reloadLivraison(){
	$('#id_contenu_livraison').load('/VAD/AjaxModeLivraison',
		function(){
			$(".ajaxLoad").hide();
			$("input[name=livraison]:checked").click();
			$("input[name=livraison1]:checked").click();
	});
	$(".ajaxLoad").show();
}

/* Fonction : Appel ajax d'affichage des informations d'un point relais */
function infoPointRelais() {
	var idPoint = $("#idPointRelais").val();
	$("#idPointRelaisSelected").val(idPoint);
	if(idPoint!=null)
		Ajax_Call("/VAD/InfoPointRelais?ptRelId="+idPoint,null);
}

/* Fonction : Appel ajax d'affichage des informations d'un point relais */
function infoPointRelaisBis(select) {
	var idPoint = select.value;
	$("#idPointRelaisSelected").val(idPoint);
	if(idPoint!= null && idPoint != ""){
		Ajax_Call("/VAD/InfoPointRelais?ptRelId="+idPoint+"&idDivSelected="+ID_DIV_SELECTED+"&idDiv2Keep="+ID_DIV_2_KEEP+"&livraison="+$('#modLiv').val() ,null);
	}
}

/* Fonction : Appel ajax d'affichage des informations d'un point relais */
function savePointRelaisClient() {
	var idPoint = document.getElementById("idPointRelais");
	var clientId = document.getElementById("clientId");
	if(idPoint!=null && clientId!=null)
		Ajax_Call("/VAD/SavePointRelaisClient?ptRelId="+idPoint.value+"&clientId="+clientId.value,null);
}

/**
*  Fonction : changement du point relais courant
*/
function switchRel() {
	if(document.getElementById('isDispo').value == '1' ) {
		$("#libNomPtRelais").html($("#libNomSea").html());
		$("#libVoieRel").html($("#libVoieRelSea").html());
		$("#cpRel").html($("#cpRelSea").html());
		$("#localiteRel").html($("#localiteRelSea").html());
		$("#spanHorRelCourant").html($("#spanHorRelSearch").html());
	} else {
		alert('Le point relais que vous avez choisi est indisponible, veuillez en choisir en un autre !')
	}
}

/* Fonction : Appel ajax d'affichage de la ville en fonction du code postal */
function verfiLocalite(pathImg,page) {
	var contenu_KO = "<img src=\""+pathImg+"icon_ko.gif"+"\" class=\"droite\" />";
	var contenu_OK = "<img src=\""+pathImg+"icon_ok.gif"+"\" class=\"droite\" />";

	var cp = $("#cp").val();
	if(cp!=null && cp!="" && page!=null && page=='panierM'){
		if(parseInt(cp) <=97000 || parseInt(cp) == 98000){
			addImg2Field('cp', contenu_OK);
			if(cp.length=5){
				Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				afficheBoutonValidation();
				// CBL : Ajout de la verification de la localite a chaque fois 
				// pour remettre a blanc la liste deroulante des villes
			} else {
				addImg2Field('cp', contenu_KO);
				$(".divBouton").hide();
				// CBL 22-02-2010 Cas particulier des CP 00000
				//Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				if (cp != "0" && cp != "00" && cp != "000" && cp != "0000") {
					Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				}
			}
		}else{
			// CBL : Ajout de la verification de la localite a chaque fois 
			// pour remettre a blanc la liste deroulante des villes
			addImg2Field('cp', contenu_KO);
			// CBL 22-02-2010 Cas particulier des CP 00000
			//Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
			if (cp != "0" && cp != "00" && cp != "000" && cp != "0000") {
			Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
			}
		}
	} else if(cp!=null && cp!="" && page!=null && page=='Lightbox'){
		Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
	} else if(cp!=null && cp!=""){
		if(page!=null && page=='panierDom'){
			if(parseInt(cp)>97000 && parseInt(cp) < 98000){
				addImg2Field('cp', contenu_OK);
				if(cp.length>=5){
					Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
					afficheBoutonValidation();
				} else {
					// CBL : Ajout de la verification de la localite a chaque fois 
					// pour remettre a blanc la liste deroulante des villes
					addImg2Field('cp', contenu_KO);
					// CBL 22-02-2010 Cas particulier des CP 00000
					//Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
					if (cp != "0" && cp != "00" && cp != "000" && cp != "0000") {
						Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
					}
				}
			}else{
				// CBL : Ajout de la verification de la localite a chaque fois 
				// pour remettre a blanc la liste deroulante des villes
				addImg2Field('cp', contenu_KO);
				// CBL 22-02-2010 Cas particulier des CP 00000
				//Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				if (cp != "0" && cp != "00" && cp != "000" && cp != "0000") {
					Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				}
			}
		}else{
			if(cp.length>=5){
				Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				afficheBoutonValidation();
			} else {
				// CBL : Ajout de la verification de la localite a chaque fois 
				// pour remettre a blanc la liste deroulante des villes
				addImg2Field('cp', contenu_KO);
				// CBL 22-02-2010 Cas particulier des CP 00000
				//Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				if (cp != "0" && cp != "00" && cp != "000" && cp != "0000") {
					Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
				}
			}
		}
	}else{
		// CBL : Ajout de la verification de la localite a chaque fois 
		// pour remettre a blanc la liste déroulante des villes
		addImg2Field('cp', contenu_KO);
		Ajax_Call("/VAD/VerifLocalite?codePostal="+cp,null);
	}
}

/**
* Suppression des message d'erreur et affichage du bouton de validation
*/
function afficheBoutonValidation(){
	$(".divMessage").empty();
	$(".divBouton").show();
}

function saveAdresseLiv(source){
	var modif = $("#modif_a").val(); 
	var montantLivClassique = $("input[name=livraison]:checked").val();
	var montantLivComplement = $("input[name=livraison1]:checked").val();
	var modeLiv = $("input[name=modLiv]").val();
	var lieuLiv = $("input[name=lieuLiv]").val();
	var tauxLiv = $("input[name=tauxLiv]").val();
	var principale = ($("#adresseId").val() == $("#id_principale").val()) ? "1" : "0";
	$("#principale").val(principale);
	if(montantLivClassique == undefined){
		montantLivClassique=$("input[name=livraison]").val();
	}
	if( source!="tunnel" && principale!="0"  && (lieuLiv==undefined || lieuLiv=="" || lieuLiv=="undefined") && (montantLivClassique == undefined || montantLivClassique=="" || montantLivComplement == undefined || montantLivComplement=="")){
		error='Veuillez selectionner votre mode de livraison';
			fillDivWithMsg(NOM_DIV_MSG, error);
			alert(error);
			//switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		if(modif!=null && modif=="1"){
			if(tunnelVerifAllChamp("#choix1")){
				addAdresse(source);
			}
		}else{
			var adresseId = $("#adresseId").val();
			var panierId = 	$("#panierId").val();
			var param="adresseId="+adresseId;
			var montantLivClassique = $("input[name=livraison]:checked").val();
			var montantLivComplement = $("input[name=livraison1]:checked").val();
			var modeLiv = $("input[name=modLiv]").val();
			var lieuLiv = $("input[name=lieuLiv]").val();
			var tauxLiv = $("input[name=tauxLiv]").val();
			if(montantLivClassique == undefined){
				montantLivClassique=$("input[name=livraison]").val();
			}
			if(montantLivComplement == undefined) montantLivComplement=0;
			param+="&commandeId="+panierId;
			param+="&modeLiv="+modeLiv;
			param+="&lieuLiv="+lieuLiv;
			param+="&montantLivClassique="+montantLivClassique;
			param+="&montantLivComplement="+montantLivComplement;
			param+="&tauxLiv="+tauxLiv;
			if(tunnelVerifAllChamp("#choix1")){
				Ajax_Call("/VAD/LivraisonAdresse?"+param,null);
			}
		}
	}
}


/**
 * VSN duplication de la fonction saveAdresseLiv pour les besoins de l'aB Testing 
 * @param source page source
 * @param paramAB parametre pour l'AB testing
 * @return
 */

function saveAdresseLivABTesting(source, paramAB){
	var modif = $("#modif_a").val(); 
	var montantLivClassique = $("input[name=livraison]:checked").val();
	var montantLivComplement = $("input[name=livraison1]:checked").val();
	var modeLiv = $("input[name=modLiv]").val();
	var lieuLiv = $("input[name=lieuLiv]").val();
	var tauxLiv = $("input[name=tauxLiv]").val();
	var principale = ($("#adresseId").val() == $("#id_principale").val()) ? "1" : "0";
	$("#principale").val(principale);
	if(montantLivClassique == undefined){
		montantLivClassique=$("input[name=livraison]").val();
	}
	if( source!="tunnel" && principale!="0"  && (lieuLiv==undefined || lieuLiv=="" || lieuLiv=="undefined") && (montantLivClassique == undefined || montantLivClassique=="" || montantLivComplement == undefined || montantLivComplement=="")){
		error='Veuillez selectionner votre mode de livraison';
			fillDivWithMsg(NOM_DIV_MSG, error);
			alert(error);
			//switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		if(modif!=null && modif=="1"){
			if(tunnelVerifAllChamp("#choix1")){
				addAdresse(source);
			}
		}else{
			var adresseId = $("#adresseId").val();
			var panierId = 	$("#panierId").val();
			var param="adresseId="+adresseId;
			var montantLivClassique = $("input[name=livraison]:checked").val();
			var montantLivComplement = $("input[name=livraison1]:checked").val();
			var modeLiv = $("input[name=modLiv]").val();
			var lieuLiv = $("input[name=lieuLiv]").val();
			var tauxLiv = $("input[name=tauxLiv]").val();
			if(montantLivClassique == undefined){
				montantLivClassique=$("input[name=livraison]").val();
			}
			if(montantLivComplement == undefined) montantLivComplement=0;
			param+="&commandeId="+panierId;
			param+="&modeLiv="+modeLiv;
			param+="&lieuLiv="+lieuLiv;
			param+="&montantLivClassique="+montantLivClassique;
			param+="&montantLivComplement="+montantLivComplement;
			param+="&tauxLiv="+tauxLiv;
			param+="&AB="+paramAB;
			if(tunnelVerifAllChamp("#choix1")){
				Ajax_Call("/VAD/LivraisonAdresse?"+param,null);
			}
		}
	}
}

function changeAdresseCadeau(etat){
	var adresse = document.getElementById("adresseId");
	for(i=0;i<adresse.options.length;i++){
		if(adresse.options[i].text.indexOf("Adresse Principale")>=0){
			if(etat=="visible"){
				adresse.options[i].disabled=false;
				adresse.options.selectedIndex=i;
				Ajax_Call("/VAD/InfoAdresse?adresseId="+adresse.options[i].value,f_displayBlocAdresse);
			}else{
				adresse.options[i].disabled=true;
				adresse.options.selectedIndex=i-1;
				Ajax_Call("/VAD/InfoAdresse?adresseId="+adresse.options[i-1].value,f_displayBlocAdresse);
			}
		}
	}
}

/* Fonction : valide les infos du relais */
function validRel() {
	Ajax_Call("/VAD/LivraisonAdresse",null);
}

/*********************************************************/
/***** ANCIEN CONTENU controls                        ****/
/*********************************************************/
//JavaScript Document for Quelle
//Version : 0.1
//Authors : Francois OLIVIER

function toLowerCase(input){
	$(input).val($(input).val().toLowerCase());
}

function toUpperCase(input){
	$(input).val($(input).val().toUpperCase());
}

function verif_login(){
	var idlogin = document.getElementById('login');
	var idpass = document.getElementById('pass_login');
	if (idpass.value == '') idpass = document.getElementById('pass');
	var idlogin_c = document.getElementById('login_c');
	var pass_c = document.getElementById('pass_c');
	if(idpass.value=='Votre mot de passe')idpass.value=''; 
	if(idlogin.value=='Votre adresse e-mail')idlogin.value='';
	if(verfi_vide(idlogin.value)){
		if(idlogin_c!=null && idlogin_c!='') idlogin.value=idlogin_c.value;
		if(pass_c!=null && pass_c!='') idpass.value=pass_c.value;
	}
	if ((verfi_vide(idlogin) || verfi_vide(idpass.value))){
		lightbox('lb3');
		return false;
	} else {	 
		LoginProceed();
		return false;
	}
}
/* VSN duplication de la fonction verif login : passage d'un parametre en entrée */
function verif_login_with_param(pageSource){
	var idlogin = document.getElementById('login');
	var idpass = document.getElementById('pass_login');
	if (idpass.value == '') idpass = document.getElementById('pass');
	var idlogin_c = document.getElementById('login_c');
	var pass_c = document.getElementById('pass_c');
	if(idpass.value=='Votre mot de passe')idpass.value=''; 
	if(idlogin.value=='Votre adresse e-mail')idlogin.value='';
	if(verfi_vide(idlogin.value)){
		if(idlogin_c!=null && idlogin_c!='') idlogin.value=idlogin_c.value;
		if(pass_c!=null && pass_c!='') idpass.value=pass_c.value;
	}
	if ((verfi_vide(idlogin) || verfi_vide(idpass.value))){
		if (pageSource == 'pageLoterie') {
			lightbox('lb3_loterie');
		} else {
			lightbox('lb3');
		}
		return false;
	} else {	 
		
		LoginProceedWithParam(pageSource);
		return false;
	}
}


/* FIN VSN */


function conrol_password(email){
	if(verif_email(email)){
		password(email);
	}else{
		alert("Email invalide");
	}
}
function verif_email(email){
	indexPoint = email.lastIndexOf(".");
	indexArro = email.indexOf("@");
	if(indexPoint>=0 && indexArro>=0 && indexArro < indexPoint){
		return true;	
	}else{
		return false;
	}
}

function verif_numerique(variable){
	var exp = new RegExp("^[0-9]+$","g");
	return exp.test(variable);
}

function verfi_vide(variable){
	if(variable==null || variable=='') return true;
	else return false;
}

function verifDate(date){
	var date_s = date.value;
	var exp = new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$","g");
	if(!exp.test(date_s)){
		alert("date invalide");
		return false;
	}
	return true;
}

function verifMontant(montant){
	var montant_s = montant.value;
	var exp = new RegExp("^[0-9]{1,5},[0-9]{2}$","g");
	var exp2 = new RegExp("^[0-9]{1,5}$","g");
	if(!exp.test(montant_s) && !exp2.test(montant_s)){
		alert("montant invalide");
		return false;
	}
	return true;
}

function addOption(selectId,value){
	var selectElm = document.getElementById(selectId);
	var optAdd = document.createElement('option');
	optAdd.text = value;
	optAdd.value = value;
	try {
	 	selectElm.add(optAdd,null); 
	} catch(ex) {
	 	selectElm.add(optAdd,1);
	}
}

function setModifAdresse(){
	if(document.getElementById("modif_a")!=null)
		document.getElementById("modif_a").value="1";
}

function showToolTip(sText, e) {
	 var oSpan = document.getElementById("toolTip_a" );
	 oSpan.innerHTML = sText;
	 oSpan.style.left = (e.clientX) + "px";
	 oSpan.style.top = (e.clientY) + "px";
	 oSpan.style.display = "inline";
};

function hideToolTip(e) {
	 var oSpan = document.getElementById("toolTip_a" );
	 oSpan.style.display = "none";
};

/**
* Méthode de vérification des champs en fonction de leur class
* 
*/
function tunnelVerifAllChamp(idDiv){
	var result = true;
	$(idDiv+" .msgErr").remove();
	// Vérification de la validité d'un champ
	$(idDiv+" .required").each(function(){
		if($(this).val() == ""){
			result = false;
			$(this).after("<a class='msgErr' style='color:red;'><br/> Ce champ est obligatoire. </a>");
		}
	});
	// Vérification que le champ est bien au format numéric
	$(idDiv+" .numeric").each(function(){
		if($(this).val() != "" && isNaN(this.value)){
			result = false;
			$(this).after("<a class='msgErr'><br/> Ce champ n'est pas un numérique. </a>");	
		}
	});
	// Vérification du format date
	$(idDiv+" .date").each(function(){
		reg =  new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{2}$","g");
		if($(this).val() != "" && reg.test(this.value)==0){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le format de la date soit être au format jj/mm/aa </a>");	
		}
	});
	// Vérification du format d'un montant
	$(idDiv+" .montant").each(function(){
		var exp = new RegExp("^[0-9]{1,5},[0-9]{2}$","g");
		var exp2 = new RegExp("^[0-9]{1,5}$","g");
		if($(this).val() != "" && !exp.test($(this).val()) && !exp2.test($(this).val())){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le format du montant doit être xxx,xx</a>");	
		}
	});	
	// Vérification de la validité d'un mail
	$(idDiv+" .mail").each(function(){
		exp = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
		reg = new RegExp(exp);
		if($(this).val() != "" && reg.test(this.value)==0){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le format de l'adresse mail est invalide. </a>");	
		}
	});
	// Vérification de la validité du mot de passe
	$(idDiv+" .password").each(function(){
		var exp = new RegExp("^([a-zA-Z0-9])*$","g");
		if(exp.test($(this).val())){
			if($(this).val()!= "" && $(this).val().length < 6){
				result = false;
				$(this).after("<a class='msgErr'><br/> Le mot de passe doit faire plus de 6 caractères. </a>");	
			}
		} else {
			result = false;
			$(this).after("<a class='msgErr'><br/> Le mot de passe ne doit pas contenir de caractères spéciaux. </a>");	
		}	
	});
	// Vérification de la validité du numero de carte bleu num_cb
	$(idDiv+" .num_cb").each(function(){
		if($(this).val()!= "" && $(this).val().length != 16){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le numero de carte bleu doit faire 16 chiffres. </a>");	
		}
	});
	// Vérification de la validité de la carte privilege quelle
	$(idDiv+" .num_cpq").each(function(){
		if($(this).val()!= "" && $(this).val().length != 1){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le numero de Carte Privilège Quelle doit faire 15 chiffres au moins. </a>");	
		}
	});
	// Vérification de la validité du cryptogramme
	$(idDiv+" .crypto").each(function(){
		if($(this).val()!= "" && $(this).val().length != 3){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le cryptogramme se compose de 3 chiffres. </a>");	
		}
	});
	// Vérification de la validité du numéro de telephone
	$(idDiv+" .telephone").each(function(){
		exp = "^0[1-99]([0-9]{2}){4}$";
		reg = new RegExp(exp);
		if($(this).val() != "" && reg.test(this.value)==0){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le téléphone saisi n'est pas correct. </a>");	
		}
	});
	$(idDiv+" .code_postal").each(function(){
		if($(this).val().length != 5  ){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le code postal n'est pas correct, celui-ci doit comporter 5 chiffres</a>");	
		}
	});
	// Vérification de la validité du code postal hors dom
	$(idDiv+" .code_postal_non_dom").each(function(){
		if($(this).val().length != 5 || (parseInt($(this).val())>97000 && parseInt($(this).val())!=98000 )){
			$(this).after("<a class='msgErr'><br/> Le code postal n'est pas correct, celui-ci doit comporter 5 chiffres et ne doit pas faire partie des Départements d'Outre Mer</a>");
			result = false;
		}
	});
	// Vérification de la validité du code potal dom
	$(idDiv+" .code_postal_dom").each(function(){
		if($(this).val().length != 5 || (parseInt($(this).val())<=97000 || parseInt($(this).val())>=98000 )  ){
			result = false;
			$(this).after("<a class='msgErr'><br/> Le code postal n'est pas correct, celui-ci doit comporter 5 chiffres et doit faire partie des Départements d'Outre Mer</a>");	
		}
	});
	/* Ajout d'un test sur la ville */
	$(idDiv+" .ville").each(function(){
		if($(this).val() == null || $(this).val() == 'null' || $(this).val() == ''){
			result = false;
			$(this).after("<a class='msgErr'><br/> Veuillez sélectionner une localité</a>");	
		}
	});
	// Vérification que le champ est bien une chaine standard
	$(idDiv+" .standardCh").each(function(){
		expAccent = "";
		for(i=192; i<=255; i++) {
			expAccent+= Chr(i);
		}
		expAccent+= '-';
		exp = "^([a-zA-Z "+ expAccent +"])*$";
		reg = new RegExp(exp);
		if( $(this).val() == "" || (reg.test($(this).val())==0) ){
			result = false;
			$(this).after("<a class='msgErr'><br/>Certain caractères ne sont pas valides</a>");	
		}
	});
	// Vérification de l'égalité de deux champs
	val="";
	newVal="";
	$(idDiv+" .same").each(function(){
		newVal = $(this).val();
		if(val!="" && val != newVal ){
			result = false;
			$(this).after("<a class='msgErr'><br/> Ce champ n'est pas identique au précédent. </a>");	
		}
		val = newVal;
	});
	return result;
}

function replaceAccent(champ){
	str = champ.value;
	str = str.replace(/à|á|â|ä|å|ã|Ä|Å|Á|Â|À|Ã/g,"a");
	str = str.replace(/é|è|ê|ë|É|Ê|Ë|È/g,"e");
	str = str.replace(/ù|ü|û|ú|Ü|Ú|Û|Ù/g,"u");
	str = str.replace(/ô|ö|ò|ó|õ|Ö|Ø|Ó|Ô|Ò|Õ/g,"o");
	str = str.replace(/î|ï|ì|í|Î|Ï|Ì/g,"i");
	str = str.replace(/ç|Ç/g,"c");
	str = str.replace(/ñ|Ñ/g,"n");
	champ.value = str;
}

/**
* Méthode de vérification des champs en fonction de leur class
* 
*/
function tunnelVerifChamp(champ){
	var valide = true
	$(".msgErr").remove();
	replaceAccent(champ);
	varClass = $(champ).attr("");
	// Vérification de la validité d'un champ
	if($(champ).hasClass("required")){
		if($(champ).val() == ""){
			//$(champ).after("<a class='msgErr'><br/> Ce champ est obligatoire. </a>");
			valide = false;
		}	
	}
	// On met les champ ayant pour classe toLowerCase en minuscule
	if($(champ).hasClass("toLowerCase")){
		toLowerCase(champ);
	}
	// On met les champs ayant pour classe toUpperCase en majuscule
	if($(champ).hasClass("toUpperCase")){
		toUpperCase(champ);
	}
	// Vérification que le champ est bien au format numéric
	if($(champ).hasClass("numeric")){
		if($(champ).val() != "" && isNaN($(champ).val())){
			valide = false;
		}
	}
	// Vérification du format date
	if($(champ).hasClass("date")){
		reg =  new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{2}$","g");
		if($(champ).val() != "" && reg.test($(champ).val())==0){
			valide = false;
		}
	}
	// Vérification du format d'un montant
	if($(champ).hasClass("montant")){
		var exp = new RegExp("^[0-9]{1,5},[0-9]{2}$","g");
		var exp2 = new RegExp("^[0-9]{1,5}$","g");
		if($(champ).val() != "" && !exp.test($(champ).val()) && !exp2.test($(champ).val())){
			valide = false;
		}
	}
	// Vérification de la validité d'un mail
	if($(champ).hasClass("mail")){
		exp = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
		reg = new RegExp(exp);
		toLowerCase(champ);
		if($(champ).val() != "" && reg.test(champ.value)==0){
			valide = false;
		} else {
			Ajax_Call("/VAD/NomDomain?champ="+champ.id+"&email="+$(champ).val());
		}
	}
	// Vérification de la validité du mot de passe
	if($(champ).hasClass("password")){
		var exp = new RegExp("^([a-zA-Z0-9])*$","g");
		if(exp.test($(champ).val())){
			if( hasTheGoodSize($(champ).val(), 6) ) { 
				valide = true;
			} else {	
				valide = false;
			}
		} else {	
			valide = false;
		}
	}
	// Vérification de la validité du numero de carte bleu
	if($(champ).hasClass("num_cb")){
		var regE = new RegExp("^[0-9]{16}$");		
		if (regE.test($(champ).val()) == 0) {
			valide = false;
		}
	}
	// Vérification de la validité du numero de carte privilège
	if($(champ).hasClass("num_cpq")){
		if($(champ).val() != "" && $(champ).val().length < 15){
			valide = false;
		}
	}
	// Vérification de la validité du cryptogramme
	if($(champ).hasClass("crypto")){
		var regE = new RegExp("^[0-9]{3}$");
		if (regE.test($(champ).val()) == 0) {
			valide = false;
		}
	}
	// Vérification de la validité du numéro de telephone
	if($(champ).hasClass("telephone")){
		exp = "^0[1-99]([0-9]{2}){4}$";
		reg = new RegExp(exp);
		if($(champ).val() != "" && reg.test(champ.value)==0){
			valide = false;
		}
	}
	// Vérification de la validité du code postal
	if($(champ).hasClass("code_postal")){
		if($(champ).val() != "" && $(champ).val().length != 5){
			valide = false;	
		}
	}
	if($(champ).hasClass("code_postal_non_dom")){
		if($(champ).val().length != 5 || parseInt($(champ).val())>97000 && parseInt($(champ).val())!=98000  ){
			valide = false;	
		}
	}
	// Vérification de la validité du code potal dom
	if($(champ).hasClass("code_postal_dom")){
		if($(champ).val().length != 5 || (parseInt($(champ).val())<=97000 || parseInt($(champ).val())>=98000 )  ){
			valide = false;	
		}
	}
	// CBL : Ajout Vérification de la validité de la ville
	if($(champ).hasClass("ville")){
		if($(champ).val() == "" || $(champ).val() == null || $(champ).val() == "null"){
			valide = false;	
		}
	}
	// Vérification que le champ est bien une chaine standard
	if($(champ).hasClass("standardCh")){
		expAccent = "";
		for(i=192; i<=255; i++) {
			expAccent+= Chr(i);
		}
		expAccent+= '-';
		exp = "^([a-zA-Z "+ expAccent +"])*$";
		reg = new RegExp(exp);
		if( $(champ).val() == "" || (reg.test($(champ).val())==0) )
			valide = false;	
	}
	// Suppression de l'image suiavnt le champs
	var next = $(champ).next();
	if(next.hasClass("droite")){
		next.remove();
	}
	// Affichage de l'image 
	if(valide){
		$(champ).after("<img src='/VAD/res/quelle/images/quelle/icon_ok.gif' class='droite' />");
	}else{
		$(champ).after("<img src='/VAD/res/quelle/images/quelle/icon_ko.gif' class='droite' />");
	}
	afficheBoutonValidation();
	return valide;
}

/* 
 * Report de la fonction ValidCart() dans le fichier fonction_tunnel_20100921.js 
 */

//BAZAARVOICE
function BVAuthenticate(nomFormLogin){
	if(tunnelVerifAllChamp("."+nomFormLogin)){
		varLogin = $("#"+nomFormLogin+"_email_client").val();
		varPass = $("#"+nomFormLogin+"_pass_client").val();
		passwordCrypte= varPass;//hex_sha1(varPass);
		var queryString = encodeURIComponent(window.location.search);		
		$("#auth_loader").show();
		$.get("/VAD/Identification",
			{login : varLogin , pass : passwordCrypte, source : 'BV', qs : queryString},
			function(data){
				$("#auth_loader").hide();
				traitementAjaxResult(data);
			}
		);	
	}
}

function bvValid(){
	var cookie = getJsonCookie("QuelleInfoClient");
	var clientId = cookie.emId;
	var offres_partenaires= $(".auth_creation_espace2 input[name=offres_partenaires]:checked").val();	
	var offres_quelle=$(".auth_creation_espace2 input[name=offres_quelle]:checked").val();
	var centres = '';
	$("#error_offres_partenaires").hide();
	$("#error_offres_quelle").hide();
	if (offres_partenaires == undefined) {
		$("#error_offres_partenaires").show();
	} 
	if (offres_quelle == undefined){
		$("#error_offres_quelle").show();
	} 
	if(offres_partenaires != undefined && offres_quelle != undefined) {
		$(".check").each(function(){
			// Récupération des centres d'intéret
			if($(this).attr("checked")!= undefined && $(this).attr("checked")!=""){
				centres+='&centre='+$(this).val();
			}			
		});
		var queryString = encodeURIComponent(window.location.search);
		var offers = offres_quelle+centres;
		// Soumission du formulaire des centres d'intéret
		$.get("/VAD/CentreNewsletter",
			{ 'src':'BV', 
			  'id_client':clientId, 
			  'offres_partenaires':offres_partenaires, 
			  'offres_quelle':offers,
			  'qs':queryString },
			function(data){
				  traitementAjaxResult(data);
			});
	}
}

function fPostAuthent() {
	var pName = window.location.pathname;
	if (pName.indexOf('BvAuthentification') >= 0) {
		window.location.href = "BvSubmitRedirect" + window.location.search;
	}
}

function deletePanierPers(panierId){
	$.get("/VAD/DeletePanierPersistant",
		{ 'panierId':encodeURI(panierId) },
		function(data){
			  traitementAjaxResult(data);
		});
}

function ajoutPanierPers(panierId){
	$.get("/VAD/RecupererPanierPersistant",
		{ 'panierId':encodeURI(panierId) },
		function(data){
			  traitementAjaxResult(data);
		});
}

function transfert(panierId){
	$.get("/VAD/RecupererPanierPersistant",
		{ 'panierId':encodeURI(panierId),
			'forced':'1'},
		function(data){
			  traitementAjaxResult(data);
		});
}

function deleteLignePanierPersistant(panierId){
	var listId=new Array();
	var i=0;
	var listCheckBox=$("#panierPersSupprForm").find("[name='ligneId']:checked");
	for(i=0;i<listCheckBox.length;i++){
		listId[i]=$(listCheckBox[i]).val();
	}
	$.get("/VAD/DeleteLignePanierPersistant",
		{ 'panierId':encodeURI(panierId),
			'ligneId':encodeURI(listId)},
		function(data){
			  traitementAjaxResult(data);
		});
}

function ajoutPanierPersWithLightBox(){
	if($('[name="panierPersId"]:checked').length>0){
		$.get("/VAD/RecupererPanierPersistant",
			{ 'panierId':encodeURI($('[name="panierPersId"]:checked').val()),
				'box':'1'},
			function(data){
				  traitementAjaxResult(data);
			});
	}else{
		$("#lb31Error").html("Veuillez saisir un panier sauvegardé à ajouter");
	}
}

function ajoutPanierPersWithLightBoxABTesting(paramAB){
	if($('[name="panierPersId"]:checked').length>0){
		$.get("/VAD/RecupererPanierPersistant",
			{ 'panierId':encodeURI($('[name="panierPersId"]:checked').val()),
				'box':'1', 'AB':paramAB},
			function(data){
				  traitementAjaxResult(data);
			});
	}else{
		$("#lb31Error").html("Veuillez saisir un panier sauvegardé à  ajouter");
	}
}

var savePanierProcessing=false;
function savePanier(){
	error="";
	if(encodeURI($("#nomPanier").val()).length>25){
		error+="Le nom de ce panier ne doit pas dépasser 25 caractères.";
	}
	
	if(encodeURI($("#commentairePanier").val()).length>250){
		if(error!="")
			error+="<br/>";
		error+="Le commentaire de ce panier ne doit pas dépasser 250 caractères.";
	}
	
	if(error==""){
	$.get("/VAD/EnregistrePanierPersistant",
			{ 'nomPanier':encodeURI($("#nomPanier").val()),
				'commentairePanier':encodeURI($("#commentairePanier").val()) },
			function(data){
				  traitementAjaxResult(data);
			});
	}else{
		$("#lb33Error").html(error);
		$("#lb33Error").show();
	}
}

function verif_login_panier_pers(){
	var idlogin = document.getElementById('login');
	var idpass = document.getElementById('pass_login');
	if (idpass.value == '') idpass = document.getElementById('pass');
	var idlogin_c = document.getElementById('login_c');
	var pass_c = document.getElementById('pass_c');

	if(idpass.value=='Votre mot de passe')idpass.value=''; 
	if(idlogin.value=='Votre adresse e-mail')idlogin.value='';
	if(verfi_vide(idlogin.value)){
		if(idlogin_c!=null && idlogin_c!='') idlogin.value=idlogin_c.value;
		if(pass_c!=null && pass_c!='') idpass.value=pass_c.value;
	}
	lightBoxName="lb33";
	if ((verfi_vide(idlogin) || verfi_vide(idpass.value))){
		lightbox('lb37',false);
		return false;
	} else {	 
		LoginProceed();
		return false;
	}
}

function addPanierPersLink(){
	$("#btn_add_panier_pers").html("<a href='#' class='notAjaxLoad' onclick='lightbox(\"lb31\")'><img src='/style1/images/quelle/btn_recuperer.gif' alt='Ajouter un panier mémorisé'/></a><img class=\"ajaxLoad\" style=\"display: none;\" src=\"/style1/images/quelle/ajax-loader.gif\"/>");
}

/* Fonctions appelees au chargement de la page */
$(document).ready(function() {
	$(".plus").toggle(function(){
		$(this).removeClass("plus").addClass("moins");
		$("#" + $(this).attr("req")).slideDown('slow');
	},function(){
		$(this).removeClass("moins").addClass("plus");
		$("#" + $(this).attr("req")).slideUp('slow');
	});
	if (getParamValue("page")=="accueil") {
		$("#contenu_espace1").hide();
		$("#contenu_espace2").hide();
		$("#contenu_espace3").hide();
		$("#contenu_espace4").hide();
		$("#contenu_espace5").hide();
		$("#contenu_espace0").show(); 
		if (getParamValue("item")!='') {
			$("#contenu_espace0").hide(); 
			$("#contenu_espace" + getParamValue("item")).show();
			$("#bouton_plus" + getParamValue("item")).removeClass("bouton_plus").addClass("bouton_moins");
		}
	}
	if (getParamValue("item")!='') {	
		$("#contenu_espace0").hide(); 
		$("#contenu_espace" + getParamValue("item")).show();
		$("#bouton_plus" + getParamValue("item")).removeClass("bouton_plus").addClass("bouton_moins");
	}
	$("#calqueSortieMenu").mouseover( function() {
		$('.menuimg').each(function() { $(this).attr('src',$(this).attr('srcOff')) });
		$('.niveau3').hide();
		$('.niveau2link').removeClass('linkon');
		$('.niveau2').hide();
		$(this).hide();
		//VSN : fonction 	setMenuOn(); définie dans le template remet en subrillance l'univers courant selectionné
		setMenuOn();
	
	});
});

function tunnelPaiementValideNumCpqSuggest(){
	tunnelPaiementErreur('cpq_erreur',"");
	var num_cpq = $("#num_cpq_sug").val();
	var date_naiss = $("#date_naiss").val();

	$.post("/VAD/AjaxCheckCPQ",
			{num_carte:num_cpq, date_naiss:date_naiss},
		function(data){
			traitementAjaxResult(data);
		}
	);
}	
/*********************************************
/** Ajout de code pour la page loterie MAEVA *
/** VSN le 10/09/2010						 *
/*********************************************/

function creationComptePageLoterie(){
	lightboxWithParam('lb4','pageLoterie');
}	

function finCreationComptePageLoterie(param){
	var divErreur = document.getElementById('ERREUR');
	if (divErreur != null) {
		divErreur.innerHTML = '';	
	}
	if (param == 'pageLoterie') {
		participer();
	}
}	
function finIdentificationPageLoterie(pageSource) {
	var divErreur = document.getElementById('ERREUR');
	if (divErreur != null) {
		divErreur.innerHTML = '';	
	}
	var id_loterie = document.getElementById('id_loterie').getAttribute('value');
	// on verifie que l'on se trouve bien sur une page loterie pour continuer sinon processus normal d'identification
	if (id_loterie != null && id_loterie != "") {

		if (pageSource == 'pageLoterie') {
			participer();
		}
	}
}	

function identificationPageLoterie(){
//	lightbox('lb3_loterie');
	lightboxWithParam('lb3_loterie','pageLoterie');
}	

function participer(){
	var divErreur = document.getElementById('ERREUR');
	if (divErreur != null) {
		divErreur.innerHTML = '';	
	}
	// appel ajax qui enregistre la participation a la loterie
	if (document.getElementById('id_loterie') != null) {
		var divConfirmation  = document.getElementById('CONFIRMATION');
		
		if (divConfirmation != null) {
			divConfirmation.innerHTML = '<div style="display:block;margin-left:73px;" class="moul_ajout_pan"><img src="/style1/images/commun/loading.gif"></div>';
		}
		
	var id_loterie 	= document.getElementById('id_loterie').getAttribute('value') ;	
	var url 	=  '/VAD/LoterieControleur?id_loterie='+ id_loterie+'&param=confirmation';
//	Ajax_Call(url);	
	
	$.get('/VAD/LoterieControleur',
			{'id_loterie': id_loterie, 'param': 'confirmation'},
			function(data){
				  //traitementAjaxResult(data);
				 var divConfirm = data;
				 $('#CONFIRMATION').html(data);
				// reloadEMSConfirmation(divConfirm);
			});

	var url 	=  '/VAD/LoterieControleur?id_loterie='+ id_loterie;
	Ajax_Call(url);
	}
}	

function confirmationParticipation(){
	var divErreur = document.getElementById('ERREUR');
	if (divErreur != null) {
		divErreur.innerHTML = '';	
	}
	cacheId('IDENTIFIE');
	cacheId('ANONYME');
	cacherReglement();
	afficheId('CONFIRMATION');
	
}	
function afficherPageIdentifie(){
	var divErreur = document.getElementById('ERREUR');
	if (divErreur != null) {
		divErreur.innerHTML = '';	
	}
	cacheId('ANONYME');
	cacherReglement();
	cacheId('CONFIRMATION');
	afficheId('IDENTIFIE');
	
}	
function finIdentificationHeader() {
	var divErreur = document.getElementById('ERREUR');
	if (divErreur != null) {
		divErreur.innerHTML = '';	
	}
	if (document.getElementById('id_loterie') != null) {
		
		var idlot 	= document.getElementById('id_loterie').getAttribute('value') ;
		if (idlot != null && idlot != '') {
			afficherPageIdentifie();
		}
	}
}

function echecParticipation(msgErreur){
	  document.getElementById('ERREUR').innerHTML = msgErreur;
}	


function afficheReglement(){
	
	var divReglement  = document.getElementById('REGLEMENT');
	if (divReglement != null) {
		divReglement.className = 'layerEnable';
	}
}	

function cacherReglement(){
	var divReglement  = document.getElementById('REGLEMENT');
	if (divReglement != null) {
		divReglement.className = 'layerDisable';
	}
}	

function reloadEMSConfirmation(content) {
	var divConfirmation  = document.getElementById('CONFIRMATION');
	
	if (divConfirmation != null) {
		divConfirmation.innerHTML = content;
	}
	
}



function afficheId(baliseId)
{
if (document.getElementById && document.getElementById(baliseId) != null)
  {
  document.getElementById(baliseId).style.visibility='visible';
  document.getElementById(baliseId).style.display='block';
  }
}

function cacheId(baliseId)
{
if (document.getElementById && document.getElementById(baliseId) != null)
  {
  document.getElementById(baliseId).style.visibility='hidden';
  document.getElementById(baliseId).style.display='none';
  }
}

/*********************************************
/** Ajout de code pour la page loterie MAEVA *
/** FIN VSN le 10/09/2010					 *
/*********************************************/

/*****************************/
/** Panier persistant lot 2 **/
/*****************************/

function recupererLigne(commandeId, ligneId){
	lightboxWithParams("", {"commandeId":commandeId, "ligneId":ligneId}, false);
}

function lightboxWithParams(id_lb, arg, cacheActive) {
	if(arg!=null && arg!="") {
		//Verification de l'existence d'une lightbox.
		if($("div.modale").length==0 && $("div.modalev1").length==0 && $("div.modalebig").length==0) {	
			//Insertion de la blackbox
			$("body").prepend('<div class="black_box" style="filter: alpha(opacity=40);"></div>');
			// Insertion du receptacle
			$("body").prepend('<div class="receptacle"></div>');
		}
		//Appel Ajax
		//append dans receptacle
		//Appel Ajax
		param = arg;
		param = $.extend(param, {"idBox": id_lb});
		var url = '/VAD/Lightbox';
		 $.ajax({
			   type: "GET",
			   cache:cacheActive,
			   url: url,
			   data: param,
			   success: function(msg){
			 		$(".receptacle").empty();
			 		$(".receptacle").append(msg);
			 		//Centre le contenu
					centre_lightbox($("#"+id_lb));
					//DEBUT VSN DI 999 [C] emplacement de la fenêtre de création de compte
   					if (id_lb == 'lb7') {
   						set_lightbox_onTop($("#"+id_lb));
   					}
   					if (id_lb == 'lb7bis') {
   						set_lightbox_onTop($("#"+id_lb));
   					}
   					//FIN VSN DI 999 [C] emplacement de la fenêtre de création de compte
					//Hack Dropdownliste IE6
					$(".black_box").bgiframe();
					//Apparition
					$('.black_box')
					.css({width: $(window).width(), height: $(document).height()})
					.fadeIn("slow",function(){$("#"+id_lb).fadeIn("slow");});
			   }
			 });
	} else {
		alert("email invalide");
	}
}

function showDetail(panier){
	$('#'+panier+'_detail').addClass('panierPerslayerEnable');
	$('#'+panier+'_detail').removeClass('panierPerslayerDisable');
	
}

function hideDetail(panier){
	$('#'+panier+'_detail').addClass('panierPerslayerDisable');
	$('#'+panier+'_detail').removeClass('panierPerslayerEnable');
}

function panierRelanceIdentification(){
	$("#erreur").html("");
	var email= $("#email").val();
	var password= $("#password").val();
	if(password.length==0){
		$("#erreur").html("Veuillez renseigner votre mot de passe");
	}else{		
		$("#auth_loader").show();
		$.get("/VAD/Identification",
				{login : email , pass : password, source : 'relance'},
				function(data){
					$("#auth_loader").hide();
					traitementAjaxResult(data);
				}
		);	
	}
}

/*********************************/
/** FIN Panier persistant lot 2 **/
/*********************************/

/*************/
/**  DI 691 **/
/*************/
function verif_login_cof(){
	var idlogin = document.getElementById('login');
	var idpass = document.getElementById('pass_login');
	if (idpass.value == '') idpass = document.getElementById('pass');
	var idlogin_c = document.getElementById('login_c');
	var pass_c = document.getElementById('pass_c');
	if(idpass.value=='Votre mot de passe')idpass.value=''; 
	if(idlogin.value=='Votre adresse e-mail')idlogin.value='';
	if(verfi_vide(idlogin.value)){
		if(idlogin_c!=null && idlogin_c!='') idlogin.value=idlogin_c.value;
		if(pass_c!=null && pass_c!='') idpass.value=pass_c.value;
	}
	if ((verfi_vide(idlogin) || verfi_vide(idpass.value))){
		lightbox('lbcofIdent');
		return false;
	} else {	 
		lightBoxName="lbcofIdent_2";
		LoginProceed();
		return false;
	}
}

function choix_catalogue_cof() {
	if (document.getElementById('radionon').checked==true) { 
		lightbox('lbcofIdent_7'); 
	} else if (document.getElementById('radiooui').checked==true) { 
		lightbox('lbcofIdent_5'); 
	}
}

function creationCompte_cof(){
	expAccent = "";
	expAccent+= '-';
	exp = "^([a-zA-Z0-9 "+ expAccent +"])*$";
	
	var exp = new RegExp(exp);
	var civiliteM=document.getElementById("mradio");
	var civiliteMm=document.getElementById("mmeradio");
	var civiliteMle=document.getElementById("mlleradio");
	var nom=document.getElementById("nom_client_c");
	var prenom=document.getElementById("prenom_client");
	var jour=document.getElementById("jj_naissance");
	var mois=document.getElementById("mm_naissance");
	var annee=document.getElementById("aaaa_naissance");
	var email=document.getElementById("email_client_c");
	var pass=document.getElementById("pass_client");
	var pass_c=document.getElementById("confirm_pass");
	//var captcha=document.getElementById("captcha");
	var type=document.getElementById("type");
	var num_client=document.getElementById("num_client_v");
	var adresse1=document.getElementById("adresse1");
	/* CBL : DI 286 : Ajout d'un complement d'adresse */
	var adresse2 = document.getElementById("adresse2");
	/* Fin CBL : DI 286 : Ajout d'un complement d'adresse */
	var cp=document.getElementById("cp");
	var ville = $("#ville").val();
	var error='';
	var error_email='';

	if(!civiliteM.checked && !civiliteMm.checked && !civiliteMle.checked) {error+='Veuillez selectionner une civilite<br />';}
	if(nom==null || nom.value=='') {error+='Veuillez saisir votre nom<br />';}
	// CBL : Ajout RDG : Le nom doit comporter au minimum 2 caractères
	else if (nom.value.length < 2) {error+='Le nom doit comporter au minimum 2 caractères<br />';}
	// Fin CBL
	else if( ! isStandardChaine(nom.value) ) {error+='Le nom saisi n\'est pas correct<br />';}
	if(prenom==null || prenom.value=='') {error+='Veuillez saisir votre prenom<br />';}
	else if( ! isStandardChaine(prenom.value) ) {error+='Le prenom saisi n\'est pas correct<br />';}
	if((jour==null || mois==null || annee==null) || ((jour.value!='' || mois.value!='' || annee.value!='') && (jour.value=='' || mois.value=='' || annee.value==''))) {
		error+='Veuillez selectionner votre date de naissance<br />';
	} else if(!isDate($("#mm_naissance").val() + '-' + $("#jj_naissance").val() + '-' + $("#aaaa_naissance").val())) { 
		error+='La date de naissance saisie n\'est pas correcte<br />';
	}
	
	if(adresse1==null || adresse1.value=='') {error +='Veuillez saisir votre adresse<br />';}
	if(adresse1.value.indexOf(';')>=0) {error +='Le champs adresse ne doit pas contenir de point-virgule<br />';}
	if(cp==null || cp.value=='' || cp.value.length!=5) {error += 'Le code postal est invalide<br />';}
	/* Ajout de la valeur null dans les tests */
	if(ville==null || ville=='' || ville=='null') {error += 'Veuillez sélectionner une ville<br />';}
	
	if(email==null || email.value=='') {error_email+='Veuillez saisir votre email<br />';}
	else if( ! isStandardEmail(email.value) ) {error_email+='L\'email saisi n\'est pas correct<br />';}
	if(pass==null || pass.value=='') {error+='Veuillez saisir un mot de passe.<br />'; }
	else{
		if(!exp.test(pass.value)){
			error+='Le mot de passe contient des caractères spéciaux.<br />';
		}else if (pass!=null && pass.value.length<6) {
			error+='Le mot de passe n\'est pas assez long.<br />';
		}
	}
	if(pass==null || pass_c==null || pass.value!='' && pass.value!=pass_c.value){
		error+='Le mot de passe et sa confirmation doivent être identique<br />';
	}
	//if(captcha==null || captcha.value=='') error+='Veuillez copier le texte de l\'image';
	if(error_email!=''){
		fillDivWithMsg(NOM_DIV_MSG, error_email);
		switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
	}else{
		if(error!=''){
			fillDivWithMsg(NOM_DIV_MSG, error);
			switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
		}else{
			if(verif_email(email.value)){
				var civilite = '1';
				if(civiliteMm.checked) civilite='2';
				if(civiliteMle.checked) civilite='3';
				fillDivWithMsg(NOM_DIV_MSG, '');
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
				/* CBL : DI 286 : Ajout d'un complément d'adresse */
				if (adresse2 != null) {
					Ajax_Call("/VAD/CreationCompte?email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&type="+type.value+"&num_client="+num_client.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&adresse2="+adresse2.value+"&cp="+cp.value+"&ville="+ville+"&cofidis=1",null);
				} else {
					Ajax_Call("/VAD/CreationCompte?email="+email.value+"&civilite="+civilite+"&jour="+jour.value+"&mois="+mois.value+"&annee="+annee.value+"&nom="+nom.value+"&prenom="+prenom.value+"&pass="+pass.value+"&type="+type.value+"&num_client="+num_client.value+"&passC="+hex_sha1(pass.value)+"&adresse1="+adresse1.value+"&cp="+cp.value+"&ville="+ville+"&cofidis=1",null);
				}
				/* Fin CBL : DI 286 : Ajout d'un complément d'adresse */
			}else{
				fillDivWithMsg(NOM_DIV_MSG, "Email incorrect");
				switchDiv(NOM_DIV_BOUTON, NOM_DIV_MSG);
			}
		}
	}
}
/****************/
/** FIN DI 691 **/
/****************/

/*********************************/
/** DI 679 Catalogue Interactif **/
/*********************************/

/*
 * Définition de la fonction d'appel à la servlet redirection
 * prrend une chaine correspondant au RFA en parametre
 * Redirige vers la page produit si RFA OK
 * affiche une lightbox d'erreur si RFA KO
 */

function afficheProduitCI(RFA) {
	Ajax_Call("/VAD/DetailProduitByRFA?rfa="+RFA);
}


/*************************************/
/**FIN  DI 679 Catalogue Interactif **/
/*************************************/

/*************/
/**   SEO   **/
/*************/

function rewriteSearch(searchTerm){
	var searchTermRewrite=encodeForRewrite(searchTerm);
	document.location="/articles/"+searchTermRewrite;
}

function encodeForRewrite(string){
	result = string.toLowerCase();
	result = result.replace(/[éèêë]/g,"e");
	result = result.replace(/[àâäã]/g,"a");
	result = result.replace(/[ïî]/g,"i");
	result = result.replace(/[ôöõ]/g,"o");
	result = result.replace(/[ùûü]/g,"u");
	result = result.replace(/[ÿ]/g,"y");
	result = result.replace(/[ç]/g,"c");
	result = result.replace(/[ñ]/g,"n");
	result = result.replace(/[ñ]/g,"n");
	result = result.replace(/[€]/g,"euros");
	result = result.replace(/ d'/g,"-");
	result = result.replace(/ l'/g,"-");
	result = result.replace(/ s'/g,"-");
	result = result.replace(/[^-\\.a-zA-Z0-9]/g,"-");
	while(result.indexOf("--")>0){
		result = result.replace(/--/g,"-");
	}
	return result;
}

/*************/
/** FIN SEO **/
/*************/


/******************/
/**   SEO lot 2  **/
/******************/
function loadMenu(){
	$.ajax({
		url: "/VAD/MenuAjax",
		cache: true,
		dataType: "text",
		success: function(data){
			var debut=data.indexOf("<ajax>")+6;
			var fin=data.indexOf("</ajax>");
			if(debut<fin){
				var script=data.substring(debut,fin);
				
				
				eval(script);
			}
		}
	});
}
/******************/
/** FIN SEO lot 2**/
/******************/
/** R13 **/


var singleton=false; 

function inscriptionNewsletter(id){
	if(!verif_email($("#"+id).val())){
		lightboxError("L'email est incorrect");
	}
	else{
		Ajax_Call("/VAD/CheckEmailNewsletter?email="+$("#"+id).val());
	}
}

function verif_login_newsletter(){
	if($('#pass_n').val()=='Votre mot de passe'){
		$('#pass_n').val(''); 
	}
	if($('#login_n').val()=='Votre adresse e-mail'){
		$('#login_n').val('');
	}
	if ((verfi_vide($('#login_n').val()) || verfi_vide($('#pass_n').val()))){
		lightboxWithParam('lb101', $('#login_n').val(), false);
		return false;
	} else {	 
		lightBoxName='lb101';
		Ajax_Call_Login_With_Param ($('#login_n').val(),$('#pass_n').val(),'NLProspect');
		return false;
	}
}

/** FIN R13 **/
/***********************/
/**Refonte page Liste **/
/***********************/

function affiche_lien_navigation(actif,clientId) {
	if (actif == 'true') {
		$("div#lienSauvegardeNavigation a").attr('href', '#');
		$("div#lienSauvegardeNavigation a").attr('onClick','Ajax_Call_Save_Navigation('+clientId+')');
		$("#lienSauvegardeNavigation ").show(); 
	} else {
		//on cache le lien
		//$("#lienSauvegardeNavigation").hide(); 
		//on ne cache plus le lien mais on ouvre une lightbox d'identification
		$("div#lienSauvegardeNavigation a").attr('href', '#');
		$("div#lienSauvegardeNavigation a").attr('onClick','verif_login_sauvegarde_navigation()');
	}	
}
	
function Ajax_Call_Save_Navigation(clientId) {
	var url = window.location.pathname+window.location.search;
	//alert('clientId : '+clientId+' / url courante : '+url+"value"+window.location.search);
	Ajax_Call("/VAD/SauvegardeNavigationController?client_id="+clientId+"&url="+url+"&action=save", 
			function(){
			kill_lightbox('lb3_sauvegarde_navigation');
			kill_lightbox('lb3_sauvegarde_navigation_error');
			lightbox('lb_confirmation_sauvegarde_nav');
	});
}

function verif_login_sauvegarde_navigation(){
	var idlogin = document.getElementById('login');
	var idpass = document.getElementById('pass_login');
	if (idpass.value == '') idpass = document.getElementById('pass');
	var idlogin_c = document.getElementById('login_c');
	var pass_c = document.getElementById('pass_c');
	if(idpass.value=='Votre mot de passe')idpass.value=''; 
	if(idlogin.value=='Votre adresse e-mail')idlogin.value='';
	if(verfi_vide(idlogin.value)){
		if(idlogin_c!=null && idlogin_c!='') idlogin.value=idlogin_c.value;
		if(pass_c!=null && pass_c!='') idpass.value=pass_c.value;
	}
	if ((verfi_vide(idlogin) || verfi_vide(idpass.value))){
			lightbox('lb3_save_navigation');
		return false;
	} else {	 
		LoginProceedWithParam(pageSource);
		return false;
	}
}

/***************************/
/**FIN Refonte page Liste **/
/***************************/
