function esNumero(a,t) {
	//t es tipo denumero: E entero para telefono, codpostal, etc. D es decimal
if (isNaN(a))
	a=cNumero(a)
if(!a )	
{	
	return false
}
else{
		//comprobar si es entero o no
		if (t=='E' && a!=Math.round(a))
		{
			return false
		}
		//Cuando es una cuantia o tarifa, el tipo es D
		//D solo tiene sentido cuando se trabaje en euros
		if(t=='D')
		{	//si la moneda es peseta, el numero debe ser entero y la longitud maxima es 6
			if(document.formu.moneda[0].checked)
			{
				if(a.length>6 || a!=Math.round(a))
					return false
			}
			else
			{//si la moneda es euro, el numero puede ser decimal, la parte entera tiene longitud maxima de 4
				pto=a.indexOf(".")
				if (pto>4||(pto==-1&& a.length>4))
					{	alert('The amount is too large')
						return false
					}
				
			}
		}
			
	}
   return true;
}

function comprobar_hora_ocurrencia() {
	x = document.formu
	if (esNumero(x.FOcu_hhQ.value,'E')) {
             if ((x.FOcu_hhQ.value) > 23 ) {
                alert("The time frame exceeds the permitted values.");
		x.FOcu_mmQ.value="";
		x.FOcu_hhQ.focus();
		return false;
             }else{
		if ( (esNumero(x.FOcu_mmQ.value,'E')) && ((x.FOcu_mmQ.value)< 60) ) {
			 return true;	
		}else{
			alert("You must enter a correct number.");
			x.FOcu_mmQ.value="";
			x.FOcu_mmQ.focus();
			return false;
		}
	      }
	}else{
		alert("You must enter a correct number.");
		x.FOcu_hhQ.value="";
		x.FOcu_mmQ.value="";
		x.FOcu_hhQ.focus();
		return false;
	}

}


