// http://docs.jquery.com/Using_jQuery_with_Other_Libraries

/*------------------------------------------- CART OVERLAYER -------------------------------------------*/
// Overlayer de suppression de tous les articles du panier
//var cartOverlayer = function() {
//	jQuery('.choice .button').click(function(e) {
//		jQuery('#allgrey, #emptyCart').css('display', 'none');
//	});
//	jQuery('.choice .png_bg').click(function(e) {
//		jQuery('#cart').addClass('open');
//	});
//};

/*------------------------------------------- CUSTOMER AREA -------------------------------------------*/
// Validation javascript des champs du formulaire formIdentification

// TVA: En commentaire à cause du nouvel header
// var CustomerArea = Class.create({
// initialize: function() {
// this.initCustomerAreaForm();
// this.initCustomerAreaFormSubmit();
// },
//	
// initCustomerAreaForm: function() {
// $("customer").observe(Tapestry.ZONE_UPDATED_EVENT, function() {
// this.initCustomerAreaFormSubmit();
// }.bind(this));
// },
//	
// initCustomerAreaFormSubmit: function() {
// if($$("form[id^=formIdentification]").first()){
// $$("form[id^=formIdentification]").first().observe(Tapestry.FORM_VALIDATE_EVENT,
// function(event) {
// var formElt = Event.element(event);
// if(!checkLogin()) {
// // soumission du formulaire non propagee a tapestry
// $T(formElt).validationError = true;
// } else {
// // désactivation du bouton submit pour empecher une nouvelle soumission
// $("formIdentificationSubmit").disabled = "disabled";
// }
// });
// }
// }
// });
// Tapestry.Initializer.customerarea = function(){ var customerarea = new
// CustomerArea(); };

/*------------------------------------------- NEWSLETTER -------------------------------------------*/
// Validation javascript de l'email du formulaire registrationForm
var Newsletter = Class.create({
	initialize : function() {
		this.initNewsletterFormSubmit();
	},

	initNewsletterFormSubmit : function() {
		if ($$("form[id^=registrationForm]").first()) {
				$$("form[id^=registrationForm]").first().observe(
					Tapestry.FORM_VALIDATE_EVENT, function(event) {
						var formElt = Event.element(event);
						//copie de la valeur pour validation serveur
						
						if (!subscribeNewsletter()) {
//							// soumission du formulaire non propagee a tapestry
							$T(formElt).validationError = true;
						} else {
							// désactivation du bouton submit pour empecher une
							// nouvelle soumission
							$("registrationFormSubmit").disabled = "disabled";
							$T(formElt).validationError = false;
						}
					});
		}
	}
});
Tapestry.Initializer.newsletter = function() {
	var newsletter = new Newsletter();
};

// Validation javascript de l'email du formulaire Newsletter
var newsletterError = function() {
	jQuery('#newsletter .nl-email').css('background-color', '#ff9999');
	jQuery('#newsletter .nl-error').show();
};

var newsletterValid = function() {	
	jQuery('#newsletter .nl-sent').show();
};
var newsletterInit = function() {
	jQuery('#emailNewsletter').val(jQuery('#emailDefaultvalue').val());
	jQuery("#hiddenemail").hide();
	jQuery("#pop-newsletter").hide();
};


// Affichage javascript de la popin de double inscription du formulaire
// Newsletter
var newsletterPopin = function() {
	
	jQuery('#allgrey, #pop-newsletter').css('display', 'block');
};

/*------------------------------------------- NEWSLETTER OVERLAYER -------------------------------------------*/
// Overlayer indiquant la double inscription à la newsletter
var newsletterOverlayer = function() {
	jQuery('.choice .btn').click(function(e) {
		jQuery('#allgrey, #pop-newsletter').css('display', 'none');
	});
};

/*------------------------------------------- PAGE LIST LOADER -------------------------------------------*/
// Affichage du spinner de chargement de la liste des produits sur action tri/pagination
var showPageListLoader = function() {
	jQuery('div.pagesNavigation .ajaxloader').show();
}

