/* 	Catalogue
	Auteur : Maxime RICHARD
	Date : 11/06/2009
*/

//Au chargement de la page
var lock=false;
var validatedForm = false;

jQuery.validator.addMethod( 
	"dateValide", 
	function(value, element) {
		var moiscarte = $("#mois_carte").val();
		if(annee==$("#annee_carte").val()){
			if(parseInt(moiscarte)<mois){
				return false;
			}
		}
		return true; 
	}, 
	"Date NOK" 
); 

jQuery.validator.addMethod( 
		"montantValid", 
		function(value, element) {
			var reg=new RegExp('[,]');
			value=value.replace(reg,'.');
			if(RAP-value >= 0){
				return true;
			}
			return false; 
		}, 
		"Vérifiez le montant à consommer sur votre carte cadeau. Il ne peut être supérieur au montant total de votre commande."
	); 

jQuery.validator.addMethod( 
		"numCarte", 
		function(value, element) {
			var re;
			if($("#type_carte").val()=='AMEX'){
				re = new RegExp("^[0-9]{15}$");
	            return re.test(value);
			}
			else{
				re = new RegExp("^[0-9]{16}$");
	            return re.test(value);
			}
			return false; 
		}, 
		"Date NOK" 
	); 

jQuery.validator.addMethod( 
		"cryptoCarte", 
		function(value, element) {
			var re;
			if($("#type_carte").val()=='AMEX'){
				re = new RegExp("^[0-9]{4}$");
	            return re.test(value);
			}
			else{
				re = new RegExp("^[0-9]{3}$");
	            return re.test(value);
			}
			return false; 
		}, 
		"Date NOK" 
	); 

