$(function() {
	
	$("#champ_recherche").keyup(function() {
		lancerRecherche($(this));
	});
	
	// envoi un mail d'activation
	$("#bloc_confirmation span").click(function() {
		var id = $(this).attr("rel");
		envoyer_mail_activation(id);
	});
	
	$("a[rel]").live("click", function() {
	
		/*$(this).overlay({
			onBeforeLoad: function() {
	    		//quantiteLignePanier(this.getTrigger().attr("id"));
	    		//afficherProduit(this.getTrigger().attr("id"));
	    	},
			effect: 'apple',
			fadeInSpeed: 'slow',
			top: 160,
			left: 'center',
			expose: {
	    		color: '#24120E'
			}
		
		});*/
	
	});
	
});

/*
Cryptage Javascript
*/
function JSdecrypt(c) {
	var r = new String;
	for (var i=0;i<c.length;i+=2) {
		r += String.fromCharCode(((isNaN(c.charAt(i))?c.charCodeAt(i)-87:parseInt(c.charAt(i),10))*16+(isNaN(c.charAt(i+1))?c.charCodeAt(i+1)-87:parseInt(c.charAt(i+1),10)))-2-(i/2)%3);
	}
	return r;
}


/*
Menu accordéon
*/
function initMenus(menu) {
	/*$('.menu div.item').hide();
	$.each($('div.menu'), function(){
		$('#' + this.id + '.expandfirst div:first').show();
	});*/

	if(menu) {
		if($('#menu_' + menu).length > 0) {
			var menu = '#menu_' + menu;
		} else {
			var menu = '#'+ $("#sousmenu_"+menu).parent().parent().attr('id');
		}
		$(menu + ' a').css('color','#342D2A');
		$(menu + ' div.item').show();
		$(menu).css('background','url(images/fond_menu_actif.jpg)');
	}

	/*$('div.menu a.all').mouseover(
		function() {
			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;

			if((!checkElement.is(':visible'))) {
				$('#' + parent + ' div.item:visible').slideUp('slow');
				checkElement.slideDown('slow');
				$('div.menu').css("background","transparent");
				$(this.parentNode).css("background","url(images/fond_menu_actif.jpg)");
				return false;
			}
		}
	);*/
}

/*
Panier
*/
function panierEtape(){
	$("#panier .btn_etape").click(
		function() {
			$.ajax({
				url: "/boutique/getIdClient",
				success: function(client){
					if(client){
						$(location).attr('href','/commande_coordonnees');
					}else{
						loadOverlayConnexion();
						$('#destination').val('/commande_coordonnees');
					}
				}
			});	
		}
	)
}

function ajouterLignePanier() {
	$("div.overlay div.bouton_ajouter").click(
		function() {
			var html;
			var id = $(this).attr('id').split('_')[1];
			var quantite = $('#quantite_' + id).val();

			$.ajax({
				type: "POST",
				data: "id=" + id + "&quantite=" + quantite,
				dataType: "json",
				url: "/boutique/ajouterLignePanier",
				success: function(object){
					$('#produit_overlay div.close').click();

					if($("#panier_" + id).length > 0){
					
						$("#panierqte_" + id).html('X ' + object.lignespanier.type_1[id].quantite);
						
					} else {
					
						$('#detail_panier .vide').hide();
						$('#detail_panier .scrollable').show();
						
						html  = '<div class="produit" style="display:none;">';
						html += '<a href="#" rel="#produit_overlay" id="panier_' + id + '">';
						html += '<div class="photo">';
						html += '<img src="photosproduits/' + object.lignespanier.type_1[id].image + '_60px.jpg" />';
						html += '</div>';
						html += '</a>';
						html += '<div class="detail">';
						html += '<div class="intitule">' + object.lignespanier.type_1[id].descriptioncourt + '</div>';
						html += '<div class="bas">';
						html += '<div class="quantite" id="panierqte_' + id + '">X ' + object.lignespanier.type_1[id].quantite + '</div>';
						html += '<div class="supprimer" id="supprimer_' + id + '"></div>';
						html += '</div>';
						html += '</div>';
						html += '</div>';

						var api = $("div.scrollable").scrollable();
						api.getItemWrap().append(html);
						api.getItemWrap().children().fadeIn('slow');
						api.reload().end();

						supprimerLignePanier("supprimer_" + id);
						loadOverlayProduit("panier_"+ id);
						validerCadeau();
						
					}
				}
			});
		}
	);
}

function modifierLignePanier() {
	$('#panier .quantite input').keyup(
		function() {
			var produit = $(this).attr('id').split('_')[1];
			var quantite = $(this).val();
			$.ajax({
				type: "POST",
				data: "produit=" + produit + "&quantite=" + quantite,
				dataType: "json",
				url: "/boutique/modifierLignePanier",
				success: function(object){
					$('#quantite_' + produit).val(object.quantite);				
					$('#panier_' + produit + ' .tarif').html(object.total);
					$('#tva .tarif').html(object.tva_montant);
					$('#total .tarif').html(object.paniertotal);
					validerCadeau();
				}
			});			
		}
	)
}

function supprimerLignePanier(id) {
	if(!id) {
		element = "#panier div.supprimer";
	} else {
		element = "#" + id;
	}
	
	$(element).click(
		function() {
			var produit = $(this).attr('id').split('_')[1];
			var page = $('body').children('div:first').attr('id');
			
			$.ajax({
				type: "POST",
				data: "produit=" + produit,
				dataType: "json",
				url: "/boutique/supprimerLignePanier",
				success: function(object){
					var parent = $('#panier_' + produit).parent();
					
					if(page == 'panier' && object.statut == 0){
					
						$(location).attr('href','/boutique');
						
					} else {
					
						parent.fadeOut("slow", function () {
							if(page == 'boutique') {
								var api = $("div.scrollable").scrollable();
								var item = api.getClickIndex();
								api.end();
								api.getItems().eq(item).remove();
								api.reload().prev();
								
								if(object.statut == 0){
									$('#detail_panier .vide').show();
									$('#detail_panier .scrollable').hide();
								}
								
							} else if(page == 'panier'){
								parent.remove();
							}
						
							$('#tva .tarif').html(object.tva_montant);
							$('#total .tarif').html(object.paniertotal);
							validerCadeau();
						});
						
					}
				}
			});
		}
	);
}

