
/*******************************************************************/
// Calendar.setup
function calendario(idField, idBoton) {
	var align = "Br";
	if ( arguments[2] )
		align = arguments[2];
	if ( typeof(Calendar)=="function" )
		Calendar.setup( { button : idBoton, inputField : idField, align : align} );
	else
		alert("Calendario no definido");
}

/*******************************************************************/
// Retorna el dígito verificador
function rutDigitoVerificador(rut) {
	var i, suma=0;
	for(i=0; i<rut.length; i++)
		suma+=parseInt(rut.substring(rut.length-i-1,rut.length-i))*(i%6+2);
	switch  (11-suma%11) {
		case 10:
			return "K";
			break;
		case 11:
			return 0;
			break;
		default:
			return 11-suma%11;
	}
}

/*******************************************************************/
// Rut no admitidos en el sistema
function rutPermitido(rut,dig) {
	if ( rut.length<6 || rut.length>9 ) {
		alert("El Rut debe contener entre 6 y 9 Dígitos");
		return false;
	}
	var ruts = new Array(Array(0,0),Array(1,1),Array(2,2),Array(3,3),Array(4,4),Array(5,5),Array(6,6),Array(7,7),Array(8,8),Array(9,9));
	var serie = parseInt(ruts[rut.substr(0,1)][0]);
	var igual = 0;

	for(i=1; i<rut.length; i++) {
		if (ruts[rut.substr(i,1)][0]==serie)
			igual++;
	}
	if (igual==rut.length-1 && ruts[serie][1]==dig) {
		alert("No se permite este tipo de Rut\n" + rut + "-" + dig);
		return false;
	}
	return true;
}

/*******************************************************************/
// Retorna true si el dig equivale al rut
function rutCorrecto(rut,dig) {
	if ( ! rutPermitido(rut,dig) ) {
		return false;
	}
	var estado = (dig.length==1 && dig.toUpperCase()==rutDigitoVerificador(rut))? true : false;
	if ( ! estado )
		alert("Dígito verificador incorrecto");
	return estado;
}

/*******************************************************************/
// Verifica que "ascii" sea uno de los parámetros permitidos en el input
function enArreglo(event) {
	var ascii = event.which;
	if ( typeof(ascii)=="undefined" )
		ascii = event.keyCode;

	permitidos = Array(0, 8, 9); // caracteres ascii permitidos, 0:NULL, 8:BORRAR, 9:TAB
	for(i=0; i<permitidos.length; i++) { // busca en los caracteres permitidos por el sistema
		if (ascii==permitidos[i])
			return true;
	}
	for(i=1; i<arguments.length; i++) { // busca en los caracteres enviados como permitidos
		if(ascii==arguments[i])
			return arguments[i];
	}
	return false;
}

/*******************************************************************/
// Guarda la cantidad de checkbox seleccionados
var codigos = Array();
function seleccion(check) {
	if ( check.checked==true ) { // Si se checkeo el checkbox entonces se crea un nuevo item de array
		codigos.push(check.value);
	}
	else { // Sino, elimina el código y reordena el array
		var aux = codigos;
		codigos = Array();
		for (pos=0; pos<aux.length; pos++)
			if ( check.value!=aux[pos] )
				codigos.push(aux[pos]);
	}
	return;
}

/*******************************************************************/
// Recorre y obtiene los checkbox seleccionados
var codigos = Array();
function selectedChecked(prefijo) {
	codigos = Array();
	for (var pos=0; document.getElementById(prefijo + pos); pos++) {
		if ( document.getElementById(prefijo + pos).checked )
			codigos.push(document.getElementById(prefijo + pos).value);
	}
	return;
}

/*******************************************************************/
// Confirma la eliminación de un registro
function continuar() {
	if ( codigos.length==0 ) {
		alert("Debe seleccionar un registro");
		return false;
	}
	var texto = (codigos.length==1) ? "¿ Confirma eliminación del registro ?" : "¿ Confirma eliminación de los " + codigos.length + " registros ?";
	var seguro = confirm(texto);
	return (!seguro) ? false : true;
}

/*******************************************************************/
// Retorna la cadena en minúscula
function minuscula(str) {
	var valor = str.value;
	document.getElementById(str.name).value = valor.toLowerCase();
}

/*******************************************************************/
// Retorna la cadena en mayúscula
function mayuscula(str) {
	var valor = str.value;
	document.getElementById(str.name).value = valor.toUpperCase();
}

/*******************************************************************/
// Muestra la cantidad de caracteres que quedan libres en un textarea
function cantCaracter(area, div, total) {
	total = parseInt(total);
	var largo = String(document.forms[0].elements[area].value);
	if (largo.length > total) {
		document.forms[0].elements[area].value = largo.substring(0,total);
		alert(" Está pasando el límite de caracteres permitidos ");
		largo = document.forms[0].elements[area].value;
	}
	var suma = new String(total - parseInt(largo.length));
	document.getElementById(div).innerHTML = "Total "+ total + " Caracteres. Quedan " + suma.bold();
}

