// Solución para evitar el uso del target en XHTML
// Se cargarán en una ventana externa aquellos enlaces con el atributo "rel" a "external"
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;

// TPV
function cargar_tpv()
{
	//vent=window.open('','tpv','width=800,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
	document.forms[0].submit();
}

function checkTabla()
{
	// Comprobaciones para la tabla de inscripciones.
	return true;
}
function confirmar(mensaje)
{
	 return confirm(mensaje);
}
function checkForm()
{
	var plant;
	//var form = document.datosusuario;
	var form = document.forms[0];
	
	var login      = form.login.value;
	var nombre     = form.nombre.value;
	var apellido1  = form.apellido1.value;
	var apellido2  = form.apellido2.value;
	var direccion  = form.direccion.value;
	var poblacion  = form.poblacion.value;
	var cp         = form.cp.value;
	var telefono   = form.telefono.value;
	var nif        = form.nif.value;
	var fecha      = form.fecha.value;
	var sexo       = form.sexo.selectedIndex;
	var vsexo      = form.sexo.options[sexo].text;
	//var aebdc      = form.aebdc.value;
	var entrenador = form.entrenador.value; // única opcional
	var idcatsta   = form.idcatsta.selectedIndex;
	var idcatlat   = form.idcatlat.selectedIndex;
	var vidcatsta  = form.idcatsta.options[idcatsta].text;
	var vidcatlat  = form.idcatsta.options[idcatlat].text;
	var mail       = form.mail.value;

	if (login == "")
	{
		form.login.focus();
		form.login.select();
		alert ("Por favor, introduce el nombre de usuario del competidor para identificarte en el sistema.");
		return false;
	}
	else
	{
		// Solo admitimos dígitos y letras. Después pasaremos todo a minúsculas
	  plant=/^([0-9a-zA-Z])+$/i
	  if (!plant.test(login))
	  {
			form.login.focus();
			form.login.select();
			alert("Por favor, introduce un nombre de usuario válido (solo dígitos y/o letras).");
			return false;
	  }
	}
	
	if (nombre == "")
	{
		form.nombre.focus();
		form.nombre.select();
		alert ("Por favor, introduce tu nombre.");
		return false;
	}
	
	if (apellido1 == "")
	{
		form.apellido1.focus();
		form.apellido1.select();
		alert ("Por favor, introduce tu primer apellido.");
		return false;
	}
	
	if (apellido2 == "")
	{
		form.apellido2.focus();
		form.apellido2.select();
		alert ("Por favor, introduce tu segundo apellido. Si eres extrangero, introduce un guión (-).");
		return false;
	}
	
	if (direccion == "")
	{
		form.direccion.focus();
		form.direccion.select();
		alert ("Por favor, introduce la dirección postal.");
		return false;
	}
	
	if (poblacion == "")
	{
		form.poblacion.focus();
		form.poblacion.select();
		alert ("Por favor, introduce la población.");
		return false;
	}
	
	if (cp == "")
	{
		form.cp.focus();
		form.cp.select();
		alert ("Por favor, introduce un código postal.");
		return false;
	}
	else
	{
	  plant=/^([0-9])+$/i
	  if (!plant.test(cp))
	  {
			form.cp.focus();
			form.cp.select();
			alert("Por favor, introduce un código postal correcto.");
			return false;
	  }	
	}
	
  if (telefono == "")
  {
		form.telefono.focus();
		form.telefono.select();
		alert("Por favor, introduce el número de teléfono.");
		return false;
  }
  
  if (fecha == "")
  {
		form.fecha.focus();
		form.fecha.select();
		alert("Por favor, introduce una fecha de nacimiento correcta (dd/mm/aaaa).");
		return false;
  }
  else
  {
	  plant=/^([0-9])+\/([0-9])+\/([0-9])+$/i
	  if (!plant.test(fecha))
	  {
			form.fecha.focus();
			form.fecha.select();
			alert("Por favor, introduce una fecha correcta (dd/mm/aaaa).");
			return false;
	  }
  }
  
  if (nif == "")
  {
	  var edad = getedad(fecha);
  	// Menores de 14, permitimos DNI vacío
	  if (edad >= 14)
	  {
			form.nif.focus();
			form.nif.select();
			alert("Por favor, introduce el NIF o NIE (XXXXXXXXL).");
			return false;
		}
	}
	else
	{
		// Si introducen un DNI, tiene que ser válido independientemente de la edad
 		if (!isnif(nif))
 		{
			form.nif.focus();
			form.nif.select();
 			alert ("Por favor, introduce un NIF (o NIE) válido. Formato: XXXXXXXXL (dígitos y letra en mayúscula sin espacios ni guiones)");
 			return false;
 		}
	}
	  	
  if (vsexo == "Sexo")
  {
  	form.sexo.focus();
  	//form.sexo.select();
  	alert("Por favor, indica el sexo del competidor.");
  	return false;
  }
  
  //if (aebdc == "")
  //{
	//	form.aebdc.focus();
	//	form.aebdc.select();
	//	alert("Por favor, introduce el número de AEBDC.");
	//	return false;
  //} 
	//else
	//{
	//  plant=/^([0-9])+$/i
	//  if (!plant.test(aebdc))
	//  {
	//		form.aebdc.focus();
	//		form.aebdc.select();
	//		alert("Por favor, introduce un número de AEBDC correcto (dígitos).");
	//		return false;
	//  }	
	//}
	
  //if (entrenador==""){
  //alert("Por favor, introduce el nombre de tu entrenador");
  // return false;
  //} 
  
  if (vidcatsta == "Categoría")
  {
  	form.idcatsta.focus();
  	//form.sexo.select();
  	alert("Por favor, selecciona tu categoría de Standard.");
  	return false;
  }
  
  if (idcatlat == "Categoría")
  {
  	form.idcatlat.focus();
  	//form.sexo.select();
  	alert("Por favor, selecciona tu categoría de Latino.");
  	return false;
  }

	if (mail == "")
	{
		form.mail.focus();
		form.mail.select();
		alert("Por favor, introduce tu dirección de correo electrónico.");
		return false;
  }
  else
  {
		//plant=/(^\w+)(@{1})([\w\.-]+$)/i
		//if (!plant.test(mail))
		if (!is_valid_email(mail))
		{
			form.mail.focus();
			form.mail.select();
			alert("Por favor, introduce un e-mail correcto.");
			return false;
		}
	}
	
	// Si hemos llegado hasta aquí es que no ha fallado nada
	return true;
}

