// ---------------------------------------------------------------------- //
//                                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;
//	}
// ---------------------------------------------------------------------- //



// ---------------------------------------------------------------------- //
//                                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 = "abcdefghijklmnopqrstuvwxyzáéíóúñäëïöü,\\().;$#&¿?!%ª/<>:\"|@_ºª¡-+*{}[]=®™*…•"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑÄËÏÖÜ_,\\().;$#&¿?!%ª/<>:\"|@ºª¡-+*{}[]=®™*…•"
var whitespace = " \t\n\r";
var indicador = "0123456789"
var UserValido = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_.@0123456789"

// caracteres admitidos en campos de telefono
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 sólo letras y/o números";
var pAlphabetic   = "Ingrese un texto que contenga sólo 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 sólo letras, números";
var msgname="Ingrese nombre "
var pano ="Ingrese el año de viaje"
panonac="Ingrese año de nacimiento"
var pRut="error"
var pDirec="Ingrese una dirección"
var pFono ="Ingrese número telefónico"
//var antes = "Error: Debe "
//var despues = ", Por favor";

var antes = ""
var despues = "";

var j_arbol="ingresar nombre del Nodo "
var j_name = " ingresar descripcion del Nodo "

// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //
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 todas las comillas que pueden molestar en el SQL
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;
}

// 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))
}

// ---------------------------------------------------------------------- //
//                          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 y espacios
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;
}



// 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 var indicador
function isPorGan (s)
{   var i;

    if (isEmpty(s)) 
       return false;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        //alert (c)
        //alert(indicador.indexOf(c))
        if (indicador.indexOf(c) == -1 )
			return false;
    }
    return true;
}

// s tiene solo var UserValido(Kaufmann-Usuarios)
function isUserValido (s)
{   var i;

    if (isEmpty(s)) 
       return false;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        //alert (c)
        //alert(UserValido.indexOf(c))
        if (UserValido.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;
    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
}

// notificar que el campo theField esta vacio
function warnEmpty (theField,s)
{   if(!theField.disabled) theField.focus();
    //original alert(mMessage+s)
    alert(antes + s + despues)
    //original statBar(mMessage)
    statBar(antes + s + despues)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   if(!theField.disabled) theField.focus()
    theField.select()
    //original alert(s)
    alert(antes + s + despues)
    statBar(pPrompt + s)
    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 == 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);
}

// El campo que se pasa se verifica que es fecha
function strIsFecha(s)
{
	return true;
}

function isDate(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 < 1 || mm > 12 )
	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 isTime(h,m,b24Horas)
{
  var hh = parseInt(h,10);
  var mm = parseInt(m,10);
  var horaMax = b24Horas?23:12;
  var horaMin = b24Horas?0:1;
  if( isNaN(hh) || isNaN(mm) || hh < horaMin || mm < 0 || hh > horaMax || mm > 59)
	return false;
  return true;
}

function CharComilladesta()
{
	var comilla = "'";
	document.nodos.nombre.value = stripCharsInBag (document.nodos.nombre.value,comilla);
	document.nodos.descripcion.value = stripCharsInBag (document.nodos.descripcion.value,comilla);

return true;
}

function CharComillasitios()
{
	var comilla = "'";
	document.nodos.nombre.value = stripCharsInBag (document.nodos.nombre.value,comilla);
	document.nodos.descripcion.value = stripCharsInBag (document.nodos.descripcion.value,comilla);

return true;
}

function vacio(num)
{
 if (num == "")
 { 
  var espacio = " ";
  var comilla = "'";
  document.Form.imagefile.value = stripCharsInBag (document.Form.imagefile.value,espacio);
  document.Form.imagefile.value = stripCharsInBag (document.Form.imagefile.value,comilla);
  if (document.Form.imagefile.value == "")
  {
	//alert("Debe ingresar la imagen...");
	//return false;
	document.Form.imagen.value = "no";
	return true;
  }
  else
  {
	return true;
  }      
 }
 else
 {
	document.Form.imagen.value = "no"; 
	return true;
 }
}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA VALIDAR EL RUT                         //
// ---------------------------------------------------------------------- //

function checkDV( crut, theField )

{
  largo = crut.length;

  if ( largo > 2 )
    rut = crut.substring(0, largo - 1);
  else
    rut = crut.charAt(0);
  dv = crut.charAt(largo-1);
 
  if ( rut == null || dv == null )
      return 0;

  var dvr = '0';

  suma = 0;
  mul  = 2;

  for (i = rut.length - 1 ; i >= 0; i--)
  {
    suma += rut.charAt(i) * mul;
    if (mul == 7)
      mul = 2;
    else    
      mul++;
  }

  res = suma % 11;
  
  
  if (res == 1)
    dvr = 'k';
  else if (res == 0)
    dvr = '0';
  else
  {
    dvi = 11-res;
    dvr = dvi + "";
  }
  if ( dvr != dv.toLowerCase() )
  {
    alert("EL rut es incorrecto.");
    theField.focus();
    theField.value = "";
    return false;
  }

  return true;
}

function validaRut(theField)
{
  rut = theField.value;
  var tmpstr = "";
  largo = rut.length;
  for ( i=0; i < largo; i++ )
    if ( rut.charAt(i) != ' ' && rut.charAt(i) != '.' && rut.charAt(i) != '-' )
      tmpstr = tmpstr + rut.charAt(i);
      
  rut = tmpstr;
  
  largo = rut.length;

  if ( largo < 2 )
  {
    alert("Debe ingresar el rut completo.");
    theField.focus();
	theField.select();
    return false;
  }

  for (i=0; i < largo ; i++ )
  { 
    if ( rut.charAt(i) !="0" && rut.charAt(i) != "1" && rut.charAt(i) !="2" && rut.charAt(i) != "3" && rut.charAt(i) != "4" && rut.charAt(i) !="5" && rut.charAt(i) != "6" && rut.charAt(i) != "7" && rut.charAt(i) !="8" && rut.charAt(i) != "9" && rut.charAt(i) !="k" && rut.charAt(i) != "K" ) 
    {
      alert("El valor ingresado no corresponde a un R.U.T valido.");
      theField.focus();
      theField.select();
      return false;
    }
  }

  var dtexto = "";
  cnt = 0;

  for ( i=largo-1, j=largo-1+3; i>=0; i--, j-- )
  {    
    if ( cnt == 3 )
    {
      dtexto = rut.charAt(i) + dtexto;
      dtexto = '.' + dtexto;
      cnt = 1;
    }
    else
    { 
      dtexto = rut.charAt(i) + dtexto;
      if( cnt == 0 )
        dtexto = '-' + dtexto;
      cnt++;
    }
  }

  theField.value = dtexto;  

  return checkDV(rut, theField);
}	
