//document.write('<div id="loading" style="display:none" >Espere...</div>');
document.onkeydown = verF5;

// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57
var asignacionFechaInicio = null;
var asignacionLabelMostrarID = null;
var nDia = null; //variable global de dia de la fecha a validar en los textChanged de las fechas
var nMes = null;
var nAno = null;
var fechaAnalizar = null; //fecha ke desde el textChanged de las fecha se pasa al Render para ver si es feriado o weekend

matrizFeriados = new Array (); 
var nav4 = window.Event ? true : false;
var vDateType
var expire = new Date("Feb 12, 2010"); // fecha pasada
var InCookie = document.cookie;
var tBus= GetCookie("tBus",document.cookie); 
var tBusV= GetCookie("tBusV",document.cookie);
var xllave = GetCookie("xllave",document.cookie);

var mydate=new Date();
var year=mydate.getYear();
if (year < 1000)
	year+=1900;

var day=mydate.getDay();
var month=mydate.getMonth()+1;
if (month<10)
	month="0"+month;
var daym=mydate.getDate();
if (daym<10)
	daym="0"+daym;

var FechaHoy = daym+"-"+month+"-"+year;
var Origen="";
var BackColor="";
var TRBackColor="";

function fdecimal(s)
{
	if (s == '') 
		return false
		
	if(s.indexOf('.') < 0 ) 
		return s + '.00'

	if( parseInt(s.length) - parseInt(s.indexOf('.')+1)< 2 )
		return s + '0' 
		
	return s;
}

function delay(millis) 
{
	date = new Date();
	var curDate = null;

	do { var curDate = new Date(); } 
	while(curDate-date < millis);	
} 

function ColorOver(Celda,Clase)
{
   Celda.style.backgroundColor="#FFFFCC";      
   Celda.style.cursor="pointer";
} 


function mOver(obj)
{
    obj.style.background='#D2ffff';  
    obj.style.cursor="pointer";
} 
    
function mOut(obj) // background-color:LightGoldenrodYellow;  
{
    if(obj.className != '') 
        obj.style.background='LightGoldenrodYellow'; 
    else 
        obj.style.background='#FFFFFF';
        
    obj.style.cursor="pointer";
} 

function ColorOut(Celda,clase)
{ 
   Celda.style.backgroundColor="";    
}

function curMano(obj)
{
	obj.style.cursor="pointer";
}

// document.getElementById(idUnder).style.fontWeight = "none"; obj.style.fontWeight = "bold";

function link(obj)
{
	obj.style.cursor = "pointer";
	obj.style.textDecoration  = "underline";
}

function desLink(obj)
{
    obj.style.textDecoration = "none";	
}

function curMover(obj)
{
	obj.style.cursor="move";
}

function curDefault(obj)
{
	obj.style.cursor="'default'";
}

function Cambia(TR)
{
	if (TR.id != Origen)
	{
		if (Origen != "")
		{
			document.getElementById(Origen).style.backgroundColor = BackColor;						
			BackColor = TR.style.backgroundColor;
			Origen = TR.id;			
			TR.style.backgroundColor = 'silver';			
		}
		else
		{
			BackColor = TR.style.backgroundColor;
			Origen = TR.id;		//FFFFCC	CCFFCC
			TR.style.backgroundColor = 'silver';			
		}	
	}		
}

function TituloVentana(tabla) //funcion para menu.htm, se llama en los body onLoads de las paginas popups
{
	if(displayItem('retu')=='')
	{
		top.frames['topFrame'].CambiaTitulo('Tabla '+ tabla);
	}
	else
	{
		document.getElementById('titulo').style.visibility='visible';
		document.getElementById('titulo').style.position='static';
	}
}


function OcultarTR(objetos) //funcion para ocultar tantos TR's suean posibles
{
	//ocultamos los TR's
	for(i=0;i<arguments.length-1;i++)
	{
		if(document.getElementById(arguments[i]).style.display == "none")
			document.getElementById(arguments[i]).style.display="";
		else
			document.getElementById(arguments[i]).style.display = "none";
	}
	//cambiamos la clase al boton (ultimo objeto de la lista de argumentos (objetos) )
 	if(arguments[arguments.length-1].className=="BtnMenos")
		arguments[arguments.length-1].className="BtnMas";
 	else
		arguments[arguments.length-1].className="BtnMenos";
}

function Trim(TRIM_VALUE) //funcion para eliminar espacios tanto de izq como der del valor
{
  
	if(TRIM_VALUE.length < 1)
	{
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE=="")
	{
	return "";
	}
	else
	{
	return TRIM_VALUE;
	}
} //End Function

function RTrim(VALUE) //elimina espacios de la derecha del valor
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
	return"";
	}
	var iTemp = v_length -1;

	while(iTemp > -1){
	if(VALUE.charAt(iTemp) == w_space){
	}
	else{
	strTemp = VALUE.substring(0,iTemp +1);
	break;
	}
	iTemp = iTemp-1;

	} //End While
return strTemp;

} //End Function

function LTrim(VALUE) //elimina espacios de la izquierdadel valor
{
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
	return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";

	var iTemp = 0;

	while(iTemp < v_length){
	if(VALUE.charAt(iTemp) == w_space){
	}
	else{
	strTemp = VALUE.substring(iTemp,v_length);
	break;
	}
	iTemp = iTemp + 1;
	} //End While
	return strTemp;
} //End Function

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.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 Letras(evt) //ingreso exclusivamente de letras sin caracteres especiales :  onKeyPress="return Letras(event);"
{
	var key = nav4 ? evt.which : evt.keyCode;
	return (key == 13 ||  (key >= 65 && key <= 90) || (key >= 97 && key <= 122));
}

function Ruts(evt) //ingreso exclusivamente de Rut (numeros, guion y K k) :  onKeyPress="return Ruts(event);"
{
	var key = nav4 ? evt.which : evt.keyCode;
	return (key <= 13 || key == 45 || key == 75 || key == 107 || (key >= 48 && key <= 57));
}

function Numeros(evt) //ingreso exclusivamente de numeros sin caracteres especiales :  onKeyPress="return Numeros(event);"
{
	var key = nav4 ? evt.which : evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57));
}

function Palabras(evt) //ingreso exclusivamente de letras y espacios sin caracteres especiales:  onKeyPress="return Palabras(event);"
{
	var key = nav4 ? evt.which : evt.keyCode;
	return ( key == 32 || key == 13 ||  (key >= 65 && key <= 90) || (key >= 97 && key <= 122));
}

function GetCookie (name, InCookie) //obtencion de cookie
{ 
		var prop = name + "="; // propiedad buscada
		var plen = prop.length;
		var clen = InCookie.length;
		var i=0;
		if (clen>0) { // Cookie no vacío;
			i = InCookie.indexOf(prop,0); // aparición de la propiedad
			if (i!=-1) { // propiedad encontrada
				// Buscamos el valor correspondiente
				j = InCookie.indexOf(";",i+plen);
				if(j!=-1) // valor encontrado
					return unescape(InCookie.substring(i+plen,j));
				else //el último no lleva ";"
					return unescape(InCookie.substring(i+plen,clen));
			}
			else
				return "";
		}
		else
			return "";
}

