//////////////////////////////////////////   CÁLCULOS SIMULADOR HIPOTECARIO      /////////////////////////////////////////////////////////////////////////////////
// columnas tabla desarrollo: |mes|cuota total|??????|plazo|cuota amortización|tipo de interés|intereses| capital amortizado|capital pendiente amortizar|flujos de caja|
var difer;
function obtendiferencial() {
	difer=formatodec(document.getElementById("formufinanciero").DIFERENCIAL.value);
}

var nfilasdesarrollo=380;
var ncolumnasdesarrollo=10;

var tabladesarrollo=new Array(nfilasdesarrollo);
for (var h=0;h<nfilasdesarrollo;h++)
	{tabladesarrollo[h]=new Array(ncolumnasdesarrollo);}

var interesestotales=0;

var compraventanueva=new Array('0#415','12000#415','15000#469','18000#517','21000#577','24000#631','27000#685','30000#739','33000#781','36000#823','39000#865','42000#907','45000#943','48000#985','51000#1028','54000#1070','57000#1112','60000#1154','66000#1226','72000#1298','78000#1376','84000#1448','90000#1520','96000#1598','102000#1670','108000#1742','114000#1820','120000#1892','150000#2246','180000#2594','210000#2924','240000#3260','270000#3590','300000#3909','330000#4257','360000#4587','390000#4917','420000#5253','450000#5583','480000#5913','510000#6249','540000#6579','570000#6915','600000#7245','900000#10443','1200000#13648','1500000#16846','1800000#20050','2100000#23248','2400000#26447','2700000#29652','3000000#32856');
var compraventalibre=new Array('0#1135','12000#1135','15000#1369','18000#1597','21000#1837','24000#2071','27000#2305','30000#2539','33000#2761','36000#2983','39000#3205','42000#3427','45000#3643','48000#3865','51000#4088','54000#4310','57000#4532','60000#4754','66000#5186','72000#5618','78000#6056','84000#6488','90000#6920','96000#7358','102000#7790','108000#8222','114000#8660','120000#9092','150000#11246','180000#13394','210000#15524','240000#17660','270000#19790','300000#21909','330000#24057','360000#26187','390000#28317','420000#30453','450000#32583','480000#34713','510000#36849','540000#38979','570000#41115','600000#43245','900000#64443','1200000#85648','1500000#106846','1800000#128050','2100000#149248','2400000#170447','2700000#191652','3000000#212856');
var compraventaVPO=new Array('0#655','12000#655','15000#769','18000#877','21000#997','24000#1111','27000#1225','30000#1339','33000#1441','36000#1543','39000#1645','42000#1747','45000#1843','48000#1945','51000#2048','54000#2150','57000#2252','60000#2354','66000#2546','72000#2738','78000#2936','84000#3128','90000#3320','96000#3518','102000#3710','108000#3902','114000#4100','120000#4292','150000#5246','180000#6194','210000#7124','240000#8060','270000#8990','300000#9909','330000#10857','360000#11787','390000#12717','420000#13653','450000#14583','480000#15513','510000#16449','540000#17379','570000#18315','600000#19245','900000#28443','1200000#37648','1500000#46846','1800000#56050','2100000#65248','2400000#74447','2700000#83652','3000000#92856');

var hipoteca=new Array('0#577','12000#577','15000#668','18000#760','21000#831','24000#907','27000#972','30000#1049','33000#1120','36000#1184','39000#1249','42000#1319','45000#1384','48000#1448','51000#1513','54000#1577','57000#1636','60000#1706','66000#1835','72000#1964','78000#2099','84000#2222','90000#2345','96000#2462','102000#2579','108000#2696','114000#2807','120000#2924','150000#3509','180000#4089','210000#4674','240000#5253','270000#5832','300000#6411','330000#6996','360000#7563','390000#8124','420000#8685','450000#9246','480000#9801','510000#10368','540000#10923','570000#11491','600000#12046','900000#17650','1200000#23248','1500000#28854','1800000#34452','2100000#40050','2400000#45444','2700000#51254','3000000#56858');

var tasacion1=new Array('0#96.76','30050.61#96.76','60101.21#128.02','120202.42#150.25','300506.05#150.25','1202024.21#280.67','3005060.52#809.56','6010121.04#1555.42','100000000000000#2245.98');
var tasacion2=new Array('0#0','120202.42#0','300506.42#0.007242','1202024.21#0.005862','3005060.52#0.004138','6010121.04#0.002300','100000000000000#0.000920');

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function iniciar()
	{
	}
	
function calcular()
	{
		rellenatabladesarrollo();
		escribirproyeccion();
	}
	
var apertura;	

