function ValidarCampo(campo, tipovalidacion, obligatorio, texto1, texto2) {
	if (obligatorio==true){
		if (campo.value == "") {
			alert(texto1); 
			campo.select() 
			campo.focus() 
			return false; 
		}
	}
	else {
		if (campo.value == "") {
			return true; 
		}	
	}
	switch (tipovalidacion) { 
    case 1:  // solo números
			var validos = '0123456789';
			if (CompruebaCaracteres(campo, validos, texto2)==false) return false;
			break
/*
			valor = parseInt(campo.value);
			if (isNaN(valor)) { 
				alert(texto2); 
				campo.select() 
				campo.select() 
				campo.focus() 
  	    return false;
    	}
			else { 
				campo.value=valor;
       	return true;
	    } 
*/
			break 
		case 2: // sin restricción
       break 
		case 3: // emilio
			var texto
			var posicionArroba
			var posicionPunto
			var posicionEspacio
			var arrobamasuno

			texto=campo.value;

			// buscamso la arroba.
			posicionArroba = texto.indexOf("@", 1);
			if (posicionArroba==-1 || posicionArroba==1 || posicionArroba==texto.length-1) {
				devolucionFalse(campo, 'no es una dirección de e-mail correcta');
				return false;
			}
		
			arrobamasuno=posicionArroba+1
			//buscamos el punto después de la arroba			
			posicionPunto = texto.indexOf(".", arrobamasuno);
			if (posicionPunto==-1 || posicionPunto==arrobamasuno || posicionPunto==texto.length-1) {
				devolucionFalse(campo, 'no es una dirección de e-mail correcta');
				return false;
			}
			
			posicionEspacio = texto.indexOf(" ", 1);
			if (posicionEspacio!=-1) {
				devolucionFalse(campo, 'no es una dirección de e-mail correcta');
				return false;
			}

			return true;
      break 
		case 4: // solo letras
			var validos = 'abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ';
			if (CompruebaCaracteres(campo, validos, texto2)==false) return false;
			break
		case 5: // sin espacios
			var texto
			var posicionEspacio

			texto=campo.value;

			// buscamso la arroba.
			posicionEspacio = texto.indexOf(" ", 1);

			if (posicionEspacio!=-1) {
				devolucionFalse(campo, 'el campo no admite espacios');
				return false;
			}
		
			return true;
      break 
		case 6: // validar contraseña segura
			//debe tener un minimo de 8 caracteres
			if (campo.value.length < 8) {
				devolucionFalse(campo, 'el campo debe tener una logintud mínima de 8 caracteres');
				return false;
			}
			//debe contener mayusculas
			var validos = 'ABCDEFGHIJKLMNÑOPQRSTUVWXYZ';
			if (compruebaCaracteresContrasenia(campo, validos)==false) {
				devolucionFalse(campo, 'el campo debe contener mayusculas');
				return false;
			}

			//debe contener minusculas
			var validos = 'abcdefghijklmnñopqrstuvwxyz';
			if (compruebaCaracteresContrasenia(campo, validos)==false) {
				devolucionFalse(campo, 'el campo debe contener minusculas');
				return false;
			}

			//debe contener numeros
			var validos = '0123456789';
			if (compruebaCaracteresContrasenia(campo, validos)==false) {
				devolucionFalse(campo, 'el campo debe contener números');
				return false;
			}
			return true;
      break 
    case 7:  // numeros con decimales
			var validos = '0123456789.,';
			if (CompruebaCaracteres(campo, validos, texto2)==false) return false;
			break		
		case 66: // validar contraseña no segura
			//debe tener un minimo de 6 caracteres
			if (campo.value.length < 6) {
				devolucionFalse(campo, 'el campo debe tener una logintud mínima de 6 caracteres');
				return false;
			}
			return true;
      break				
		case 8: // validar fecha
			if (!esFecha(campo.value)) {
				alert(texto2);
	  		return false;
	  	}
			return true;
      break				
    default:		 
	} 
}

function esFecha (strValue){	
  //check to see if its in a correct format
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;

  if(!objRegExp.test(strValue)){
    return false; //doesn't match pattern, bad date
  } else {
    var strSeparator = strValue.substring(2,3)
    //create a lookup for months not equal to Feb.
    var arrayDate = strValue.split(strSeparator);

    var arrayLookup = { '01' : 31,'03' : 31,
      '04' : 30,'05' : 31,
      '06' : 30,'07' : 31,
      '08' : 31,'09' : 30,
      '10' : 31,'11' : 30,'12' : 31
    }

    var intDay = parseInt(arrayDate[0],10);
    var intMonth = parseInt(arrayDate[1],10);
    var intYear = parseInt(arrayDate[2],10);
    //check if month value and day value agree

    if (arrayLookup[arrayDate[1]]!=null) {
      if (intDay<=arrayLookup[arrayDate[1]] && intDay!=0) {
	  		return true; //found in lookup table, good date
			}
    }

    if (intMonth==2) {			
      var intYear = parseInt(arrayDate[2]);

      if (intDay > 0 && intDay < 29) {
        return true;
      }
      else if (intDay == 29) {
        if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
            (intYear % 400 == 0)) {
          // year div by 4 and ((not div by 100) or div by 400) ->ok
          return true;
        }
      }
    }
  }

  return false; //any other values, bad date
}