function SetCookie (name, value) //modificacion de cookie
{ 
		// número de parámetros variable.
		var argv = SetCookie.arguments;
		var argc = SetCookie.arguments.length;
		// asociación de parámetros a los campos cookie.
		var expires = (argc > 2) ? argv[2] : null;
		var path = (argc > 3) ? argv[3] : null;
		var domain = (argc > 4) ? argv[4] : null;
		var secure = (argc > 5) ? argv[5] : false;
		// asignación de la propiedad tras la codificación URL
		document.cookie = name + "=" + escape(value) +
			((expires==null) ? "" : ("; expires=" + expires.toGMTString())) +
			((path==null) ? "" : (";path=" + path)) +
			((domain==null) ? "" : ("; domain=" + domain)) +
			((secure==true) ? "; secure" : "");
}

function ValidaRut(verirut) //valida rut
{
	texto=verirut;
	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");
		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 R.U.T valido");
			return false;
		}
	}

	var invertido = "";
	for ( i=(largo-1),j=0; i>=0; i--,j++ )
		invertido = invertido + texto.charAt(i);
	var dtexto = "";
	dtexto = dtexto + invertido.charAt(0);
	dtexto = dtexto + '-';
	cnt = 0;

	for ( i=1,j=2; i<largo; i++,j++ )
	{
		//alert("i=[" + i + "] j=[" + 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++ )
		invertido = invertido + dtexto.charAt(i);


	if ( revisarDigito2(texto) )
		return true;

	return false;
}

function revisarDigito( dvr ) //subfunciones de ValidarRut()
{
	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')
	{
		alert("Debe ingresar un digito verificador valido");
		return false;
	}
	return true;
}

function revisarDigito2( crut ) //subfunciones de ValidarRut()
{
	largo = crut.length;
	if ( largo < 2 )
	{
		alert("Debe ingresar el rut completo")
		return false;
	}
	if ( largo > 2 )
		rut = crut.substring(0, largo - 1);
	else
		rut = crut.charAt(0);
	dv = crut.charAt(largo-1);
	revisarDigito( dv );

	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")
		return false
	}

	return true
}

function PageQueryURL(q)  //subfunciones de displayItem()
{
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q)
	{
		for(var i=0; i < this.q.split("&").length; i++)
		{
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s)
	{
		for(var j=0; j < this.keyValuePairs.length; j++)
		{
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function()
	{
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++)
		{
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
	return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}

function queryString(key) //subfunciones de displayItem()
{
	var page = new PageQueryURL(window.location.search);
	return unescape(page.getValue(key));
}

function displayItem(key) //funcion para obtener el valor de un QueryString, false si no
{
	if(queryString(key)=='false')
		return false;
	else
		return queryString(key);
}

function PageQuery(q)
{
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q)
	{
		for(var i=0; i < this.q.split("&").length; i++)
		{
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s)
	{
		for(var j=0; j < this.keyValuePairs.length; j++)
		{
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function()
	{
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++)
		{
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
	return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}

function SelectAll(Campo,nivel) //funcion para seleccionar todo el texto de un TextBox
						  //se puede pasar el mismo objeto (this) o una ID de otro TextBox:
						  //	onClick="SelectAll(this);" 	onClick="SelectAll('txtNumCli');", subieno o no de nivel
{    
	if(Campo=='[object]')
		Campo.select();
	else	
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(Campo).select();
		if(nivel==1)
			window.parent.document.getElementById(Campo).select();
		if(nivel==2)
			window.parent.parent.document.getElementById(Campo).select();	
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(Campo).select();
	}	
		
}

function PoneGuion(obj) //funcion para los TextBox de Rut's ... le añade un guion antes del ultimo caracter, se puede pasar el mismo objeto (this) o una ID de otro TextBox
{
	var valor="";

	if(obj=='[object]')
		valor=Trim(obj.value);
	else
		valor=document.getElementById(obj).value;

	if( (valor.indexOf('-')!=-1) || (Trim(valor)=="") )
		return false;

	var Izq = valor.substring(0,valor.length-1);
	var Der = valor.substring(valor.length-1);
	var Final = Trim(Izq) + "-" + Trim(Der);

	if(obj=='[object]')
		obj.value=Final;
	else
		document.getElementById(obj).value=Final;


}

function Link(Url,Destino) //link a una pagina, indicando el frame
{
	if((Destino==null)||(Destino=="undefined"))
		Destino="";

	if(Destino.toUpperCase()=="UP")
		top.frames['topFrame'].location.href = Url;
	if(Destino.toUpperCase()=="LEFT")
		top.frames['leftFrame'].location.href = Url;
	if(Destino.toUpperCase()=="MIDDLE")
		top.frames['middleFrame'].location.href = Url;
	if(Destino.toUpperCase()=="MAIN" || Trim(Destino.toUpperCase())=="")
		top.frames['mainFrame'].location.href = Url;		
}

function setFocus(evt,Destino,nivel) //funcion para pasar el focus a un campo: "setFocus(event,'txtPas');" al presionar enter en un objeto
{	
	var key = window.event.keyCode ? window.event.keyCode : window.event.which ? window.event.which : window.event.charCode;
	
	if(key==13)
	{
		if(Destino=='[object]')
		{			
		    try{SelectAll(Destino,nivel)}catch(e){}
			Destino.focus();
			return false;
		}
		else
		{
			if((nivel==null)||(nivel=="undefined"))
				document.getElementById(Destino).focus();
			if(nivel==1)
				window.parent.document.getElementById(Destino).focus();
			if(nivel==2)
				window.parent.parent.document.getElementById(Destino).focus();
			if(nivel==3)
				window.parent.parent.parent.document.getElementById(Destino).focus();
				
		    try{SelectAll(Destino,nivel)}catch(e){}
			return false;
		}	
	}
}

function setFoco(Destino,nivel) //funcion para pasar el focus a un campo: "setFoco(event,'txtPas');" desde cualquier parte del setframe
{	
	if(Destino=='[object]')
	{	
		Destino.focus();	
	}
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(Destino).focus();	
		if(nivel==1)
			window.parent.document.getElementById(Destino).focus();
		if(nivel==2)
			window.parent.parent.document.getElementById(Destino).focus();
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(Destino).focus();
	}		
}


function Vacio(objeto,nivel) //verifica el contenido de un campo,  se puede pasar el mismo objeto (this) o una ID de otro TextBox
{
	var Valor="";
	if(objeto=='[object]')
		Valor=objeto.value;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			Valor=document.getElementById(objeto).value;
		if(nivel==1)
			Valor=window.parent.document.getElementById(objeto).value;
		if(nivel==2)
			Valor=window.parent.parent.document.getElementById(objeto).value;	
		if(nivel==3)
			Valor=window.parent.parent.parent.document.getElementById(objeto).value;
	}	
	
	if(Trim(Valor)!="")
		return false;
	else
		return true;
}

 

function setSelIndexCombo(combo,valor, nivel) //estavlece el indice a seleccionar
{   
    if(combo=='[object]')
		combo.selectedIndex = valor;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(combo).selectedIndex = valor;
		if(nivel==1)
			window.parent.document.getElementById(combo).selectedIndex = valor;
		if(nivel==2)
			window.parent.parent.document.getElementById(combo).selectedIndex = valor;
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(combo).selectedIndex = valor;	
	}		
}

function CombOK(combo,nivel) //verifica ke el valor seleccionado del combo no sea el primero en caso de "seleccione..", se puede pasar el mismo objeto (this) o una ID de otro TextBox
{
	var Valor="";
	if(combo=='[object]')
		Valor=combo.selectedIndex;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			Valor=document.getElementById(combo).selectedIndex;
		if(nivel==1)
			Valor=window.parent.document.getElementById(combo).selectedIndex;
		if(nivel==2)
			Valor=window.parent.parent.document.getElementById(combo).selectedIndex;	
		if(nivel==3)
			Valor=window.parent.parent.parent.document.getElementById(combo).selectedIndex;		
	}		
	
	if((Valor==0) || (Valor==-1))
		return false;
	else
		return true;
}

function isChecked(checkbox,nivel) //verifica si un checkbox esta seleccionado, se puede pasar el mismo objeto (this) o una ID de otro TextBox, subiendo niveles o no 
{
	var Valor="";
	if(checkbox=='[object]')
		Valor=checkbox.checked;
	else		
	{
		if((nivel==null)||(nivel=="undefined"))
			Valor=document.getElementById(checkbox).checked;
		if(nivel==1)
			Valor=window.parent.document.getElementById(checkbox).checked;
		if(nivel==2)
			Valor=window.parent.parent.document.getElementById(checkbox).checked;		
		if(nivel==3)
			Valor=window.parent.parent.parent.document.getElementById(checkbox).checked;		
	}		

	if (isTrue(Valor))
		return true;
	else
		return false;
}

function Disable(obj,nivel) //deshabilita  objeto, se puede pasar el mismo objeto (this) o una ID de otro TextBox, subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.disabled=true;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).disabled=true;
		if(nivel==1)
			window.parent.document.getElementById(obj).disabled=true;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).disabled=true;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).disabled=true;			
	}	
}

