var defaultEmptyOK = false
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ"
var whitespace = " \t\n\r";
var phoneChars = "()-+ ";

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function ValidBlanks(frmField,strFldName)
{
	if (frmField.value == "" || frmField.value == null || frmField.value == " " ){
		return false;
	} else{
		return true;
	}
}
//CAMBIO añadir esta funcion 
function BusqCaracteres(texto)
{
	var txt = texto.toString()
	var valido = true
	for(var i = 0;i < texto.length;i++)
	{
		var oneChar = txt.charAt(i)
		if (oneChar == "<" || oneChar == ">"  || oneChar == "#" || oneChar == "/" || oneChar == '\"'  || oneChar == "\'" || oneChar == "\\"  )
		{
			valido = false
		}
	}
	if (!valido)
		return false
	else
		return true
	
}
function ValidField(strFldName,frmField,intLength,strDtType,obligatorio,campo_2nombre,campo_2)
{	
frmField = eval(frmField);
campo_2 = eval(campo_2);
obligatorio=eval(obligatorio);

	
	switch (strDtType)
		{
			case 'string' : 
						if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if (!BusqCaracteres(frmField.value)){
									error="  NO es correcto porque tiene caracteres extraños";
									return reporter(frmField,strFldName,error);
								}
								if (frmField.value.length > intLength){
									error="  NO es correcto porque supera los "+ intLength + " caracteres";
									return reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}
						break;
			case 'mail': 
						if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if (!isEmail(frmField.value)){
									error="  NO es correcto porque esta mal formado";
									return reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}
					break;	
			case 'nif': 
						if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if (!isNif(frmField.value)){
									error="  NO es correcto porque no es NIF correcto";
									return reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}
						
				break;				
			case 'number': 
						if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if (!isNumber(frmField.value)){
									error="  NO es correcto porque debe ser númerico";
									return reporter(frmField,strFldName,error);
								}if (frmField.value.length > intLength){
									error="  NO es correcto porque supera los "+ intLength + " caracteres";
									return reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}
					
				break;
			case 'hour': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if (!isHour(frmField.value)){
									error="  No es una hora correcta.El formato correcto es 00:00.";
									return reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}		
				break;
					
			case 'date': 
					 if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if (!isDate(frmField.value)){
									error="  No es una fecha correcta. El formato correcto es DD/MM/AAAA.";
									reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}
					
				break;
			case 'list' : 
                    if ((obligatorio) && (frmField.selectedIndex==0)){
                         
						if(!reporteErr==true){
							alert("Debe seleccionar algún valor de la lista " + strFldName);
							frmField.focus();
							return false;
						}else{
							txt+="Debe seleccionar algún valor de la lista " + strFldName+"\n";
							campFocus.push(frmField);
						}
					}
				break;

	case 'phone' : 
					 if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							if(ValidBlanks(frmField,strFldName)){
								if ((frmField.value.length<9)||(frmField.value.length>11)){
									error="  No es un numero correcto debe tener entre 9-11 caracteres.";
									return reporter(frmField,strFldName,error);
								}else{
									return true;
								}
							}
						}
					break;
	case 'compare' :
					
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))){
							error="  es obligatorio";
							return reporter(frmField,strFldName,error);
						}else{
							
							if(ValidBlanks(!frmField,strFldName) && isDate(frmField.value) ){
								error="no es una fecha o bien no esta bien compuesto";	
								return reporter(frmField,strFldName,error);
							}
							
							if(ValidBlanks(!campo_2,campo_2nombre) && isDate(campo_2.value)){
								error="no es una fecha o bien no esta bien compuesto";	
								return reporter(campo_2,campo_2nombre,error);
							}
							
							if(compDates(frmField.value,campo_2.value)==1){
								error="no puede ser inferior al campo "+strFldName;	
								return reporter(campo_2,campo_2nombre,error);
							}else{
								return true;
							}
						}
					break;
	}
	// fin del interuptor
	
}


function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

function isNumber (s)
{   
/*    var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "," ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && c != ".") return false;
        } else { 
            if ( c == "," ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
	if(s<0) return false;
	isInteger(s);
    return true;*/
	var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    if(s<0) return false;
	return true;
}

function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}


function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

letras = 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");
function isNif(nif)
{
  nif=nif.toLowerCase();
  nifcorrecto = true;
  dni=nif.substring(0,nif.length-1);
  dni=parseInt(dni);
  letra=nif.charAt(nif.length-1);
  letraCorrecta = letras[ dni % 23];

  if (dni > 99999999)
    nifcorrecto = false;
  if(letra!=letraCorrecta)
    nifcorrecto = false;
    
   if (nifcorrecto) 
	return true;
   else
	return false;
}

function isPhoneNumber (s)
{   var modString;
    if (isEmpty(s)) 
      if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
      else return (isPhoneNumber.arguments[1] == true);			 
    	modString = stripCharsInBag( s, phoneChars );				
			return (isInteger(modString))
}

