// Script general de validación de formularios (Version 1.0)
// Impiric

function esNumero(s) {
	num=parseFloat(s)
	if (num!=''+s) return false
    return true
}
function esEntero(s)
	{
		a = 0;
		numeros = '0123456789';
		while (a<s.length) if(numeros.indexOf(s.substr(a, 1))<0) return false; else a++;
		return true;
	}	
function esEntero2(s) {   
	num=parseInt(s)
	if (num!=''+s) return false
    return true

	return !isNaN(s);
}

function esVacio(s){
   return ((s == null) || (s.length == 0));
}

var numeros="0123456789"
var letras_minusculas="a,b,c,d,e,f,g,h,i,j,k,l,m,n,ñ,o,p,q,r,s,t,u,v,w,x,y,z"
var letras_mayusculas=letras_minusculas.toUpperCase()
var letras=letras_minusculas+letras_mayusculas

function esNombre (s){
    if (esVacio(s)) return false
    validos = letras+" "
    for (i = 0; i < s.length; i++){   
        c = s.charAt(i);
        if (validos.indexOf(c) == -1) return false;
    }
	return true
}

function esDNI(s) {
	if (s.length<=8) return esEntero(s)
}

function esNIF(s) {
	
	//s=s.replace("-","");
    lo=s.length
	if (lo<2 || lo>9) return false
    dni=s.substring(0,lo-1)
    if (!esDNI(dni)) return false
	letra=new Array("T","R","W","A","G","M","Y","F",
					"P","D","X","B","N","J","Z","S",
					"Q","V","H","L","C","K","E");
    nif=s.substring(lo-1,lo).toUpperCase()
    if (nif!=letra[dni%23]) return false

	return true
}

function esEmail(s) {
	if (s=="") return true;
    pb=s.indexOf(' ')
    if (pb!=-1) return false
	p1=s.indexOf('@')
    if (p1<1 || p1==(s.length-1) || p1==-1) return false
	p2=s.indexOf('.');
	if (p2<1 || p2==p1+1 || p2==-1 || p2==(s.length-1)) return false
	return true
}


function esTelefono(tel){
	primerdigito="9"
	if (tel.length!=9 || !esEntero(tel) || (primerdigito.indexOf(tel.charAt(0)) == -1)) 
		return false
	return true
}
function esMovil(tel){
	primerdigito="6"
	if (tel.length!=9 || !esEntero(tel) || (primerdigito.indexOf(tel.charAt(0)) == -1)) 
		return false
	return true
}

/*
function esTelefono(tel){
		if (tel=="") return false;
		num = parseInt(tel);
		if (num != '' + tel)
			return false;

		primerdigito = "69";
		if (tel.length!=9 || (primerdigito.indexOf(tel.charAt(0))==-1))
			return false;
		return true;
}
*/

function esFecha(diaV,mesV,anoV)
{
	

	// Valido el año
	if (isNaN(anoV) || anoV.length<4 || parseFloat(anoV)<1900){
		return false
	}
	// Valido el Mes
	if (isNaN(mesV) || parseFloat(mesV)<1 || parseFloat(mesV)>12){
		return false
	}
	// Valido el Dia
	if (isNaN(diaV) || parseInt(diaV)<1 || parseInt(diaV)>31){
		return false
	}
	if (mesV==4 || mesV==6 || mesV==9 || mesV==11 || mesV==2) {
		if (mesV==2 && diaV > 28 || diaV>30) {
			return false
		}
	}

return true;

}
function esCPostal(e)
{
	if (e=="99000") return true; //Codigo Postal establecido para Andorra
	num=(e)*1;
	if ((num < 1001) || (num > 52080) || (!esEntero2(num)))
		return false;
	return true;
}
function fcn_Muestra_Error_Login(MsgError)
{
	if(MsgError.length != 0)
        {
		alert (MsgError);
	}

	return (false);
}


function i_fcnValNIF(p_txtCampo) {

	strNif		= "";
	strNumero	= "";
	strLetra	= "";
	if (!i_fcnTamMinCampo(p_txtCampo,3)) return(3);
	p_txtCampo	= i_fcnQuitaBlancos(p_txtCampo);
	strPrimero	= p_txtCampo.charAt(0);
	strPrimero	= strPrimero.toUpperCase();
	if((strPrimero=="X") && (!(strPrimero>90 || strPrimero<65))) {
		straux		= p_txtCampo;
		p_txtCampo	= " ";
		x = 0;
		for (var i=1;i<(straux.length);i++){
			x = x+1;
			p_txtCampo = p_txtCampo + straux.charAt(x);
		}
	}
	strUltimo	= p_txtCampo.charAt(p_txtCampo.length-1);
	strLetra	= i_fcnLetraNif(p_txtCampo);
	if((strUltimo>90 || strUltimo<65)){
		return (1);
	}
	strUltimo	= strUltimo.toUpperCase();
	if(strUltimo != strLetra) {

  		return (2);
	}
	strNumero = p_txtCampo.substring(1,p_txtCampo.length-1);

	//inicio
	var check = "0123456789";
	var carac;
	var cont	= 0;
	for (var i=0; i<strNumero.length; i++) {
		carac	= strNumero.substring(i, i+1);
		if(check.indexOf(carac) != -1 ) cont ++;
	}
	if(cont == strNumero.length)
	{
	}
	else
	{

		return(7);
	 }
	//final

	if (strPrimero=="X") {
		strNumero	= i_fcnRelleno(strNumero,8);
		p_txtCampo	= "X" + strNumero + strUltimo;
	}
	else {
		strNumero	= p_txtCampo.substring(0,p_txtCampo.length-1);
		strNumero	= i_fcnRelleno(strNumero,9);
		p_txtCampo	= strNumero + strUltimo;
		}

	return (p_txtCampo);
}

