  //Libreria de validacion. Ver 1.4
  //Jesus Lopez Gijon - quick_end@hotmail.com
  //Creación :  23 de Julio de 2001.
  //Ultima modificación :  19 de Agosto de 2003.
  //Como se manda llamar en el HTML:

  //<SCRIPT SRC="libV4.js"></SCRIPT>
  //<FORM action="Interprete.php" MeTHOD=POST  onSubmit="return FieldsOK();">
  //Funciones :
  //isEmpty(s)                    Función interna que determina si un elemento es vacio o nulo.
  //isDigit(s)                    Función interna que determina si un elemento es un digito.
  //FieldsOK()                    FUNCION PRINCIPAL
  //isWhitespace(Element)         Valida si el elemento esta vacio o tiene solo caracteres espacio.
  //isEmail(Element)              Validación de que el Email sea valido.(valido = true).
  //isLetras(Element, tipo)       Validacion que solo permite letras.
  //                              Tipo = 0   Solo Letras sin acentuadas
  //                              Tipo = 1   Letras normales y acentuadas
  //                              Tipo = 2   Alfanumerico (Sin acentos).
  //CheckDate(Element)            Validacion de la Fecha (DD/MM/AAAA).
  //isFloat(Element)              Validacion si el elemento es una numero real.
  //isInteger(Element)            Validacion que solo permite numeros.
  //isCP(Element)                 Validacion que verifica que sea un codigo postal.
  //isCombo(Element)              Verifica si un combo esta pocisionado en un valor diferente al de default (el valor de default es "0" cero)
  //isTelefono(Element)           Validacion si el campo el tipo telefono - (52) 52762474 Ext.203 (52) 52762474/203
  //isCElector(Element)           Validacion de la Clave de Elector.
  //getRadioButtonValue(Element)  Verifica si el radio button tiane algun elemento seleccionado.
  //isPassword(Element, Element1) Verificación de contraseña esta necesita que los objetos esten continuos ya que necesita dos uno el
  //                              password y la confirmacion de este y al menos 4 caracteres para un password.
  //isRFC(elemento)               Verificación y validacion de formato del RFC.
  /*
  Comentarios
    decimalPointDelimiter(dPD)
    En los tipos de validacion no se puede ocupar "P", "p" por tener conficto con la conficion con la variable elemento.name = "PHPSESSID"
  */
  /*
     Para bloquear cajas de texto se tiene que poner en INPUT la siguiente instruccion:
     OnFocus="this.blur();"
  */
  /*
     Para saber la resolucion de la pantalla el comendo es:
     Ancho:                screen.width
     Largo:                screen.height
  */
  /*
     Funcion para limitar el tamaño de un textarea
         function textCounter(field, countfield, maxlimit) {
           if (field.value.length > maxlimit)
             field.value = field.value.substring(0, maxlimit);
           else
             countfield.value = maxlimit - field.value.length;
         }
  */

  var letras  = "abcdefghijklmn" + unescape("%F1") + "opqrstuvwxyzABCDEFGHIJKLMN" + unescape("%D1") + "OPQRSTUVWXYZ" + unescape("%20%E1%E9%ED%F3%FA%C1%C9%CD%D3%DA");
  var digito = "0123456789";
  var dPD = "."
  var space = " \t\n\r";
  var ok = "yes";

  function isEmpty(s){
    return ((s == null) || (s.length == 0))
  }

  function isDigit(s){
    return ((s >= "0") && (s <= "9"))
  }

  function FieldsOK(val){
    var salida=true, vacio=true, newstr="", radio="", check, sale=false;
    var old="", check=false;
	if (isNaN(val)) val = 0; 
    for(i = 0; i<document.forms.length; i++){
      for (j =0; j<document.forms[i].elements.length-val; j++){
        elemento = document.forms[i].elements[j];		
        strE = elemento.name;
        arr = strE.split(":");
        if (strE.substr(1,1)== "_") sale=true;
        else sale=false;
        switch (strE.substr(2,1)){
          case "h":
          case "I":
          case "b":
          case "S":
          case "R":
            break;
          case "x":
          case "r":
            if (sale) {
              radio = document.forms[i].elements[elemento.name];
              if ( old != elemento.name)
                newstr += ((getRadioButtonValue(radio)) ? "" : unescape("%B7") + " " + arr[1].replace(/;/g, " ") + "\n");
              old = elemento.name;
            }
            break;
          case "c":
            if (sale)
              newstr += ((isCombo(elemento)) ? "" : unescape("%B7") + " " + arr[1].replace(/;/g, " ") + "\n");
            break;
          default :
            /*if (strE.substr(0,1) == "B"){
              alert (document.forms[i].elements[j].name);
              for (h = 0; h < 4; h++){
                alert (isWhitespace(document.forms[i].elements[h+j].value));
                if(isWhitespace(document.forms[i].elements[h+j].value))

                  break;
              }
              j += (3 - h);
              alert (document.forms[i].elements[j].name)
              alert(h);
            } */
            //alert(sale);
            vacio=!(isWhitespace(elemento.value));
			
            if (sale)
              newstr += ((vacio) ? "" : unescape("%B7") + " " + arr[1].replace(/;/g, " ") + "\n");
            if (vacio){
             switch (strE.substr(0,1)){
               case "E" :
                 salida = isEmail(elemento);
                 break;
               case "L" :
                 salida = isLetras(elemento, 0);
                 break;
               case "l" :
                 salida = isLetras(elemento, 1);
                 break;
               case "A" :
                 salida = isLetras(elemento, 2);
                 break;
               case "D" :
                 salida = CheckDate(elemento);
                 break;
               case "F" :
                 salida = isFloat(elemento);
                 break;
               case "I" :
                 salida = isInteger(elemento);
                 break;
               case "H" :
                 salida = isCP(elemento);
                 break;
               case "T" :
                 salida = isTelefono(elemento);
                 break;
               case "e" :
                  salida = isCElector(elemento);
                  break;
               case "W" :
                 elemento1 = document.forms[i].elements[++j];
                 salida = isPassword(elemento, elemento1);
                 break;
               case "f" : // Validacion RFC
                  salida = isRFC(elemento);
                  break;
               case "c" :
                 /*if (h == 3){
                 valor = "";
                 valor += elemento.value
                 valor += document.forms[i].elements[++j].value;
                 valor += document.forms[i].elements[++j].value;
                 valor += document.forms[i].elements[++j].value;
                 salida = isCreditCard(valor);
                 } */
                 salida = false;
                 break;
			   case "k" :
			     salida = isMoney(elemento);
				 break;
             }
             if (!salida) return false;
            }
        }
      }
    }
    if (! isWhitespace(newstr)){
      var pleaseDo = "\n\nPor favor, introduce los datos e intenta nuevamente";
      alert("Es imposible continuar, debido a que \nlos siguientes campos se encuentran vacios:\n\n" + newstr + pleaseDo);
      salida = false;
    }
    return salida;
  }
  //TERMINA FUNCION PRINCIPAL

  function isWhitespace(Element){
    var i;
    if (isEmpty(Element)) return true;
    for (i = 0; i < Element.length; i++){
       var c = Element.charAt(i);
       if (space.indexOf(c) == -1)
         return false;
    }
    return true;
  }

  function isEmail(Element)
  {
    var s = Element.value;
    var filter=/^[A-Za-z0-9][A-Za-z0-9_\-.]*@[A-Za-z0-9_\-]+\.[A-Za-z0-9_.\-]+[A-za-z]$/;
    if (filter.test(s))
      return true;
	Element.value = "";
    Element.focus();
    Element.select();
    return false;
  }

  function isLetras(Element, s){
    var temp, ok = true;
    letrasA = letras;
    letrasA += ((s == 1) ? unescape("%E1%E9%ED%F3%FA%C1%C9%CD%D3%DA") : ((s == 2) ? digito : ""));
    for (var i=0; i< Element.value.length; i++) {
      temp = "" + Element.value.substring(i, i+1);
      if (letrasA.indexOf(temp) == "-1") ok = false;
    }
    if (!ok) {
      if (s == 1)
        alert("Solo puede introducir letras.");
      else
        if (s == 0)
          alert("Solo puede introducir letras, no acentuadas.");
        else
          alert("Solo puedes introducir carácteres alfanúmericos.");
      Element.focus();
      Element.select();
    }
    return ok;
  }

  function CheckDate(Element) {
    var err=0
    a=Element.value
    if (a.length != 10) err=1
    b = a.substring(3, 5)// day
    c = a.substring(2, 3)// '/'
    d = a.substring(0, 2)// month
    e = a.substring(5, 6)// '/'
    f = a.substring(6, 10)// year
    if (!(isDigit(b.substring(0,1)) && isDigit(b.substring(1,2)))) err=1
    if (!(isDigit(d.substring(0,1)) && isDigit(d.substring(1,2)))) err=1
    if (!(isDigit(f.substring(0,1)) && isDigit(f.substring(1,2)) && isDigit(f.substring(2,3)) && isDigit(f.substring(3,4)))) err=1
    if (b<1 || b>12) err = 1
    if (d<1 || d>31) err = 1
    if (f<1900) err = 1
    if (b==4 || b==6 || b==9 || b==11)
      if (d==31) err=1;
    if (b==2){
      var g=parseInt(f/4)
      if (isNaN(g)) err=1;
        if (d>29) err=1
          if (d==29 && ((f/4)!=parseInt(f/4))) err=1
    }
    if (err==1){
      alert('Es necesario que escribas la fecha de manera correcta dd/mm/aaaa (ej. 31/12/2000)');
      fecha_actual = new Date();
      dia_mes = fecha_actual.getDate();
      strdia_mes = (dia_mes <= 9) ? "0" + dia_mes : dia_mes;
      mes = fecha_actual.getMonth() + 1;
      strmes = (mes <= 9) ? "0" + mes : mes;
      anio = fecha_actual.getYear();
      if (anio < 100) anio = "19" + anio
      else if ( ( anio > 100 ) && ( anio < 999 ) ) {
        var cadena_anio = new String(anio)
        anio = "20" + cadena_anio.substring(1,3)
      }
      Element.value = strdia_mes + "/" + strmes + "/" + anio;
      Element.focus();
      Element.select();
      return false;
    }
    return true;
  }

  function isFloat(Element){
    var i, salida = true;
    var seenDecimalPoint = false;
    s = Element.value;
    if (s == dPD) salida = false;
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if ((c == dPD) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) salida = false;
    }
    if (!salida){
      alert("Es necesario que escribas la cantidad numérica correctamente (ej. 92345.893)");
      Element.focus();
      Element.select();
    }
    return salida;
  }

  function isMoney(Element){
    var i, salida = true;
    var seenDecimalPoint = false;
    s = Element.value;
    if (s == dPD) salida = false;
    for (i = 1; i < s.length; i++){
        var c = s.charAt(i);
        if ((c == dPD) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) salida = false;
    }
    if (!salida){
      alert("Es necesario que escribas la cantidad correctamente (ej. $92345.893)");
      Element.focus();
      Element.select();
    }
    return salida;
  }
  
  function isInteger(Element){
    var i;
    s = Element.value;
    for (i = 0; i < s.length; i++){
      var c = s.charAt(i);
      if (!isDigit(c)){
        alert("Solo puedes introducir caracteres numéricos (ej. 24)");
        Element.focus();
        Element.select();
        return false;
        break;
      }
    }
    return true;
  }

  function isCP(Element){
    var i;
    s = Element.value;
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if ((!isDigit(c)) || (s.length != 5)){
          alert("Es necesario que escribas el Código Postal correctamente (ej. 11800)");
          Element.focus();
          Element.select();
          return false;
          break;
        }
    }
    return true;
  }

  function isCombo(Element){
    if (Element.type != "text"){
      if (Element.selectedIndex == -1)  return false;
      var s = Element.options[Element.selectedIndex].value;
      if (s == 0 ||  s == "")
        return false;
    }
    return true;
  }

  function isTelefono(Element){
    var s = Element.value;
    if (s.charAt(0) == "(")
      if (s.charAt(3) == ")")
        var filter=/^[(][0-9][0-9][)][0-9 ]+[0-9\- ]+[0-9\-E][0-9\-x][0-9\-t][0-9\-\.\/ ]+[0-9 ][0-9]$/;
      else
        if (s.charAt(4) == ")")
          var filter=/^[(][0-9][0-9][0-9][)][0-9 ]+[0-9\- ]+[0-9\-E][0-9\-x][0-9\-t][0-9\-\.\/ ]+[0-9 ][0-9]$/;
        else
          var filter=/^[(][0-9][)][0-9 ]+[0-9\- ]+[0-9\-E][0-9\-x][0-9\-t][0-9\-\.\/ ]+[0-9 ][0-9]$/;
    else
      var filter=/^[0-9]+[0-9\- ]+[0-9\-E][0-9\-x][0-9\-t][0-9\-\.\/ ]+[0-9 ][0-9]$/;
    if (filter.test(s))
      return true;
    else
      alert("Es necesario que escribas tu teléfono de manera correcta\n(ej. (52) 52762474 Ext.203  ó (52) 52762474/203 ó (52) 52762474-2035 ó 52-762474)");
    Element.focus();
    Element.select();
    return false;
  }

  function isCElector(Element){
    Element.value = Element.value.toUpperCase();
    var s = Element.value;
    var filter=/^[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][HM][0-9][0-9][0-9]$/;
    if (filter.test(s))
      return true;
    else
      alert("Es necesario que escribas tu Clave Elector de manera correcta\n(ej. PRTRRM94062954H475)");
    Element.focus();
    Element.select();
    return false;
  }

  function getRadioButtonValue(radio){
    if (radio.checked) return true;
    for (var i = 0; i < radio.length; i++)
      if (!((radio[i].checked == "")))
        if (radio[i].checked) return true;
    return false;
  }

  function isPassword(Element, Element1)
  {
    var s = Element.value, r = Element1.value;
    if (Element.value.length < 5){
      alert("Tu contraseña debe tener mínimo 5 carácteres de longitud.\n\nPor favor, inténta nuevamente.")
      Element.value = "";
      Element.focus();
      return false;
    }
    if (Element.value != Element1.value){
      alert("La confirmación de tu contraseña es incorrecta.")
      Element1.value = "";
      Element1.focus();
      return false;
    }
    return true;
  }

  function isRFC(Element){
    Element.value = Element.value.toUpperCase();
    var s = Element.value;
    var filter=/^[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9][0-9][A-Z0-9][A-Z0-9][A-Z0-9]$/;
    if (filter.test(s))
      return true;
    else
      alert("Es necesario que escribas el RFC correctamente, agrega tu homoclave (ej. LOGJ730809V52)");
    Element.focus();
    Element.select();
    return false;
  }

  function isCreditCard(s) {
    for (i = 0; i < s.length; i++){
      var c = s.charAt(i);
      if (!isDigit(c)){
        alert("Es necesario que escribas correctamente tu Tarjeta de Crédito");
        return false;
        break;
      }
    }
    return true;
  }

  function formatnum(tmpcampo)
  {
	cadena = tmpcampo.toString();
    n1 = cadena.length;
    n2 = n1-3;
    if (n2 > 3){
      mod = (n2 % 3);
      cuenta=0;
      cadena1 = "";
	  if (mod){
	    for ( i = 0; i < mod; i++ )
	      cadena1 += cadena.charAt(i);
	    cadena1 += ",";
		div = ((n2-mod)/3)-1;
	  }	
	  else
	    div = ((n2-mod)/3)-1;
      for ( i = mod; i < n1; i++ ){
         cadena1 += cadena.charAt(i);
         cuenta++;
         if (cuenta == 3){
           if(div > 0){
             cadena1 += ",";
             div--;
           }
           cuenta = 0;
         }
      }
    }
    else
      cadena1 = cadena;
    return "$"+cadena1;
  }

  function fmtPrice(element,decimal)
  {
    if (isFloat(element)){
	  value = element.value;
      if (!decimal) decimal = 2;
      result=Math.floor(value)+".";
      var cents=(Math.pow(10, decimal))*(value-Math.floor(value))+0.5;
      result += Math.floor(cents/10);
      result += Math.floor(cents%10); 
      return formatnum(result);
	}
	else return 0;
  }
   
  function QuitafmtPrice(element){
    return element.value.substr(1,element.value.length).replace(/,/g, "");
  }
  // para validar el tipo is Money  onblur="this.value=fmtPrice(this)" onfocus="this.value=QuitafmtPrice(this)"
  /*
  Webmonkey GET Parsing Module
  Language: JavaScript 1.0
  The parsing of GET queries is fundamental
  to the basic functionality of HTTP/1.0.
  This module parses GET with JavaScript 1.0.

  Source: Webmonkey Code Library
  (http://www.hotwired.com/webmonkey/javascript/code_library/)

  Author: Patrick Corcoran
  Author Email: patrick@taylor.org
  */

  function createRequestObject() {

    FORM_DATA = new Object();
    // The Object ("Array") where our data will be stored.

    separator = ',';
    // The token used to separate data from multi-select inputs

    query = '' + this.location;
    qu = query
    // Get the current URL so we can parse out the data.
    // Adding a null-string '' forces an implicit type cast
    // from property to string, for NS2 compatibility.

    query = query.substring((query.indexOf('?')) + 1);
    // Keep everything after the question mark '?'.

    if (query.length < 1) { return false; }  // Perhaps we got some bad data?

    keypairs = new Object();
    numKP = 1;
    // Local vars used to store and keep track of name/value pairs
    // as we parse them back into a usable form.

    while (query.indexOf('&') > -1) {
      keypairs[numKP] = query.substring(0,query.indexOf('&'));
      query = query.substring((query.indexOf('&')) + 1);
      numKP++;
      // Split the query string at each '&', storing the left-hand side
      // of the split in a new keypairs[] holder, and chopping the query
      // so that it gets the value of the right-hand string.
    }
    keypairs[numKP] = query;
    // Store what's left in the query string as the final keypairs[] data.

    for (i in keypairs) {
      keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
      // Left of '=' is name.
      keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      // Right of '=' is value.
      while (keyValue.indexOf('+') > -1) {
        keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
        // Replace each '+' in data string with a space.
      }

      keyValue = unescape(keyValue);
      // Unescape non-alphanumerics

      if (FORM_DATA[keyName]) {
        FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
        // Object already exists, it is probably a multi-select input,
        // and we need to generate a separator-delimited string
        // by appending to what we already have stored.
      } else {
        FORM_DATA[keyName] = keyValue;
        // Normal case: name gets value.
      }
    }

    return FORM_DATA;
  }
  // FORM_DATA = createRequestObject();
  // This is the array/object containing the GET data.
  // Retrieve information with 'FORM_DATA [ key ] = value'.
  //alert(FORM_DATA ["q"]) ;
  	
  function setSections(names) {
    names.style.display="";
    names.style.visibility="visible";
  }

  function hideSections(names) {
    names.style.display="none";
    names.style.visibility="hidden";
  }
  
  function fiNumeroLetras(sCaracter)
{
	if (sCaracter != 45)
	if ( fLetras(sCaracter) == 0 && fbNumeros(sCaracter) == 0)
	{
     return 0;
    }
}
function fiNumeroLetrasNEspacioBlanco(sCaracter)
{
	if ( fLetras(sCaracter) == 0 && fbNumeros(sCaracter) == 0 || sCaracter == 32) 
	{
     return 0;
    }
}
function fNApostrofeComillas(sCaracter)
{
	if (sCaracter == 34 || sCaracter == 39)
	{
		return 0;
	} 
}   
function fNApostrofeComillasEspacioBlanco(sCaracter)
{
	if (sCaracter == 34 || sCaracter == 39 || sCaracter == 32 )
	{
		return 0;
	} 
}   
function fLetras(sLetra)
{
	if ((sLetra < 65 || sLetra > 90) && sLetra < 97 || sLetra > 122)
	{
		if (!(sLetra == 209 || sLetra == 241 || sLetra == 32))
			return 0;
	}
}
function fbNumeros(sNumero)
{
	if (sNumero < 48 || sNumero > 57)
	{
	  return 0;
	}
}

function fiNumero(sCaracter)
{
	if (sCaracter != 47)
	if (fbNumeros(sCaracter) == 0)
	{
     return 0;
    }
}

function isValidDate(iDate){
  var dteDate;
  sDate = iDate.value.split("/");
  if (sDate.length != 3) return false;
  dteDate=new Date("20" + sDate[2],sDate[0]-1,sDate[1]);
  return ((sDate[1]==dteDate.getDate()) && (sDate[0]-1==dteDate.getMonth()) && ("20" + sDate[2]==dteDate.getFullYear()));
}
function ValidDate(iDate){
	if (!isValidDate(iDate)){
		alert("Is not valid Date. (mm/dd/yy)")
		iDate.value = "";
	}
} 