$(document).ready(function(){
	//Si le client a choisi son mode de livraison, son adersse et a cocher les CGV alors on déchache le paiement
	decouvrePaiement();
	
	$("#newsOKHeader").click(function(){
		newsletterForm1();
	});
	
	$("#newsOKFooter").click(function(){
		newsletterForm2();
	});
	
	$("#cgv").hide();
	
	$(".mode_livraison").click(function(){
		decouvrePaiement();
	});

	$(".adresse-box").mouseover(function(){
		$(this).addClass('adresse-box-over');
	});
	
	$(".adresse-box").mouseout(function(){
		$(this).removeClass('adresse-box-over');
	});
	
	$(".ChoisirAdresse").click(function(){
		choisirAdresse();
	});
	
	//test des codes promotion
	$("#PromotionFormValidate").click(function(){
		if($("#PromotionCode").val()==''){
			Box.open({ url: "/nocibe/AjaxErrorMessageCommand?"+paramsGlobal+"&ErrorCode=MsgInfo_c0015_UnknownPromotionCode", modal:true });
		}
		else{
			//Lancement du spinner
			launchSpinner(function(){$("#PromotionForm").submit();});
		}
	});
	
	$("#ValidePanier").click(function(){
		$("#cadeau_val").val($("#cadeau input:checked").val());
		$("#messageCadeau_val").val($("#messageCadeau_ok").val());
		$("#PanierForm").submit();
	});
	
	$("#ValidePlusNocibe").click(function(){
		$("#PlusNocibeForm").submit();			
	});

	// Appel des modales
	$("#lien_details_relais").click(function(){
		Box.open({ url: "/nocibe/AjaxRelaisDetails?"+paramsGlobal+"&RelaisID="+$("#RelaisID").val(), modal:true,top:100, loading:true });
	});

	$(".lien_ajout_adresse").click(function() {
		Box.open({ url: "/nocibe/AjaxAddAddress?"+paramsGlobal+"&AddressBookID="+adresseBookLivraisonId+"&basket=1", modal:true,loading:true });
	});

	$(".lien_ajout_adresse_facturation").click(function(){
		Box.open({ url: "/nocibe/AjaxAddAddress?"+paramsGlobal+"&AddressBookID="+adresseBookFacturationId+"&basket=1", modal:true,loading:true });
	});

	$(".lien_modif_adresseLivraison").click(function(){
		Box.open({ url: "/nocibe/AjaxGestionAddressModification?"+paramsGlobal+"&adresseId="+billingAddressId+"&basket=1"+"&TypeId=1", modal:true, loading:true });
	});
	$(".lien_modif_adresseFacturation").click(function(){
		Box.open({ url: "/nocibe/AjaxGestionAddressModification?"+paramsGlobal+"&adresseId="+$("#adrFac").val()+"&basket=1"+"&TypeId=2", modal:true,loading:true });
	});
	
	$("#lien_oubli_pass").click(function(){
		Box.open({ url: "../../01_catalog/00_ajax/oubli_pass.jsp", modal:true });
	});
	
	$("#acheterAvecPaypal").click(function(){
		validePaypal();
	});
	
	$("#validePaiementBAP").click(function(){
		valideBAP();
	});
	
	$("#validePaiementCKDO").click(function(){
		valideCKDO();
	});

	//Achat Express
	$(".articleCraquage").hover(
			function(){$(this).find(".ae").fadeIn(300);},
			function(){$(this).find(".ae").fadeOut(300);}
	);
	$(".articleCraquage").click(function(){
		var rayon = $("#vgRayon").val();
		Box.open({ url: "/nocibe/AjaxAchatExpress?productID="+ $(this).parent().find("input[name=ProductID]").val() +"&"+paramsGlobal+"&vRayon="+rayon+"&rechargement="+ 1, modal:true });
	});
	
	// Incrémente / décrémente la quantité d'échantillons
	$(".echAdd").click(
			function(){
				var tmp = eval($(this).parent().parent().find(".qte").val()) + 1;
				var total = 0;
				$("input[id^='qte']").each(function(){
					total= total+eval($(this).val());
				});
				if (total<echantillon)
				{	$(this).parent().parent().find(".qte").val(tmp);
					$("#qte_total").html(total+1);
				}
				return false;
			}
	);
	$(".echSub").click(
			function(){
				var tmp = eval($(this).parent().parent().find(".qte").val()) - 1;
				var total = 0;
				$("input[id^='qte']").each(function(){
					total= total+eval($(this).val());
				});
				if (tmp>=0)
				{	$(this).parent().parent().find(".qte").val(tmp);
					$("#qte_total").html(total-1);
				}
				return false;
			}
	);
	
	// Affiche / masque le choix de l'emballage cadeau
	$("#cadeau_oui").click(function() {
		var val = $("#messageCadeau_ok").html();
		Box.open({ url: "/nocibe/03_order/00_ajax/gift_message.jsp?"+paramsGlobal+"&msg="+val, modal:true, loading:true });
		$("#container_cadeau").slideDown();
		$("#cadeau_coffret").attr('checked',true);
		
	});
	$("#cadeau_non").click(function() {
		$("#container_cadeau").slideUp();
	});

	$("#cp").focus(function() {
		$(this).val('');
	});
	$("#cp").blur(function() {
		if($(this).val()=='')
			$(this).val(cpMsgDefaut);
	});
	
	$("#cp").keypress(function(event) {
		if (event.keyCode==13 || event.which==13){
			if($(this).val()=='' || $(this).val()==cpMsgDefaut ){
				 reloadPointRelais();
			}
			return false;
		}
	});

	// Affiche / masque le choix du mode de livraison
	$("input[id^='livraison_']").click(function() {
		$("div[id^='container_livraison']").each(function(){
			var $this=$(this);
			$this.slideUp();
		});
		$("input[id^='livraison_']").each(function(){
			var $this=$(this);
			$this.next("label").removeClass("bold");
			$this.next("label").children().removeClass("redRubine");
		});	
		$("#container_livraison"+$(this).attr("id").split('livraison_')[1]).slideDown();
		$(this).next("label").addClass("bold");
		$(this).next("label").children().addClass("redRubine");
	});
	
	// Affiche / masque le choix du mode de paiement
	$("#paiement1").click(function() {
		$("#container_paiement2").slideUp();
		$("#container_paiement3").slideUp();
		$("#container_paiement4").slideUp();
		$("#container_paiement5").slideUp();
		$("#container_paiement1").slideDown();
		$("#paiement2").next("label").removeClass("bold");
		$("#paiement3").next("label").removeClass("bold");
		$("#paiement4").next("label").removeClass("bold");
		$("#paiement5").next("label").removeClass("bold");
		$("#paiement1").next("label").addClass("bold");
	});
	$("#paiement2").click(function() {
		$("#container_paiement1").slideUp();
		$("#container_paiement3").slideUp();
		$("#container_paiement4").slideUp();
		$("#container_paiement5").slideUp();
		$("#container_paiement2").slideDown();
		$("#paiement1").next("label").removeClass("bold");
		$("#paiement3").next("label").removeClass("bold");
		$("#paiement4").next("label").removeClass("bold");
		$("#paiement5").next("label").removeClass("bold");
		$("#paiement2").next("label").addClass("bold");
	});
	$("#paiement3").click(function() {
		$("#container_paiement1").slideUp();
		$("#container_paiement2").slideUp();
		$("#container_paiement4").slideUp();
		$("#container_paiement5").slideUp();
		$("#container_paiement3").slideDown();
		$("#paiement1").next("label").removeClass("bold");
		$("#paiement2").next("label").removeClass("bold");
		$("#paiement4").next("label").removeClass("bold");
		$("#paiement5").next("label").removeClass("bold");
		$("#paiement3").next("label").addClass("bold");
	});
	$("#paiement4").click(function() {
		$("#container_paiement1").slideUp();
		$("#container_paiement2").slideUp();
		$("#container_paiement3").slideUp();
		$("#container_paiement5").slideUp();
		$("#container_paiement4").slideDown();
		$("#paiement1").next("label").removeClass("bold");
		$("#paiement2").next("label").removeClass("bold");
		$("#paiement3").next("label").removeClass("bold");
		$("#paiement5").next("label").removeClass("bold");
		$("#paiement4").next("label").addClass("bold");
	});
	
	$("#paiement5").click(function() {
		$("#container_paiement1").slideUp();
		$("#container_paiement2").slideUp();
		$("#container_paiement3").slideUp();
		$("#container_paiement4").slideUp();
		$("#container_paiement5").slideDown();
		$("#paiement1").next("label").removeClass("bold");
		$("#paiement2").next("label").removeClass("bold");
		$("#paiement3").next("label").removeClass("bold");
		$("#paiement4").next("label").removeClass("bold");
		$("#paiement5").next("label").addClass("bold");
	});

	$("#messageCadeau").keypress(function(){
		if($(this).val().length>=250){
			$(this).val($(this).val().substr(0,249));
		}
	});
	
	var validatorCarteBancaire = $("#carteBancaire").validate({
		groups: {
    		fulldate: "jj_naissance mm_naissance aaaa_naissance"
		},
		rules: {
			num_carte: 		{ required: true, numCarte: true },
			mois_carte:	{required:false, dateValide: true},
			annee_carte:	{required:false, dateValide: true},
			crypto_carte: 		{ required: true,cryptoCarte: true }
		},
		messages: {
			num_carte: 		{ required: "Indiquez votre numéro de carte bancaire",numCarte: "Le numéro de carte bancaire est incorrect" },
			mois_carte:	{dateValide:"Vérifiez la date de validité de votre carte bancaire. Elle ne doit pas être antérieure à la date du jour."},
			annee_carte:	{dateValide:"Vérifiez la date de validité de votre carte bancaire. Elle ne doit pas être antérieure à la date du jour."},
			crypto_carte: 		{ required: "Indiquez votre cryptogramme de carte bancaire",cryptoCarte: "Le cryptogramme est incorrect" }
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if (element.attr("name") == "mois_carte" || element.attr("name") == "annee_carte")
			{
				$("#date_p").empty();
				error.appendTo( $("#date_p") );
				$("#date_label").removeClass("valid").addClass("notvalid");
			}
			else
			{
				error.appendTo( element.next().next() );
				$('#'+element.name+"_label").removeClass("valid").addClass("notvalid");
			}
		},
		
		// strips the invalid class from the invalid elements when they become valid
		highlight: function(element, errorClass) {
		 	if(element.name == "mois_carte" || element.name == "annee_carte")
			{	$("#date_label").removeClass("valid").addClass("notvalid");
			}
			else
			{	$('#'+element.name+"_label").removeClass("valid").addClass("notvalid");
			}
		},
		// puts it back if they are still invalid
		unhighlight: function(element, errorClass) {
			if (element.name == "mois_carte" || element.name == "annee_carte")
			{	$("#date_label").removeClass("notvalid").addClass("valid");
				$("#date_p").empty();
			}
			else
			{  $('#'+element.name+"_label").removeClass("notvalid").addClass("valid");
			}
		}
		
	});
	
	var validatorCarteCadeau = $("#carteCadeau").validate({
		
		rules: {
			montant_carte: 		{ 	required: true, 
									regex: "^([0-9]+|([0-9]+\.[0-9]{0,2}))$", montantValid: true 
								},
			num_carte: 			{ 	required: true, 
									regex: "^[0-9]{19}$"
								},
			crypto_carte: 		{ 	required: true, 
									regex: "^[0-9]{3}$" 
								}
		},
		messages: {
			montant_carte: 		{ 	required: "Indiquez le montant à régler avec la carte cadeau", 
									regex: "Le montant à régler est incorrect",
									montantValid: "Vérifiez le montant à consommer sur votre carte cadeau. Il ne peut être supérieur au montant total de votre commande."
								},
			num_carte: 			{ 	required: "Indiquez le numéro de la carte cadeau", 
									regex: "Le numéro de la carte est incorrect" 
								},
			crypto_carte: 		{ 	required: "Indiquez le cryptogramme de la carte cadeau", 
									regex: "Le cryptogramme est incorrect" 
								}
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
				error.appendTo( element.next().next() );
				$('#'+element.name+"_cardops_label").removeClass("valid").addClass("notvalid");
		},// set this class to error-labels to indicate valid fields
		success: function(label) {
			label.remove();
		},
		// strips the invalid class from the invalid elements when they become valid
		highlight: function(element, errorClass) {
			$('#'+element.name+"_cardops_label").removeClass("valid").addClass("notvalid");
		},
		// puts it back if they are still invalid
		unhighlight: function(element, errorClass) {
			$('#'+element.name+"_cardops_label").removeClass("notvalid").addClass("valid");
		}
		
	});
	
	var validatorCarteCadeau = $("#boxAdresseLivraison").validate({
		
		rules: {
			nom: 		{ required: true},
			prenom: 	{ required: false},
			adrL1: 		{ required: true},
			adrL2:		{ required: false},
			adrL3:		{ required: false},
			adrL4:		{ required: false},
			cp:			{ required: true, regex: "^[0-9]{5}$" },
			ville:		{ required: true},
			pays:		{ required: true},
			telephone:	{ required: true, regex: "^[0-9]{10}$" }
		},
		messages: {
			nom: 		{ required: "Veuillez saisir votre nom en modifiant votre adresse de livraison."},
			prenom: 	{ },
			adrL1: 		{ required: "Veuillez saisir votre adresse en modifiant votre adresse de livraison."},
			adrL2:		{ },
			adrL3:		{ },
			adrL4:		{ },
			cp:			{ required: "Veuillez saisir votre code postal en modifiant votre adresse de livraison.", regex: "Votre code postal n'est pas au bon format." },
			ville:		{ required: "Veuillez saisir votre ville en modifiant voter adresse de livraison."},
			pays:		{ required: "Veuillez saisir votre pays en modifiant votre adresse de livraison."},
			telephone:	{ required: "Veuillez saisir votre numéro de téléphone en modifiant votre adresse de livraison.", regex: "Votre numéro de téléphone n'est pas au bon format." }
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
				error.appendTo( element.next().next() );
				$('#'+element.name+"_box_label").removeClass("valid").addClass("notvalid");
		},// set this class to error-labels to indicate valid fields
		success: function(label) {
			label.remove();
		},
		// strips the invalid class from the invalid elements when they become valid
		highlight: function(element, errorClass) {
			$('#'+element.name+"_box_label").removeClass("valid").addClass("notvalid");
		},
		// puts it back if they are still invalid
		unhighlight: function(element, errorClass) {
			$('#'+element.name+"_box_label").removeClass("notvalid").addClass("valid");
		}
		
	});
	
	// Switche les cases de choix du cadeau dans le panier
	$(".cadeau_radio").click(function() {
		$(".cadeau_radio").attr('checked',false);
		if ($(this).attr('checked')==false)
		{ $(this).attr('checked',true); }
	});
	
	$(".imprimer").click(function() {
		document.print();
	});
	
	$(".wishlist_b").click(function() {
		Box.open({ url: "/nocibe/AjaxWishList?"+paramsGlobal+"&skuID=no&basket=1", modal:true });
	});

	var validator2 = $("#maximilesForm").validate({		
		rules: {
			maximiles_email: 		{ required: true}
		},
		messages: {
			maximiles_email: 		{ required: "Veuillez saisir votre identifiant Maximiles."}
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			element.next().next().next().empty();
			error.appendTo( element.next().next().next() );
			element.next().removeClass("valid").addClass("notvalid");
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			label.remove();
		},
		// strips the invalid class from the invalid elements when they become valid
		highlight: function(element, errorClass) {		 	
				$('#'+element.name).next().removeClass("valid").addClass("notvalid");			
		},
		// puts it back if they are still invalid
		unhighlight: function(element, errorClass) {
		  $('#'+element.name).next().removeClass("notvalid").addClass("valid");		
		}
	});
	
	$("#maximilesForm").click(function() {
		if($("#maximilesForm").valid()) {
			$.ajax({
				type: "GET",
				data: paramsGlobal+"&login="+$("#maximiles_email").val()+"&CommandeID="+commandeId,
				url:  "/nocibe/Maximiles",
				cache: false,
				success: function(data) {
					eval(data);
				}
			});
		}
	});
	
	
	$("input[id^='cadeauOK_']").click(function() {
		if($(this).is(":checked")){			
			$("#giftId").val($(this).val());
			$("#operationId").val($(this).parent().parent().parent().parent().parent().parent().find("input[name='codeOp']").attr("value"));
			$("#actionCode").val('ok');
			launchSpinner(function(){$("#giftForm").submit();});
		}
	});

	$("input[id^='cadeauKO_']").click(function() {
		if($(this).is(":refused")){			
			$("#giftId").val($(this).val());
			$("#operationId").val($(this).parent().parent().parent().parent().parent().parent().find("input[name='codeOp']").attr("value"));			
			$("#actionCode").val('ko');
			launchSpinner(function(){$("#giftForm").submit();});
		}
	});

	$("#PromotionCode").blur(function(){
		$(this).val($(this).val().toUpperCase());
	});
	
	$("#PromotionCode").keypress(function(event){
		if(event.keyCode==13 || event.which==13){
			$(this).val($(this).val().toUpperCase());
		}
	});
	
	
});