/**
 * This  function thus  simply makes  sure the  email address  has one  (@),
 * atleast one (.). It also  makes sure that there are  no spaces, extra '@'s or a
 * (.) just before or after the @. It also makes sure that there is atleast one (.)
 * after the @.
 */
 
function is_valid_email(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    //alert("Invalid E-mail ID")
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    //alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    //alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    //alert("Invalid E-mail ID")
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    //alert("Invalid E-mail ID")
	    return false
	 }

	 return true					
}

function isnif(dni) {
  numero = dni.substr(0,dni.length-1);
  let = dni.substr(dni.length-1,1);
  numero = numero % 23;
  letra='TRWAGMYFPDXBNJZSQVHLCKET';
  letra=letra.substring(numero,numero+1);
  if (letra!=let)
  	return false;
  else
  	return true;
}

function getedad (fecha) {
	var hoy=new Date();
	var array_fecha = fecha.split("/");
	
  //compruebo que los ano, mes, dia son correctos
  var ano
  ano = parseInt(array_fecha[2]);
  if (isNaN(ano))
     return false;

  var mes
  mes = parseInt(array_fecha[1]);
  if (isNaN(mes))
     return false;

  var dia
  dia = parseInt(array_fecha[0]);
  if (isNaN(dia))
     return false;

  //si el año de la fecha que recibo solo tiene 2 cifras hay que cambiarlo a 4
  if (ano<=99)
     ano +=1900;

  //resto los años de las dos fechas
  edad=hoy.getYear()- ano - 1; //-1 porque no se si ha cumplido años ya este año

  //si resto los meses y me da menor que 0 entonces no ha cumplido años. Si da mayor si ha cumplido
  if (hoy.getMonth() + 1 - mes < 0) //+ 1 porque los meses empiezan en 0
     return edad;
  if (hoy.getMonth() + 1 - mes > 0)
     return edad+1;

  //entonces es que eran iguales. miro los dias
  //si resto los dias y me da menor que 0 entonces no ha cumplido años. Si da mayor o igual si ha cumplido
  if (hoy.getUTCDate() - dia >= 0)
     return edad + 1; 	
}