/*
###################################################################
##        VARIÁVEIS PARA O CÁLCULO, CONFORME ÁREA ADM
###################################################################
*/
var TipoTaxaID = 1;
var TipoCorrecaoID = 1;
var PeCorrecao = eval('0.0005000000');
var VrTarifaMensal = eval('25.00');
var VrTarifaInicial = eval('700.00');
var PeDFI = eval('0.0001200000');
var PeMIP = eval('0.0002670000');
var PeRenda = eval('0.3000000000');
var VrEntrada = eval('30000.00');
var NuPrazoPadrao = eval('30');

var VrMin1 = eval('0.00');
var VrMax1 = eval('120000.00');
var PeJuros1 = eval('0.0850000000');

var VrMin2 = eval('120001.00');
var VrMax2 = eval('500000.00');
var PeJuros2 = eval('0.1050000000');

var VrMin3 = eval('500001.00');
var VrMax3 = eval('10000000.00');
var PeJuros3 = eval('0.1100000000');
//###################################################################

onerror = handleErr;        // se der algum erro no javascript da página, a funçao handleErr será executada

/*
###################################################################
##        VARIÁVEIS DE RETORNO
###################################################################
*/
var VrPrimeiraPrestacao = '';
var VrUltimaPrestacao = '';
var RendaNecessaria = '';
//###################################################################

function SagaceObtemEntradaDefault()
{
	return fmtNumero(VrEntrada, 0);
}

function SagaceObtemPrazoDefault()
{
	return fmtNumero(NuPrazoPadrao, 0);
}

function SagaceCalcula1aPrestacao( vlrImovel, vlrEntrada, iPrazo )
{
    // Realiza a simulação
    calculaSimulacao(vlrImovel, vlrEntrada, iPrazo);
	
	return fmtNumero(VrPrimeiraPrestacao, 0);
}

function SagaceCalculaUltimaPrestacao( vlrImovel, vlrEntrada, iPrazo )
{
    // Realiza a simulação
    calculaSimulacao(vlrImovel, vlrEntrada, iPrazo);
	
	return fmtNumero(VrUltimaPrestacao, 0);
}

function SagaceCalculaRendaNecessaria( vlrImovel, vlrEntrada, iPrazo )
{
    // Realiza a simulação
    calculaSimulacao(vlrImovel, vlrEntrada, iPrazo);

	return fmtNumero(RendaNecessaria, 0);
}

function fn_TaxaJurosMensal(TaxaTipo, TaxaJuros)
{
    if (TaxaTipo == 1)
	    return (Math.pow((TaxaJuros+1), (1/12))) - 1.0;
    else if (TaxaTipo == 2)
	    return TaxaJuros / 12.0;
}

function fn_TaxaJuros(vlrImovel)
{
    if (vlrImovel >= VrMin1 && vlrImovel <= VrMax1)
        return PeJuros1;
    else if (vlrImovel >= VrMin2 && vlrImovel <= VrMax2)
        return PeJuros2;
    else
        return PeJuros3;
}


function calculaSimulacao(vlrImovel, vlrEntrada, iPrazo)
{
    VrPrimeiraPrestacao = '';
    VrUltimaPrestacao = '';
    RendaNecessaria = '';

    var TemErro = false;
    if (!ValidaNumero(vlrImovel)) {
        window.alert('Valor do Imóvel não é um número valido');
        TemErro = true;
    }
    
    if (!ValidaNumero(vlrEntrada)) {
        window.alert('Valor da Entrada não é um número valido');
        TemErro = true;
    }
    
    if (!ValidaNumero(iPrazo)) {
        window.alert('Prazo de financiamento não é um número valido');
        TemErro = true;
    }

    if (!TemErro)
    {
        var vlrImovel   = NumeroCalculo(vlrImovel);
        var vlrEntrada  = NumeroCalculo(vlrEntrada);
        
        var ValorEmprestimo = vlrImovel - vlrEntrada;
        var PrazoMeses = iPrazo * 12;
        var TaxaJuros = fn_TaxaJuros(vlrImovel);
        var TaxaJurosMensal = fn_TaxaJurosMensal(TipoTaxaID, TaxaJuros);

        var SeguroDIF = PeDFI * vlrImovel;
        var Amortizacao = ValorEmprestimo / PrazoMeses;

        // Calculo para a Primeira Prestação
        var Juros = ValorEmprestimo * TaxaJurosMensal;
        var Prestacao = Juros + Amortizacao;
        var SeguroMIP = PeMIP * ValorEmprestimo;
        var Total = Prestacao + SeguroMIP + SeguroDIF + VrTarifaMensal;
        
        VrPrimeiraPrestacao = Total;
        RendaNecessaria = VrPrimeiraPrestacao / PeRenda;
        
        // Calculo para a Última Prestação
        
        // CASO O TIPO DE CORREÇÃO SERÁ PRÉ-CALCULADO O ÍNDICE É DEFINIDO COMO 0 (ZERO)
        if (TipoCorrecaoID == 2)
            PeCorrecao = 0;
        
        var Correcao;
        var SaldoDevedor = ValorEmprestimo;
        
        for (mes = 1; mes <= PrazoMeses; mes++)
        {
            Correcao = SaldoDevedor * PeCorrecao;
            Juros = (Correcao + SaldoDevedor) * TaxaJurosMensal;
            Amortizacao = Amortizacao * (1 + PeCorrecao);
            Prestacao = Juros + Amortizacao;
            SeguroMIP = PeMIP * SaldoDevedor;
            SeguroDIF = SeguroDIF * (1 + PeCorrecao);
            
            Total = Prestacao + SeguroMIP + SeguroDIF + VrTarifaMensal;
	        SaldoDevedor = SaldoDevedor + Correcao - Amortizacao;
	        if (SaldoDevedor < 0)
	            SaldoDevedor = 0;
        }

        VrUltimaPrestacao = Total;
    }
}
















