// ---------------------------------------------------------------------- //
//           FormCheq.js (c) ChaTo 1998,1999 [www.chato.cl]
//                           Basado en:
//           FormChek.js (c) Eric Krock (c) 1997 Netscape              
// ---------------------------------------------------------------------- //
// 18 Feb 97 creado por Eric Krock (c) 1997
//   Netscape Communications Corporation
// 18 Ago 98 modificado por Carlos Castillo (c) 1998 ChaTo
//   Los principales cambios son: esta version es simplificada, para
//   propositos de ensennanza y validacion basica de formularios, y esta
//   adaptada para recibir caracteres del alfabeto espannol (acentos, etc.)
// 20 Oct 99 modificado por Carlos Castillo (c) 1999 ChaTo
//   Se agrega la funcion isNice que ayuda a evitar comillas simples
//   o dobles que causan problemas con muchos CGIs
// 
// ---------------------------------------------------------------------- //
//                             RESUMEN                                    //
// ---------------------------------------------------------------------- //
// 
// El objetivo de las siguientes funciones en JavaScript es
// validar los ingresos del usuario en un formulario antes
// de que estos datos vayan al servidor.
//
// Varias de ellas toman un parametro opcional E.O.K (eok) (emptyOK
// - true si se acepta que el valor este vacio, false si no
// se acepta). El valor por omision es el que indique la
// variable global defaultEmptyOK definida mas abajo.
//
// ---------------------------------------------------------------------- //
//                      SINTAXIS DE LAS FUNCIONES                         //
// ---------------------------------------------------------------------- //
//
// FUNCION PARA CHEQUEAR UN CAMPO DE INGRESO:
//
// checkField (theField, theFunction, [, s] [,eok])
//        verifica que el campo de ingreso theField cumpla con la
//        condicion indicada en la funcion theFunction (que puede ser
//        una de las descritas en "FUNCIONES DE VALIDACION" o cualquier
//        otra provista por el usuario). En caso contrario despliega el
//        string "s" (opcional, hay mensajes por default para las
//        funciones de validacion provistas aqui).
//
// FUNCIONES DE VALIDACION:
//
// isInteger (s [,eok])                s representa un entero
// isNumber (s [,eok])                 s es entero o tiene punto decimal
// isAlphabetic (s [,eok])             s tiene solo letras
// isAlphanumeric (s [,eok])           s tiene solo letras y/o numeros
// isPhoneNumber (s [,eok])            s tiene solo numeros, (,),-
// isEmail (s [,eok])                  s es una direccion de e-mail
//
// 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

// Esta variable indica si se debe verificar la presencia de comillas
// u otros símbolos extraños en un campo, por omisión no, porque
// siempre crea problemas con las bases de datos o programas CGI
var checkNiceness = true;

// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü "
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ "
var whitespace = " \t\n\r";

// caracteres admitidos en nos de telefono
var phoneChars = "()-+ ";

// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar este espacio vacio"

// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = "ingrese un texto que contenga solo letras y/o numeros";
var pAlphabetic   = "ingrese un texto que contenga solo letras";
var pInteger = "ingrese un numero entero";
var pNumber = "ingrese un numero";
var pPhoneNumber = "ingrese un número de teléfono";
var pEmail = "ingrese una dirección de correo electrónico válida";
var pName = "ingrese un texto que contenga solo letras, numeros o espacios";
var pNice = "no puede utilizar comillas aqui";

// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //

// JavaScript 1.0 (Netscape 2.0) no tenia un constructor para arreglos,
// asi que ellos tenian que ser hechos a mano. Desde JavaScript 1.1 
// (Netscape 3.0) en adelante, las funciones de manejo de arreglos no
// son necesarias.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

// ---------------------------------------------------------------------- //
//                  CODIGO PARA FUNCIONES BASICAS                         //
// ---------------------------------------------------------------------- //


// s es vacio
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// s es vacio o solo caracteres de espacio
function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

// Quita todos los caracteres que que estan en "bag" del string "s" s.
function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Buscar por el string, si el caracter no esta en "bag", 
    // agregarlo a returnString
    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