function quantitePanier(){
	$('#produit_overlay .quantite input').keyup(
		function(){
			$('div.overlay div.bouton_ajouter').unbind('click');
			if(!validQuantite($('#produit_overlay .quantite input').val())) {
				$('#produit_overlay .erreur').show();
			} else {
				$('#produit_overlay .erreur').hide();
				ajouterLignePanier();		
			}
		}
	);
}

function validerCadeau(){

	$.ajax({
		type: "POST",
		dataType: "json",
		url: "/boutique/validerCadeau",
		success: function(object){

			if(object.aMontantcadeauplus.montantcadeauplus == 0){
				var html;
				html  = '<div id="cadeaupanier_' +  object.aPanier.lignespanier.type_6[0].produit + '">';
				html += '<a href="#" rel="#produit_overlay" id="photo_' + object.aPanier.lignespanier.type_6[0].produit + '">';
				html += '<div class="photo">';
				html += '<img src="photosproduits/' + object.aPanier.lignespanier.type_6[0].image + '_60px.jpg" />';
				html += '</div>';
				html += '</a>';
				html += '<div class="detail">';
				html += '<a href="#" rel="#produit_overlay" id="cadeaudetail_' + object.aPanier.lignespanier.type_6[0].produit + '">';
				html += '<div class="intitule">' + object.aPanier.lignespanier.type_6[0].descriptioncourt + '</div>';
				html += '</a>';
				html += '<div class="bas">';
				html += '<div class="quantite">';
				html += object.aPanier.lignespanier.type_6[0].quantite;
				html += '</div>';
				html += '</div>';
				html += '</div>';
				html += '<div class="tarif">';
				html += 'Offert';
				html += '</div>';
				html += '</div>';
				
				$('#panier #cadeau').html(html);
				
				$('#panier .cadeau').hide();
				
				loadOverlayProduit("photo_"+ object.aPanier.lignespanier.type_6[0].produit);
				loadOverlayProduit("cadeaudetail_"+ object.aPanier.lignespanier.type_6[0].produit);
						
			} else {
				
				$('#panier .cadeau #montantcadeauplus').html(object.aMontantcadeauplus.montantcadeauplus);
				$('#panier .cadeau').show();
				$('#panier #cadeau div').remove();
				
			}
			
		}
	});
}

/*
Historique
*/

function ajouterHistorique(id){

	var html;
	var id = id.split('_')[1];

	$.ajax({
		type: "POST",
		data: "id=" + id,
		dataType: "json",
		url: "/boutique/ajouterLigneHistorique",
		success: function(object){
			html  = '<div class="produit" style="display:none;">';
			html += '<a href="#" rel="#produit_overlay" id="historique_' + id + '">';
			html += '<div class="photo">';
			html += '<img src="photosproduits/' + object.ligneshistorique[id].image + '_60px.jpg" />';
			html += '</div>';
			html += '<div class="detail">';
			html += '<div class="intitule">' + object.ligneshistorique[id].descriptioncourt + '</div>';
			html += '</div>';
			html += '</a>';
			html += '</div>';

			$('#detail_historique').prepend(html);
			$('#detail_historique').children().fadeIn('slow');

			loadOverlayProduit("historique_" + id);
		}
	});
}

function supprimerHistorique(){
	var produit = $('#detail_historique .produit:last').children().attr('id').split('_')[1];

	$.ajax({
		type: "POST",
		data: "produit=" + produit,
		async: false,
		url: "/boutique/supprimerLigneHistorique",
		success: function(){
			$('#detail_historique .produit:last').remove();
		}
	});
}

/*
Produit
*/

function slideProduit() {
	$("div.overlay div.bouton_infos").click(
		function() {

			for(var x = 0; x < this.childNodes.length; x++) {
				if(this.childNodes[x].nodeName == "DIV") {
					var fond = $(this.childNodes[x]);
					break;
				}
			}

			var parent =  $(this.parentNode.parentNode);

			if(fond.hasClass('fond_plus')) {
				fond.removeClass('fond_plus');
				fond.addClass('fond_moins');
				parent.animate({"left": "-=230px"}, "slow");
			} else if(fond.hasClass('fond_moins')) {
				fond.removeClass('fond_moins');
				fond.addClass('fond_plus');
				parent.animate({"left": "+=230px"}, "slow");
			}
		}
	);
}

