
document.write("<scr"+"ipt language='JavaScript' src='js/ajax.js'><\/scr"+"ipt>");

/*******************************************************************/
// 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;
}

/*******************************************************************/
// Obtiene el valor de un Objeto v1.5
function Value(obj, tipo) {
	if ( document.getElementById(obj) ) {
		if ( typeof(tipo)!="undefined" ) {
			if ( tipo=="number" )
				return Number(document.getElementById(obj).value);
			else if ( tipo=="string" )
				return String(document.getElementById(obj).value);
		}
		return document.getElementById(obj).value;
	}
	return;
}

/*******************************************************************/
// 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 número v2.1
function isNumero(id) {
	if ( !document.getElementById(id) ) {
		alert("ID = " + id + ' "undefined"');
		return false;
	}
	var num = new Number(document.getElementById(id).value);
	return (num==0 || isNaN(num)) ? false : true;
}

/*******************************************************************/
// Permite validar el ingreso correcto de un email v1.5
function isEmail(obj) {
	var txt = Value(obj);
	var filter = /^\w+(\.)*@\w+\.\w{2,3}$/;
	return ( txt.length==0 || filter.test(txt) ) ? true : false;
}

/*******************************************************************/
// Formato de número v2.0
// dec: Separador de decimales
function NumberFormat(valor, dec) {

	try {
		valor = String(valor).replace(/\s/g,"");
		if ( typeof(dec)=="undefined" )
			dec = ",";
		var numero = new RegExp(/^\d+(\.\d+)*$/);
		var moneda = new RegExp(/^[\d\.]+(\,\d+)*$/);

		// Si es formato moneda
		if ( dec=="," && moneda.test(valor) ) {
			valor = valor.replace(/\./g, "");
			valor = valor.replace(/,/, ".");
		}
		// Verifica finalmente si es un número válido
		if ( !numero.test(valor) )
			valor = (Boolean(0));

		return valor;
	}
	catch (e) {
		return (Boolean(0));
	}
}

/*******************************************************************/
// Formatea un número a formato : con "," como separador de decimales
function CommaSeparated(valor) {
	return String(valor).replace(/\./, ",");
}

/*******************************************************************/
// Devuelve el valor en formato moneda v2.0.1
function MoneyFormat(valor, dec) {

	var input = "";
	var decimales = "";
	if ( typeof(valor)=="object" ) {
		input = valor;
		valor = valor.value;
	}
	if ( typeof(dec)=="undefined" )
		dec = 2;

	var numero = NumberFormat(valor);
	if ( typeof(numero)=="boolean" ) {
		alert("Formato de número incorrecto");
		return;
	}

	numero = String(numero);
	if ( numero.indexOf(".")!=-1 ) {
		numero = Number(numero).toFixed(dec);
		var div = String(numero).split(".");
		numero = String(div[0]);
		if ( div[1] )
			decimales = String(div[1]);
	}

	// Agrega el "."
	var aux = 0;
	var nuevo = "";
	for (var pos=numero.length-1; pos >= 0; pos--) {
		var num = numero.charAt(pos);
		if ( aux==3 ) {
			nuevo = num + "." + nuevo;
			aux = 1;
		}
		else {
			nuevo = num + nuevo;
			aux++;
		}
	}
	// Agrega los decimales
	numero = nuevo;
	if ( decimales.length )
		numero += "," + decimales;

	// Retorna el valor
	if ( typeof(input)=="object" )
		input.value = numero;
	else
		return numero;
}

/*******************************************************************/
// 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;
}

/*******************************************************************/
// 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;
}

/*******************************************************************/
// 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;
}

/*******************************************************************/
// Muestra la ficha de la Propiedad
function VerPropiedad(id) {
	window.location= "ficha_propiedad.php?id="+id;
}

/*******************************************************************/
// Ejecuta mouseover de Imagenes
function RollOverImagen(obj, evento) {
	var imagen = obj.src;
	if ( imagen.lastIndexOf("/")!=-1 ) {
		imagen = imagen.substr(imagen.lastIndexOf("/")+1);
	}
	if ( imagen.indexOf("block")==-1 ) {
		if ( evento==1 ) {
			obj.style.cursor = "pointer";
			obj.src = ( obj.id=="atras" ) ? "images/atras_over.gif" : "images/adelante_over.gif";
		}
		else
			obj.src = ( obj.id=="atras" ) ? "images/atras.gif" : "images/adelante.gif";
	}
}

/*******************************************************************/
// Muestra las otras Fotos de la Propiedad
function ViewImg(pos) {
	key = key + pos;
	if ( key >= total ){
		key = total-1;
		return;
	}
	if ( key < 0 ){
		key = 0;
		return;
	}
	document.getElementById("adelante").src = ( key==total-1 ) ? "images/adelante_block.gif" : "images/adelante.gif";
	document.getElementById("atras").src = ( key==0 ) ? "images/atras_block.gif" : "images/atras.gif";

	document.getElementById("imagen").src = "fotos.php?id="+fotos[key]+"&width=280&height=210";
	document.getElementById("nombre").innerHTML = nombres[key];
	return;
}