// Quitar todos los espacios en blanco de un string
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

// La rutina siguiente es para cubrir un bug en Netscape
// 2.0.2 - seria mejor usar indexOf, pero si se hace
// asi stripInitialWhitespace() no funcionaria

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Quita todos los espacios que antecedan al string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// c es una letra del alfabeto espanol
function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// c 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;
//-----------------coto------------------
myString = new String(s)
rExp = /./gi;
newString = new String ("")
results = myString.replace(rExp, newString)
document.write(results)
//-----------------coto------------------
    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;
}






// s es un valor de dinero
function isMoney (s){   		
var aux;
	if (s.value.length == 0) {
	alert("Ingrese el cupo solicitado por favor.");
	s.focus();
	return false;
	}
	
    return true;
}

function isVacio (s, msje){
		if (s.value.length == 0){
			alert(msje);
			s.focus();
			return false;
		}
    return true;
}

function noread(s){
	eval(s+".readOnly=true");
	return;
}

function read(s){
	eval(s+".readOnly=false");
	return;
}
// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //

// s tiene solo letras
function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}


// s tiene solo letras y numeros
function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

// s tiene solo letras, numeros 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))
	return true
}

function isNice(s)
{
        var i = 1;
        var sLength = s.length;
        var b = 1;
        while(i<sLength) {
                if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
                i++;
        }
        return b;
}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA RECLAMARLE AL USUARIO                  //
// ---------------------------------------------------------------------- //

// pone el string s en la barra de estado
function statBar (s)
{   //window.status = s
}

// notificar que el campo theField esta vacio
function warnEmpty (theField)
{   theField.focus()
    alert(mMessage)
    statBar(mMessage)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(s)
    statBar(pPrompt + s)
    return false
}

// the center of everything: checkField
function checkField (theField, theFunction, emptyOK, s, d)
{   
	//alert(checkField.arguments[0].value)
	if ((checkField.arguments[0].value == "") && (checkField.arguments[4] != "")){
		alert(d);
		theField.focus();
		return false;
	}
    var msg;
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 5) {
        msg = s;
    } else {
        if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        if( theFunction == isInteger ) msg = pInteger;
        if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
        if( theFunction == isName ) msg = pName;
    }
    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField);

    if ( checkNiceness && !isNice(theField.value))
        return warnInvalid(theField, pNice);

    if (theFunction(theField.value) == true) 
        return true;
    else
        return warnInvalid(theField,msg);

}

// ---------------------------------------------------------------------- //
//                          FUNCION TRIM                                  //
//                  FUNCIONES PARA VERIFICAR RUT                          //
// ---------------------------------------------------------------------- //
function verificarRut(strRut){
	var rut;
	var rut_array;
	var falso_array;
	var dv;
	var falso ;
	var c = 0;

	falso = "000000000,00000000-0,111111111,11111111-1,222222222,22222222-2,333333333,33333333-3,";
	falso = falso + "444444444,44444444-4,555555555,55555555-5,666666666,66666666-6,";
	falso = falso + "777777777,77777777-7,888888888,88888888-8,999999999,99999999-9";
	falso_array = falso.split(",");
	//alert(falso_array.length);
	//alert(falso_array[0]);
	/*while(c < falso_array.length) 
	{ 
	   if (strRut == falso_array[c])
		{
		alert("Rut no es válido!!!");
		document.solicitelo.rutdig.focus();
		return false;
		}
	   c++; 
	}*/ 

	if( strRut.value.length == 0 )
	{
	//alert(rut_array.length)
		alert("Por favor ingrese su Rut.");
		strRut.focus();
		return false;
		}

	rut_array=strRut.value.split("-");
	if( rut_array[0].length == 1 || rut_array[0].length == 2 )
	{
	//alert(rut_array.length)
		alert("Rut no es válido!!!");
		strRut.focus();
		strRut.value="";
		return false;
		}

	if(rut_array[0].length != 0)
		{
		if (rut_array[0].length == strRut.value.length)// sin guion
		   {
			dv = rut_array[0].substring(strRut.value.length-1,strRut.value.length);
			rut = rut_array[0].substring(0,strRut.value.length-1);

			if (esRutValido(rut,dv) != 1)
				{
				alert("Rut no es válido");
				strRut.focus();
				strRut.select();
				return false;
				}
			}
		else                             //   con guion
			{
			rut = rut_array[0];
			dv = rut_array[1];
			if (esRutValido(rut,dv) != 1)
				{
				alert("Rut no es válido");
				strRut.focus();
				strRut.select();
				return false;
				}
			}
		strRut.value=rut+"-"+dv;
		return true;
		}

}
//------------------------------------------------------------
// Verifica que el Digito verificador se corresponda al RUT.
function esRutValido(strRut,strDigito) {
   var digVerif;
   digVerif=digitoVerificador(strRut)
  // alert("digito:" + digVerif + "| dig ing:"+strDigito+"|");
   if(digVerif==strDigito.toLowerCase())
       return(1);
   else
   	   return(0);

}

