﻿// Globales web
var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);

var LoadHandler = {
  handlers:[],
  add:function(fn){
    if(window.onload!=LoadHandler.theHandler) LoadHandler._push(window.onload);
    LoadHandler._push(fn);
    window.onload=LoadHandler.theHandler;
  },
  _push:function(fn){
    if(typeof(fn)!='function') return;
    LoadHandler.handlers[LoadHandler.handlers.length]=fn;
  },
  theHandler:function(){
    var handlers=LoadHandler.handlers,i=-1,fn;
    while(fn=handlers[++i]) fn();
  }
}

function usuariologin_onclick() {
    campousuario = document.getElementById('usuariologin');   
    if(campousuario.value == 'usuario') campousuario.value = '';
}

/*
function ValidaLogin(){
    var nErrores = 0;
    var msgError = '';
    var usuario = document.getElementById('usuariologin');
    var clave = document.getElementById('clavelogin');
    var msglogin = document.getElementById('msglogin');
    var frm = document.getElementById('frmlogin');
    
    if(usuario.value == '' || usuario.value == 'usuario'){
        msgError += '- usuario\n';
        nErrores++;
    } else {
        if(usuario.value.length < 6){
            msgError += '- largo usuario\n';
            nErrores++;
        }
    }
    
    if(clave.value == '' || clave.value == 'contraseña'){
        msgError += '- contraseña\n';
        nErrores++;
    } else {
        if(clave.value.length < 6){
            msgError += '- largo contraseña\n';
            nErrores++;
        }
    }       
    
    if (nErrores > 0){
        msglogin.innerHTML = 'Complete: \n'+msgError;
        alert('Complete: \n'+msgError);
        return false;
    } else {
        frm.submit();
    }    
}*/

function changeInputType(
  oldElm, // a reference to the input element
  iType, // value of the type property: 'text' or 'password'
  iValue, // the default value, set to 'password' in the demo
  blankValue, // true if the value should be empty, false otherwise
  noFocus) {  // set to true if the element should not be given focus
  
  if(!oldElm || !oldElm.parentNode || (iType.length<4) || 
    !document.getElementById || !document.createElement) return;
  
  var isMSIE=/*@cc_on!@*/false;
  
  if(!isMSIE){
    var newElm=document.createElement('input');
    newElm.type=iType;
  } else {
    var newElm=document.createElement('span');
    newElm.innerHTML='<input type="'+iType+'" name="'+oldElm.name+'">';
    newElm=newElm.firstChild;
  }
  
  var props=['name','id','className','size','tabIndex','accessKey'];
  for(var i=0,l=props.length;i<l;i++){
    if(oldElm[props[i]]) newElm[props[i]]=oldElm[props[i]];
  }
  
  newElm.onfocus=function(){return function(){
    if(this.hasFocus) return;
    var newElm=changeInputType(this,'password',iValue,
      (this.value.toLowerCase()==iValue.toLowerCase())?true:false);
    if(newElm) newElm.hasFocus=true;
  }}();
  
  newElm.onblur=function(){return function(){
    if(this.hasFocus)
    if(this.value=='' || (this.value.toLowerCase()==iValue.toLowerCase())) {
      changeInputType(this,'text',iValue,false,true);
    }
  }}();
  // hasFocus is to prevent a loop where onfocus is triggered over and over again
  newElm.hasFocus=false;
  // some browsers need the value set before the element is added to the page
  // while others need it set after
  if(!blankValue) newElm.value=iValue;
  oldElm.parentNode.replaceChild(newElm,oldElm);
  if(!isMSIE && !blankValue) newElm.value=iValue;
  if(!noFocus || typeof(noFocus)=='undefined') {
    window.tempElm=newElm;
    setTimeout("tempElm.hasFocus=true;tempElm.focus();",1);
  }
  return newElm;
}

LoadHandler.add(
function(){
  var ua=navigator.userAgent.toLowerCase();
  if(!((ua.indexOf('konqueror')!=-1) && /khtml\/3\.[0-4]/.test(ua)) && !(((ua.indexOf('safari')!=-1) && !window.print))) {      
      changeInputType(document.forms[0].clavelogin,'text','contraseña',false,true);
  }
});