//Au chargement mais avec les taille pour chrome
$(window).load(function(){
	//Initialisation du cache Paiement
	decouvrePaiement();
});

// affichage du message d'erreur lors du clic sur la zone de paiement grise
function showErreurCmdMsg() {
	// le message d'erreur doit etre adapte a la situtation
	var modeLiv = ($(".mode_livraison:checked").val() != undefined);
	var cgv = $("#cgv").attr('checked') == true;
	var adrLiv = ($("#boxAdresseLivraison .bold").text().length > 0);
	//initialisation du message d'erreur par sa valeur par defaut.
	var msg = 'MsgError_c0013_NoPaymentPossible_1';
	
	//pas de mode de livraison (seul)
	if (!modeLiv && cgv && adrLiv) {
		msg = 'MsgError_c0013_NoPaymentPossible_2';
	} else if (modeLiv && !cgv && adrLiv) {
		// cgv non validees (seul)
		msg = 'MsgError_c0013_NoPaymentPossible_3';
	} else if (modeLiv && cgv && !adrLiv) {
		// pas d'adresse de livraison (seul)
		msg = 'MsgError_c0013_NoPaymentPossible_4';
	} else if (!modeLiv && !cgv) {
		// pas de mode de livraison + cgv non validees
		msg = 'MsgError_c0013_NoPaymentPossible_1';
	} else if (modeLiv && !cgv && !adrLiv) {
		// pas de mode de livraison + cgv non validees
		msg = 'MsgError_c0013_NoPaymentPossible_5';
	}

	// ouverture du popup d'erreur
	Box.open({ url: "/nocibe/AjaxErrorMessageCommand?" + paramsGlobal+"&ErrorCode=" + msg, modal:true });
}