function i_fcnLetraNif(p_strCadena){
 numero=p_strCadena;
 tabla_letras="TRWAGMYFPDXBNJZSQVHLCKET";
 entero=parseInt(numero,10);
 resultado=parseInt(entero/23,10);
 resultado=resultado*23;
 diferencia=entero-resultado;
 letra=tabla_letras.charAt(diferencia);
 return letra;
}

function i_fcnRelleno(strNumero,p_intLongCampo){
 cero="0";
 cad="";
 log=strNumero.length;
 if ((log)<p_intLongCampo){
  resto=(p_intLongCampo-parseInt(log));
  for(var i=0;i<resto;i++)
  cad=cad+cero;
 }
 cad=cad+strNumero;
return cad
}

function i_fcnTamMinCampo(p_txtCampo,p_intlongnum){
 p_txtCampo = i_fcnQuitaBlancos(p_txtCampo);
  if (p_txtCampo.length < p_intlongnum){
   //alert (strCli003);
   return (false);
  }
  else return (true);
 }
 
 function i_fcnQuitaBlancos(p_txtCampo){
 p_txtCampoFormateado = new Object();
 p_txtCampoFormateado.value= "";
 strLong= p_txtCampo.value.length;
 for (var i=0; i < strLong; i++)
 {if (p_txtCampo.value.charAt(i) !=" ") p_txtCampoFormateado.value = p_txtCampoFormateado.value+p_txtCampo.value.charAt(i);}
 return (p_txtCampoFormateado.value);
}


 
function fcnValidar_Login(frmLogin){
	if(frmLogin.value == ""){
		//fcn_Muestra_Error_Login('Introduce un NIE ó NIF');
		return false;
	}else{
		var tamano = frmLogin.value.length;
		var esBusiness = false;
		var cPrimer_carac 	= frmLogin.value.charAt(0).toUpperCase();
		var cUlt_carac 		=	frmLogin.value.charAt(tamano - 1).toUpperCase();

			//Si el primer caracter es una letra diferente a X es de tipo business
		if ( (isNaN(cPrimer_carac ) ) && (cPrimer_carac != "X") ) {
			esBusiness = true;
			var strNumero = frmLogin.value.substring(1,tamano );
						
				//Si el ultimo caracter NO es un numero se deja el DNI igual
			if (isNaN(cUlt_carac)) {								
					strNumero = frmLogin.value.substring(1,tamano - 1 );
					NifBusiness = cPrimer_carac + strNumero + cUlt_carac;					
					strInicio = cUlt_carac;
				//Si el ultimo caracter es un numero se pone un espacio al final
			} else {
					NifBusiness = cPrimer_carac + strNumero + " ";
					strInicio = "0";
			}
				//Se pone el DNI, de forma normal, en la caja de texto
			frmLogin.value = strInicio + strNumero + cPrimer_carac;			
		}


		//NIF
		var NIF_Tit = i_fcnValNIF(frmLogin);
		switch(NIF_Tit)
		{
		case 3: // Revise Tamaño Campo
			//fcn_Muestra_Error_Login('Revise el tamaño del campo');
			return false;
		case 1: //Revise NIF
			//fcn_Muestra_Error_Login('El NIF ó NIe introducido no es correcto');
			return false;
		case 2: // Revise Letra NIF
			//fcn_Muestra_Error_Login('Revise la letra del NIF ó NIE introducido');
			return false;
		case 7: // Acentos y caracteres invalidos
			//fcn_Muestra_Error_Login('Ha introducido caracteres inválidos');
			return false;
		}

		//Una vez validado en DNI, si es Business se pasa al formulario el nif del tipo Business , si no, se pasa de tipo normal
	if (esBusiness) {
				frmLogin.value = NifBusiness.toUpperCase();			
		} else {
				frmLogin.value = NIF_Tit;				
		}

	}
	return true;
}


function valida_formulario(){
		error = 0;	
		
				
	if( document.getElementById('nombre').value == "" || document.getElementById('conocistes').value == "" || document.getElementById('apellidos').value== "" || document.getElementById('nacionalidad').value=="" ||  document.getElementById('cp').value =="" || document.getElementById('poblacion').value =="" || document.getElementById('email').value =="" || document.getElementById('pais').value =="" ){
			error = 1;
			alert("Es obligatorio rellenar todos los campos marcados con *(asterisco)");
		}else{
				
				/*if(document.getElementById('cavisolegal').checked  == false ){
					error = 1;
					alert("Debes aceptar las bases para poder inscribirte");
					document.getElementById('cavisolegal').focus();
				}*/
				if(!esEmail(document.getElementById('email').value)){
					error = 1;
					alert("Debes introducir una dirección email correcta");
					document.getElementById('email').focus();
				}
				if(!esEntero(document.getElementById('telefono').value)){
					error = 1;
					alert("Debes introducir un teléfono válido");
					document.getElementById('telefono').focus();
				}
				/*if(!esDNI(document.getElementById('dni').value)){
					error = 1;
					alert("Debes introducir un DNI válido");
					document.getElementById('dni').focus();
				}*/
				
				
		}
		if( error == 0){
			alert("Gracias por ponerte en contacto con nosotros. Nos pondremos en contacto contigo lo antes posible.");
			document.form1.action="email.php";
			document.form1.submit();
			
		}
}

function cambia_idioma(ingles){
		urltext = new Array();
		url = new String();
	if (ingles==1){
		urltext = location.href.split("/");
		for(n=0;n<urltext.length-1;n++){
		 url +=	urltext[n].toString();
		 url += "/";
		}
		url += "en/";
		url += urltext[n].toString();
	}else{
		
		url = location.href.replace("/en/","/");
		
		
	}
	
	location.href = url;
}
