var Simulador = (function()
{
	
	var f, taxj, tac=0.02;
	
	return {
		
		init: function()
		{
			f = $("formSimulador");
			taxj = new Number(f.taxj.value);
			
			$("btOk").e("click", _d( this, this.doOk ) );
			$("btReset").e("click", _d( this, this.reset ) );
			
			this.reset();
		},
		
		money2int: function(v)
		{
			v = v.toString().split("R$").join("").trim();
			
			v = v.split(",");
			if(v.length > 1) 
			{
				v[0] = v[0].split(".").join("");
				v[1] = v[1].substr(0, 2);
			}
			
			v = new Number(v.join("."));
			
			return v;
		},
		
		int2money: function(v)
		{
			return "R$ " + number_format(v, 2, ",", ".");
		},
		
		doOk: function(e)
		{
			var t = this.money2int(f.v.value);
			var n = new Number(f.p.value);
			
			if(t < 200 || t > 20000)
			{
				alert("A valor financiado deve estar entre R$ 200,00 a R$ 20.000,00.");
				
				Event.cancel(e);
				return false;
			}
			
			t = t + (t * tac); 
			
			var r = this.calc(t, n);

			var rm = this.int2money(r);
			
			$("#resposta-simulador strong").first().innerHTML = rm;
			
			$("resposta-simulador", "btReset", "btOk").apply("toggle");
			
			equalColumns();
			
			Event.cancel(e);
			return false;
		},
		
		calc: function(t, n)
		{
			i = taxj;

			p = t * i * (Math.pow((1+i), n));
			p = p / (Math.pow((1+i), n) - 1);

			return p;
		},
		
		reset: function()
		{
			$("resposta-simulador").toggle();
			$("btReset").toggle();
			$("btOk").css({"display": "block"});
			
			equalColumns();
		}
		
	};
	
})();

_c( _d( Simulador, Simulador.init) );

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
