// <![CDATA[

    function reset_obj(obj) 
    {
        obj.value = obj.defaultValue;
    }

    function getRefToDiv(divID,oDoc) {
        if( !oDoc ) { oDoc = document; }
        if( document.layers ) {
            if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
                //repeatedly run through all child layers
                for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
                    //on success, return that layer, else return nothing
                    y = getRefToDiv(divID,oDoc.layers[x].document); }
                return y; } }
        if( document.getElementById ) {
            return document.getElementById(divID); }
        if( document.all ) {
            return document.all[divID]; }
        return false;
    }

    function showDiv(divID, show) {
        //get a reference as above ...
        myReference = getRefToDiv(divID);
        if( !myReference ) {
            //window.alert('Nothing works in this browser');
            return false; //don't go any further
            //return anything would work,
            //but I am using false to show failure
        }
        //now we have a reference to it
        if( myReference.style ) { //DOM & proprietary DOM
            myReference.style.visibility = (show ? 'visible' : 'hidden');
        } else {
            if( myReference.visibility ) { //Netscape
                myReference.visibility = (show ? 'show' : 'hide');
            } else {
                //window.alert('Nothing works in this browser');
                return false; //don't go any further
            }
        }
        return true;
    }

    function trim_obj(obj)
    {
            var s = obj.value;

            if (s.length > 0)
            {
                    for (i = 0; i < s.length && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i ++);
                    for (j = s.length - 1; j >= 0 && (s.charAt(j) == ' ' || s.charAt(j) == '\t'); j --);

                    obj.value = s.substring(i, j + 1);
            }
    }

    function elimina_marcas(f)
    {
            for (i = 0; i < f.length; i ++)
            {
                    if (f[i].tagName == "A" || (f[i].tagName == "INPUT" && (f[i].type == "checkbox" || f[i].type == "image")))
                    {
                            f[i].onfocus = f[i].blur;
                    }
            }
    }

