/*
function calculoCota()
{	
	inter = parseFloat(desformatear(document.inter.value));
	impor = parseFloat(desformatear(document.impor.value));

	meses = parseFloat($("#plazo").val()) * 12;
	cuota = impor * (inter/1200) / (1-Math.pow(1+inter/1200,-meses));	

	txt = '<b>Cuota mensual</b><h1>';
	var n = new String(cuota);
	txt += formatNumber(n,".##0,00");
	txt += ' &euro;</h1>';
	
	$("#resultado").html(txt);
}				
*/

function calculoCota()
{	
	inter = parseFloat(desformatear($("#inter1").val()));
	impor = parseFloat(desformatear($("#impor1").val()));

	meses = parseFloat($("#plazo").val()) * 12;
	cuota = impor * (inter/1200) / (1-Math.pow(1+inter/1200,-meses));	

	txt = '<b>Cuota mensual</b><h1>';
	var n = new String(cuota);
	txt += formatNumber(n,".##0,00");
	txt += ' &euro;</h1>';
	
	$("#resultado").html(txt);
}				

function eurocalculadora(a){
	var nulos=0
	p=new Object(document.euro_calc.pesetas)
	e=new Object(document.euro_calc.euros)
	if (a==2){//pesetas a euros
		var imporpesetas=p.value
		if(isNaN(imporpesetas)){
			var imporpesetas=new NumberFormat(p.value).Numero()
		}
		var imporeuros=imporpesetas/166.386
		e.value=new NumberFormat(imporeuros).toFormatted()
	}else{
		if (a==1){//euros a pesetas
			var imporeuros=e.value
			if (isNaN(imporeuros)){
				imporeuros=new NumberFormat(imporeuros).Numero()
			}
			var imporpesetas=Math.round(imporeuros*166.386)
			p.value=new NumberFormat(imporpesetas).toFormatted()
			var ss=new String(p.value)
			p.value=ss.substr(0,ss.length-3)
		}
	}
}

function formatearcalculadora(objeto){
	var valor= desformatear(objeto.value);
	objeto.value=new NumberFormat(valor).toFormatted()
	if (objeto.id=="pesetas"){
		var p=new Object(document.euro_calc.pesetas)
		var ss=new String(p.value)
		p.value=ss.substr(0,ss.length-3)
	}
}

function validartecla(objeto){
	var valor=new String(objeto.value)
	if(valor.length>0){
		var c=new String(valor.charAt(valor.length-1))
		if(isNaN(c)){
			if(c!='.' && c!=','){
				if(valor.length==1) objeto.value="";
				else objeto.value=valor.substr(0, valor.length-1);
			}
		}
	}
}


// función para modificar la visión de la página dinamicamente
function tipocalc(tipo){
	document.hipoteca.impor.style.visibility="visible";
	document.hipoteca.plazo.style.visibility="visible";
	document.hipoteca.inter.style.visibility="visible";
	document.hipoteca.cuota.style.visibility="visible";
	document.hipoteca.impor.disabled=false;
	document.hipoteca.plazo.disabled=false;
	document.hipoteca.inter.disabled=false;
	document.hipoteca.cuota.disabled=false;
	// desamblo el control...
	if(tipo=="impor"){
		document.hipoteca.impor.style.visibility="hidden";
		document.hipoteca.impor.value="";
	}else if(tipo=="plazo"){
		document.hipoteca.plazo.style.visibility="hidden";
		document.hipoteca.plazo.value="";
	}else if(tipo=="inter"){
		document.hipoteca.inter.style.visibility="hidden";
		document.hipoteca.inter.value="";
	}else{
		document.hipoteca.cuota.style.visibility="hidden";
		document.hipoteca.cuota.value="";
	}
}

// Función para poder mostrar el cuadro con el resultado...
function mostrarmsg(msg, valor, cuadro){
	var mensage=new String(msg);
	var str_htm=new String();
	var bc=new Number(cuadro);
	// Muestro la capa y el mensaje escondido en ella...
	Capa("resultado").visibility=ConstMostrar;
	str_htm='<table align="center" width="220" border="0" cellpadding="0" cellspacing="0" bgcolor="#00A5FF">';
	str_htm+='<tr><td width="8" height="20"><img src="imaxes/bordeu.gif"></td><td width="5" rowspan="3"></td>';
	str_htm+='<td rowspan="3" class="txtinf" align="center"><form name="res" id="res"><br>';
	str_htm+='<center>'+msg;
	if(valor>"") str_htm+='<b>&nbsp;&nbsp;'+valor+'</b>';
	str_htm+='</center>';
	if(bc>0)  str_htm+='<br><input type="button" name="cuadro" value="Cuadro de Amortización" onClick="amortizacion()" tabindex="8">';
	str_htm+='</form></td><td width="8" height="20"><img src="imaxes/esqbsd.gif"></td></tr>';
	str_htm+='<tr><td height="90" bgcolor="#9C24BA"></td><td></td></tr>';
	str_htm+='<tr><td width="8" height="20"><img src="imaxes/borde.gif"></td><td width="8" height="20"><img src="imaxes/esqbid.gif"></td></tr></table>';

	ContidoCapa("resultado", str_htm);
	/*document.getElementById("resultado").style.visibility="visible";
	document.res.informacion.value=mensage;
	if(bc>0) document.res.cuadro.style.visibility="visible";
	else document.res.cuadro.style.visibility="hidden";*/
}