/*******************************************************************/
function PopupFoto() {
	var path = document.getElementById("imagen").src;
	if ( path.indexOf(".gif")==-1 ) {
		path = path.substring(0, path.indexOf("&"));
		id = path.substring(path.indexOf("=")+1);
	//	window.open("ver_fotos.php?action=frame&id="+id+"&foto="+path, "popup"+id, "scrollbars=1,resizable=1,width=770,height=580,top=20,left=20");
		window.open("ver_fotos.php?action=frame&id="+id+"&foto="+path, "popup"+id, "scrollbars=1,resizable=1,width=770,height=580,top=20,left=20");
	}
}

/*******************************************************************/
/* Calcula los valores de UF o % según se modifique alguno de ellos */
// 1 = UF
// 0 = %
function UF_Porcentaje(posicion) {
	var valorTotal = Value("total");
	if ( posicion==1 ) {
		var valorUF = NumberFormat( Value("uf") );
		if ( valorUF > 1 ) {
			var porcentaje = (valorUF * 100) / valorTotal;
			document.getElementById("porcen").value = MoneyFormat( this.CommaSeparated(porcentaje) );
			return;
		}
	}
	else {
		var valorPorc = NumberFormat( Value("porcen") );
		if ( valorPorc > 1 ) {
			var UF = (valorPorc * valorTotal) / 100;
			document.getElementById("uf").value = MoneyFormat( this.CommaSeparated(UF) );
			return;
		}
	}
	return;
}

/*******************************************************************/
// Calculo del Dividendo
function Calcular() {

	try {
		var meses = 12;
		var valorUF = Value("valor_uf");
		var valorTotal = Value("total");
		var monto = NumberFormat(Value("uf"));
		var tasa = NumberFormat(Value("tasa"));
		var totalMeses = parseInt(document.getElementById("anos").options[document.getElementById("anos").selectedIndex].value) * meses;
		var dividendo, totalMeses;

		if ( tasa > 1.0 )
			tasa = tasa / 100.0;

		tasa = Math.pow(1+tasa,1/meses)-1;
		dividendo = (tasa/(1 - Math.pow(1+tasa, -totalMeses)));

		document.getElementById("dividendo_uf").value = "UF " + MoneyFormat( this.CommaSeparated(monto * dividendo) );
		document.getElementById("dividendo_peso").value = "$ " + MoneyFormat( this.CommaSeparated(monto * dividendo * valorUF), 0 );
	}
	catch (e) {
		document.getElementById("dividendo_uf").value = "UF 0";
		document.getElementById("dividendo_peso").value = "$ 0";
	}
}

/*******************************************************************/
// Guarda en SESION la propiedad seleccionada
function Guardar(obj) {
	this.send_POST("ficha_propiedad.php", "sesion="+obj.value+"&checked="+obj.checked);
}

/*******************************************************************/
// Valida los datos del Formulario de Solicitud de Información
function ValidarSolicitud() {
	if ( !isNumero("rut") ) {
		return returnError("rut","Debe ingresar rut");
	}
	if ( !rutCorrecto(Value("rut"), Value("dig")) ) {
		return returnError("rut");
	}
	if ( !isText("nombre") ) {
		return returnError("nombre","Debe ingresar nombre");
	}
	if ( !isText("fono") ) {
		return returnError("fono","Debe ingresar fono");
	}
	if ( !isText("email") ) {
		return returnError("email","Debe ingresar email");
	}
	if ( !isEmail("email") ) {
		return returnError("email","Email no válido");
	}
	return true;
}

/*******************************************************************/
// Valida los datos del Formulario de Solicitud de Información
function ValidarFormulario() {
	if ( !isText("nombre") ) {
		return returnError("nombre","Debe ingresar nombre");
	}
	if ( !isText("fono") ) {
		return returnError("fono","Debe ingresar fono");
	}
	if ( !isText("email") ) {
		return returnError("email","Debe ingresar email");
	}
	if ( !isEmail("email") ) {
		return returnError("email","Email no válido");
	}
	document.getElementById("tipo_propiedad").value = document.getElementById("tipo").options[document.getElementById("tipo").selectedIndex].text;
	return true;
}

/*******************************************************************/
// Valida los datos del Formulario de Contacto
function ValidarContactenos() {
	var error=0;
	if ( !isText("nombre") ) {
		error=1;
		return returnError("nombre","Debe ingresar nombre");
	}
	if ( !isText("fono") ) {
		error=1;
		return returnError("fono","Debe ingresar fono");
	}
	if ( !isText("email") ) {
		error=1;
		return returnError("email","Debe ingresar email");
	}
	if ( !isEmail("email") ) {
		error=1;
		return returnError("email","Email no válido");
	}
	if ( !isText("mensaje") ) {
		error=1;
		return returnError("mensaje","Debe ingresar un Mensaje");
	}
	if (error==0) {
		document.form1.submit();
	}
	return true;
}

/*******************************************************************/
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_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_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];}
}