function Enable(obj,nivel) //habilita  objeto, se puede pasar el mismo objeto (this) o una ID de otro TextBox, subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.disabled=false;
	else		
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).disabled=false;
		if(nivel==1)
			window.parent.document.getElementById(obj).disabled=false;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).disabled=false;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).disabled=false;			
	}	
}

function reLoad(iframe,url) //recarga un iframe con url dada, si no se especifica se recarga solamente el iframe con la url ke tenia
{
	// tambien sirve asi:	
	//document.frmBusqueda.location.href = 'www.asd.asd';
	
	if ( url == null || url == "undefined")
		url = document.getElementById(iframe).src;			
	
	document.getElementById(iframe).src=url;
	document.getElementById(iframe).load;	
}

function setValue(obj,valor,nivel) // establece un valor a un objeto , subiendo niveles o no (document.parents)
{	
    if (valor == null)
        valor = '';
	if(obj=='[object]')
		obj.value=valor;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).value=valor;
		if(nivel==1)
			window.parent.document.getElementById(obj).value=valor;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).value=valor;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).value=valor;				
	}	
}

function getValue(obj,nivel) // obtiene  el valor de un  objeto , subiendo niveles o no (document.parents)
{	
	var valor ="";
	if(obj=='[object]')
		valor=obj.value;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			valor=document.getElementById(obj).value;
		if(nivel==1)
			valor=window.parent.document.getElementById(obj).value;
		if(nivel==2)
			valor=window.parent.parent.document.getElementById(obj).value;			
		if(nivel==3)
			valor=window.parent.parent.parent.document.getElementById(obj).value;			
	}
	
	if(obj=='[object]' && obj.type=="checkbox")
    {
        if (isChecked(obj))
            return "true";
        else
            return "false";	
    }
	else if (obj!='[object]')
	{	
	    if(document.getElementById(obj).type=="checkbox")
	    {
	        if (isChecked(obj))
	            return "true";
	        else
	            return "false";	   
	    }
	}

	return Trim(valor);
}

function getTextCombo(obj,nivel) //obtiene el TEXTO de la seleccion de un combo,  subiendo niveles o no (document.parents)
{
	var valor ="";
	    
	if(obj=='[object]')		
		valor=obj[obj.selectedIndex].innerHTML;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			valor=document.getElementById(obj)[document.getElementById(obj).selectedIndex].innerHTML;
		if(nivel==1)
			valor=window.parent.document.getElementById(obj)[window.parent.document.getElementById(obj).selectedIndex].innerHTML;
		if(nivel==2)
			valor=window.parent.parent.document.getElementById(obj)[window.parent.parent.document.getElementById(obj).selectedIndex].innerHTML;	
		if(nivel==3)
			valor=window.parent.parent.parent.document.getElementById(obj)[window.parent.parent.document.getElementById(obj).selectedIndex].innerHTML;		
	}	

	return Trim(valor);
}


function setTextCombo(valor,obj,nivel) //setea el TEXTO de la seleccion de un combo,  subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')		
		obj[obj.selectedIndex].innerText = valor;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj)[document.getElementById(obj).selectedIndex].innerText = valor;
		if(nivel==1)
			window.parent.document.getElementById(obj)[window.parent.document.getElementById(obj).selectedIndex].innerText = valor;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj)[window.parent.parent.document.getElementById(obj).selectedIndex].innerText = valor;
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj)[window.parent.parent.document.getElementById(obj).selectedIndex].innerText = valor;		
	}	
}

function Limpiar(objetos) //limpia objetos, se recibe frases 'textboxs' 'combos' 'checkboxs' , o por c/u ej: 'txtRut','cmbDir','chkPer' , o sin parametros para todos
{	
   	var AllInputs="";
		
	if((objetos==null)||(objetos=="undefined"))	
	{
		Limpiar('combos');
		Limpiar('textboxs');
		Limpiar('checkboxs');		
		Limpiar('passwords');
		return false;
	}
	
	if(arguments.length==1)
	{	
		AllInputs = document.getElementsByTagName('textarea');
		for(x=0; x<AllInputs.length; x++)
		{			
			AllInputs[x].innerText="";	
		}	
	
		if(objetos=='combos')	
			AllInputs = document.getElementsByTagName('select');		
		else if (objetos=='textboxs')	
			AllInputs = document.getElementsByTagName('input');
        else if (objetos=='passwords')	
			AllInputs = document.getElementsByTagName('password');
			
		if( (objetos!='combos') && (objetos!='textboxs') && (objetos!='checkboxs') )
			AllInputs="";
					
		for(x=0; x<AllInputs.length; x++)
		{			
			if( (objetos=='textboxs') && (AllInputs[x].type=='text'))
				AllInputs[x].value="";	
			if( (objetos=='checkboxs') && (AllInputs[x].type=='checkbox'))
				AllInputs[x].checked=false;
			if( (objetos=='combos') && (AllInputs[x].type=='select-one'))							
				AllInputs[x].selectedIndex = AllInputs[x].length;							
		}	

		if(arguments.length==1)
			return false;
	}

	for(i=0;i<arguments.length;i++)
	{		
		if((document.getElementById(arguments[i]).type)=="text")
			document.getElementById(arguments[i]).value="";
		if((document.getElementById(arguments[i]).type)=="select-one")
			document.getElementById(arguments[i]).selectedIndex=0;
		if((document.getElementById(arguments[i]).type)=="checkbox")
			document.getElementById(arguments[i]).checked=false;
	}
}

