$(document).ready(function() {
	
	//IE toujours le mauvais élève
	ie = $.browser.msie;
	ie6 = $.browser.msie && ($.browser.version < 7);
	ie7 = $.browser.msie && ($.browser.version == 8);
	ie6_7 = $.browser.msie && ($.browser.version < 8);
	ie8 = $.browser.msie && ($.browser.version > 7);
	
	//On cache ce qu'il y'a a cacher
	 //$("#parchment #intro").hide();
	 slideSpeed = "normal";
	 
	function hideThis(selecteur) {
		 $(selecteur).animate({ 
					marginTop : - 40
				}).slideToggle(slideSpeed); 
	 }
	 function showThis(selecteur) {
		 $(selecteur).animate({ 
					marginTop : 0
				}).slideToggle(slideSpeed); 
	 }
	 
	 allContainersExceptIntro = "#parchment #carrousel, #form_result, #parchment #fix-instructions, #parchment #queteAccomplie";
	
	hideThis(allContainersExceptIntro);
	
	$("a.retour_accueil").click(function () {
	  $(allContainersExceptIntro).slideUp(slideSpeed);
	  $("#parchment #intro").slideDown(slideSpeed);
	 });
	 
	 $("#intro a.quest_start").click(function () {
	  hideThis("#parchment #intro");
	  showThis("#parchment #fix-instructions");
	 });
	 
	 $("#intro a.quest_end").click(function () {
	  hideThis("#parchment #intro");
	  showThis("#parchment #queteAccomplie");
	 });
	 
	 
	 $("#btdeguerpir").click(function () {
		 hideThis("#parchment #fix-instructions");
		showThis("#parchment #intro");
	 });
	 
	 $(".retourIntro").click(function () {
		 hideThis("#parchment #carrousel");
		showThis("#parchment #intro");
	 });
	 
	 $("#btcommencer").click(function () {
		 hideThis("#parchment #fix-instructions");
		showThis("#parchment #carrousel");
	 });
	// Fonction de remplacement select/text		  
	$("select.styled").change(function () {
		var str = "";
		$(this).find("option:selected").each(function () {
			str += $(this).text() + " ";
		  });
		$(this).siblings(".replace").text(str).show();
		$(this).hide();
	});
	$(".replace").click(function () {
		$(this).siblings("select.styled").show();
		$(this).hide();
	});

	// CARROUSEL
	// Element de référence pour la zone de visualisation (ici le premier item) 
	Reference = $(".carrousel li:first-child"); 
	// Nombre d'éléments de la liste 
	NbElement = $(".carrousel li").length; 
	// appliqué en javascript pour acessibilité
	//$(".carrousel li").css("padding", '0');
	//$(".carrousel").addClass("loader");
	// Ciblage de la bande de diapositives 
	$(".carrousel") 
	// Englobage de la liste par la zone de visualisation 
	//.wrap('<div class="carrousel-conteneur"></div>')
	// Application d'une largeur à la bande de diapositive afin de conserver une structrure horizontale 
	.css("width", (Reference.width() * NbElement) )
	.css("height", Reference.height() ) ;
	// Ciblage de la zone de visualisation 
	$(".carrousel-overflow").css("overflow", "hidden")
	// Blocage des débordements appliqué en javascript pour acessibilité
	// Application de la largeur d'une seule diapositive 
	//.width(  Reference.width() * 2 )
	// Application de la hauteur d'une seule diapositive 
	//.height( Reference.height() ) 
	// Insertion des boutons de navigation 
	.before('' 
		+    '<ul class="carrousel-pagination">' 
		+    '    <li class="carrousel-prev"><span class="border"></span><span class="text"></span><a href="#"><span>Etape  Précédente</span></a></li>' 
		+    '    <li class="carrousel-next"><span class="border"></span><span class="text"></span><span id="wax_seal"><a href="#"></a></span><span id="text-wax_seal"></span><a href="#"><span>Etape Suivante</span></a></li>' 
		+    '</ul>' 
		+    '');
	

	//Planquez vous ! 
	function hideThem() {
		if(ie) {
			$(".carrousel-next #wax_seal").hide();
			$(".carrousel-next #text-wax_seal").hide();	
		}
		else {
			$(".carrousel-next #wax_seal").css('opacity', 0);
			$(".carrousel-next #text-wax_seal").css('opacity', 0);
		}
	};
	
	//fonction de check des boutons
	function checkButtons() {
		//On désactive les animations de type opacité qu'IE toutes versions ne comprends pas, et on les remplace par un hide/show
		if(ie) {
			if(Cpt == 0) {
				$(".carrousel-prev").addClass("inactif").animate({ 
				}, 300).hide();
				$(".arrow.left, .carrousel-prev .text").stop().animate({
					marginLeft : 10
				}, 300).hide();
			}
			else {
				$(".carrousel-prev").removeClass("inactif").animate({ 
				}, 300).show();
				$(".arrow.left, .carrousel-prev .text").stop().animate({
					marginLeft : 0
				}, 300).show();
			}
			if(Cpt == (NbElement-2) ) {
				
				 $(".arrow.right, .carrousel-next .text").stop().animate({
					marginRight : -10
				}, 300).hide();
				 $(".carrousel-next #wax_seal, .carrousel-next #text-wax_seal").animate({
					marginRight : 0
				}, 300).show();
			}
			else {
				$(".arrow.right, .carrousel-next .text").stop().animate({
					marginRight : 0
				}, 300).show();
				$(".carrousel-next #wax_seal, .carrousel-next #text-wax_seal").animate({
					marginRight : -10
				}, 300).hide();
			}
		}
		
		// tous les autres navigateurs
		else {
			if(Cpt == 0) {
				$(".carrousel-prev").addClass("inactif").animate({ 
					opacity: 0
				}, 300);
				$(".arrow.left, .carrousel-prev .text").stop().animate({
					marginLeft : 10,
					opacity: 0
				}, 300);
			}
			else {
				$(".carrousel-prev").removeClass("inactif").animate({ 
					opacity: 1
				}, 300);
				$(".arrow.left, .carrousel-prev .text").stop().animate({
					marginLeft : 0,
					opacity: 1
				}, 300);
			}
			if(Cpt == (NbElement-2) ) {
				 $(".arrow.right, .carrousel-next .text").stop().animate({
					marginRight : -10,
					opacity: 0
				}, 300);
				 $(".carrousel-next #wax_seal, .carrousel-next #text-wax_seal").animate({
					marginRight : 0,
					opacity:1
				}, 300).show();
			}
			else {
				$(".arrow.right, .carrousel-next .text").stop().animate({
					marginRight : 0,
					opacity: 1
				}, 300);
				$(".carrousel-next #wax_seal, .carrousel-next #text-wax_seal").animate({
					marginRight : -10,
					opacity:0
				}, 300).hide();
			}
		}
	};
	
	// Initialisation du compteur 
	Cpt = 0;
	fadeSpeed = 1000;
	
	if(Cpt == 0) {
		/*$(".carrousel li:first-child .savon-texte").fadeIn(fadeSpeed);*/
	}
	
	hideThem();
	checkButtons();
	
	$(".carrousel-prev a").hover(function(){
	   $(".arrow.left").stop().animate({ 
				marginLeft : -10
			}, 300);
	 },function(){
	   $(".arrow.left").stop().animate({ 
				marginLeft : 0
			}, 300);
	 });
	
	$(".carrousel-next a").hover(function(){
	   $(".arrow.right").stop().animate({ 
				marginRight : -10
			}, 300);
	 },function(){
	   $(".arrow.right").stop().animate({ 
				marginRight : 0
			}, 300);
	 });
	
	// Clic sur le lien "Suivant" 
	$(".carrousel-next a").click(function() { 
		// Si le compteur est inférieur au nombre de diaposives moins 1  
		if(Cpt < (NbElement-2) ) { 
			// Ajout +1 au compteur (nous allons sur la diapositive suivante) 
			Cpt++;
			// Mouvement du carrousel en arrière-plan 
			if(Cpt == (NbElement-2) ) {
				$(".carrousel").stop().animate({ 
					marginLeft : - (Reference.width() * Cpt) 
				}, fadeSpeed, checkButtons); 
			}
			else {
				$(".carrousel").stop().animate({ 
					marginLeft : - (Reference.width() * Cpt) 
				}, fadeSpeed); 
				// check boutons
				checkButtons();
			}
		} // fin du if 
		// Blocage du lien 
		return false;
	}); 
	 
	// Action du lien "Précédent" 
	$(".carrousel-prev a").click(function() { 
		// Si le compteur est supérieur à zéro 
		if(Cpt > 0) {
			// Soustraction -1 au compteur (nous allons sur la diapositive précédente) 
			Cpt--;
			// Mouvement du carrousel en arrière-plan 
			$(".carrousel").stop().animate({ 
				marginLeft : - (Reference.width() * Cpt) 
			}, fadeSpeed);
			// Bouton actif
			checkButtons();
		} // fin du if 
		// Blocage du lien 
		return false;
	}); 

	function hashlocation(Cpt) {
		
		$(".carrousel").stop().animate({ 
		marginLeft : - (Reference.width() * Cpt) 
	}, fadeSpeed, checkButtons);
	};




/* function send 
* Récupère les données du formulaire et les envoi à form.php
* En cas de succés, form.php envoie un mail et retourne une phrase
*/
function send(){

	//some lazy variables
	var report = false;
	var fields ='';
	var etape1 = $("select[name='etape1'] option:selected");
	var etape2 = $("select[name='etape2'] option:selected");
	var etape3 = $("select[name='etape3'] option:selected");
	var etape4 = $("select[name='etape4'] option:selected");
	var etape5 = $("select[name='etape5'] option:selected");
	var etape6 = $("select[name='etape6'] option:selected");
	var nomprenom = $("input[name='nomprenom']");
	var recevoir = $("#recevoir_resume").attr("checked");
	var adresse = $('textarea#adresse_postale');
	var email = $("input[name='email']");
	
	//check fields
	if (nomprenom.val().match(/Nom complet/)){
		fields += '<li><label for="nomprenom"><a href="#">Pr&eacute;nom &amp; Nom</a></label></li>';
		report = true;
	}
	if (recevoir && adresse.val().match(/Adresse/)){
		fields += '<li><label for="adresse_postale"><a href="#">Adresse postale</a></label></li>';
		report = true;
	}
	if (!email.val().match(/^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\.-]{2,}[\.][a-zA-Z]{2,4}$/)){
		fields += '<li><label for="email"><a href="#">Adresse Email</a></label></li>';
		report = true;
	}
	if (etape1.val() === 'choisir'){
		fields += '<li><a href="#" class="warning" name="1">Commandement n&ordm;1</a></li>';
		report = true;
	}
	if (etape2.val() === 'choisir'){
		fields += '<li><a href="#" class="warning" name="2">Commandement n&ordm;2</a></li>';
		report = true;
	}
	if (etape3.val() === 'choisir'){
		fields += '<li><a href="#" class="warning" name="3">Commandement n&ordm;3</a></li>';
		report = true;
	}
	if (etape4.val() === 'choisir'){
		fields += '<li><a href="#" class="warning" name="4">Commandement n&ordm;4</a></li>';
		report = true;
	}
	if (etape5.val() === 'choisir'){
		fields += '<li><a href="#" class="warning" name="5">Commandement n&ordm;5</a></li>';
		report = true;
	}
	if (etape6.val() === 'choisir'){
		fields += '<li><a href="#" class="warning" name="6">Commandement n&ordm;6</a></li>';
		report = true;
	}
	
	if (report){
		$('.final_step .container .report').hide().html("Hol&agrave; manant ! L'aventure est au bout du chemin mais vous avez voulu br&ucirc;ler les &eacute;tapes !   Vous avez ignor&eacute; :<ul>"+ fields +"</ul> <br class='clear' /><br />Faites demi-tour et acceptez de remplir ces quelques champs, sinon jamais vous ne serez chevalier.<a href='#' class='close'>x Fermer</a>").fadeIn();
			
		$(".warning").each(function(i){
			$(this).click(function() {
				Cpt = $(this).attr("name") -1;
				hashlocation(Cpt);
				$("select.styled").eq(Cpt).css("border", "1px solid red").select();
				return false;
			});
		 });
		
		$(".final_step .container .report .close, .final_step .container .report, .final_step .container .report a").click(function() {
			$(".final_step .container .report").css("display", "block").fadeOut();									   
}); 

		return;
	}


	$.ajax({
		type: "POST",
		url: "form.php",
		data: {
			'etape1':etape1.text(),
			'etape2':etape2.text(),
			'etape3':etape3.text(),
			'etape4':etape4.text(),
			'etape5':etape5.text(),
			'etape6':etape6.text(),
			'adresse':adresse.val(),
			'recevoir':recevoir,
			'nomprenom':$("input[name='nomprenom']").val(),
			'email':$("input[name='email']").val()
		},
		success: function(msg){
				$('#form_result p').html(msg);
				$("#parchment #form_result").show();
				$("#parchment #carrousel").hide();
	  	}
 	});
	
	
	
};

	$("#wax_seal a").click(function() {
	send();
	});
	
	$(".final_step .container .report").hide();



	jQuery.fn.resetDefaultValue = function() {
		function _clearDefaultValue() {
			var _$ = $(this);
			if ( _$.val() == this.defaultValue ) { _$.val(''); }
		};
		function _resetDefaultValue() {
			var _$ = $(this);
			if ( _$.val() == '' ) { _$.val(this.defaultValue); }
		};
		return this.click(_clearDefaultValue).focus(_clearDefaultValue).blur(_resetDefaultValue);
	}
	$(function() {
		$('input.nomprenom, input.email, textarea.adresse_postale').resetDefaultValue();
	});
	
	function checkAndEnableDisable(checkBox, destination) {
		checkChecked = $(checkBox).attr("checked");
		if (checkChecked == true) {
			$(destination).removeAttr("disabled").removeClass("disabled");
		}
		else {
			$(destination).attr("disabled", "disabled").addClass("disabled");
		}
	}
	
	checkAndEnableDisable(".recevoir_resume", "textarea.adresse_postale");
	
	$(".recevoir_resume").click(function() {
		checkAndEnableDisable(".recevoir_resume", "textarea.adresse_postale");
	});
	

// END document ready	 
});