/*------------------------------------------- QUANTITY MANAGER -------------------------------------------*/
// Gestionnaire de modification des quantités de produits dans le panier
// soumet le formulaire updateProductQtyForm via un appel Ajax
// Utilisé aussi pour le tri et la pagination Page Liste
var submitForm = function(formID) {
	$(formID).fire(Tapestry.FORM_PROCESS_SUBMIT_EVENT);
};

//var QtyMgr = Class.create({
//	value : "qtyMgr",
//	options : {
//		delay : 1000
//	},
//
//	initialize : function() {
//		this.initialiseZone();
//	},
//
//	initialiseZone : function() {
//	},
//
//	 add : function(target, e) {
//		 add(target, e);
//		 this.temporizeAjax($(target).down("input"));
//	 },
//		
//	 subtract : function(target, e) {
//		 subtract(target, e);
//		 this.temporizeAjax($(target).down("input"));
//	 },
//		
//	 checkValue : function(target, e) {
//		 checkValue(target, e);
//		 this.temporizeAjax(target);
//	 },
//
//	temporizeAjax : function(input) {
//		window.clearTimeout(input.actionTimer);
//		var self = this;
//		input.actionTimer = window.setTimeout(function(){ self.sendAjax.call(input); }, this.options.delay);
//	},
//
//	sendAjax : function() {
//		$T(this).zoneId = this.readAttribute("zone");
//		var zoneObject = Tapestry.findZoneManager(this);
//		if (!zoneObject) return;
//		var dynHref = this.readAttribute("eventLink");
//		dynHref = dynHref.replace("-qty-", this.value);
//		zoneObject.updateFromURL(dynHref);
//	}
//});
//var qtyMgr = null;
//Tapestry.Initializer.qtyMgr = function() {
//	qtyMgr = new QtyMgr();
//};

/*------------------------------------------- BazaarVoice -------------------------------------------*/
// fonction de routage vers la page d'identification en cas d'avis BZV demandé par un utilisateur non loggué
function doAuchanLogin(cug) {
	location.href="/inscription/inscription_cv.jsp?rewrite=1&sessionhttp=1&cv_add_to_selection=2&cug="+cug; 
}
/*------------------------------------------- SEARCH AUTOCOMPLETE -------------------------------------------*/
// la recherche lucene s'effectue sans accents
function noaccent(chaine) {
	  temp = chaine.replace(/[àâä]/gi,"a")
	  temp = temp.replace(/[éèêë]/gi,"e")
	  temp = temp.replace(/[îï]/gi,"i")
	  temp = temp.replace(/[ôö]/gi,"o")
	  temp = temp.replace(/[ùûü]/gi,"u")
//	  temp = temp.replace(/[ÀÂÄ]/gi,"A")
//	  temp = temp.replace(/[ÉÈÊË]/gi,"E")
//	  temp = temp.replace(/[ÎÏ]/gi,"I")
//	  temp = temp.replace(/[ÔÖ]/gi,"O")
//	  temp = temp.replace(/[ÙÛÜ]/gi,"U")
	  return temp
	} 

function validateSearch() {
	var myLinkValue = jQuery('#textSearch').attr('value');
	var defaultTextSearch = jQuery('#searchDefaultText').attr('value');
	if (myLinkValue!=null && myLinkValue.length>0 && myLinkValue != defaultTextSearch){
		document.getElementById('searchRefonte').value=noaccent(myLinkValue);
		document.getElementById('formSearchRefonte').submit();
		return true;
	}
}

function validateEnter(e){
	e = e || window.event;
	var code = e.keyCode || e.which;
	if(code == 13){
		validateSearch();
		return false;
	}
	return true;
}