function validarFecha(dia,mes,anyo) 
	{

		if (isNaN(dia))
			return false;

		if (isNaN(mes))
			return false;
		
		if (isNaN(anyo))
			return false;

	
		if (anyoBisiesto (anyo))
			febrero = 29;
		else
			febrero = 28;
	
		if ((mes < 1) || (mes > 12))
			return false;

		if ((mes == 2) && ((dia < 1) || (dia > febrero)))
			return false;

	
		if (((mes == 1) || (mes == 3) || (mes == 5) || (mes == 7) || (mes == 8) || (mes == 10) || (mes== 12)) && ((dia < 1) || (dia > 31)))
			return false;
		if (((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) && ((dia < 1) || (dia > 30)))
			return false;

		if (anyo < 1900)
			return false;

		return true;
	}

	function anyoBisiesto (anyo)
	{
		if (anyo % 4 != 0)
			return false;
		else
		{
			if (anyo % 100 == 0)
			{
				if (anyo % 400 == 0)
					return true;
				else
					return false;
			}
			else
				return true;
		}
	}



function esNumero(a) {
   for(var i=0; i<a.length; i++) {
     if (a.charAt(i) < "0" || a.charAt(i)>"9")
       return false;
   }
   return true;
}

function trim(cadena) //para evitar que se introduzcan valores blancos en los campos del formulario web
{
	for(i=0; i<cadena.length; )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	
	return cadena;
}

function checkdatos() {

	x=document.formu
	var comentario="";
	var longi=0;
	var i=0;
	var vacio=false;
	var caracter="";
	
	// 18/01/2012 IFCM --- Se añade comprobación y modificación de valor para evitar que se graben con CIF vacío al introducir espacios
	if(trim(x.des_Enombre.value) == "")
		x.des_Enombre.value = "";
	
	if(trim(x.des_CIF.value) == "")
		x.des_CIF.value = "";
	// 18/01/2012
	
	//modified 11/11/2007 --- cambio de orden para la situacion cif empre mal - nif mal //se añanden trims en el método culpa de firefox
	if(x.des_pais.value.toUpperCase()=='ESPAÑA')
	{	
		nprovincia();
		//falta validar cif, si es españa
		if(trim(x.des_Enombre.value)!="" && (trim(x.des_CIF.value)=="" || !validaNIF(x.des_CIF.value)))
		{							
			if(confirm('The CIF (Corporate Tax ID) is invalid. Your complaint will be registered as an individual'))
				x.des_CIF.value=''											
			else
				return false	
		}
	}
	//end modified	
	
	//modified 29/06/2007
	if(trim(x.des_Enombre.value)=="" || trim(x.des_CIF.value) =="" )
	{			
		if(x.tipo_doc_id.value == 0)
		{
			if(x.des_id.value == "")
			{
				alert("NIF/NIE not valid.")
			}
			
			if (!validaNIFNIE(x.des_id.value))
			{			
			//alert("NIF / NIE no válido.")
			x.des_id.focus();
			return false;
			}			
		}
		else
		{
			//modified 24/10/2007
			//if (isNaN(trim(x.des_id.value)))			
			if (x.des_id.value == "")
			{					
				alert('Passport not valid')
				return false;
			}
			
			//modified 05/11/2007 -- quitar el trim arriba en validaNIFNIE
			cad=x.des_id.value.toUpperCase()
			limpia=""
			for(i=0;i<cad.length;i++)
			{
				ci=cad.charAt(i)
				if((ci>='A' && ci<='Z') || (ci>='0' && ci<='9'))
					limpia=limpia+cad.charAt(i)
			}
			if(limpia.length != x.des_id.value.length)
			{
				alert('Passport not valid')
				return false;
			}
			//end modified
		}		
	}	
		//end modified		
		
if(trim(x.des_nombre.value)=="" || trim(x.des_apellidos.value)=="" )	
{
	alert("You must complete the Name and Surname")
	if (trim(x.des_nombre.value)=="")
	{
		x.des_nombre.value="";
		x.des_nombre.focus();
	}
	else
	{
		x.des_apellidos.value="";
		x.des_apellidos.focus();
	}
		
	return false;
}


if(trim(x.des_Enombre.value)=="" && trim(x.des_CIF.value)!="" )	
{
	
	if(confirm('The name of the company is invalid. Your complaint will be registered as an individual'))
		x.des_CIF.value=''
	
	else
		return false;
}


//dirección
if (trim(x.des_calle.value)=="" || trim(x.des_pobl.value)=="" || trim(x.des_cp.value)=="" || trim(x.des_provincia).value=="") {
		alert("You must complete the address: Street, Town, Post Code and Province.")
		if(trim(x.des_calle.value)=="")
		{
			x.des_calle.value="";
			x.des_calle.focus();
		}
		else
		{
		     if (trim(x.des_pobl.value)=="")
		     {	
						x.des_pobl.value="";
						x.des_pobl.focus();
		     }
		     else
		     { 
			if (trim(x.des_cp.value)=="")
		  {
				x.des_cp.value="";
				x.des_cp.focus();
			}
		  else 
			{
				if (trim(x.des_provincia.value)=="") 
				{
					x.des_provincia.value="";
					x.des_provincia.focus();
				}
			}
		}
		}
		return false;		
}
	 	
if (trim(x.des_pais.value)==""){
	if(confirm('The country is required. Click OK if it is Spain, or Cancel if it is not'))
	{
		x.des_pais.value="";
		x.des_pais.value='ESPAÑA'
	}
	else{ 
		x.des_pais.value="";
		x.des_pais.focus();
		return false
		}
}
		
if (trim(x.des_email.value)=="") {
		alert("You must complete the e-mail field.")
		x.des_email.focus()
		return false;
} 
else 
{
//08-06-06
//if (x.des_email.value.indexOf('@')==-1 || x.des_email.value.indexOf('.')==-1 || x.des_email.value.indexOf('@')+2 >= //x.des_email.value.lastIndexOf('.') || x.des_email.value.lastIndexOf('.')+1== x.des_email.value.length ) {

	if(ValidaEmail(x.des_email.value) == false)
	{

//08-06-06
//		alert("You must enter a valid e-mail address.")
		x.des_email.focus()
		return false;
	}

}

if (trim(x.des_tel.value)=="") {
		alert("You must complete the telephone field.")
		x.des_tel.value="";
		x.des_tel.focus()
		return false;
} 

if ( validarFecha(x.FOcu_dQ.value,x.FOcu_mQ.value,x.FOcu_aQ.value) == false )
{
		alert("The date format is invalid.")
		x.FOcu_dQ.value="";
		x.FOcu_aQ.value="";
		x.FOcu_mQ.value="";
		x.FOcu_dQ.focus()
		return false;

}

if (trim(x.FOcu_hhQ.value)=="") {
		alert("You must indicate a time for the incident.")
		x.FOcu_hhQ.value="";
		x.FOcu_hhQ.focus()
		return false;
}

if (trim(x.FOcu_mmQ.value)=="") {
		alert("You must include the minutes for the time of the incident.")
		x.FOcu_mmQ.value="";
		x.FOcu_mmQ.focus()
		return false;
}


if (!comprobar_hora_ocurrencia()){
	return false;
}

	


if (trim(x.des_mensaje.value)=="") {
		alert("The exact details of the complaint must be stated.")
		x.des_mensaje.value="";
		x.des_mensaje.focus()
		return false;}
else	
	if(x.des_mensaje.value.length>800){
		alert('Your text is longer than 800 characters. Please limit the text of the complaint to that length.')
			return false;
	}
	
//modified 10/10/2007
if(trim(x.des_id.value) == "" && trim(x.des_CIF.value) == "")
{
	alert("NIF/NIE not valid")
	return false;
} 	
//end modified	

	return true;
}

//modified 29/06/2007///////Validamos NIF/NIE//////////

function validaNIFNIE(valor)
{	
	x=document.formu
	if(valor!='')
	{
		cad=valor.toUpperCase()
		limpia=""
		for(i=0;i<cad.length;i++)
		{
			ci=cad.charAt(i)
			if((ci>='A' && ci<='Z') || (ci>='0' && ci<='9'))
				limpia=limpia+cad.charAt(i)
		}
		if(limpia.length>9 )
		{
			alert('Format not valid ')
			return false;
		}
		
		//modified 10/10/2007
		if(x.tipo_doc_id.selectedIndex==0 && x.des_id.value != "")
		{
			if(limpia.length != valor.length)
			{
				alert("NIF/NIE not valid")
				return false;
			}
		}
		
	if(x.des_CIF.value != "")
		{
			if(limpia.length != valor.length)
			{
				//alert('formato NIF/NIE incorrecto')			
				return false;
			}
		}	
		//end modified
		
		//nif
		
		if(limpia.charAt(0)=='X')
			nif=limpia.substring(1,limpia.length-1)
		else if(limpia.charAt(0)=='Y')	
			nif= 1 + limpia.substring(1,limpia.length-1)
		else if(limpia.charAt(0)=='Z')	
			nif= 2 + limpia.substring(1,limpia.length-1)			
		else
			nif=limpia.substring(0,limpia.length-1)
		
		lnif=limpia.charAt(limpia.length-1)	
		
		if( isNaN(nif) || !(isNaN(lnif)))
		{
			alert('NIF/NIE not valid')
			return false;
		}
		else	
			return letraNIF(nif,lnif);		
	}
	else
		return false;
}

function letraNIF(nif,lnif) 
{
    var cadena = 'TRWAGMYFPDXBNJZSQVHLCKE';
    var nifnum = parseInt(nif, 10);
    var posicion = nifnum % 23;
    
    //return cadena.charAt(posicion)!=lnif;
	if(cadena.charAt(posicion)!=lnif)
	{
		alert('NIF o NIE not valid');
		return false;
	}
    else
		return true;
}


//end modified///////////////////////////

function validaNIF(valor){

	x=document.formu
	cad=valor.toUpperCase()
	limpia=""
	for(i=0;i<cad.length;i++){
		ci=cad.charAt(i)
		if((ci>='A' && ci<='Z') || (ci>='0' && ci<='9'))
			limpia=limpia+cad.charAt(i)

	}
	if(limpia.length>9 ){
		//alert('Incorrect CIF (Corporate Tax ID) format ')
		return false;
	}
	
	//modified 10/10/2007
	
	if(x.tipo_doc_id.selectedIndex==0 && x.des_id.value != "")
		{
			if(limpia.length != valor.length)
			{
				alert('NIF/NIE not valid')
				return false;
			}
		}
		
	if(x.des_CIF.value != "")
		{
			if(limpia.length != valor.length)
			{
				//alert('formato NIF/NIE incorrecto')			
				return false;
			}
		}	
	
	//end modified
	
		lcif=limpia.charAt(0) //primer caracter
		dcnif=limpia.charAt(limpia.length-1) //ultimo (control)
		if(lcif=='A' || lcif=='B' ||lcif=='C' ||lcif=='D' ||lcif=='E' ||lcif=='F' ||lcif=='G' ||lcif=='H' ||lcif=='K' ||lcif=='M' ||lcif=='N' ||lcif=='P' ||lcif=='Q' ||lcif=='S' ||lcif=='J' ||lcif=='U'||lcif=='V'||lcif=='R'||lcif=='W'){
			ncif=limpia.substring(1,limpia.length-1)
			return letraCIF(ncif,dcnif,limpia)
		}
		else{
		//	alert('Incorrect CIF (Corporate Tax ID) format ')
			return false;
			}
//}
return true;
}

function letraCIF(ncif,dcnif,limpia){
	sumpar=0
	sumimpar=0
	for(i=0;i<ncif.length;i=i+2){
		tm=parseInt(ncif.charAt(i),10)*2
		if(tm>9){
				tms=tm.toString()
				tm=parseInt(tms.charAt(0),10)+parseInt(tms.charAt(1),10)
		}
		sumimpar=sumimpar+tm			
	}
	for(i=1;i<ncif.length;i=i+2){
		sumpar=sumpar+parseInt(ncif.charAt(i),10)			
	}
	dcun=(sumpar+sumimpar) % 10
	dc=(10-dcun)%10	
	cadenal='JABCDEFGHI'
	if(dcnif!=dc && dcnif!=cadenal.charAt(dc)){
		//alert('Incorrect CIF (Corporate Tax ID)');
		return false;
	}
	else
	{
		des_CIF = limpia;
		return des_CIF;
		//return true;
	}
}

//aquí mi código.Práctica 2 Pedro L. Jiménez 09/02/2006
function contar_letras(carac,max){
	//Cuenta decreciente de número de caracteres del area comentarios. Alerta al usario sobre el máximo del texto.
	if(carac>max){
		document.formu.des_mensaje.value=document.formu.des_mensaje.value.substring(0,max);
		alert ("Your text is longer than "+max+" characters. Please limit the text of the complaint to that length.");
		document.formu.jorcontador.value=max-(document.formu.des_mensaje.value.length);
		//Solución al desfase en el uso de tecla -intro-.
		if(document.formu.jorcontador.value==-1){
			document.formu.des_mensaje.value=document.formu.des_mensaje.value.substring(0,(max-1));
			document.formu.jorcontador.value=max-(document.formu.des_mensaje.value.length);
			alert("The line break requires 2 spaces, you only have 1 available");
		}
	}		
	else {
		document.formu.jorcontador.value=max-carac;
	}		
}
//fin código practica 2


//código para validación Email 8-Junio-06


function ValidaEmail(email) {

 if(email.length > 0){
        if (! ValidaCarac(email)) {  
// comprueba que todos los caracteres son validos
        return false;
    }
    if (email.indexOf("@") < 1 ) {
    	alert('The format of the e-mail address is incorrect.');
//  debe contener @, y no debe ser el primer carácter 
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {
    	alert('Invalid e-mail address. You must enter a valid domain after the @ sign.');
// el ultimo punto debe estar despues de la @
        return false;
    } else if (email.indexOf("@") == (email.length-1)) {
    	alert('The format of the e-mail address is incorrect. It cannot end with the @ sign.');
 // @ no puede estar el ultimo 
         return false;
	} else if (email.indexOf("..") >=0) {
		alert('Invalid e-mail address. Two consecutive dots are not allowed');
 //mas de dos puntos seguidos son invalidos
		return false;
	} else if (email.indexOf(".") == (email.length-1)) {
		alert('The format of the e-mail address is incorrect. It cannot end with a dot.');
  //  no puede terminar con punto
		return false;
    } else if(!formato(email)){
    	alert ('The format of the e-mail address entered is incorrect');
  // comprueba que tiene un formato correcto
		return false; }
  }
    return true;
}

function formato(email){
var b=/^[^@\s]+@[^@\.\s]+(\.[^@\.\s]+)+$/
  //devuelve verdadero si validacion OK, y falso en caso contrario            
  return b.test(email)
  }

function ValidaCarac(email) {
  var parsed = true;
   var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";  //Caracteres validos para dirección de correo
  for (var i=0; i < email.length; i++) {
    var letra = email.charAt(i).toLowerCase();    //Pasamos todo a minusculas
        if (validchars.indexOf(letra) != -1){	//Comparamos los caracteres introduccidos con los validos
          continue;		//Si el caracter es valido entra en el if y continua ejecutando el for
		}else{			//Si el caracter no es valido entra en el else, cambia el retorno a false y sale del for
				if (letra == ' '){alert ('The e-mail address cannot include any blank spaces');
				parsed = false;
				break;		
				}else {alert (letra + '   It is not a valid character for an e-mail address');
				parsed = false;		
				break;
				}
		}
  } 
 return parsed;
}

