// ---------------------------------------------------------------------- //
//           FormCheq.js (c) ChaTo, simplificacion/traduccion             //
//              											              //
// ---------------------------------------------------------------------- //
// 
// ---------------------------------------------------------------------- //
//                             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, (,),-
// isAnything(s [,eok])				   Vale todo excepto que metan un nº
// 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

// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = " abcdefghijklmno.pqrstuvwxyzáéíóúñü¿?¡!"
var uppercaseLetters = " ABCDEFGHIJKLMNO.PQRSTUVWXYZÁÉÍÓÚÑ¿?¡!"
var whitespace = " \t\n\r";
// caracteres admitidos en nos de telefono
//var phoneChars = "()-+ ";
var phoneChars = "";
// ---------------------------------------------------------------------- //
//          TEXTOS PARA LOS MENSAJES. AÑADIR MENSAJES DE ERROR AQUÍ       //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar vacio el campo "

// p abrevia "prompt"
var pPrompt = "Error: ";
var pEntryPrompt=" Introduzca el campo "

var pAlphanumeric = "ingrese un texto que contenga solo letras y/o numeros en el campo ";
var pAlphabetic   = "ingrese un texto que contenga solo letras en el campo ";
var pInteger = "ingrese un numero entero en el campo ";
var pPositiveInteger = "ingrese un numero entero positivo en el campo ";
var pNumber = "ingrese un numero en el campo ";
var pPhoneNumber = "ingrese un número de teléfono válido en el campo ";
var pEmail = "ingrese una dirección de correo electrónico válida en el campo ";
var pName = "ingrese un texto que contenga solo letras, numeros o espacios en el campo ";
var pIntegerInRange = " ingrese un número entre ";
var pChecked = " debe de seleccionar ";
var pAnything= "El valor no puede ser numérico en el campo ";



// ---------------------------------------------------------------------- //
//         FUNCIONES PARA MANEJO DE ARREGLOS NO TOCAR ESTE MODULILLO      //
// ---------------------------------------------------------------------- //

// 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 NO TOCAR ESTE MÓDULO    //
// ---------------------------------------------------------------------- //


// 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 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 no es letra ni digito
function isOtro (c)
{   return (!isLetter(c) && !isDigit(c))
}


// ---------------------------------------------------------------------- //
//                          NUMEROS      NO TOCAR ESTE MÓDULO             //
// ---------------------------------------------------------------------- //

// 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 isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        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 isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    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) > 0) ) );
}







// 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;
}



function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);
	   
    if (!isInteger(s, false)) return false;
	
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}






// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES NO TOCAR ESTE MÓDULO            //
// ---------------------------------------------------------------------- //

// 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;
}



//Vale todo excepto que metan un nº
function isAnything (s)
{   var i;
	
    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    if (!isNumber(s)) return true
	else return false
}


// 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;
    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;
}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA RECLAMARLE AL USUARIO                  //
// ---------------------------------------------------------------------- //

// pone el string s en la barra de estado
function statBar (s)
{   window.status = s
}

// pone el string s en la barra de estado
function promptEntry (s)
{   window.status = pEntryPrompt + s
}

// notificar que el campo theField esta vacio
function warnEmpty (theField,s)
{   theField.focus()
    alert(mMessage+s)
    statBar(mMessage+s)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(pPrompt + s)
    statBar(pPrompt + s)
    return false
}

// el corazon de todo: checkField
function checkField (theField, theFunction, s,emptyOK)
{
    var msg;
    if (checkField.arguments.length <= 3) emptyOK = defaultEmptyOK;
  	
	// Asigna los mensajes segun la función
	
	if ( theFunction == isAlphabetic ) msg = pAlphabetic + s;
    if ( theFunction == isAlphanumeric ) msg = pAlphanumeric + s;
    if ( theFunction == isInteger ) msg = pInteger + s;
	if ( theFunction == isPositiveInteger ) msg = pPositiveInteger + s;
    if ( theFunction == isNumber ) msg = pNumber + s;
    if ( theFunction == isEmail ) msg = pEmail + s;
    if ( theFunction == isPhoneNumber ) msg = pPhoneNumber + s;
    if ( theFunction == isName ) msg = pName + s;
    if ( theFunction == isChecked) msg = pChecked + s;
	if ( theFunction == isAnything) msg = pAnything + s;


    if ((emptyOK == true) && (isEmpty(theField.value)))
	{
	 return true;
	}
    if ((emptyOK == false) && (isEmpty(theField.value))) 
	{
        return warnEmpty(theField,s);
	}
		
	if (theFunction(theField.value) == true) 
	{ 
		return true;	
	}
    else
		{
        return warnInvalid(theField,msg);
		}

}


