﻿function homeErrorMsg(v,n,t){
	var msj="Error de campo";
	if(n==1){msj=" El campo " + t + " no puede estar vacío";}
	if(n==2){msj=" El usuario ya existe";}
	if(n==3){msj=" El alias ya existe";}
	if(n==4){msj=" No ha aceptado las condiciones de uso";}
	if(n==5){msj=" Email incorrecto";}
	if(n==6){msj=" Sólo se permiten letras, números y guiones";}
	if(n==7){msj=" Seleccione una localidad";}
	if(n==8){msj=" Las contraseñas no coinciden";}
	if(n==9){msj=" Seleccione un destinatario";}
	if(n==10){msj=" Se ha producido un error inesperado, vuelva a intentarlo";}
	if(n==11){msj=" Contraseña: entre 4 y 20 caracteres a-z A-Z 0-9 ._-";}
	if(n==12){msj=" La contraseña actual no es correcta";}
	if(n==13){msj=" Seleccione un área de recorte";}
	if(n==14){msj=" El email no existe";}
	if(n==15){msj=" Seleccione una subcategoria";}
	if(n==16){msj=" Formato incorrecto";}
	if(n==17){msj=" Fecha incorrecta";}
	if(n==18){msj=" Debe seleccionar al menos un criterio";}
	if(n==19){msj=" Revise los datos";}
	$("#"+v+"-st").html("<span class=\"home_errortext\">"+msj+"</span>");
}
function homeCheckRegister(){
	cleanSt();
	$("#alias-st").html("");
	$("#pass-st").html("");
	$("#email-st").html("");
	$("#terms-st").html("");
	$("#finish-st").html("");
	mail=$("#email-field").val();
	pass=$("#password-field").val();
	alias=$("#alias-field").val();
	var expreg=/^[a-zA-Z0-9\-\_\.]{4,20}$/;
	if($("#terms-field").attr('checked')){terms="si";}else{terms="no";}
	if(mail!="" && pass.match(expreg) && alias!="" && terms=="si"){
		$("#finish-st").load("funciones/comprobaciones.php", {mails0:mail,passs0:pass,aliass0:alias} );
	}else{
		if(alias==""){$("#alias-field").focus(); homeErrorMsg("alias",1, "Nombre público")}
		if(!pass.match(expreg)){$("#password-field").focus(); homeErrorMsg("pass",11)}
		if(mail==""){$("#email-field").focus(); homeErrorMsg("email",1, "Correo electrónico")}
		if(terms=="no"){homeErrorMsg("terms",4)}
	}
	return false;
}

function homePrevAlias(v){
	var expregt=/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_]*[a-zA-Z0-9]{1}$/;
	if(v.match(expregt)){$("#alias-prev").html("<br>&nbsp;&nbsp;&nbsp;&nbsp;<strong>Tu dirección:</strong> http://www.negofeed.com/<strong>"+v+"</strong>");}else{$("#alias-prev").html("");}	
}

//$(function(){$("#alias-field").keyup(function(){homePrevAlias($(this).val())})});


function homeRegisterScreenHelper(showHide, fieldToHelp) {
	var IE7 = (navigator.appVersion.indexOf("MSIE 7")==-1) ? false : true;
	var regMain = (_registered == true) ? document.getElementById('home_register_success') : document.getElementById('home_register');
	var regHelp = document.getElementById('home_register_helper');
	var regBack = document.getElementById('home_darkbg');
	var regClose = document.getElementById('home_darkbg_close');
	if (IE7 == true) alert('Atenci&oacute: Su versi&oacute;n de Internet Explorer 7 presenta problemas con el proceso de registro');
	switch(showHide) {
		case 0:
			regMain.style.display='none';
			regBack.style.display='none';
			regHelp.style.display='none';
			regBack.appendChild(regClose);
			break;
		case 1:
			regMain.style.display='block';
			regBack.style.display='block';
			regHelp.style.display='block';
			regMain.appendChild(regClose);
			regClose.style.top='-18px';
			regClose.style.right='25px';
			//regFocus(document.getElementById('form_register'));
			break;
	}
	if (fieldToHelp != null) helpMe(fieldToHelp);
}

