﻿function Financiamento(serverclass) {

    var codAnuncio = 0;
    var listaParcelas = new Hashtable();
    var me = this;
    
    var Constructor = function() {
        initialize();
        if (parseInt($get('sltNumeroParcelas')) > 0)
            me.calcularFinanciamento();
    };

    var clearCombo = function(comboName) {
        while ($(comboName).childNodes.length > 0) $(comboName).removeChild($(comboName).firstChild);
        $(comboName).options[0] = new Option('Selecione', 0);
        $set(comboName, 0);
    };

    var initialize = function() {
        // Formated fields
        $('txtAnoVeiculo').numbersOnly();
        $('txtEntradaPorcent').setMask('##,##');
        $('txtEntradaPorcent').numbersOnly();
        $('txtValorTotalVeiculo').formatCurrency(2);
        $('txtEntradaValor').formatCurrency(2);
        $('txtCPFFinanciamento').numbersOnly();

        // Box
        $('sFinResposta').style.display = 'none';
        $('sFinDadosUsuario').style.display = 'none';

        setParcelas();
    };

    var reinitialize = function() {
        unBlockBoxInicial();
        // Box
        $('sFinResposta').style.display = 'none';
        $('sFinDadosUsuario').style.display = 'none';

        // Box Dados do Usuário
        $set('txtNomeFinanciamento', '');
        $set('txtCPFFinanciamento', '');
        $set('txtEmailFinanciamento', '');
        $set('txtConfirmarEmailFinanciamento', '');
        $set('txtTelefoneFinanciamento', '');
    };

    var blockBoxInicial = function() {
        $('txtAnoVeiculo').disabled = 'disabled';
        $('txtValorTotalVeiculo').disabled = 'disabled';
        //$('txtEntradaValor').disabled = 'disabled';
        //$('txtEntradaPorcent').disabled = 'disabled';
        //$('sltNumeroParcelas').disabled = 'disabled';
    };

    var unBlockBoxInicial = function() {
        $('txtAnoVeiculo').disabled = '';
        $('txtValorTotalVeiculo').disabled = '';
        $('txtEntradaValor').disabled = '';
        $('txtEntradaPorcent').disabled = '';
        $('sltNumeroParcelas').disabled = '';
    };

    var clearFieldsSFin = function() {
        // Box Inicial
        $set('txtAnoVeiculo', '');
        $set('txtValorTotalVeiculo', '0,0');
        $set('txtEntradaValor', '0,0');
        $set('txtEntradaPorcent', '20,00%');
        clearCombo('sltNumeroParcelas');

        $set('txtValorParcela', '');

        // Box Dados do Usuário
        $set('txtNomeFinanciamento', '');
        $set('txtCPFFinanciamento', '');
        $set('txtEmailFinanciamento', '');
        $set('txtConfirmarEmailFinanciamento', '');
        $set('txtTelefoneFinanciamento', '');

        $('sFinResposta').style.display = 'none';
        $('sFinDadosUsuario').style.display = 'none';
    };

    this.verificaPorcentagem = function() {
        if ($get('txtEntradaPorcent').trim() != '') {
            if (parseInt($get('txtEntradaPorcent')) > 100) {
                alert('O valor máximo para a porcentagem (%) é 100');
                $set('txtEntradaPorcent', '');
            }
        }
    };

    var verificaDadosIniciais = function() {

        if ($get('txtAnoVeiculo').trim() == '') {
            alert('Preencha o ano do veículo');
            $('txtAnoVeiculo').focus();
            return false;
        }

        if ($get('txtValorTotalVeiculo').trim() == '' && parseInt($get('txtValorTotalVeiculo').trim()) > 0) {
            alert('Preencha o valor total do veículo');
            $('txtValorTotalVeiculo').focus();
            return false;
        } else {
            var valorTotal = parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace('.', '').trim());
            var valorEntrada = parseFloat($get('txtEntradaValor').replace('.', '').replace('.', '').trim());

            if (valorEntrada >= (valorTotal - parseFloat($get('hValorMinFin').replace('.', '').replace('.', '')))) {
                alert('O valor mínimo para o financiamento é de ' + $get('hValorMinFin'));
                $set('txtEntradaValor', '');
                $('txtEntradaValor').focus();
                return;
            }
        }

        if ($get('txtEntradaValor').trim() == '' && parseInt($get('txtEntradaValor').trim()) > 0) {
            alert('Preencha o valor de entrada para o financiamento');
            return false;
        }

        if ($get('txtEntradaPorcent').trim() == '' && parseInt($get('txtEntradaPorcent').trim()) > 0) {
            alert('Preencha o valor de entrada para o financiamento');
            return false;
        }

        if ($('sltNumeroParcelas').selectedIndex <= 0) {
            alert('Selecione o número de parcelas');
            return false;
        }

        if (parseInt($get('txtEntradaValor')) == 0) {
            alert('O valor mínimo de entrada deve ser de 20% do valor total');
            calcular20Porcent();
            return false;
        }

        return true;
    }


    this.getParcelas = function() {
        if ($get('txtAnoVeiculo').trim() != '') {
            serverclass.GetParcelas(parseInt($get('txtAnoVeiculo')), function(res) {
                if (res.error) return alert(res.error.message);
                if (res.value.rows.length > 0) {
                    listaParcelas = new Hashtable();
                    clearCombo('sltNumeroParcelas');
                    $set('hValorMinFin', res.value.rows[0].ValorMinimo);
                    for (var i = 0; i < res.value.rows.length; i++) {
                        $('sltNumeroParcelas').options[$('sltNumeroParcelas').options.length] = new Option(res.value.rows[i].NumeroParcelas + 'x', res.value.rows[i].NumeroParcelas);
                        listaParcelas.add(res.value.rows[i].NumeroParcelas, res.value.rows[i].CodTabelaFinanciamentoParcela);
                    }
                } else { alert('Nenhum financiamento se enquadra no ano do veículo'); }
            });
        }
    };


    var setParcelas = function() {
        if ($get('txtAnoVeiculo').trim() != '') {
            serverclass.GetParcelas(parseInt($get('txtAnoVeiculo')), function(res) {
                if (res.error) return alert(res.error.message);
                if (res.value.rows.length > 0) {
                    listaParcelas = new Hashtable();
                    $set('hValorMinFin', res.value.rows[0].ValorMinimo);
                    for (var i = 0; i < res.value.rows.length; i++)
                        listaParcelas.add(res.value.rows[i].NumeroParcelas, res.value.rows[i].CodTabelaFinanciamentoParcela);
                }
            });
        }
    };

    var checkFinanciamentoFields = function() {
        if (parseInt($get('txtAnoVeiculo')) <= 0) {
            alert('Informe o ano do veículo');
            $('txtAnoVeiculo').focus();
            return false;
        }

        if (parseFloat($get('txtValorTotalVeiculo')) <= 0 || $get('txtValorTotalVeiculo').trim() == '') {
            alert('Informe o valor total do veículo');
            $('txtValorTotalVeiculo').focus();
            return false;
        }
        return true;
    };

    var calcularCET = function() {

        var montante_float = parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace(',', '.')) - parseFloat($get('txtEntradaValor').replace('.', '').replace(',', '.'));
        var parcela_float = parseFloat($get('txtValorParcela').replace('.', '').replace(',', '.'));
        var per_int = parseInt($get('sltNumeroParcelas'));

        juros_inicial = parseFloat("-1");
        juros_final = parseFloat("99999");
        suposto_juros = parseFloat("0");
        suposto_parcela = parseFloat("0");
        var cont = 1;
        var achou = false;
        while (true) {
            suposto_juros = (juros_final + juros_inicial) / 2;
            suposto_parcela = (montante_float * suposto_juros) / (1 - Math.pow(1 / (1 + suposto_juros), per_int));
            suposta_diferenca = Math.abs(parcela_float - suposto_parcela);
            if (suposta_diferenca > 0.000000001) {
                if (suposto_parcela > parcela_float) {
                    juros_final = suposto_juros;
                }
                else {
                    juros_inicial = suposto_juros;
                }
            }
            else {
                achou = true;
                break;
            }
            if (cont > 5000) {
                break;
            }
            cont++;
        }
        if (achou == false) {
            return -1;
        }
        else {
            if (suposto_juros != -100) {
                suposto_juros = suposto_juros * 100;
            }
            juros_float = Math.round(suposto_juros * 100000) / 100000;
            var s = String(juros_float);
            i = s.indexOf(".");
            if (i != -1) {
                s = s.substring(0, i) + "," + s.substring(i + 1, s.length);
            }
            return s;
        }
    };

    var calcularCETAnual = function() {
        return (Math.pow((1 + parseFloat(calcularCET().replace('.', '').replace(',', '.'))/100), 12) - 1)*100;
    };

    var calcular20Porcent = function() {
        var valorTotal = parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace('.', '').trim());
        var valorEntrada = ((valorTotal * (20 / 100))).formatNumber(2, true);
        $set('txtEntradaValor', valorEntrada);
        $set('txtEntradaPorcent', '20,00%');
    };

    var calcularValores = function() {
        var valorTotal = parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace('.', '').trim());
        var valorEntrada = parseFloat($get('txtEntradaValor').replace('.', '').replace('.', '').trim());

        var resultPorcent = ((valorEntrada / valorTotal) * 100).formatNumber(2, true);
        if (parseInt(resultPorcent) >= 20) {
            $set('txtEntradaPorcent', resultPorcent + '%');
        } else {
            alert('O valor mínimo de entrada deve ser de 20% do valor total');
            calcular20Porcent();
        }
    };

    this.onblurValorTotal = function() {
        if (parseInt($get('txtEntradaValor')) == 0)
            calcular20Porcent();
        else
            calcularValores();

    };

    this.calcularEntradaValor = function() {

        if (!checkFinanciamentoFields()) return;

        if ($get('txtEntradaValor').trim() != '') {
            var valorTotal = parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace('.', '').trim());
            var valorEntrada = parseFloat($get('txtEntradaValor').replace('.', '').replace('.', '').trim());

            if (valorEntrada >= (valorTotal - parseFloat($get('hValorMinFin').replace('.', '')))) {
                alert('O valor para financiamento deve ser maior que ' + $get('hValorMinFin'));
                $set('txtEntradaValor', '');
                $('txtEntradaValor').focus();
                return;
            }
            /*if (valorEntrada == 0) {
            $set('txtEntradaPorcent', '0,00' + '%');
            return;
            }*/
        } else {
            alert('Informe o valor da entrada');
            return;
        }
        var resultPorcent = ((valorEntrada / valorTotal) * 100).formatNumber(2, true);
        if (parseInt(resultPorcent) >= 20) {
            $set('txtEntradaPorcent', resultPorcent + '%');
        } else {
            alert('O valor mínimo de entrada deve ser de 20% do valor total');
            calcular20Porcent();
        }
    };

    this.calcularEntradaPorcent = function() {

        if (!checkFinanciamentoFields()) return;

        if ($get('txtEntradaPorcent').trim() != '') {
            var valorTotal = parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace('.', '').trim());
            var valorEntrada = parseFloat($get('txtEntradaPorcent').replace(',', '.').replace('%', '').trim());

            if (parseFloat($get('hValorMinFin').replace('.', '').replace('.', '')) >= (valorTotal - (valorTotal * (valorEntrada / 100)))) {
                alert('O valor para financiamento deve ser maior que ' + $get('hValorMinFin'));
                $set('txtEntradaPorcent', '');
                $('txtEntradaPorcent').focus();
                return;
            }
            /*if (valorEntrada == 0) {
            $set('txtEntradaValor', 0, 00);
            return;
            }*/
            $set('txtEntradaValor', ((valorTotal * (valorEntrada / 100))).formatNumber(2, true));
        } else {
            alert('Informe o percentual da entrada');
            return;
        }

        var porcentValue = Number(parseFloat($get('txtEntradaPorcent').replace('%', '').replace(',', '.'))).formatNumber(2, true);
        if (parseInt(porcentValue) >= 20) {
            $set('txtEntradaPorcent', porcentValue + '%');
        } else {
            alert('O valor mínimo de entrada deve ser de 20% do valor total');
            calcular20Porcent();
        }

    };

    this.calcularFinanciamento = function() {
        // Validando dados do box inicial
        if (verificaDadosIniciais()) {
            serverclass.CalcularFinanciamento(parseInt($get('txtAnoVeiculo')),
                        parseFloat($get('txtValorTotalVeiculo').replace('.', '').replace('.', '').trim()),
                        parseFloat($get('txtEntradaValor').replace('.', '').replace('.', '').trim()),
                        parseInt($get('sltNumeroParcelas').replace(',', '.').trim()),
                        function(res) {
                            if (res.error) return alert(res.error.message);
                            if (res.value) {
                                blockBoxInicial();
                                $set('txtValorParcela', res.value.formatNumber(2, true));
                                $('sFinResposta').style.display = 'block';
                                $('sFinDadosUsuario').style.display = 'block';
                                $set('txtcetmes', parseFloat(calcularCET().replace('.', '').replace(',', '.')).formatNumber(2, true) + ' %');
                                $set('txtcetano', calcularCETAnual().formatNumber(2, true) + ' %');
                            }
                        });
        }
    };

    this.RetirarAnuncio = function() {
        $html('hTitulo', '');
        $set('hdCodAnuncio', '0');
        reinitialize();
    };


    this.showReceberPropostas = function() {
        $('sFinDadosUsuario').style.display = 'block';
        blockBoxInicial();
    };

    this.salvarProposta = function() {
        if ($get('txtNomeFinanciamento') == '') {
            alert('Digite o nome');
            $('txtNomeFinanciamento').focus();
            return;
        }

        if (!$get('txtCPFFinanciamento').isCPF()) {
            alert('Campo CPF está com formato inválido.');
            $('txtCPFFinanciamento').focus();
            return false;
        }

        if ($get('txtEmailFinanciamento') == '') {
            alert('Digite seu e-mail');
            $('txtEmailFinanciamento').focus();
            return;
        } else {
            if (!$get('txtEmailFinanciamento').isEmail()) {
                alert('Campo e-mail está com formato inválido.');
                $('txtEmailFinanciamento').focus();
                return;
            }
        }
        if ($get('txtConfirmarEmailFinanciamento') == '') {
            alert('Digite o e-mail de confirmação');
            $('txtConfirmarEmailFinanciamento').focus();
            return;
        } else {
            if (!$get('txtConfirmarEmailFinanciamento').isEmail()) {
                alert('O campo confirmar e-mail está com formato inválido.');
                $('txtConfirmarEmailFinanciamento').focus();
                return;
            }
        }

        if ($get('txtEmailFinanciamento') != $get('txtConfirmarEmailFinanciamento')) {
            alert('Os e-mails fornecidos não são correspondentes');
            $('txtEmailFinanciamento').focus();
            return;
        }

        if ($get('txtTelefoneFinanciamento') == '') {
            alert('Digite seu telefone');
            $('txtTelefoneFinanciamento').focus();
            return;
        }

        var codTabelaFinanciamentoParcela = 0;
        for (var i = 0; i < listaParcelas.keys.length; i++)
            if (listaParcelas.keys[i] == parseInt($get('sltNumeroParcelas')))
            codTabelaFinanciamentoParcela = listaParcelas.values[i];

        if ($get('hdCodAnuncio') != '') {
            codAnuncio = parseInt($get('hdCodAnuncio'));
        }

		$('btnEnviarFinanciamento').style.display = 'none';
		$('loadingFinanciamento').style.display = 'block';

        serverclass.SalvarProposta(codTabelaFinanciamentoParcela, codAnuncio, parseInt($get('txtAnoVeiculo')), $get('txtValorTotalVeiculo'), $get('txtEntradaValor'),
                                    $get('txtNomeFinanciamento'), $get('txtCPFFinanciamento'), $get('txtEmailFinanciamento'), $get('txtTelefoneFinanciamento'), function(res) {
										
										$('btnEnviarFinanciamento').style.display = 'block';
										$('loadingFinanciamento').style.display = 'none';
                                        if (res.error) return alert(res.error.message);
                                        if (res.value) {
                                            alert('Proposta para o financiamento efetuada com sucesso');
                                            $set('hdCodAnuncio', '0');
                                            $html('hTitulo', '');
                                            clearFieldsSFin();
                                            unBlockBoxInicial();
                                            $('siteSombraSFin').style.display = 'none';
                                            $('boxSimuladorFinanciamento').style.display = 'none';
                                        }
                                });
    };

    Constructor();
};

var oFinanciamento;
$load(function() {
    oFinanciamento = new Financiamento(UI_Financiamento);
});