// Retorna el Digito verificador de un RUT.
function digitoVerificador(strRut) {

    var Largo, LargoN, i, Total;
    var Numero="", Verif, Carac, CaracVal;
    var tmpRut,intTmp;

    tmpRut = trim(strRut)

    Largo = tmpRut.length
    LargoN = 0
    for(i=0;i<Largo;i++) {
        Carac = parseInt(tmpRut.charAt(i),10);
        if(Carac >=0 && Carac <=9) {
			Numero+=tmpRut.charAt(i);
            LargoN++;
	 	}
    }

	Total=0;
    for(i=LargoN-1;i>=0;i--) {
		if((LargoN - i) < 7) {
		   intTmp=LargoN - i + 1;
		} else {
		   intTmp=LargoN - i - 5;
		}
        Total+= parseInt(Numero.charAt(i),10) * intTmp 
    }
    
    CaracVal = 11 - (Total % 11)
    
    if(CaracVal==10) {

       return('k');
	}
	
	if(CaracVal >=0 && CaracVal <=9) {

       return(CaracVal);
	}
	
	if(CaracVal==11) {
	   return(0);
    }
}

// ---------------------------------------------------------------------- //
//                 FIN FUNCIONES PARA VERIFICAR RUT                       //
//                          FUNCION TRIM                                  //
// ---------------------------------------------------------------------- //

function trim(cadena) {
	var nuevacadenal="";
	var nuevacadenar="";
	var intLimitel;
	var intLimiter;
	
	for(i=0;i<cadena.length;i++) {
	  if(cadena.charAt(i)==" ") {
	    intLimitel++;
	  } 
	  else {
	  	break;
	  }
	}
	
	nuevacadenal=cadena.substring(intLimitel,cadena.length);
	intLimiter=nuevacadenal.length;
	for(i=nuevacadenal.length-1;i>=0;i--) {
	    if(nuevacadenal.charAt(i)==" ") {
			intLimiter--;
	    } else {
		  break;
		}
	}
	
	nuevacadenar=nuevacadenal.substring(0,intLimiter);
	
	return(nuevacadenar)
}
// ---------------------------------------------------------------------- //
//                FUNCIONES PARA VERIFICAR EMAIL (v1)                     //
// ---------------------------------------------------------------------- //
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) != "@"))// avanza en toda la variable hasta encontrar @ 
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;//llego al finl y no encontro el @
    else i += 2;


    while ((i < sLength) && (s.charAt(i) != ".") && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".") || (s.charAt(i) == "@")) return false;
    else return true;
}
// ---------------------------------------------------------------------- //
//                FUNCIONES PARA VERIFICAR EMAIL (v2)                     //
// ---------------------------------------------------------------------- //

