// JavaScript Document
var contador = 0;

//funcion para validar formulario de registro paso 1 (home)
function validadorRegistro() 
{
  respuesta = cleanValidator.init({ 
 	    	  	formId: 'registroFormM', 
			  	newLine: '<br>', 
			  	inputColors: ['#FFFFFF', '#CCCCCC'], 
			  	errorColors: ['#FFFF99', '#CCCCCC'],
				isEmail: ['emailM'], 
			  	isEmailName: ['Correo Electr\u00F3nico'],
			  	isRequired: ['cpostalM'], 
			  	isRequiredName: ['C\u00F3digo Postal'],
				isCodigoPostal: ['cpostalM'],
				isCodigoPostalName: ['C\u00F3digo Postal']
		});
  if(respuesta == true)
  {
	if(document.getElementById("cpostalM").value == "código postal")
	{
	  coolMessage("error", feedBack("@@305@@","c\u00F3digo postal"));
	}
	else
	{
      if(document.getElementById("clausula").checked)
	  {
	   var emailenc = encriptar(document.getElementById("emailM").value);
	   $.ajax({
  		type: "POST",
		url: "registro_valemail.php",
		data: "email="+encodeURIComponent(emailenc),
		success: function(msg){
			if(msg.search(':ERROR@@')!=-1)
			{
			  coolMessage("error", feedBack(msg));
			}
			else
			{
			  $.ajax({
  				type: "POST",
				url: "registro_valcpostal.php",
				data: "codigoPostal="+encodeURIComponent(document.getElementById("cpostalM").value),
		        success: function(msg){
					if(msg.search('@@')!=-1)
					{
						var datos = msg.split("@@");
						document.getElementById("pais").value = datos[0];
						document.getElementById("comunidad").value = datos[1];
						document.getElementById("provincia").value = datos[2];
			  			document.getElementById("email").value = emailenc;
			  			document.getElementById("cpostal").value = document.getElementById("cpostalM").value;
	          			$("#registroForm").submit();
					}
					else
					{ 
			  		  if(msg == "2")
					  {
						abrirPopMensaje("registro_seleccionar_pais.php", true, 470, 220);
					  }
					  else
					  {
						if(msg == "0")
						{
						  coolMessage("error", feedBack("@@301@@"));	
						}
						else
						{
						  if(msg == "3")
						  {
						    coolMessage("error", feedBack("@@305@@","c\u00F3digo postal"));	
						  }
						}
					  }
					}
	 			}
       		  });   	
			}
	 	}
       });   
	 }
	  else
	  {
	    coolMessage('error', feedBack("@@342@@"));
	  }
	}
  }
}

//funcion para quitar los textos informativos que aparecen en los campos del formulario
function quitarTxtInformativo(campo)
{
  campo.value = "";
  campo.onfocus = "";
}

//funcion para validar que se haya seleccionado un pais en el pop del primer paso de registro
function validarPais()
{
  pais = document.getElementById("selPais").value;
	
  if(pais == 0)
  { 
	window.top.coolMessage("error", feedBack("@@305@@","pais"));	
  }
  else
  {
	$.ajax({
  		type: "POST",
		url: "registro_guardar_pais.php",
		data: "pais="+pais,
		success: function(msg){
			if(msg.search('ERROR')!=-1)
			{
			  window.top.coolMessage("error", feedBack("@@305@@","pais"));
			}
			else
			{
			  window.top.cerrarPopMensaje();
			}
		}
	});
  }
}

//funcion para quitar los textos informativos que aparecen en los campos del formulario
function quitarTxtInformativoP2()
{
  if(contador == 0)
  {
	  document.getElementById("nombre").value = "";
	  document.getElementById("apellido").value = "";
	  contador++;
  }  
}