function checkFieldRange (theField, theFunction,a,b,s,emptyOK)
{
    var msg;
    if (checkFieldRange.arguments.length <= 5) emptyOK = defaultEmptyOK;
  	
	// Asigna los mensajes por defecto segun la función
	if ( theFunction == isIntegerInRange ) msg = pIntegerInRange + a + ' y ' + b + ' en el campo ' + s;
    
    
    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
	
    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField,s);
		
	if (theFunction(theField.value,a,b) == true) 
	{ 
		return true;	
	}
    else
		{
        return warnInvalid(theField,msg);
		}

}

// ----------------------------------------------------------------------//
//      COMPRUEBA SI UN CAMPO DE UN FORMULARIO ESTA CHEQUEADO            //
// ----------------------------------------------------------------------//
function isChecked(theField1,theField2,s){
	
	if (theField1.checked == false && theField2.checked == false)
		 return warnInvalid(theField1,pChecked + s);
	else
		return true;	
}



// ---------------------------------------------------------------------- //
//               GESTIÓN DE ERRORES DEL LADO DEL SERVIDOR              //
// ---------------------------------------------------------------------- //

//Ir introduciendo aquí los textos de los errores que os vayais encontrando.
//Ir aumentando el índice del array

var servidor= new Array(30);

servidor[0]='Esa empresa ya existe.';
servidor[1]='Esa empresa no se puede borrar ya que tiene contactos.';
servidor[2]='Ya hay algún Tema con ese Nombre';
servidor[3]='Ya hay algún Subtema con ese Nombre';
servidor[4]='Ya hay algún Código de Usuario con ese Usuario';
servidor[5]='Ya hay algún Subcampo 1 con ese Nombre para ese Campo';
servidor[6]='Ya hay algún Nombre de Cliente con ese Nombre';
servidor[7]='Ya hay algún Tipo de Proyecto con ese Nombre';
servidor[8]='Ya hay algún Trabajo con ese Nombre';
servidor[9]='Esta dirección ya existe para esa selección de campos';
servidor[10]='Ya hay algún Subcampo 2 con ese Nombre para ese Subcampo2';
servidor[11]='No se puede borrar el Tema ya que tiene Subtemas.';
servidor[12]='No se puede borrar el Subtema ya que tiene Subtemas 2.';
servidor[13]='No se puede borrar el Sector ya que tiene ideas';
servidor[14]='No se puede borrar el Subtema 2 ya que tiene ideas';
servidor[15]='Este Subtema 2 no se puede borrar ya que tiene Enlaces';
servidor[16]='Este Subtema 1 no se puede borrar ya que tiene Enlaces';
servidor[17]='Ya hay algún Sector con ese Nombre';
servidor[18]='Este Sector no se puede borrar ya que tiene Enlaces';
servidor[19]='No existen Enlaces para esta selección';
servidor[20]='No se puede borrar este Sector ya que tiene Documentos.';
servidor[21]='No se puede consultar este sector ya que no tiene Documentos.';
servidor[22]='No se puede borrar el Subtema 2 ya que tiene documentos';
servidor[23]='No existen Documentos para esta selección';
servidor[24]='Ya existe un Nombre de Perfil con ese nombre';
servidor[25]='No hay datos en la tabla.';
servidor[26]='No existen Preguntas para esta selección';
servidor[27]='Esta pregunta ya existe para esa selección de campos';
servidor[28]='No se puede borrar el Sector ya que tiene Enlaces';
servidor[29]='Este nombre de proyecto ya existe';
// ---------------------------------------------------------------------- //
//               GESTIÓN DE MENSAJES INDICATIVOS			              //
// ---------------------------------------------------------------------- //

//Ir introduciendo aquí los textos de los mensajes indicativos.
//Ir aumentando el índice del array

var indica= new Array(15);

indica[0]='Tiene correo interno.';
indica[1]='Está Ud en el apartado de correo interno.';
indica[2]='Debe de seleccionar al menos una opción para el perfil';
indica[3]='Debe seleccionar una pregunta para poder borrarla';
indica[4]='¿ Está seguro que quiere BORRAR esta pregunta ?';
indica[5]='Sólo puede introducir una palabra para la busqueda.';
indica[6]='Debe seleccionar una pregunta para poder modificarla';
indica[7]='La password y su confirmación deben coincidir';
indica[8]='Debe seleccionar un Subcampo 1';
indica[9]='Debe seleccionar un Subcampo 2';
indica[10]='Debe seleccionar un Sector';
indica[11]='Debe introducir un documento';
indica[12]='Debe introducir una dirección WEB';
indica[13]='Ha sobrepasado el número de horas';
indica[14]='Debe introducir un nombre de Subcampo2';