function valida_mail(campo) 
{       
	alert(campo)
        campo.value = campo.replace (/[ ]+$/,"");                 //realiza un rtrim... 
        campo.value = campo.replace (/^[ ]+/,"");                 //realiza un ltrim... 
        valor=campo 

        if (valor=="") { alert("Debe ingresar una dirección email.");return (false); } 

        if (/(.*);(.+)/.test(valor) || /(.*),(.+)/.test(valor))         //valida que no haya mas de una direccion ( , ) y ( ; )
          { alert("Sólo puede ingresar una dirección email.");return (false);} 
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(valor))        //valida el email 
          {return (true);} 
        else 
          {alert("La dirección email es incorrecta.");return (false);} 
return false; 
} 
// ---------------------------------------------------------------------- //
//   FUNCIONES PARA PERMITIR SOLO EL INGRESO DE NUMEROS (SIN , Y/O .)     //
// ---------------------------------------------------------------------- //
function OnlyNumCoto()
{
if (document.all)
 {
  t=event.keyCode;
  if ((t>=48 && t<=57) || t==8 || t==46) 
    {t=0}
  else 
   {event.keyCode= 0;}
 }  
} 
// ---------------------------------------------------------------------- //
//  FIN FUNCIONES PARA PERMITIR SOLO EL INGRESO DE NUMEROS (SIN , Y/O .)  //
// ---------------------------------------------------------------------- //

<!--
/* CONSIDERACIONES GENERALES
	Las funciones principales son verificarRutGeneral y verificarRutGeneralEnter.
*/

/*var accionInterna: 
Se utiliza en la funcion verificarRutGeneralEnter, para discernir si se realiza la verificacion o no. Si esta variable no está se verificaria dos veces en el caso de pulsar enter en el primer cuadro de texto (por OnChange y por ENTER en si).
*/  
var accionInterna=0;
var submitcount=0;


//--------------------------------------
//function blurTxt
//Objetivo: Saca el focus de los cuadros de texto.
//Parametro(s):
//Uso: Cuando se termina de cargar la pagina.
//Requiere: --- 
//--------------------------------------
function blurTxt(){	
	document.autent.d_pin.blur();
	document.autent.d_rut.blur();
}

//--------------------------------------
//function digitoVerificador
//Objetivo: Retornar el Digito verificador de un RUT.
//Parametro(s):(input)String de ingreso de rut (incluyendo el DV).
//(output) DV obtenido
//Uso: desde fnc. verificarRut
//Requiere:  
//--------------------------------------
function digitoVerificador(strRut) {
    var Largo, LargoN, i, Total;
    var Numero="", Verif, Carac, CaracVal;
    var tmpRut,intTmp;
    
    tmpRut = strRut;
    Largo = tmpRut.length;
    LargoN = 0;
    for(i=0;i<Largo;i++) {
        Carac = parseInt(tmpRut.charAt(i),10);
        if(Carac >=0 && Carac <=9) {
			Numero+=tmpRut.charAt(i);
            LargoN++;
	 	}
    }
	Total=0;
    for(i=LargoN-1;i>=0;i--) {
		if((LargoN - i) < 7) {
		   intTmp=LargoN - i + 1;
		} else {
		   intTmp=LargoN - i - 5;
		}
        Total+= parseInt(Numero.charAt(i),10) * intTmp 
    }
    
    CaracVal = 11 - (Total % 11)

    if(CaracVal==10) {
       return('K');
	}
	
	if(CaracVal >=0 && CaracVal <=9) {
       return(CaracVal);
	}
	
	if(CaracVal==11) {
	   return(0);
    }
}

//--------------------------------------
//function soloNumeros
//Objetivo: Verifica que existan solo numeros.
//Parametro(s):(input)String 
//(output) 1 sin son solo numeros, 0 en caso contrario
//Uso: desde fnc. verificarRut y verificarRutGeneral
//Requiere:  
//--------------------------------------
function soloNumeros(strIn) {
  var Nros="1234567890";
  var CrtrAux;
  var iaux=0;
  for (var i=0; i < strIn.length; i++)
  {
    CrtrAux = strIn.charAt(i);
    if (Nros.indexOf(CrtrAux) != -1)
      iaux++;
  }
  if ((iaux != strIn.length) || (strIn.length==0)){
   	return 0
	}
  else
    return 1;
}

