$(document).ready(function() {
	
	// Verification formulaire connexion au compte client
	$("#identification_compteclient").validate({
		rules: {
			identification_email: {
				required: true,
				email: true,
				maxlength: 80
			},
			identification_password: {
				required: true,
				maxlength: 10
			}
		},
		messages: {
			identification_email: $.i18n._('erreur_email'),
			identification_password: $.i18n._('erreur_password')
		},
		errorPlacement: function(error, element) {
			 $("#msg_identification_error").append(error);
		},
        highlight: function(element, errorClass) {
            $(element.form).find("label[id=error_" + element.id + "]").addClass("nokpicto");
            $(element.form).find("label[id=error_" + element.id + "]").removeClass("okpicto");
         },
         unhighlight: function(element, errorClass) {        	
        	$(element.form).find("label[id=error_" + element.id + "]").addClass("okpicto");
            $(element.form).find("label[id=error_" + element.id + "]").removeClass("nokpicto");
         }
	});
	
    // Validateur spécifique pour la RDG CP obligatoire seulement si Carte_Fid remplie... 
    $.validator.addMethod("required_group",
          function(val, el) {
                if ($('#creation_num_fidelite:filled').length) {
                	return $('#creation_cp:filled').length;
                }
                return true;
          }, "Remplissez au moins l'un des champs"
    );
    jQuery.validator.addMethod("numCarteFid", function(value,element){
    	var numCarteFid  = $("#creation_num_fidelite").val();
		return verifNumCarteFid(numCarteFid);
	}, " ");

    // Vérification formulaire de création d'un compte client
	$("#creation_compteclient_ri").validate({
		rules: {
			creation_email: {
				required: true,
				email: true,
				maxlength : 80
			},
			creation_password: {
				required: true,
				minlength: 6,
				maxlength: 10
			},
			creation_conf_password: {
				required : true,
				equalTo: "#creation_password",
				minlength: 6,
				maxlength: 10
			},
			creation_num_fidelite: {
				required:false,
				numCarteFid:true
			},
			creation_cp: {
				required_group:true
			},
			pays: {
				required: true
				
			}
		},
		messages: {
			creation_email: $.i18n._('erreur_email'),
			creation_password: {
				required: $.i18n._('erreur_password'),
				minlength: $.i18n._('erreur_new_password_taille'),
				maxlength: $.i18n._('erreur_new_password_taille_max')
			},
			creation_conf_password: {
				required: $.i18n._('erreur_conf_password'),
				equalTo: $.i18n._('erreur_conf_password'),
				minlength: $.i18n._('erreur_ancien_password_taille'),
				maxlength: $.i18n._('erreur_ancien_password_taille_max')
			},
			creation_num_fidelite: $.i18n._('erreur_num_fidelite'),
			creation_cp: $.i18n._('erreur_cp')
			//pays: $.i18n._('erreur_pays')
		},
		errorPlacement: function(error, element) {
			 $("#msg_creation_error").append(error);
		},
		highlight: function(element, errorClass) {
			$(element.form).find("label[id=error_" + element.id + "]").addClass("nokpicto");
			$(element.form).find("label[id=error_" + element.id + "]").removeClass("okpicto");
        },
        unhighlight: function(element, errorClass) {        	
        	$(element.form).find("label[id=error_" + element.id + "]").addClass("okpicto");
            $(element.form).find("label[id=error_" + element.id + "]").removeClass("nokpicto");
        }
	});
});

//Le numéro de carte de fidélité commencera toujours par 911 sur GDM et comportera 13 caractères
function verifNumCarteFid(numCarteFid) {
	var bool = false; 
	
	if (numCarteFid == '' || numCarteFid == null){
		return true;
	}else{
		var reg		= new RegExp('^910[a-zA-Z0-9]{10}');
		if (numCarteFid.match(reg)) {
			bool = true;
		}
	}
	return bool;
}

// Appel au WS pour la connexion
function callWSConnexion() {
	openWaitBox();

	$.ajax({
		type: "GET",
		data: PARAMGLOBAL,
		url: PATHRACINE + "/AjaxConnexion",
		cache: false
	});	
	
	launchTimer('AjaxCheckConnexion', 'false');
}

//Appel au WS pour le num fidélité
function callWSNumFid() {
	openWaitBox();
	
	$.ajax({
		type: "GET",
		data: PARAMGLOBAL,
		url: PATHRACINE + "/AjaxNumFidelite",
		cache: false
	});	
	
	launchTimer('AjaxCheckNumFidelite', 'false');
}

