// ---------------------------------------------------------------------- //
//           FormCheq.js (c) ChaTo 1998,1999 [www.chato.cl]
//                           Basado en:
//           FormChek.js (c) Eric Krock (c) 1997 Netscape              
// ---------------------------------------------------------------------- //
// 18 Feb 97 creado por Eric Krock (c) 1997
//   Netscape Communications Corporation
// 18 Ago 98 modificado por Carlos Castillo (c) 1998 ChaTo
//   Los principales cambios son: esta version es simplificada, para
//   propositos de ensennanza y validacion basica de formularios, y esta
//   adaptada para recibir caracteres del alfabeto espannol (acentos, etc.)
// 20 Oct 99 modificado por Carlos Castillo (c) 1999 ChaTo
//   Se agrega la funcion isNice que ayuda a evitar comillas simples
//   o dobles que causan problemas con muchos CGIs
// 
// ---------------------------------------------------------------------- //
//                             RESUMEN                                    //
// ---------------------------------------------------------------------- //
// 
// El objetivo de las siguientes funciones en JavaScript es
// validar los ingresos del usuario en un formulario antes
// de que estos datos vayan al servidor.
//
// Varias de ellas toman un parametro opcional E.O.K (eok) (emptyOK
// - true si se acepta que el valor este vacio, false si no
// se acepta). El valor por omision es el que indique la
// variable global defaultEmptyOK definida mas abajo.
//
// ---------------------------------------------------------------------- //
//                      SINTAXIS DE LAS FUNCIONES                         //
// ---------------------------------------------------------------------- //
//
// FUNCION PARA CHEQUEAR UN CAMPO DE INGRESO:
//
// checkField (theField, theFunction, [, s] [,eok])
//        verifica que el campo de ingreso theField cumpla con la
//        condicion indicada en la funcion theFunction (que puede ser
//        una de las descritas en "FUNCIONES DE VALIDACION" o cualquier
//        otra provista por el usuario). En caso contrario despliega el
//        string "s" (opcional, hay mensajes por default para las
//        funciones de validacion provistas aqui).
//
// FUNCIONES DE VALIDACION:
//
// isInteger (s [,eok])                s representa un entero
// isNumber (s [,eok])                 s es entero o tiene punto decimal
// isAlphabetic (s [,eok])             s tiene solo letras
// isAlphanumeric (s [,eok])           s tiene solo letras y/o numeros
// isPhoneNumber (s [,eok])            s tiene solo numeros, (,),-
// isEmail (s [,eok])                  s es una direccion de e-mail
//
// FUNCIONES INTERNAS:
//
// isWhitespace (s)                    s es vacio o solo son espacios
// isLetter (c)                        c es una letra
// isDigit (c)                         c es un digito
// isLetterOrDigit (c)                 c es letra o digito
//
// FUNCIONES PARA REFORMATEAR DATOS:
//
// stripCharsInBag (s, bag)            quita de s los caracteres en bag
// stripCharsNotInBag (s, bag)         quita de s los caracteres NO en bag
// stripWhitespace (s)                 quita el espacio dentro de s
// stripInitialWhitespace (s)          quita el espacio al principio de s
//
// FUNCIONES PARA PREGUNTARLE AL USUARIO:
//
// statBar (s)                         pone s en la barra de estado
// warnEmpty (theField, s)             indica que theField esta vacio
// warnInvalid (theField, s)           indica que theField es invalido
//
// ---------------------------------------------------------------------- //
//                                VARIABLES                               //
// ---------------------------------------------------------------------- //

// Esta variable indica si está bien dejar las casillas
// en blanco como regla general
var defaultEmptyOK = false

// Esta variable indica si se debe verificar la presencia de comillas
// u otros símbolos extraños en un campo, por omisión no, porque
// siempre crea problemas con las bases de datos o programas CGI
var checkNiceness = false;

// listas de caracteres
var digits = "0123456789";
var specialChars = ",.:;?¿!¡/*-\"";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ"
var whitespace = " \t\n\r";

//Caracteres admitidos para el url
var urlChars = ":/.-_?&+=%";

// caracteres admitidos en nos de telefono
var phoneChars = "()-+ ";

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

// m abrevia "missing" (faltante)
var mMessage = "Error:"

// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = " debe contener solo letras y/o numeros";
var pAlphanumericNoWhiteSpaces = " debe contener solo letras y/o numeros sin espacios en blanco";
var pDomain = " debe contener solo letras, numeros y guiones sin espacios en blanco";
var pNotWhiteSpaces = " no debe poseer espacios en blanco";
var pAlphabetic   = " debe contener solo letras";
var pInteger = " debe ser un número entero";
var pNumber = " debe ser numérico";
var pPhoneNumber = " debe ser un número de teléfono válido";
var pEmail = " debe ser una dirección de correo electrónico válida";
var pName = " debe contener solo letras, numeros y espacios";
var pNice = " no debe poseer comillas ('')";
var pUrl = "Url inválido";
var pPassword = " no coincide con la verificación";
var pSelect= " debe ser seleccionado";
var pText= " debe ser un texto válido";
var pDate= " debe ser una fecha válida";

// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //

// JavaScript 1.0 (Netscape 2.0) no tenia un constructor para arreglos,
// asi que ellos tenian que ser hechos a mano. Desde JavaScript 1.1 
// (Netscape 3.0) en adelante, las funciones de manejo de arreglos no
// son necesarias.

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
}

// ---------------------------------------------------------------------- //
//                  CODIGO PARA FUNCIONES BASICAS                         //
// ---------------------------------------------------------------------- //


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

// s es vacio o solo caracteres de espacio
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;
}

// Quita todos los caracteres que que estan en "bag" del string "s" s.
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;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
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;
}

// Quitar todos los espacios en blanco de un string
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

// La rutina siguiente es para cubrir un bug en Netscape
// 2.0.2 - seria mejor usar indexOf, pero si se hace
// asi stripInitialWhitespace() no funcionaria

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

// Quita todos los espacios que antecedan al string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// c es una letra del alfabeto espanol
function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) || ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// c es letra o digito
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

//c es un caracter válido de url
function isUrlChar (c) {
	return (urlChars.indexOf( c ) != -1)	
}

//c es un caracter valido para un texto
function isSpecialChars(c) {	
	return (specialChars.indexOf( c ) != -1)
}

// ---------------------------------------------------------------------- //
//                          NUMEROS                                       //
// ---------------------------------------------------------------------- //

function isGreaterThanZero (s) {

	if (isEmpty(s)) {
  	if (isGreaterThanZero.arguments.length == 1) {
			return defaultEmptyOK;
		}
		else {
			return (isInteger.arguments[1] == true);
		}
	}
  else {
		return (s>"0");
	}
}

// s es un numero entero (con o sin signo)
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)
{
	if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;    	
	return (s.search(/^(?:\+|-)?\d+(.|,)+d*$/) != -1);
}


// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //

// s tiene solo letras
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) || isWhitespace(c) ) )
        return false;
    }
    return true;
}

// s tiene letras numeros y caracteres especiales 
function isText(s)
{   var i;

    if (isEmpty(s)) 
       if (isText.arguments.length == 1) return defaultEmptyOK;
       else return (isText.arguments[1] == true);
	   
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (! ( isLetter(c) || isDigit(c)|| isWhitespace(c) || isSpecialChars(c) ) )
        return false;
    }
    return true;
}




// s tiene solo letras y numeros
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)|| isWhitespace(c) ) )
        return false;
    }

    return true;
}

// s tiene solo letras y numeros y no posee espacios en blanco
function isAlphanumericNoWhiteSpaces (s)
{   var i;
    if (isEmpty(s)) 
       if (isAlphanumericNoWhiteSpaces.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumericNoWhiteSpaces.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if ( (!isLetter(c) && !isDigit(c)) ) {
	        return false;
				}
		else {
			if (whitespace.indexOf(c) != -1) {
				return false;
			} 
		}
    }

    return true;
}

function isDomain (s)
{   var i;
    if (isEmpty(s)) 
       if (isAlphanumericNoWhiteSpaces.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumericNoWhiteSpaces.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
		
        if ( (!isLetter(c) && !isDigit(c) && c!="-") ) {
	        return false;
		}
		else {
			if (whitespace.indexOf(c) != -1) {
				return false;
			} 
		}
    }

    return true;
}

// s no posee espacios en blanco
function isNotWhiteSpaces (s) {   
	var i;
    if (isEmpty(s)) 
       if (isNotWhiteSpaces.arguments.length == 1) return defaultEmptyOK;
       else return (isNotWhiteSpaces.arguments[1] == true);
    for (i = 0; i < s.length; i++) {   
        var c = s.charAt(i);
       	if (whitespace.indexOf(c) != -1) {
			return false;
		} 
	}
   return true;
}


// s tiene solo letras, numeros o espacios en blanco
function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

// ---------------------------------------------------------------------- //
//                           FONO o EMAIL                                 //
// ---------------------------------------------------------------------- //

// s es numero de telefono valido
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))
}