//--------------------------------------
//function enviarRut
//Objetivo: Envio de formulario
//Parametro(s):(input)String con Rut y entero tipo
//(output) submit
//Uso: desde fnc. verificarRutGeneral
//Requiere:  
//--------------------------------------
function enviarRut(strRut, tipo){
var movie = window.document.dvd_1;
var movieb = window.document.ski_home;

if (movie){
	movie.Stop();
	closeIt('layerdvd');
}

if (movieb){
	movie.Stop();
	closeIt('Layer1');
}

var navegador = navigator.appName;
var version = navigator.appVersion;
var punto = navigator.appVersion;
var total;

version = parseInt(version);
punto = "" + parseInt(punto.substring(punto.indexOf(".")+1,punto.length - 1)) + "00";
punto = punto.substring(0,2);
total = (version * 100) + parseInt(punto);
if ((navegador == "Netscape") && (total < 499)){
		document.layers['enviar'].innerHTML=''; 
		document.layers['cubrex'].visibility='show';
	}
	else {
		document.getElementById("enviar").innerHTML=''; 
		document.getElementById("cubrex").style.visibility='visible';
	}

	straux = strRut.substring(0,strRut.length-1);	
    document.autent.d_rut.value = "";
    document.autent.d_pin.value = "";
    document.autent.rut.value="" + straux + digVerifIn;
    document.autent.tipo.value=tipo;
  	var OnlyRut = new Number(straux);
  	if (OnlyRut > 50000000){
		document.passemp.rut.value = document.autent.rut.value;	
		document.passemp.pin.value = document.autent.pin.value;	
		document.passemp.submit();	
		return true;			  	  
  	}

  	document.autent.submit();
  	return true;
}

//--------------------------------------
//function limpiarRut
//Objetivo: Solo Limpieza de RUT de ceros a la izquierda, guiones y puntos(deja digitos y k)
//Parametro(s):(input)String con Rut
//(output) String con rut limpio
//Uso: desde fnc. verificarRutGeneral
//Requiere:  
//--------------------------------------
function limpiarRut(strRut){	
	document.autent.rut.value = document.autent.d_rut.value;
	var digVerif ="";
	var digVerifIn ="";
	var straux ="";
	var rutsgnp = "";
	while((new Number(strRut.charAt(0))==0)&&(strRut!="")){
		strRut=strRut.substring(1,strRut.length);		
	}
	for (i=0; i < strRut.length; i++)
	{
		if ((strRut.charAt(i) != ".") && (strRut.charAt(i) != "-") && (strRut.charAt(i)!=" "))
			rutsgnp= rutsgnp + strRut.charAt(i);
	   }
	return rutsgnp;
}

//--------------------------------------
//function verificarRut
//Objetivo: Solo Verificacion del string RUT
//Parametro(s):(input)String con Rut
//(output) true si el rut es correcto, false si no
//Uso: desde fnc. verificarRutGeneral
//Requiere:  fnc. solonumeros, digitoVerificador
//--------------------------------------
function verificarRut(strRut)
{	
	if (strRut != "")  
	{
	   straux = strRut.substring(strRut.length-1,strRut.length);
	   if (straux == "k") 
		 digVerifIn = straux.toUpperCase()
	   else
		 digVerifIn = straux;
	   straux = strRut.substring(0,strRut.length-1);
	   if (soloNumeros(straux) == 0)
		 digVerif = "KX"
	   else
		 digVerif = digitoVerificador(straux);

	   if(digVerif == digVerifIn){
			accionInterna=1;
			return true;
			}
	   else 
	   {
		   alert("RUT incorrecto.");
		   submitcount=0;
		   document.autent.d_rut.value="";
		   document.autent.d_pin.value="";
		   document.autent.d_pin.blur();
		   document.autent.d_rut.focus();
		   document.autent.d_rut.select();
		   accionInterna=0;		   
		   return false;
		}
	} 
	else
	{	alert("Debe ingresar el RUT.");
		submitcount=0;
		document.autent.d_rut.value="";
		document.autent.d_pin.blur();
		document.autent.d_rut.focus();
		document.autent.d_rut.select();		
		return false;
	}
}

