//Función de validación para campos (Javascript)
//V 1.0
//uso:
//	Colocar para validación de formularios (evento onSubmit)
//	Validar(nombreCampo1,restriccionesCampo1,nombreCampo2,restriccionesCampo2...)
//		todos los parámetros son cadenas
//	nombreCampo        -> nombre del elemento de formulario a validar
//	valorOpcional      -> valor a dar a la variable si es requerida y no se ha especificado
//	restriccionesCampo -> Comprobaciones que se haran sobre el campo:
//			R 			-> Requerido
//			esEmail 	-> El campo especifica una dirección de email
//			esNum		-> El campo debe tener un valor numérico
//			enRangoX:Y 	-> El valor del campo debe estar en el rango numérico (X<=valor<=Y)
//			longMinX	-> La longitud del campo como cadena debe ser mayor que X
//			longMaxY	-> La longitud del campo como cadena debe ser menor que Y
//			esNif		-> El valor del campo debe ser un Nif (DNI o Cif)
//
//			Ejemplo de uso: Validar('nombre','Nombre','R','email','E-Mail','ResEmail','dni','DNI','ResNif','numhermanos','Numero de hermanos','enRango0:10')
// 				-El nombre debe especificarse
//				-El campo email es requerido y se valida que sea una direccion de mail correcta
//				-El campo dni es requerido y se comprueba que sea un Nif correcto (numero y letra)
//				-El campo numhermanos es opcional, pero si se especifica debe estar en el rango 1-10

function trim(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;
  if(!d) d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    	d=parent.frames[n.substring(p+1)].document; 
		n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); 
  return x;
}

function ValidarVector(vector) {
  var val,i,j,p,q,nm,test,opcional,num,min,max,nif_num,nif_char,cif_num,cif_char,aux,numDigitos,doble,total,caracteresvalidosnif,errors='',args=Validar.arguments;
  for (i=0; i<(vector.length-2); i+=3) {  	
  		test=vector[i+2];
		mostrar=vector[i+1]
		campo=MM_findObj(vector[i]);		
		if (campo) { 		
			nm=mostrar; 			
			val = trim(campo.value);
			if (val!="") { // Si ha introducido algo
			
				//validando longitud minima
				if (test.indexOf('longMin')!=-1){ 
					pos = test.indexOf('longMin')+7;
					longitud = 1;
					//vamos creando el numero mientras podamos
					while(longitud+pos<=test.length && !isNaN(test.substring(pos,pos+longitud)))
						longitud++;
					longitud--;
					valor = parseInt(test.substring(pos,pos+longitud))
					if(val.length<valor)
						errors+="- El campo "+nm+" debe tener como mínimo "+valor+" caracteres\n";
				}	
				
				//validando longitud maxima
				if (test.indexOf('longMax')!=-1){ 
					pos = test.indexOf('longMax')+7;					
					longitud = 1;
					//vamos creando el numero mientras podamos
					while(longitud+pos<=test.length && !isNaN(test.substring(pos,pos+longitud)))
						longitud++;
					longitud--;
					valor = parseInt(test.substring(pos,pos+longitud))
					if(val.length>valor)
						errors+="- El campo "+nm+" debe tener como máximo "+valor+" caracteres\n";
				}	
			
				//validando email
      			if (test.indexOf('esEmail')!=-1) { 
					p=val.indexOf('@');
        			if (p<1 || p==(val.length-1)) errors+='- '+nm+' debe contener una direccion de correo electronico.\n';
      			}
				//Si es un numero o se trata de un rango (los rangos siempre se consideran para los numeros)
				if (test.indexOf('esNum')!=-1 || test.indexOf('enRango') != -1) { 
	  				num = parseFloat(val);
      				if (isNaN(val)) errors+='- '+nm+' debe contener un numero.\n';
      				if (test.indexOf('enRango') != -1) { 
	  					p=test.indexOf(':');                                                                                                                                                                                                                                                                                                                                              
        				min=test.substring(8,p); 
						max=test.substring(p+1);
        				if (num<min || max<num) errors+='- '+nm+' ha introducido un numero fuera del rango establecido ('+min+'-'+max+').\n';
      				} 
				} 
				//Para controlar el NIF
				if(test.indexOf('esNif') != -1){
					if (isNaN(val.substr(0,1))){
						var control ="JABCDEFGHI";
						var temp = val.toUpperCase(); // pasar a mayúsculas
						if (!/^[A-Za-z0-9]{9}$/.test(temp)) {
							errors += '- Longitud incorrecta, un CIF consta de 9 dígitos\n';
							}
						else if (!/^[ABCDEFGHKLMNPQS]/.test(temp)){
							errors += '- Error en CIF, el primer dígito es incorrecto, debe ser una letra de las siguientes: A,B,C,D,E,F,G,H,K,L,M,N,P,Q,S\n';
							}
						else {
							  var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
							  var temp = 0; 
							  for( j = 2; j <= 6; j += 2 ) 
									{
									temp = temp + v1[ parseInt(val.substr(j-1,1)) ];
									temp = temp + parseInt(val.substr(j,1));
									}
							  temp = temp + v1[ parseInt(val.substr(7,1)) ];
							  temp = 10 - (temp % 10);
							  if (temp == 10) temp = 0;
							  if (isNaN(val.substr(8,1))){
									if (control.substr(temp,1) != val.substr(8,1).toUpperCase()){
										errors += "- El CIF no es valido, escribalo sin guiones (A12345678 ó A1234567A)\n";
									}
							  }
							  else{
									if ((temp%10) != parseInt(val.substr(8,1))){
										errors += "- El CIF no es valido, escribalo sin guiones (A12345678 ó A1234567A)\n";
									}
							  }
						}
					}else{
						caracteresvalidosnif="TRWAGMYFPDXBNJZSQVHLCKET";
						aux=val.length;
						nif_num=val.substring(0,aux-1);
						nif_char=(val.substring(aux-1)).toUpperCase();
						//errors+=nif_num+'  '+ nif_char+'  \n';
						if (isNaN(nif_num) || nif_char.length != 1 || caracteresvalidosnif.indexOf(nif_char)==-1 ){
							errors+='- En el campo '+nm+' no tiene un formato correcto de NIF, (12345678A)\n';
						}else{
							num=(nif_num)% 23;
							if (caracteresvalidosnif.substring(num,num+1) != nif_char) errors+='- La letra del Nif no es correcta.\n';
						}
					}
				}
				
			//Si no ha introducido nada
			} else if (test.charAt(0) == 'R'){
				errors += '- El campo '+nm+' es requerido.\n'; 
			} 
		} //fin if(val)
  } //fin for
  if (errors!='') alert('El/Los siguiente(s) error(es) ha(n) ocurrido:\n'+errors);
  return (errors == ''); //devolvemos true si se ha validado bien
}

function Validar() {
	var vector = args;
	ValidarVector(vector);
}