function afficherProduit(id) {

	var id = id.split('_')[1];
	var html = '';
	var active = 'active';
	
	$.ajax({
		type: "POST",
		data: "id=" + id,
		dataType: "json",
		url: "/boutique/getDetailProduit",
		success: function(json){
			//$('#produit_overlay .photo').css('background-image', 'url(photosproduits/' + json.images[1].nom + '_450px.jpg)');
			for (i in json.images)
			{
				html += '<img src="photosproduits/' + json.images[i].nom + '_450px.jpg" class="' + active + '" />\n\r';
				active = '';
			}
			
			$('#produit_overlay .photo').html(html);
			
			
			$('#produit_overlay .intitule').html(json.descriptioncourt);
			
			if(json.slogan) {
				$('#produit_overlay .slogan').css('margin', '10px');
				$('#produit_overlay .slogan').html(json.slogan);
			} else {
				$('#produit_overlay .slogan').css('margin', '0px');	
			}
			
			var description = json.descriptioncommerciale;
			
			if(json.descriptiontechnique){
				description += '<br />' + json.descriptiontechnique; 			
			}
			
			if(json.etiquettes){
				var etiquettes = '';
				var etiquettes_details = '';
			
				for (i in json.etiquettes)
				{
					
					etiquettes += '<img src="images/' + json.etiquettes[i].image + '_60.jpg" alt="' + json.etiquettes[i].nom + '"  />\n\r';
					etiquettes_details += '<div><img src="images/' + json.etiquettes[i].image + '_60.jpg" alt="' + json.etiquettes[i].nom + '" />' + json.etiquettes[i].description + '</div>\n\r'
				}
				
				$('#produit_overlay .description div.etiquettes').html(etiquettes);
				$('#produit_overlay .infos div.etiquettes').html(etiquettes_details);			
			}

			if(json.allergenes){
				$('#produit_overlay div.allergenes').html('<strong>Allerg&egrave;nes :</strong><br /><br />' + json.allergenes);		
			}
			
			if(json.ingredients){
				$('#produit_overlay div.ingredients').html('<strong>Ingr&eacute;dients :</strong><br /><br />' + json.ingredients);		
			}			
			
			$('#produit_overlay .descriptif').html(description);
			
			$('#produit_overlay .prix').html(json.prixmin);
			if(json.poids){
				$('#produit_overlay .tarif .info').html('soit ' + json.tarifpoids + ' &#8364; les 100 g');
				$('#produit_overlay .poids').html(json.poids + ' g');
			}
			//$('#produit_overlay .infos').html('Ingr&eacute;dients :<br />' + json.ingredients + '<br /><br />Allerg&egrave;nes :<br />' + json.allergenes);
			$('#produit_overlay .quantite input').attr('id', 'quantite_' + json.id);
			$('#produit_overlay div.bouton_ajouter').attr('id', 'ajouter_' + json.id);
			$('#produit_overlay div.commentaire').html(json.envente_commentaire);
			
			if(json.envente == 0){
				$('#produit_overlay .panier').hide();
				$('#produit_overlay .commentaire').show();
			} else {
				$('#produit_overlay .commentaire').hide();
				$('#produit_overlay .panier').show();			
			}
		}
	});
}

function quantiteLignePanier(id) {

	var produit = id.split('_')[1];
	$.ajax({
		type: "POST",
		data: "produit=" + produit,
		url: "/boutique/quantiteLignePanier",
		success: function(quantite){
			if(!quantite)
				var quantite = 1;
			$('#produit_overlay .quantite input').attr('value', quantite);
		}
	});		
}

function loadOverlayProduit(id) {

	if(!id) {
		element = "a[rel]";
	} else {
		element = "#" + id;
	}

    $(element).overlay({
    	onBeforeLoad: function(event) {
    		quantiteLignePanier(this.getTrigger().attr("id"));
    		afficherProduit(this.getTrigger().attr("id"));
    	},
		effect: 'apple',
		fadeInSpeed: 'slow',
		top: 160,
		left: 'center',
		expose: {
    		color: '#24120E'
		},
		onClose: function(event){
			$('div.animate').css("left","450px");
			if($('#produit_overlay div.bouton_infos div').hasClass('fond_moins')) {
				$('#produit_overlay div.bouton_infos div').removeClass('fond_moins');
				$('#produit_overlay div.bouton_infos div').addClass('fond_plus');
			}
			var id = this.getTrigger().attr('id');
			if(id.split('_')[0] == "produit" || id.split('_')[0] == "recherche" && $('#historique_' + id.split('_')[1]).length == 0) {
				if($('#detail_historique .produit').length > 4) {
					supprimerHistorique();
				}
				ajouterHistorique(id);
			}
		}
	});
}

function loadScrollable() {
    $("div.scrollable").scrollable({
    	items: '#produit',
    	size: 4,
    	clickable: true,
    	keyboard: false
	});
}

function slidePhoto() {
	setInterval(
		function() {
    		var active = $('#produit_overlay .detail .photo img.active');
    		
    		if($('#produit_overlay .detail .photo img').length > 1) {
    			if (active.length == 0) active = $('#produit_overlay .detail .photo img:last');
    			var next =  active.next().length ? active.next() : $('#produit_overlay .detail .photo img:first');
    			active.addClass('last-active');

    			next.css({opacity: 0.0})
        			.addClass('active')
        			.animate({opacity: 1.0}, 1000, function() {
            			active.removeClass('active last-active');
        			});
        	}
		}, 4000);
}

/*
Adresse
*/
function getAdresse(id){
	if(id){
		var id = id.split('_')[2];
		$.ajax({
			type: "POST",
			data: "id=" + id,
			dataType: "json",
			url: "/boutique/getDetailAdresse",
			success: function(object){
				$("#overlay_id").val(object.id);
				$("#overlay_civilite option[value=" + object.civilite + "]").attr("selected", "selected");
				$("#overlay_nom").val(object.nom);
				$("#overlay_prenom").val(object.prenom);
				$("#overlay_societe").val(object.societe);
				$("#overlay_adresse1").val(object.adresse1);
				$("#overlay_adresse2").val(object.adresse2);
				$("#overlay_codepostal").val(object.codepostal);
				$("#overlay_ville").val(object.ville);
				$("#overlay_tel").val(object.tel);
				$("#overlay_email").val(object.email);
				$("#overlay_naissance").val(object.naissance.split('-')[2] +"/"+ object.naissance.split('-')[1] +"/"+ object.naissance.split('-')[0]);
			}
		});
	} else {
		$("#overlay_id").val("");
		$("#overlay_nom").val("");
		$("#overlay_prenom").val("");
		$("#overlay_societe").val("");
		$("#overlay_adresse1").val("");
		$("#overlay_adresse2").val("");
		$("#overlay_codepostal").val("");
		$("#overlay_ville").val("");
		$("#overlay_tel").val("");
		$("#overlay_email").val("");
		$("#overlay_naissance").val("");
	}
}