/*******************************************************************/
// Verifica que el valor ingresado no sea sólo espacios en blanco
function sinEspacios(str) {
	var i,j;
	for(i=0; i<str.length && str.substring(i,i+1)==" "; i++);
	for(j=str.length; j && str.substring(j-1,j)==" "; j--);
	return (i<j)?str.substring(i,j):false;
}

/*******************************************************************/
// Busca espacios en el texto
function buscarEspacios(str) {
	return (str.indexOf(" ")>0) ? false : true;
}

/*******************************************************************/
// Valida texto v2.0
function isText(id) {
	var str = new String();
	if ( ! document.getElementById(id) ) {
		alert("ID = " + id + ' "undefined"');
		return false;
	}
	if ( document.getElementById(id).value=="" ) {
		return false;
	}
	str = sinEspacios(document.getElementById(id).value);
	if ( ! str ) {
		document.getElementById(id).value="";
		return false;
	}
	else if ( str!=document.getElementById(id).value ) {
		document.getElementById(id).value = str;
	}
	return true;
}

/*******************************************************************/
// Valida numero v2.0
function isNumero(id) {
	if ( ! document.getElementById(id) ) {
		alert("ID = " + id + ' "undefined"');
		return false;
	}
	var num = new Number(document.getElementById(id).value);
	return (num==0) ? false : true;
}

/*******************************************************************/
// Permite validar el ingreso de un email válido
function isEmail(obj) {
	var txt = _value(obj);
	var filter = /^[A-Za-z0-9_\.]*@[A-Za-z0-9_]+\.[A-Za-z0-9]+[A-za-z]$/;
	return ( txt.length==0 || filter.test(txt) ) ? true : false;
}

/*******************************************************************/
// Valida el ingreso de usuario de registro
function isValidUser(id) {
	if ( ! document.getElementById(id) ) {
		alert("ID = " + id + ' "undefined"');
		return false;
	}
	if ( !isText(id) ) {
		return returnError(id, "Debe ingresar nombre de Usuario");
	}
	if ( !buscarEspacios(document.getElementById(id).value) ) {
		return returnError(id,"El nombre de Usuario no puede contener Espacios");
	}
	var txt = document.getElementById(id).value;
	var filter = /^[A-Za-z0-9_]*$/;
	if ( !filter.test(txt) ) {
		return returnError(id,"El nombre de Usuario contiene caracteres no válidos");
	}
	return true;
}

/*******************************************************************/
// Valida el ingreso correcto de la password
function isValidPassword(pass1, pass2) {
	var text = _value(pass1);
	if ( text.length < 6 ) {
		return returnError(pass1, "Password debe contener mínimo 6 caracteres");
	}
	if ( _value(pass1)!=_value(pass2) ) {
		return returnError(pass2, "El password ingresado no coincide con el Confirmado, Por Favor Revisar");
	}
	return true;
}

/*******************************************************************/
// Obtiene el valor de un Objeto
function _value(obj, tipo) {
	if ( document.getElementById(obj) ) {
		if ( typeof(tipo)!="undefined" ) {
			if ( tipo==1 )
				return Number(document.getElementById(obj).value);
			else if ( tipo==2 )
				return String(document.getElementById(obj).value);
		}
		return document.getElementById(obj).value;
	}
	return;
}

/*******************************************************************/
// Muestra un mensaje de alerta y pone el cursor en el campo enviado, retorna falso
function returnError(id) {
	if ( arguments[1] ) {
		alert(arguments[1]);
	}
	if ( document.getElementById(id) ) {
		document.getElementById(id).focus();
	}
	return false;
}

/*******************************************************************/
// Envía la pagina actual a la url indicada
function back() {
	if ( window.history.length==0 ) {
		window.close();
	}
	else
		window.history.back();
}

/*******************************************************************/
// Formatea un numero a formato : sin puntos de miles y con punto separador decimal
function formatNumero(num) {
	var valorStr = new String(num);
	valorStr = valorStr.replace(/\./g, "");
	valorStr = valorStr.replace(/,/, ".");
	return Number(valorStr);
}

/*******************************************************************/
// Formatea un número a formato : con "," como separador de decimales
function formatString(numero, decimales) {

	var valor = new Number(numero);
	var decimales = ( typeof(decimales)=="undefined" ) ? 2 : decimales;
	valor = valor.toFixed(decimales);

	valorStr = new String(valor);
	return valorStr.replace(/\./, ",");
}