// s es una direccion de correo valida
function isEmail (s)
{
  	if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;    	
	return (s.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}

function isDate(s)
{
	if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;
	
	return (s.search(/^([012][0-9]|3[01])(-)(0[0-9]|1[012])\2(\d{4})$/) != -1);
}

function isNice(s)
{
		var i = 0;
		var sLength = s.length;
		var b = 1;
		while(i<sLength) {
			if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
			i++;
		}
		return b;
}

function isUrl(s) {
	
	for (i = 0; i < s.length; i++) {   
		var c = s.charAt(i);
		if ( !(isLetterOrDigit(c) || isUrlChar(c) ) )
			return false;
		}
	
		return true;	
}


// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA RECLAMARLE AL USUARIO                  //
// ---------------------------------------------------------------------- //

// pone el string s en la barra de estado
function statBar (s)
{   window.status = s
}

// notificar que el campo theField esta vacio
function warnEmpty (theField, theFieldName)
{   theField.focus()
    alert(mMessage+' El campo '+theFieldName+' es obligatorio. ')
    //statBar(mMessage)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, theFieldName, s)
{   //theField.focus()

    theField.focus()
     alert(mMessage+' El campo '+theFieldName+s)
    //statBar(pPrompt + s)
    return false
}

// el corazon de todo: checkField
//theField: el campo a validar (obligatorio)
//emptyOK: indica si el campo puede o no ser vacío (opcional)
//En caso de no incluirse, se toma defaultEmptyOK
//theFunction: la función que valida el tipo de dato del campo (opcional)
//En caso de no incluirse se asume que el campo puede contener cualquier valor
//s: un string con el mensaje que se va a mostrar en caso de que el campo no pase la prueba de validación
function checkField (theField, theFieldName, emptyOK, theFunction, s) {   

	var msg;
	var areFunction=0;

	if (checkField.arguments.length == 2) {
		emptyOK = defaultEmptyOK;

	}
	else {
		if (checkField.arguments.length == 3) {
			//No se hace nada pues solo se quier validar que el campo no sea vacío
		}
		else {

			if (checkField.arguments.length == 4) {

				if( theFunction == isAlphabetic ) { 
					msg = pAlphabetic; 
					areFunction=1;
				} 
				if( theFunction == isAlphanumeric ) { 
					msg = pAlphanumeric; 
					areFunction=1;
				}
				if( theFunction == isAlphanumericNoWhiteSpaces ) { 
//alert ("entro"+theFunction);
					msg = pAlphanumericNoWhiteSpaces; 
					areFunction=1;
				}
				if( theFunction == isNotWhiteSpaces ) { 
					msg = pNotWhiteSpaces; 
					areFunction=1;
				}
				if( theFunction == isInteger ) { 
					msg = pInteger; 
					areFunction=1;
				}				
				if( theFunction == isNumber ) { 
					msg = pNumber; 
					areFunction=1;
				}
				if( theFunction == isEmail ) { 
					msg = pEmail; 
					areFunction=1;
				}
				if( theFunction == isPhoneNumber ) { 
					msg = pPhoneNumber;  
					areFunction=1;
				}
				if( theFunction == isName ) { 
					msg = pName; 
					areFunction=1;
				}
				if( theFunction == isGreaterThanZero ) { 
					msg = pSelect; 
					areFunction=1;

				}
				if( theFunction == isDomain ) { 
					msg = pDomain; 
					areFunction=1;

				}
				if( theFunction == isUrl ) { 
					msg = pUrl; 
					areFunction=1;

				}
				if( theFunction == isText ) { 
					msg = pText; 
					areFunction=1;

				}
				if( theFunction == isDate ) { 
					msg = pDate; 
					areFunction=1;
				}
			}
			else {
				if (checkField.arguments.length == 5) {
					msg=s;
				}
			}
		}
	}

	if ((emptyOK == true) && (isEmpty(theField.value))) {
		return true;	
	}

	if ((emptyOK == false) && (isEmpty(theField.value))) {
		return warnEmpty(theField, theFieldName);
	}

	if ( checkNiceness && !isNice(theField.value)) {
		alert("entro");
			return warnInvalid(theField, theFieldName, pNice);
	}
	
	if (areFunction && theFunction(theField.value) == true) {

			return true;
	} else {

			if (!areFunction) {
				return true;
			} else {

				return warnInvalid(theField, theFieldName, msg);
			}
	}

}

var tmpValue;
function checkLength(theField, sLength) {
	if (theField.value.length>=sLength) {
		theField.value=tmpValue;
		return;
	}	
	tmpValue=theField.value;
}


function isEqual(theField1, theField2, theFieldName) {
	if (theField1.value==theField2.value) {
		return true;
	}
	else {
		return warnInvalid(theField2, theFieldName, pPassword);		
	}
}	