function ajouterAdresse(){
	$("#adresse_overlay div.btn_ajouter").click(
		function() {
			$('#adresse_overlay .bulle').hide();
		
			var civilite = $("#overlay_civilite").val();
			var nom = $("#overlay_nom").val();
			var prenom = $("#overlay_prenom").val();
			var societe = $("#overlay_societe").val();
			var adresse1 = $("#overlay_adresse1").val();
			var adresse2 = $("#overlay_adresse2").val();
			var codepostal = $("#overlay_codepostal").val();
			var ville = $("#overlay_ville").val();
			var tel = $("#overlay_tel").val();
			var email = $("#overlay_email").val();
			var naissance = $("#overlay_naissance").val();
			var type = $("#overlay_type").val();
			
			var display;
			
			var input = new Array('nom', 'prenom', 'adresse1', 'codepostal', 'ville', 'tel', 'email', 'naissance');
			var value = new Array(nom, prenom, adresse1, codepostal, ville, tel, email, naissance);
			var error = '';
				
			$(input).each(
				function(i){
					if((value[i] == '' && input[i] != 'naissance') || ((input[i] == 'codepostal' && !validCodePostal(value[i])) || (input[i] == 'tel' && !validTelephone(value[i])) || (input[i] == 'email' && !validEmail(value[i])) || (value[i] != '' && input[i] == 'naissance' && !validDate(value[i])))) {
						$('#adresse_overlay #bulle_' + input[i]).show();
						error = 'erreur';
					}
				}
			);
			
			if(error != 'erreur') {
			
				$.ajax({
					type: "POST",
					data: "civilite=" + civilite + "&nom=" + nom + "&prenom=" + prenom + "&societe=" + societe + "&adresse1=" + adresse1 + "&adresse2=" + adresse2 + "&codepostal=" + codepostal + "&ville=" + ville + "&tel=" + tel + "&email=" + email + "&naissance=" + naissance + "&type=" + type,
					url: "/boutique/ajouterAdresse",
					success: function(id){
					
						if(societe){
							display = 'block';
						} else {
							display = 'none';
						}
						
						html  = '<div  id="adresse_fac_' + id + '" class="adresse">';
						html += '<div>';
						html += '<div class="container">';
						html += '<div class="content">';
						html += '<div class="coche">';
						html += '<div id="coche_fac_' + id + '"></div>';
						html += '</div>';
						html += '<div class="detail">';
						html += '<div id="societe_fac_' + id + '" style="display:' + display + '">';
						html += '<span class="societe">' + societe + '</span><br />';
						html += '</div>';						
						html += '<span class="civilite">' + civilite + '</span> <span class="nom">' + nom + '</span> <span class="prenom">' + prenom + '</span><br />';
						html += '<span class="adresse1">' + adresse1 + '</span><br />';
						html += '<span class="adresse2">' + adresse2 + '</span><br />';
						html += '<span class="codepostal">' + codepostal + '</span> <span class="ville">' + ville + '</span>';
						html += '</div>';
						html += '</div>';
						html += '</div>';
						html += '</div>';
						html += '<div class="btn">';														
						html += '<a href="#" rel="#adresse_overlay" id="modifier_fac_' + id + '"><div class="btn_modifier"></div></a>';
						html += '<div id="supprimer_fac_' + id + '" class="btn_supprimer"></div>';
						html += '</div>';						
						html += '</div>';
					
						$(".liste_adresses div.fac").append(html);
						modifierAdresseType("#adresse_fac_" + id);
						loadOverlayAdresse("#modifier_fac_" + id);
						supprimerAdresse("#supprimer_fac_" + id);					
					
						if($('.liste_adresses div.liv').length > 0){
						
							html  = '<div  id="adresse_liv_' + id + '" class="adresse">';
							html += '<div>';
							html += '<div class="container">';
							html += '<div class="content">';
							html += '<div class="coche">';
							html += '<div id="coche_liv_' + id + '"></div>';
							html += '</div>';					
							html += '<div class="detail">';
							html += '<div id="societe_liv_' + id + '" style="display:' + display + '">';
							html += '<span class="societe">' + societe + '</span><br />';
							html += '</div>';							
							html += '<span class="civilite">' + civilite + '</span> <span class="nom">' + nom + '</span> <span class="prenom">' + prenom + '</span><br />';
							html += '<span class="adresse1">' + adresse1 + '</span><br />';
							html += '<span class="adresse2">' + adresse2 + '</span><br />';
							html += '<span class="codepostal">' + codepostal + '</span> <span class="ville">' + ville + '</span>';
							html += '</div>';
							html += '</div>';
							html += '</div>';
							html += '</div>';
							html += '<div class="btn">';													
							html += '<a href="#" rel="#adresse_overlay" id="modifier_liv_' + id + '"><div class="btn_modifier"></div></a>';
							html += '<div id="supprimer_liv_' + id + '" class="btn_supprimer"></div>';
							html += '</div>';
							html += '</div>';
						
							$(".liste_adresses div.liv").append(html);
							modifierAdresseType("#adresse_liv_" + id);
							loadOverlayAdresse("#modifier_liv_" + id);
							supprimerAdresse("#supprimer_liv_" + id);											
					
						}
														
						$("." + type + " .adresse").children().removeClass("select");
						
						if($('.liste_adresses div.fac').children('div').length == 1 && $('.liste_adresses div.liv').children('div').length == 1){
							$("#adresse_fac_" + id).children('div:first').addClass("select");
							$("#adresse_liv_" + id).children('div:first').addClass("select");
						} else {
							$("#adresse_" + type + "_" + id).children('div:first').addClass("select");
						}
						
						$("#adresse_overlay div.close").click();
						$("#navigation_bas .btn_etape").css('display', 'block');
						$("#adresse_overlay div.btn_ajouter").unbind('click');	
					}
				});
			}	
		}
	);
}

