
// ---------------------------------------------------------------------- //
//                             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
// isDescripcion (s [,eok])            s No está vacio
//
// 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                               //
// ---------------------------------------------------------------------- //

//var mMessage = "Error: no puede dejar este campo vacío";
var mMessage = "No puede dejar este campo vacío";

// p abrevia "prompt"
//var pPrompt = "Error: ES";
var pPrompt = "Error: ES";
//var pAlphanumeric ="Introduzca un texto que contenga sólo letras y/o numeros";
var pAlphanumeric ="Introduzca un texto que contenga sólo letras y/o numeros";
//var pAlphabetic   ="Introduzca un texto que contenga sólo letras";
var pAlphabetic   ="Introduzca un texto que contenga sólo letras";
//var pInteger ="Introduzca un número entero";
var pInteger ="Introduzca un número entero";
//var pNumber ="Introduzca un numero";
var pNumber ="Introduzca un numero";
//var pPhoneNumber ="Introduzca un número de teléfono";
var pPhoneNumber ="Introduzca un número de teléfono";
//var pEmail ="Introduzca una dirección de correo electrónico válida";
var pEmail ="Introduzca una dirección de correo electrónico válida";
//var pName ="Introduzca un texto que contenga solo letras, numeros o espacios";
var pName ="Introduzca un texto que contenga solo letras, numeros o espacios";
//var pNice ="No puede utilizar comillas aqui";
var pNice ="No puede utilizar comillas aqui";
//var pNameUser ="· El usuario sólo puede tener números, letras y los signos - y _ \n· No puede tener menos de 3 caracteres \n· No debe comenzar ni terminar en - o _";
var pNameUser ="El usuario sólo puede tener números, letras y los signos - y _ \n· No puede tener menos de 3 caracteres \n· No debe comenzar ni terminar en - o _";
//var pLogin ="El nombre de usuario no es correcto";
var pLogin ="El nombre de usuario no es correcto";

// 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 = true;

// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑÜ"
var whitespace = " \t\n\r";

// caracteres admitidos en números de telefono
var phoneChars = "()-+ ";

// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
// var mMessage = "Error: no puede dejar este espacio vacio"

// p abrevia "prompt"
// var pPrompt = "Error: ";
// var pAlphanumeric = "Introduzca un texto que contenga solo letras y/o numeros";
// var pAlphabetic   = "Introduzca un texto que contenga solo letras";
// var pInteger = "Introduzca un numero entero";
// var pNumber = "Introduzca un numero";
// var pPhoneNumber = "Introduzca un número de teléfono";
// var pEmail = "Introduzca una dirección de correo electrónico válida";
// var pName = "Introduzca un texto que contenga solo letras, numeros o espacios";
// var pNice = "No puede utilizar comillas aqui";


// m abrevia "missing" (faltante)

// ---------------------------------------------------------------------- //
//                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 == "."))
}

function isCharLogin (c)
{   return ((c >= "0") && (c <= "9") || (c == ".") || (c == "_") || (c == "-"))
}

function isCharAllowed (c)
{   return ((c >= "0") && (c <= "9") || (c == "_") || (c == "-"))
}

// c es letra o digito
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

// ---------------------------------------------------------------------- //
//                          NUMEROS                                       //
// ---------------------------------------------------------------------- //

// 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;
}

// s es un numero (entero o flotante, con o sin signo)
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;
}

// ---------------------------------------------------------------------- //
//                        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))
        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) ) )
        return false;
    }

    return true;
}

// s tiene solo letras, numeros, "." , "-", y "_"
function isLogin (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) || isCharLogin(c) ) )
        return false;
    }

    return true;
}

function isNameUser (s)
// Función para validar el nombre de usuario del portal OCHOANEGOCIO
// El nombre de usuario estará compuesto por letras, números y los signos - y _
// No podrá tener menos de 3 caracteres
{   var i;
	
    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

	var x = s.length;
	var admin = s.split('.');
	
//	alert (s);
//	alert (admin[0]);

//  Si el usuario es el admin.ACRONIMO el campo USUUSU no se le chequea.
//  Encontraría un punto en el nombre y no lo permitiría
	if (admin[0] == 'admin')
		return true;
		
    for (i = 0; i < x; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isCharAllowed(c) ) )
        return false;

		if (i == 0)
			if ((c == '-') || (c == '_'))
			return false;
    }

//alert (eval(x));
//alert (s.charAt(0));	
//alert (s.charAt(eval(x-1)));	
	if (x < 3)
	return false;
	
	if (s.charAt(eval(x-1)) == '-')
	return false;
	
	if (s.charAt(eval(x-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 ) ) );
}

// s tiene solo letras, numeros o espacios en blanco
function isDescription (s)
{
    if (isEmpty(s)) return defaultEmptyOK;
	return true;
}

// ---------------------------------------------------------------------- //
//                           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;
    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;
}

//ayuda a evitar comillas simples
//   o dobles que causan problemas con muchos CGIs
function isNice(s)
{
        var i = 1;
        var sLength = s.length;
        var b = 1;
        while(i<sLength) {
                if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
                i++;
        }
        return b;
}

// ---------------------------------------------------------------------- //
//                  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)
{   
    alert(mMessage)
    statBar(mMessage)
    theField.focus()
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   
    theField.select()
    alert(s)
    statBar(pPrompt + s)
    theField.focus()
    return false
}

// el corazon de todo: checkField
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 == isPhoneNumber ) msg = pPhoneNumber;
        if( theFunction == isName ) msg = pName;
        if( theFunction == isDescription ) msg = pAlphanumeric;
        if( theFunction == isNameUser ) msg = pNameUser;
        if( theFunction == isLogin ) msg = pLogin;
    }
    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField);

    if ( checkNiceness && !isNice(theField.value))
        return warnInvalid(theField, pNice);

    if (theFunction(theField.value) == true) 
        return true;
    else
        return warnInvalid(theField,msg);

}

function Trim(cadena)
{
  var comienzo = 0;
  var fin = 0;
  var caracter;
  var longitud = cadena.length;

  for(var i=0; i<longitud; i++)
  {
    caracter = cadena.substring(i,i+1);
    if(caracter == " ") comienzo++;
    else break;
  }

  for(var i=longitud; i>0; i--)
  {
    caracter = cadena.substring(i-1,i);
    if(caracter == " ") fin--;
    else break;
  }

  if(fin == 0)
  {
    return cadena.slice(comienzo);
  }
  return cadena.slice(comienzo,fin);
}