//funcion para validar formulario de registro paso 2 (registro_paso2)
function validadorRegistroPaso2(tipo) 
{
  respuesta = cleanValidator.init({ 
     	  	  formId: 'registro2FormM', 
			  newLine: '<br>', 
			  inputColors: ['#FFFFFF', '#CCCCCC'], 
			  errorColors: ['#FFFF99', '#CCCCCC'],
			  isRequired: ['nombreM', 'apellidoM', 'passwordM'], 
			  isRequiredName: ['Nombre', 'Apellido', 'Contrase\u00F1a'],
			  isEmail: ['emailM'], 
			  isEmailName: ['Correo Electr\u00F3nico']
  });
  
  if(respuesta == true)
  {
	if(document.getElementById("clausula").checked)
	{
	  var emailenc = encriptar(document.getElementById("emailM").value);
	  $.ajax({
  	  type: "POST",
	  url: "registro_valemail.php",
	  data: "email="+encodeURIComponent(emailenc),
	  success: function(msg){
	  	if(msg.search(':ERROR@@')!=-1)
	  	{
			window.top.coolMessage("error", feedBack(msg));
	  	}
	 	else
	  	{
		  if(menorEdadVariable(parseInt(document.getElementById("diaM").value), parseInt(document.getElementById("mesM").value) + 1, parseInt(document.getElementById("anioM").value),14))
		  {
			 window.top.coolMessage("error", feedBack("@@344@@")); 
		  }
		  else
		  {
			document.getElementById("nombre").value = encriptar(document.getElementById("nombreM").value);
		    document.getElementById("apellido").value = encriptar(document.getElementById("apellidoM").value);
		    document.getElementById("password").value = encriptar(document.getElementById("passwordM").value);	
		    document.getElementById("email").value = emailenc;
		    document.getElementById("dia").value = document.getElementById("diaM").value;
		    document.getElementById("mes").value = document.getElementById("mesM").value;
		    document.getElementById("anio").value = document.getElementById("anioM").value;
		  
		    if(tipo == 1)
		    {
			  if(!menorEdadVariable(parseInt(document.getElementById("dia").value), parseInt(document.getElementById("mes").value) + 1, parseInt(document.getElementById("anio").value),18))	
		      {
			    document.getElementById("esMen").value = 0;
			  }
			  else
			    document.getElementById("esMen").value = 1;  
			  
			  document.getElementById("registro2Form").action = "registro_pasoafiliados.php";
		    }
		    else
		    {
			  if(!menorEdadVariable(parseInt(document.getElementById("dia").value), parseInt(document.getElementById("mes").value) + 1, parseInt(document.getElementById("anio").value),18))	
		      {	
		        document.getElementById("registro2Form").action = "registro_paso3.php";
		      }
		      else
		      {	
			    document.getElementById("registro2Form").action = "registro_paso2_1.php";
		      }
		    }
		  
	        document.getElementById("registro2Form").submit();
		  }
	  	}
	  }
      });   
	}
	else
	{
	  coolMessage('error', feedBack("@@323@@"));
    }
  }
}

function validadorRegistroAfiliados() 
{
  respuesta = cleanValidator.init({ 
     	  	  formId: 'registroAfFormM', 
			  newLine: '<br>', 
			  inputColors: ['#FFFFFF', '#CCCCCC'], 
			  errorColors: ['#FFFF99', '#CCCCCC'],
			  isDNI: ['dniM'],
			  isDNIName: ['D.N.I.']
  });
  
  if(respuesta == true)
  {
	if(document.getElementById("clausula").checked)
	{
	  document.getElementById("dni").value = encriptar(document.getElementById("dniM").value);	
	  document.getElementById("movil").value = document.getElementById("movilM").value;
	  
	  if(document.getElementById("verMen").value == 0)	
	  {	
	    document.getElementById("registroAfForm").action = "registro_paso3.php";
	  }
	  else
	  {
	    document.getElementById("registroAfForm").action = "registro_paso2_1.php";
	  }	
	  
	  document.getElementById("registroAfForm").submit();
	}
	else
	{
	  coolMessage('error', feedBack("@@323@@"));
    }
  }
}