function formatoRut(fldRut, evt){
    rut = document.getElementById(fldRut);	 
    var strrut = rut.value;
    var rutfinal = '';
    var largo = strrut.length;
    var dvaux = '';
    
    if(evt){                                            
        if(typeof(evt.keyCode) == 'number'){
            //DOM
            e = evt.keyCode;
        }else if(typeof(evt.which) == 'number'){
            //NS 4 compatible
            e = evt.which;
        }else if(typeof(evt.charCode) == 'number'){
            //also NS 6+, Mozilla 0.9+
            e = evt.charCode;
        }
        
        if (e == 8 || e == 46){
            return true;
        }else{
            if(largo > 7){
                if ((e >= 48 && e <= 57) || (e >= 96 && e <= 105) || (e == 75) || (e == 107) || (e == 9)){                         
                    if (largo == 8) rut.value = strrut+'-';               
                    return e;
                }else{                                                
                    return false;
                }
            }else{                 
                if ((e >= 48 && e <= 57) || (e >= 96 && e <= 105)){             
                    return e;
                }else{                                                
                    return false;
                }
            }
        }
    }else{
        alert('Su navegador no soporta javascript');
        return;
    }               
}

function showhide(id){
    elem = document.getElementById(id);    
    
    if (elem.style.display == 'none'){	
	    // Netscape 4
	    if(ns4){
		    document.layers[id].position = 'static';
		    document.layers[id].visibility = 'show';
	    }
	    // Explorer 4
	    else if(ie4){
		    document.all[id].style.position = 'static';
		    document.all[id].style.visibility = 'visible';
	    }
	    // W3C - Explorer 5+ and Netscape 6+
	    else if(ie5 || ns6){
		    document.getElementById(id).style.position = 'static';
		    document.getElementById(id).style.visibility = 'visible';
	    }
	    elem.style.display = '';
	} else {
		// Netscape 4
	    if(ns4){
		    document.layers[id].position = 'absolute';
		    document.layers[id].visibility = 'hide';
	    }
	    // Explorer 4
	    else if(ie4){
		    document.all[id].style.position = 'absolute';
		    document.all[id].style.visibility = 'hidden';
	    }
	    // W3C - Explorer 5+ and Netscape 6+
	    else if(ie5 || ns6){
		    document.getElementById(id).style.position = 'absolute';
		    document.getElementById(id).style.visibility = 'hidden';
	    }
	    elem.style.display = 'none';
	}
}

function separaRut(obj_rut,obj_dv){

    texto = obj_rut.value + obj_dv.value
	var dv = obj_rut.value.charAt(obj_rut.value.length-1);
	var rut = obj_rut.value.substring(0,obj_rut.value.length-1);
	if(!isEmpty(obj_rut.value)){
		if ((obj_rut.value.indexOf(".") == -1) && (obj_rut.value.indexOf("-") == -1)){
			obj_rut.value = rut;
			obj_dv.value = dv;
			if (esNumeroPos(obj_rut)){
				puntosEnNumero(obj_rut)
				if(!checkRutField(obj_rut,obj_dv))
					return false
				obj_rut.value = obj_rut.value +'-'+obj_dv.value
			}
			else 
				return false
		} else {
			var raya = rut.charAt(rut.length-1);
			rut = rut.substring(0,rut.length-1);
			if (raya == "-"){
				obj_rut.value = sacaPuntos(rut);
				obj_dv.value = dv;
				if (esNumeroPos(obj_rut)){
					puntosEnNumero(obj_rut)
					if(!checkRutField(obj_rut,obj_dv))
						return false
					obj_rut.value = obj_rut.value +'-'+obj_dv.value
				} else {
					alert("El RUT es Incorrecto")
					obj_rut.focus();
					obj_rut.value = '';
					return false;
				}
			} else {
				alert("El RUT es Incorrecto")
				obj_rut.focus();
				obj_rut.value = '';
				return false;
			}
			
		}
	} else
		return false;
	return true;
}