//Fonction : Ouverture de la box mot de passe oublié
function forgottenPwd(){
	var email = '';
	
	if($('#login_email').length != 0) {
		email = $('#login_email').val();
	}

	Box.open({
		modal: true,
		url: PATHRACINE+"/MdpOublie",
		urldata: PARAMGLOBAL,
		show: function() {
			if(email != '') $("#mdpoublie_email").val(email);

			$(".pwd_fermer").click(function(){
				Box._close();
				return false;
			});

			$("#envoipwd").validate({
				rules: {
					mdpoublie_email: {
						required: true,
						email: true						
					}					
				},
				messages: {
					mdpoublie_email: "ERREUR EMAIL"
				},
				errorPlacement: function(error, element) {
					 $("#envoipwd_error").append(error);
				},
		      	highlight: function(element, errorClass) {
		          	$(element.form).find("label[id=error_" + element.id + "]").addClass("nokpicto");
		          	$(element.form).find("label[id=error_" + element.id + "]").removeClass("okpicto");
		       	},
		       unhighlight: function(element, errorClass) {        	
		    	  	$(element.form).find("label[id=error_" + element.id + "]").addClass("okpicto");
		          	$(element.form).find("label[id=error_" + element.id + "]").removeClass("nokpicto");
		       }
			});

			$("#envoipwd").submit( function(){
				if($("#envoipwd").valid()){
					$.ajax({
						type: "POST",
						data: PARAMGLOBAL +"&"+ $("#envoipwd").serialize(),
						cache: false,
						url: PATHRACINE+"/MdpOublie",
						success: function(data) {
							if ($.trim(data) != null && $.trim(data) != "") {
								eval(data);
							}
						}
					});
				}

				return false;
			});
		}
	});

	return false;
}

//En cas d'erreur => affichage des erreurs
function majPwd(mdpoublieEmail, hasError, hasErrorMdpOublieEmail, hasErrorMdpOublieEmailCptClient) {
	$("#mdpoublie_email").attr("value", mdpoublieEmail);

	if(hasErrorMdpOublieEmail == 'true'){
		$('#envoipwd_error').html('<label class="error" for="mdpoublie_email" generated="true">'+$.i18n._('erreur_email')+'</label>');
		$("#error_mdpoublie_email").addClass("nokpicto");
	}
	
	if(hasErrorMdpOublieEmailCptClient == 'true') {
		$('#envoipwd_error').html('<label class="error" for="mdpoublie_email" generated="true">'+$.i18n._('erreur_email_inexistant')+'</label>');
		$("#error_mdpoublie_email").addClass("nokpicto"); 
	};

	if(hasError == 'false') { 
		$("#envoipwd_error").html($.i18n._('msg_nouveau_mdp'));
		$("#envoipwd_error").css({visibility : "visible"});
		setTimeout("Box._close()", 1000); 
	}
}

function majFastLogin(titre, nom, prenom, urlDeco, urlSuiviCommandes, urlSL, urlPF, urlInfosPersos) {
	var htmlFastLogin = "";
	htmlFastLogin += '<div id="accueil_ident"><span>';
	htmlFastLogin += $.i18n._("Bonjour");	
	htmlFastLogin += '&nbsp;' + titre;
	htmlFastLogin += '&nbsp;' + prenom;
	htmlFastLogin += '&nbsp;' + nom;
	htmlFastLogin += '</span><a id="fastDeconnexion">Me déconnecter <img src="' + PATHRES + '/img/00-header/n_picto_deconnecter.gif" border="0" width="9" height="8"></a></div>';
	htmlFastLogin += '<ul id="menu_ident">';
	htmlFastLogin += '<li><a href="' + urlSuiviCommandes + '">Suivre mes commandes</a></li>';
	htmlFastLogin += '<li><a href="' + urlSL + '">Voir ma shopping liste</a></li>';
	htmlFastLogin += '<li><a href="' + urlPF + '">Consulter mon solde de points fidélité</a></li>';
	htmlFastLogin += '<li><a href="' + urlInfosPersos + '">Modifier mes informations personnelles</a></li>';
	htmlFastLogin += '</ul>';
	
	$("#bandeau #login").html(htmlFastLogin);
}

function majFastLogout() {
	var htmlFastLogout = "";
	htmlFastLogout += '<form name="fast_identification_compteclient" id="fast_identification_compteclient" method="post">';
		htmlFastLogout += '<p style="font-weight:bold">Je suis d&eacute;j&agrave; cliente Phildar.fr</p>';
		htmlFastLogout += '<p><label for="identification_email">E-mail</label> <input name="identification_email" id="identification_email" type="text" maxlength="80"> <label for="identification_password">Mot de passe</label> <input name="identification_password" id="identification_password" type="password" maxlength="10"></p>';
		htmlFastLogout += '<p class="error"><label>Message d\'erreur</label></p>';
		htmlFastLogout += '<p><button type="submit"> <img src="' + PATHRES + '/img/00-menu/n_fleche_grise.png" border="0" width="13" height="12"> Je valide</button> <a class="mdp" href="#" onclick="forgottenPwd();">Mot de passe oubli&eacute;&nbsp;?</a></p>';
	htmlFastLogout += '</form>';
	htmlFastLogout += '<div class="separateur"></div>';
	htmlFastLogout += '<p style="font-weight:bold">Je ne suis pas encore cliente</p>';
	htmlFastLogout += '<p> <a href="/espace-client.r.html"><img src="' + PATHRES + '/img/00-menu/n_fleche_grise.png" border="0" width="13" height="12">&nbsp;Je cr&eacute;e mon compte</a></p>';
	
	$("#bandeau #login").html(htmlFastLogout);
}