function ValidarFecha(campodia, campomes, campoanio, testo1) {
var dia=campodia.value;
var mes=campomes.value;
var anio=campoanio.value;

	if (ValidarCampo(campodia, 1, false, '', 'este campo solo admite valorers numéricos')==false) return false;
	if (ValidarCampo(campomes, 1, false, '', 'este campo solo admite valorers numéricos')==false) return false;
	if (ValidarCampo(campoanio, 1, false, '', 'este campo solo admite valorers numéricos')==false) return false;

	if (dia==''&&mes==''&&anio=='') return true;

	if ((dia!=''||mes!=''||anio!='')&&(dia==''||mes==''||anio=='')) {
		alert(testo1);
		campodia.focus();
		campodia.select();
		return false; 
	}

	if (anio.length!=4) {
		alert('Introduzca el año con 4 dígitos');
		campoanio.select();
		campoanio.focus();
		return false; 
	}

	if (mes>12) {
		alert('El campo mes no puede ser superior a 12');
		campomes.select() 
		campomes.focus() 
		return false;
	}

	if (mes==1||mes==3||mes==5||mes==7||mes==8||mes==10||mes==12) {
		if (dia>31) {
			alert('El campo día no puede ser superior a 31');
			campodia.select() 
			campodia.focus() 
			return false;
		}
	}
	if (mes==4||mes==6||mes==9||mes==11) {
		if (dia>30) {
			alert('El campo día no puede ser superior a 30');
			campodia.select() 
			campodia.focus() 
			return false;
		}
	}
	if (mes==2) {
		if (dia>29) {
			alert('El campo día no puede ser superior a 29');
			campodia.select() 
			campodia.focus() 
			return false;
		}
	}
}

function devolucionFalse(campo, mensaje) {
	alert(mensaje); 
	campo.select() 
	campo.focus() 
	return false;
}
function  CompruebaCaracteres(campo, validos, mensaje) {
	var res = 1;
	var temp;
	
	for (var i=0; i<campo.value.length; i++) {
		temp = '' + campo.value.substring(i, i+1);
		if (validos.indexOf(temp) == -1) res = 0;
	}
	
	if (res == 0) {
		alert(mensaje); 
		campo.select();
		campo.focus(); 
		return false;
	}
	return true;	
}
function  compruebaCaracteresContrasenia(campo, validos) {
	var res = 0;
	var temp;

	for (var i=0; i<validos.length; i++) {
		temp=validos.substring(i, i+1);

		if (campo.value.indexOf(temp)!= -1) {
			res=1;
			break;
		}
	}
	return res;	
}
function CalculaNIF(NIF, LetraNIF) {

var varNIF;        

            if (NIF.value=="") return false;

            if (NIF.value.substring(0,1)=="0") {

                        alert("el NIF no puede empezar por 0");

                        LetraNIF.value = "";

                        NIF.value = "";

                        return false;

            }

            varNIF = parseInt(NIF.value);

 

            if (isNaN(varNIF)) {

                        LetraNIF.value = "";

                        NIF.value = "";

                        return false;

            }

            cadena="TRWAGMYFPDXBNJZSQVHLCKET";

            posicion = varNIF % 23;

            letra = cadena.substring(posicion,posicion+1);

            LetraNIF.value = letra;

  NIF.value = varNIF;

}
function validacionCIF(CIF) {
	var dc;
	var ud;
	if (CIF.value!='') {
		if (CompruebaCIF(CIF, 'el CIF debe tener una longitud de 9 dígitos', 'el primer caracter debe ser una letra de las siguientes A,B,C,D,E,F,G,H,K,L,M,N,P,Q,S')==true) {
			dc=ValidaCIF(CIF, 'El dígito de control es: J ó 0');
			alert(dc);
			ud=parseInt(CIF.value.substr(8,1),10);
			alert(ud);
			if (dc!=ud) {
				alert('El dígito de control no coincide');
				CIF.select(); 
				CIF.focus();
				return false;
			}
		}
		else {
			CIF.select(); 
			CIF.focus();
			return false;
		}				
	}
	return true;
}