//--------------------------------------
//function formatearRut
//Objetivo: Formateo del RUT
//Parametro(s):(input)String con Rut
//(output) imprime rut formateado en cuadro de texto
//Uso: desde fnc. verificarRutGeneral
//Requiere:  
//--------------------------------------
function formatearRut(strRut){
	straux = strRut.substring(strRut.length-1,strRut.length);
	rutsgnp= strRut.substring(0,strRut.length-1);

	strAuxArray = new Array(0,0,0);
	strAuxArray[0]=rutsgnp.substring(rutsgnp.length-3,rutsgnp.length);
	strAuxArray[1]=rutsgnp.substring(rutsgnp.length-6,rutsgnp.length-3);
	strAuxArray[2]=rutsgnp.substring(0,rutsgnp.length-6);
	i=0;
	rutsgnp="-"+straux;
	for (i=0; i < 3; i++){
		if (strAuxArray[i]==""){
			i=3;
		}else{
			if (i>0){
				rutsgnp="."+rutsgnp;
			}
			rutsgnp=strAuxArray[i]+rutsgnp;
		}
	}
	document.autent.d_rut.value=rutsgnp;
	document.autent.d_rut.blur();
	document.autent.d_pin.focus();
	document.autent.d_pin.select();
}

//--------------------------------------
//function verificarRutGeneralEnter
//Objetivo: Verificacion del rut ingresado cuando se teclea ENTER.
//va a verificarRutGeneral solo si el cuadro de clave no es vacio.
//Parametro(s):(input)String con Rut, int tipo, int action
//Uso: desde pagina
//Requiere:  verificarRutGeneral
//--------------------------------------


//--------------------------------------
//--------- Verificacion (Enter) -------
//--------------------------------------
function verificarRutGeneralEnter(strRut, tipo, action) {
		if (document.autent.d_pin.value!=""){
			if (conta()){		
			 	verificarRutGeneral(strRut, tipo, action);
			}else{
				alert("Complete todos los datos, por favor.");
			}				
		}else{
			if (document.autent.d_rut.value!=""){
				if (accionInterna==1){
					document.autent.d_pin.focus();
					document.autent.d_pin.select();
					alert("Debe ingresar la clave");
				}else{
					document.autent.d_pin.blur();
					document.autent.d_rut.focus();
					document.autent.d_rut.select();
					alert("Debe ingresar el RUT.");				
				}

			}

		}
	 return false;
}

//--------------------------------------
//function verificarRutGeneral
//Objetivo: Verificacion del rut ingresado. 
// si la accion no es envio solo formatea 
//Parametro(s):(input)String con Rut, int tipo, int action
//Uso: desde pagina
//Requiere:  limpiarRut, verificarRut, soloNumeros, enviarRut, formatearRut
//--------------------------------------

function verificarRutGeneral(strRut, tipo, action){
	if (strRut==""){
		alert("Debe ingresar el RUT.");
		submitcount=0;
		document.autent.d_pin.blur();
		document.autent.d_rut.focus();
		document.autent.d_rut.select();
		}
	else{	
		strRut=limpiarRut(strRut);
		if (verificarRut(strRut)){			
			if (action==1){ //envia
				if (document.autent.d_pin.value!=""){
					if (document.autent.d_pin.value.length==4){						
						document.autent.pin.value = document.autent.d_pin.value;
						if(soloNumeros(document.autent.d_pin.value)==0){
							alert("Clave incorrecta.");
							submitcount=0;
							document.autent.d_pin.value="";
							document.autent.d_pin.focus();
							document.autent.d_pin.select();
							return;
						}else{
							if (tipo != 0){
								document.img_log.src="/log/proceso.asp?id=001&descripcion=seleccion_"+tipo+"&sal=banners&dl=" + Math.random()*1000;
							 }
							enviarRut(strRut, tipo);
						}
					}else{
						alert("La clave debe poseer un largo de cuatro dígitos");
						submitcount=0;
						document.autent.d_pin.value="";
						document.autent.d_pin.focus();
						document.autent.d_pin.select();
						return;
					}
				}else{
					alert("Debe ingresar la clave.");
					submitcount=0;
					document.autent.d_rut.blur();
					document.autent.d_pin.focus();
					document.autent.d_pin.select();
				}
			}else{ //formatea
				formatearRut(strRut);
				document.autent.d_pin.select();				
			}
		}
	}
}