function helpMe(fieldToHelp) {

	switch(fieldToHelp.id) {
		case 'email-field':
			$("#helper_title").html('Correo electrónico');
			$("#helper_subtitle").html('Indícanos tu cuenta de correo electrónico');
			$("#helper_explain").html('Debe ser una cuenta de correo electrónico existente (ejemplo: <b>tunombre@hotmail.com</b>). Esa dirección será tu identificador principal con el cual podrás iniciar sesión en Negofeed. Enviaremos un mensaje de confirmación a tu cuenta de correo para verificar tu identidad y confirmar el proceso de registro.');
			break;
		case 'password-field':
			$("#helper_title").html('Contraseña');
			$("#helper_subtitle").html('Elige una contraseña');
			$("#helper_explain").html('Escribe una contraseña de <b>entre 4 y 20 caracteres</b>. La contraseña debe ser algo fácil de recordar, y difícil de adivinar. Procura evitar contraseñas como tu DNI, tu fecha de nacimiento, aniversarios, o el nombre de tu pareja. Una buena contraseña debería contener mayúsculas, minúsculas y algún número o signo de puntuación.');
			break;
		case 'alias-field':
			$("#helper_title").html('Nombre público');
			$("#helper_subtitle").html('Tu identificador único en Negofeed');
			$("#helper_explain").html('Elige un nombre público para tu nueva dirección web. Puede ser el nombre de tu empresa, tu nombre o apellidos. Es importante que este nombre sea <b>una única palabra</b>, sin espacios ni signos de puntuación. Tampoco se admiten caracteres especiales como la eñe o vocales con tilde.<br><br><u>Ejemplo</u>: <b>josemartinez</b><br> <u>Resultado</u>: http://www.negofeed.com/<b>josemartinez</b>');
			break;
		case 'terms-field':
			$("#helper_title").html('Términos y condiciones');
			$("#helper_subtitle").html('Lee y acepta los términos y condiciones de uso');
			$("#helper_explain").html('Debes leer y aceptar los términos y condiciones de uso para registrarte en Negofeed. En este texto te informamos de tus derechos y deberes, la seguridad de tus datos, y demás disposiciones legales.');
			break;
	}
	//if (timerHelp != null) clearTimeout(timerHelp);
}

function regFocus(aForm) {
	var fields = Array();
	for (i=0; i<aForm.elements.length; i++) {
		aField = aForm.elements[i];
		if ((aField.type == 'text') || (aField.type == 'password')) {
			if (homeRegisterCheckField(aField) != true) {
				if (aField.value == '') aField.focus();
				timerHelp = setTimeout("helpMe(aField)", 500);
				break;
			}
		}
		//alert('Id del campo: ' + aForm.elements[i].id + "\n" + 'Tipo: ' + aForm.elements[i].type);
	}
}

function homeRegisterCheckField(field) {
	String.prototype.trim = function () {
		return this.replace(/^\s*/, "").replace(/\s*$/, "");
	}
	switch(field.id) {
		case 'email-field':
			//var field = document.getElementById('email-field');
			//var email = $("#email-field").val();
			var email = field.value.trim();
			if (email != '') {
				if (checkEmail(email) == false) {field.style.background = '#ffc9c9'; return false; break;}
			}
			field.style.background = '#fff'; //'#d7fbdb';
			if (email == '') return false;
			else return true;
			break;
		case 'password-field':
			//var field = document.getElementById('password-field');
			var password = field.value.trim();
			if (password != '') {
				if ((password.length < 4) || (password.length > 20)) {field.style.background = '#ffc9c9'; return false; break;}
			}
			field.style.background = '#fff';
			if (password == '') return false;
			else return true;
			break;
		case 'alias-field':
			//var field = document.getElementById('alias-field');
			var alias = field.value;
			if (alias != '') {
				var expregt=/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_]*[a-zA-Z0-9]{1}$/;
				if (!(alias.match(expregt))) {field.style.background = '#ffc9c9'; return false; break;}
			}
			field.style.background = '#fff';
			if (alias == '') return false;
			else return true;
			break;
		case 'terms-field':
			//var field = document.getElementById('terms-field');
			if (field.checked == false) {return false; break;}
			else return true;
			break;
			//if($("#terms-field").attr('checked')){terms="si";}else{terms="no";}
	}
}

