$(document).ready(function() {

	// start plug in jquery
	
	var options = { 
			serverURL : "http://"+document.location.hostname,
			getCountryOnLoad : false,
			loadingDivId : "#loading_ajax",
			countryDivId : "#country_cont",
			countryInputId : "#your_country",
			countryText : "#countryText",
			countryLabel : "#your_country_label",
			useZipcodeVerification : true,
			areaDivId : "#area_cont",
			areaInputId : "#your_area",
			areaText : "#areaText",
			areaLabel : "#your_area_label",
			zipcodeDivId : "#zipcode_cont",
			zipcodeInputId : "#your_zipcode",
			zipcodeText : "#zipcodeText",
			zipcodeLabel : "#your_zipcode_label",
			cityDivId : "#city_cont",
			cityInputId : "#your_city",
			cityText : "#cityText",
			cityLabel : "#your_city_label",
			noCityFoundErrorMessage : $('#geolocNoCityFoundErrorMessage').text()
	};
	
	$("#loading_ajax").geoloc( options );
	
	if($('#your_zipcode').val()!='')
	{
		$.fn.geoloc.publicZipcodeWasEntered();
		//TODO : passer cette fonction en callback de publicZipcodeWasEntered
		setTimeout(function(){
			if(document.signupform._cityId.options.length > 1)
			{
				document.signupform._cityId.selectedIndex = 1;
	    	}
		},3000);
	}
	
	/******************************
	 *******   birthday     *******
	 ******************************/
	$("#_userDay").one("focus", function(){
		$("#_userDay").val('');
	}).blur(function(){
		concatBirthday();
	});
	$("#_userMonth").one("focus", function(){
		$("#_userMonth").val('');
	}).blur(function(){
		concatBirthday();
	});
	$("#_userYear").one("focus", function(){
		$("#_userYear").val('');
	}).blur(function(){
		concatBirthday();
	});
	
	function concatBirthday() {
		var datenaiss = $("#_userDay").val() + '/' + $("#_userMonth").val() + '/' + $("#_userYear").val();
		$("#birthdaydate").val(datenaiss);
		$("#signupform").validate().element($("#birthdaydate"));
	};
	
	$("#_userDay").keyup( function() { 
		if($(this).val().length == 2){
			$('#_userMonth').focus();
		}
	});

	$("#_userMonth").keyup( function() { 
		if($(this).val().length == 2){
			$('#_userYear').focus();
		}
	});

	/********************
	 ***** header **
	 ********************/

	$("#loginMember").one("focus", function(){
		$("#loginMember").val('');
	});
	
	$("#_userPassword").one("focus", function(){
		$("#_userPassword").val('');
	});

	/********************
	 ***** AUTENT FALSE **
	 ********************/
	var showAuthentFalse = $.getURLParam("authent");
	if(showAuthentFalse == 'false'){		
		$('#showAuthentFalse').fadeIn('slow');
		setTimeout("$('#showAuthentFalse').fadeOut()",3000);
	}

	/********************
	 ***** validation **
	 ********************/
	// bouton de validation
	$("#sendSignup").click(function(){
		$('#signupform').submit();
	});
	
	// a la soumission du formulaire
	// on check le signup
	// et on lance jquery validate !
	$("#signupform").submit(function() {
		return false;
	});

	/************************
	 * JQuery validate ******
	 ************************/
	$("#signupform").validate({
		
		rules: {
			_userEmail : {
				remote : 
				{
					url: '/ajax/freemail'
				}
			}
		},
		submitHandler : function(form) {
			signupForm.check();
		},
		groups: {
			username: "_userGender _userGender"
		},
		errorPlacement: function(error, element) {
			 if (element.attr("name") == "_userGender" 
						 || element.attr("name") == "_userGender" )
			   error.insertAfter("#labelgarcon");
			 else if (element.attr("name") == "attribute_1[]" 
						 || element.attr("name") == "attribute_1[]" )
			   error.insertAfter("#label_herefor1");
			 else if (element.attr("name") == "_userAcceptConditions[]" 
				 || element.attr("name") == "_userAcceptConditions" )
				 error.insertAfter("#label_ok_cus");
			 else
			   error.insertAfter(element);
		},
		showErrors: function(errorMap, errorList) {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass );
				}
			}
			$('#sendSignup').css('top','94%');
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).css('display', 'block');
		},
		debug:true
	});
	
	jQuery.validator.addMethod("alphanumwithpunc", function(value, element) {
		return this.optional(element) || /^[a-zA-Z0-9-.,_]*$/i.test(value);
	});
	
	jQuery.validator.addMethod("beginwithletter", function(value, element) {
		return this.optional(element) || /^[a-z].*$/i.test(value);
	});
	
	jQuery.validator.addMethod("dateFR", 
		function(value, element) {
			try {
				var elem = value.split('/'); 
				day = elem[0]; 
				month = elem[1]; 
				year = elem[2];
				
				date = new Date(month + '/' + day + '/' + year );
				
				ok = date.getDate() == parseInt(day, 10);
				ok &= (date.getMonth() + 1) == parseInt(month, 10);
				ok &= date.getFullYear() == parseInt(year, 10);
				return this.optional(element) || ok;
			}
			catch (e) {
				return false;
			}
		}
	);
	
	jQuery.validator.addMethod("remote", function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			
			var previous = this.previousValue(element);
			
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			
			param = typeof param == "string" && {url:param} || param; 
			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "xml",
					data: data,
					success: function(response) {
						response = ( $(response).find('result').text() == '1' );
						if ( response ) {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						} else {
							var errors = {};
							errors[element.name] =  response || validator.defaultMessage( element, "remote" );
							// message specifique a chaque requete
							if( param['url'] && param['url'] == '/ajax/freemail') {
								errors[element.name] = response || validator.defaultMessage( element, "freemail" );
							}
							validator.showErrors(errors);
						}
						previous.valid = response;
						validator.stopRequest(element, response);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		}
	);
	
	jQuery.validator.addMethod("birthday",
		function(value, element) {
			try {
				var elem = value.split('/'); 
				day = elem[0]; 
				month = elem[1]; 
				year = elem[2];
				
				birthday = new Date(month + '/' + day + '/' + year );
				today = new Date();
				
				age = today.getFullYear() - birthday.getFullYear();
				if( today.getMonth() < birthday.getMonth() || ( today.getMonth() == birthday.getMonth() && today.getDate() < birthday.getDate() ) ) {
				    age--;
				}
				return this.optional(element) || (age >= 16 && age <100);
			}
			catch (e) {
				return false;
			}
		}
	);
	
	
	jQuery.extend(jQuery.validator.messages, {
	        required: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validaterequired").text() + "</p>",
	        remote: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validateremote").text() + "</p> ",
	        alphanumwithpunc: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatealphanumwithpunc").text() + "</p> ",
	        beginwithletter: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatebeginwithletter").text() + "</p> ",
	        freemail: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatefreemail").text() + "</p> ",
	        email: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validateemail").text() + "</p>",
	        url: $("#validateurl").text(),
	        date: $("#validatedate").text(),
	        dateISO: $("#validatedateISO").text(),
	        dateFR : "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatedateFR").text(),
	        birthday : "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatebirthday").text(),
	        number: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatenumber").text() + "</p>",
	        digits: $("#validatedigits").text(),
	        creditcard: $("#validatecreditcard").text(),
	        equalTo: "<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validateequalTo").text(),
	        accept: $("#validateaccept").text(),
	        maxlength: jQuery.format("<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validatemaxlength").text() + "</p>"),
	        minlength: jQuery.format("<span class=\"cross\">x</span><br class=\"clear\" /><p>" + $("#validateminlength").text() + "</p>"),
	        rangelength: jQuery.format($("#validaterangelength").text()),
	        range: jQuery.format($("#validaterange").text()),
	        max: jQuery.format($("#validatemax").text()),
	        min: jQuery.format($("#validatemin").text()),
	        phoneFR : $("#validatephoneFR").text()
	});
	
	/* cas login */
	$("#lite_deja_membre").click(function(){			
		$('#form_signup').slideUp();
		$('#lite_deja_membre').hide();
		$('#popin_top_1').hide();
		$('#popin_top_2').show();		
		$('#form_signin').slideDown();
		$('#lite_mdp_forget').show();	
	});

	/* cas mdp oublié */
	$("#lite_mdp_forget").click(function(){			
		$('#form_signin').slideUp();
		$('#lite_mdp_forget').hide();
		$('#popin_top_2').hide();
		$('#popin_top_3').show();	
		$('#lite_visiteur_login_mdp').slideDown();
		$('#lite_retour_id').show();		
	});
	
	/* cas message pour le msg perdu */
	$("#forgotpasswordButtonSend").click(function(){			
		$('#lite_visiteur_login_mdp').slideUp();
		$('#home_visiteur_login_mdp_sended').slideDown();
	});

	/* cas retour au login */
	$("#lite_retour_id").click(function(){			
		$('#home_visiteur_login_mdp_sended').slideUp();
		$('#lite_visiteur_login_mdp').slideUp();
		$('#lite_retour_id').hide();
		$('#popin_top_3').hide();
		$('#popin_top_2').show()
		$('#form_signin').slideDown();
		$('#lite_mdp_forget').show();		
	});
	
	$('#your_city').blur(function(){
		$('#your_pseudo').focus();
	});
	
	
});
	
	/*******************
	 *** req Ajax ******
	 *******************/
	// fonction de callback de callApp (appelee par le flash)
	// situé dans le xsl
	
	var signupForm = (function() {
		//private/////////////////////
		var _sURL      = encodeURI( "http://" + document.location.hostname + "/ajax/signuplandingformvalidation" );
		var _form      = '#signupform';
		var _redirect  = "/signup/confirm";
		var _getXHR    = null;
		
		function handleSuccess(o){
			if(o !== undefined){
				var obj = o;
				var signupformvalidation = $(obj).find('signuplandingformvalidation');
				
				if(signupformvalidation.length == 0) {
					return false;
				}
				
				//no errors
				
				if(signupformvalidation.find('errorList').length == 0){ //no error
					
					// redirect vers upload photo
					document.location.href = _redirect;
				}
				//errors
				var errors = signupformvalidation.find('error');
				$(errors).each(function( ) {
					// pour chaque champ
					$(this).children().each(function( ) {
						var errorsTxt = "";
						var id ='';
						
						id = $(this).get(0).nodeName;
						// pour chaque erreur de ce champs
						$(errors).find(id).children().each(function(){ 
							errorsTxt = $(this).text() + "<br />";
						});
						
						var html = '<label class="error" style="display:block;" id="' + id + '_error"><span class="paragraphe">' + errorsTxt + '</span></label>';

						var this_id = $("input[name='" + id + "']").attr("id");
						$("label[for='" + this_id + "']").remove(":contains('ok!')");
						if(  id == "_zipCode" ) {
							$("#zipcodeText").after(html);
						} else {
							$("input[name='" + id + "']").after(html);
						}
					});
					
				});
				return false;
			}
		}
		
		function handleFailure(){
			//alert("handleFailure");
			_getXHR = null;
		}
		
		function getFormData(f){
			var params = '';
			// var params = {};
			$(f)
			.find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea")
			
			.each(function(){
				// params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
				if (params == '') {
					params = (this.name || this.id || this.parentNode.name || this.parentNode.id) + '=' + this.value;
				} else {
					params = params + '&' + (this.name || this.id || this.parentNode.name || this.parentNode.id) + '=' + this.value;
				}
			});//.filter(":enabled")
			return params;
		}
		
		function formReq(){
			_getXHR = $.ajax({
				type: "POST",
				url: _sURL,
				data: getFormData(_form),
				dataType: "xml",
				success: handleSuccess,
				error: handleFailure
			});
		}
		
		//public/////////////////////
		return{
			"check": function(){
			formReq();
			return false;
		}
		};
		
	})();
