function inicia_calculo_hipoteca(){

	if (document.form_hipoteca.importe_selec.value == ""){
	alert ("Debe especificar el importe de hipoteca que desea solicitar");
	} else {

	document.miForm.importe.value = "";
	document.miForm.interes.value = "";
	document.miForm.amortizacion.value = "";
	document.miForm.cuota.value = "";

	document.miForm.importe.value = document.form_hipoteca.importe_selec.value;
	document.miForm.interes.value = document.form_hipoteca.interes_selec.value;
	document.miForm.amortizacion.value = document.form_hipoteca.amortizacion_selec.value;

	calcula();
	document.getElementById('div_cuota_hipoteca').innerHTML = "<span class=\"txt_nar_16_n\">&nbsp;"+document.miForm.cuota.value+" &euro;</span>";
	
	}

}
function Delete_miles(numero_puntos){
   		var num_p;
    		num_p = numero_puntos;
    		longitud = 0;
    		longitud = num_p.length;
			n = 0;
    		var num_sp = "";
    		while (n<longitud){
        		var car = ' ';
        		var car = num_p.charAt(n);

        		if ((car != '.')&&(car!=','))
							num_sp += num_p.charAt(n);
        		n++;  
    		}
    		var sin_puntos = parseInt(num_sp,10);
    		return sin_puntos;
	}
	function separador_miles(obj, sign, imaxlength)
{
   var snumero;
   snumero = obj.value + 1; 
  if (snumero.length > imaxlength)
   {  
 event.returnValue = false;
     return false;  
   }
   if ((obj.value=="") && (event.keyCode == 48)) {

     event.returnValue = false;
  }
  else
  if (sign == "positive")
  {
    if ((event.keyCode < 48) || (event.keyCode > 57))
    {
      event.returnValue = false;
    }
	else 
    {
      var s_pre = obj.value;

      var s_inter = "";

      var s_post = "";

      var single_character = "";

      var poner_punto = 1;
	  for (var i = 0; i < s_pre.length; i++)

      {

        single_character = s_pre.substring(i,i+1);

        if (single_character != ".")

        {
          s_inter = s_inter + single_character;
        }
		}
      s_inter = s_inter + String.fromCharCode(event.keyCode);
      for (var j = s_inter.length; j > 0; j--, poner_punto++)
      {

        s_post = s_inter.substring(j-1,j) + s_post;
        if ((poner_punto == 3) && (j != 1))
		{

          poner_punto = 0;

          s_post = "." + s_post;
        }

      }
obj.value = s_post;



      event.returnValue = false;

    }
  }
   else

  {

    if (

         (

           isEmpty(obj.value)

             &&

           ((event.keyCode < 48) || (event.keyCode > 57))

             &&

           (event.keyCode != 43)

             &&
			 (event.keyCode != 45)

         )

           ||

         (

           (obj.value.length > 0)

             &&

           ((event.keyCode < 48) || (event.keyCode > 57))

         )

       )
	   {

      event.returnValue = false;

    }

    else if (obj.value != "+" && obj.value != "-")

    {

      var s_pre = obj.value;

      var s_inter = "";

      var s_post = "";

      var single_character = "";

      var poner_punto = 1;

      var sign_character = "";
	  if (

           (s_pre.substring(0, 1) == "+")

             ||

           (s_pre.substring(0, 1) == "-")

         )

      {
	  sign_character = s_pre.substring(0, 1);

        s_pre = s_pre.substring(1, s_pre.length);

      }



      for (var i = 0; i < s_pre.length; i++)

      {

        single_character = s_pre.substring(i,i+1);



        if (single_character != ".")

        {

          s_inter = s_inter + single_character;

        }
		}



      s_inter = s_inter + String.fromCharCode(event.keyCode);



      for (var j = s_inter.length; j > 0; j--, poner_punto++)

      {

        s_post = s_inter.substring(j-1,j) + s_post;



        if ((poner_punto == 3) && (j != 1))

        {
		poner_punto = 0;

          s_post = "." + s_post;

        }

      }



      obj.value = sign_character + s_post;



      event.returnValue = false;

    }
	}

}

   