function rellenatabladesarrollo()
	{
		// INTERESPERIODOVBLE = EURIBOR+ DIFERENCIAL;
		document.getElementById("formufinanciero").INTERESPERIODOVBLE.value = parseFloat(document.getElementById("formufinanciero").DIFERENCIAL.value) + euribor;
		document.getElementById('formufinanciero').INTERESPERIODOFIJO.value=document.getElementById("formufinanciero").INTERESPERIODOVBLE.value;
		
		var x=0;
		var aux;
		
		for (x=0;x<nfilasdesarrollo;x++)
			{
				//var apertura;
				if ((parseFloat(document.getElementById("formufinanciero").COMISIONAPERTURA.value)/100)*parseFloat(document.getElementById("formufinanciero").CAPITAL.value)<parseFloat(document.getElementById("formufinanciero").MINIMOCOMISIONAPERTURA.value))
					{apertura=parseFloat(document.getElementById("formufinanciero").MINIMOCOMISIONAPERTURA.value);}
				else
					{apertura=(parseFloat(document.getElementById("formufinanciero").COMISIONAPERTURA.value)/100)*parseFloat(document.getElementById("formufinanciero").CAPITAL.value);}
				
				var estudio;
				if ((parseFloat(document.getElementById("formufinanciero").COMISIONESTUDIO.value)/100)*parseFloat(document.getElementById("formufinanciero").CAPITAL.value)<parseFloat(document.getElementById("formufinanciero").MINIMOCOMISIONESTUDIO.value))
					{estudio=parseFloat(document.getElementById("formufinanciero").MINIMOCOMISIONESTUDIO.value);}
				else
					{estudio=(parseFloat(document.getElementById("formufinanciero").COMISIONESTUDIO.value)/100)*parseFloat(document.getElementById("formufinanciero").CAPITAL.value);}

				tabladesarrollo[x][0]=x;
				
				if (x<7)
					{
						tabladesarrollo[x][2]=parseFloat(document.getElementById("formufinanciero").CAPITAL.value);

						tabladesarrollo[x][3]=parseFloat(document.getElementById("formufinanciero").PLAZO.value);

						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==6)
							{tabladesarrollo[x][5]=parseFloat(document.getElementById("formufinanciero").INTERESPERIODOFIJO.value);}
						else
							{tabladesarrollo[x][5]=parseFloat(document.getElementById("formufinanciero").INTERESPERIODOFIJO.value);}
					}
				else if ((x>=7)&&(x<13))
					{
						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==12)
							{tabladesarrollo[x][2]=parseFloat(document.getElementById("formufinanciero").CAPITAL.value);}
						else
							{tabladesarrollo[x][2]=tabladesarrollo[6][8];}

						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==6)
							{tabladesarrollo[x][3]=parseFloat(document.getElementById("formufinanciero").PLAZO.value)-6;}
						else
							{tabladesarrollo[x][3]=parseFloat(document.getElementById("formufinanciero").PLAZO.value);}

						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==6)
							{tabladesarrollo[x][5]=parseFloat(document.getElementById("formufinanciero").INTERESPERIODOFIJO.value);}
						else
							{tabladesarrollo[x][5]=parseFloat(document.getElementById("formufinanciero").INTERESPERIODOFIJO.value);}
					}
				else
					{
						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==6)
							{tabladesarrollo[x][2]=tabladesarrollo[6][8];}
						else
							{tabladesarrollo[x][2]=tabladesarrollo[12][8];}

						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==12)
							{tabladesarrollo[x][3]=parseFloat(document.getElementById("formufinanciero").PLAZO.value)-12;}
						else
							{tabladesarrollo[x][3]=parseFloat(document.getElementById("formufinanciero").PLAZO.value)-6;}

						if (parseInt(document.getElementById("formufinanciero").PERIODOINTERESFIJO[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].value,10)==12)
							{tabladesarrollo[x][5]=parseFloat(document.getElementById("formufinanciero").INTERESPERIODOFIJO.value);}
						else
							{tabladesarrollo[x][5]=parseFloat(document.getElementById("formufinanciero").INTERESPERIODOVBLE.value);}
					}

				if (x==0)
					{
						tabladesarrollo[x][1]=0;
						tabladesarrollo[x][4]=0;
						tabladesarrollo[x][6]=0;
						tabladesarrollo[x][7]=0;
						tabladesarrollo[x][8]=parseFloat(document.getElementById("formufinanciero").CAPITAL.value);
						tabladesarrollo[x][9]=-parseFloat(document.getElementById("formufinanciero").CAPITAL.value)+apertura+estudio;
					}
				else
					{
						if (tabladesarrollo[x-1][8]>1)
							{tabladesarrollo[x][1]=pago(tabladesarrollo[x][5],tabladesarrollo[x][3]/12,tabladesarrollo[x][2]);}
						else
							{tabladesarrollo[x][1]=0;}

						tabladesarrollo[x][6]=(tabladesarrollo[x][5]*30/36000)*tabladesarrollo[x-1][8];
						tabladesarrollo[x][4]=tabladesarrollo[x][1]-tabladesarrollo[x][6];
						tabladesarrollo[x][7]=tabladesarrollo[x][4]+tabladesarrollo[x-1][7];
						tabladesarrollo[x][8]=tabladesarrollo[0][8]-tabladesarrollo[x][7];
						tabladesarrollo[x][9]=tabladesarrollo[x][1];
					}
				interesestotales+=tabladesarrollo[x][6];
			}
	}
	
// VARIABLES PARA CUOTAS, TAE E INTERESES
	var filacuotainicial;
	var filacuotaposterior;
	var filatae;
	var filainteresestotales;	
		

function escribirproyeccion()
	{
		document.getElementById("formufinanciero").CUOTAINICIAL.value=Math.round(tabladesarrollo[1][1]*100)/100;
		document.getElementById("formufinanciero").CUOTAPOSTERIOR.value=Math.round(tabladesarrollo[13][1]*100)/100;
		document.getElementById("formufinanciero").TAE.value=Math.round((Math.pow(1+TIR(0.0001),12)-1)*10000)/100;
		document.getElementById("formufinanciero").INTERESESTOTALES.value=Math.round(interesestotales*100)/100;
		
		
			
		filacuotainicial=formatodec(document.getElementById('formufinanciero').CUOTAINICIAL.value);
		filacuotaposterior=formatodec(document.getElementById('formufinanciero').CUOTAPOSTERIOR.value);
		filatae=formatodec(document.getElementById('formufinanciero').TAE.value);
		filainteresestotales=formatodec(document.getElementById('formufinanciero').INTERESESTOTALES.value);
	}

function VAN(tasa)
	{
		var van=0;
		
		for (var i=1;i<=nfilasdesarrollo;i++)
			{
				if (tabladesarrollo[i-1][9]==0)
					{break;}
				else
					{van+=tabladesarrollo[i-1][9]*Math.pow(1+tasa,-i);}
			}
		return van
	}

function TIR(error)
	{
		var tir=error;
		var van1,van2,dif;
		
		for (var i=0;i<20;i++)
			{
				van1=VAN(tir);
				if (Math.abs(van1)<error)
					return tir
					
				van2=VAN(tir+error);
				dif=(van1-van2)/error;
				(van1>van2)?tir=tir+(van1/dif):tir=tir-(van1/dif);
				//alert("van1: "+van1+'\n'+"van2: "+van2+'\n'+"tir: "+tir+'\n');
			}
		alert("Atención: se ha producido un error durante el cálculo del TAE.\n Por favor introduzca otros valores e inténtelo de nuevo.");
	}

function pago(interes,plazo,capital)
	{
		// El plazo se le pasa en años
		var npagosanio=12;  //nº de pagos anuales

		var tae=(Math.pow(1+((interes/100)/npagosanio),npagosanio)-1)*100;
		var cuota=capital/((1-(Math.pow((interes/100/npagosanio)+1,-1*npagosanio*plazo)))/(interes/100/npagosanio));
		
		//CUOTA -------> cuota
		//TAE ----------> tae
		//Nº PLAZOS --> npagosanio*plazo
		//TOTAL--> npagosanio*plazo*cuota
		
		return cuota;
	}

function buscarV(tabla,valor,colindice,col)
	{
		for (var x=0;x<tabla.length;x++)
			{if (tabla[x][colindice]==valor) return tabla[x][col]}
		return null;
	}

function buscarVaprox(tabla,valor,colindice,col)
	{
		for (var x=0;x<tabla.length;x++)
			{
				if (tabla[x][colindice]==valor)
					return tabla[x][col]
				else
					{
						if (tabla[x][colindice]>valor)
							{
								if (x==0) return tabla[x][col]
								else return tabla[x-1][col];
							}
					}
			}
		return tabla[tabla.length-1][col];			
	}
	
function maximocolumna(col)
	{
		var max=tabladesarrollo[0][col];
		
		for (var x=1;x<nfilasdesarrollo;x++)
			{max=Math.max(max,tabladesarrollo[x][col]);}
		return max;
	}
	
function espar(num)
	{
		if (num%2)
			return 0
		else
			return 1
	}

//////////////////////////////////// DATOS INTRODUCIDOS POR EL USUARIO ///////////////////////////////////////////
//////////////////////////////////// CÁLCULOS SIMULADOR HIPOTECARIO //////////////////////////////////////////////





// IMPORTE APROXIMADO A SOLICITAR
var importesolicitar='';