var searchAutocompletion = function() {
	// Complément de script pour l'autocomplétion de la recherche
	var nbclic = 0; // Initialisation à 0 du nombre de clic
	function CompteClic() {
		nbclic++; // nbclic+1
		if (nbclic > 1) { // Plus de 1 clic
			alert("Vous avez déjà effectué une recherche.\nVeuillez patientez, la recherche est en cours de traitement... ");
			return false; // n'envois pas le formulaire au serveur.
		} else { // 1 seul clic
			return true;
		}
	}

	/* ! Suggestion Search */
	var hasBeenClosed = false; // to check if the autocompletion layer has
								// already been close once, and avoid re-show it
								// each time

	// Init Search Navigation
	function initLayerNavigation() {
		var serchfile = "/ResultSearch"
		var millisBetween2Search = 500;
		var timeoutDisplay;
		var autoCompleteNum = 2;

		var active = 0;
		var showLayer = true;

		var inputSearch = jQuery(".searchInputDisplay");
		var siblingLayer = jQuery(".suggestionsLayer");

		var inputSearchLength = jQuery(".searchInputDisplay").val().length
		if (inputSearchLength < 1) {
			jQuery(".searchInputDisplay").val(
					jQuery(".searchInputDisplayDefaultText").val());
		}

		// KEYDOWN
		jQuery(inputSearch).bind("keydown", function(event) {
			var myInputLength = event.target.value.length;
			if (myInputLength >= autoCompleteNum) {
				switch (event.keyCode) {
				case 38: // up
					event.preventDefault();
					moveSelect(-1);
					break;
				case 40: // down
					event.preventDefault();
					moveSelect(1);
					break;
				case 13: // return
					jQuery(siblingLayer).find("li.current a").trigger("click");
					jQuery(inputSearch).unbind("blur");
					break;
				}
			}

			inputSearchLength = jQuery(".searchInputDisplay").val().length

		});

		function launchSearch(event) {
			var myInputLength = event.target.value.length;

			var myInputValue = event.target.value;
			if (myInputLength === 0) {
				showLayer = true;
				hasBeenClosed = false;
				jQuery(siblingLayer).slideUp("fast"); // Hide the suggestions
														// box
			} else if (myInputLength >= autoCompleteNum
					&& inputSearchLength != myInputLength && showLayer == true
					&& !hasBeenClosed) {
				active = 0;
				
				strAccents = myInputValue.toLowerCase().split('');
			    strAccentsOut = new Array();
			    strAccentsLen = strAccents.length;
			    var accents = ' ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
			    var accentsOut = ['/espace/','A','A','A','A','A','A','/a1/','a','/a2/','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','/e1/','/e0/','/e2/','/e3/','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
			    for (var y = 0; y < strAccentsLen; y++) {
			        if (accents.indexOf(strAccents[y]) != -1) {
			            strAccentsOut[y] = accentsOut[accents.indexOf(strAccents[y])];
			        }
			        else
			            strAccentsOut[y] = strAccents[y];
			    }
			    myInputValue = strAccentsOut.join('');
				
				jQuery.post(serchfile + "/" + myInputValue, {
					queryString : "" + myInputValue + ""
				}, function(data) { // Do an AJAX call
					jQuery(siblingLayer).find(".suggestionsLayerContent").html(
							data); // Fill the suggestions box
					jQuery(siblingLayer).find(".suggestionsLayerContent").find(
							"li a").click(function(eventClick) {
						eventClick.preventDefault();
						var myLinkValue = jQuery(this).find(".heading").text();
						event.target.value = myLinkValue;
						jQuery(siblingLayer).slideUp("fast");
				//		jQuery(this).parents("searchForm").submit(); //TODO:test
			
						document.getElementById('searchRefonte').value=noaccent(myLinkValue);
						document.getElementById('formSearchRefonte').submit();
					});
					if (jQuery(siblingLayer).find(".suggestionsLayerContent")
							.find("li").length > 0) {
						jQuery(siblingLayer).slideDown("fast"); // Show the
																// suggestions
																// box
					} else {
						jQuery(siblingLayer).slideUp("fast"); // hide the
																// suggestion
																// box if no
																// result
					}
				});

			}
		}

		// KEYUP
		jQuery(".searchInputDisplay").bind("keyup", function(event) {
			if (timeoutDisplay != null)
				clearTimeout(timeoutDisplay);
			// alert("GTH 1 "+clearTimeout);
			timeoutDisplay = setTimeout(function() {
				launchSearch(event);
			}, millisBetween2Search);
			// alert("GTH 2 "+clearTimeout);
		});
		jQuery(inputSearch).bind("focus", function() {
			// at focus, bind the blur event, with a timeout to prevent conflict
			// between blur and focus
			jQuery(inputSearch).bind("blur", function() {
				setTimeout(function() {
					jQuery(siblingLayer).slideUp("fast");
				}, 500);
			});
		});

		function moveSelect(step) {
			var lis = jQuery("li", siblingLayer);
			if (!lis || lis.length == 0)
				return false;
			active += step;
			// loop through list
			if (active < 0) {
				active = lis.size();
			} else if (active > lis.size()) {
				active = 0;
			}
			lis.removeClass("current");
			jQuery(lis[active - 1]).addClass("current");
		}

		jQuery(".suggestionsLayer .btCloseSearch a").bind("click", function() {
			jQuery(this).parents(".suggestionsLayer").slideUp("fast");
			showLayer = false;
			hasBeenClosed = true;// set the flag for hiding autocompletion
									// until field will be emptyed again
			jQuery(inputSearch).trigger("focus");
			return false;
		});
	}

	function removeValueSeardField() {
		var searchFieldDefault = "Rechercher";
		if (jQuery(this).val() == searchFieldDefault) {
			jQuery(this).val("");
		}
		jQuery(this).blur(function() {
			if (jQuery(this).val() == "") {
				jQuery(this).val(searchFieldDefault);
			}
		});
	}

	initLayerNavigation();
}

// Affichage javascript du message de recherche par défaut
var searchInit = function() {
	defaultTextSearch = jQuery('#searchDefaultText').attr('value');
	jQuery('#searchForm').attr('autocomplete', 'off');
};


var addCartConfirmeZone = function() {
	$("addCartConfirmeZone").observe(Tapestry.ZONE_UPDATED_EVENT, function(e) {
		jQuery('.pop-in').hide(); // hide les éventuelles pop-in déjà ouvertes
		jQuery('#allgrey,'+'#addCartConfirme').css('display','block' );
		jQuery('#allgrey').attr('rel', '#addCartConfirme' );
		// Positionnement de la pop-in
		repositionPopIn( '#addCartConfirme' );
		
		var resizeFunc = function(){repositionPopIn('#addCartConfirme');};
		jQuery(window).resize( resizeFunc );
		jQuery('#addCartConfirme').unbind().bind("close", function (){jQuery(window).unbind("resize", resizeFunc);})
	});
};

var caracStyleToDisplay = function () {
	jQuery(document).ready(function()
	{
		var indexDeleted = jQuery("input[id='indexCugsSupp']").val().split(";");
		
		// recuperation du nombre de caracteristiques (ie : le nombre de champs hidden)
		var val=jQuery("input[id^='carac']").length;
		
		// nombre de produits devant etre traites
		var nbCugs=jQuery("input[id='nbCugs']").val();
		
		// style a appliquer si carac different
		var style=jQuery("input[id='style']").val();
		
		// nombre de masques
		var nbMasks=jQuery("input[id='nbMasks']").val();
		
		// index pour les iterations
		var indexMask = 0;
		var indexCarac=0;
		var indexProduit = 0;
		var indexValue = 0;
		var changed=false;
		
		var values=new Array();
		
		for(i = 0 ; i < val+1 ; i++){
			
			// Recuperation du nombre de caracteristique pour le masque en cours
			var nbCarac=jQuery("input[id='nbCaracMask_"+indexMask+"']").val();
			// Traitement des valeurs et passage a la caracteristique suivante
			if((i != 0 && i%nbCugs == 0) || i == val){
				// Comparaison des valeurs
				if(values.length > 1 ) {
					for(v=0 ; v < values.length-1 ; v++){
						if(values[v] != values[v+1]){
							jQuery("div[id^='div_"+indexMask+"_"+indexCarac+"']").addClass( "different "+style );
							changed=true;
							break;
						}
						if(!changed){
							jQuery("div[id^='div_"+indexMask+"_"+indexCarac+"']").removeClass( "different "+style );
						}
					}
				}else {
					jQuery("div[id^='div_"+indexMask+"_"+indexCarac+"']").removeClass( "different "+style );
				}
				if(i == val)break; // pour sortir avant les undefined
				values=new Array();
				indexProduit = 0;
				indexValue = 0;
				changed=false;
				// si on a traite toutes les caracteristiques du masque on passe au masque suivant
				if(indexCarac != 0 && indexCarac%(nbCarac-1) == 0){
					indexCarac=0;
					indexMask++;
				}else{ // sinon on passe a la caracteristique suivante
					indexCarac++;
				}
			}
			
			// recalcul du bon index produit a recuperer si le champ cache contenant les produits supprimes n'est pas vide
			if(indexDeleted.length > 1) {
				for(d=0 ; d < indexDeleted.length-1 ; d++){
					if(indexDeleted[d] == indexProduit){
						indexProduit++;
						break;
					}
				}
			}
			values[indexValue] = jQuery("input[id='carac_"+indexMask+"_"+indexCarac+"_"+indexProduit+"']").val();
			
			indexProduit++;
			indexValue++;
		}
	});
};

function deleteAndRefreshCaracStyle(indexCug) {
	value=jQuery("input[id='nbCugs']").val();
	jQuery("input[id='nbCugs']").val(""+value-1);
	value=jQuery("input[id='indexCugsSupp']").val();
	jQuery("input[id='indexCugsSupp']").val(value+indexCug+";");
	caracStyleToDisplay();
}


/*------------------------------------------- TabLivraison verif code postal-------------------------------------------*/
//Validation javascript des champs du formulaire formCodePostal

var ZipCodeAjax = Class.create({
	initialize: function() {
	this.initZipCodeForm();
	this.initZipCodeFormSubmit();
},
	
initZipCodeForm: function() {
	if($("formZone")!=null) {
		$("formZone").observe(Tapestry.ZONE_UPDATED_EVENT, function() {
		this.initZipCodeFormSubmit();
		}.bind(this));
	}
},

initZipCodeFormSubmit: function() {
	if($$("form[id^=formCodePostal]").first()){
		$$("form[id^=formCodePostal]").first().observe(Tapestry.FORM_VALIDATE_EVENT,
				function(event) {
			var formElt = Event.element(event);
			if(!checkZipCode()) {
				$T(formElt).validationError = true;
			}
			else {
				$T(formElt).validationError = false;
			}
		});
	}
}

});

Tapestry.Initializer.zipcodeajax = function(){ var zipcodeajax = new
	ZipCodeAjax(); };

var checkZipCode = function() {
		var zipcode = jQuery("input[name=zipcode]").val();
		if(zipcode!=undefined && zipcode!="") {
			var country = jQuery("select[name=country]").val();
			var taille_cp;
			if(country=="France") {
				taille_cp = 5;
			}
			else if(country=="Belgique") {
				taille_cp = 4;
			}
			else if(country=="Luxembourg") {
				taille_cp = 6;
			}
			var lengthCp = zipcode.length;
			if(lengthCp==taille_cp) {
				return true;
			}
			else {
				alert("Veuillez choisir un code postal correct");
				return false;
			}
		} 
		else {
			alert("Veuillez renseigner un code postal");
			return false;
		}
};	



/*------------------------------------------- popin Availability envoi d'un email-------------------------------------------*/
//Validation javascript des champs du formulaire formAvailability

var Availability = Class.create({
	initialize: function() {
		this.initAvailabilityForm();
		this.initAvailabilityFormSubmit();
	},
	
	initAvailabilityForm: function() {
		 $("availabilityZone").observe(Tapestry.ZONE_UPDATED_EVENT, function() {
		 this.initAvailabilityFormSubmit();
		 }.bind(this));
		 },

	initAvailabilityFormSubmit: function() {
	if($$("form[id^=formAvailability]").first()){
			$$("form[id^=formAvailability]").first().observe(Tapestry.FORM_VALIDATE_EVENT,
					function(event) {
				var formElt = Event.element(event);
				if(!availabilityMail()) {
					$T(formElt).validationError = true;
				} else {
					$("formAvailabilitySubmit").disabled = "disabled";
					$T(formElt).validationError = false;
				}
			});
		}
	}
});
Tapestry.Initializer.availability = function(){ var availability = new
	Availability(); };