function Formato_numero(numero){



	var nombre = "";



	//alert("En Formato_numero, Nombre recibido :" + name);

		var num = numero;
		//alert("Numero recibido :" + num);

	

	if (num != ""){

	

	//alert ("Entra en num !=");

	

		var str = "";

		while (num > 999){

	

			n1 = Math.floor(num/1000);
			n2 = num - 1000 * n1;

			

			if (n2 < 10){

			   n2 = "00" + n2;

	        	}   

			else{
			if (n2 < 100)
	       		      n2 = "0" + n2;
	                }
			str = "." + n2 + str;
			num = n1;
		}
		str = num + str;
		//return (str);
	}
	return (str);
}
function esNumero(temp){

        cadenaInput=""+temp;

        if (cadenaInput=="NaN"){

                return false;

        }
		for ( var j=0 ; j <= cadenaInput.length-1 ; j++ ){

                var caracter=cadenaInput.charAt(j);

                if (caracter <"0" || caracter >"9"){

                        if (caracter!="."){

                                return false;

                        }

                }

        }

        return true;

}
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("Introduzca un valor entre "+formatoMoneda(inf,".")+" y "+formatoMoneda(sup,".")+cadena);

                        temp.value="";

                        resultado=false;

                }

        }
		else {

                alert("Debe de ser un número.");

                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("Debe de ser un nú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.miForm.elements[num].value=""

}

function calcula(){

sigo = true

if (!(document.miForm.importe.value == "")){

document.miForm.importe.value = Delete_miles(document.miForm.importe.value);}

if (!(document.miForm.cuota.value == "")){

document.miForm.cuota.value = Delete_miles(document.miForm.cuota.value);}

if (document.miForm.elements[0].value < document.miForm.elements[3].value && !(document.miForm.elements[0].value == ""))

{
alert ("el importe de la cuota no puede ser mayor que el importe de la hipoteca");

	document.miForm.elements[3].focus();

	return;

}
if (document.miForm.elements[1].value < 0){

				alert ("únicamente introduzca números positivos");

				//document.miForm.elements[1].value = "";

				document.miForm.importe.value = Formato_numero(document.miForm.importe.value);

				document.miForm.elements[1].focus();

				return; }
				if (document.miForm.elements[2].value < 0){

				alert ("únicamente introduzca números positivos");

				//document.miForm.elements[1].value = "";

				document.miForm.importe.value = Formato_numero(document.miForm.importe.value);

				document.miForm.elements[2].focus();

				return; }
				if (document.miForm.elements[2].value > 50)

  {

	alert("El plazo de amortización máximo es de 50 años");

	//document.miForm.elements[1].value = "";

    document.miForm.elements[2].value = ""; 

    document.miForm.importe.value = Formato_numero(document.miForm.importe.value);

    document.miForm.elements[2].focus();

	return;

  }
  if (document.miForm.elements[1].value > 20)

  {

	alert("El interés no puede ser mayor al 20%");

    if (!(document.miForm.importe.value == "")) {

    document.miForm.importe.value = Formato_numero(document.miForm.importe.value);}

    if (!(document.miForm.cuota.value == "")) {

    document.miForm.cuota.value = Formato_numero(document.miForm.cuota.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.amortizacion.value == "")) {

		document.miForm.amortizacion.value = parseInt(document.miForm.amortizacion.value) * 12;}

		calculaprestamo()

	}

if (!(document.miForm.importe.value == "") && !(document.miForm.cuota.value == "")){

document.miForm.importe.value = Formato_numero(document.miForm.importe.value);

document.miForm.cuota.value = Formato_numero(document.miForm.cuota.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.amortizacion.value = parseInt(document.miForm.amortizacion.value) / 12;

		alert("debe dejar el campo vacío del valor que quiere calcular")

	}else{
	if (suma<3){

			correcto=false

			document.miForm.amortizacion.value = parseInt(document.miForm.amortizacion.value) / 12;

			document.miForm.elements[2].value = ""; 

			alert("Debe especificar tres valores como mínimo, deje sólo vacío el campo que quiera calcular")

			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("combinación de valores errónea")

			}else{

				calculainteres()

			}

		}
		if (datos[0]==""){

			id=datos[1]/1200



			//******************Operación espejo***********************

			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.amortizacion.value = parseInt(document.miForm.amortizacion.value) / 12;

		}

		if (datos[2]==""){

			id=datos[1]/1200

			//res=-Math.log((datos[0]*i/datos[3])-1)/Math.log(1+id)

			dividendo1=Math.log(datos[3])

			suma1=(-datos[0]*id)
			suma2=datos[3]

			

			sumando=parseFloat(suma1)+parseFloat(suma2)

			

			dividendo2=Math.log(sumando)

			//alert("Dividiendo..:" + dividendo2 + "Sumando..:" + 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 plazo máximo de amortización es de 35 años");

				//document.miForm.elements[1].value = "";

				document.miForm.elements[2].value = "";

				document.miForm.importe.value = Formato_numero(document.miForm.importe.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)

				//document.miForm.amortizacion.value = Math.round(parseInt(document.miForm.amortizacion.value) / 12);

				alert("Se ha modificado el importe de la hipoteca para ajustar los valores a un resultado válido")

			}		

document.miForm.amortizacion.value = Math.round(parseInt(document.miForm.amortizacion.value) / 12);

		}

		if (datos[3]==""){

			id=datos[1]/1200

			//res=datos[0]/((1-Math.pow(1+id,2)-datos[2])/id)

			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.amortizacion.value = parseInt(document.miForm.amortizacion.value) / 12;



		}

	}
	}



function calculainteres(){

	inter=4.50
		//******************Operación espejo***********************************

			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)
	//alert(comparo1)
	//alert("paso="+parseInt(res)<parseInt(comparo) && parseInt(res)>parseInt(comparo1))
	}		
		while (parseInt(res)>parseInt(comparo) || parseInt(res)<parseInt(comparo1))
	inter=inter*100
	inter=parseInt(inter)
	inter=inter/100
	document.miForm.elements[1].value=inter

	//**********Modificamos el capital inicial******************
			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)

				//document.miForm.amortizacion.value = parseInt(document.miForm.amortizacion.value) / 12;

				alert("Se ha modificado el importe de la hipoteca para ajustar los valores a un resultado válido")

			}
			document.miForm.amortizacion.value = parseInt(document.miForm.amortizacion.value) / 12;
	capinitemp=0
	plazotemp=0
}
function set_vacio(obj) {
obj.value = "";
}