function Frame(Destino,obj) //referencia a un frame  o un objeto del frame determinado
{	
	if((obj==null)||(obj=="undefined"))
	{
		if(Destino.toUpperCase()=="UP")	
			return top.frames['topFrame'];	
		if(Destino.toUpperCase()=="LEFT")	
			return top.frames['leftFrame'];	
		if(Destino.toUpperCase()=="MAIN" || Trim(Destino.toUpperCase())=="")	
			return top.frames['mainFrame'];
		if(Destino.toUpperCase()=="MIDDLE")
			return top.frames['middleFrame'];		
	}	
	else
	{
		if(Destino.toUpperCase()=="UP")	
			return top.frames['topFrame'].document.getElementById(obj);	
		if(Destino.toUpperCase()=="LEFT")	
			return top.frames['leftFrame'].document.getElementById(obj);	
		if(Destino.toUpperCase()=="MIDDLE")	
			return top.frames['middleFrame'].document.getElementById(obj);
		if(Destino.toUpperCase()=="MAIN" || Trim(Destino.toUpperCase())=="")
		{
			if(top.frames['mainFrame']!=null)
				return top.frames['mainFrame'].document.getElementById(obj);
			else
				return document.getElementById(obj);
		}
	}	
}

function Espera(ocultar) //muestra el gif de esperar, si viene con parametros lo oculta
{	
	if((ocultar==null)||(ocultar=="undefined"))
		Frame('up','Procesando').style.visibility="visible"; //Frame('up').document.getElementById('Procesando').style.visibility="visible";
	else
		Frame('up','Procesando').style.visibility="hidden"; //Frame('up').document.getElementById('Procesando').style.visibility="hidden";
}

function Mostrar(obj,nivel) //muestra una division,  subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.style.visibility="visible";
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).style.visibility="visible";
		if(nivel==1)
			window.parent.document.getElementById(obj).style.visibility="visible";
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).style.visibility="visible";			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).style.visibility="visible";			
	}	
}

function Ocultar(obj,nivel) //oculta una division,  subiendo niveles o no (document.parents)
{		
	if(obj=='[object]')
		obj.style.visibility="hidden";
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).style.visibility="hidden";
		if(nivel==1)
			window.parent.document.getElementById(obj).style.visibility="hidden";
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).style.visibility="hidden";			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).style.visibility="hidden";			
	}	
}

function inCombo(obj,valor,nivel)  //busca un valor en los values de un combo,  subiendo niveles o no (document.parents)
{	
	var i=0;
	
	if(obj!='[object]')				
	{
		if((nivel==null)||(nivel=="undefined"))
			obj=document.getElementById(obj);
		if(nivel==1)
			obj=window.parent.document.getElementById(obj);
		if(nivel==2)
			obj=window.parent.parent.document.getElementById(obj);	
		if(nivel==3)
			obj=window.parent.parent.parent.document.getElementById(obj);	
		
	}
	
	for(i=0; i < obj.length; i++)
	{				
		if(Trim(valor)==Trim(obj[i].value))		
			i=obj.length + 1;					
	}
	
	if(i==obj.length)
		return false
	else	
		return true;
}


function delCombo(obj,valor,nivel)  //elimina un valor de un combo (value)
{	
	var i=0;
	
	if(obj!='[object]')				
	{
		if((nivel==null)||(nivel=="undefined"))
			obj=document.getElementById(obj);
		if(nivel==1)
			obj=window.parent.document.getElementById(obj);
		if(nivel==2)
			obj=window.parent.parent.document.getElementById(obj);	
		if(nivel==3)
			obj=window.parent.parent.parent.document.getElementById(obj);	
		
	}
	
	
	var pos = null;
	for(i=0; i < obj.length; i++)
	{				
		if(valor == Trim(obj[i].value))		
		{
			pos = i;	
			break;		
		}    	    
	}
	
	if (pos != null)
	    obj.options[pos] = null;	
}


function setClass(obj,clase,nivel) // establece la class CS a un objeto , subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.className = clase;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).className = clase;
		if(nivel==1)
			window.parent.document.getElementById(obj).className = clase;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).className = clase;		
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).className = clase;				
	}	
}

function setPos(obj,posicion,nivel) //establece la posicion de la division (static o absolite)
{	
	if(obj=='[object]')
		obj.style.position=posicion;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).style.position=posicion;
		if(nivel==1)
			window.parent.document.getElementById(obj).style.position=posicion;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).style.position=posicion;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).style.position=posicion;			
	}	
}

function Hide(obj,nivel) //oculta un Objeto ,  subiendo niveles o no (document.parents)
{	
    try
    {
	    if(obj=='[object]')
		    obj.style.display="none";
	    else
	    {
		    if((nivel==null)||(nivel=="undefined"))
			    document.getElementById(obj).style.display="none";
		    if(nivel==1)
			    window.parent.document.getElementById(obj).style.display="none";
		    if(nivel==2)
			    window.parent.parent.document.getElementById(obj).style.display="none";			
		    if(nivel==3)
			    window.parent.parent.parent.document.getElementById(obj).style.display="none";			
	    }	
	}
	catch(e)
	{}
}

function Show(obj,nivel) //Muestra un Objeto ,  subiendo niveles o no (document.parents)
{	
    try
    {
	    if(obj=='[object]')
		    obj.style.display="";
	    else
	    {
		    if((nivel==null)||(nivel=="undefined"))
			    document.getElementById(obj).style.display="";
		    if(nivel==1)
			    window.parent.document.getElementById(obj).style.display="";
		    if(nivel==2)
			    window.parent.parent.document.getElementById(obj).style.display="";			
		    if(nivel==3)
			    window.parent.parent.parent.document.getElementById(obj).style.display="";			
	    }	
	}
	catch(e)
	{}
}

function Atras()
{
	javaScript:window.history.back();
}

function showLoad()
{
	Mostrar(Frame('up','Procesando'));
}

function hideLoad()
{	
	Ocultar(Frame('up','Procesando'));
}

function setTrd(obj,valor,nivel) // establece el valor a mostrar de un TR o un TD , subiendo niveles o no (document.parents)
{		
	if(obj=='[object]')
		obj.innerHTML = valor;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).innerHTML = valor;
		if(nivel==1)
			window.parent.document.getElementById(obj).innerHTML = valor;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).innerHTML = valor;		
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).innerHTML = valor;				
	}
}

function setLogo(obj, valor, nivel) // establece el valor a mostrar de un TR o un TD , subiendo niveles o no (document.parents)
{
    var img;
    if (obj == '[object]')
        img = obj;
    else {
        if ((nivel == null) || (nivel == "undefined"))
            img = document.getElementById(obj);
        if (nivel == 1)
            img = window.parent.document.getElementById(obj);
        if (nivel == 2)
            img = window.parent.parent.document.getElementById(obj);
        if (nivel == 3)
            img = window.parent.parent.parent.document.getElementById(obj);
    }
    img.src = valor;
}

function Alt(Frase)
{
	//onMouseOver="Alt('Atachar Documentos');"  onMouseOut="Ocultar('Info');"
	document.getElementById('Info').innerText=" " + Frase + "  ";			
	document.getElementById('Info').style.top=tempY;
	document.getElementById('Info').style.left=tempX+16;
	document.getElementById('Info').style.visibility="visible";
	
	tempY=0;
	tempX=0;
}

function setTrTxt(Objetos) //Muestra los datos de una TR dentro de un iframe en los objetos que se indicen parametros ('trDestino','objDestino1','objDestino2'.... )
{
	var Tr = arguments[0];
	var Celdas = Tr.getElementsByTagName('td');	
	var k = 1;
	
	for(i=0;i<Celdas.length;i++)
	{			
		if(arguments[k]!="")			
			window.parent.document.getElementById(arguments[k]).value=Celdas[i].innerHTML;
			
		k++;
	}
}