function homeRegisterShowErrors(str) {
	$("#helper_title").html('<font color="red">Error en el formulario</font>');
	$("#helper_subtitle").html('Hay algún error en los datos introducidos');
	$("#helper_explain").html('Por favor, corrige lo siguiente:<br><ul style="list-style-type:circle; margin-top:1em;">'+str+'</ul>');
}
function homeRegisterShowSuccess(str) {
	$("#helper_title").html('<font color="green">Solicitud de registro correcta</font>');
	$("#helper_subtitle").html('La solicitud de registro se ha completado correctamente');
	$("#helper_explain").html('Gracias por registrarte en Negofeed. Ahora debes tener en cuenta:<br><ul style="list-style-type:circle; margin-top:1em;">'+str+'</ul>');
}

function homeRegisterCheckForm(){
	var errors = false;
	var str = '';
	var field = document.getElementById('email-field');
	if (homeRegisterCheckField(field) != true) {
		errors = true;
		field.style.background = '#ffc9c9';
		str = str + '<li style="margin-left:3em; margin-bottom:8px;">Correo electrónico: debe ser una dirección de email válida</li>';
	}
	field = document.getElementById('password-field');
	if (homeRegisterCheckField(field) != true) {
		errors = true;
		field.style.background = '#ffc9c9';
		str = str + '<li style="margin-left:3em; margin-bottom:8px;">Contraseña: debe ser una palabra entre 4 y 20 caracteres</li>';
	}
	field = document.getElementById('alias-field');
	if (homeRegisterCheckField(field) != true) {
		errors = true;
		field.style.background = '#ffc9c9';
		str = str + '<li style="margin-left:3em; margin-bottom:8px;">Nombre público: debe ser una palabra única, sin espacios ni signos de puntuación</li>';
	}
	field = document.getElementById('terms-field');
	if (homeRegisterCheckField(field) != true) {
		errors = true;
		str = str + '<li style="margin-left:3em; margin-bottom:8px;">Términos y condiciones de uso: debes aceptarlos para continuar con el registro</li>';
	}
		
	if (errors == true) {
		homeRegisterShowErrors(str);
	}	else {
		mail=$("#email-field").val();
		//$("#finish-st").load("funciones/comprobaciones.php", {checkmail:mail});
		jQuery.post("funciones/comprobaciones.php", {checkmail:mail}, function(response, status, xhr){
			var errors = false;
			switch (response) {
			case '1':
				errors = true;
				str = str + '<li style="margin-left:3em; margin-bottom:8px;">Correo electrónico: debe ser una dirección de email válida</li>';
				break;
			case '2':
				errors = true;
				str = str + '<li style="margin-left:3em; margin-bottom:8px;">Correo electrónico: la dirección de correo <b>'+mail+'</b> ya está registrada. Si esta es tu dirección de correo y has olvidado la contraseña, haz click en <a href="registro/recordar">recordar contraseña</a>.</li>';
				break;
			}
			if (errors == true) {
				homeRegisterShowErrors(str);
				document.getElementById('email-field').style.background = '#ffc9c9';
			}
			else hash = response;
			alias = $("#alias-field").val();
			jQuery.post("funciones/comprobaciones.php", {checkalias:alias}, function(response, status, xhr){
				var errors = false;
				switch (response) {
				case '1':
					errors = true;
					str = str + '<li style="margin-left:3em; margin-bottom:8px;">Nombre público: debe ser una palabra única, sin espacios ni signos de puntuación</li>';
					break;
				case '2':
					errors = true;
					str = str + '<li style="margin-left:3em; margin-bottom:8px;">Nombre público: el nombre <b>'+alias+'</b> ya está ocupado. Por favor, elije otro.</li>';
					break;
				}
				if (errors == true) {
					homeRegisterShowErrors(str);
					document.getElementById('alias-field').style.background = '#ffc9c9';
				}
				else {
					//alert(hash);
					pass = $("#password-field").val();
					jQuery.post("funciones/comprobaciones.php", {doregister:hash, mail:mail, pass:pass, alias:alias}, function(response, status, xhr){
						switch (response) {
						case '1':
							_registered = true;
							str = '<li style="margin-left:3em; margin-bottom:8px;">Hemos enviado un mensaje a tu dirección de corrreo <b>'+mail+'</b>. Por favor, abre tu correo y localiza el mensaje.</li>';
							str = str + '<li style="margin-left:3em; margin-bottom:8px;">En dicho mensaje encontrarás un enlace sobre el que debes hacer click para verificar tu identidad.</li>';
							homeRegisterShowSuccess(str);
							document.getElementById('home_register').style.display = 'none';
							document.getElementById('home_register_success').style.display = 'block';
							document.getElementById('home_register_success').appendChild(document.getElementById('home_darkbg_close'));
							var ind=mail.indexOf("@");
							var my_slice=mail.slice((ind+1),mail.length);
							document.getElementById('othermailproviders').href = 'http://www.google.es/search?hl=es&q=webmail+'+my_slice+'';
							break;
						default:
							str = '<li style="margin-left:3em; margin-bottom:8px;"><b>Error no especificado:</b> esto puede ser debido a un fallo en el procesamiento de datos.</li>';
							str = str + '<li style="margin-left:3em; margin-bottom:8px;">Puedes ponerte en contacto con el departamento de soporte técnico o con tu responsable comercial.</li>';
							homeRegisterShowErrors(str);
							break;
						}
					});
				}
			});
		});

	}
	
	
	
	return false;
	cleanSt();
	$("#alias-st").html("");
	$("#pass-st").html("");
	$("#email-st").html("");
	$("#terms-st").html("");
	$("#finish-st").html("");
	mail=$("#email-field").val();
	pass=$("#password-field").val();
	alias=$("#alias-field").val();
	var expreg=/^[a-zA-Z0-9\-\_\.]{4,20}$/;
	if($("#terms-field").attr('checked')){terms="si";}else{terms="no";}
	if(mail!="" && pass.match(expreg) && alias!="" && terms=="si"){
		$("#finish-st").load("funciones/comprobaciones.php", {mails0:mail,passs0:pass,aliass0:alias} );
	}else{
		if(alias==""){$("#alias-field").focus(); homeErrorMsg("alias",1, "Nombre público")}
		if(!pass.match(expreg)){$("#password-field").focus(); homeErrorMsg("pass",11)}
		if(mail==""){$("#email-field").focus(); homeErrorMsg("email",1, "Correo electrónico")}
		if(terms=="no"){homeErrorMsg("terms",4)}
	}
	return false;
}

