function entreLimites(inf,sup,temp,cadena)
{
resultado=true
	if(temp.value=="")
		{
		temp.value = 0
		}
cantidad=quitaMillares(temp.value);
	if (esNumero(cantidad))
		{
        if (cantidad < inf || cantidad > sup)
			{
		alert("Por favor, introduzca un valor comprendido entre "+formatoMoneda(inf,".")+" y "+formatoMoneda(sup,".")+cadena);temp.value="";resultado=false;
			}
		}
else
		{
	alert("Por favor, introduzca un numero.");temp.value="";resultado=false;
		}
	return resultado;
}
//-------------------------------------------------
function calculaPrestamo(temp)
{
if (validas == 1)
	{
	temp.formCapital.value=quitaMillares(temp.formCapital.value);
	var capital=temp.formCapital.value;
	var tiempo=temp.formTiempo.value;
	var interes=temp.formInteres.value/1200;
	factor=Math.pow((1+interes),tiempo)
	cuota=capital * ( (factor*interes) / (factor-1) );
	temp.formCapital.value=formatoMoneda(temp.formCapital.value);
	temp.formTiempo.value=formatoMoneda(temp.formTiempo.value);
	
	if("NaN"==""+cuota || "Infinity"==""+cuota)
		{
		cuota=0;
		}
	temp.formResultado.value=formatoMoneda(Math.round(cuota));
		}
		else{temp.formResultado.value=""
		}
	}
//-------------------------------------------------
function compruebaEntradas(temp)
{
	validas=1;
	if(!esNumero(quitaMillares(temp.formCapital.value))){alert("Por favor, introduzca un n&uacute;mero.");temp.formCapital.value="";validas=0;}
	if(!entreLimites(1000000,30000000,temp.formCapital,' de pesetas.')){validas=0;}
	if(!entreLimites(1,300,temp.formTiempo,' meses.')){validas=0;}
}
//-------------------------------------------------
function ponInteres(temp){
var inte=0;
if (temp.Rmeses[0].checked){inte=3.75;}
if (temp.Rmeses[1].checked){inte=4.25;}
if (temp.Rmeses[2].checked){inte=6.;}
temp.formInteres.value=inte;}
//-------------------------------------------------
function ponInteres2(temp){
var t_inte=0;
if (temp.periodo_inicial.options[0].selected == true){t_inte=3.75;}
if (temp.periodo_inicial.options[1].selected == true){t_inte=4.25;}
if (temp.periodo_inicial.options[2].selected == true){t_inte=6.;}
temp.formInteres.value=t_inte;}
//-------------------------------------------------
var elem=new Array(6,9,11,12,13,17,19)
var campos=new Array("Importe a financiar","Plazo","Apellidos","Nombre","D.N.I.","E-mail","Teléfono")
//-------------------------------------------------
function obligatorios(){
var cont=0
var paso=true
for (var i=0;i<elem.length;i++){
	cont+=1 
	if(document.forms['PrestamoPersonal'].elements[elem[i]].value==""){
		alert("Debe rellenar el campo \""+campos[i]+"\"")
		document.forms['PrestamoPersonal'].elements[elem[i]].focus()
		paso=false
		break}}
        if (paso) document.forms['PrestamoPersonal'].submit()}
