var whitespace = " \t\n\r";

function Validar(Objeto,NombreMostrar ,LongitudMax,LongitudMin,Obligatorio,Numerico,Fecha,Texto) {
//Objeto es el objeto que deseamos comprobar
//NombreMostrar es el nombre con el con que nos referimos al campo a validar
//LongitudMax es un numero que indica la longitud máxima del campo
//LongitudMin es un número que indica la longitud mínima del campo
//Obligatorio es un S/N que indica si el campo es obligatorio o no
//Numérico es un S/N que indica si el campo ha de contener sólo números
//Fecha es un S/N que indica que el campo es de tipo fecha. El ormato es de dd/mm/aaaa
//Texto es un S/N que indica si el campo es de tipo texto.

//Validamos si el campo es de obligatorio. Si lo es y no ha escrito nada se le pone el foco al campo y se pide que se rellene

if ((Obligatorio == "S" ) && (Objeto.value == "")){
        alert("El Campo " + NombreMostrar + " es obligatorio y no se ha introducido ningún valor. Por favor rellénelo");
        return false;
}
else {
        //validamos que el texto introducido no superé la longitud máxima permitida
        if (Objeto.value.length > LongitudMax) {
                alert("La longitud del texto introducido en " + NombreMostrar + " no puede superar los " + LongitudMax + " caracteres");
                return false;   
        }
        else {
                //validamos que el texto introducido no sea inferior a la longitud mínima permitida
                if ( Objeto.value.length < LongitudMin ) {
                        alert("La longitud del texto introducido en " + NombreMostrar + " no puede ser inferior a " + LongitudMin + " caracteres");
                        return false;
                }
                else {
                        //Validamos si el campo es numérico
                        if ((Numerico == "S") && (isNaN(Objeto.value))) {
                                alert("El valor de " + NombreMostrar + " ha de ser numérico. No introduzca signos de puntuación.");
                                return false;
                        }
                        //Validamos si el campo es de tipo fecha
                        else{
                                if (Fecha=="S"){
                                        if (Comprobar_Fecha(strFecha)==false){
                                                alert("La fecha de " + NombreMostrar + " no es correcta. Compruebe que el formato es DD/MM/AA.");
                                                return false;
                                        }
                                        else
                                                return true;
                                }
                                else
                                        return true;    
                        }
                }
        }
}
}

function Comprobar_Fecha(cadena) {
        //Validamos el tamaño de la cadena
        if (cadena.length!=10) {
                return false;
        }
        else {
                //Validamos que todos los campos sean numeros o "/"
                if (EsCaracterFecha(cadena)==false){
                        return false;
                }
                else {  //Validamos que se trate de una fecha
                        var strFecha;
                        strFecha = cadena.charAt(3)+ cadena.charAt(4)
                        strFecha = strFecha + cadena.charAt(2)+ cadena.charAt(0)+ cadena.charAt(1)
                        strFecha = strFecha + cadena.charAt(5)+ cadena.charAt(6)+ cadena.charAt(7)
                        strFecha = strFecha + cadena.charAt(8)+ cadena.charAt(9)
                        if (EsFechaValida(strFecha)==false) {
                                return false;
                        }
                        else {
                                return true;
                        }
                }
        }
}

function EsFechaValida(dateStr) {
        // Chequea los formatos:
        // MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
        
        // Si es año es de 2 o 4 posiciones usar esta línea
        //var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

        // si el año es de 4 posiciones obligatoriamente usar esta línea
        var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
        
        var matchArray = dateStr.match(datePat); // comprueba el formato.
        if (matchArray == null) {
                return false;
        }
        month = matchArray[1]; // desglosamos en variables
        day = matchArray[3];
        year = matchArray[4];
        if (month < 1 || month > 12) { // chequeamos el mes.
                return false;
        }
        if (day < 1 || day > 31) {
                return false;
        }
        if ((month==4 || month==6 || month==9 || month==11) && day==31) {
                return false
        }
        if (month == 2) { // chequea el 29 de febrero
                var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
                if (day>29 || (day==29 && !isleap)) {
                        return false;
                }
        }
        return true;  // la fecha es válida.
}
function EsCaracterFecha(Fecha){
//recorremos toda la fecha y validamos que todos los caracteres son numeros o la "/"
//Los carateres de las posiciones 2 y 5 son los separadores, y el resto números
        for (var i = 0; i < Fecha.length; i++){
                        var Caracter = Fecha.charAt(i)                  
                        if (i!=2 && i!=5){
                           if (Caracter < "0" || Caracter > "9"){
                                                return false;
                           }
                        }
                        else{
                           if (Caracter!="/")
                                  return false;
                        }                       
        }
        return true;
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return false;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}



// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function isPositiveInteger (s)
{   var secondArg = false;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) > 0) ) );
}

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return false;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = false;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}


function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return false;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}


function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}