// JavaScript Document


function fixElement(element, message) {
	alert(message);
	element.focus();	
}

function verifica(form, diaActual, mesActual, anyoActual) {

	var passed = false;

	if (formulario.nombre.value == "") {
		fixElement(formulario.nombre, "Por favor, introduzca su nombre.");
	}
	else if(formulario.primer_apellido.value == ""){
		fixElement(formulario.primer_apellido, "Por favor, introduzca su primer apellido.");
	}
	else if(formulario.segundo_apellido.value == ""){
		fixElement(formulario.segundo_apellido, "Por favor, introduzca su segundo apellido.");
	}
	else if(formulario.dia.value>31){
		alert('Introduzca correctamente su día de nacimiento');	
	}
	else if(formulario.mes.value>12){
		alert('Introduzca correctamente su mes de nacimiento');	
	}
	else if(formulario.direccion.value == ""){
		fixElement(formulario.direccion, "Por favor, introduzca su dirección.");
	}	
	else if(formulario.cp.value == ""){
		fixElement(formulario.cp, "Por favor, introduzca su código postal.");
	}
	else if(formulario.poblacion.value == ""){
		fixElement(formulario.poblacion, "Por favor, introduzca su población.");
	}
	else if(formulario.provincia.value == ""){
		fixElement(formulario.provincia, "Por favor, introduzca su provincia.");
	}
	else if(formulario.nombre_bebe.value == ""){
		fixElement(formulario.nombre_bebe, "Por favor, introduzca el nombre del bebé.");
	}
	else if(formulario.dia_bebe.value == ""){
		fixElement(formulario.dia_bebe, "Por favor, introduzca el día de nacimiento del bebé.");
	}
	else if(formulario.mes_bebe.value == ""){
		fixElement(formulario.mes_bebe, "Por favor, introduzca el mes de nacimiento del bebé.");
	}
	else if(formulario.anio_bebe.value == ""){
		fixElement(formulario.anio_bebe, "Por favor, introduzca el año de nacimiento del bebé.");
	}else  {

	
		//COMPRUEBA LA FECHA DE NACIMIENTO
		// 1.- Comprueba que el año de nacimiento no sea mayor que el actual	
		if(formulario.anio.value.length > 0 || 
			formulario.mes.value.length > 0 ||
			formulario.dia.value.length > 0){
			
		if(formulario.anio.value>anyoActual || formulario.anio.value<1920){
			fixElement(formulario.anio, "Por favor, introduzca correctamente la fecha");
			return false;
		}		
		//2.- Comprueba que el mes de nacimiento no sea mayor que el actual siempre y cuando el año sea el actual		
		if(formulario.anio.value == anyoActual && formulario.mes.value > mesActual){
			fixElement(formulario.mes, "El mes de nacimiento introducido no puede ser mayor al mes actual.");
			return false;
		}
		//3.- Comprueba que el día corresponde con el número de días del mes introducido
		var elMes = formulario.mes.value;
		var meses = new Array(31, 28,31,30, 31,30, 31, 31, 30, 31, 30, 31);		
		if (Number(formulario.dia.value) > Number(meses[Number(elMes) - 1])){
			fixElement(formulario.dia, "El día de nacimiento introducido no puede ser mayor de "+meses[Number(elMes) - 1]+".");
			return false;
		}
		
		}
			
		//COMPRUEBA LA FECHA DEL BEBÉ		
		var numDiasTotal;
		mesActual=Number(mesActual);
		diaActual = Number(diaActual);
		
		var anio_introducido_bebe = Number(formulario.anio_bebe.value);				
		var mes_introducido_bebe  = Number(formulario.mes_bebe.value);
		var dia_introducido_bebe  = Number(formulario.dia_bebe.value);
		var anioActual2 = Number(anyoActual);
		
		// 1.- Comprueba que el año de nacimiento no sea mayor que el actual		
		if(anio_introducido_bebe>anioActual2){
		
			fixElement(formulario.anio_bebe,"Por favor, introduzca correctamente la fecha");
			return false;
			
		}else if(anio_introducido_bebe<anioActual2 - 2){
			fixElement(formulario.anio_bebe,"El bebé no puede ser mayor de 2 años");
			return false;
		}
		
		
		/*
		
		else if(anio_introducido_bebe != anioActual2) {			
		
			if (((mesActual==1)||(mesActual==2)||(mesActual==3)) && (calculaMesAnterior(mesActual - 3)<= mes_introducido_bebe) ){			
			
			//alert("Fecha correcta!");
			
			}else{			
				fixElement(formulario.dia_bebe,"El bebé no puede ser mayor de 3 meses");				
				return false;
			}		
		
		}else if(mes_introducido_bebe==mesActual){
		
			//alert("Fecha correcta!");			

		} else if ((mes_introducido_bebe>mesActual)&&(anio_introducido_bebe == anioActual2)){
		
			fixElement(formulario.mes_bebe,"Por favor, introduzca correctamente la fecha");
			return false;
		
		}
		
		
		else if(mes_introducido_bebe>=calculaMesAnterior(mesActual - 3)){
				
			//alert("Fecha correcta!");

		}else {
		
			fixElement(formulario.dia_bebe,"El bebé no puede ser mayor de 3 meses");
			return false;
		}
		
		*/

		if (formulario.mail.value != ""){
			//emailCheck(formulario.mail.value);
		
		// 031006 - Rubén Valverde - Comprobamos que el valor del mail es == al valor del mail2
			if (formulario.mail.value != formulario.mail2.value){
				
					alert ('Por favor, asegúrese de que su mail es correcto');
					return false;
				
				}else{
					
					emailCheck(formulario.mail.value);
					
				}
				
		/////////////////////////////////////////////////////////////////////////////////////////		
		
			
		}else{
			passed = true;
			registrarCliente();
		}
		
	}

	return passed;
}

function calculaMesAnterior(mes){

	//mes = mes -1;
	if(mes <= 0){					
		if (mes==0) mes=12;
		else if (mes==-1)	mes=11;
		else if (mes==-2)	mes=10;		
		
	}

	mes=Number(mes);
	return mes;
}

//REGISTRO
function registrarCliente(idioma) {
		//alert('terminado de revisar, se procede a enviar');
	document.getElementById("botEnviarCliente").disabled = true;
	formulario.submit();
	
	return true;
}




//ESTA FUNCIÓN LIMITA EL EMAIL
function emailCheck (emailStr) {
	
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("La entrada de e-mail parece ser incorrecta")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("El nombre de usuario parece no ser correcto.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Direccion IP no valida!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("El nombre de dominio parace no ser correcto.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("La direccion de correo debe acabar en 3 letras de dominio o 2 de un pais.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="Esta direccion es desconocida como IP!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
passed = true;
registrarCliente();
}





	