//-------------------------------------------------
var datos = new Array(4)
var nomdatos =new Array("Capital inicial","Tipo de interés","Plazo de amortización","Mensualidad")
var capitemp=0
var intetemp=0
var plazotemp=0
var mensutemp=0
//-------------------------------------------------
function borradato(num){document.forms[0].elements[num].value=""}
//-------------------------------------------------
function compruebadatos(){
sigo = true
if (!(document.miForm.c.value == "")){document.miForm.c.value = Delete_miles(document.miForm.c.value);}
if (!(document.miForm.m.value == "")){document.miForm.m.value = Delete_miles(document.miForm.m.value);}

var capital;
capital = parseInt(document.miForm.c.value);
//capital = parseInt('10000000');
var mensualidad;
mensualidad = Math.round((parseInt(document.miForm.m.value)*100)/100);
if (capital < mensualidad && !(document.miForm.elements[0].value == "")){alert ("La cuota no puede ser mayor que el importe inicial!");document.miForm.elements[3].focus();return;}
if (document.miForm.elements[1].value < 0){alert ("No introduzca intereses negativos");document.miForm.c.value = Formato_numero(document.miForm.c.value);document.miForm.elements[1].focus();return;}
if (document.miForm.elements[2].value < 0){alert ("No introduzca años negativos");document.miForm.c.value = Formato_numero(document.miForm.c.value);document.miForm.elements[2].focus();return;}
if (document.miForm.elements[2].value > 35){alert("El Banco de España no autoriza amortizaciones de mas de 35 años");document.miForm.elements[2].value = "";document.miForm.c.value = Formato_numero(document.miForm.c.value);document.miForm.elements[2].focus();return;}
if (document.miForm.elements[1].value > 20){alert("El interés máximo es 20%!");
if (!(document.miForm.c.value == "")){document.miForm.c.value = Formato_numero(document.miForm.c.value);}
if (!(document.miForm.m.value == "")){document.miForm.m.value = Formato_numero(document.miForm.m.value);}  
	document.miForm.elements[1].focus();
	return;}
	for (i=0;i<4;i++){
		if (isNaN(document.miForm.elements[i].value)){
			sigo=false
			alert("El dato introducido en "+nomdatos[i]+" no es un número");
			if (!(document.miForm.elements[0].value == "")){document.miForm.elements[0].value = Formato_numero(document.miForm.elements[0].value);}
			if (!(document.miForm.elements[3].value == "")){document.miForm.elements[3].value = Formato_numero(document.miForm.elements[3].value);}
			document.miForm.elements[i].focus();
			break}
	}
	if (sigo){if (!(document.miForm.p.value == "")){document.miForm.p.value = parseInt(document.miForm.p.value) * 12;}
		calculaprestamo()}
if (!(document.miForm.c.value == "") && !(document.miForm.m.value == "")){document.miForm.c.value = Formato_numero(document.miForm.c.value);document.miForm.m.value = Formato_numero(document.miForm.m.value);}}
//-------------------------------------------------
function calculaprestamo(){
var suma=0
correcto=true
for (i=0;i<4;i++){datos[i]=document.miForm.elements[i].value
if (datos[i]!=""){suma+=1}}
if (suma==4){
correcto=false
document.miForm.p.value = parseInt(document.miForm.p.value) / 12;
alert("Es necesario que deje uno de los datos vacío")
}else{
if (suma<3){
	correcto=false
	document.miForm.p.value = parseInt(document.miForm.p.value) / 12;
	document.miForm.elements[2].value = ""; 
	alert("Es necesario que introduzca tres datos")
	for (h=0;h<3;h++){
		if (!(document.miForm.elements[h].value == "")){document.miForm.elements[h].value = Formato_numero(document.miForm.elements[h].value);}}}}
if (correcto){if (datos[1]==""){
mtemp=datos[0]/datos[2]
if (datos[3]<mtemp){
	correcto=false
	alert("Ha introducido una combinación no válida de capital, plazo y mensualidad")
}else{calculainteres()}}
if (datos[0]==""){
id=datos[1]/1200

if (plazotemp==datos[2] && intetemp==id && parseInt(mensutemp)==datos[3]){res=mensutemp/((Math.pow(1+intetemp,plazotemp)*intetemp)/(Math.pow(1+intetemp,plazotemp)-1))}else{res=datos[3]/((Math.pow(1+id,datos[2])*id)/(Math.pow(1+id,datos[2])-1))}
res=parseInt(res)
document.miForm.elements[0].value=res
document.miForm.p.value = parseInt(document.miForm.p.value) / 12;
}
if (datos[2]==""){
	id=datos[1]/1200
dividendo1=Math.log(datos[3])
suma1=(-datos[0]*id)
suma2=datos[3]
sumando=parseFloat(suma1)+parseFloat(suma2)
dividendo2=Math.log(sumando)
divisor=Math.log(1+id)
res=(dividendo1-dividendo2)/divisor
res=Math.ceil(res)
document.miForm.elements[2].value=res
if ((res /12) > 35 || isNaN(res)) {alert("El Banco de España no autoriza amortizaciones de mas de 35 años");document.miForm.elements[2].value = "";document.miForm.c.value = Formato_numero(document.miForm.c.value);document.miForm.elements[2].focus();return;}

//**********Modificamos el capital inicial******************
cinicial=datos[3]/((Math.pow(1+id,res)*id)/(Math.pow(1+id,res)-1))
if (document.miForm.elements[0].value!=parseInt(cinicial)){ 
	document.miForm.elements[0].value=parseInt(cinicial)
	alert("Se ha modificado el Capital inicial para que sea \ncoherente con el resultado del plazo en valores enteros")}		
document.miForm.p.value = Math.round(parseInt(document.miForm.p.value) / 12);}
if (datos[3]==""){
id=datos[1]/1200
res=datos[0]*((Math.pow(1+id,datos[2])*id)/(Math.pow(1+id,datos[2])-1))
intetemp=id
capinitemp=datos[0]
plazotemp=datos[2]
mensutemp=res
dato=res+""
indi=dato.indexOf(".")
if (dato!=-1){
deci=dato.substring(indi+1,indi+3)
	if (parseInt(deci)>=50){document.miForm.elements[3].value=Math.ceil(res)}else{document.miForm.elements[3].value=parseInt(res)}}else{res=parseInt(res)
	document.miForm.elements[3].value=res}
	document.miForm.p.value = parseInt(document.miForm.p.value) / 12;}}}
