var uC = null;
var m = new Array();
var antes = "El valor del campo '";
var despues = "' debe ser un número mayor que cero y no puede contener ni puntos ni comas.";
var despuesCero = "' debe ser un número mayor o igual que cero y no puede contener ni puntos ni comas.";
var despuesCeroCien = "' debe ser un número entre cero y cien (0 y 100).";
var despuesUnoCincuenta = "' debe ser un número entre uno y treinta (1 y 30).";
var g = new Array();
var mTabla = false;

g[ 0] = [ "tasaDeInteres", "PorcentajeCuotaInicial", "PorcentajeCreditoEnCuotasExtra"];

m[ "precioInmueble"] = antes + "Precio inmueble" + despues;
m[ "tasaDeInteres"] = antes + "Tasa de interés" + despuesCeroCien;
m[ "PorcentajeCuotaInicial"] = antes + "% cuota inicial" + despuesCeroCien;
m[ "PorcentajeCreditoEnCuotasExtra"] = antes + "% crédito en cuotas extra" + despuesCeroCien;
m[ "CuotaInicial"] = antes + "Cuota inicial" + despuesCero;
m[ "CreditoEnCuotasExtra"] = antes + "Crédito en cuotas extra" + despuesCero;
m[ "PlazoDePago"] = antes + "Plazo de pago" + despuesUnoCincuenta;

function verificarMonto( campo, a, positivo) {
    var v;
    var r;

    v = campo.value;

    campo.value = unformatNumber( v);
    r = checkInteger( campo, a, false);

    if( r) {
        campo.value = formatNumber( campo.value);
    } else {
        campo.value = v;
        campo.focus();
        campo.select();
    }

    return r;
}

function verificarCampo( campo) {
    var r;
    var s = campo.name;
    var a = m[ s];
	var v1, v2, v3;
    var v;

	with( document.calc) {
        if( s == "precioInmueble") {
            r = verificarMonto( campo, a, true);
        } else if( s == "PlazoDePago") {
            r = checkPositiveInteger( campo, a, false);
            if( r) {
                r = ( parseInt( campo.value) <= 30);
                if( !r) {
                    warnInvalid( campo, a);
                }
            }
        } else if ( g[ 0].indexOf( s) != -1) {
            r = checkInteger( campo, a, false);
            if( r) {
                r = ( parseInt( campo.value) <= 100);
                if( !r) {
                    warnInvalid( campo, a);
                } else {
			        if( s == "PorcentajeCuotaInicial" ) {
			        	r = verificarCampo( precioInmueble);
			            if( r) {
			            	v1 = parseInt( campo.value);
			            	v2 = unformatNumber( precioInmueble.value);
			                CuotaInicial.value = Math.round( v2 * v1 / 100);
			            }

			        } else if ( s == "PorcentajeCreditoEnCuotasExtra") {
			        	r = verificarCampo( precioInmueble) && verificarCampo( CuotaInicial);
			            if( r) {
			            	v1 = parseInt( campo.value);
			            	v2 = parseFmtNumber( precioInmueble.value);
			            	v3 = parseFmtNumber( CuotaInicial.value);
			            	v2 = v2 - v3;

			                CreditoEnCuotasExtra.value = Math.round( v2 * v1 / 100);
			            }
                	}
                }
            }
        } else if ( s == "CuotaInicial") {
            r = verificarMonto( campo, a, false) && verificarCampo( precioInmueble);

            if( r) {

            	v1 = parseFmtNumber( campo.value);
            	v2 = parseFmtNumber( precioInmueble.value);
                r = ( v1 < v2);
                if( !r) {
                    warnInvalid( campo, "La cuota inicial debe ser menor al precio del inmueble.");

                } else if( v2 > 0){
                    PorcentajeCuotaInicial.value = Math.round( v1 / v2 * 100);
                }
            }

        } else if ( s == "CreditoEnCuotasExtra") {
            r = verificarMonto( campo, a, false) && verificarCampo( precioInmueble) && verificarCampo( CuotaInicial);

            if( r) {
            	v1 = parseFmtNumber( campo.value);
            	v2 = parseFmtNumber( precioInmueble.value);
            	v3 = parseFmtNumber( CuotaInicial.value);
            	v2 = v2 - v3;

                r = ( v1 < v2);
                if( !r) {
                    warnInvalid( campo, "El crédito en cuotas extra debe ser menor al precio del inmueble menos la inicial.");

                } else if( v2 > 0){
                    PorcentajeCreditoEnCuotasExtra.value = Math.round( v1 / v2 * 100);
                }
            }
		}
        //NN6
        /*if( !r) {
            uC = campo;
            setTimeout( "uC.focus()", 1);
        }*/
	}
    return r;
}

function verificarValores( frm) {
	var b = true;
    var e = frm.elements;
    var s;

    for( var i = 0; i < e.length; i++) {
        s = e[ i].name;
        if( !isEmpty( m[ s]))
            b = b && verificarCampo( e[ s]);
    }

	return b;
}

function pmt( r, n, p) {
    if( r > 0) {
        return ( p * r) / ( 1 - Math.pow( r + 1, -n));
    } else {
        return p / n;
    }
}