function CompruebaCIF(CIF,msg1,msg2) {
	var res=false;
	var aux=CIF.value.toUpperCase(); 
	if (!/^[A-Za-z0-9]{9}$/.test(aux)) alert (msg1); //"Longitud incorrecta, un CIF consta de 9 dígitos"

	else if (!/^[ABCDEFGHKLMNPQS]/.test(aux)) alert (msg2); //"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"
	
	else res = true;

	return res;
}
function ValidaCIF(CIF,msg1) {
	var arrN = new Array(0,2,4,6,8,1,3,5,7,9); 
	var aux = 0; 

	for(i=2;i<=6;i+=2 ) {
		aux = aux + arrN[parseInt(CIF.value.substr(i-1,1))];
		aux = aux + parseInt(CIF.value.substr(i,1));
	}

	aux = aux + arrN[parseInt(CIF.value.substr(7,1))];
	aux = (10 - ( aux % 10));

	if(aux==10) {
		return 0;
//	    alert(msg1); //"El dígito de control es: J ó 0"
	}
	else {
		return aux;
	}

	return aux;
}

function validaCIFNIF_old(strDoc) {
var strNIF;
var varNIF;        
var letraNIF;
	if (strDoc.value.length==0) return false;
	
	if (isNaN(strDoc.value.charAt(0))) { 	//CIF
		if (!validacionCIF(strDoc)) return false;	
	}
	else { 				//NIF
		strNIF=strDoc.value;
//		if (strNIF.substring(0,1)=="0") strNIF=strNIF.substring(1);
//		if (strNIF.substring(0,1)=="0") {
//      alert("el NIF no puede empezar por 0");
//			return false;
//		}

		varNIF = parseInt(strNIF.substring(0,strNIF.length-1),10);
		letraNIF =strNIF.charAt(strNIF.length-1);

		if (isNaN(varNIF)) {
			alert("NIF erroneo");
			return false;
		}
		cadena="TRWAGMYFPDXBNJZSQVHLCKET";
		posicion = varNIF % 23;
		letra = cadena.substring(posicion,posicion+1);

		if (letraNIF.toUpperCase() != letra) {
			alert("NIF erroneo");
			return false;
		}
	}
	return true;
}



function validaCIFNIF(strDoc) {
var resul = true;
var temp = strDoc.value.toUpperCase();
var cadenadni = "TRWAGMYFPDXBNJZSQVHLCKE";

	if (temp.length==0) return false;
	if (temp.length<9) {
		var aux='000000000';
		temp=(aux.substring(0,9-temp.length))+temp;
	}
	
	//Comprobacion de formato
	if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp)) resul=false;

  //algoritmo para comprobacion de codigos tipo CIF
  suma = parseInt(temp[2]) + parseInt(temp[4]) + parseInt(temp[6]);
  for (i = 1; i < 8; i += 2) {
    temp1 = 2 * parseInt(temp[i]);
    temp1 += '';
    temp1 = temp1.substring(0,1);
    temp2 = 2 * parseInt(temp[i]);
    temp2 += '';
    temp2 = temp2.substring(1,2);
		
    if (temp2 == '') temp2 = '0';
    suma += (parseInt(temp1) + parseInt(temp2));
  }

  suma += '';
  n = 10 - parseInt(suma.substring(suma.length-1, suma.length));

  if (/^[0-9]{8}[A-Z]{1}$/.test(temp)) { //comprobacion de NIFs estandar
    var posicion = temp.substring(8,0) % 23;
    var letra = cadenadni.charAt(posicion);
    var letradni = temp.charAt(8);
		
    if (letra == letradni) {
      resul= true;
    } else {
      resul= false;
    }
  } else if (/^[KLM]{1}/.test(temp)) { //comprobacion de NIFs especiales (se calculan como CIFs)
    if (temp[8] == String.fromCharCode(64 + n)) {
      resul= true;
    } else  {
      resul = false;
    }
  } else if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp)) { //comprobacion de CIFs
    var temp_n = n + '';
    if (temp[8] == String.fromCharCode(64 + n) || temp[8] == parseInt(temp_n.substring(temp_n.length-1, temp_n.length))) {
      resul= true;    
    } else {
      resul = false;
    }
  } else if (/^[T]{1}/.test(temp)) {//comprobacion de NIE T
    if (temp[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp)) {
      resul= true;
    } else {
      resul = false;
    }
  } else if (/^[XYZ]{1}/.test(temp)) { //comprobacion de NIE XYZ
  	if(temp.substring(0,1)=='X') temp_n=temp.replace('X', '0');
		if(temp.substring(0,1)=='Y') temp_n=temp.replace('Y', '1');
		if(temp.substring(0,1)=='Z') temp_n=temp.replace('Z', '2');

    var pos = temp_n.substring(0, 8) % 23;
    var letra = cadenadni.substring(pos, pos + 1);
    var letranie = temp_n.charAt(8);
    if (letranie == letra) {
      resul = true;
    } else {
      resul = false;
    }
  }

	if(!resul) alert("NIF erroneo");
  return resul;
}