// Función para realizar los calculos necesarios para obtener los datos de la hipoteca...
//
var cero="0,00"
var h_impor=0;
var h_meses=0;
var h_inter=0;
var h_cuota=0;
function calculos(){
	var resultado=new String();
	var valor=new String();
	var medida=1.0;
	var nulos=0;
	if ((document.hipoteca.plazo.value>600 && document.hipoteca.plazod.options.selectedIndex==1) || 
		(document.hipoteca.plazo.value>50 && document.hipoteca.plazod.options.selectedIndex==0)){
		window.alert("El plazo máximo es de 50 años.");
		return;
	}
	if (document.hipoteca.plazod.options.selectedIndex==0) 	medida = 12.0;
	else													medida = 1.0;
	for (i=0;i<document.hipoteca.length;i++) {
		if (document.hipoteca[i].type=="text" && document.hipoteca[i].value==""){
			if (document.hipoteca[i].name=="plazo")	document.hipoteca[i].value=0;
			else									document.hipoteca[i].value=cero;
		}
		if (document.hipoteca[i].type=="text" && (document.hipoteca[i].value==0 || document.hipoteca[i].value==cero)) nulos++;
	}
	if (nulos>1){
		window.alert("Debe rellenar todos los campos menos el que quiera calcular."); return;
	}
	// vamos ha realizar los calculos...
	if (document.hipoteca.tipocalculo[2].checked){	//Calcula el plazo
		h_impor=new NumberFormat(document.hipoteca.impor.value).Numero();
		h_cuota=new NumberFormat(document.hipoteca.cuota.value).Numero();
		h_inter=new NumberFormat(document.hipoteca.inter.value).Numero();
		h_meses = Math.round(Math.log(1-(h_impor*h_inter/(h_cuota*1200)))/(-1*Math.log(1+h_inter/1200)));
		var resto=h_meses % 12;
		if (resto==0){
			document.hipoteca.plazod.options.selectedIndex=0;
			var anos=Math.round(h_meses/12);
			//resultado = "El plazo del prestamo estimado es de:";// + anos + " años";
			//valor = " "+anos+" años";
			//mostrarmsg(resultado, valor, 1);
			amortizacion();
		}else{
			document.hipoteca.plazod.options.selectedIndex=1
			//resultado = "El plazo del prestamo estimado es de:";// + h_meses + " meses";
			//valor = " "+h_meses + " meses";
			//var a=h_meses/12;
			//mostrarmsg(resultado, valor, 1);
			amortizacion();
		}
		if (isNaN(h_meses) || isFinite(h_meses)==false)
		{
			window.alert("Imposible calcular el plazo. Alguno de los datos introducidos es erróneo o excede el límite máximo (30 años).");
			return;
		}else{
			if (h_meses>420) { window.alert("El plazo calculado excede del límite máximo (35 años)."); return; }
		}
	}else if (document.hipoteca.tipocalculo[1].checked){  // Calculo del impor
		h_cuota=new NumberFormat(document.hipoteca.cuota.value).Numero();
		h_meses=new NumberFormat(document.hipoteca.plazo.value).Numero() * medida;
		h_inter=new NumberFormat(document.hipoteca.inter.value).Numero();
		h_impor=h_cuota*(1-Math.pow(1+h_inter/1200,-h_meses))/(h_inter/1200);
		//var impor_calculo =new NumberFormat(cuotaunf*(1-Math.pow(1+document.hipoteca.inter.value/1200,-document.hipoteca.plazo.value*12))/(document.hipoteca.inter.value/1200))
		//var imp=new NumberFormat(h_impor).toFormatted();
		//resultado = "El impor del prestamo estimado es de:";// + imp + " €uros";
		//valor = " "+imp+" &euro;uros";
		//mostrarmsg(resultado, valor, 1);
		amortizacion();
	}else if (document.hipoteca.tipocalculo[3].checked){	//Calcula el tipo de interés
		h_impor=new NumberFormat(document.hipoteca.impor.value).Numero();
		h_cuota=new NumberFormat(document.hipoteca.cuota.value).Numero();
		h_meses=new NumberFormat(document.hipoteca.plazo.value).Numero() * medida;
		//plazo_meses = parseInt(document.hipoteca.plazo.value)
		tipo_mensual = 20.0 / 1200.0;
		inc_tipo_mensual = 10.0 / 1200.0;
		y  = 1.0 + tipo_mensual;
		cuota_actual=Math.round(h_impor*tipo_mensual*Math.pow(y,h_meses)/(Math.pow(y,h_meses)-1.0));
		var contador=0
		if ((h_cuota*h_meses)<h_impor){
			window.alert("Resulta imposible calcular un tipo de interés, debe indicar un impor de cuota superior.");
			return;
		}
		var cuota_redondeada=Math.round(h_cuota);
		while (cuota_actual!=cuota_redondeada && contador<35){
			y=1.0+tipo_mensual;

			cuota_actual=Math.round(h_impor*tipo_mensual*Math.pow(y,h_meses)/(Math.pow(y,h_meses)-1.0))
			if (cuota_actual==cuota_redondeada || contador==35)	inc_tipo_mensual=0;
			if (cuota_actual>h_cuota){ 	// se aplica un inter muy alto, hay que bajarlo
				tipo_mensual=tipo_mensual-inc_tipo_mensual;
			}else{						// se aplica un inter muy bajo, hay que subirlo
				tipo_mensual=tipo_mensual+inc_tipo_mensual;
			}
			inc_tipo_mensual=inc_tipo_mensual/2.0;
			contador=contador+1;
		}
		if (contador==35) {//LO QUITAMOS PARA QUE LO CALCULE SIEMPRE Y NO LO LIMITE AL 20%
			window.alert("Resulta imposible calcular un tipo de interés, debe indicar un impor de cuota inferior.");
			return;
		}
		tipo_mensual=tipo_mensual*1200.0;
		h_inter = Math.round(tipo_mensual * 100.0) / 100.0;
		//resultado = "El tipo de inter aplicado al prestamo es de:";// + h_inter + " %";
		//valor = " "+h_interes + " %";
		//mostrarmsg(resultado, valor, 1);
		amortizacion();
	} else {	// CALCULO LA CUOTA
		h_impor=new NumberFormat(document.hipoteca.impor.value).Numero();	
		h_meses=new NumberFormat(document.hipoteca.plazo.value).Numero() * medida;
		h_inter=new NumberFormat(document.hipoteca.inter.value).Numero();
		h_cuota=h_impor*(h_inter/1200)/(1-Math.pow(1+h_inter/1200,-h_meses));
		//var cuota_calculo=new NumberFormat(imporunf*(document.hipoteca.inter.value/1200)/(1-Math.pow(1+document.hipoteca.inter.value/1200,-document.hipoteca.plazo.value*medida)))
		var cota=new NumberFormat(h_cuota).toFormatted();
//		resultado = "La cuota estimada del prestamo es de:";// + cota + " €uros";
//		valor = " "+cota+" &euro;uros";
//		mostrarmsg(resultado, valor, 1);
		amortizacion();
	}
}