function fmtNumero(numero, decimal) {
    return FormatNumber(numero, decimal, 1, 0, 1);
}

function FormatNumber(num, decimalNum, bolLeadingZero, bolParens, bolCommas)
/**********************************************************************
IN:
NUM - the number to format
decimalNum - the number of decimal places to format the number to
bolLeadingZero - true / false - display a leading zero for
numbers between -1 and 1
bolParens - true / false - use parenthesis around negative numbers
bolCommas - put commas as number separators.
 
RETVAL:
The formatted number!
**********************************************************************/
{
    //return BuscaImovel.FormataNumero(num, decimalNum, callback_FormataNumero);

    if (isNaN(parseInt(num))) return 0;

    var tmpNum = num;
    var iSign = num < 0 ? -1 : 1; 	// Get sign of number

    // Adjust number so only the specified number of numbers after
    // the decimal point are shown.
    tmpNum *= Math.pow(10, decimalNum);
    tmpNum = Math.round(Math.abs(tmpNum))
    tmpNum /= Math.pow(10, decimalNum);
    tmpNum *= iSign; 				// Readjust for sign

    // Create a string object to do our formatting on
    var tmpNumStr = new String(tmpNum);

    var iComma = tmpNumStr.indexOf(".");

    if ((tmpNumStr.length - iComma) == 2 && iComma != -1)
        tmpNumStr = tmpNumStr + "0";

    if (iComma == -1) {
        if (decimalNum != 0) {
            tmpNumStr = tmpNumStr + "."
            for (i = 0; i < decimalNum; i++)
                tmpNumStr = tmpNumStr + "0";
        }
    } else {
        for (i = (tmpNumStr.length - iComma); i <= decimalNum; i++)
            tmpNumStr = tmpNumStr + "0";
    }

    // See if we need to strip out the leading zero or not.
    if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
        if (num > 0)
        tmpNumStr = tmpNumStr.substring(1, tmpNumStr.length);
    else
        tmpNumStr = "-" + tmpNumStr.substring(2, tmpNumStr.length);

    if (num < 0) tmpNumStr = tmpNumStr.substring(1, tmpNumStr.length);

    // See if we need to put in the commas
    if (bolCommas && (num >= 1000 || num <= -1000)) {
        var iStart = tmpNumStr.indexOf(".");

        if (iStart < 0)
            iStart = tmpNumStr.length;

        iStart -= 3;
        while (iStart >= 1) {
            tmpNumStr = tmpNumStr.substring(0, iStart) + "," + tmpNumStr.substring(iStart, tmpNumStr.length)
            iStart -= 3;
        }
    }

    // See if we need to use parenthesis
    if (num < 0) {
        if (tmpNumStr == '') {
            tmpNumStr = 0;
        } else {
            if (bolParens)
                tmpNumStr = "(" + tmpNumStr + ")";
            else
                tmpNumStr = "-" + tmpNumStr;
        }
    }

    tmpNumStr = NumeroSeparadores(tmpNumStr);

    return tmpNumStr; 	// Return our formatted string!
}

function NumeroCalculo(numero) {

    var novo = LimpaNumero(numero);

    if (isNaN(novo)) return 0;
    else return eval(novo);
}

function ValidaNumero(numero) {

    var novo = LimpaNumero(numero);
    
    if (isNaN(novo)) return false;
    else return true;
}

function handleErr(msg,url,l)
{
    txt ="Foi encontrado um erro nesta pagina.\n\n"
	txt+="Erro: " + msg + "\n"
	txt+="Pagina: " + url + "\n"
	txt+="Linha: " + l + "\n\n"
	txt+="Pedimos que anote os dados acima e informe-nos pelo contato do site."
	alert(txt)
	return true
}

function LimpaNumero(numeroLN)
{
    var tmpNumStrLN = '';
    var tmpStrLN = '';

    for (iLN = 0; iLN < numeroLN.length; iLN++) {
        tmpStrLN = numeroLN.substr(iLN, 1);
        if (tmpStrLN == ',') tmpNumStrLN += '.';
        else if (!isNaN(tmpStrLN)) tmpNumStrLN += tmpStrLN;
    }

    return tmpNumStrLN;
}

function NumeroSeparadores(numeroNS)
{
    var tmpNumStrNS = '';
    var tmpStrNS = '';

    for (iNS = 0; iNS < numeroNS.length; iNS++) {
        tmpStrNS = numeroNS.substr(iNS, 1);
        if (tmpStrNS == '.') tmpNumStrNS += ',';
        else if (tmpStrNS == ',') tmpNumStrNS += '.';
        else if (!isNaN(tmpStrNS)) tmpNumStrNS += tmpStrNS;
    }

    return tmpNumStrNS;
}