function modifierAdresse(){
	$("#adresse_overlay div.btn_valider").click(
		function() {
			$('#adresse_overlay .bulle').hide();
		
			var id = $("#overlay_id").val();
			var civilite = $("#overlay_civilite").val();
			var nom = $("#overlay_nom").val();
			var prenom = $("#overlay_prenom").val();
			var societe = $("#overlay_societe").val();
			var adresse1 = $("#overlay_adresse1").val();
			var adresse2 = $("#overlay_adresse2").val();
			var codepostal = $("#overlay_codepostal").val();
			var ville = $("#overlay_ville").val();
			var tel = $("#overlay_tel").val();
			var email = $("#overlay_email").val();
			var naissance = $("#overlay_naissance").val();
			var type = $("#overlay_type").val();
			
			var input = new Array('nom', 'prenom', 'adresse1', 'codepostal', 'ville', 'tel', 'email', 'naissance');
			var value = new Array(nom, prenom, adresse1, codepostal, ville, tel, email, naissance);
			var error = '';
				
			$(input).each(
				function(i){
					if((value[i] == '' && input[i] != 'naissance') || ((input[i] == 'codepostal' && !validCodePostal(value[i])) || (input[i] == 'tel' && !validTelephone(value[i])) || (input[i] == 'email' && !validEmail(value[i])) || (value[i] != '' && input[i] == 'naissance' && !validDate(value[i])))) {
						$('#adresse_overlay #bulle_' + input[i]).show();
						error = 'erreur';
					}
				}
			);
			
			if(error != 'erreur') {
						
				$.ajax({
					type: "POST",
					data: "id=" + id + "&civilite=" + civilite + "&nom=" + nom + "&prenom=" + prenom + "&societe=" + societe + "&adresse1=" + adresse1 + "&adresse2=" + adresse2 + "&codepostal=" + codepostal + "&ville=" + ville + "&tel=" + tel + "&email=" + email + "&naissance=" + naissance,
					url: "/boutique/modifierAdresse",
					success: function(){
					
						if(societe){
							$("#adresse_fac_" + id + " .societe").text(societe);
							$("#societe_fac_" + id).show();
						}else{
							$("#societe_fac_" + id).hide();
						}
						
						$("#adresse_fac_" + id + " .civilite").text(civilite);
						$("#adresse_fac_" + id + " .nom").text(nom);
						$("#adresse_fac_" + id + " .prenom").text(prenom);
						$("#adresse_fac_" + id + " .adresse1").text(adresse1);
						$("#adresse_fac_" + id + " .adresse2").text(adresse2);
						$("#adresse_fac_" + id + " .codepostal").text(codepostal);
						$("#adresse_fac_" + id + " .ville").text(ville);
					
						if($('.liste_adresses div.liv').length > 0){
						
							if(societe){
								$("#adresse_liv_" + id + " .societe").text(societe);
								$("#societe_liv_" + id).show();
							}else{
								$("#societe_liv_" + id).hide();
							}
														
							$("#adresse_liv_" + id + " .civilite").text(civilite);
							$("#adresse_liv_" + id + " .nom").text(nom);
							$("#adresse_liv_" + id + " .prenom").text(prenom);
							$("#adresse_liv_" + id + " .adresse1").text(adresse1);
							$("#adresse_liv_" + id + " .adresse2").text(adresse2);
							$("#adresse_liv_" + id + " .codepostal").text(codepostal);
							$("#adresse_liv_" + id + " .ville").text(ville);
						}
					
						$("#adresse_overlay div.close").click();
						$("#adresse_overlay div.btn_valider").unbind('click');
					}
				});
			}
		}
	);
}

function modifierAdresseType(id){
	if(id){
		element = id;
	}else{
		element = ".adresse";
	}
	$(element + " .coche").click(
		function() {
			var type = $(this).parents('.liste_adresses').children('div:first').attr('class');
			var id = $(this).parents('.adresse').attr('id').split('_')[2];

			$.ajax({
				type: "POST",
				data: "id=" + id + "&type=" + type,
				url: "/boutique/adresseClient",
				success: function(){
					if(type == 'fac'){
						$(".fac .adresse").children().removeClass("select");
					} else {
						$(".liv .adresse").children().removeClass("select");				
					}

					$("#adresse_" + type + "_" + id).children().addClass("select");
				}
			});
		}
	);
}

function supprimerAdresse(id){
	if(id){
		element = id;
	}else{
		element = ".btn_supprimer";
	}
	
	$(element).click(
		function() {
			var id = $(this).attr('id').split('_')[2];
			var type = $(this).attr('id').split('_')[1];
			
			$.ajax({
				type: "POST",
				data: "id=" + id,
				url: "/boutique/supprimerAdresse",
				success: function(nb){
					if($("#adresse_fac_" + id).children().hasClass("select")){
						$("#adresse_fac_" + id).remove();
						$('.fac .adresse').children('div:first').addClass("select");
					} else {
						$("#adresse_fac_" + id).remove();
					}
					
					if($('.liste_adresses div.liv').length > 0){
						if($("#adresse_liv_" + id).children().hasClass("select")){
							$("#adresse_liv_" + id).remove();
							$('.liv .adresse').children('div:first').addClass("select");
						} else {
							$("#adresse_liv_" + id).remove();
						}					
						
					}
					
					if(nb == 0){
						$("#navigation_bas .btn_etape").css('display', 'none');
					}
				}
			});	
		}
	)
}