//Cache les fonctionnalitées de paiement
function init_cachePaiement()
{
	//Verification de l'existant
	if($("#paiement.blanc").length>0)
	{
		$("body").prepend("<div id='paiementC' onclick='showErreurCmdMsg();'></div>");
		var pos = $("#paiement").offset();
		$("#paiementC").css({top:pos.top,left:pos.left,width:$("#paiement").outerWidth(),height:$("#paiement").outerHeight()});
		$("#paiementC").show();
	}
}

function killPaiement()
{
	$("#paiementC").hide().remove();
}

function confirmOrderItemDelete(itemID) {
	Box.open({ url: "/nocibe/03_order/00_ajax/confirmItemDelete.jsp?"+paramsGlobal+"&itemID="+itemID, modal:true });
}

function confirmOrderItemDeleteOK(itemID) {
	document.location.href = "/nocibe/OrderItemDelete?" + paramsGlobal + "&LineID=" + itemID + "&etape=1";
}

function annulerOrderItemDelete() {
	Box._close();
}

var relaisInfo=[];

function ouvrirMessageCadeau() {
	var val = $("#messageCadeau_ok").html();
	Box.open({ url: "/nocibe/03_order/00_ajax/gift_message.jsp?"+paramsGlobal+"&msg="+val, modal:true });
}

