﻿function SimuladorFinanciamento(serverclass) {

    var codAnuncio = 0;
    var listaParcelas = new Hashtable();

    var Constructor = function() {
        initialize();
    };
    
    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';
        
        // Combo
        clearCombo('sltNumeroParcelas');
    };
    
    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 = '';
    };

    this.showOverlay = function(ano, valor, anuncio, porc) {
        /*unBlockBoxInicial();
        clearFieldsSFin();
        
        document.getElementById('siteSombraSFin').style.height = document.body.offsetHeight + 'px';
	    document.getElementById('siteSombraSFin').style.width = document.body.offsetWidth + 'px';
        
        $('siteSombraSFin').style.display = 'block';
        $('boxSimuladorFinanciamento').style.display = 'block';
        if(ano != null) {
            $set('txtAnoVeiculo', ano);
            oSimuladorFinanciamento.getParcelas();
        }
        if(valor != null) {
            $set('txtValorTotalVeiculo', valor);
            calcular20Porcent();
        }
        if(anuncio != null)
            codAnuncio = anuncio;
        else
            codAnuncio = 0;*/


        var queryString = '';
        if (ano != null && ano != '')
            queryString += 'Ano=' + ano;
        if (valor != null && valor != '0,0')
            queryString += '&Valor=' + valor;
        if (anuncio != null)
            queryString += '&CodAnuncio=' + anuncio;
        if(porc != null)
            queryString += '&Porc=' + porc;
            
        if (queryString != '')
            document.location = 'UI/Financiamento.aspx?' + queryString;
        else
            document.location = 'UI/Financiamento.aspx';
    };
    
    this.hideOverlay = function() {
        $('siteSombraSFin').style.display = 'none';
        $('boxSimuladorFinanciamento').style.display = 'none';
    };
    
    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('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 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 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) {
                                $set('txtValorParcela', res.value.formatNumber(2, true));
                                $('sFinResposta').style.display = 'block';
                            }
                        });
        }
    };
    
    
    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];

    	serverclass.SalvarProposta(codTabelaFinanciamentoParcela, codAnuncio, parseInt($get('txtAnoVeiculo')), $get('txtValorTotalVeiculo'), $get('txtEntradaValor'),
                                    $get('txtNomeFinanciamento'), $get('txtCPFFinanciamento'), $get('txtEmailFinanciamento'), $get('txtTelefoneFinanciamento'), function(res) {
                                    	if (res.error) return alert(res.error.message);
                                    	if (res.value) {
                                    		alert('Proposta para o financiamento efetuada com sucesso');
                                    		clearFieldsSFin();
                                    		unBlockBoxInicial();
                                    		$('siteSombraSFin').style.display = 'none';
                                    		$('boxSimuladorFinanciamento').style.display = 'none';
                                    	}
                                    });
    };

    //Constructor();
};

var oSimuladorFinanciamento;
    $load(function() {
    oSimuladorFinanciamento = new SimuladorFinanciamento(SimulaFinanciamento);
});