function loadOverlayAdresse(id){
	if(id){
		element = id + "[rel]";
	}else{
		element = "a[rel]";
	}
    $(element).overlay({
    	onBeforeLoad: function(event) {
    		getAdresse(this.getTrigger().attr('id'));
    		if(this.getTrigger().children().hasClass('btn_modifier')) { 
    			$('#overlay_type').attr('value', this.getTrigger().parents('.liste_adresses').children('div:first').attr('class')); 		
    			$('#adresse_overlay .header div').removeClass('titre_nouveau');
    			$('#adresse_overlay .header div').addClass('titre_modifier');
    			$('#adresse_overlay .footer div').removeClass('btn_ajouter');
    			$('#adresse_overlay .footer div').addClass('btn_valider'); 
    			modifierAdresse();	
    		} else if (this.getTrigger().children().hasClass('btn_ajouter')) {
    			$('#overlay_type').attr('value', this.getTrigger().prev('.liste_adresses').children('div:first').attr('class')); 
    			$('#adresse_overlay .header div').removeClass('titre_modifier');
    			$('#adresse_overlay .header div').addClass('titre_nouveau');
    			$('#adresse_overlay .footer div').removeClass('btn_valider');
    			$('#adresse_overlay .footer div').addClass('btn_ajouter');  
    			ajouterAdresse();			
    		}
    	},
		effect: 'apple',
		fadeInSpeed: 'slow',
		top: 160,
		left: 'center',
		expose: {
    		color: '#24120E'
		}
	});
}

/*
Connexion
*/

function navigationCompte(){
	$(".nav_compte").click(
		function() {
			$.ajax({
				url: "/boutique/getIdClient",
				success: function(client){
					if(client){
						$(location).attr('href','/compte');
					}else{
						loadOverlayConnexion();
					}
				}
			});	
		}
	)
}

function Deconnexion(){
	$("#navigation #deconnexion").click(
		function() {
			$.ajax({
				type: "POST",
				url: "/boutique/deconnexionCompte",
				success: function(){					
					$(location).attr('href','/');
				}
			});
		}
	);
}

function loadOverlayConnexion(){
    $("#connexion_overlay").overlay({
    	onBeforeLoad: function(event) {
    		$('#connexion_overlay .bulle').hide();
			$('#connexion_overlay #forget').hide();
			$('#connexion_overlay #send').hide();
			$('#connexion_overlay .btn_poursuivre').show();
		    $('#connexion_overlay #connect').show();	
    	},    
		effect: 'apple',
		fadeInSpeed: 'slow',
		top: 160,
		left: 'center',
		expose: {
    		color: '#24120E'
		},
		api: true
	}).load();
}

function connexionCompte(){
	$("#connexion_overlay .btn_poursuivre").click(
		function() {
			$('#connexion_overlay .bulle').hide();
			$('#connexion_overlay #bulle_email').html('Indiquez un email valide !');
			
			var destination = "";
			
			if ($("#destination").length > 0) {
				destination = $("#destination").val();
			}
				
			var email = $("#overlay_email").val();
			var password = $("#overlay_password").val();
			var nom = $("#overlay_nom").val();
			var prenom = $("#overlay_prenom").val();
			var naissance = $("#overlay_naissance").val();				
				
			var input = new Array('email', 'password');
			var value = new Array(email, password);
			var error = '';
				
			$(input).each(
				function(i){
					if((value[i] == '' && input[i] != 'naissance') || (input[i] == 'email' && !validEmail(value[i]))) {
						$('#connexion_overlay #bulle_' + input[i]).show();
						error = 'erreur';
					}
				}
			);
				
			if(error != 'erreur') {				
				$.ajax({
					type: "POST",
					data: "email=" + email + "&password=" + password,
					url: "/boutique/connexionCompte",
					success: function(client){

						if(client) {
						
							if(client == 'confirm') {
								$.ajax({
									type: "POST",
									async: false,
									data: "email=" + email + "&password=" + password + "&nom=" + nom + "&prenom=" + prenom + "&naissance=" + naissance,
									url: "/boutique/creationCompte"
								});
							}
							
							if(destination == '/commande_coordonnees') {
								$(location).attr('href','/commande_coordonnees');
							} else {
								$(location).attr('href','/compte');				
							}
	
						} else {
							
							if($("#btn_client").hasClass('btn_new_client')) {
								$("#new_connexion").show();
								$("#btn_client").removeClass('btn_new_client');
								$("#btn_client").addClass('btn_client');
								$("#texte").css("display","none");
								$("#texte_new").css("display","block");
								$("#connexion_overlay .password").css("display","none");
								$("#connexion_overlay .detail").animate({"height": "+=140px"}, "slow");
								$("#connexion_overlay #connect.middle").animate({"height": "+=140px"}, "slow");
								
								$("#connexion_overlay .btn_poursuivre").unbind('click');
								inscriptionCompte();
							} 
						}
					}
				});
			}
				
		}
	);
}		

function inscriptionCompte(){
	$("#connexion_overlay .btn_poursuivre").click(
		function() {
		
			$('#connexion_overlay .bulle').hide();
			$('#connexion_overlay #bulle_email').html('Indiquez un email valide !');
			
			var destination = $("#destination").val();
			
			var email = $("#overlay_email").val();
			var password = $("#overlay_password").val();
			var nom = $("#overlay_nom").val();
			var prenom = $("#overlay_prenom").val();
			var naissance = $("#overlay_naissance").val();
				
			var input = new Array('email', 'password', 'nom', 'prenom', 'naissance');
			var value = new Array(email, password, nom, prenom, naissance);
			var error = '';
				
			$(input).each(
				function(i){
					if((value[i] == '' && input[i] != 'naissance') || (input[i] == 'email' && !validEmail(value[i])) || (value[i] != '' && input[i] == 'naissance' && !validDate(value[i]))) {
						$('#connexion_overlay #bulle_' + input[i]).show();
						error = 'erreur';
					}
				}
			);
				
			if(existEmail(email)){
				$('#connexion_overlay #bulle_email').html('Cet email est d&eacute;j&agrave; utilis&eacute; !').show();
				error = 'erreur';
			}

			if(error != 'erreur') {
				$.ajax({
					type: "POST",
					data: "email=" + email + "&password=" + password + "&nom=" + nom + "&prenom=" + prenom + "&naissance=" + naissance,
					url: "/boutique/creationCompte",
					success: function(client){
						if(client != 'confirmation' && client != "exist") {
							if(destination == 'commande_coordonnees') {
								$(location).attr('href','/commande_coordonnees');
							} else {
								$(location).attr('href','/compte');							
							}							
						} else if(client == 'confirmation' && client != "exist"){
							$(location).attr('href','/compte_confirmation');
						}
					}
				});
				
				if($('#overlay_newsletter').is(':checked')){
					ajouterNewsletter(email,'inscription');
				}
			}
		}
	);
}