function TFCheck(obj,valor)
{
    if (valor == "true" || valor == "TRUE" || valor == "True" || valor == true || valor == 1 || valor == "1")
        Check(obj);
    else
        desCheck(obj);
}

function Check(obj,nivel) // Establece el Check a un ChekBox, subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.checked=true;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).checked=true;
		if(nivel==1)
			window.parent.document.getElementById(obj).checked=true;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).checked=true;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).checked=true;				
	}	
}

function desCheck(obj,nivel) // Quita el Check a un ChekBox, subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.checked=false;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).checked=false;
		if(nivel==1)
			window.parent.document.getElementById(obj).checked=false;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).checked=false;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).checked=false;				
	}	
}

function getCheckRadio(obj,nivel) // Retorna el radio seleccionado del grupo de radios que se indique, subiendo niveles o no (document.parents)
{	
	var Radios = new Array();
	var NombreRadio = "";	
	
	if(obj!='[object]')				
		NombreRadio = obj.toUpperCase();					
	else	
		NombreRadio = obj.name.toUpperCase();
	
	if((nivel==null)||(nivel=="undefined"))
		obj=document.getElementsByTagName('input');
	if(nivel==1)
		obj=window.parent.document.getElementsByTagName('input');
	if(nivel==2)
		obj=window.parent.parent.getElementsByTagName('input');		
	if(nivel==3)
		obj=window.parent.parent.parent.getElementsByTagName('input');		
	
	var k = 0;
	for(i=0;i<obj.length;i++)
	{		
		if( (obj[i].type=="radio") && (obj[i].name.toUpperCase()==NombreRadio) && (obj[i].checked) )	
		{
			return obj[i].id;
		}									
	}
	
	if(i==obj.length)
		return "";
	
	/*for(i=0;i<Radios.length;i++)
	{	
		if( (Radios[i].name==NombreRadio) && (Radios[i].checked) )	
		{				
			return Radios[i].value ;
		}	
	}*/
}


function EliminarTr(idTabla,idTr,nivel) //Elimina una TR de la tabla indicada, especificacndo Tabla, idTR, subiendo niveles o no (document.parents)
{
	if((nivel==null)||(nivel=="undefined"))	
		Tabla=document.getElementById(idTabla);		
	
	if(nivel==1)	
		Tabla=window.parent.document.getElementById(idTabla);		
	
	if(nivel==2)	
		Tabla=window.parent.parent.document.getElementById(idTabla);
	
	if(nivel==3)	
		Tabla=window.parent.parent.parent.document.getElementById(idTabla);
	
	AllTrs=Tabla.getElementsByTagName('tr');	
	CSS1 = AllTrs[1].className;
	CSS2 = AllTrs[2].className;

	for (var i=1; i < AllTrs.length; i++) 
	{					
		if(AllTrs[i].id==idTr)
			Tabla.deleteRow(i);		
	}
	
	for (var i=1; i < AllTrs.length; i++) 
	{		
		if((i%2)==0)	
			AllTrs[i].className=CSS2;	
		else	
			AllTrs[i].className=CSS1;
	}	
}


function setTr(Objetos) //Inserta datos a una TR, el 1º argumento debe ser el 'document.frmUsuarios' donde frmUsuarios es el Iframe ke contiene la tabla afectada con id Tablax
{	
	Tabla = arguments[0].document.getElementById('Tablax');
	
	var AllTrs = Tabla.getElementsByTagName('tr');
	CSS1 = AllTrs[1].className;
	CSS2 = AllTrs[2].className;
	
	var AllTds = AllTrs[0].getElementsByTagName('td');
	
	//AllTrs[2].cells[0].innerText="asdasd";
	//Tabla.rows[1].cells[0].innerText="dato";

	Tabla.insertRow();

	for(i=0; i<AllTds.length; i++)
	{
		Tabla.rows[AllTrs.length-1].insertCell();
		Tabla.rows[AllTrs.length-1].cells[i].innerText=arguments[i+1];
	}
	
	for (var i=1; i < AllTrs.length; i++) 
	{		
		if((i%2)==0)	
			AllTrs[i].className=CSS2;	
		else	
			AllTrs[i].className=CSS1;
	}		
}


function setTrCells(Objetos) //Inserta datos a una TR, el 1º argumento debe ser el 'document.frmUsuarios' donde frmUsuarios es el Iframe ke contiene la tabla afectada con id Tablax
{	
	var TR = document.getElementById(arguments[0]);	
	var AllTds = TR.getElementsByTagName('td');

	for(i = 0; i < AllTds.length; i++)
	{		
		TR.cells[i].innerText = arguments[i + 1];
	}	
}


function addCombo(obj,texto,valor,nivel) // establece un nuevo valor a un combo , subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.options=[obj.length] = new Option(texto,valor);
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).options[document.getElementById(obj).length] = new Option(texto,valor);
		if(nivel==1)
			window.parent.document.getElementById(obj).options[window.parent.document.getElementById(obj).length] = new Option(texto,valor);
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).options[window.parent.parent.document.getElementById(obj).length] = new Option(texto,valor);	
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).options[window.parent.parent.parent.document.getElementById(obj).length] = new Option(texto,valor);				
	}	
}

function getIframeVal(obj) //Obitiene el objeto indicado del iframe frmBusqueda
{	
	iFrame=document.frmBusqueda.document;
	return(iFrame.getElementById(obj).value);	
}
	
	/*
function Buscar(iframe,url,objcomp) //recarga un iframe con url dada, si no se especifica se recarga solamente el iframe con la url ke tenia
{
	// tambien sirve asi:	
	//document.frmBusqueda.location.href = 'www.asd.asd';
	
	document.getElementById(iframe).src=url;
	document.getElementById(iframe).load;	
}*/

function WriteOnlyIframes(form) //Deja ReadOnly=true los objetos en los ifrmes, para los niveles el iframe hijo debe tener el mismo nombre que el iframe padre
{
			
		AllInputs =  form.getElementsByTagName("input");			
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{			
			if (AllInputs[i].type=="text")
				AllInputs[i].readOnly = false;
			if (AllInputs[i].type=="checkbox")
				AllInputs[i].disabled = false;
			if (AllInputs[i].type=="radio")						
				AllInputs[i].disabled = false;
			if (AllInputs[i].type=="select-one")						
				AllInputs[i].disabled = false;
		}
		
	
		AllInputs =  form.getElementsByTagName("textarea");		

		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{			
			AllInputs[i].readOnly = false;
		}	
		
		AllInputs =  form.getElementsByTagName("select");		
	
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{					
			AllInputs[i].disabled = false;
		}	
}

function ReadOnly(obj,nivel) //Deja ReadOnly=true un objeto, con su nivel o, sin parametros para TODOS los objetos
{
	if((obj==null)||(obj=="undefined"))
	{
		AllInputs = document.getElementsByTagName("input");		
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{			
			if (AllInputs[i].type=="text")
				AllInputs[i].readOnly = true;
			if (AllInputs[i].type=="checkbox")
				AllInputs[i].disabled = true;
			if (AllInputs[i].type=="radio")						
				AllInputs[i].disabled = true;
			if (AllInputs[i].type=="select-one")						
				AllInputs[i].disabled = true;
		}
		
		AllInputs = document.getElementsByTagName("textarea");		
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{			
			AllInputs[i].readOnly = true;
		}		
		
		AllInputs = document.getElementsByTagName("select");		
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{					
			AllInputs[i].disabled = true;
		}	
	
	}
	else
	{
		if(obj=='[object]')
			obj.readOnly = true;	
		else
		{
			if((nivel==null)||(nivel=="undefined"))
				document.getElementById(obj).readOnly = true;	
			if(nivel==1)
				window.parent.document.getElementById(obj).readOnly=true;
			if(nivel==2)
				window.parent.parent.document.getElementById(obj).readOnly=true;
			if(nivel==3)
				window.parent.parent.parent.document.getElementById(obj).readOnly=true;
		}	
	}	
}