function validerMessageCadeau() {
	var val = $("#messageCadeau").val();
	$("#messageCadeau_ok").html(val);
	$("#messageCadeau_span").html(val.replace('\n','<br>'));
	Box._close();
}

function validerSampleForm() {
	var ids = "";
	var obj;
	for (i=0; i<nbEchantillonProposes; i++) {
		if (document.getElementsByName("sample_checkbox")[i].checked == true) {
			obj = document.getElementsByName("sample_checkbox")[i];
			if (ids == "") {
				ids = obj.value; 
			} else {
				ids = ids + ";" + obj.value;
			}
		}
	}

	var isCad = document.getElementById("cadeau_oui").checked;
	var msg = document.getElementById("messageCadeau_ok").value;
	document.location.href="/nocibe/SampleSave?" + paramsGlobal+"&idSamples="+ids+"&cadeau_val="+isCad+"&messageCadeau_val="+msg;
}

function setRelais(){
	var index=$("#relaisList").val();
	var html = "";

	if(relaisInfo.length>index){
		$("#RelaisAddressDiv").html("<span class=\"bold\">"+relaisInfo[index][1]+"</span><br/>"+relaisInfo[index][2]+"<br/>"+relaisInfo[index][3]+" "+relaisInfo[index][4]+"<br/>");
		$("#relais_title").text("Relais colis sélectionné");

		//on ajoute l'adresse dans la box adresse de livraison
		html = "<span class=\"bold\">"+ relaisInfo[index][1] +"</span><br />"+
		relaisInfo[index][2]+"<br />"+
		relaisInfo[index][3] +  " " + relaisInfo[index][4] +"<br />"+
		"<form id=\"livraisonform\" action=\"/nocibe/AjaxSaveAddressRelaisColis\">"+
		"<input id=\"StoreID\" type=\"hidden\" name=\"StoreID\" class=\"StoreID\" value=\"1\" />" +
		"<input id=\"CatalogueID\" type=\"hidden\" name=\"CatalogueID\" class=\"CatalogueID\" value=\"1\" />" +
		"<input id=\"LangueID\" type=\"hidden\" name=\"LangueID\" class=\"LangueID\" value=\"1\" />" +
		"<input id=\"relaisID\" type=\"hidden\" name=\"relaisID\" class=\"relaisID\" value=\""+ relaisInfo[index][0] +"\" />" +	
		"<input id=\"relaisName\" type=\"hidden\" name=\"relaisName\" class=\"relaisName\" value=\""+ relaisInfo[index][1] +"\" />" +
		"<input id=\"relaisAddresspl\" type=\"hidden\" name=\"relaisAddresspl\" class=\"relaisAddresspl\" value=\""+ relaisInfo[index][2] +"\" />" +
		"<input id=\"relaisZipcode\" type=\"hidden\" name=\"relaisZipcode\" class=\"relaisZipcode\" value=\""+ relaisInfo[index][3] +"\" />" +
		"<input id=\"relaisCity\" type=\"hidden\" name=\"relaisCity\" class=\"relaisCity\" value=\""+ relaisInfo[index][4] +"\" />" +
		"</form>"+
		"<div class=\"relais_decale floatLeft\">Choisir un autre relais colis :</div><br/>" +
		"<div class=\"overflow clear\" style=\"margin-left:45px;\">" +
		"<input id=\"cp\" type=\"text\" name=\"cp\" class=\"cp\" value=\""+ $('#cp').val() +"\" />" +									  
		"<img src=\"/nocibe/res/fr_FR/img/btn_voir_liste.gif\" class=\"floatRight hand bt_bas\" width=\"96\" height=\"25\" border=\"0\" alt=\"\" id=\"lien_liste_relais\" onclick=\"javascript:reloadPointRelais();\"/>" +
		"</div>";
	}

	Box._close();
	$("#boxAdresseLivraison").html(html);

	// Enregistrement du Relais sur la commande
	validationAdresseLivraisonRelaisColis();
}

