function cuotaFrancesa(aFinanciar, interes, meses)
{
	r = interes / 1200.0;
	return ( aFinanciar * r * (Math.pow((1.0+r), meses) / (Math.pow((1.0+r), meses) - 1)) );
}

function simula(sacarFallos,txtImporte,txtPlazo,divCuota)
{
	var interes=8.95;
	var porcentajeGtoFinanciacion=2.3;
	var gtoAplazado = true;
	
	var importe=0, plazo=0, aFinanciar = 0;
	var errores = "";
	
	importe = parseFloat(txtImporte.value);
	plazo = parseFloat(txtPlazo.value);
	
	//COMPROBAMOS LOS VALORES
	if (isNaN(importe))
	{
		errores += "- Debe insertar un importe correcto.\n";
	}
	if (isNaN(plazo))
	{
		errores += "- Debe insertar un plazo correcto\n";
	}
	
	if ( (errores != "") && (sacarFallos) )
	{
		alert("Se han producido los siguientes errores:\n" + errores);
		return;
	}
	//CALCULAR CUOTA
	aFinanciar = importe;
	var gtoFinanciacion = aFinanciar * porcentajeGtoFinanciacion / 100;
	if (gtoAplazado)
	{
		aFinanciar += gtoFinanciacion;
	}
	cuota = cuotaFrancesa(aFinanciar, interes, plazo);
	
	divCuota.innerHTML = format_number(cuota,2)
	
}


function format_number(pnumber,decimals) 
{  
		if (isNaN(pnumber)) { return 0};  
		if (pnumber=='') { return 0};  
		   
		var IsNegative=(parseInt(pnumber)<0); 
		if(IsNegative)pnumber=-pnumber; 

		var snum = new String(pnumber);  
		var sec = snum.split('.');  
		var whole = parseInt(sec[0]);  
		var result = '';  
		if(sec.length > 1){  
			var dec = new String(sec[1]);  
			dec = parseInt(dec)/Math.pow(10,parseInt(dec.length-decimals-1)); 
		Math.round(dec); 
		dec = parseInt(dec)/10; 

		if(IsNegative) 
		{ 
		var x = 0-dec; 
			x = Math.round(x); 
		dec = - x; 
		} 
		else 
		{ 
			dec = Math.round(dec); 
		} 

		/* 
		* If the number was rounded up from 9 to 10, and it was for 1 'decimal' 
		* then we need to add 1 to the 'whole' and set the dec to 0. 
		*/ 
		if(dec==Math.pow(10, parseInt(decimals)))
		{ 
		whole+=1; 
		dec="0"; 
		} 

			dec = String(whole) + "." + String(dec);  
			var dot = dec.indexOf('.');  
			if(dot == -1){  
			dec += '.';  
			dot = dec.indexOf('.');  
			} 
		var l=parseInt(dot)+parseInt(decimals); 
			while(dec.length <= l) { dec += '0'; }  
			result = dec;  
		} else{  
			var dot;  
			var dec = new String(whole);  
			dec += '.';  
			dot = dec.indexOf('.');  
		var l=parseInt(dot)+parseInt(decimals); 
			while(dec.length <= l) { dec += '0'; }  
			result = dec;  
		}  
		if(IsNegative)result="-"+result; 
		return result;  
}  