function comprobacionesimporte() {
	// Precio de la vivienda
	if ( (document.getElementById('formuimporte').PRECIOVIVIENDA.value=='') || isNaN(document.getElementById('formuimporte').PRECIOVIVIENDA.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Precio de la vivienda"\ son correctos');
		document.getElementById('formuimporte').PRECIOVIVIENDA.focus();
		return false;
	}
	if ( parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)>3000000 ) {
		alert('Por favor, el valor del campo \"Precio de la vivienda"\ no puede superar el valor \"3.000.000"\ para esta simulación');
		document.getElementById('formuimporte').PRECIOVIVIENDA.focus();
		return false;
	}		
	// Importe ya ahorrado
	if ( isNaN(document.getElementById('formuimporte').AHORRADO.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Importe ya ahorrado"\ son correctos');
		document.getElementById('formuimporte').AHORRADO.focus();
		return false;
	}
	else if ( document.getElementById('formuimporte').AHORRADO.value=='' ) {
		document.getElementById('formuimporte').AHORRADO.value="0";
	} 
	return true;
}

function obtenvalor1(arr,camp) {
	var aux_campos_ant=0;
	var aux_campos=0;
	var gastoscompraventa=0;
	for (i=0;i<arr.length;i++) {		
                aux_campos=arr[i].split('#');
                if( (parseFloat(camp)>parseFloat(aux_campos_ant[0])) && (parseFloat(camp)<=parseFloat(aux_campos[0])) ) {
                	camp=aux_campos_ant[0];
                	break;
                }
                aux_campos_ant=aux_campos;
        }
        return camp;
}

var gastosotros;
var gastoscompraventa;
var gastoshipoteca;
var gastosapertura;

function obtenvalor(arr,camp) {
	var aux_campos_ant=0;
	var aux_campos=0;
	var gastoscompraventa=0;
	for (i=0;i<arr.length;i++) {		
                aux_campos=arr[i].split('#');
                if( (parseFloat(camp)>parseFloat(aux_campos_ant[0])) && (parseFloat(camp)<=parseFloat(aux_campos[0])) ) {
                	camp=aux_campos[1];
                	break;
                }
                aux_campos_ant=aux_campos;
        }
        return camp;
}

function calcularcompraventa() {
	// Comprobamos cuál es el 'radio' seleccionado
	for (i=0;i<document.getElementById('formuimporte').tipovivienda.length;i++){ 
		if (document.getElementById('formuimporte').tipovivienda[i].checked) {
	          	break;
	       	}   
	}
	var coniva=0;
	if (i==0) {compraventa=compraventanueva; coniva=parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)*0.07;}
	if (i==1) {compraventa=compraventalibre}
	if (i==2) {compraventa=compraventaVPO}
	
	// Cogemos el valor q nos interesa
	gastoscompraventa=obtenvalor(compraventa,document.getElementById('formuimporte').PRECIOVIVIENDA.value);
   
    document.getElementById('estgastoscompraventa').innerHTML=formatodec(gastoscompraventa)+ ' &euro;';
}

function calcularhipoteca() {
	var gastosprestamo=(parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)+parseFloat(gastoscompraventa)+parseFloat(gastosotros))-parseFloat(document.getElementById('formuimporte').AHORRADO.value);
	gastoshipoteca=obtenvalor(hipoteca,gastosprestamo);
	document.getElementById('estgastoshipoteca').innerHTML=formatodec(gastoshipoteca)+ ' &euro;';		
}

function calcularotros() {
	// Costes de tasación
	var tas1=obtenvalor(tasacion1,document.getElementById('formuimporte').PRECIOVIVIENDA.value);
	var tas2=obtenvalor(tasacion2,document.getElementById('formuimporte').PRECIOVIVIENDA.value);
	var impuestos=(parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)-obtenvalor1(tasacion2,document.getElementById('formuimporte').PRECIOVIVIENDA.value))*tas2;
	var ctasacion=parseFloat(tas1)+parseFloat(impuestos);
	
	// Costes de seguro multirriesgo
	var cmultirriesgo=((parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)*166.386)/1000000)*6.3;
	gastosotros=parseFloat(ctasacion)+parseFloat(cmultirriesgo);
		
	document.getElementById('estotrosgastos').innerHTML=formatodec(gastosotros)+ ' &euro;';
}

function calcularapertura() {
	var gastosprevios=(parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)+parseFloat(gastoscompraventa)+parseFloat(gastosotros)+parseFloat(gastoshipoteca))-parseFloat(document.getElementById('formuimporte').AHORRADO.value);
	// Cálculo de la comisión de apertura
	var min=600;
	gastosapertura=parseFloat(gastosprevios)*0.01;	
	if(gastosapertura<min) {
		gastosapertura=min;
	}
	document.getElementById('estgastosapertura').innerHTML=formatodec(gastosapertura)+ ' &euro;';
}

var resul;