function WriteOnly(obj,nivel) //Deja ReadOnly=false un objeto, con su nivel o, sin parametros para TODOS los objetos
{		
	if((obj==null)||(obj=="undefined"))
	{
		AllInputs = document.getElementsByTagName("input");		
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{		 
			if (AllInputs[i].type=="text")
			{			
				AllInputs[i].readOnly = false;	
				AllInputs[i].disabled = false;					
			}
			if (AllInputs[i].type=="checkbox")						
				AllInputs[i].disabled = false;
			if (AllInputs[i].type=="radio")						
				AllInputs[i].disabled = false;						
			if (AllInputs[i].type=="select-one")						
				AllInputs[i].disabled = false;
		}		
		
		AllInputs = document.getElementsByTagName("textarea");	
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{			
			AllInputs[i].readOnly = false;
		}
		
		AllInputs = document.getElementsByTagName("select");		
		var k=0
		for (var i=0; i<AllInputs.length; i++) 
		{			
			AllInputs[i].disabled = false;
		}	
	}
	else
	{
		if(obj=='[object]')
			obj.readOnly = false;	
		else
		{
			if((nivel==null)||(nivel=="undefined"))
				document.getElementById(obj).readOnly = false;	
			if(nivel==1)
				window.parent.document.getElementById(obj).readOnly=false;
			if(nivel==2)
				window.parent.parent.document.getElementById(obj).readOnly=false;
			if(nivel==3)
				window.parent.parent.parent.document.getElementById(obj).readOnly=false;
		}	
	}
		
}

function isMain(Pagina) //obtiene y compara el nombre de la pagina cargada en el mainframe. solo el nombre ej: host/inicio.aspx?val=23&rut?35 devuelve 'inicio'
{
	var Url = (Frame('main').document.location.href);	
	
	posicion = Url.indexOf('?')-1;
	cadena = Url.substring(0,posicion)
	Slash = cadena.lastIndexOf('/')+1;
	Actual = cadena.substring(Slash)
	Punto = Actual.indexOf('.');

	if (Pagina.toUpperCase()==Actual.substring(0,Punto).toUpperCase())
		return true;
	else	
		return false;
}


function getMain(Pagina) //obtiene y  el nombre de la pagina cargada en el mainframe. solo el nombre ej: host/inicio.aspx?val=23&rut?35 devuelve 'inicio'
{
	var Url = "";
	if(Frame('main')!=null)	
		Url = Frame('main').document.location.href;
	else
		Url = document.location.href;
		
	Slash = Url.lastIndexOf('/')+1;
	Actual = Url.substring(Slash)
	
	Interroga = Actual.indexOf('?');	
	if(Interroga!=-1)
		Actual = Actual.substring(0,Interroga);	
	
	return Actual;
}

function isOrigen(Pagina) //obtiene y compara el nombre de la pagina de la que se llamo, solo el nombre ej: host/inicio.aspx?val=23&rut?35 devuelve 'inicio'
{
	var Url = document.referrer;
	Slash = Url.lastIndexOf('/')+1;
	Actual = Url.substring(Slash)
	Punto = Actual.indexOf('.');
	
	if (Pagina.toUpperCase()==Actual.substring(0,Punto).toUpperCase())
		return true;
	else	
		return false;
	//return Actual.substring(0,Punto).toUpperCase();

}

function handleEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	} 
	else
	return true;
}  

function setArea(obj,valor,nivel) // establece un valor a un textArea , subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.innerText=valor;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).innerText=valor;
		if(nivel==1)
			window.parent.document.getElementById(obj).innerText=valor;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).innerText=valor;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).innerText=valor;				
	}	
}

function getUrl(frmDestino) //obtiene y el nombre de la pagina indicada como frmDestino
{
	var Url = (Frame(frmDestino).document.location.href);	
	Slash = Url.lastIndexOf('/')+1;
	Actual = Url.substring(Slash)	
	return Actual;
	
}

function getTR(obj,nivel) // obtiene  el valor de un tr , subiendo niveles o no (document.parents)
{	
	var valor ="";
	if(obj=='[object]')
		valor=obj.innerText;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			valor=document.getElementById(obj).innerText;
		if(nivel==1)
			valor=window.parent.document.getElementById(obj).innerText;
		if(nivel==2)
			valor=window.parent.parent.document.getElementById(obj).innerText;			
		if(nivel==3)
			valor=window.parent.parent.parent.document.getElementById(obj).innerText;			
	}
	
	return Trim(valor);
}

function getTextInCombo(obj,valor,nivel)  //devuelve el Texto del option del combo en el cual se coincida con el valor buscado,  subiendo niveles o no (document.parents)
{	
	if(obj!='[object]')
	{
		if((nivel==null)||(nivel=="undefined"))
			obj=document.getElementById(obj);
		if(nivel==1)
			obj=window.parent.document.getElementById(obj);
		if(nivel==2)
			obj=window.parent.parent.document.getElementById(obj);			
		if(nivel==3)
			obj=window.parent.parent.parent.document.getElementById(obj);			
	}
	
	var Texto=0;
	var Antes = getValue(obj);
	if(inCombo(obj,valor))
	{
		setValue(obj,valor);
		Texto = getTextCombo(obj);
		setValue(obj,Antes);
	}
	else
		Texto = "No Encontrado";
	return Texto;	
}

function setInnerCombo(obj,valor,nivel)  //compara valor con los InnerText del combo y selecciona el encontrado,  subiendo niveles o no (document.parents)
{	
	if(obj!='[object]')
	{
		if((nivel==null)||(nivel=="undefined"))
			obj=document.getElementById(obj);
		if(nivel==1)
			obj=window.parent.document.getElementById(obj);
		if(nivel==2)
			obj=window.parent.parent.document.getElementById(obj);			
		if(nivel==3)
			obj=window.parent.parent.parent.document.getElementById(obj);			
	}
	
	for(var i=0;i<obj.length;i++)
	{			
		/*if(Trim(valor).toUpperCase()==Trim(getTextInCombo(obj,obj[i].value)).toUpperCase())
			setValue(obj,obj[i].value);*/
		if(Trim(valor).toUpperCase()==Trim(obj[i].innerText.toUpperCase()))
		{
			obj.selectedIndex=i;
			i=obj.length+1;
		}
	}	
}

function esDigito(sChr){
var sCod = sChr.charCodeAt(0);
return ((sCod > 47) && (sCod < 58));
}

function valSep(oTxt){
var bOk = false;
bOk = bOk || ((oTxt.value.charAt(2) == "-") && (oTxt.value.charAt(5) == "-"));
bOk = bOk || ((oTxt.value.charAt(2) == "/") && (oTxt.value.charAt(5) == "/"));
return bOk;
}