/*******************************************************************/
// Formatea un número con separadores de miles y decimales 999.999,00
function formatMoneda(valor, objeto) {

	var numero = String(valor);
	var newNumero = "";
	var decimal = "";
	numero = numero.replace(/\./g, "");

	// Separa la parte entera de la decimal
	if ( numero.indexOf(",")!=-1 ) {
		var division = numero.split(",");
		numero = division[0]; // parte modificable
		var decimal = new String(division[1]) // parte decimal
	}
	else
		var decimal = "";

	// Gira el número y le agrega el caracter 'forma'
	var pos = 0;
	var cont = 0;
	for (pos=numero.length-1; pos >= 0; pos--) {
		var num = numero.charAt(pos);
		if ( cont==3 ) {
			newNumero += '.' + num;
			cont = 1;
		}
		else {
			newNumero += num;
			cont ++;
		}
	}

	// Vuelve a girar el número
	var pos = '';
	var numero = '';
	for ( pos=newNumero.length-1; pos>=0; pos-- ) {
		var num = newNumero.charAt(pos);
		numero += num;
	}

	if ( decimal.length>0 ) {
		numero += "," + decimal.substr(0, 2);
	}

	if ( typeof(objeto)=="object" )
		objeto.value = numero;
	else
		return numero;
}

/*******************************************************************/
// Agrega items a un campo select
function agregarItems(desde, hasta) {
	if (document.getElementById(desde) && document.getElementById(hasta)) {
		var obj_des = document.getElementById(desde);
		var obj_has = document.getElementById(hasta);
		var option;
		for(aux=0; aux<obj_des.length; aux++) {
			if (obj_des.options[aux].selected) {
				var existe = false;
				for (pos=0; pos<obj_has.length; pos++) {
					if (obj_has.options[pos].value==obj_des.options[aux].value)
						existe = true;
				}
				if (!existe) {
					option = new Option(obj_des.options[aux].text, obj_des.options[aux].value);
					obj_has.options[obj_has.options.length] = option;
				}
			}
		}
	}
}

/*******************************************************************/
// Quita items a un campo select
function quitarItems(objeto) {
	if (document.getElementById(objeto)) {
		var obj = document.getElementById(objeto);
		var aux = 0;
		while (aux < obj.length) {
			if (obj.options[aux].selected)
				obj.options[aux] = null;
			else
				aux++;
		}
	}
}

/*******************************************************************/
// Crea una Cookie
function SetCookie (name, value) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2 && argv[2]!="") ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = window.location.host;
	var valCookie = name + "=" + escape(value) +
	((expires==null) ? "" : "; expires=" + expires.toGMTString()) +
	((path==null) ? "" : ("; path=" + path)) + "; domain=" + domain;
	document.cookie = valCookie;
}

/*******************************************************************/
// Crea una popup
// @param id : Id de registro a buscar
// @param page : Página de destino
// @param name : Nombre del popup
// @param width : Ancho del popup
// @param height : Alto del popup
// @param top : Margen de altura
// @param left : Margen desde la derecha
function createPopup(id, page, name, width, height, top, left) {
	var width = (typeof(width)!="undefined") ? width:"";
	var height = (typeof(height)!="undefined") ? height:"";
	var top = (typeof(top)!="undefined") ? top:"";
	var left = (typeof(left)!="undefined") ? left:"";
	var name = (typeof(name)!="undefined") ? name : Math.round(Math.random() * id);
	window.open(page+"&popup=1&id="+id, name,"scrollbars=yes,resizable=yes"+windowPosition(width, height, top, left));
}

/*******************************************************************/
// Valida y da formato al Rut ingresado
function RutFormat(obj) {
	var temp = "";

	if ( typeof(obj)=="object" )
		var rut = new String(obj.value);
	else
		var rut = new String(obj);

	// Limpiamos
	for (var i=0; i<rut.length; i++) {
		if ( rut.charAt(i)!=" " && rut.charAt(i)!="." && rut.charAt(i)!="-" )
			temp += rut.charAt(i);
	}

	// Validamos que el rut sea correcto, considerando el último valor como el dígito verificador
	var valor = temp.substring(0, temp.length-1);
	var digito = temp.substring(temp.length-1);

	if ( !rutCorrecto(valor, digito) ) {
		return returnError("", "");
	}

	// Invertimos el valor
	var invertido = "";
	for (i=(temp.length); i>=0; i--)
		invertido += temp.charAt(i);

	// Agregamos el "." cada tres dígitos
	var drut = invertido.charAt(0) + "-";
	cnt = 0;
	for (i=1; i<temp.length; i++) {
		if ( cnt==3 ) {
			drut += "." + invertido.charAt(i);
			cnt = 1;
		}
		else {
			drut += invertido.charAt(i);
			cnt++;
		}
	}

	// Invertimos al sentido original
	invertido = "";
	for ( i=(drut.length-1); i>=0; i-- )
		invertido += drut.charAt(i);

	if ( typeof(obj)=="object" && obj.id )
		document.getElementById(obj.id).value = invertido;
	else
		return invertido;
}