// Función para mostrar el cuadro de amortización
function amortizacion(){
	if(h_impor!=0 && h_meses!=0 && h_inter!=0 && h_cuota!=0){
		// Realiza un enlace con la pagina web de amortización...
		//location="amortizacion.htm?impor="+h_impor+"&meses="+h_meses+"&inter="+h_inter+"&cuota="+h_cuota;
		location.href="amortizacion.htm?impor="+h_impor+"&meses="+h_meses+"&inter="+h_inter+"&cuota="+h_cuota;
	}
}

function blanco(objeto) {
	objeto.value=new NumberFormat(objeto.value).Numero()
	if (objeto.value==0) {objeto.value=""}
}

function validar(objeto){
	if (objeto.id!="plazo"){
		if (objeto.value==""){
			objeto.value=0
		}
		objeto.value=new NumberFormat(objeto.value).toFormatted();
	}
}

function redondea(parametro){
	if (isNaN(parametro.value)){
		alert("El dato debe ser un n&uacute;mero.");
		parametro.value="0"
	}else{
		parametro.value=Math.round(parametro.value)
	}
}

// Formatear números...
//
function NumberFormat(num){
	// member variables
	this.num;

	// external methods
	this.setNumber = setNumberNF;
	this.toFormatted = toFormattedNF;
	this.Numero = NumeroNF;
	this.setNumber((num==null) ? 0 : num);
}

function setNumberNF(num){
	this.num = num;
}

