function obtenerElemento(id)
{
	var elemento;

	if(document.all) // IE5 
		elemento = document.all[id];

	if(document.getElementById) // IE6+, Mozila, Opera
		elemento = document.getElementById(id);

	return elemento;

}

function obtenerTexto(elemento)  
{

	if (elemento == null) return false;

	if (elemento.textContent != undefined)
		return elemento.textContent;

	if (elemento.text != undefined)
		return elemento.text;

	if (elemento.innerText != undefined)
		return elemento.innerText;

	return elemento.value;
}

function escribirTexto(elemento,texto)  
{

	if (elemento == null) return false;

	if (elemento.innerText != undefined) 
	{
		elemento.innerText=texto;
		return true;
	}
	elemento.textContent=texto;
	return true;

}

function validarFecha(dtStr)	
{
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;

	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	var strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	var xmonth=parseInt(strMonth);
	var xday=parseInt(strDay);
	var xyear=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : dd/mm/yyyy");
		return false;
	}
	if (strMonth.length<1 || xmonth<1 || xmonth>12){
		//alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || xday<1 || xday>31 || (xmonth==2 && xday>daysInFebruary(xyear)) || xday > daysInMonth[xmonth]){
		//alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || xyear==0 || xyear<minYear || xyear>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date");
		return false;
	}
	return true;
}