function validaInput(tipo,e){
	var teclaCodigo = 0;
	if (navigator.appName == 'Netscape')	    
		teclaCodigo = e.which
    else
		teclaCodigo = e.keyCode
			
	if (tipo == "rut"){//desde el 0 al 9 mas punto (.)
		if ((teclaCodigo >= 48 && teclaCodigo <= 57)
		|| (teclaCodigo >= 45 && teclaCodigo <= 46)
		|| (teclaCodigo == 75)
		|| (teclaCodigo == 8) //tecla para borrar
		|| (teclaCodigo == 0)
		|| (teclaCodigo == 107)){e.returnValue = true}else return false;

	}
	if (tipo == "dv"){//desde el 0 al 9 mas - y la k y K
		if ((teclaCodigo >= 49 && teclaCodigo <= 57)
		//|| (teclaCodigo == 48)
		|| (teclaCodigo == 75)
		|| (teclaCodigo == 8) //tecla para borrar
		|| (teclaCodigo == 0)
		|| (teclaCodigo == 107)){e.returnValue = true}else return false;
	}
	//return false
}

function isEmpty(s){
	return ((s == null) || (s.length == 0))
}

function esNumeroPos(numero){
	nNumero = new Number(sacaPuntos(numero.value))
	if (isNaN(nNumero)){
		alert("Casilla con Caracter no Valido")
		numero.focus();
		numero.value = "";
		return false;
	}
	if (nNumero < 0){
		alert("Debe ingresar un valor mayor que cero")
		numero.focus();
		numero.value = "";
		return false;
	}
	var numeroLength = numero.value.length;
	for (i = 0; i < numeroLength; i++) {
		var aChar = numero.value.substring(i,i+1);
		if (aChar == " ") return false;
	}
	if ((nNumero == "") && (numeroLength != 0) && (nNumero != 0)){
		alert("No es un numero Valido")
		numero.focus();
		numero.value = "";
		return false;
	}
	return true;
}

function sacaPuntos(numero){
	var sinPtos = numero;
	var nNum = new String(numero)
	if (nNum.indexOf(".") != -1){		
		var sinPtos = '';
		for (i=0;i<nNum.length;i++){
			if (nNum.substr(i,1) != ".")
				sinPtos += nNum.substr(i,1)
		}
	}
	return sinPtos
}

function puntosEnNumero(obj_rut){
	var invertido = "";
	var texto="";
	var tmpstr="";

	texto=obj_rut.value
	largoRut=texto.length
	
	for ( i=0; i < largoRut ; i++ ){
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
		{
			tmpstr = tmpstr + texto.charAt(i);
		}
	}
	texto = tmpstr;
	largoRut=texto.length
	
	for ( i=(largoRut-1),j=0; i>=0; i--,j++ ){
	  invertido = invertido + texto.charAt(i);
	}
	var dtexto = "";
	cnt = 0;

	for (i=0,j=1; i<largoRut; i++,j++){
		if (cnt == 3){
			dtexto = dtexto + '.';
			j++;
			dtexto = dtexto + invertido.charAt(i);
			cnt = 1;
		}
		else{ 
			dtexto = dtexto + invertido.charAt(i);
			cnt++;
		}
	}

	invertido = "";

	for (i=(dtexto.length-1),j=0; i>=0; i--,j++)
		if (dtexto.charAt(i) == "k")
			invertido = invertido + "K";		
		else
			invertido = invertido + dtexto.charAt(i);
	obj_rut.value = Trim(invertido);  
}