function isEmail (s) 
{
	if (isEmpty(s))
		return false; 
	var i = 1; var sLength = s.length; 
	while ((i < sLength) && (s.charAt(i) != "@")) 
	{ 
		i++;
	}
	if ((i >= sLength) || (s.charAt(i) != "@")) 
		return false; 
	else 
		i += 2;
	
	while ((i < sLength) && (s.charAt(i) != ".")) 
	{
		i++; 
	}
	if ((i >= sLength - 1) || (s.charAt(i) != ".")) 
	 	return false; 

	
	else return true; 
} 
function isHour(s)
{
	var Horacorrecta=true
	var horas,min
	horas=parseInt(s.substring(0,2),10)
	min=parseInt(s.substring(3,5),10)
	
	if(s.length!=5) Horacorrecta=false;
	if(s.indexOf(':')==-1) Horacorrecta=false;
	if(horas>24|| horas<0) Horacorrecta=false;
	if(min>60 || min<0) Horacorrecta=false;
	if(isNaN(horas))Horacorrecta=false;
	if(isNaN(min))Horacorrecta=false;
		
	if(Horacorrecta)
		return true
	else
		return false
}
function isDate(s)
{
    var day,month,year,mod,chr
    if (s==null || s.length==0)
        return true
    if (s.length!=10)
        return false

    for (var ij=0;ij<10;ij++)
    {
        chr=s.charAt(ij)
        if (ij!=2 && ij!=5)
        {
            if (chr<"0"||chr>"9") return false
        }
        else
        {
            if (chr!="/") return false
        }
    }


	tempoDate=s.split("/");
	day=parseInt(tempoDate[0],10);
    month=parseInt(tempoDate[1],10);
    year=parseInt(tempoDate[2],10);

    if (1>day || day>31)
        return false
    if (1>month || month>12)
        return false
    if ((1>year)&&(year.length!=4))
        return false
    if ((month==4 || month==6 || month==9 || month==11) && day==31)
        return false
    if (month==2)
    {
        mod=year%4
    	if (mod==0)
    	{
            mod=year%100
	    if(mod==0)
	    {
                var mod2=year%400
                if(mod2==0 &&  day>29)
                    return false
                else if(mod2!=0 && day>28)
                    return false
            }
	    else if(day>29)
	        return false
        }
        else if (day>28)
            return false
    }
    return true 		
}

function compDates(s1,s2)
{
    var f1, f2	

    f1 = s1.substring(6,10) + "/";    
    f1 = f1 + s1.substring(3,5) + "/";
    f1 = f1 + s1.substring(0,2);

    f2 = s2.substring(6,10) + "/";    
    f2 = f2 + s2.substring(3,5) + "/";
    f2 = f2 + s2.substring(0,2);
	if (f1 == f2) 
		return 0
	else	
    	return (f1 < f2) + 1
}

function stripCharsInBag(origen, filtro){	
	re = new RegExp("["+filtro+"]","gi")
	var resultado = "";
  resultado = origen.replace(re,""); 	
	return resultado;
}

function trim(s) 
{
	while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

 while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function reporter(campo,campo_nombe,error){
		
		if(reporteErr!=true){
			alert("El contenido del campo ==>  " + campo_nombe + error);
			campo.focus();
			return false;
		}else{
			txt+="El contenido del campo ==>  " + campo_nombe + error + "\n"; 
			campFocus.push(campo);
			return false;
		}
}

function envioValidar(txt){
	
	if(txt == ""){
		document.forms[valida[0][0]].submit();
		return true;
	}else{
		cab = "No se ha podido efectuar el envio del formulario por los siguientes errores:";
		alert (cab+"\n"+"\n"+txt);
		campFocus[0].focus();
		delete campFocus;
		return false;
	}
}
function indiz(formulario,campo){
	if( !isNaN(formulario) && !isNaN(campo) ){
		val = "document.forms[" + formulario + "][" + campo + "]"
		return val;
	}else if ( isNaN(formulario) && isNaN(campo) ){
		val= "document."+formulario+"."+campo;
		return val;
	}else if ( !isNaN(formulario) && isNaN(campo) ){
		val= "document.forms[" + formulario + "]."+campo;
		return val;
	}else if ( isNaN(formulario) && !isNaN(campo) ){
		val= "document."+formulario+".elements["+campo+"]";
		return val;
	}
}
function validaForms(){
	campFocus=new Array();
	txt="";
	for(i=0;i<valida.length;i++){
		formulario = valida[i][0];
		nombreComun = valida[i][1];
		campo = valida[i][2] ;
		valor = indiz(formulario,campo)
		accion = valida[i][4];
		maxi = valida[i][3];
		obligatorio = valida[i][5];
		campo_2nombre = valida[i][6];
		campo2 = valida[i][7];
		if( !isEmpty(campo_2nombre) || !isEmpty(campo2) ){
			campo_2 = indiz(formulario,campo2) 
		}else{
			campo_2 = "document.forms[0][0]"
		}
		
		// I M P O R T A N T E
		// se debe de igualar la acción a la que tengamos para no ponerla mal o bien para declarar una que no exista
		if(accion=="number" || accion=="string" || accion=="list" || accion=="mail" || accion=="phone"){
			eval("ValidField('"+nombreComun+"','"+valor+"',"+maxi+",'"+accion+"','"+obligatorio+"','"+campo_2nombre+"','"+campo_2 +"')")
		}else{
				alert("AVISO AL DESARROLLADOR"+"\n"+"\n"+"esta mal configurado el array de validaciones, has puesto una accion que esta mal escrita o no esta validada"+"\n"+"\n"+"asegurate de que la instruccion que usas esta validada  en la funcion validaForms(); ")
				return false;
			}		
}
return envioValidar(txt);
}