function menorEdad(dia,mes,anio)
{
  miFechaActual = new Date();
  anioActual = miFechaActual.getFullYear();
  
  diferenciaAnios = anioActual - anio;
  
  if(diferenciaAnios > 14)
  {
	  return false;
  }
  else
  {
	if(diferenciaAnios < 14)
	{
	   return true;
	}
	else
	{
		mesActual = parseInt(miFechaActual.getMonth()) + 1;
		if(mesActual < mes)
		{
			return true;
		}
		else
		{
			if(mesActual > mes)
			{
				return false;
			}
			else
			{
				diaActual = miFechaActual.getDate();
				if(diaActual < dia)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
	}
  }
}


function menorEdadVariable(dia,mes,anio,edadMin)
{
  miFechaActual = new Date();
  anioActual = miFechaActual.getFullYear();
  
  diferenciaAnios = anioActual - anio;
  
  if(diferenciaAnios > edadMin)
  {
	  return false;
  }
  else
  {
	if(diferenciaAnios < edadMin)
	{
	   return true;
	}
	else
	{
		mesActual = parseInt(miFechaActual.getMonth()) + 1;
		if(mesActual < mes)
		{
			return true;
		}
		else
		{
			if(mesActual > mes)
			{
				return false;
			}
			else
			{
				diaActual = miFechaActual.getDate();
				if(diaActual < dia)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
	}
  }
}

//funcion para validar formulario de registro paso 3 (registro_paso3)
function validadorRegistroPaso3() 
{
  respuesta = cleanValidator.init({ 
 	    	  	formId: 'registro3Form', 
			  	newLine: '<br>', 
			  	inputColors: ['#FFFFFF', '#CCCCCC'], 
			  	errorColors: ['#FFFF99', '#CCCCCC'],
				isMultiImg: ['foto'], 
			  	isMultiImgName: ['Foto']
		});
  if(respuesta == true)
  {
     if(document.getElementById("clausula").checked)
	 {
	   $("#registro3Form").submit();
	 }
	 else
	 {
	   coolMessage('error', feedBack("@@323@@"));
	 }
  }
}

//funcion para validar formulario donde se insertar los emails de contactos a invitar
function validarCorreos()
{
  var lista = document.getElementById("listaContactos").value
  if(lista!="")
  {
	var listado = lista.split(",");			
	for (i=0;i<listado.length;i++)
	{
	  if(isEmail(listado[i])==false)
	  {
		coolMessage('error', feedBack("@@327@@"));
		return false;
	  }	
	}
	document.getElementById("registro4Form").submit();
  }
  else
  {
	coolMessage('error', feedBack("@@328@@"));
  }	
}

//funcion para quitar los textos informativos que aparecen en los campos del formulario
function quitarTxtInformativoP4()
{
  if(contador == 0)
  {
	  document.getElementById("listaContactos").value = "";
	  contador++;
  }  
}

//funcion para quitar los textos informativos que aparecen en los campos del formulario
function quitarTxtInformativoP4_1()
{
  if(contador == 0)
  {
	document.getElementById("email").value = "";
	contador++;
  }  
}

//funcion para validar formulario de registro paso 4_1 (registro_paso4_1)
function validadorRegistroPaso4_1() 
{
  respuesta = cleanValidator.init({ 
 	    	  	formId: 'registro4_1FormM', 
			  	newLine: '<br>', 
			  	inputColors: ['#FFFFFF', '#CCCCCC'], 
			  	errorColors: ['#FFFF99', '#CCCCCC'],
				isEmail: ['emailM'], 
			  	isEmailName: ['Correo Electr\u00F3nico'],
			  	isRequired: ['claveM'], 
			  	isRequiredName: ['Contrase\u00F1a']
		});
  if(respuesta == true)
  {
    if(document.getElementById("servicioM").value != "")
	{
	  var emailenc = encriptar(document.getElementById("emailM").value);
	  var claveenc = encriptar(document.getElementById("claveM").value);
	  document.getElementById("email").value = emailenc;
	  document.getElementById("clave").value = claveenc;
	  document.getElementById("servicio").value = document.getElementById("servicioM").value;
	  $("#registro4_1Form").submit();
	}
	else
	{
	  coolMessage('error', feedBack("@@334@@"));
	}
  }
}

//funcion para validar que se haya seleccionado algún contacto para enviar la invitacion
function enviarInvitaciones()
{
  var cont =0;
  var lista = "";
  $("#registro4_2Form").find("input[@type$='checkbox']").each(function(){
    if(this.checked)
	{
      cont++;
	}
  });
	   
  if(cont >=1)
  {				
    $("#registro4_2Form").submit();
  }
  else if(cont==0)
  {
    coolMessage('error', feedBack("@@330@@"));
    return false;				
  }
}

//funcion en actualiza la imagen del servicio seleccionado por el usuario
function cambiarServicio()
{
  var serv = document.getElementById("servicioM").value;	
  var imagen = document.getElementById("imgServicio");
  
  imagen.src = "img/correos/"+serv+"2.jpg";
}

//funcion para quitar los textos informativos que aparecen en los campos del formulario
function quitarTxtInformativoP6()
{
  if(contador == 0)
  {
	  document.getElementById("estado").value = "";
	  contador++;
  }  
}

//Funcion para actualizar el estado del usuario Paso 6
function cambiarEstadoRegistro()
{
  var vars = $("#registro6Form").serialize();
  var contenedor = document.getElementById("estadoUsuario");
  
  $.ajax({
  	type: "POST",
	url: "registro_estado_guardar.php",
	data: vars,
	beforeSend:function(){ 
	   contenedor.innerHTML = '<img src="img/ajax-loader.gif">';
	}, 
	success: function(msg){
		if(msg.search(':ERROR@@')!=-1)
		{
	  		coolMessage("error", feedBack(msg));
		}
		else
		{
	  					
			$("#auxEstado").html(document.getElementById("estado").value);
			$("#estadoUsuario").text($("#auxEstado").text());
			
	  		document.getElementById("estado").value = "¿Qué estás haciendo ahora?";
		}
	}
  });   
}
