// ---------------------------------------------------------------------- //
//                                VARIABLES                               //
// ---------------------------------------------------------------------- //
// defaultEmptyOk --> Indica si el hecho de tener un campo vacio es correcto
//                    normalmente debería estar a false.
// digits --> Lista de caracteres que representan dígitos
// lowercaseLetters --> Lista de caracteres que son letras (no numeros)
// uppercaseLetters --> Lo mismo pero en mayúsculas
// whitespace --> Lista de caracteres que son blancos en javascript
// phoneChars --> caracteres válidos en un campo telefónico
// ---------------------------------------------------------------------- //

// ---------------------------------------------------------------------- //
//                          FUNCIONALIDADES                               //
// ---------------------------------------------------------------------- //
//
// isEmpty(s)  --> Cadena vacío. devuelve true o false
// isWhitespace(s) --> Cadena con espacios o vacío. Devuelve true o false
// stripQuote(s) --> Quita "'" de una cadena. Devuelve la cadena.
// stripCharsInBag (s,bag) --> quita los chars de s que estén en bag. 
//							   devuelve la cadena corregida
// stripCharsNotInBag (s,bag) --> quita los chars de s que no estén en bag.
//							      devuelve la cadena corregida
// stripWhitespace (s) --> Quita los blancos. Devuelve la cadena
// charInString (c, s) --> Indica si el char c está en la cadena
// stripInitialWhitespace (s) --> Quita los blancos al principio. 
// isLetter (c) --> Indica si el char c está en lowercaseletters o upper.
// isDigit(c) --> Indica si el char c esta en digits
// isLetterOrDigit(c) --> isLetter || isDigit
// isInteger(s) --> para todo c en s isDigit(c)
// isNumber(s) --> numeros reales (.) con signo (+,-)
// isAlphabetic(s) --> para todo c en s isLetter(c)
// isAlphaOrSpace(s) --> para todo c en s isLetter(c) || c==" "
// isAlphanumeric(s) --> para todo c en s isLetter(c) || isDigit(c)
// isName(s) --> isAlphanumeric(s) || isAlphanumeric(stripWhitespace(s))
// isPhoneNumber(s) --> para todo c en s, isDigit(s) || c en phoneChars
// isEmail(s) --> s es un email válido
// isFecha(d,m,a) --> verifica la fecha
// checkField(theField,theFunction,isEmptyOk,s) --> VERIFICADOR DE CAMPOS
//		theField --> CONTROL que se quiere verificar
//		theFunction --> FUNCION con la que se quiere verificar
//		isEmptyOk --> ¿Está bien que esté vacío? --> FALSE
//		s --> mensaje a mostrar si hay error
//	Esta función devuelve TRUE cuando el campo está correcto.
//	si devuelve FALSE deja el focus en el campo malo y muestra el mensaje s
//
//	ejemplo de funcion verificadora de datos de un formulario
//
//	function validar(){
//		if(!checkfield(...)) return false;
//		...
//		return true;
//	}
// ---------------------------------------------------------------------- //

var defaultEmptyOK = false
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü,().;$#&¿?!%ª/<>:\"|@_ºª¡-+*{}[]="
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ_,().;$#&¿?!%ª/<>:\"|@ºª¡-+*{}[]="
var whitespace = " \t\n\r";
var phoneChars = "()-+ ";



// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar este espacio vacío, es obligatorio "
// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = "Ingrese un texto que contenga solo letras y/o números";
var pAlphabetic   = "Ingrese un texto que contenga solo letras";
var pInteger = "Ingrese un número entero";
var pNumber = "Ingrese un número";
var pPhoneNumber = "Ingrese un número de teléfono";
var pEmail = "Ingrese una dirección de correo electrónico válida\n Ej: agv@i.cl";
var pName = "Ingrese un texto que contenga solo letras, números";

//var antes = "Error: Debe "
//var despues = ", Por favor";

var antes = ""
var despues = "";

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

function isBlanco (s)
{
	if (s = "")
		return false;
	else
		return true;
}


function isEmpty(s)
{   
	return ((s == null) || (s.length == 0))
}

function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

function stripQuote(s)
{
	var i;
    var returnString = "";

    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (c!="'") returnString += c;
        else returnString += " ";
    }

    return returnString;
}

function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Buscar por el string, si el caracter no esta en "bag", 
    // agregarlo a returnString
    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

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)) return false;
        } else { 
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

function isAlphaOrSpace(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))&&(whitespace.indexOf(c) == -1))
        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 ) ) );
}

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)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(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 statBar (s)
{   window.status = s
}

function warnEmpty (theField,s)
{   if(!theField.disabled) theField.focus();
    alert(antes + s + despues)
    statBar(antes + s + despues)
    return false
}

function warnInvalid (theField, s)
{   if(!theField.disabled) theField.focus()
    theField.select()
    alert(antes + s + despues)
    statBar(pPrompt + s)
    return false
}

function checkField (theField, theFunction, emptyOK, s)
{   
    var msg;
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 4) {
        msg = s;
    } else {
        //if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        //if( theFunction == isInteger ) msg = pInteger;
        //if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isName ) msg = pName;
        //if( theFunction == isPhoneNumber ) msg = pPhoneNumber;        
    }    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField, s); //aqui

    if (theFunction(theField.value) == true) 
        return true;
    else
        return warnInvalid(theField,msg);
}

function isFecha(d,m,a)
{
  var dd = parseInt(d,10);
  var mm = parseInt(m,10);
  var aa = parseInt(a,10);
  if( isNaN(dd) || isNaN(mm) || isNaN(aa) || dd < 1 || aa < 1 )
  	return false;
  if (mm>12 ||mm<1)	
  	return false;
  var Dias;
  Dias = new Array(12);
  Dias[0] = 31;
  Dias[1] = 28;
  Dias[2] = 31;
  Dias[3] = 30;
  Dias[4] = 31;
  Dias[5] = 30;
  Dias[6] = 31;
  Dias[7] = 31;
  Dias[8] = 30;
  Dias[9] = 31;
  Dias[10] = 30;
  Dias[11] = 31;
  if( (mm == 2) && (aa % 4 == 0 && aa % 100 == 0) || (aa % 400 == 0) )
	  Dias[1] = 29;
  if( dd > Dias[mm-1] )
	return false
  return true;
}

function EsFechaMenor(dd,mm,aa,ddh,mmh,aah)
{ 
if (parseInt(aa) > parseInt(aah))
	{	//alert("hh1");//AÑO
		return false;
	}
	else
    {	
	  if (parseInt(aa) < parseInt(aah)) 
	  { //alert("hh2");
	  	
	  	return true;
	  }
	  else
	  { 
		if (parseInt(mm) > parseInt(mmh))
		{		//	alert("hh3");
		 			//MES
			return false;
		}
		else
		{ 
		  if (parseInt(mm) < parseInt(mmh))
		    { //alert("hh4");
				return true;
			}
			else
			{ 
			if (parseInt(dd) > parseInt(ddh))
			   {		//alert("hh5");			 			//DIA
				return false;
				}
				else
				{ 
				  if (parseInt(dd) < parseInt(ddh))
				    {//alert("hh6");
					  return true;
					}
					else
					{//alert("hh7");
    			      return true;
					}
				}
			}								
		}
 	 }
							
   }

}