function actualizarValores( campo) {
    var rs = verificarValores( campo.form);
    var p, r, n, ex, ci, cm, exa, mf;

    with( document.calc) {

        if( rs) {
            p = parseFmtNumber( precioInmueble.value);

            ci = p * ( parseInt( PorcentajeCuotaInicial.value) / 100);
			mf = p - ci;

            ex = ( p - ci) * ( parseInt( PorcentajeCreditoEnCuotasExtra.value) / 100);
            r = parseInt( tasaDeInteres.value) / 1200;
            n = parseInt( PlazoDePago.value) * 12;

            p = p - ci - ex;
            cm = pmt( r, n, p);
            exa = pmt( r * 12, n / 12, ex);


            MontoFinanciar.value = formatNumber( mf);
            CuotaInicial.value = formatNumber( ci);
            CreditoEnCuotasExtra.value = formatNumber( ex);
            CuotaMensual.value = formatNumber( cm);
            CuotaExtraAnual.value = formatNumber( exa);
            IngresosFamiliaresRequeridos.value = formatNumber( ( cm * 12 + exa) / 0.33);
        }
    }

    return rs;
}

function calcularCampos( campo) {
	//if( document.all) { //IE
        var rs = verificarCampo( campo);

        //if( rs) {
          //  rs = actualizarValores( campo)
        //}

        return rs;
    /* } else {
     	return true;
     }*/
}

function escribirTabla() {

	var t, tit, t_include;
	var s = "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
	var i;
    var p, r, n, ex, ci, cm, exa, pa, ri, ppi, rix, c;

	with( document) {
    	if( document.getElementById) { //DOM
    		t = getElementById( "tabla");
            tit = getElementById( "titulo");
    	} else { //IE4
    		t = all.tabla;
            tit = all.titulo;
    	}

    	with( calc) {
			if( !actualizarValores( precioInmueble)) return;

	        p = parseFmtNumber( precioInmueble.value);
	        ci = p * ( parseInt( PorcentajeCuotaInicial.value) / 100);

	        ex = ( p - ci) * ( parseInt( PorcentajeCreditoEnCuotasExtra.value) / 100);
	        r = parseInt( tasaDeInteres.value) / 1200;
	        n = parseInt( PlazoDePago.value) * 12;

	        p = p - ci - ex;
	        cm = pmt( r, n, p);
	        exa = pmt( r * 12, n / 12, ex);
	        pa = p;

        	s = s + "<tr align='center' class='ItensCalcu'>";
        	s = s + "<td>Cuota</td>";
        	s = s + "<td>Intereses</td>";
        	s = s + "<td>Abono a Capital</td>";
        	s = s + "<td>Capital</td>";
        	s = s + "</tr><tr><td bgcolor='#990000' colspan='4'></td></tr>";

	        for( i = 1; i <= n; i++) {

	        	ri = p * r;
	        	ppi = cm - ri;
	        	p = p - ppi;

	        	c = i % 2;

				if( i % 12 == 0) {
					rix = ppi + ri + exa;
					c = 2;
				} else
					rix = ppi + ri;

	        	s = s + "<tr  class='gris" + c + "' align='center'>";
	        	s = s + "<td>" + i + "</td>";
	        	s = s + "<td>" + formatNumber( ri) + "</td>";
	        	s = s + "<td>" + formatNumber( ppi) + "</td>";
	        	s = s + "<td>" + formatNumber( p) + "</td>";
	        	s = s + "</tr><tr><td bgcolor='#990000' colspan='4'></td></tr>";
	        }
		}

	    s = s + "</table><br>";
        tit.innerHTML = "<a class='amorti' name='o' href='#o'>Tabla de Amortización</a>";
    	t.innerHTML = s;

        if( document.all) {
            document.all[ "o"].click();
        } else {
    	    window.location.href = "#o";
        }

        mTabla = true;

        //document.izq_boton_h.height = t.offsetHeight;
	}
}

function calcularClick( c) {/*
	with( document.calc)
    	if( ( uC == CuotaInicial) || ( uC == CreditoEnCuotasExtra))
    		if( !verificarCampo( uC))
    			return false;*/

    if( document.layers) {
        actualizarValores( c);
    } else {
        if( mTabla)
            escribirTabla();
        else
            actualizarValores( c);
    }
}

function calcSubmit() {
	if( document.layers) {
        with( document.calc)
            if( actualizarValores( precioInmueble)) {
                precioInmueble.value = unformatNumber( precioInmueble.value);
                return true;
            } else
                return false;
	} else {
		escribirTabla();
		return false;
	}
}

function bodyLoad() {
	if( location.href.charAt( location.href.length - 2) != '#') {

        window.focus();
        window.moveTo( Math.round( ( screen.availWidth - 440) / 2), 0);
        window.resizeTo( 440, screen.availHeight);
		campoFocus( document.calc.precioInmueble);
	}
}


function solicitudPrestamoClick( sender) {
    if( actualizarValores( sender))
        location.href = '/solicitud_prestamo.do?monto=' +
            unformatNumber( sender.form.MontoFinanciar.value) + '&plazo=' +
                parseInt( sender.form.PlazoDePago.value)
}

function campoFocus( f) {
    f.value = unformatNumber( f.value);
    f.oldValue = f.value;
    f.focus();
    f.select();

    return true;
}

function campoBlur( f) {
    uC = this;

    if( f.oldValue == f.value)
        f.value = formatNumber( f.value);
}

var prestamos = true;