//--------------------------------------
//----  envio del formulario con ENTER
//--------------------------------------
function clickHandlerx(evnt) {
   var codigo
   if (navigator.appName == "Netscape"){
     codigo = evnt.which
   } else {
     codigo = window.event.keyCode
   }
   
   if (codigo == 13){
   	  verificarRutGeneralEnter(document.autent.d_rut.value,0,1);
	  //esRutValido(document.autent.d_rut.value,0);
      return false;
   } else
       return true;
}

//--------------------------------------
//----  cambio de focus
//--------------------------------------
function cambio(){
	document.autent.d_pin.focus();
	document.autent.d_pin.select();	
}

//--------------------------------------
//----  cambio de focus
//--------------------------------------
function submit_envio(paramRut,param1,param2){
	if (conta())	
		verificarRutGeneral(paramRut,param1,param2);
	else
		alert( "Complete todos los datos, por favor.");
}

function conta() {
   if (submitcount == 0)
      {	submitcount++;
      	return true;}
   else 
      return false;      
   }

//-------------------------------------
//----- rollover
//-------------------------------------

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// ---- Abre Pop up

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//----  NETSCAPE

if (navigator.appName == "Netscape"){
  document.captureEvents(Event.KEYPRESS);
  document.onkeypress = clickHandlerx;
}

//--------------------------------------
//function open_win
//Objetivo: Abrir un nuevo vinculo como nueva página o pop up y registrar
// por cada nuevo vinculo cliqueado genera un nuevo log.
//Parametro(s):(int id)código ubicación vinculo, (str desc)descripción vinculo, , (str atex)nombre archivo texto salida,
// (str url)nombre vinculo a abrir, (bool popup) es pop up o página, (str namframe) popup=0; nombre frame de abertura, 
// (str features) popup=1; nombre frame de abertura
// 'toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=200,height=200'
//Uso: desde pagina
//Requiere:  abrir vunculo, generar log
// PERSONAS___id:  		101-banner superior   ;   102-banner inferior   ;    103-caluga izquierda    ;    104-caluga //derecha
// EMPRESAS___id:  		201-banner superior   ;   202-banner inferior   ;    203-caluga izquierda    ;    204-caluga //derecha
// PYME___id:  			301-banner superior   ;   302-banner inferior   ;    303-caluga izquierda    ;    304-caluga //derecha
// NINTERNACIONAL___id:  401-banner superior   ;   402-banner inferior   ;    403-caluga izquierda    ;    404-caluga derecha
// FF.MM.___id:  		501-banner superior   ;   502-banner inferior   ;    503-caluga izquierda    ;    504-caluga derecha
// Banners para sitios externos 	"utilizar externos.txt"
// desdeotrossitio con informacion del banco___id:	600-banners		;	601-link texto
// email____id:		700
// <img name="img_log" src="http://www.santandersantiago.cl/log/proceso.asp?id='700'&descripcion='escribir_descripcion'&sal='emails'" width="1" height="1">
//--------------------------------------

function open_win(id, desc, atex, popup, url, namframe, features) {
//poner en onclick cuando sea pop up (blank) y en href cuando sea pagina (self, top, perent)
	if (popup == 0){ 
	    document.img_log.src="/log/proceso.asp?id="+id+"&descripcion="+desc+"&sal="+atex+"&dl=" + Math.random()*1000;
		cad = namframe + ".location.href='" + url + "'";
	  	eval(cad);
	  }
	else if (popup == 1)
		{
		document.img_log.src="/log/proceso.asp?id="+id+"&descripcion="+desc+"&sal="+atex+"&dl=" + Math.random()*1000;
		window.open(url, namframe, features);
		}
	document.img_log.src="/img_comunes/transpa.gif";
}


//-->