//-------------------------------------------------
function calculainteres(){
inter=4.50
if (plazotemp==datos[2] && capinitemp==datos[0] && parseInt(mensutemp)==datos[3]){d3=mensutemp;d2=plazotemp;d0=capinitemp;}else{d0=datos[0];d3=datos[3];d2=datos[2]};
do{
id=inter/1200
res=d0*((Math.pow(1+id,d2)*id)/(Math.pow(1+id,d2)-1))
if (parseInt(res)>d3){inter=inter-0.01}
if (parseInt(res)<d3){inter= inter+0.01}
comparo=(parseInt(d3))+parseInt(31)
comparo1=(parseInt(d3))-parseInt(31)}
while (parseInt(res)>parseInt(comparo) || parseInt(res)<parseInt(comparo1))
inter=inter*100
inter=parseInt(inter)
inter=inter/100
document.miForm.elements[1].value=inter
id=inter/1200
cinicial=datos[3]/((Math.pow(1+id,datos[2])*id)/(Math.pow(1+id,datos[2])-1))
if (document.miForm.elements[0].value!=parseInt(cinicial)){ 
	document.miForm.elements[0].value=parseInt(cinicial)
	alert("Se ha modificado el Capital inicial para que sea \ncoherente con el redondeo aplicado al resultado")
	}
document.miForm.p.value = parseInt(document.miForm.p.value) / 12;
capinitemp=0
plazotemp=0
}
//-------------------------------------------------
function cerrar(){Window.close();}
//-------------------------------------------------
function borrar(obj){obj.value = "";}
valorNominal = 4.799;
function calculaCuota(va,nper,tasa_anual,periodo_anual){	
	var tasa = eval((tasa_anual/periodo_anual)/100);	
	tasa = eval(1+tasa);
	nper = parseInt(nper) * 12;
	valor1 = Math.pow(tasa, nper);
	tasa = eval(tasa - 1);
	valor2 = eval(tasa*valor1);	
	valor1 = eval(valor1 - 1);	
	valor3 = eval(valor2/valor1);	
	valor4 = eval(va * valor3);
	capital = eval(valor4 * 100);
	capital = Math.round(capital);
	capital = capital/100;
	document.miForm.m.value = capital;
}
function suma(){
	var valor = document.getElementsByName("p");
	anno = valor[0].value;
	anno = parseInt(anno) +1;
    if(comprobacion(anno)){
		valor[0].value = anno;
	    calculaCuota(document.miForm.c.value,valor[0].value,valorNominal,12);
	    valor = document.getElementsByName("m");
	    getCadenaHipoteca(valor[0].value);
  	}
    return false;
}

function resta(){
	var valor = document.getElementsByName("p");
    anno = valor[0].value;
    anno = parseInt(anno) -1;
    if(comprobacion(anno)){
		valor[0].value = anno;
	    calculaCuota(document.miForm.c.value,valor[0].value,valorNominal,12);
	    valor = document.getElementsByName("m");
	    getCadenaHipoteca(valor[0].value);
     }
     return false;
}
function calculoInicial(){
	var valor = document.getElementsByName("p");
    anno = valor[0].value;
    if(comprobacion(anno)){
		calculaCuota(document.miForm.c.value,anno,valorNominal,12);
	    valor = document.getElementsByName("m");
	    getCadenaHipoteca(valor[0].value);
    }
    return false;
}
function getCadenaHipoteca(valor){
	var hipo = document.getElementById("hipoteca");
    hipo.innerHTML = cambiarFormato(valor) + ' &euro;/mes en';
}    
function comprobacion(anno){
	if(isNaN(anno)){
    	alert("El plazo debe ser un valor numérico");
        return false;
     }
     if(anno < 9 || anno > 35){
     	alert("El plazo debe estar comprendido entre 9 y 35 años");
        return false;
     }
     return true;
}       
function cambiarFormato(valor){	
	// DECLARACION DE VARIABLES
	var i;
	var valorSinDecimal = valor;
	var valorDecimal = '';
	if(valor.indexOf('.') > 1){
	  valorSinDecimal = valor.substring(0, valor.indexOf('.'));
	  valorDecimal = valor.substring(valor.indexOf('.')+1);
	}		
	var numPosiciones = valorSinDecimal.length;	
	var pos = 0;
	var resultado = '';
	var sep = '';	
	for(i = numPosiciones -1; i >= 0; i--){
		if(pos == 2){			
			resultado = valorSinDecimal.substring(i,i+3) + sep + resultado;
			if(i == (numPosiciones-3)){
				sep = ".";
			}
			pos=0;
		}else{
			pos++;
		}
	}	
	if(pos > 0){
		resultado = valorSinDecimal.substring(0,pos) + sep + resultado;
	}
	if(valorDecimal != ''){
		resultado = resultado + "," + valorDecimal;
	}
	return resultado;	
}                 		