function toFormattedNF() {
	var n=new String(this.num)
	n=formatNumber(n,".##0,00")
	//CANDO QUEIRAMOS QUITAR DECIMAIS
	//n=formatNumber(n,".##0")
	return n
}

// CONSTANTES
var separator = ".";
var decpoint = ",";

function formatNumber(number, format){
	number=number.replace(/,/g,".")
	if (isNaN(number)){
		alert("El dato debe ser un número.")
		number="0,00"
		return number
	}else{
		if (number<0){
			alert("El campo debe ser un número positivo.")
			number="0,00"
			return number
		}
	}
	
	var useSeparator = format.indexOf(separator) != -1; // use separators in number
	format = strip(format, separator); // remove key characters
	number = "" + number; // convert number input to string
	number=poner_coma(number)
	// split number and format into LHS and RHS using decpoint as divider
	var dec = number.indexOf(decpoint) != -1;
	var nleftEnd = (dec) ? number.substring(0, number.indexOf(",")) : number;
	var nrightEnd = (dec) ? number.substring(number.indexOf(",") + 1) : "";
    
	dec = format.indexOf(decpoint) != -1;
	var sleftEnd = (dec) ? format.substring(0, format.indexOf(",")) : format;
	var srightEnd = (dec) ? format.substring(format.indexOf(",") + 1) : "";
	
	// adjust decimal places by cropping or adding zeros to LHS of number
	if (srightEnd.length < nrightEnd.length){
		var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
		nrightEnd = nrightEnd.substring(0, srightEnd.length);
		if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1); // round up

		// patch provided by Patti Marcoux 1999/08/06
		while (srightEnd.length > nrightEnd.length) {
			nrightEnd = "0" + nrightEnd;
		}

		if (srightEnd.length < nrightEnd.length){
			nrightEnd = nrightEnd.substring(1);
			nleftEnd = (nleftEnd - 0) + 1;
		}
	}else{
		for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++){
			if (srightEnd.charAt(i) == "0") nrightEnd += "0"; // append zero to RHS of number
			else break;
		}
	}

	// adjust leading zeros
	sleftEnd = strip(sleftEnd, "#"); // remove hashes from LHS of format
	nleftEnd = strip(nleftEnd, separator); // remove key characters
    
	while (sleftEnd.length > nleftEnd.length){
		nleftEnd = "0" + nleftEnd; // prepend zero to LHS of number
	}

	// patch provided by Drew Degentesh 2001/02/07
	var isNegative = (nleftEnd.length > 0 && nleftEnd.charAt(0) == "-");
	if (isNegative) nleftEnd = nleftEnd.substring(1);

	if (useSeparator) nleftEnd = separate(nleftEnd, separator); // add separator
	var output = nleftEnd + ((nrightEnd != "") ? "," + nrightEnd : ""); // combine parts
	return (isNegative ? "-" : "") + output;
}

function strip(input, chars){ // strip all characters in 'chars' from input
	var output = ""; // initialise output string
	for (var i=0; i<input.length; i++)
		if (chars.indexOf(input.charAt(i))==-1) output += input.charAt(i);
	return output;
}

function separate(input, separator){ // format input using 'separator' to mark 000's
	input = "" + input;
	var output = ""; // initialise output string
	for (var i=0; i<input.length; i++){
		if (i != 0 && (input.length - i) % 3 == 0) output += separator;
	output += input.charAt(i);
	}
	return output;
}

function NumeroNF(){
	var n=new String(this.num)
	desformatear(n)
	n=dato
	return n
}

function desformatear(cadena) {
	var div=new Number(1)
	dato=new String(cadena)
	if (dato.indexOf(",")>=0) {dec=dato.length-dato.indexOf(",")-1} else {dec=0}
	if (dec>2) {dato=dato.substr(0,dato.indexOf(",")+2);dec=2}
	switch (dec) {
		case 0 : div=1;break
		case 1 : div=10;break
		case 2 : div=100;break
	}
	for (i=0;i<=dato.length;i++){
		if (dato.charAt(i)=="." || dato.charAt(i)==",") {
			dato=dato.substr(0,i)+dato.substr(i+1)
		}
	}
	//if (isNaN(dato)) {alert("El dato debe ser un número.")}
	//else {dato=dato/div}
	dato=dato/div
	return dato;
}

function quitarformato(objeto){
	objeto.value=desformatear(objeto.value);
}

function poner_coma(valor){
	var dato=new String(valor)
	for (i=0;i<=dato.length;i++) {
		if (dato.charAt(i)==".") {dato=dato.substr(0,i)+","+dato.substr(i+1)}
		//CANDO QUEIRAMOS QUITAR DECIMAIS
		//if (dato.charAt(i)==".") {dato=dato.substr(0,i)+dato.substr(i+1)}
	}
	return dato
}