function passwordCompte(){
	$("#connexion_overlay .btn_poursuivre").click(
		function(){
			$('#connexion_overlay .bulle').hide();
			$('#connexion_overlay #bulle_email_password').html('Indiquez un email valide !');

			var email_password = $("#overlay_email_password").val();
				
			var input = new Array('email_password');
			var value = new Array(email_password);
			var error = '';
				
			$(input).each(
				function(i){
					if(value[i] == '' || !validEmail(value[i])) {
						$('#connexion_overlay #bulle_' + input[i]).show();
						error = 'erreur';
					}
				}
			);
			
			if(error != 'erreur') {				
				$.ajax({
					type: "POST",
					data: "email=" + email_password,
					url: "/boutique/sendPassword",
					success: function(send){
						if(send){
							$('#connexion_overlay #send .texte').html('Votre mot de passe a &eacute;t&eacute; envoy&eacute; avec succ&egrave;s.');
							$('#connexion_overlay #forget').hide();
							$('#connexion_overlay #send').show();
							$("#connexion_overlay .btn_poursuivre").unbind('click');
							$('#connexion_overlay .btn_poursuivre').hide();			
						connexionCompte();	
						} else {
							$('#connexion_overlay #forget .texte').html('<span style="color:#FF0000">Aucun compte ne correspond &agrave; cet email.</span>');
						}

					}
				});
			}				
		}
	);	
}


function passwordConnexion(){
	$("#connexion_overlay .password").click(
		function() {
			$("#connexion_overlay #connect").hide();
			$("#connexion_overlay #forget").show();
			$("#connexion_overlay .btn_poursuivre").unbind('click');
			passwordCompte();
		}
	);
}

function slideConnexion(){
	$("#btn_client").click(
		function() {
			
			$('#connexion_overlay .bulle').hide();
			$("#connexion_overlay #forget").hide();
			$("#connexion_overlay #send").hide();
			$("#connexion_overlay .btn_poursuivre").show();	
					
			if($("#btn_client").hasClass('btn_new_client')) {
				$('#new_connexion').show();
				$("#btn_client").removeClass('btn_new_client');
				$("#btn_client").addClass('btn_client');
				$("#texte").css("display","none");
				$("#texte_new").css("display","block");
				$("#connexion_overlay .password").css("display","none");
				$("#connexion_overlay .detail").animate({"height": "+=140px"}, "slow");
				$("#connexion_overlay #connect.middle").animate({"height": "+=140px"}, "slow");

				$("#connexion_overlay .btn_poursuivre").unbind('click');	
				inscriptionCompte();			
			} else {
				$('#new_connexion').hide();
				$("#btn_client").removeClass('btn_client');
				$("#btn_client").addClass('btn_new_client');
				$("#texte").css("display","block");
				$("#texte_new").css("display","none");
				$("#connexion_overlay .password").css("display","block");
				$("#connexion_overlay .detail").animate({"height": "-=140px"}, "slow");
				$("#connexion_overlay #connect.middle").animate({"height": "-=140px"}, "slow");

				$("#connexion_overlay .btn_poursuivre").unbind('click');	
				connexionCompte();				
			}
		}
	);
}

/*
Coordonnees
*/

function validerCoordonnees(){
	$("#coordonnees .btn_valider").click(
		function() {
			$('#coordonnees .bulle').hide();
			$('#coordonnees #bulle_email').html('Indiquez un email valide !');
		
			var nom = $("#client_nom").val();
			var prenom = $("#client_prenom").val();
			var naissance = $("#client_naissance").val();
			var email = $("#client_email").val();
			var password = $("#client_password").val();
			var newsletter = $("#client_newsletter").val();
			
			var input = new Array('email', 'password', 'nom', 'prenom', 'naissance');
			var value = new Array(email, password, nom, prenom, naissance);
			var error = '';
				
			$(input).each(
				function(i){
					if((value[i] == '' && input[i] != 'naissance') || (input[i] == 'email' && !validEmail(value[i])) || (value[i] != '' && input[i] == 'naissance' && !validDate(value[i]))) {
						$('#coordonnees #bulle_' + input[i]).show();
						error = 'erreur';
					}
				}
			);
			
			if(existEmail(email)){
				$('#coordonnees #bulle_email').html('Cet email est d&eacute;j&agrave; utilis&eacute; !').show();
				error = 'erreur';
			}			
			
			if(error != 'erreur') {						
				$.ajax({
					type: "POST",
					data: "nom=" + nom + "&prenom=" + prenom + "&naissance=" + naissance + "&email=" + email + "&password=" + password + "&newsletter=" + newsletter,
					url: "/boutique/updateClient"
				});
			}
		}
	);
}

function coordonneesEtape(){
	$("#coordonnees .btn_etape").click(
		function() {
			$.ajax({
				dataType: "json",
				url: "/boutique/getAdresseClient",
				success: function(object){
					if(object.fac && object.liv){
						$(location).attr('href','/commande_recapitulatif');
					} else {
						if(!object.fac && object.liv){
							$('#bulle_adresse').html('Sélectionner une adresse de facturation !');
						} else if(object.fac && !object.liv){
							$('#bulle_adresse').html('Sélectionner une adresse de livraison !');
						} else if(!object.liv && !object.fac){
							$('#bulle_adresse').html('Sélectionner une adresse de facturation et une de livraison !');
						}
						$('#bulle_adresse').show();
					}
				}
			});	
		}
	)
}