function encode(chaine){
	var reg=new RegExp("[%]");
	var res=chaine.replace(reg,"%25");
	reg=new RegExp("[&]");
	res=res.replace(reg,"%26");
	reg=new RegExp("[?]");
	res=res.replace(reg,"%3F");
	reg=new RegExp("[=]");
	res=res.replace(reg,"%3D");
	return res;
}

function incrementQuantity(lineId){
	if(!lock){
		lock=true;
		$("#updateForm").find("[id='lineId']").val(lineId);
		$("#qte"+lineId).val($("#qte"+lineId).val()*1+1);
		$("#updateForm").find("[id='quantity']").val($("#qte"+lineId).val());
		$("#updateForm").submit();
	}
}


function discrementQuantity(lineId){
	if(!lock){
		lock=true;
		$("#updateForm").find("[id='lineId']").val(lineId);
		$("#qte"+lineId).val($("#qte"+lineId).val()-1);
		$("#updateForm").find("[id='quantity']").val($("#qte"+lineId).val());
		$("#updateForm").submit();
	}
}

function incrementInstitutCardQuantity(lineId){
	if(!lock){
		lock=true;
		$("#updateInstitutForm").find("[id='lineId']").val(lineId);
		$("#qte"+lineId).val($("#qte"+lineId).val()*1+1);
		$("#updateInstitutForm").find("[id='quantity']").val($("#qte"+lineId).val());
		$("#updateInstitutForm").submit();
	}
}

function discrementInstitutCardQuantity(lineId){
	if(!lock){
		lock=true;
		$("#updateInstitutForm").find("[id='lineId']").val(lineId);
		$("#qte"+lineId).val($("#qte"+lineId).val()-1);
		$("#updateInstitutForm").find("[id='quantity']").val($("#qte"+lineId).val());
		$("#updateInstitutForm").submit();
	}
}