function ponerPuntosEnNumero(valor){
	var invertido = "";
	var texto="";
	var tmpstr="";

	texto=valor + "";
	largoRut=texto.length
	
	for ( i=0; i < largoRut ; i++ ){
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
		{
			tmpstr = tmpstr + texto.charAt(i);
		}
	}
	texto = tmpstr;
	largoRut=texto.length
	
	for ( i=(largoRut-1),j=0; i>=0; i--,j++ ){
	  invertido = invertido + texto.charAt(i);
	}
	var dtexto = "";
	cnt = 0;

	for (i=0,j=1; i<largoRut; i++,j++){
		if (cnt == 3){
			dtexto = dtexto + '.';
			j++;
			dtexto = dtexto + invertido.charAt(i);
			cnt = 1;
		}
		else{ 
			dtexto = dtexto + invertido.charAt(i);
			cnt++;
		}
	}

	invertido = "";

	for (i=(dtexto.length-1),j=0; i>=0; i--,j++)
		if (dtexto.charAt(i) == "k")
			invertido = invertido + "K";		
		else
			invertido = invertido + dtexto.charAt(i);
	return (Trim(invertido));  
}

function Trim(strTxt){
	pos1 = 0;
	pos2 = strTxt.length-1;
	for (i=0; i<strTxt.length; i++){
		if (strTxt.charAt(i) == ' ') pos1 = pos1 + 1;
		else break;
	}
	if (pos1 != (pos2+1)){
		for (i=strTxt.length-1; i>0; i--){
			if (strTxt.charAt(i) == ' ') pos2 = pos2 - 1
			else break;
		}
	}
	return strTxt.substring(pos1,pos2+1);
}

function checkRutField(obj_rut,obj_dv){
	//Quitar Ceros
	var auxRut=obj_rut.value;
	var auxLargo=auxRut.length;
	if (auxLargo>1){
		while ((auxRut.substring(0,1)=="0") || (auxRut.substring(0,1)==".")){
			auxRut=auxRut.substring(1,auxLargo);
			auxLargo=auxRut.length
		}
	}
	obj_rut.value=auxRut;
	//Fin Quitar Ceros

	texto = obj_rut.value + obj_dv.value
 	   
	var tmpstr = "";
	if ((obj_rut.value==0)&&(obj_dv.value==0)){
		alert("El RUT no es válido.");
		obj_rut.value="";
		obj_dv.value = "";
		obj_rut.focus();
		return false;
	}	  
	for ( i=0; i < texto.length ; i++ )
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
			tmpstr = tmpstr + texto.charAt(i);
	texto = tmpstr;
	largo = texto.length;
	if (largo < 2){
		alert("Debe ingresar el RUT completo.")
		obj_rut.select();
		obj_dv.value = "";
		obj_rut.focus();
		return false;
	}
	for (i=0; i < largo ; i++ ){ 
		if (texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" ){
			alert("El valor ingresado no corresponde a un RUT válido.");
			obj_dv.value = "";
			obj_dv.focus();
			return false;
		}
	}
	if (obj_dv.value == "k"){
		obj_dv.value="K"		
	}
	if (checkDV(obj_rut,obj_dv))
		return true;
	return false;
}

function checkDV(obj_rut,obj_dv){
	texto = obj_rut.value + obj_dv.value  
	var tmpstr = "";
	for (i=0; i < texto.length ; i++)
		if (texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-')
			tmpstr = tmpstr + texto.charAt(i);
	texto = tmpstr;

	largo = texto.length;
	if (largo < 2){
		alert("Debe ingresar el RUT completo.")
		obj_rut.focus();
		obj_rut.select();
		return false;
	}

	if (largo > 2)
		rut = texto.substring(0, largo - 1);
	else
		rut = texto.charAt(0);
	dv = texto.charAt(largo-1);
	if (!checkCDV(dv)){
		alert("Debe ingresar un dígito verificador válido.");
		obj_dv.focus();
		obj_dv.select();
	}

	if (rut == null || dv == null)
		return 0
	var dvr = '0'

	suma = 0
	mul  = 2
	
	for (i= rut.length -1 ; i >= 0; i--){
		suma = 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.");
		obj_rut.select();
		obj_rut.value = "";
		obj_dv.value = "";
		obj_rut.focus();
		return false;
	}
	return true
}

function checkCDV( dvr ){
	dv = dvr + ""
	if (dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K'){
		return false;
	}
	return true;
}

function MM_findObj(n, d) { //v4.01
  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 && d.getElementById) x=d.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];}
}

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;
}