/*
Commande
*/
function commandeValider(){
	$("#recapitulatif .valider_ma_commande").click(	
		function() {
			var error = '';
			$('#bulle_paiement').hide();
			
			if($('input[type=radio][name=paiement]:checked').length != 1){
				error = 'erreur';
				$('#bulle_paiement').show();			
			}
		
			if(!$('#cgv').attr('checked')){
				error = 'erreur';
				$('#bulle_cgv').show();
			}

			if(error != 'erreur') {
				if($('input[type=radio][name=paiement]:checked').val() == 'cheque'){
					$.ajax({
						url: "/boutique/validerCommande",
						success: function(commande){
							if(commande){
								$(location).attr('href','/commande_confirmation');
							}
						}
					});
				} else if($('input[type=radio][name=paiement]:checked').val() == 'carte'){
					$(location).attr('href','/call_request');
				}
			}
		}
	)
}

/*
CGV
*/

function loadOverlayCgv() {
	$(".cgv[rel]").overlay({
		effect: 'apple',
		top: 160,
		left: 'center',
		expose: {
    		color: '#24120E'
		}
    });
}

/*
Association
*/

function loadOverlayAssociation() {
	$(".association[rel]").overlay({
		effect: 'apple',
		top: 160,
		left: 'center',
		expose: {
    		color: '#24120E'
		}
    });
}

/*
Input File
*/
function loadInputFile(){
	$("input[type=file]").filestyle({
		image: "images/bouton_choisir.png",
		imageheight: 29,
		imagewidth: 76,
		width: 100
	});
}

/*
Inscription newsletter
*/
function inscriptionNewsletter(){
	$('#entete .newsletter .btn_ok').click(	
		function() {
			var email =$('#newsletter_email').val();
			if(!validEmail(email)){
				//alert('Email invalide');
			} else {
				ajouterNewsletter(email,'entete');
			}
		}
	);
}


function ajouterNewsletter(email, source){
	var email = email;
	$.ajax({
		type: "POST",
		data: "email=" + email,
		url: "/newsletter/ajouterNewsletter",
		success: function(id){
			if(source == 'entete'){
				if(id){
					$('#entete .newsletter').html('<div class="intitule">Inscription r&eacute;ussie.</div>');
				} else {
					$('#entete .newsletter ').html('<div class="intitule">Vous &ecirc;tes d&eacute;j&agrave; inscrit &agrave; la newsletter.</div>');				
				}
			}
		}
	});
};

/*
Vérification formulaire
*/

function validQuantite(quantite){
	return quantite.match(/^[1-9][0-9]*$/);
}

function validEmail(email){
	return email.match(/[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+[.]+[a-zA-Z]+/);
}

function validDate(date){
	return date.match(/^[0-9]{1,2}\/[01]?[0-9]\/[0-9]{4}$/);
}

function validCodePostal(codepostal){
	return codepostal.match(/^([0-9]{5})$/);
}

function validTelephone(telephone){
	return telephone.match(/^0[1-9]([\.\-\ ]?[0-9]{2}){4}$/);
}

function existEmail(email){

	return $.ajax({
		type: "POST",
		data: "email=" + email,
		url: "boutique/emailClient",
		async: false
	}).responseText;

}

/*
Moteur de recherche
*/
function lancerRecherche(object) {

	var recherche = object.val();
	
	//au bout de 3 caractères tapés, on commence la recherche
	if (recherche.length >= 3) {
		
		$.ajax({
			type: "POST",
			url: "/boutique/rechercherProduit",
			data: "recherche=" + recherche,
			dataType: "json",
			success: function(object) {

				var html;
				
				$("#produits_recherche").html('');
				
				// on parcourt les résultats
				$.each(object, function() {		
					
					html = '';
					html += '<a id="recherche_' + this.id + '" rel="#produit_overlay" href="#">';
					html +=		'<div>';
					html +=			'<div class="container">';
					html +=				'<div class="image"><img alt="' + this.image + '" src="/photosproduits/' + this.image + '_233px.jpg" /></div>';
					html +=				'<div class="logo"><div>';				

					$.each(this.etiquettes, function() {	
						html +=				'<img alt="' + this.nom + '" src="/images/' + this.image + '_40.jpg">';	
					});
					
					html +=				'</div></div>';
					html +=				'<div class="etiquette">';
					html +=					'<div>';
					html +=						'<span class="intitule">' + this.descriptioncourt + '</span>';
					html +=						'<span class="prix">' + this.prixmin +'</span>';
					html +=					'</div>';
					html +=				'</div>';
					html +=			'</div>';
					html +=		'</div>';
					html += '</a>';
					
					$("#produits_recherche").append(html);

					loadOverlayProduit("recherche_" + this.id);
				});
				
				
				if ($("#produits_recherche").html() == "") {
					$("#produits_recherche").html('<div id="aucun_resultat_recherche">Aucun résultat ne correspond à votre recherche.</div>');
				}
				
				var produits_page = $("#produit").html();
				$("#produits_page").hide();
				
			}
				
		});
		
	}
	else {
		$("#produits_page").show();
		$("#produits_recherche").html("");
	}
	
}

function envoyer_mail_activation(id) {

	$.ajax({
		type: "POST",
		data: "id=" + id,
		url: "/boutique/envoyerMailActivation",
		success: function(response){
		
			if (response == "send") {
				$("#bloc_confirmation").html("Un email d'activation de votre compte vous a été envoyé à l'adresse indiquée.");
			}
		
		}
			
	});

}