function valideCGV(){
	if($("#cgv").attr('checked') == false){
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?"+paramsGlobal+"&ErrorCode=MsgInfo_c0016_AcceptCGV", modal:true });
		return false;
	}else{
		return true;
	}
}

function valideCB(){
	cacheBouton();	
	
	var ship = $(".mode_livraison:checked").val();

	if (ship == undefined || ship == null || ship == "") {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?" + paramsGlobal + "&ErrorCode=MsgError_c0013_ShipmodeNotSelected", modal:true });
		afficheBouton();
	}else{	
		var mdl = $(".mode_livraison:checked").val();
		if(mdl == 1 && $("#boxAdresseLivraison .bold").text().length == 0){
			selectShippingMode(1);
			afficheBouton();
			return false;
		}else if($("#carteBancaire").valid() && valideLivraison()== true && valideCGV() == true){
			$("#carteBancaire").submit();
			validatedForm = true;					
		}else{
			afficheBouton();
		}
	}
}

function valideCKDO(){
	$("#validePaiementCKDO").css("display", "none");
	$("#loadingCKDO").css("display", "block");
	
	var ship = $(".mode_livraison:checked").val();

	if (ship == undefined || ship == null || ship == "") {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?" + paramsGlobal + "&ErrorCode=MsgError_c0013_ShipmodeNotSelected", modal:true });
		$("#validePaiementCKDO").css("display", "block");
		$("#loadingCKDO").css("display", "none");
	}else{
		var mdl = $(".mode_livraison:checked").val();
		if(mdl == 1 && $("#boxAdresseLivraison .bold").text().length == 0){
			selectShippingMode(1);
			afficheBouton();
			return false;
		}else if($("#carteCadeau").valid() && valideLivraison()== true && valideCGV() == true){					
			$("#carteCadeau").submit();
			validatedForm = true;											
		}else{
			$("#validePaiementCKDO").css("display", "block");
			$("#loadingCKDO").css("display", "none");
		}
	}
}

function valideBAP(){
	$("#validePaiementBAP").css("display", "none");
	$("#loadingBAP").css("display", "block");
	var ship = $(".mode_livraison:checked").val();

	if (ship == undefined || ship == null || ship == "") {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?" + paramsGlobal + "&ErrorCode=MsgError_c0013_ShipmodeNotSelected", modal:true });
		$("#validePaiementBAP").css("display", "block");
		$("#loadingBAP").css("display", "none");
	}else{
		var mdl = $(".mode_livraison:checked").val();
		if(mdl == 1 && $("#boxAdresseLivraison .bold").text().length == 0){
			selectShippingMode(1);
			afficheBouton();
			return false;
		}else if(valideLivraison()== true && valideCGV() == true){
			$("#bonAchat").submit();
			validatedForm = true;	
		}else{
			$("#validePaiementBAP").css("display", "block");
			$("#loadingBAP").css("display", "none");
		}
	}
}

function validePaypal(){
	$("#acheterAvecPaypal").css("display", "none");
	$("#loadingPaypal").css("display", "block");
	var ship = $(".mode_livraison:checked").val();

	if (ship == undefined || ship == null || ship == "") {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?" + paramsGlobal + "&ErrorCode=MsgError_c0013_ShipmodeNotSelected", modal:true });
		$("#acheterAvecPaypal").css("display", "block");
		$("#loadingPaypal").css("display", "none");
	}else{
		var mdl = $(".mode_livraison:checked").val();
		if(mdl == 1 && $("#boxAdresseLivraison .bold").text().length == 0){
			selectShippingMode(1);
			afficheBouton();
			return false;
		}else if(valideLivraison()== true && valideCGV() == true){
			document.location.href=$("#urlPaypal").val();	
		}else{
			$("#acheterAvecPaypal").css("display", "block");
			$("#loadingPaypal").css("display", "none");
		}
	}
}

function afficheBouton(){
	$("#validePaiement").css("display", "block");
	$("#loading").css("display", "none");
}

function cacheBouton(){
	$("#validePaiement").css("display", "none");
	$("#loading").css("display", "block");
}

function ImgError(source, taille){
    source.src = "/bibliotheque/produits/Photo_indispo"+taille+"x"+taille+".jpg";
    source.onerror = "";
    return true;
}