function finMes(oTxt)
{
    var nMes = parseInt(oTxt.value.substr(3, 2), 10);
    var nRes = 0;
    switch (nMes)
    {
        case 1: nRes = 31; break;
        case 2: nRes = 29; break;
        case 3: nRes = 31; break;
        case 4: nRes = 30; break;
        case 5: nRes = 31; break;
        case 6: nRes = 30; break;
        case 7: nRes = 31; break;
        case 8: nRes = 31; break;
        case 9: nRes = 30; break;
        case 10: nRes = 31; break;
        case 11: nRes = 30; break;
        case 12: nRes = 31; break;
    }
    return nRes;
}

function valDia(oTxt){
var bOk = false;
nDia = parseInt(oTxt.value.substr(0, 2), 10);
bOk = bOk || ((nDia >= 1) && (nDia <= finMes(oTxt)));
return bOk;
}

function valMes(oTxt){
var bOk = false;
nMes = parseInt(oTxt.value.substr(3, 2), 10);
bOk = bOk || ((nMes >= 1) && (nMes <= 12));
return bOk;
}

function valAno(oTxt)
{
    var bOk = true;
    nAno = oTxt.value.substr(6);
    bOk = bOk && ((nAno.length == 2) || (nAno.length == 4));
    
    if (bOk)
    {
        for (var i = 0; i < nAno.length; i++)   
        {    
            bOk = bOk && esDigito(nAno.charAt(i));    
        }    
    }
    
    var aa = nAno;
    aa = parseInt(aa);
    
    if (nAno.length == 2)
    {
        for (var i = 0; i < nAno.length; i++)
        {
            if (nAno.charAt(i) == '0')
            {
                nAno = nAno.charAt(i+1);
                break;
            }
        }
    }
        
    switch (parseInt(nAno))
    {
        case 1:
            nAno = '2001';
            break;
        case 2:
            nAno = '2002';
            break;
        case 3:
            nAno = '2003';
            break;
        case 4:
            nAno = '2004';
            break;
        case 5:
            nAno = '2005';
            break;
        case 6:
            nAno = '2006';
            break;
        case 7:
            nAno = '2007';
            break;
        case 8:
            nAno = '2008';
            break;
        case 9:
            nAno = '2009';
            break;
        case 0:
            nAno = '2000';
            break; 
        default:
            break;
    }
    
    return bOk;
}

function valFecha(oTxt){
var bOk = true;
if (oTxt.value != ""){
bOk = bOk && (valAno(oTxt));
bOk = bOk && (valMes(oTxt));
bOk = bOk && (valDia(oTxt));
bOk = bOk && (valSep(oTxt));
if (!bOk)
{
//alert("Fecha incorrecta.");
//oTxt.select();
//oTxt.focus();
return false;
}
else
    return true;
}
}


function validarFecha(oTxt)
{
    var bOk = true;   
    bOk = bOk && (valAno(oTxt));
    bOk = bOk && (valMes(oTxt));
    bOk = bOk && (valDia(oTxt));
    bOk = bOk && (valSep(oTxt));
    return bOk    
}

function setTrTxtSelf(Objetos) //Muestra los datos de una TR dentro de un iframe en los objetos que se indicen parametros ('trDestino','objDestino1','objDestino2'.... )
{	
	var Tr = arguments[0];
	var Celdas = Tr.getElementsByTagName('td');	
	var k = 1;
	
	for(i=0;i<Celdas.length;i++)
	{			
		//alert(Celdas[i].innerText + " a " + arguments[k]);
		if(arguments[k]!="")			
			document.getElementById(arguments[k]).value=Celdas[i].innerText;
			
		k++;
	}
}

var RutDir="";
var NomDir="";

function clonaCombo(objOrig,objdest)
{	
	window.parent.document.getElementById(objdest).length = objOrig.length;
	window.parent.document.getElementById(objdest).options[0] = new Option('','');			
	for (var j=0; j < objOrig.length; j++)
	{ 
		window.parent.document.getElementById(objdest).options[j+1] = new Option(objOrig.options[j].text,objOrig.options[j].value);
		if(objdest.toUpperCase() == "CMBPLAN") 
		{
			window.parent.document.getElementById(objdest).options[j+1].setAttribute('cargo',objOrig.options[j].cargo);
		}	
	}
	
	window.parent.document.getElementById(objdest).disabled = false;
	
	if(window.parent.document.getElementById('txtDir')!=null)  //textbox del director
	{
		setValue('txtDir',RutDir + " " + NomDir,'1');			
	}
	
	if(displayItem('ValorOrigen')) //si viene un valor para poner en el cmbDestino despues del llenado, lo asignamos
		setValue(window.parent.document.getElementById(objdest),displayItem('ValorOrigen'));
		
	
}

function isEnable(obj,nivel) //deshabilita  objeto, se puede pasar el mismo objeto (this) o una ID de otro TextBox, subiendo niveles o no (document.parents)
{
	if(obj!='[object]')		
	{
		if((nivel==null)||(nivel=="undefined"))
			obj = document.getElementById(obj);
		if(nivel==1)
			obj = window.parent.document.getElementById(obj);
		if(nivel==2)
			obj = window.parent.parent.document.getElementById(obj);			
		if(nivel==3)
			obj = window.parent.parent.parent.document.getElementById(obj);			
	}		
	
	if(obj.disabled)
		return false;
	else
		return true;
}

function limpiarLista(obj)
{   
    lista = document.getElementById(obj);
    if(lista.options)
    {
        for (m = lista.options.length; m > -1 ; m--)
            lista.options[m]=null
    }
}


function limpiarCombo(obj)
{   
    combo = document.getElementById(obj);
    if(combo.options)
    {
        for (m = combo.options.length-1; m >= 0 ; m--)
            combo.options[m]=null;
    }
}



function changeBG(obj,color,nivel) // cambia el color del fondo del objeto, subiendo o no de nivels
{	   
	var valor ="";
	if(obj == '[object]')
		valor=obj.style.backgroundColor=color;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			valor=document.getElementById(obj).style.backgroundColor=color;
		if(nivel==1)
			valor=window.parent.document.getElementById(obj).style.backgroundColor=color;
		if(nivel==2)
			valor=window.parent.parent.document.getElementById(obj).style.backgroundColor=color;	
		if(nivel==3)
			valor=window.parent.parent.parent.document.getElementById(obj).style.backgroundColor=color;		
	}	
}

function construirFeridados(anioValidar)
{
    matrizFeriados[0] = new Array('01-01-' + anioValidar,'New Year');
    matrizFeriados[1] = new Array('01-05-' + anioValidar,'Dia del Trabajador');
    matrizFeriados[2] = new Array('21-05-' + anioValidar,'Glorias Navales');
    matrizFeriados[3] = new Array('15-08-' + anioValidar,'Asuncion la Virgen Maria');
    matrizFeriados[4] = new Array('18-09-' + anioValidar,'Fiestas Patrias');
    matrizFeriados[5] = new Array('19-09-' + anioValidar,'Dia del Ejercito');
    matrizFeriados[6] = new Array('12-10-' + anioValidar,'Dia de la Raza');
    matrizFeriados[7] = new Array('01-11-' + anioValidar,'Todos los Santos');
    matrizFeriados[8] = new Array('08-12-' + anioValidar,'Inmaculada Concepcion');
    matrizFeriados[9] = new Array('25-12-' + anioValidar,'Navidad');
}