function validarEmail(email)
{
    var re = /^[A-Za-z][A-Za-z0-9_\.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/
    return re.test(email);
}

function validarHora(value)
{
        var re = /^(0[1-9]|1\d|2[0-3]):([0-5]\d)$/
        return re.test(value);
}

function isInteger(value)
{
	var re = /^\-?[0-9]+$/
	return re.test(value);
}

function stripCharsInBag(s, bag){

    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (var i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year)
{
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}

function trim(str)
{
  return( (""+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}

function isNumeric(strString) //  check for valid numeric strings	
{
	var strValidChars = "0123456789.-";
	var blnResult = true;

	if (strString.length == 0) return false;
	//  test strString consists of valid characters listed above
	for (var i = 0; i < strString.length && blnResult == true; i++)
		if (strValidChars.indexOf(strString.charAt(i)) == -1)
			blnResult = false;
	return blnResult;
}

function deshabilitarFila(cual)
{
	var fila = cual.parentNode.parentNode;
	for (var a=0;a<fila.cells.length;a++)
	{
		for (var b=0;b<fila.cells[a].childNodes.length;b++)
		{
			if (fila.cells[a].childNodes[b].type!="checkbox")
				continue;
			if (fila.cells[a].childNodes[b]==cual)
				continue;

			if (!cual.checked)
			{
				fila.cells[a].childNodes[b].disabled=true;
				fila.cells[a].childNodes[b].checked=false;
			}
			else
			{
				fila.cells[a].childNodes[b].disabled=false;
			}
		}
	}
	
}

function URLEncode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}


function validarFormulario(formulario,numericos,optativos)
{
	//formulario = formulario.form;
	
	for (var a=0;a<formulario.elements.length;a++)
	{
		if (optativos)
		{
			var salir=false;
			
			for (b=0; b<optativos.length; b++)
			{
				if (optativos[b]==formulario.elements[a].id)
				{
                                        if (formulario.elements[a].value=="") salir=true;
					break;
				}
			}
			if (salir)
				continue;
		}

		if (formulario.elements[a].id) 
		{
			if (formulario.elements[a].value=="")
			{
				if (formulario.elements[a].type=="text")
				{
					formulario.elements[a].className="erroneo";
					formulario.elements[a].focus();
					alert("Campo no debe estar vacio");
					return false;
				}
				if (formulario.elements[a].type=="select-one")
				{
					formulario.elements[a].className="erroneo";
					formulario.elements[a].focus();
					alert("Seleccione para continuar");
					return false;
				}
			}
			if (formulario.elements[a].id=="email")
			{
				if (!validarEmail(formulario.elements[a].value))
				{
					formulario.elements[a].className="erroneo";
					formulario.elements[a].focus();
					alert("Campo debe ser un email");
					return false;
				}
			}
			if (formulario.elements[a].id.substring(formulario.elements[a].id.length-5,formulario.elements[a].id.length)=="fecha")
			{
				if (!validarFecha(formulario.elements[a].value))
				{
					formulario.elements[a].className="erroneo";
					formulario.elements[a].focus();
					alert("Campo debe ser una fecha");
					return false;
				}
			}
			if (formulario.elements[a].id.substring(formulario.elements[a].name.length-4,formulario.elements[a].id.length)=="hora")
			{
				if (!validarHora(formulario.elements[a].value))
				{
					formulario.elements[a].className="erroneo";
					formulario.elements[a].focus();
					alert("Campo debe ser una hora");
					return false;
				}
			}
		}	
		if (numericos)
		{
			for (var b=0; b<numericos.length; b++)
			{
				if (numericos[b]==formulario.elements[a].id)
				{
					if (!isNumeric(formulario.elements[a].value))
					{
						formulario.elements[a].className="erroneo";
						formulario.elements[a].focus();
						alert("Campo " + formulario.elements[a].id + " debe ser numerico");
						return false;
					}
				}
			}
		}
		if (formulario.elements[a].type)
			if (formulario.elements[a].type=="text" || formulario.elements[a].type=="select-one")
				formulario.elements[a].className="normal";

	}
	return true;
}



function validaRut(campo)
{ 
	texto = campo.value;
	/// EXPRESIONES REGULARES
	var reg_rut=/[0-9]{7,8}\-[k|K|0-9]/;
	// si no pasa el test entonces no es un rut valido
      
	 if (texto == "679-K")  {return true}

	if(!reg_rut.test(texto)) {
		alert('Rut en formato invalido, debe contener a lo menos 7 numeros, un guion y el digito verificador, ej: 12345678-9');
		campo.focus();
		campo.className="erroneo";
		return false;
	}
	// Separamos el rut del digito verificador
	var array_rut=texto.split("-");
	var rut=array_rut[0];
	var dv=array_rut[1];
	// si es K minuscula la agrandamos
	if(dv == 'k') dv = 'K';	

	// calculamos y si son iguales esta todo bien
	if (dv!=calcularDigito(rut)) {
		alert('Digito Incorrecto');
		campo.focus();
		campo.className="erroneo";
		return false;
	}
	campo.className="normal";
	return true;
}

function calcularDigito(rut)
{
      
	var largo=rut.length;
	var mult=2;
	var suma=0;
	largo--;
	while(largo>=0)
	{
		suma=suma+(rut.charAt(largo)*mult);
		if(mult>6)
			mult=2;
		else
			mult++;
		largo--;

	}

	var resto = suma%11;
	var digito = 11-resto
	if(digito==10)
		digito="K";
	else
		if(digito==11)
			digito=0;

	return digito;
}

function actualizarRut(cual) 
{
	escribirTexto(obtenerElemento(cual + '_rut'),calcularDigito(obtenerElemento(cual).value));
}

function mostrarOcultar(este,cual)
{
	if (este.checked)
		obtenerElemento(cual).className="mostrar";
	else
		obtenerElemento(cual).className="nomostrar";
}

function mostrarOcultar2(cual)
{
	if (obtenerElemento(cual).style.display=="block")
		obtenerElemento(cual).style.display="none";
	else
		obtenerElemento(cual).style.display="block";
}

function enviarActualizandoOculto(formulario,campo,conque)
{
	obtenerElemento(campo).value=conque;
	obtenerElemento(formulario).submit();
}


function fillSelectFromArray(selectCtrl, itemArray, selectednado, goodPrompt, badPrompt, defaultItem) { 
	var i, j, g; 
	var prompt; // empty existing items 
	for (i = selectCtrl.options.length; i >= 0; i--) { 
		selectCtrl.options[i] = null; 
	} 
	prompt = (itemArray != null) ? goodPrompt : badPrompt; 
	if (prompt == null) { 
		j = 0; 
	} else { 
		selectCtrl.options[0] = new Option(prompt); 
		j = 1; 
	} 
	g = 0;
	if (itemArray != null) { // add new items 
		for (i = 0; i < itemArray.length; i++) { 
			//alert(selectednado+" "+itemArray[i][0]);
			if (selectednado==itemArray[i][0]) {
				selectCtrl.options[j] = new Option(itemArray[i][2]); 
				if (itemArray[i][1] != null) { 
					selectCtrl.options[j].value = itemArray[i][1]; 
					g++;
				} 
				j++;
			}
		} // select first item (prompt) for sub list 
	} 
	
/*	selectCtrl.options[j] = new Option("Todas"); 
	selectCtrl.options[j].value = "-1"; 
	/*if (g != 0) {
		selectCtrl.disabled = false;
	} else {
		selectCtrl.disabled = true;
	}*/
	selectCtrl.selectedIndex=g;
}

		function changeIn(campo) {
			campo.value = campo.value.toUpperCase();
		}
	
		function NoMostrar(tabla) {
			if (document.getElementById(tabla).style.display!='table') {
				document.getElementById(tabla).style.display='table';
				document.images['i'+tabla].src='/imagenes/minus_.gif';
			} else {
				document.getElementById(tabla).style.display='none';
				document.images['i'+tabla].src='/imagenes/plus_.gif';
			}
		}

		function onKeyPress () {
		
		  	var keycode;
		  	if (window.event) keycode = window.event.keyCode;
		  	else return true;
		
		 	if (keycode == 13){
			    validaFrm(document.frm);
			    return false;
			}
		
			return true;
		}

		function Trim(TRIM_VALUE){
			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){
			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){
			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 cambiarHojaEstilos (idh,estilo) {
		if (document.getElementById && document.getElementById(idh) != null)
		node = document.getElementById(idh).className=estilo;
		else if (document.layers && document.layers[idh] != null)
		document.layers[idh].className=estilo;
		else if (document.all)
		document.all[idh].className=estilo;
	}

function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if (isNaN(key)) return true;
	
	keychar = String.fromCharCode(key);
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
	
	return isFirstN || isFirstD || reg.test(keychar);
}

function onlyDigits(e,decReq) {
		var isIE = document.all?true:false;
		var isNS = document.layers?true:false;
		var key = (isIE) ? window.event.keyCode : e.which;
		var obj = (isIE) ? event.srcElement : e.target;
		var isNum = (key > 47 && key < 58) ? true:false;
		var dotOK = (key==46 && decReq=='decOK' && (obj.value.indexOf(".")<0 || obj.value.length==0)) ? true:false;
		if(key < 32)  return true;
		return (isNum || dotOK);
}

function extractNumber(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = temp;
}

		function f_digvercnt(cVar) {
			var nVar1=0;
			var nVar2=0;
			var i=0;
			var j=0;
			var z=0;
			
			var cVar1=cVar.toUpperCase();
			var cRet="?";
			
			cVar2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			cVar3 = "1012131415161718192021232425262728293031323435363738";
			
			for(i=1; i<=4; i++) {
				for(j=1; j<=26; j++) {
					if (cVar1.substring(i-1,i)==cVar2.substring(j-1,j)) {	
						nVar1=nVar1+(parseInt(cVar3.substring((j*2)-2,(j*2)))*Math.pow(2,i-1));
						break;
					}
				}
			}
			
			for(i=5; i<=10; i++) {
				nVar1=nVar1+(parseInt(cVar1.substring(i-1,i))*Math.pow(2,i-1));
			}
			
			nVar2 = nVar1%11;
			if (nVar2==10) {
			   nVar2=0;
			}
			
			return nVar2;
		}



function changeToVisible(obj)
{
obj = document.getElementById(obj);

obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible';

if (document.body.scrollHeight && navigator.appVersion.indexOf("Win") != -1)
{

document.getElementById('popUp').style.height = document.body.scrollHeight;

}
else if (document.documentElement.scrollHeight)
{

document.getElementById('popUp').style.height = document.documentElement.scrollHeight;

}
else if (document.documentElement.offsetHeight)
{

document.getElementById('popUp').style.height = document.documentElement.offsetHeight;

}

}


function setPosition(obj)
{
x = 0;

y = 0;

obj = document.getElementById(obj);

if (document.documentElement)
{
posLeft = document.documentElement.scrollLeft;

posTop = (document.all)?document.body.scrollTop:window.pageYOffset;

}
else if (document.body)
{

theLeft = document.body.scrollLeft;

theTop = (document.all)?document.body.scrollTop:window.pageYOffset;

}

posLeft += x;

posTop += y;

obj.style.left = posLeft + 'px' ;

obj.style.top = posTop + 'px' ;

setTimeout("setPosition('layer1')",1);

}



function scrollPopUp()
{

setTimeout("setPosition('layer1')",1);

}

function revisarError(){

	if (obtenerTexto(obtenerElemento("mensajeError"))=="") return true;

	var div = document.createElement("div");
	div.id = "popUp";
	document.getElementById("todo").appendChild(div);
	
	var div = document.createElement("div");
	div.id = "layer1";
	document.getElementById("todo").appendChild(div);

	var div = document.createElement("div");
	div.id = "middle";
	document.getElementById("layer1").appendChild(div);

	var div = document.createElement("h3");
	escribirTexto(div,"Mensaje");
	document.getElementById("middle").appendChild(div);

	var p = document.createElement("p");
	document.getElementById("middle").appendChild(p);
	var erro = obtenerElemento("mensajeError");
	var node = p.appendChild(erro);


	var boton = document.createElement("div");
	boton.className = "botones";
	p.appendChild(boton);


	var div = document.createElement("a");
	div.className = "optionsTopic";
	div.style.paddingRight="5px";
	div.style.lineHeight="12pt";
	div.href="javascript:changeToVisible('layer1'); changeToVisible('popUp');"
	escribirTexto(div,"Continuar");
	boton.appendChild(div);
	
	setTimeout('changeToVisible(\'popUp\');changeToVisible(\'layer1\')',300);
	
	//escribirTexto(obtenerElemento("mensajeError"),"");
}