function calcularimporte() {	
	// Cambiamos comas por puntos para realizar los cálculos
	document.getElementById('formuimporte').PRECIOVIVIENDA.value=document.getElementById('formuimporte').PRECIOVIVIENDA.value.replace(',','.');
	document.getElementById('formuimporte').AHORRADO.value=document.getElementById('formuimporte').AHORRADO.value.replace(',','.');
	
	if(comprobacionesimporte()) {
		var strTabla = ''+
		'<table id="tablaimporte" cellpadding="0" cellspacing="0" summary="Tabla que indica el resultado de la simulación de cálculo de importes.">'+
		'	<caption>Importe aproximado a solicitar</caption>'+
		'		<tbody>'+
		'			<tr class="gris">'+
		'				<td>'+
		'					Estimación Gastos de compraventa<br />'+
		'					<span class="comentario">Estimación del importe del Impuesto de Actos Jurídicos Documentados más el <acronym lang="es" title="Impuesto sobre el Valor Añadido">IVA</acronym> o el Impuesto de Transmisiones Patrimoniales, según proceda</span>'+
		'				</td>'+
		'				<td id="estgastoscompraventa" align="right" valign="top">'+
		'					<img src="/images/sizer.gif" alt="" />'+
		'				</td>'+
		'			</tr>'+
		'			<tr class="blanco">'+
		'				<td> '+
		'					Estimación Gastos de constitución de hipoteca <br />'+
		'						<span class="comentario">Gastos de notario, Registro de la Propiedad, etc</span>'+
		'				</td>'+
		'				<td id="estgastoshipoteca" align="right" valign="top">'+
		'					<img src="/images/sizer.gif" alt="" />'+
		'				</td>'+
		'			</tr>'+
		'			<tr class="gris">'+
		'				<td> '+
		'					Estimación Otros Gastos (tasación, seguro, ...)'+
		'				</td>'+
		'				<td id="estotrosgastos" align="right" valign="top">'+
		'					<img src="/images/sizer.gif" alt="" />'+
		'				</td>'+
		'			</tr>'+
		'			<tr class="blanco">'+
		'				<td> '+
		'					Comisión de apertura<br />'+
		'					<span class="comentario">Calculado bajo el supuesto del 1%, con mínimo de 600 &euro;</span>'+
		'				</td>'+
		'				<td id="estgastosapertura" align="right" valign="top">'+
		'					<img src="/images/sizer.gif" alt="" />'+
		'				</td>'+
		'			</tr>'+
		'			<tr class="gris">'+
		'				<td> '+
		'					<strong>Importe a solicitar</strong>'+
		'				</td>'+
		'				<td id="cimporte" align="right" valign="top">'+
		'				<img src="/images/sizer.gif" alt="" />'+
		'				</td>'+
		'			</tr>'+
		'			<tr class="blanco">'+
		'				<td colspan="2" class="comentario"> '+
		'					Recuerda que <strong>el importe de tu préstamo no podrá sobrepasar el 80% del valor de tasación</strong> del inmueble (vivienda, garaje, trastero).<br />'+
		'					Los resultados que se presentan son una estimación de acuerdo con los gastos derivados de la normativa fiscal aplicable en el Principado de Asturias, empleando además otros supuestos de cálculo considerados frecuentes, siendo necesario que se verifique antes de la solicitud la adecuación a cada caso concreto.'+
		'				</td>'+
		'			</tr>'+
		'		</tbody>'+
		'</table>';
		
		document.getElementById('resultadoimporte').innerHTML=strTabla;
		
		calcularcompraventa();
		calcularotros();
		calcularhipoteca();
		calcularapertura();
		
		
		resul=(parseFloat(document.getElementById('formuimporte').PRECIOVIVIENDA.value)+parseFloat(gastoscompraventa)+parseFloat(gastosotros)+parseFloat(gastoshipoteca)+parseFloat(gastosapertura))-parseFloat(document.getElementById('formuimporte').AHORRADO.value);
		document.getElementById('cimporte').innerHTML='<strong>'+formatodec(resul)+ ' &euro;</strong>';
		
		document.getElementById('resultadoimporte').style.display='block';
			
		
		// Cambiamos puntos por comas para realizar que los vea el usuario en ese formato
		document.getElementById('formuimporte').PRECIOVIVIENDA.value=document.getElementById('formuimporte').PRECIOVIVIENDA.value.replace('.',',');
		document.getElementById('formuimporte').AHORRADO.value=document.getElementById('formuimporte').AHORRADO.value.replace('.',',');
		
		// Si no hay ningún valor introducido en el campo 'CAPITAL', le ponemos el valor de 'resul'
		if(document.getElementById('formufinanciero').CAPITAL.value=='')
			document.getElementById('formufinanciero').CAPITAL.value=(formatodec(resul).replace('.','')).replace('.','');
	}
}

function ocultacapaimporte() {
	document.getElementById('calculaimp').style.display='block';
	document.getElementById('resultadoimporte').style.display='none';
	
	// Borramos los campos de los 'input'
	document.getElementById('formuimporte').PRECIOVIVIENDA.value='';
	document.getElementById('formuimporte').AHORRADO.value='';
	
	document.getElementById('formuimporte').PRECIOVIVIENDA.focus();
}