function dtFechaIngreso_CalendarRenderDay(oCalendar, dday, oEvent)
{
    if (dday.year != null)
        construirFeridados(dday.year);
     else
        construirFeridados(dday.getFullYear());

	if (dday.month < 10 && dday.day < 10) //mes 1 y dia 1 
	    dday.fecha = "0" + dday.day + "-0" + dday.month + "-" + dday.year;
	    
	if (dday.month < 10 && dday.day > 9) //mes 1 y dia 2
	    dday.fecha = dday.day + "-0" + dday.month + "-" + dday.year;
		
	if (dday.month > 9 && dday.day < 10)  //mes 2 y dia 1 
        dday.fecha = "0" + dday.day + "-" + dday.month + "-" + dday.year;
    
    dday.isFeriado = false;
    dday.glosaFeriado = "";
    var fecha = new Date(dday.year, dday.month - 1, dday.day); 
     
    if (fecha == null || fecha == 'NaN')
    {
        fecha = new Date(dday.getFullYear(), dday.getMonth(), dday.getDate());
        var x = dday.getMonth();
        x =dday.getMonth() + 1;
        x =dday.getDate();
        x =dday.getFullYear();
        
        if (dday.getMonth() < 10 && dday.getDate() < 10) //mes 1 y dia 1 
            dday.fecha = "0" + dday.getDate() + "-0" + (dday.getMonth() + 1) + "-" + dday.getFullYear();

        if (dday.getMonth() < 10 && dday.getDate() > 9) //mes 1 y dia 2
            dday.fecha = dday.getDate() + "-0" + (dday.getMonth() + 1) + "-" + dday.getFullYear();

        if (dday.getMonth() > 9 && dday.getDate() < 10)  //mes 2 y dia 1 
            dday.fecha = "0" + dday.getDate() + "-" + (dday.getMonth() + 1) + "-" + dday.getFullYear();

        if (dday.getMonth() > 9 && dday.getDate() > 9)  //mes 2 y dia  2
            dday.fecha = dday.getDate() + "-" + (dday.getMonth() + 1) + "-" + dday.getFullYear();
    }
          
    dday.diaSemanaNumero = fecha.getDay();
        
    switch (dday.diaSemanaNumero) 
    {
        case 0:
           dday.diaSemanaGlosa = 'Domingo';
           break;
        case 1:
           dday.diaSemanaGlosa = 'Lunes';
           break;
        case 2:
           dday.diaSemanaGlosa = 'Martes';
           break;
        case 3:
            dday.diaSemanaGlosa = 'Miercoles';
            break;
        case 4:
            dday.diaSemanaGlosa = 'Jueves';
            break;
        case 5:
            dday.diaSemanaGlosa = 'Viernes';
            break;
        case 6:
            dday.diaSemanaGlosa = 'Sabado';
            break;
        default:
            break;
    } 
    
	for(i in matrizFeriados)
	{	
	    if(dday.fecha == matrizFeriados[i][0])
	    {
	        dday.css = 'Feriado';
	        dday.isFeriado = true;
	        dday.glosaFeriado = matrizFeriados[i][1];
	    }
	}
	fechaAnalizar = dday;
}

function dtFechaIngreso_TextChanged(oDropDown, newText, oEvent)
{
    if (!validarFecha(oDropDown.inputBox))
        return false;
  
    dtFechaIngreso_CalendarRenderDay(null, newText, null);
        
    if (fechaAnalizar.isFeriado || fechaAnalizar.diaSemanaNumero == 0 || fechaAnalizar.diaSemanaNumero == 6 )
    {
        if (fechaAnalizar.isFeriado)
            alert('No puede escojer un feriado. (' + fechaAnalizar.glosaFeriado + '.)');
        else 
            alert('No puede escojer un dia de fin de semana.');
            
        oDropDown.inputBox.value = "";
        setValue(asignacionLabelMostrarID,"");
        return false;
    }		
}
 
function setIndex(obj,valor,nivel) // establece un indice a un objeto , subiendo niveles o no (document.parents)
{	
	if(obj=='[object]')
		obj.value=valor;
	else
	{
		if((nivel==null)||(nivel=="undefined"))
			document.getElementById(obj).selectedIndex=valor;
		if(nivel==1)
			window.parent.document.getElementById(obj).selectedIndex=valor;
		if(nivel==2)
			window.parent.parent.document.getElementById(obj).selectedIndex=valor;			
		if(nivel==3)
			window.parent.parent.parent.document.getElementById(obj).selectedIndex=valor;				
	}	
}

function isTrue(valor)
{
    if (valor == "true" || valor == "TRUE" || valor == "True" || valor == true)
        return true;
    else
        return false;
}


function changeText(chk)
{    
    var test = "";
    var a = getValue('hidCanRec');    
    for(i = 0; i <= a -1 ; i++)
    {
        var e = document.getElementById('chk' + i);
        if(e.checked)        
            test += "|" + e.name;
    }
    
    if (test != "")
        cbo1.text = "Varios";
    else
      cbo1.text = "";
    
}

function verMostrarResponsables(nombre)
{
    var tupla = document.getElementById(nombre);
    if (tupla.style.display=="none")
        Show(tupla)
    else
        Hide(tupla);
}

function creaFechaJS(fecha)
{
    if (fecha == "")
        return "";
    
    fecha = fecha.replace("/","-");
    fecha = fecha.replace("/","-");
    var tags = fecha.split('-');
    var dia = tags[0];
    var mes = tags[1];
    var ano = tags[2];

    return new Date(ano, mes - 1, dia); 
}


function creaFechaChilena(fecha)
{
    var nueva = '';
    if (fecha == null)
        return nueva;
        
     if ( (fecha.getMonth() + 1) < 10 && fecha.getDate() < 10) //mes 1 y dia 1 
        nueva = "0" + fecha.getDate() + "-0" + (fecha.getMonth() + 1) + "-" + fecha.getFullYear();

    if ( (fecha.getMonth() + 1) < 10 && fecha.getDate() > 9) //mes 1 y dia 2
        nueva = fecha.getDate() + "-0" + (fecha.getMonth() + 1) + "-" + fecha.getFullYear();

    if ( (fecha.getMonth() + 1) > 9 && fecha.getDate() < 10)  //mes 2 y dia 1 
        nueva = "0" + fecha.getDate() + "-" + (fecha.getMonth() + 1) + "-" + fecha.getFullYear();

    if ( (fecha.getMonth() + 1) > 9 && fecha.getDate() > 9)  //mes 2 y dia  2
        nueva = fecha.getDate() + "-" + (fecha.getMonth() + 1) + "-" + fecha.getFullYear();

    if (nueva == "01-01-1901")
        nueva = "";
    return nueva;
}

function verF5(elEvento)
{
    var a = document.location.href;
    var evento = elEvento || window.event;
    var caracter = evento.charCode || evento.keyCode;
    
    if (caracter == 116) //pulsando F5
    {
        if (window.parent.cerrar)
            window.parent.cerrar = 0
		else
			cerrar = 0;
    }
    else   
    { 
        if (window.parent.cerrar)
            window.parent.cerrar = 1;
		else
			cerrar = 1;
    }
}    


function customTR()
{
    try
    {
        var x = 0;
        var ide = "treMenun";
        var click;
        for(x=1; x < 100; x++)
        {
            ide = "treMenun" + x;
            if (document.getElementById(ide))
            {
                if (!document.getElementById(ide).onclick)
                    document.getElementById(ide).onclick = function (){Cambia(this)}
                else
                    document.getElementById(ide).onclick = null;
            }
            else
                return;
        }
     }
     catch(e)
     {}
}