function checkEmail(inputvalue){	
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	if(pattern.test(inputvalue)){         
		return true; 
	}else{   
		return false; 
	}
}


$(function(){$("#email-field").focus(function(){homeRegisterScreenHelper(1, this)})});
$(function(){$("#password-field").focus(function(){homeRegisterScreenHelper(1, this)})});
$(function(){$("#alias-field").focus(function(){homeRegisterScreenHelper(1, this)})});
$(function(){$("#terms-field").focus(function(){homeRegisterScreenHelper(1, this)})});
$(function(){$("#register-button").click(function(){homeRegisterScreenHelper(1, null)})});//onclick="document.getElementById('home_register_st').style.visibility='visible';"
//$(function(){$("#email-field").blur(function(){homeRegisterScreenHelper(0)})});
$(function(){$("#email-field").blur(function(){homeRegisterCheckField(this)})});
$(function(){$("#password-field").blur(function(){homeRegisterCheckField(this)})});
$(function(){$("#alias-field").blur(function(){homeRegisterCheckField(this)})});
$(function(){$("#alias-field").keyup(function(){homePrevAlias($(this).val()); homeRegisterCheckField('alias');})});
var _registered = false;


///////////////////////////// });

function showLoginFormNOIE() {
	$("#dialog-modal").load("funciones/comprobacionesV2.php", {loadLoginForm:'True'}, function(){
		openModalV2("Inicio de sesión");
	});
}

function showLoginForm() {
        $("#dialog-modal").load("funciones/comprobacionesV2.php?_=" + (new Date()).getTime(), {loadLoginForm:'True'}, function(){
		openModalV2("Inicio de sesión");
        });
}


$(document).ready(function() {
		/*
    $('#album').iphoneSlide({
			handler: "#paging",
			pageHandler: ".page",
			direction: "horizontal",
			easing: "easeOutBounce"
		});
    
    $('.jcarousel').jcarousel({
        // Configuration goes here
				auto: 300,  
				visible:5,
				speed: 1500,
    });
    */
		//showLoginForm();

    
});