// ASPECTOS FINANCIEROS
function comprobacionesfinanciero() {
	// Importe a solicitar
	if ( (document.getElementById('formufinanciero').CAPITAL.value=='') || isNaN(document.getElementById('formufinanciero').CAPITAL.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Importe a solicitar"\ son correctos');
		document.getElementById('formufinanciero').CAPITAL.focus();
		return false;
	}
	// Plazo
	if ( (document.getElementById('formufinanciero').PLAZOANYOS.value=='') || isNaN(document.getElementById('formufinanciero').PLAZOANYOS.value) || (parseInt(document.getElementById('formufinanciero').PLAZOANYOS.value)>30) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Plazo"\ son correctos');
		document.getElementById('formufinanciero').PLAZOANYOS.focus();
		return false;
	}
	// Tipo de interés (fijo)
/*	if ( (document.getElementById('formufinanciero').INTERESPERIODOFIJO.value=='') || isNaN(document.getElementById('formufinanciero').INTERESPERIODOFIJO.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Tipo de interés"\ son correctos');
		document.getElementById('formufinanciero').INTERESPERIODOFIJO.focus();
		return false;
	}*/

	// Tipo de interés (variable)
	if ( (document.getElementById('formufinanciero').DIFERENCIAL.value=='') || isNaN(document.getElementById('formufinanciero').DIFERENCIAL.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Tipo de interés"\ son correctos');
		document.getElementById('formufinanciero').DIFERENCIAL.focus();
		return false;
	}
	// Comisión apertura
	if ( (document.getElementById('formufinanciero').COMISIONAPERTURA.value=='') || isNaN(document.getElementById('formufinanciero').COMISIONAPERTURA.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Comisión apertura"\ son correctos');
		document.getElementById('formufinanciero').COMISIONAPERTURA.focus();
		return false;
	}
	// Comisión estudio
	if ( (document.getElementById('formufinanciero').COMISIONESTUDIO.value=='') || isNaN(document.getElementById('formufinanciero').COMISIONESTUDIO.value) ) {
		alert('Por favor, verifique que los datos introducidos en el campo \"Comisión estudio"\ son correctos');
		document.getElementById('formufinanciero').COMISIONESTUDIO.focus();
		return false;
	}
	return true;
}

function calcularfinanciero() {	
	// Asignamos valor a 'PLAZO'
	document.getElementById('formufinanciero').PLAZO.value=parseInt(document.getElementById('formufinanciero').PLAZOANYOS.value)*12;	
	
	// Cambiamos las comas por puntos para los cálculos
	document.getElementById('formufinanciero').CAPITAL.value=document.getElementById('formufinanciero').CAPITAL.value.replace(',','.');
	importesolicitar=document.getElementById('formufinanciero').CAPITAL.value;
	document.getElementById('formufinanciero').PLAZOANYOS.value=document.getElementById('formufinanciero').PLAZOANYOS.value.replace(',','.');
	//document.getElementById('formufinanciero').INTERESPERIODOFIJO.value=document.getElementById('formufinanciero').INTERESPERIODOFIJO.value.replace(',','.');
	document.getElementById('formufinanciero').DIFERENCIAL.value=document.getElementById('formufinanciero').DIFERENCIAL.value.replace(',','.');
	document.getElementById('formufinanciero').COMISIONAPERTURA.value=document.getElementById('formufinanciero').COMISIONAPERTURA.value.replace(',','.');
	document.getElementById('formufinanciero').COMISIONESTUDIO.value=document.getElementById('formufinanciero').COMISIONESTUDIO.value.replace(',','.');

	obtendiferencial();

	if(comprobacionesfinanciero()) {
		calcular();					
		//document.getElementById('linea').style.display='block';
		
		var strTabla = ''+
		'	<div class="tabla2col">'+
		'		<div class="azuloscuro">Datos del Préstamo Hipotecario</div>'+
		'		<div class="separador">&nbsp;</div>'+
		'		<div class="col1 blanco">Cuota mensual '+
		'				<script type="text/javascript">'+
		'					escribeeuribor2();'+
		'				</script>'+	
		'		</div>'+
		'		<div class="col2 blanco" id="filacuotainicial">&nbsp;</div>'+
		'		<div class="separador">&nbsp;</div>'+
		'		<div class="col1 blanco oculta">Cuota posterior</div>'+
		'		<div class="col2 blanco oculta" id="filacuotaposterior">&nbsp;</div>'+
		'		<div class="separador">&nbsp;</div>	'+
		'		<div class="col1 gris"><a href="#infotae" title="más información sobre la TAE"><acronym title="Tasa Anual Equivalente">TAE</acronym></a>'+
		'		</div>'+
		'		<div class="col2 gris" id="filatae">&nbsp;</div>'+
		'		<div class="separador">&nbsp;</div>	'+
		'	</div>'+
		'	<p class="comentario">'+
		'			Recuerda que esta simulación se realiza meramente a efectos informativos, no constituyendo una oferta en firme por parte de Cajastur.'+
		'	</p>';
		
		document.getElementById('resultadofinanciero').innerHTML=strTabla;					
		
		document.getElementById('resultadofinanciero').style.display='block';
		document.getElementById('botonaniadir').style.display='block';	
		
		escribirimpacto(numsimulaciones);
		
		document.getElementById('impacto').style.display='block';
		document.getElementById('botonaniadir').style.display='block';
		document.getElementById('filacuotainicial').innerHTML=filacuotainicial+' &euro;';
		document.getElementById('filacuotaposterior').innerHTML=filacuotaposterior+' &euro;';
		document.getElementById('filatae').innerHTML=filatae+' %';
		//document.getElementById('filainteresestotales').innerHTML=filainteresestotales;
	}
	
	// Cambiamos los puntos por comas para el usuario
	document.getElementById('formufinanciero').CAPITAL.value=document.getElementById('formufinanciero').CAPITAL.value.replace('.',',');
	document.getElementById('formufinanciero').PLAZOANYOS.value=document.getElementById('formufinanciero').PLAZOANYOS.value.replace('.',',');
	//document.getElementById('formufinanciero').INTERESPERIODOFIJO.value=document.getElementById('formufinanciero').INTERESPERIODOFIJO.value.replace('.',',');
	document.getElementById('formufinanciero').DIFERENCIAL.value=document.getElementById('formufinanciero').DIFERENCIAL.value.replace('.',',');
	document.getElementById('formufinanciero').COMISIONAPERTURA.value=document.getElementById('formufinanciero').COMISIONAPERTURA.value.replace('.',',');
	document.getElementById('formufinanciero').COMISIONESTUDIO.value=document.getElementById('formufinanciero').COMISIONESTUDIO.value.replace('.',',');
}

function ocultacapafinanciero() {	
	document.getElementById('resultadofinanciero').style.display='none';
}

function muestracapa(int) {
	if (int==0) {
		document.getElementById('importe').style.display='block';
		document.getElementById('formuimporte').PRECIOVIVIENDA.focus();
			
		//document.getElementById('tablacomparativa').style.display='none';
		//document.getElementById('impacto').style.display='none';
		document.getElementById('texto').style.display='none';
		document.getElementById('prestamo').style.display='block';
	}
	if (int==1) {
		document.getElementById('importe').style.display='none';
		document.getElementById('financiero').style.display='block';		
		if(formatodec(resul)!='NaN,00') {
			document.getElementById('formufinanciero').CAPITAL.value=(formatodec(resul).replace('.','')).replace('.','');
			document.getElementById('formufinanciero').PLAZOANYOS.focus();
		}
		else {					
			document.getElementById('formufinanciero').CAPITAL.focus();
		}
		document.getElementById('tablacomparativa').style.display='block';
		iniciarfinanciero();
	}	
}


function iniciarfinanciero() {
	//mostramos la capa con javascript
	document.getElementById('conjavascript').style.display='block';
	
	// Valores por defecto
	document.getElementById('formufinanciero').CAPITAL.focus();
	
	document.getElementById('formufinanciero').COMISIONAPERTURA.value="1,00";
	document.getElementById('formufinanciero').DIFERENCIAL.value="1,00";

	document.getElementById('formufinanciero').MINIMOCOMISIONAPERTURA.value="1.00";
	document.getElementById('formufinanciero').MINIMOCOMISIONESTUDIO.value="0.00";
	
	// Iniciamos el período de interés a 12 meses
	document.getElementById('formufinanciero').PERIODOINTERESFIJO.options[document.getElementById('formufinanciero').PERIODOINTERESFIJO.selectedIndex].value="6";
}

function iniciarimporte() {
	document.getElementById('formuimporte').PRECIOVIVIENDA.focus();
}

// Código para tabla de simulaciones
var numsimulaciones=0;

// Campos para simulación	
var simulacion=new Array();
for (var h=1;h<5;h++) {
	simulacion[h]=new Array(11);
}
for (var h=0;h<12;h++) {
	simulacion[1][h]='';
	simulacion[2][h]='';
	simulacion[3][h]='';
	simulacion[4][h]='';
}

// Campos para evolución según simulaciones
var str_impacto1='';
var str_impacto2='';
var str_impacto3='';
var str_impacto4='';


function campostabla(i) {
	if (i==0) {simulacion[1]=new Array(formatodec(importesolicitar),document.getElementById("formufinanciero").PLAZOANYOS.value,document.getElementById("formufinanciero").PERIODOINTERESFIJO.options[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].text,document.getElementById("formufinanciero").INTERESPERIODOFIJO.value,document.getElementById("formufinanciero").DIFERENCIAL.value,formatodec(apertura),document.getElementById("formufinanciero").MINIMOCOMISIONAPERTURA.value,document.getElementById("formufinanciero").COMISIONESTUDIO.value,document.getElementById("formufinanciero").MINIMOCOMISIONESTUDIO.value,filacuotainicial,filacuotaposterior,filatae,formatodec(euribor),formatodec(deduccion1),formatodec(deduccion3));}
	if (i==1) {simulacion[2]=new Array(formatodec(importesolicitar),document.getElementById("formufinanciero").PLAZOANYOS.value,document.getElementById("formufinanciero").PERIODOINTERESFIJO.options[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].text,document.getElementById("formufinanciero").INTERESPERIODOFIJO.value,document.getElementById("formufinanciero").DIFERENCIAL.value,formatodec(apertura),document.getElementById("formufinanciero").MINIMOCOMISIONAPERTURA.value,document.getElementById("formufinanciero").COMISIONESTUDIO.value,document.getElementById("formufinanciero").MINIMOCOMISIONESTUDIO.value,filacuotainicial,filacuotaposterior,filatae,formatodec(euribor),formatodec(deduccion1),formatodec(deduccion3));}
	if (i==2) {simulacion[3]=new Array(formatodec(importesolicitar),document.getElementById("formufinanciero").PLAZOANYOS.value,document.getElementById("formufinanciero").PERIODOINTERESFIJO.options[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].text,document.getElementById("formufinanciero").INTERESPERIODOFIJO.value,document.getElementById("formufinanciero").DIFERENCIAL.value,formatodec(apertura),document.getElementById("formufinanciero").MINIMOCOMISIONAPERTURA.value,document.getElementById("formufinanciero").COMISIONESTUDIO.value,document.getElementById("formufinanciero").MINIMOCOMISIONESTUDIO.value,filacuotainicial,filacuotaposterior,filatae,formatodec(euribor),formatodec(deduccion1),formatodec(deduccion3));}
	if (i==3) {simulacion[4]=new Array(formatodec(importesolicitar),document.getElementById("formufinanciero").PLAZOANYOS.value,document.getElementById("formufinanciero").PERIODOINTERESFIJO.options[document.getElementById("formufinanciero").PERIODOINTERESFIJO.selectedIndex].text,document.getElementById("formufinanciero").INTERESPERIODOFIJO.value,document.getElementById("formufinanciero").DIFERENCIAL.value,formatodec(apertura),document.getElementById("formufinanciero").MINIMOCOMISIONAPERTURA.value,document.getElementById("formufinanciero").COMISIONESTUDIO.value,document.getElementById("formufinanciero").MINIMOCOMISIONESTUDIO.value,filacuotainicial,filacuotaposterior,filatae,formatodec(euribor),formatodec(deduccion1),formatodec(deduccion3));}
}

function mostrartabla() {
	campostabla(numsimulaciones);
	numsimulaciones++;
	if (numsimulaciones<=4) {
		escribircomparativa();
	}
	else {
		alert('Se ha superado el máximo de simulaciones. Pulsa \"eliminar simulaciones"\ para realizar una nueva simulación.');
	}	
	//document.getElementById('calculo').style.display='block';
	document.getElementById('tablacomparativa').style.display='block';
	document.getElementById('botonaniadir').style.display='none';
	
	// Ocultamos 'Datos del Préstamo Hipotecario' e 'Impacto Fiscal'
	document.getElementById('resultadofinanciero').style.display='none';
	document.getElementById('impacto').style.display='none';
		
	document.getElementById('formufinanciero').CAPITAL.value='';
	document.getElementById('formufinanciero').PLAZOANYOS.value='';
	document.getElementById('formufinanciero').CAPITAL.focus();
}

function noesvacio(celda, texto) {
	if((celda!='') && (celda!=undefined)) {
		return (celda+' '+texto);
	}
	else
		return '';
}

function enlace(celda,num) {
	if(celda!='') {
		if (num==1) return  '<a href="javascript:verimpacto(1)"><img src="images/evolucion.gif" alt="Ver el Impacto Fiscal asociado a este Préstamo" /></a>';
		if (num==2) return  '<a href="javascript:verimpacto(2)"><img src="images/evolucion.gif" alt="Ver el Impacto Fiscal asociado a este Préstamo" /></a>';
		if (num==3) return  '<a href="javascript:verimpacto(3)"><img src="images/evolucion.gif" alt="Ver el Impacto Fiscal asociado a este Préstamo" /></a>';
		if (num==4) return  '<a href="javascript:verimpacto(4)"><img src="images/evolucion.gif" alt="Ver el Impacto Fiscal asociado a este Préstamo" /></a>';		
	}	
	else
		return '';
}

function verimpacto(int) {
	if (int==1) {document.getElementById('resultadofinanciero').style.display='none';document.getElementById('tablacomparativa').style.display='none';document.getElementById('impacto').innerHTML=str_impacto1;document.getElementById('impacto').style.display='block';}	
	if (int==2) {document.getElementById('resultadofinanciero').style.display='none';document.getElementById('tablacomparativa').style.display='none';document.getElementById('impacto').innerHTML=str_impacto2;document.getElementById('impacto').style.display='block';}
	if (int==3) {document.getElementById('resultadofinanciero').style.display='none';document.getElementById('tablacomparativa').style.display='none';document.getElementById('impacto').innerHTML=str_impacto3;document.getElementById('impacto').style.display='block';}
	if (int==4) {document.getElementById('resultadofinanciero').style.display='none';document.getElementById('tablacomparativa').style.display='none';document.getElementById('impacto').innerHTML=str_impacto4;document.getElementById('impacto').style.display='block';}
}

function escribircomparativa()
	{
	
		var str_comparativa="";
				
		var cabeza = '<table width="100%" cellspacing="0" id="tablacompara" summary="Tabla representativa de los resultados de la simulación o las simulaciones realizadas.">';
		cabeza += '<caption>Resultados de las simulaciones.</caption>';
		cabeza += '<thead>';
		cabeza += '<tr><th class="clave"> &nbsp; </th><th align="right" scope="col">Simulación 1</th><th align="right" scope="col">Simulación 2</th><th align="right" scope="col">Simulación 3</th><th align="right" scope="col">Simulación 4</th></tr>';
		cabeza += '</thead>';
		
		var cuerpo = '<tbody>';
		cuerpo += '<tr class="gris"><td class="clave">Importe a solicitar</td><td align="right">'+noesvacio(simulacion[1][0],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[2][0],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[3][0],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[4][0],'&euro;')+'</td></tr>';
		cuerpo += '<tr class="blanco"><td class="clave">Plazo</td><td align="right">'+noesvacio(simulacion[1][1],'años')+'</td><td align="right">'+noesvacio(simulacion[2][1],'años')+'</td><td align="right">'+noesvacio(simulacion[3][1],'años')+'</td><td align="right">'+noesvacio(simulacion[4][1],'años')+'</td></tr>';
		cuerpo += '<tr class="gris"><td class="clave">Euribor</td><td align="right">'+noesvacio(simulacion[1][12],'%')+'</td><td align="right">'+noesvacio(simulacion[2][12],'%')+'</td><td align="right">'+noesvacio(simulacion[3][12],'%')+'</td><td align="right">'+noesvacio(simulacion[4][12],'%')+'</td></tr>';
		cuerpo += '<tr class="blanco"><td class="clave">Diferencial</td><td align="right">'+noesvacio(simulacion[1][4],'%')+'</td><td align="right">'+noesvacio(simulacion[2][4],'%')+'</td><td align="right">'+noesvacio(simulacion[3][4],'%')+'</td><td align="right">'+noesvacio(simulacion[4][4],'%')+'</td></tr>';
		cuerpo += '<tr class="gris"><td class="clave">Cuota mensual</td><td align="right">'+noesvacio(simulacion[1][9],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[2][9],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[3][9],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[4][9],'&euro;')+'</td></tr>';
		cuerpo += '<tr class="blanco"><td class="clave"><a href="#infotae" title="más información sobre la TAE"><acronym title="Tasa Anual Equivalente">TAE</acronym></a></td><td align="right">'+noesvacio(simulacion[1][11],'%')+'</td><td align="right">'+noesvacio(simulacion[2][11],'%')+'</td><td align="right">'+noesvacio(simulacion[3][11],'%')+'</td><td align="right">'+noesvacio(simulacion[4][11],'%')+'</td></tr>';
		cuerpo += '<tr class="gris"><td class="clave">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym></td><td align="right">'+noesvacio(simulacion[1][13],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[2][13],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[3][13],'&euro;')+'</td><td align="right">'+noesvacio(simulacion[4][13],'&euro;')+'</td></tr>';
		cuerpo += '</tbody>';
				
		var pie = '<tfoot>';
		pie += '<tr><td colspan="5"><a href="javascript:eliminasimulaciones()"><img src="images/eliminar.gif" alt="Eliminar todas las simulaciones existentes en la tabla" /></a></td></tr>';
		pie += '<tr><td colspan="5">Recuerda que esta simulación se realiza meramente a efectos informativos, no constituyendo una oferta en firme por parte de Cajastur.</td></tr>';
		pie += '</tfoot>';
		pie += '</table>';
				

		
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Importe a solicitar</div><div class="colc2">'+noesvacio(simulacion[1][0],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][0],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][0],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][0],'&euro;')+'</div></li></ul>';
//		str_comparativa+='<ul class="blanco"><li><div class="colc1">Plazo</div><div class="colc2">'+noesvacio(simulacion[1][1],'años')+'</div><div class="colc2">'+noesvacio(simulacion[2][1],'años')+'</div><div class="colc2">'+noesvacio(simulacion[3][1],'años')+'</div><div class="colc2">'+noesvacio(simulacion[4][1],'años')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Período int. fijo</div><div class="colc2">'+simulacion[1][2]+'</div><div class="colc2">'+simulacion[2][2]+'</div><div class="colc2">'+simulacion[3][2]+'</div><div class="colc2">'+simulacion[4][2]+'</div></li></ul>';
//		str_comparativa+='<ul class="blanco"><li><div class="colc1">Interés período fijo</div><div class="colc2">'+noesvacio(simulacion[1][3],'%')+'</div><div class="colc2">'+noesvacio(simulacion[2][3],'%')+'</div><div class="colc2">'+noesvacio(simulacion[3][3],'%')+'</div><div class="colc2">'+noesvacio(simulacion[4][3],'%')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Euribor</div><div class="colc2">'+noesvacio(simulacion[1][12],'%')+'</div><div class="colc2">'+noesvacio(simulacion[2][12],'%')+'</div><div class="colc2">'+noesvacio(simulacion[3][12],'%')+'</div><div class="colc2">'+noesvacio(simulacion[4][12],'%')+'</div></li></ul>';
//		str_comparativa+='<ul class="blanco"><li><div class="colc1">Diferencial</div><div class="colc2">'+noesvacio(simulacion[1][4],'%')+'</div><div class="colc2">'+noesvacio(simulacion[2][4],'%')+'</div><div class="colc2">'+noesvacio(simulacion[3][4],'%')+'</div><div class="colc2">'+noesvacio(simulacion[4][4],'%')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Comisión de apertura</div><div class="colc2">'+noesvacio(simulacion[1][5],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][5],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][5],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][5],'&euro;')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Mínimo Comisión de apertura</div><div class="colc2">'+noesvacio(simulacion[1][6],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][6],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][6],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][6],'&euro;')+'</div></li></ul>';
//		str_comparativa+='<ul class="blanco"><li><div class="colc1">Comisión de estudio</div><div class="colc2">'+noesvacio(simulacion[1][7],'%')+'</div><div class="colc2">'+noesvacio(simulacion[2][7],'%')+'</div><div class="colc2">'+noesvacio(simulacion[3][7],'%')+'</div><div class="colc2">'+noesvacio(simulacion[4][7],'%')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Mínimo Comisión de estudio</div><div class="colc2">'+noesvacio(simulacion[1][8],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][8],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][8],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][8],'&euro;')+'</div></li></ul>';
//		str_comparativa+='<ul class="blanco"><li><div class="colc1">Cuota mensual</div><div class="colc2">'+noesvacio(simulacion[1][9],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][9],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][9],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][9],'&euro;')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1">Cuota posterior</div><div class="colc2">'+noesvacio(simulacion[1][10],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][10],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][10],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][10],'&euro;')+'</div></li></ul>';
//		str_comparativa+='<ul class="gris"><li><div class="colc1"><a href="#infotae" title="más información sobre la TAE"><acronym title="Tasa Anual Equivalente">TAE</acronym></a> <br /></div><div class="colc2">'+noesvacio(simulacion[1][11],'%')+'</div><div class="colc2">'+noesvacio(simulacion[2][11],'%')+'</div><div class="colc2">'+noesvacio(simulacion[3][11],'%')+'</div><div class="colc2">'+noesvacio(simulacion[4][11],'%')+'</div></li></ul>';
		
		//DEDUCCIÓN ANTES 2007
		//str_comparativa+='<ul class="blanco"><li><div class="colc1">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym> dos primeros años</div><div class="colc2">'+noesvacio(simulacion[1][13],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][13],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][13],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][13],'&euro;')+'</div></li></ul>';
		//str_comparativa+='<ul class="gris"><li><div class="colc1">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym> a partir tercer año</div><div class="colc2">'+noesvacio(simulacion[1][14],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][14],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][14],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][14],'&euro;')+'</div></li></ul>';
		//DEDUCCION DESPUES 2007
//		str_comparativa+='<ul class="blanco"><li><div class="colc1">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym></div><div class="colc2">'+noesvacio(simulacion[1][13],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[2][13],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[3][13],'&euro;')+'</div><div class="colc2">'+noesvacio(simulacion[4][13],'&euro;')+'</div></li></ul>';
		
//		str_comparativa+='<ul class="blanco"><li><div class="colc1"><a href="javascript:eliminasimulaciones()"><img src="images/eliminar.gif" alt="Eliminar todas las simulaciones existentes en la tabla" /></a></div><div class="colc2">'+enlace(simulacion[1][1],1)+'</div><div class="colc2">'+enlace(simulacion[2][1],2)+'</div><div class="colc2">'+enlace(simulacion[3][1],3)+'</div><div class="colc2">'+enlace(simulacion[4][1],4)+'</div></li></ul>';
//		str_comparativa+='<ul class="blanco"><li><div class="colc1"><a href="javascript:eliminasimulaciones()"><img src="images/eliminar.gif" alt="Eliminar todas las simulaciones existentes en la tabla" /></a></div><div class="colc2"></div><div class="colc2"></div><div class="colc2"></div><div class="colc2"></div></li></ul>';
		

//		str_comparativa+=str_pietabla2col;
//		str_comparativa+='<div style="margin:0px 0px 5px 0px;font-size:9px;color:#A5A5A5;text-decoration:none">Recuerda que esta simulación se realiza meramente a efectos informativos, no constituyendo una oferta en firme por parte de Cajastur.</div>';		

		str_comparativa = cabeza + cuerpo + pie;

		document.getElementById('tablacomparativa').innerHTML=str_comparativa;
	}
	
function eliminasimulaciones() {
	for (var h=0;h<15;h++) {
		simulacion[1][h]='';
		simulacion[2][h]='';
		simulacion[3][h]='';
		simulacion[4][h]='';
	}
	escribircomparativa();
	numsimulaciones=0;
}

var deduccion1='';
var deduccion2='';
var deduccion3='';

function escribirimpacto(num)
	{
		var periodocuota=document.getElementById('formufinanciero').PERIODOINTERESFIJO.options[document.getElementById('formufinanciero').PERIODOINTERESFIJO.selectedIndex].value;
		var cuota1='';
		var cuota2='';
		var cuota3='';
		var valor='';

		//while(filacuotainicial.indexOf(',')!=-1)
			filacuotainicial=filacuotainicial.replace('.','');
		filacuotainicial=filacuotainicial.replace(',','.');
		filacuotaposterior=filacuotainicial;
				
		switch(periodocuota)
		{
			case '6':  cuota1=(parseFloat(filacuotainicial)*6)+(parseFloat(filacuotaposterior)*6);
				   if(cuota1>9015) {cuota1=9015}
				   deduccion1=cuota1*0.15;
				   deduccion2=cuota1*0.15;
				   deduccion3=cuota1*0.15;
					 break;
			
			case '12': cuota1=parseFloat(filacuotainicial)*12;
				   if(cuota1>9015.18) {valor=9015.18}
				   else {valor=cuota1-4507.59}
				   			
				   if(cuota1<4507.59) {
				   	deduccion1=cuota1*0.25;
				   }
				   if(cuota1>4507.59) {
				   	deduccion1=(1126.8975)+(valor*0.15);
				   }
				   
				   cuota2=parseFloat(filacuotaposterior)*12;
				   if(cuota1<4507.59) {
				   	deduccion2=cuota2*0.25;
				   }
				   if(cuota1>4507.59) {
				   	deduccion2=(1126.8975)+(valor*0.15);
				   }
				   
				   cuota3=parseFloat(filacuotaposterior)*12;
				   if(cuota1<4507.59) {
				   	deduccion3=cuota3*0.20;
				   }
				   if(cuota1>4507.59) {
				   	deduccion3=(901.518)+(valor*0.15);
				   }				   
		};	
		filacuotainicial=formatodec(filacuotainicial);	
		filacuotaposterior=formatodec(filacuotaposterior);
				
		
		var str_impacto;		
//		str_impacto='<ul class="enlacesinf"><li><a href="javascript:mostrarcapa(0)">Aspectos financieros</a><img src="../../images/sizer.gif" alt="" width="6" height="1" /></li><li>|<img src="../../images/sizer.gif" alt="" width="6" height="1" /><strong>Impacto fiscal</strong></li></ul>';
//		str_impacto='<div class="separador"><img src="../../images/sizer.gif" alt="" width="1" height="1" /></div>';		
		str_impacto='<div class="tabla2col">'+
					'<div class="azuloscuro">Impacto fiscal</div>';		
		str_impacto+='<div class="separador">&nbsp;</div>';
		/* deducciones anteriores a 2007 */
		//str_impacto+='<ul class="blanco"><li><div class="col1">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym> dos primeros años</div><div class="col2" id="año1">'+formatodec(deduccion1)+' &euro;</div></li></ul>';
		//str_impacto+='<ul class="gris"><li><div class="col1">Deducción segundo <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym> año</div><div class="col2" id="año2">'+formatodec(deduccion2)+'</div></li></ul>';
		//str_impacto+='<ul class="gris"><li><div class="col1">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym> a partir tercer año</div><div class="col2" id="año3">'+formatodec(deduccion3)+' &euro;</div></li></ul></div>';

		
		/* deducciones posteriores a 2007 */
		str_impacto+='<div class="col1 blanco">Deducción anual <acronym lang="es" title="Impuesto de la Renta sobre las Personas Físicas">IRPF</acronym> (toda la vida del préstamo)</div><div class="col2" id="año1">'+formatodec(deduccion1)+' &euro;</div>';
		
		str_impacto+='<div class="separador">&nbsp;</div>';
		str_impacto+='<div class="deducciones">Las deducciones calculadas sólo son de aplicación para aquellos contribuyentes que compren su primera vivienda habitual.<br /><br />El periodo durante el que pueden practicarse las deducciones se computan de fecha a fecha desde el momento de compra de la vivienda.<br /><br />Los resultados aquí obtenidos son sólo una estimación orientativa, habiendo sido calculados para el Principado de Asturias, pudiendo variar para otras Comunidades Autónomas.</div>';
		str_impacto+='</div><div class="separador"><img src="../../../images/sizer.gif" alt="" width="1" height="1" /></div></div>';

		// Evoluciones según la simulación
		if (num==0) {str_impacto1=str_impacto;}		
		if (num==1) {str_impacto2=str_impacto;}
		if (num==2) {str_impacto3=str_impacto;}
		if (num==3) {str_impacto4=str_impacto;}						
		document.getElementById('impacto').innerHTML=str_impacto;
	}
	
function mostrarcapa(num) {
	if (num==0) {document.getElementById('resultadofinanciero').style.display='block';document.getElementById('impacto').style.display='none';document.getElementById('tablacomparativa').style.display='block';}
	if (num==1) {document.getElementById('resultadoimporte').style.display='none';document.getElementById('tablacomparativa').style.display='none';document.getElementById('impacto').style.display='block';document.getElementById('resultadofinanciero').style.display='none';}
}

function formatodec(numero) 
	{
		var entero;
		var decimal;
		var coma;
		var final;

		numero=String(Math.round(numero*100)/100);
		var pos=numero.indexOf(".");
		if (pos==-1)
			{decimal=0;coma="";}
		else
			{decimal=numero.substr(pos,3);coma=","+decimal.substr(1,2);};
		
		if (pos==-1)
			{entero=numero;}
		else
			{entero=numero.substring(0,pos);};

		contador=1;
		for (pos=(entero.length-1);pos>0;pos--)
			{
				contador++
				if (contador>3)
					{
						entero=entero.substring(0,pos)+"."+entero.substr(pos);
						contador=1;
					}
			}
		// Ponemos los dos últimos decimales si fuese necesario
		if(coma=='')
			coma=',00';
		if(coma.length<3)
			coma+='0';	
		numero=entero+coma;
		return (numero);
	}
	
	
function escribeeuribor(){
	eur=formatodec(euribor);
	document.write('Euribor <a href="#infoeuribor"><img src="images/info.gif" alt="más información del euribor" /></a> con diferencial de <input type="text" name="DIFERENCIAL" id="DIFERENCIAL" size="5" maxlength="5" /> %');
}
function escribeeuriborCompleto(){
	document.write('<div class="textonormal">Tipo de interés del préstamo</div>');
	document.write('<div class="textointro">');
	eur=formatodec(euribor);
	document.write('<label for="DIFERENCIAL">Euribor <a href="#infoeuribor"><img src="images/info.gif" alt="más información del euribor" /></a> con diferencial de </label><input type="text" name="DIFERENCIAL" id="DIFERENCIAL" size="5" maxlength="5" /> %');
	document.write('</div>');
}
function escribeeuribor2(){
	Eur=formatodec(euribor);
	document.write('<img src="images/info.gif" alt="Cuota orientativa con Euribor al '+eur+'% y el diferencial introducido" />');	
}
function escribecomentarioeuribor(){
	document.write('<br />'+eur+'% último valor oficial del Euribor publicado.');
}