function modalesLivraison(){
	//ouverture de la pop-up point relais.
	var cond1 = $(".mode_livraison:checked").val(); // retourne 1 ou 2 pour Relais colis
	var cond3 = $("#cp").val();

	if ((cond1 != undefined && (cond1 == 1 || cond1 == 2)) && (cond3 != undefined  && cond3 != '' && cond3 != 'Code Postal')) {
		var html = "";

		html = "<img src=\"/nocibe/res/fr_FR/img/logo_relais.gif\" class=\"fleche floatLeft\" width=\"35\" height=\"28\" border=\"0\" alt=\"\" />" +
				"<input id=\"cp\" type=\"text\" name=\"cp\" class=\"cp\" value="+$('#cp').val()+" />" +
				"<img src=\"/nocibe/res/fr_FR/img/btn_voir_liste.gif\" class=\"floatRight hand\" width=\"96\" height=\"25\" border=\"0\" alt=\"\" id=\"lien_liste_relais\" style=\"margin-top:74px;\" onclick=\"javascript:reloadPointRelais();\" />";

		$("#boxAdresseLivraison").html(html);

		Box.open({ url: "/nocibe/AjaxRelaisList?"+paramsGlobal+"&ZipCode="+ cond3, modal:true});
	}
}

function selectShippingMode(shippingMode) {
	launchSpinner(function(){document.location.href = "/nocibe/ChangeShippingMode?" + paramsGlobal + "&mode_livraison=" + shippingMode;});
}

function gestionAdresses(adr){
	Box.open({ url: "/nocibe/AjaxGestionAddressModification?"+paramsGlobal+"&adresseId="+adr+"&TypeId=1", modal:true });
}

function valideLivraison(){
	var mdl = $(".mode_livraison:checked").val();
	$(".contenu_paiement #TransportID").val(mdl);
	
	if (mdl == undefined || mdl == null || mdl == '') {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?"+paramsGlobal+"&ErrorCode=MsgError_c0001_ShipmodeUndefined", modal:true });
		return false;
	}
	
	var adresseFac = $("#boxAdresseFacturation").text();
	if(adresseFac == ''){
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?"+paramsGlobal+"&ErrorCode=MsgError_c0004_LackOfAddress", modal:true });
		return false;
	}

	return true;
}

function reloadPointRelais(){
	var cp = $('#cp').val();
	if(cp == undefined || cp=='' || cp==cpMsgDefaut) {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?"+paramsGlobal+"&ErrorCode=MsgError_c0004_NoZipCode", modal:true,loading:true });
	}else{
		Box.open({ url: "/nocibe/AjaxRelaisList?"+paramsGlobal+"&ZipCode="+$('#cp').val(), modal:true ,loading:true});
	}
}

function isShippingModeChecked() {
	var ship = $(".mode_livraison:checked").val();

	if (ship == undefined || ship == null || ship == "") {
		Box.open({ url: "/nocibe/AjaxErrorMessageCommand?" + paramsGlobal + "&ErrorCode=MsgError_c0013_ShipmodeNotSelected", modal:true });
	}
}

function validationAdresseLivraisonRelaisColis(){
	$("#livraisonform").find("input[name=TransportID]").val($(".mode_livraison:checked").val());
	$("#livraisonform").find("input[name=relaisID]").val();
	$("#livraisonform").find("input[name=relaisName]").val();
	$("#livraisonform").find("input[name=relaisAddresspl]").val();
	$("#livraisonform").find("input[name=relaisZipcode]").val();
	$("#livraisonform").find("input[name=relaisCity]").val();

	$("#livraisonform").submit();
	return true;
}

//Lancement du spinner d'attente
function launchSpinner(callback)
{
	Box.open({ url: "/nocibe/00_include/04_modal/spinner.jsp?"+paramsGlobal, modal:true, afterShow:callback });
}

//Effacer un Code Avantage
function removeCA(url)
{
	launchSpinner(function(){
		document.location.href=url;
	});
}

// Popup de selection du mode de livraison
function selectShipMode() {
	Box.open({ url: "/nocibe/AjaxSelectShipMode?"+paramsGlobal, modal:true,loading:true });
}

function decouvrePaiement(){
	if($("#cgv").attr('checked') == true && $(".mode_livraison:checked").val() != undefined && $("#boxAdresseLivraison .bold").text().length > 0){
		killPaiement();
	}else{
		init_cachePaiement();
	}
}

function addAddressToAddressBook(addressBookId){
	Box.open({ url: "/nocibe/AjaxAddAddress?"+paramsGlobal+"&AddressBookID="+addressBookId+"&basket=1", modal:true,loading:true });
}

function newsletterForm1(){
	document.location.href = "/nocibe/Newsletter?Email="+ $("#newsletterEmail").val() +"&"+paramsGlobal;
}

function newsletterForm2(){
	document.location.href = "/nocibe/Newsletter?Email="+ $("#newsletterEmailFooter").val() +"&"+paramsGlobal;
}