/*
    function mod_obj(str_obj)
    {
        if (eval(str_obj + ".value") != eval(str_obj + ".defaultValue"))
        {
            eval(str_obj + "_mod.value = 'M'"); 
        }
    } 
*/
    function sel_obj(obj, no_sel) {
    
        obj.focus();

        if (!no_sel)
            obj.select();
    }   
 
    function comprueba_obl(obj, msg_err, filtro, no_foco)
    {
        if (es_vacio(obj, false, filtro))
        {
            alert(msg_err);

            if (!no_foco)
                sel_obj(obj, true);
    
            return false;
        }

        return true;
    }

    // -------------------------
    // FUNCIONES DE COMPROBACION
    // -------------------------
    // 
    //	boolean es_nif(obj);
    //	boolean es_numero(obj);
    //	boolean es_caracter(obj);
    //	boolean es_alfanumerico(obj);
    //	boolean es_vacio(obj, esp);
    //	boolean es_fecha(obj);
    //

    // -----------------------------------------------------------------------------
    // Valida si el el NIF es correcto
    // -----------------------------------------------------------------------------

    function es_nif(obj, sel)
    {
            var str;
            var newstr;
            var letras = 
                    [
                    "T","t","R","r","W","w","A","A","G","g",
                "M","m","Y","y","F","f","P","p","D","d",
                "X","x","B","b","N","n","J","j","Z","z",
                "S","s","Q","q","V","v","H","h","L","l",
                "C","c","K","k","E","e"
                ];

            str = '';
            str = obj.value.toUpperCase();

            if ((longitud = str.length) == 0) 
                    return true;

            letra = str.substr(longitud - 1, 1);

            numero = str.substr (0, longitud - 1);
            resto = numero - (parseInt(numero / 23)) * 23;

            newstr = '000000000' + str;
            obj.value = newstr.substr(longitud).toUpperCase();

            if ((letras[2 * resto] != letra) && (letras[2 * resto + 1] != letra ))
            {
                    if (sel)
                    {
                            alert('Debe especificar correctamente el NIF (Formato: 99999999X)');
                            sel_obj(obj);
                    }

                    return false;
            }

            return true;
    }

    function calcula_letra(nif_cif)
    {
            var letras = "TRWAGMYFPDXBNJZSQVHLCKE";

            return letras.charAt(parseInt(nif_cif,10) % 23);
    }

    function completa_nif(obj)
    {
            if ((!es_vacio(obj)) && es_numero(obj))
            {
                    return (obj.value + calcula_letra(obj.value));
            }

            return obj.value;
    }

    // -----------------------------------------------------------------------------
    // Valida si el CIF es correcto
    // -----------------------------------------------------------------------------

    function es_cif(obj, sel)
    {
     v_numero_c = "";
     v_control = 0;
     v_letra = "";
     v_par = 0;
     v_impar = 0;
     v_cont = 1;
     v_doble = 0;
     v_mod_10 = 0;
     v_letras = "ABCDEFGHIJ";
     v_ultimo = "";
     retorno = false;

    if (obj.value.length == 0) 
                    return true;

      v_numero_c = obj.value.substring(1,obj.value.length);
      v_par = parseFloat(v_numero_c.substring(1,2)) +
              parseFloat(v_numero_c.substring(3,4)) +
              parseFloat(v_numero_c.substring(5,6));
      while( v_cont < 9) {
       v_doble = 2 * v_numero_c.substring(v_cont - 1, v_cont);
       if (v_doble <=9) {
          v_impar = v_impar + v_doble;}
       else {
          v_impar = v_impar + v_doble - 9;
       }
       v_cont = v_cont + 2;
      }
      v_mod_10 = (v_par + v_impar) % 10;
      v_control = 10 - v_mod_10;
      v_ultimo = obj.value.substring(obj.value.length -1, obj.value.length);
      if (v_ultimo >= '0' & v_ultimo <='9')
      {
       if (v_control == 10)
       {
        v_control = 0;
       }
       if (v_control != v_ultimo)
       {
                    if (sel)
                    {
                            alert('Debe especificar correctamente el CIF');
                            sel_obj(obj);
                    }
                    return false;
       }
       else
       {
        return true;
       }
      }
      else
      {
       v_letra = v_letras.substring(v_control - 1, v_control);
       if (v_letra != v_ultimo)
       {
                    if (sel)
                    {
                            alert('Debe especificar correctamente el CIF');
                            sel_obj(obj);
                    }
        return false;
       }
       else
       {
        return true;
       }
      }
            if (sel)
            {
                    alert('Debe especificar correctamente el CIF');
                    sel_obj(obj);
            }
      return false;
    }

    // -----------------------------------------------------------------------------
    // Comprueba si el valor del objeto es numerico
    // -----------------------------------------------------------------------------

    function es_numero(obj, sel)
    {
        reNoNumeros = new RegExp('[^0-9]','i');

        if (reNoNumeros.test(obj.value))
        {
            if (sel)
            {
                alert('Debe especificar un valor entero positivo');
                sel_obj(obj);
            }

            return false;
        }
        else
            return true;
    }

    // -----------------------------------------------------------------------------
    // Comprueba si el valor del objeto es decimal
    // -----------------------------------------------------------------------------

    function es_decimal(obj, enteros, decimales, sel) 
    {
            var prueba = new RegExp("^(([0-9]{1," + enteros + "})([\.][0-9]{1," + decimales + "})?)?$");

            if (!prueba.test(obj.value))
            {
                    if (sel)
                    {
                            alert('Debe especificar un decimal');
                            sel_obj(obj);
                    }

                    return false;
            }
            else
                    return true;
    }

    // -----------------------------------------------------------------------------
    // Comprueba si el valor del objeto no es numerico
    // -----------------------------------------------------------------------------

    function es_caracter(obj, sel)
    {
            reNoNumeros = new RegExp('[0-9]');

            if (reNoNumeros.test(obj.value))
            {
                    if (sel) 
                    {
                            alert('Debe especificar un valor no numérico');
                            sel_obj(obj);
                    }

                    return false;
            }
            else
            {
                    obj.value = obj.value.toUpperCase();
                    return true;
            }
    }

    // -----------------------------------------------------------------------------
    // Comprueba si el valor del objeto no es numerico
    // -----------------------------------------------------------------------------

    function es_alfanumerico(obj, sel)
    {
            re = new RegExp('[0-9a-zA-Z]');

            if (!re.test(obj.value))
            {
                    if (sel)
                    {
                            alert('Debe especificar un valor alfanumerico');
                            sel_obj(obj);
                    }

                    return false;
            }
            else
            {
                    obj.value = obj.value.toUpperCase();
                    return true;
            }
    }

    // -----------------------------------------------------------------------------
    // Comprueba si el texto del objeto enviado esta vacio
    // -----------------------------------------------------------------------------

    function es_vacio(obj, sel, trim, upp)
    {
            if (trim)
            {
                trim_obj(obj);
            }

            if (upp)
            {
                obj.value = obj.value.toUpperCase();
            }

            var str = obj.value;

            if (str.length == 0)
            {
                    obj.value = str;

                    if (sel)
                    {
                            alert('Debe especificar algún valor');
                            sel_obj(obj);
                    }

                    return true;
            }
            else	
                    return false;	
    }

    //------------------------------------------------------------------------------
    // Valida si el campo contiene una telefono valido 
    //------------------------------------------------------------------------------

    function es_telefono(obj, sel, trim)
    {
        if (trim)
        {
            trim_obj(obj);
        }

        var len = longitud_obj(obj);

        if (len != 0 && (len < 9 || !es_numero(obj)))
        {
                if (sel)
                {
                        alert('Debe especificar un número de teléfono (al menos 9 dígitos numericos)');
                        sel_obj(obj);
                }

                return false;
        }
        else
        {
                //obj.value = obj.value.toUpperCase();
                return true;
        }
    }

    //------------------------------------------------------------------------------
    // Valida si el campo contiene una direccion email valida
    //------------------------------------------------------------------------------

    function es_email(obj, sel, trim)
    {
        if (trim)
        {
            trim_obj(obj);
        }

        var len = longitud_obj(obj);
        var pos = obj.value.indexOf('@');

        if (len != 0 && (pos == -1 || pos == 0 || pos == len - 1 || obj.value.substring(pos + 1).indexOf('@') != -1))
        {
                if (sel)
                {
                        alert('Debe especificar una dirección de correo electrónico válida (e-mail)');
                        sel_obj(obj);
                }

                return false;
        }
        else
        {
                //obj.value = obj.value.toUpperCase();
                return true;
        }
    }

    //------------------------------------------------------------------------------
    // Valida si el campo contiene un codigo postal (formato Espana pero sin validar el codigo)
    //------------------------------------------------------------------------------

    function es_codigo_postal(obj, sel, trim)
    {
        if (trim)
        {
            trim_obj(obj);
        }

        if (!es_numero(obj) || longitud_obj(obj) != 5)
        {
                if (sel)
                {
                        alert('Debe especificar un código postal con formato válido');
                        sel_obj(obj);
                }

                return false;
        }
        else
        {
                //obj.value = obj.value.toUpperCase();
                return true;
        }
    }

    //------------------------------------------------------------------------------
    // Valida si el campo contiene valor determinado
    //------------------------------------------------------------------------------

    function es_igual(obj, val, sel, trim, ignore)
    {
        if (trim)
        {
            trim_obj(obj);
        }

        var val1 = obj.value;
        var val2 = val;

        if (ignore)
        {
            val1 = val1.toUpperCase();
            val2 = val2.toUpperCase();
        }

        if (val1 != val2)
        {
                if (sel)
                {
                        alert('Valor de campo inválido');
                        sel_obj(obj);
                }

                return false;
        }
        else
        {
                //obj.value = obj.value.toUpperCase();
                return true;
        }
    }

    //------------------------------------------------------------------------
    // Funcion para validar el numero de la seguridad social.
    //----------------------------------------------------------------------

    function es_numero_SSS(pSSS1, pSSS2, pSSS3, sel, trim) 
    { 
        if (trim)
        {
            trim_obj(pSSS1);
            trim_obj(pSSS2);
            trim_obj(pSSS3);
        }
    
        var SSS1 = pSSS1.value; 
        var SSS2 = pSSS2.value; 
        var SSS3 = pSSS3.value; 
        var aux;

        var reNoNumeros = new RegExp('[^0-9]','i');

        if (!reNoNumeros.test("" + SSS1 + SSS2 + SSS3))
        {
            if ((pSSS1.value=='') || (pSSS2.value=='') || (pSSS3.value=='') )
                return true; 

            if ( (SSS1 == '99') || ( (SSS2.length == 8) && ( (SSS2.substr(0,3) == '100') || (SSS2.substr(0,3) == '101'))))
                return true; 

            while ( (SSS2.substr(0,1) == '0') && (SSS2.length > 1) ) 
            { 
                SSS2 = SSS2.substr(SSS2.length - 1, 1); 
            } 

            if (pSSS2.value.length < 6) 
            { 
                aux = '000000' + pSSS2.value; 
                SSS2 = aux.substr(aux.length - 1, 1); 
            }
            else 
            { 
                if (pSSS2.value.length == 6) 
                    SSS2 = '0' + pSSS2.value; 
            } 

            aux = SSS1 + SSS2; 

            if (pSSS3.value == (parseInt(aux) % 97) )
                return true; 
        }

        if (sel)
        {
            alert('El número de la seguridad social no es válido');
            sel_obj(pSSS1);
        }

        return false;
    }

    //------------------------------------------------------------------------------
    // Valida si el campo contiene una fecha valida
    //------------------------------------------------------------------------------
   
    function es_fecha(obj, sel, yy_ini) 
    {
        var a, i;

        a = pasar_formato(obj, yy_ini);

        if (a == "") {
        
           // Para dar el error en el caso de que la funcion pasar_formato nos devuelva
           // una cadena vacia pero sea una fecha invalida.
           if (obj.value != "") {
           
                if (sel) {

                    alert('La fecha no es correcta');
                    sel_obj(obj);
                }

                return false;
           }
            
            /* fecha.value = ''; */
        }

        i = comprobar_fecha(a);

        if (i == 1)
            obj.value = a;
        else if (obj.value.length > 0) {
        
            if (sel) {

                alert('La fecha no es correcta');
                sel_obj(obj);
            }

            return false;
        }
        //else
            //	return false;

        return true;
    }

    function elimina_espacios(sString) 
    {
        while (sString.substring(0,1) == ' ') 
            sString = sString.substring(1, sString.length);
    
        while (sString.substring(sString.length-1, sString.length) == ' ')
            sString = sString.substring(0,sString.length-1);
   
        return sString;
    }

    function pasar_formato(fecha, yy_ini) 
    {    
        var i, j, d, m, y, dd, mm, yyyy, tmp;
        var n_dd = new Number();
        var n_mm = new Number();
        var n_yyyy = new Number();
        var fecha_actual = new Date(); 
        var fecha_retorno = '';
        var valor_fecha = elimina_espacios(fecha.value).replace(/ /gi, '-').replace(/\//gi, '-');
        var barra = new RegExp("[-]");

        i = valor_fecha.search(barra);

        if (i == -1) {
        
            // Error: No es el formato correcto 

            fecha_retorno = '';
            return fecha_retorno;             
        }
        else {
        
           // posibles formatos DD-MM o DD-MM-YY o DD-MM-YYYY 

           tmp = valor_fecha.substr(i + 1, valor_fecha.length);

           j = tmp.search("[-]");

           if (j == -1) {
           
              // posible formato DD/MM 

              dd = valor_fecha.substr(0, i);
              n_dd = dd;

              if (isNaN(n_dd)) {
              
                  // Error: dia incorrecto 

                  fecha_retorno = '';
                  return fecha_retorno;             
              }
              
              mm = valor_fecha.substr(i + 1, valor_fecha.length);
              n_mm = mm;
 
              if (isNaN(n_mm)) {

                  // Error: mes incorrecto 

                  fecha_retorno = '';
                  return fecha_retorno;             
              }
              
              yyyy = fecha_actual.getYear();
              
              if (dd.length == 1) {
              
                  d = '0' + dd;
              }
              else {
              
                  d = dd;
              }
              
              if (mm.length == 1) {
              
                  m = '0' + mm; 
              }
              else {
              
                  m = mm;
              }   

              fecha_retorno = d + '-' + m + '-' + yyyy;
           }
           else {
           
              // posible formato DD/MM/YY o DD/MM/YYYY 

              dd = valor_fecha.substr(0, i);
              n_dd = dd;
              
              if (isNaN(n_dd)) {
              
                  // Error: dia incorrecto 

                  fecha_retorno = '';
                  return fecha_retorno;             
              }

              mm = valor_fecha.substr(i + 1, j);
              n_mm = mm;
              
              if (isNaN(n_mm)) {

                  //  Error: mes incorrecto 

                  fecha_retorno = '';
                  return fecha_retorno;             
              }
              
              yyyy = valor_fecha.substr(i + j + 2, valor_fecha.length);
              n_yyyy = yyyy;

              if (isNaN(n_yyyy)) {
              
                  // Error: ano incorrecto

                  fecha_retorno = '';
                  return fecha_retorno;             
              }
              
              if (dd.length == 1) {
              
                  d = '0' + dd;
              }
              else {
              
                  d = dd;
              }
              
              if (mm.length == 1) {
              
                  m = '0' + mm; 
              }
              else {
              
                  m = mm;
              }   

              if (yyyy.length == 2 && yy_ini) {
                
                  y = yy_ini + yyyy; 
              }
              else {
              
                  y = yyyy;
              }   

              fecha_retorno = d + '-' + m + '-' + y;
           } 
        }   
        
        return fecha_retorno;             
    }

    function comprobar_fecha(fecha) 
    {    
        var ret;
        n_d = new Number();
        n_m = new Number();
        n_y = new Number();

        n_d = fecha.substr(0,2);
        n_m = fecha.substr(3,2);
        n_y = fecha.substr(6,4);

        if ( fecha.length != 10 )
        {
                    return( 0 );	 
        }

        if ( n_m==1 || n_m==3 || n_m==5 || n_m==7 || n_m==8 || n_m==10 || n_m == 12 )
        {
            if ( n_d >0 && n_d <=31 )
            {
                return( 1 );
            }
            else
            {
                return( 0 );
            }
        }
        else if ( n_m==4 || n_m==6 || n_m==9 || n_m==11 )
        {
            if ( n_d >0 && n_d <=30 )
            {
                return( 1 );
            }
            else
            {
                return( 0 );
            }
        }
        else if ( n_m==2 )
        {
            if ( (n_y%4?0:(n_y%100?1:(n_y%400?0:1))) )
            {
               // el ano es bisiesto

               if ( n_d>0 && n_d<=29 )
               {
                   return( 1 );
               }
               else
               {
                   return( 0 );
               }
            }
            else
            {
               if ( n_d >0 && n_d <=28 )
               {
                   return( 1 );
               }
               else
               {
                   return( 0 );
               }
            }
        }
        else
        {
             return( 0 );
        }
    }

    // -----------------------------------------------------------------------------
    // Compara dos fechas
    // -----------------------------------------------------------------------------

    function compara_fecha(fechai, fechaf)
    {
            var pbarra = fechai.lastIndexOf("-");
            var sbarra = fechai.lastIndexOf("-", pbarra-1);

            var fano = fechai.substring( pbarra+1 , fechai.length );
            var fmes = fechai.substring( sbarra+1 , pbarra );
            var fdia = fechai.substring( 0, sbarra);

            mfeci = new Date( fano, fmes-1, fdia );

            var pbarra = fechaf.lastIndexOf("-");
            var sbarra = fechaf.lastIndexOf("-", pbarra-1);

            var fano = fechaf.substring( pbarra+1 , fechaf.length );
            var fmes = fechaf.substring( sbarra+1 , pbarra );
            var fdia = fechaf.substring( 0, sbarra);

            mfecf = new Date( fano, fmes-1, fdia );

            return (mfeci-mfecf);
    }

    function compararfecha(fecha1, fecha2, tipo)
    {
            var dif = compara_fecha(fecha1, fecha2);

            if (tipo == '=' && dif == 0) return true;

            if (tipo == '>' && dif > 0) return true;

            if (tipo == '<' && dif < 0) return true;

            if (tipo == '>=' && dif >= 0) return true;

            if (tipo == '<=' && dif <= 0) return true;

            return false;
    }

    //-----------------------------------------------------------------------
    // Comprueba que la FECHA este comprendida entre FECHA1 y FECHA2
    // -------------------------------------------------------------

    function entre_fechas(fecha, fecha1, fecha2)
    {
      var respuesta;
      respuesta=false;
      if (compararfecha(fecha, fecha1, '>=') && compararfecha(fecha, fecha2, '<='))
      { respuesta=true; }
      return respuesta; 
    }

    // -----------------------------------------------------------------------------
    // Corta los caracteres sobrantes
    // -----------------------------------------------------------------------------

    function corta_len(item,max)
    {
       item.value = item.value.substr(0,max-1);
    }

    // ------------------------------------------------------------------------------
    // Comprueba la longitud maxima de un campo
    // ------------------------------------------------------------------------------

    function longitud_obj(obj, trim)
    {
        if (trim)
        {
            trim_obj(obj);
        }

        return obj.value.length;
    }

    function comp_len(item,max)
    {
            lon = item.value.length;

            if(lon >= max)
            {
                    cadena = "Ha superado la longitud máxima del campo: " + max + " caracteres. Se perderán los caracteres que sobran";
                    alert(cadena);
                    valor = item.value;
                    lon = item.value.length
                    item.value = valor.substring(0,max-1);
                    item.focus;
                    return false;
            }
            else
            {
                    return true;
            }
    }

    // -----------------------------------------------------------------------------
    // Convierte los decimales con comas a decimales con puntos
    // -----------------------------------------------------------------------------

    function ConPunto(obj)
    {
       coma = new RegExp( "[',']" );

       i = obj.value.search(coma);

       if ( i != -1 ) {

          obj.value = obj.value.substr(0,i)+"."+obj.value.substr(i+1,obj.value.length-i-1);           
       }

       if (obj.value.substr(0,1)=='.') {
          obj.value = '0' + obj.value.substr(0,obj.value.length-1);
       }
    }

    // -----------------------------------------------------------------------------
    // Convierte el texto del objeto enviado a mayusculas
    // -----------------------------------------------------------------------------

    function pasa_mayuscula(obj)
    {
            obj.value = obj.value.toUpperCase();
    }

    // -----------------------------------------------------------------------------
    // Comprueba si el texto del objeto SELECT enviado esta vacio
    // -----------------------------------------------------------------------------

    function EsVacioCombo(obj) 
    {
          if (obj.options[obj.selectedIndex].value.length==0) 
          {
              obj.focus();
              return false;
          }
          else
          {
              return true
          }
    }

    function EsMesAno( mesano )
    {
        var a;
        var i;
        var valor;

        valor = mesano.value;
        mesano.value='01/'+mesano.value;

        a = pasar_formato( mesano );

        if ( a == "" )
        {
            mesano.value = '';
        }
        i = comprobar_fecha( a );

        if ( i == 1 )
        {
           mesano.value = a.substr(3,7);
        }
        else if ( mesano.value.length > 0 )
        {
           mesano.value = valor;
           alert( "la fecha no es correcta. ");
              mesano.focus();
           mesano.select();
           return false;
        }
        else
        {
           return false;
        }

    return true;
    }

    //---------------------------------------------------------------
    // Obliga a seleccionar al menos un valor de una caja de seleccion
    //---------------------------------------------------------------

    function sel_option(obj)
    {
            var seleccionados = 0;

            var indice_actual = 0;

            if (obj.selectedIndex == -1)
            {
                    for (a=0;a<obj.length;a++)
                    {
                            if (obj.options(a).defaultSelected)
                            {
                                    indice_actual = a;
                            }
                    }
            }
            else
            {
                    for (a=0;a<obj.length;a++)
                    {		
                            if (obj(a).selected)
                            {
                                    seleccionados ++;
                                    obj.options(a).defaultSelected=true;
                            }
                            else
                            {
                                    obj.options(a).defaultSelected=false;
                            }
                    }
            }

            if (seleccionados == 0)
            {    
                    obj(indice_actual).selected=true;
            }
    }

    //---------------------------------------------------------------
    // Nos situa en el primer elemento del primer formulario de una pagina
    //---------------------------------------------------------------
    function sel_primer_elem_form()
    {
        if (document.forms.length > 0)
        {
            var i = 0;
            var f = document.forms[0];
            var num_elem = f.elements.length;

            while (i < num_elem && (f.elements[i].type == 'hidden' || f.elements[i].disabled))
            {                
                i = i + 1;
            }
            if (i < num_elem)
            {
                sel_obj(f.elements[i], true);
            }
        }
    }

// ]]>
