
var jbTitre = {
	connexion: 'Merci de vous identifier pour acc&eacute;der &agrave; votre compte',
	creataccount: 'GRATUIT et sans engagement !<br/>Devenez membre de "Pour Les Enfants"',
	mustValidat: 'Un email a &eacute;t&eacute; envoy&eacute; &agrave; :',
	forgetPass: 'Vous avez oubli&eacute; votre mot de passe ?',
	forgetPassSubmit: 'Un email a &eacute;t&eacute; envoy&eacute; &agrave; : ',
	accountCreated: 'Votre compte a &eacute;t&eacute; cr&eacute;&eacute;',
	accountNeed: 'Vous devez vous identifier pour acc&eacute;der &agrave; cette fonctionnalit&eacute;.',
	accountNeedConnec: 'Me connecter',
	accountNeedCreat: 'Cr&eacute;er un compte GRATUIT !'
};
var jbMsg = {
	mustValidat: '<br />Pour finaliser votre inscription, vous devez cliquez sur le lien qui y figure.<br /><br />Merci de patienter, ce mail peut mettre quelques minutes à vous parvenir.<br /><br />'
};

var scriptAjax = '/identification/create_account.php';

var zoneIdentificationBG;
var zoneIdentification;
var zoneCreatAccount;
var zoneMustValid;
var zoneGetPass;
var zoneGetPassPost;
var zoneCompteCree;
var zoneConnexion;
var mailZone;
var destination = '';

(function($){
	var cookieOption = {
		//domain: '.medias-tactiles.fr',//pour-les-enfants.fr
		path: '/',
		expires: ''
	};

	function controle_number(p){
		var pattern = '0123456789';
		var newvalue = '';
		for (i = 0; i < p.length; i++){
			var c =  p.charAt(i);
			if (pattern.indexOf(c) > -1){
				newvalue = newvalue+c;
			}
		}
		return newvalue;
	}
	function verifEmail(e){
		if (e.length < 1) return false;
		var i = e.indexOf('@');
		var j = e.indexOf('.',i);
		var k = e.length-1;
		if(i<1 || j==-1 || (j-i)==1 || j==k){ return false; }else{ return true; }
	}
	function hideZone(){
		zoneIdentificationBG.hide();
		zoneIdentification.hide();
	}

	function showIdentifiedZone(xml)
	{
		$('.userPseudo').html($('pseudo', xml).text());
		$('.userEmail').html($('email', xml).text());
		$('.userCP').html($('cp', xml).text());
		$('.jbIdentificationZone').hide();
		$('.jbIdentified').show();
	}

	//function validation_controle(){
	$.fn.validation_controle = function(){
		var url = window.location.href;
		var pos = url.indexOf('?');
		if (pos > 0){
			var exp1 = new RegExp('[&]+','g');
			var exp2 = new RegExp('[=]+','g');
			var getStr = url.substring(pos+1);
			var getStr = getStr.split(exp1);
			if (getStr!=null){
				for (var i=0; i < getStr.length; i++){
					var nom = getStr[i].split(exp2);
					if (nom[0] == 'validate'){
						$.post(scriptAjax, 
							{validation_account: nom[1]},
							function(xml){
							if ($('errorNum', xml).text() == '0'){
								$.cookie('identificationCreatEnCours','', {expires: -1});
								$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
								zoneCompteCree.show();
								zoneIdentificationBG.show();
								zoneIdentification.show();

								showIdentifiedZone(xml);
							}
						});
					}
				}
			}
		}
	};

	//-----------------------------------JBPropose
	$.fn.jbpropose = function(user_param){
		var inputauto = $(this);

		var param = $.extend({
			target: '', // script a interroger pour afficher les propositions.
			start_lenght: 0 // a partir de combien de caractere les propositions commence.
		}, user_param);

		var divproposition = $('<div></div>').attr('class','proposition').hide();

		function show_propose(){
			inputauto.after(divproposition);
			divproposition.width(inputauto.innerWidth());
			divproposition.css('left', inputauto.position().left+'px');
			divproposition.css('top', inputauto.position().top+inputauto.outerHeight()-1+'px');
			divproposition.show();
		}

		function get_proposition(target){
			divproposition.html('');
			$.get(target, {input: inputauto.val()}, function(xml){
				$('contenu', xml).each(function(){
					var id = $('id', this).text();
					var texte = $('texte', this).text();
					$('<a></a>').attr('href','javascript:;').html(texte).prependTo(divproposition).click(function(){
						var labelVille = $('#ville_12345');
						if (labelVille.length < 1){
							labelVille = $('<label></label>').attr('id','ville_12345').appendTo(inputauto.parent().parent());
						}
						labelVille.html('Ville :<br/> <input type="text" name="ville" value="'+texte+'" />');
					});
				});
			});
		}

		inputauto.keyup(function(e){
			var newvalue = controle_number(inputauto.val());
			if (newvalue != inputauto.val())
				inputauto.val(newvalue);
			if (inputauto.val().length > param.start_lenght){
				if (divproposition.css('display') == 'none'){
					show_propose(inputauto);
				}
				get_proposition(param.target);
			}else{
				divproposition.hide();
			}
		});
		inputauto.blur(function(){
			setTimeout(function(){divproposition.hide();}, 300);
		});
		inputauto.focus(function(){
			if (inputauto.val().length > param.start_lenght){
				show_propose(inputauto);
			}
		});
		return inputauto;
	};
	//-----------------------------------jbConnexion
	$.fn.jbConnexion = function(user_param){
		var formulaire = $(this);

		var erreur = $('<p class="erreur">Ce compte n\'existe pas.</p>');
		var erreurmail = $('<p class="erreur">Email invalide</p>');
		var erreurmdp = $('<p class="erreur">Champs obligatoire</p>');

		formulaire.submit(function(){

			var mail = $('input[@name="mail"]', this);
			var pseudo = $('input[@name="pseudo"]', this);
			var mdp = $('input[@name="mdp"]', this);
			var submit = true;

			if (!verifEmail(mail.val())){
				submit = false;
				mail.parent().append(erreurmail);
			}else{
				$('.error', mail.parent()).remove();
			}

			if (mdp.val().length < 1){
				submit = false;
				mdp.parent().append(erreurmdp);
			}else{
				$('.error', mdp.parent()).remove();
			}

			if (submit == true){
				$.post(scriptAjax, 
					{connexion: 1, mail: mail.val(), mdp: mdp.val()},
					function(xml){
						if ($('errorNum', xml).text() == '0'){
							hideZone();
							$('.userPseudo').html($('pseudo', xml).text());
							$('.userEmail').html($('email', xml).text());
							$('.userCP').html($('cp', xml).text());
							$('.jbIdentificationZone').hide();
							$('.jbIdentified').show();
							if (destination !== '')
								document.location.href = destination;
						}else if ($('errorNum', xml).text() == '1'){
							$('p.errorg').append(erreur);
							erreur.html($('error', xml).text());
						}else{
							alert($('error', xml).text());
						}
				});
			}
		});
	};
	//-----------------------------------jbCreatACount
	$.fn.jbcreatacount = function(){
		var formulaire = $(this);

		var erreurmail = $('<p class="erreur">Email invalide</p>');
		var erreurpseudo = $('<p class="erreur">Champs obligatoire</p>');
		var erreurmdp = $('<p class="erreur">Champs obligatoire</p>');
		var erreurtype = $('<p class="erreur">Champs obligatoire</p>');
		var erreurcp = $('<p class="erreur">Champs obligatoire</p>');

		formulaire.submit(function(){
			var submit = true;

			var mail = $('input[@name="mail"]', this);
			var pseudo = $('input[@name="pseudo"]', this);
			var mdp = $('input[@name="mdp"]', this);
			var type = $('select[@name="type"]', this);
			var cp = $('input[@name="cp"]', this);
			var ville = $('input[@name="ville"]', this);

			if (!verifEmail(mail.val())){
				submit = false;
				mail.parent().append(erreurmail);
			}else{
				$('.error', mail.parent()).remove();
			}

			if (pseudo.val().length < 1){
				submit = false;
				pseudo.parent().append(erreurpseudo);
			}else{
				$('.error', pseudo.parent()).remove();
			}

			if (mdp.val().length < 1){
				submit = false;
				mdp.parent().append(erreurmdp);
			}else{
				$('.error', mdp.parent()).remove();
			}

			if (type.val() == null){
				submit = false;
				type.parent().append(erreurtype);
			}else{
				$('.error', type.parent()).remove();
			}

			if (cp.val().length < 1){
				submit = false;
				cp.parent().append(erreurcp);
			}else{
				$('.error', cp.parent()).remove();
			}

			if (submit){
				$.post(scriptAjax, 
					{creat: 1, mail: mail.val(), pseudo: pseudo.val(), mdp: mdp.val(), type: type.val(), cp: cp.val(), ville: ville.val()},
					function(xml){
						if ($('errorNum', xml).text() == '0'){
							$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
							$.cookie('identificationCreatEnCours','1', cookieOption);
							$.cookie('identificationMail',mail.val(), cookieOption);
							mailZone.html(mail.val());
							zoneMustValid.css('display', 'block');
						}else if ($('errorNum', xml).text() == '1'){
							alert($('error', xml).text());
						}else if ($('errorNum', xml).text() == '2'){
							$.cookie('identificationMail',mail.val(), cookieOption);
							$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
							zoneGetPass.show();
						}else{
							alert($('error', xml).text());
						}
				});
			}
			return this;
		});
	};
	//-----------------------------------jbzoneIdentification
	$.fn.jbzoneIdentification = function(){

		zoneIdentificationBG = $('<div id="identificationZoneBG"></div>').css('display', 'none');
		$(this).append(zoneIdentificationBG);
		zoneIdentification = $('<div id="identificationZone"></div>').css('display', 'none');
		$(this).append(zoneIdentification);


		zoneForgetPass = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneIdentification.prepend(zoneForgetPass);
		zoneForgetPass.html('<h1>'+jbTitre.forgetPass+'</h1>');
		var formulaire = $('<form></form>').attr('action', 'javascript:;');
		formulaire.submit(function(e){
			$.cookie('identificationMail', $('input[name="mail"]', this).val(), cookieOption);
			$.post(scriptAjax, {getPass: 1, mail: $('input[name="mail"]', this).val()}, function(xml){
				if ($('errorNum', xml).text() == '0'){
					$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
					$('.email', zoneGetPassPost).html($.cookie('identificationMail'));
					zoneGetPassPost.css('display', 'block');
				}else{
					alert($('error', xml).text());
				}
			});
			e.stopPropagation();
			return false;
		});
		zoneForgetPass.append(formulaire);
		var zoneP = $('<p></p>');
		formulaire.append(zoneP);
		var zone = $('<label></label>').html('Votre email <input type="text" name="mail" value="" />');
		zoneP.append(zone);
		var zoneP = $('<p class="submit"></p>');
		formulaire.append(zoneP);
		var lienClose = $('<a></a>').attr('href', 'javascript:;').html('Fermer');
		lienClose.click(function(){ hideZone(); });
		zoneP.append(lienClose);
		var zone = $('<input type="submit" value="Envoyer" />');
		zoneP.append(zone);
		zoneP.append('<br/>&nbsp;');



		zoneConnexion = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneIdentification.prepend(zoneConnexion);
		zoneConnexion.html('<h1>'+jbTitre.connexion+'</h1><p class="errorg"></p>');
		var formulaire = $('<form></form>').attr('action', 'javascript:;');
		zoneConnexion.append(formulaire);
		formulaire.jbConnexion();
		var zoneP = $('<p></p>');
		formulaire.append(zoneP);
		var zone = $('<label></label>').html('Votre email <input type="text" name="mail" value="" />');
		zoneP.append(zone);
		var zone = $('<label></label>').html('Votre mot de passe <input type="text" name="mdp" value="" />');
		zoneP.append(zone);
		var forgetPass = $('<p></p>').attr('class','forgetpass').append($('<a></a>').attr('href','javascript:;').html(jbTitre.forgetPass).click(function(e){
			$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
			zoneForgetPass.show();
			e.stopPropagation();
			return false;
		}));
		zoneP.append(forgetPass);
		var zone = $('<a></a>').attr('href', 'javascript:;');
		var zoneP = $('<p class="submit"></p>');
		formulaire.append(zoneP);
		zone.html('Fermer');
		zone.click(function(){ hideZone(); });
		zoneP.append(zone);
		var zone = $('<input type="submit" value="Connexion" />');
		zoneP.append(zone);
		zoneP.append('<br />&nbsp;');


		zoneCreatAccount = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneIdentification.prepend(zoneCreatAccount);
		zoneCreatAccount.html('<h1>'+jbTitre.creataccount+'</h1>');
		var formulaire = $('<form></form>').attr('action', 'javascript:;');
		zoneCreatAccount.append(formulaire);
		formulaire.jbcreatacount();
		var zoneP = $('<p></p>');
		formulaire.append(zoneP);
		var zone = $('<label></label>').html('Votre email (pas diffus&eacute;) <input type="text" name="mail" value="" />');
		zoneP.append(zone);
		var zone = $('<label></label>').html('Votre nom ou pseudo <input type="text" name="pseudo" value="" />');
		zoneP.append(zone);
		var zone = $('<label></label>').html('Votre mot de passe <input type="text" name="mdp" value="" />');
		zoneP.append(zone);
		var zone = $('<label></label>').html('Vous &ecirc;tes <select name="type" size="4"><option value="1">Une maman</option><option value="2">Un papa</option><option value="3">Un professionnel</option></select>');
		zoneP.append(zone);
		var zone = $('<label></label>').html('Votre code postal');
		var cp = $('<input type="text" name="cp" value="" maxlength="5" />').jbpropose({target: scriptAjax, start_lenght: 4});
		zone.append(cp);
		zoneP.append(zone);
		var zoneP = $('<p class="submit"></p>');
		formulaire.append(zoneP);
		var zone = $('<a></a>').attr('href', 'javascript:;');
		zone.html('Non, merci !');
		zone.click(function(){ hideZone(); });
		zoneP.append(zone);
		var zone = $('<input type="submit" value="M\'enregistrer !" />');
		zoneP.append(zone);
		zoneP.append('<br />&nbsp;');

		zoneMustValid = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneMustValid.html('<h2>'+jbTitre.mustValidat+'</h2>');
		mailZone = $('<p></p>');
		zoneMustValid.append(mailZone);
		zoneMustValid.append('<p>'+jbMsg.mustValidat+'</p>');
		var lienClose = $('<a></a>').attr('href', 'javascript:;').html('Fermer');
		lienClose.click(function(){ hideZone(); });
		zoneMustValid.append(lienClose);
		zoneIdentification.append(zoneMustValid);

		zoneGetPass = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneGetPass.html('<h2>'+jbTitre.forgetPass+'</h2>');
		var zoneP = $('<p class="c"></p>');
		zoneGetPass.append(zoneP);
		var lien = $('<a></a>').attr('href', 'javascript:;').html('Recevoir votre mot de passe par e-mail.');
		lien.click(function(){
			if ($.cookie('identificationMail')){
				$.post(scriptAjax, {getPass: 1, mail: $.cookie('identificationMail')}, function(xml){
					if ($('errorNum', xml).text() == '0'){
						$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
						$('.email', zoneGetPassPost).html($.cookie('identificationMail'));
						zoneGetPassPost.css('display', 'block');
					}else{
						alert($('error', xml).text());
					}
				});
			}
		});
		zoneP.append(lien);
		var lienClose = $('<a></a>').attr('href', 'javascript:;').html('Fermer');
		lienClose.click(function(){ hideZone(); });
		zoneGetPass.append(lienClose);
		zoneIdentification.append(zoneGetPass);

		zoneGetPassPost = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneGetPassPost.html('<h2>'+jbTitre.forgetPassSubmit+'</h2>');
		var pmail = $('<p></p>').attr('class','email');
		zoneGetPassPost.append(pmail);
		var lienClose = $('<a></a>').attr('href', 'javascript:;').html('Fermer');
		lienClose.click(function(){ hideZone(); });
		zoneGetPassPost.append(lienClose);
		zoneIdentification.append(zoneGetPassPost);

		zoneCompteCree = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneCompteCree.html('<h2>'+jbTitre.accountCreated+'</h2>');
		var lienClose = $('<a></a>').attr('href', 'javascript:;').html('Fermer');
		lienClose.click(function(){ hideZone(); });
		zoneCompteCree.append(lienClose);
		zoneIdentification.append(zoneCompteCree);

		// --- AccountNeed --- 
		zoneAccountNeed = $('<div>').attr('class', 'subZone').css('display', 'none');
		zoneIdentification.prepend(zoneAccountNeed);
		zoneAccountNeed.html('<h1>'+jbTitre.accountNeed+'</h1>');
		var connexion = $('<a></a>').attr('href','#').html(jbTitre.accountNeedConnec).click(function(){
			$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
			zoneConnexion.show();
		});
		zoneAccountNeed.append($('<p></p>').attr('style','text-align: center').append(connexion));
		var creation = $('<a></a>').attr('href','#').html(jbTitre.accountNeedCreat).click(function(){
			$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
			zoneCreatAccount.show();
		});
		zoneAccountNeed.append($('<p></p>').attr('style','text-align: center').append(creation));
		var lienClose = $('<a></a>').attr('href', 'javascript:;').html('Fermer').attr('class', 'fermer');
		lienClose.click(function(){ hideZone(); });
		zoneAccountNeed.append(lienClose);

		$.extend(zoneIdentification, {
			showCreatAccount: function(a){
				if(a == 'valideAccount'){
					$.cookie('identificationCreatEnCours', '0');
					$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
					zoneCompteCree.show();
					zoneIdentificationBG.show();
					this.show();
				}else if ($.cookie('identificationCreatEnCours') == '1'){
					mailZone.html($.cookie('identificationMail'));
					$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
					zoneMustValid.show();
					zoneIdentificationBG.show();
					this.show();
				}else{
					$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
					zoneCreatAccount.show();
					zoneIdentificationBG.show();
					this.show();
				}
			},
			showIdentification: function(a){
				$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
				zoneConnexion.show();
				zoneIdentificationBG.show();
				this.show();
			},
			showAccountNeed: function(a){
				$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
				zoneAccountNeed.show();
				zoneIdentificationBG.show();
				this.show();
			},
			showForgetPass: function(a){
				$('div.subZone', zoneIdentification).each(function(){ $(this).hide(); });
				zoneForgetPass.show();
				zoneIdentificationBG.show();
				this.show();
			}
		});

		return zoneIdentification;
	};
})(jQuery);

var jbIdentification;
$(document).ready(function(){
	jbIdentification = $('body').jbzoneIdentification();
	$('.showIdentification').click(function(){jbIdentification.showIdentification();});
	$('.showCreatAccount').click(function(){jbIdentification.showCreatAccount();});

	$('.showAccountNeed').click(function(e){
		if ('0' == $.ajax({ url: scriptAjax+'?identified=1', async: false, dataType: 'text' }).responseText){
			destination = $(this).attr('href');
			jbIdentification.showAccountNeed();
			e.stopPropagation();
			return false;
		}
	});

	$('.showIdentification').show();
	$('.showCreatAccount').show();
	$('.showAccountNeed').show();

	if ($.cookie('identificationCreatEnCours') && $.cookie('identificationMail')){
		jbIdentification.validation_controle();
	}

});

