﻿    //---------------------------------------------------------------------------------------    
    //Estrutura dos divs
    /*
        <divDetalhesVeiculo_cod>
            <divDetalhesVeiculoDestaque_cod>
                
            </divDetalhesVeiculoDestaque_cod>
            <divDetalhesVeiculoFinanciamento_cod>
                <divEtapasProposta_id>
                    <divEtapa1_id>  </divEtapa1_id>
                    <divEtapa2_1_id></divEtapa2_1_id>
                    <divEtapa2_2_id></divEtapa2_2_id>
                    <divEtapa3_id>  </divEtapa3_id>
                </divEtapasProposta_id>
            </divDetalhesVeiculoFinanciamento_cod>
        </divDetalhesVeiculo_cod>
    
    */
    
    function reset(obj) {
        var radios = obj.getElementsByTagName("input");
        for(var i=0; i<radios.length; i++) {
            if(radios[i].getAttribute("type")=="radio") { radios[i].checked = false; }
        }
    }
    
    //---------------------------------------------------------------------------------------    
    //UserControl/DetalhesVeiculo.ascx - início

    function exibirDetalhesVeiculo(tp,cod,exibir,cia) {
        if(exibir==1) { 
            createIframeVeiculo(tp,cod,cia);
            adicionarAMinhaLista(tp,cod); 
        }
        else { 
            closeIframeVeiculo(tp,cod);
        }
    }
    
    function createIframeVeiculo(tp,cod,cia){
        var myBackground = document.getElementById( "myBackground" );
        var form =  document.getElementsByTagName("form")[0];
        if( ! myBackground ){
	        if( form ){
	        
		        var myBackground = document.createElement("div");
		            myBackground.style.position = "absolute";
		            myBackground.id = "myBackground";
		            myBackground.style.width = getPageSize()[0] + "px";
		            myBackground.style.height = getPageSize()[1] + "px";
		            myBackground.style.left = "0px";
		            myBackground.style.top = "0px";
		            myBackground.style.backgroundColor = "#000000";
		            myBackground.style.filter = "alpha(opacity=70)";
		            myBackground.style.opacity = 0.7;		            
		            myBackground.style.zIndex = 10000;
		        
		            form.appendChild( myBackground );
		        
                var myDetails = document.createElement( "iframe" );
                    myDetails.id = "iframeDetalhesVeiculo_"+cod;
                    myDetails.style.position = "absolute";
                    myDetails.align = "center";
                    myDetails.frameBorder = 0;
                    myDetails.style.width = "600px";
                    myDetails.style.height = "400px";
                    myDetails.style.left = "200px";
                    myDetails.style.top = (getCoords()[1] + 50) + "px";                    
                    myDetails.style.zIndex = 10001;
                    myDetails.src = "PopVeiculo.aspx?cod="+cod+"&tpv="+tp + (cia==null? "" : "&cia="+cia);
                    //myDetails.style.filter = "alpha(opacity=100)";
                    
                    form.appendChild( myDetails );
                
	        }
        }
    }

    // getPageSize()
    // Returns array with page width, height and window width, height
    // Core code from - quirksmode.org
    // Edit for Firefox by pHaez
    function getPageSize(){
     
        var xScroll, yScroll;
         
        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
         
        var windowWidth, windowHeight;
        if (self.innerHeight) {	// all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }
         
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }
         
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){
            pageWidth = windowWidth;
        } else {
            pageWidth = xScroll;
        }
         
        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
         
        return arrayPageSize;
    }                    
    
    function closeIframeVeiculo(tp,cod){
        var form = window.parent.document.getElementsByTagName("form")[0];
        var myBackground = window.parent.document.getElementById( "myBackground" );
        var myDetails = window.parent.document.getElementById( "iframeDetalhesVeiculo_"+cod );
        
        if( myBackground && myDetails){
	        if( form ){
	            form.removeChild( myDetails );
		        delete myDetails;

		        form.removeChild( myBackground );
		        delete myBackground;
	        }
        }
    }

    function comoChegar(cod){
        window.open("Pop_ComoChegar.aspx?loja=" + cod,"","width=597px,height=580px,menubar=0,scrollbars=yes");
    }
    function imprimir(tp,cod){
        window.open("ImprimirVeiculo.aspx?tpv=" + tp + "&cod=" + cod,"","width=600,height=450,menubar=0,scrollbars=yes");
    }
    function indicarAmigo(tp,cod){
        window.open("PopIndique.aspx?tpv=" + tp + "&cod=" + cod,"","width=520,height=450,menubar=0,scrollbars=yes");
    }
    function exibirDetalhesVeiculoFinanciamento(cod, exibir) {
        var container = window.document.getElementById("divDetalhesVeiculoFinanciamento_" + cod);
            container.style.display = ( exibir==1? "block" : "none" );
        
        if(exibir == 0) {
            var divs = container.getElementsByTagName("div");
            for(var i=0; i<divs.length; i++) {
                if(divs[i].id.indexOf("divEtapa1")>-1) { divs[i].style.display="block"; }
                if(divs[i].id.indexOf("divEtapa2")>-1) { divs[i].style.display="none"; }
                if(divs[i].id.indexOf("divEtapa3")>-1) { divs[i].style.display="none"; }
            }
        }
        
        var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
            myDetails.style.height = (window.document.getElementById("divDetalhesVeiculo_"+cod).offsetHeight + 40) + "px";

    }
    function adicionarAMinhaLista(tp,cod) {
        //window.document.getElementById("iframeVisualizarVeiculo").src="VisualizarVeiculo.aspx?tpv=" + tp + "&cod=" + cod;
        //UserControl_DetalhesVeiculo.AdicionarAMinhaLista(tp,parseInt(cod),adicionarAMinhaLista_callback);
        if(typeof(AtualizarMinhaLista)!="undefined"){
            AtualizarMinhaLista(tp,cod);
        }
    }
    function adicionarAMinhaLista_callback(response){
        if(response.error!=null) {
            alert(response.error);
        }
    }
    
    function iniciarFotos(id){
        //ctl00_Meio_ucResultadosBusca_gvResultadosSemi_ctl02_ucDetalhesVeiculoSemi
        //ctl00_Meio_ucResultadosBusca_gvResultadosSemi_ctl02_ucDetalhesVeiculoSemi_ucDetalhesVeiculoSimples_ucVisualizarImagensVeiculo_hlAvancar
        //var hBtVerAvancarImagem = window.document.getElementById(id+"_ucDetalhesVeiculoSimples_ucVisualizarImagensVeiculo_hBtVerAvancarImagem");
        
        var hBtVerAvancarImagem = window.document.getElementById(id+"_hBtVerAvancarImagem");
        
        if(hBtVerAvancarImagem!=null) {
            if(hBtVerAvancarImagem.value != "1") {
                hBtVerAvancarImagem.value = "1";
                setTimeout("avancarImagem('"+ id +"');",2500);
            }
        }
    }

    
    //UserControl/DetalhesVeiculo.ascx - fim
    //---------------------------------------------------------------------------------------    



    
    //---------------------------------------------------------------------------------------    
    //UserControl/FinanciamentoSemi.ascx - início
    
    function exibirDadosModoPagamento(modo,id,obj){
        var container = window.document.getElementById("divDados" + modo + "Veiculo_" + id);
        
        if(modo=="Troco" && obj.checked) {
            var txtValorMeuUsado  = window.document.getElementById(id+"_txtValorMeuUsado");
            var txtValorConsorcio = window.document.getElementById(id+"_txtValorConsorcio");
            if(converterNumerico(txtValorMeuUsado.value)+converterNumerico(txtValorConsorcio.value)==0){
                alert("Você só pode receber troco se optar por Meu Usado ou Consórcio."); obj.checked = false;
            }
        }
        
        container.style.display = (obj.checked ? "block" : "none");
        if(!obj.checked) {
            var inputs = container.getElementsByTagName("input");
            for(var i=0; i<inputs.length; i++) {
                if(inputs[i].getAttribute("type")!=null && inputs[i].getAttribute("type")=="text") {
                    inputs[i].value="";
                    if(inputs[i].getAttribute("onchange")!=null) {
                        inputs[i].onchange();
                    }
                }
            }
        }
        limparDadosPagamento(id);
        
        if((modo=="MeuUsado"||modo=="Consorcio") && !obj.checked) {
            var txtValorMeuUsado  = window.document.getElementById(id+"_txtValorMeuUsado");
            var txtValorConsorcio = window.document.getElementById(id+"_txtValorConsorcio");
            if(converterNumerico(txtValorMeuUsado.value)+converterNumerico(txtValorConsorcio.value)==0){
                var chkComTroco = window.document.getElementById(obj.id.replace(modo,"Troco"));
                if(chkComTroco.checked) { chkComTroco.checked = false; chkComTroco.click(); }
            }
        }
        
        var cod = getCodeById(id);
        var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
            myDetails.style.height = (window.document.getElementById("divDetalhesVeiculo_"+cod).offsetHeight + 40) + "px";

    }
    
    function limparDadosPagamento(id){
        var container = window.document.getElementById("divEtapasProposta_" + id);
        var inputs = container.getElementsByTagName("input");
        for(var i=0;i<inputs.length;i++) {
            if(inputs[i].getAttribute("type")!=null && inputs[i].getAttribute("type")=="radio") {
                inputs[i].checked = false;
            }
        }
        window.document.getElementById(id+"_lblTextoLegal").innerHTML = "";
        window.document.getElementById(id+"_chkConcordo").checked = false;
        window.document.getElementById(id+"_chkConcordo").onclick();
    }
    
    function validarEtapa1(id) {
        var rbtModoPagamento = window.event.srcElement;
        //var id = rbtModoPagamento.id.replace("rbtFinanciamento","").replace("rbtAVista","");
        
        //validar se todas informações foram preenchidas
        if(window.document.getElementById(id+"_chkComEntrada").checked) {
            if(window.document.getElementById(id+"_txtValorEntrada").value.trim()=="") {
                alert("Informe o valor da entrada."); return false; }
        }
        if(window.document.getElementById(id+"_chkComConsorcio").checked) {
            if(window.document.getElementById(id+"_txtNomeConsorcio").value.trim()=="") {
                alert("Informe o nome do Consórcio."); return false; }
            if(window.document.getElementById(id+"_txtGrupoConsorcio").value.trim()=="") {
                alert("Informe o grupo do Consórcio."); return false; }
            if(window.document.getElementById(id+"_txtCotaConsorcio").value.trim()=="") {
                alert("Informe a cota do Consórcio."); return false; }
            if(window.document.getElementById(id+"_txtValorConsorcio").value.trim()=="") {
                alert("Informe o valor do Consórcio."); return false; }
        }
        if(window.document.getElementById(id+"_chkComMeuUsado").checked) {
            if(window.document.getElementById(id+"_txtValorMeuUsado").value.trim()=="") {
                alert("Informe o valor do seu usado."); return false; }
        }
        if(window.document.getElementById(id+"_chkComTroco").checked) {
            if(window.document.getElementById(id+"_txtValorTrocoDesejado").value.trim()=="") {
                alert("Informe o valor do troco desejado."); return false; }
                
            //validar se o valor do troco é menor ou igual ao valor do usado + carta de crédito
            var valorTrocoDesejado = converterNumerico(window.document.getElementById(id+"_txtValorTrocoDesejado").value);
            var valorMeuUsado = converterNumerico(window.document.getElementById(id+"_txtValorMeuUsado").value);
            var valorConsorcio = converterNumerico(window.document.getElementById(id+"_txtValorConsorcio").value);
            if(valorTrocoDesejado > (valorMeuUsado + valorConsorcio)){
                alert("O valor do troco desejado não pode ser superior ao valor do seu usado + valor da carta de crédito.");
                return false;
            }
        }
        
        //se for financiamento, validar se o saldo a pagar é maior que R$ 1,00
        if(rbtModoPagamento.id.indexOf("rbtFinanciamento")>-1) { 
            var txtValorAPagar = window.document.getElementById(id+"_txtValorAPagar");
            if(converterNumerico(txtValorAPagar.value)<1) { alert("O valor a pagar deve ser maior que R$ 1,00."); return false;}
            carregarParcelasFinanciamento(id);
            exibirEtapa(id,22);
        }
        else {
            exibirEtapa(id,21);
        }
        
        atualizarDadosProposta(id);
        
        return true;
    }
    
    function atualizarDadosProposta(id) {

        var ValorVeiculo        = converterNumerico(window.document.getElementById(id+"_txtValorVeiculo").value);
        var ValorEntrada        = converterNumerico(window.document.getElementById(id+"_txtValorEntrada").value);
        var ValorConsorcio      = converterNumerico(window.document.getElementById(id+"_txtValorConsorcio").value);
        var ValorMeuUsado       = converterNumerico(window.document.getElementById(id+"_txtValorMeuUsado").value);
        var ValorTrocoDesejado  = converterNumerico(window.document.getElementById(id+"_txtValorTrocoDesejado").value);
        
        var valor_a_pagar = ValorVeiculo - ValorEntrada - ValorConsorcio - ValorMeuUsado + ValorTrocoDesejado;
        var valor_a_receber = ValorTrocoDesejado;
        
        if(valor_a_pagar < 0) {
            valor_a_pagar = valor_a_pagar * -1;
            valor_a_receber += valor_a_pagar;
        }
        
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaEntrada").innerHTML = formatarNumeroPadrao(ValorEntrada);
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaEntrada").parentNode.parentNode.style.display = (ValorEntrada > 0) ? "block":"none";
        
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaConsorcio").innerHTML = formatarNumeroPadrao(ValorConsorcio);
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaConsorcio").parentNode.parentNode.style.display = (ValorConsorcio > 0) ? "block":"none";
        
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaUsado").innerHTML = formatarNumeroPadrao(ValorMeuUsado);
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaUsado").parentNode.parentNode.style.display = (ValorMeuUsado > 0) ? "block":"none";
        
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaTroco").innerHTML = formatarNumeroPadrao(valor_a_receber);
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaTroco").parentNode.parentNode.style.display = (valor_a_receber > 0) ? "block":"none";

        window.document.getElementById(id+"_lblFinanciamentoValorEntrada").innerHTML = formatarNumeroPadrao(ValorEntrada);
        window.document.getElementById(id+"_lblFinanciamentoValorEntrada").parentNode.parentNode.style.display = (ValorEntrada > 0) ? "block":"none";
        
        window.document.getElementById(id+"_lblFinanciamentoValorConsorcio").innerHTML = formatarNumeroPadrao(ValorConsorcio);
        window.document.getElementById(id+"_lblFinanciamentoValorConsorcio").parentNode.parentNode.style.display = (ValorConsorcio > 0) ? "block":"none";
        
        window.document.getElementById(id+"_lblFinanciamentoValorUsado").innerHTML = formatarNumeroPadrao(ValorMeuUsado);
        window.document.getElementById(id+"_lblFinanciamentoValorUsado").parentNode.parentNode.style.display = (ValorMeuUsado > 0) ? "block":"none";
        
        window.document.getElementById(id+"_lblFinanciamentoValorTroco").innerHTML = formatarNumeroPadrao(valor_a_receber);
        window.document.getElementById(id+"_lblFinanciamentoValorTroco").parentNode.parentNode.style.display = (valor_a_receber > 0) ? "block":"none";
        
        if(window.document.getElementById(id+"_rbtAVista").checked) {
            window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaFormaPagamento").innerHTML = "À vista";
            window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaDadosFinanciamento").innerHTML = "";
        }
        else {
            window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaFormaPagamento").innerHTML = "Financiado";
        }
    }
    
    function exibirEtapa(id,etapa) {
        window.document.getElementById("divEtapa1_"+id).style.display = (etapa==1 ? "block" : "none");
        window.document.getElementById("divEtapa2_1_"+id).style.display = (etapa==21 ? "block" : "none");
        window.document.getElementById("divEtapa2_2_"+id).style.display = (etapa==22 ? "block" : "none");
        window.document.getElementById("divEtapa3_"+id).style.display = (etapa==3 ? "block" : "none");
        
        var cod = getCodeById(id);
        window.document.getElementById("divDetalhesVeiculoDestaque_"+cod).style.display = (etapa==3 ? "none" : "block");
        
        var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
            myDetails.style.height = (window.document.getElementById("divDetalhesVeiculo_"+cod).offsetHeight + 40) + "px";
        
        if(etapa==1) {limparDadosPagamento(id);}
    }
    
    function calcularValoresPagamento(id) {
        
        var ValorVeiculo        = window.document.getElementById(id+"_txtValorVeiculo").value;
        var ValorEntrada        = window.document.getElementById(id+"_txtValorEntrada").value;
        var ValorConsorcio      = window.document.getElementById(id+"_txtValorConsorcio").value;
        var ValorMeuUsado       = window.document.getElementById(id+"_txtValorMeuUsado").value;
        var ValorTrocoDesejado  = window.document.getElementById(id+"_txtValorTrocoDesejado").value;
        
        var valor_a_pagar = converterNumerico(ValorVeiculo) - converterNumerico(ValorEntrada) - converterNumerico(ValorConsorcio) - converterNumerico(ValorMeuUsado) + converterNumerico(ValorTrocoDesejado);
        var valor_a_receber = converterNumerico(ValorTrocoDesejado);
        
        if(valor_a_pagar >= 0) {
            window.document.getElementById(id+"_txtValorAPagar").value = formatarNumeroPadrao(valor_a_pagar);
            window.document.getElementById(id+"_lblFinanciamentoValorAPagar").innerHTML = formatarNumeroPadrao(valor_a_pagar);
            window.document.getElementById(id+"_txtValorAReceber").value = formatarNumeroPadrao(valor_a_receber);
        }
        else
        {
            valor_a_pagar = valor_a_pagar * -1;
            valor_a_receber += valor_a_pagar;
            window.document.getElementById(id+"_txtValorAPagar").value = "0,00";
            window.document.getElementById(id+"_lblFinanciamentoValorAPagar").value = "0,00";
            window.document.getElementById(id+"_txtValorAReceber").value = formatarNumeroPadrao(valor_a_receber);
        }
        
        window.document.getElementById(id+"_chkComTroco").parentNode.parentNode.style.display = (converterNumerico(ValorConsorcio) > 0 || converterNumerico(ValorMeuUsado) > 0) ? "block" : "none";
        
        window.document.getElementById(id+"_txtValorAReceber").parentNode.parentNode.style.display = (valor_a_receber > 0) ? "block" : "none";
        
        limparDadosPagamento(id);
    }
    
    function avaliarMeuUsado(id){
        var txtValorMeuUsado = window.document.getElementById(id+"_txtValorMeuUsado");
        var hCodigoAvaliacaoMeuUsado = window.document.getElementById(id+"_hCodigoAvaliacaoMeuUsado");
        var valorAvaliado = window.showModalDialog("AvaliacaoVeiculoUsado.aspx","","dialogWidth:600px; dialogHeight:500px; scroll:yes;");
        if(valorAvaliado != null) {
            hCodigoAvaliacaoMeuUsado.value = valorAvaliado[0];
            txtValorMeuUsado.value = valorAvaliado[1];
            txtValorMeuUsado.onchange();
        }
    }
    
    function replaceAll(texto, substituirDe, substituirPara) {
        while(texto.indexOf(substituirDe)>-1) {
            texto = texto.replace(substituirDe, substituirPara);
        }
        return texto;
    }
    
    function converterNumerico(valor){
        var retorno = replaceAll(valor, ".", "");
        retorno = retorno.replace(",", ".");
        if(retorno=="") retorno = 0;
        return parseFloat(retorno);
    }
    
    function validarNumero(obj) {
        var chrDigito = String.fromCharCode(event.keyCode);
        
	    if (isNaN(chrDigito))
	    {
		    if(chrDigito==",") {
		        if(obj.value.indexOf(",")>=0) {return false;}
		        else {return true;}
		    }
		    else {
		        if(chrDigito==".") {return true;}
		        else {return false;}
		    }
	    }
	    else { return true; }
    }
    
    function validarNumeroComFormatacao(obj) {
        var chrDigito = String.fromCharCode(event.keyCode);
        
	    if(isNaN(chrDigito) || chrDigito == " ") {return false;}
	    
	    var strTemp = obj.value;
	        strTemp = strTemp.replace(",", "");
	        strTemp = replaceAll(strTemp, ".", "");
	        strTemp = strTemp + chrDigito;
	    
	    if(strTemp.length > 2) {
	        var parteInteira = strTemp.substring(0, (strTemp.length-2));
	        var parteDecimal = strTemp.substring((strTemp.length-2), (strTemp.length));

	        strTemp =  formatarMilhar(parteInteira) + "," + parteDecimal;
	    }
	    
	    obj.value = strTemp;
	    return false;
    }
    
    function carregarParcelasFinanciamento(id) {
        var container = window.document.getElementById("divEtapa2_2_" + id);
        var inputs = container.getElementsByTagName("input");
        for(var i=0; i<inputs.length; i++) {
            if(inputs[i].getAttribute("type")!=null && inputs[i].getAttribute("type")=="text") {
                inputs[i].value="";
            }
        }

        UserControl_FinanciamentoSemi.CarregarCondicoesFinanciamentoNroParcelas(getTypeById(id), getCodeById(id), carregarParcelasFinanciamento_callback);
        
        function carregarParcelasFinanciamento_callback(response) {
            if(response.error != null) {
                alert(response.error); return false;
            }
            
            var container = window.document.getElementById("divEtapa2_2_" + id);
            var selects = container.getElementsByTagName("select");
            if(selects.length > 0) {
                var select = selects[0];
                select.options.length = 0;
                select.options[select.options.length] = new Option("", "");
                
                var opcoes = response.value[1].split('|');
                for(var i=0; i<opcoes.length; i++) {
                    if(opcoes[i]!="") {
                        var opcao = opcoes[i].split(',');
                        select.options[select.options.length] = new Option(opcao[1],opcao[0]);
                    }
                }
            }
        }
    }
    
    function getCodeById(id){
        return window.document.getElementById(id+"_hCdv").value;
    }
    function getTypeById(id){
        return window.document.getElementById(id+"_hTpv").value;
    }
    
    function carregarDadosFinanciamento(id, obj) {
        var container = window.document.getElementById("divEtapa2_2_"+id);
        
        var inputs = container.getElementsByTagName("input");
        for(var i=0; i<inputs.length; i++) {
            inputs[i].value="";
        }

        if(obj.value != "") {
            var txtValorFinanciar = window.document.getElementById(id+"_txtValorAPagar");
            var txtValorEntrada = window.document.getElementById(id+"_txtValorEntrada");
            var txtValorConsorcio = window.document.getElementById(id+"_txtValorConsorcio");
            var txtValorMeuUsado = window.document.getElementById(id+"_txtValorMeuUsado");
            
            var valorCompostoEntrada = converterNumerico(txtValorEntrada.value) + converterNumerico(txtValorConsorcio.value) + converterNumerico(txtValorMeuUsado.value);
                valorCompostoEntrada = formatarNumeroPadrao(valorCompostoEntrada);
                
            UserControl_FinanciamentoSemi.CarregarCondicoesFinanciamento(getTypeById(id), getCodeById(id), obj.value, txtValorFinanciar.value, valorCompostoEntrada, carregarDadosFinanciamento_callback);
        }
        function carregarDadosFinanciamento_callback(response) {
            if(response.error != null) {
                alert(response.error); return false;
            }
            
            window.document.getElementById(id+"_txtValorParcela").value = formatarNumeroPadrao(response.value.Nm_vlr_calculado_parcelas);
            window.document.getElementById(id+"_lblFinanciamentoNumeroParcelas").innerHTML = response.value.Ti_num_parcelas_financiamento.toString() + "x";
            window.document.getElementById(id+"_txtJurosMes").value = formatarNumeroPadrao(response.value.Nm_vlr_condicoes_financeira_juros_mes);
            window.document.getElementById(id+"_txtJurosAno").value = formatarNumeroPadrao(response.value.Nm_vlr_condicoes_financeira_juros_ano);
            window.document.getElementById(id+"_txtTAC").value = formatarNumeroPadrao(response.value.Nm_vlr_condicoes_financeira_tac);
            window.document.getElementById(id+"_txtValorFinalFinanciamento").value = formatarNumeroPadrao(formatarNumero(parseFloat(response.value.Ti_num_parcelas_financiamento) * parseFloat(response.value.Nm_vlr_calculado_parcelas)));
            window.document.getElementById(id+"_lblTextoLegal").innerHTML = response.value.Tx_des_condicoes_financeira_texto_legal_composto;
            window.document.getElementById(id+"_ucFinanciamentoProposta_lblTextoLegal").innerHTML = response.value.Tx_des_condicoes_financeira_texto_legal_composto;
            
            var descricaoFormaPagamento =  "<font color=red>" + response.value.Ti_num_parcelas_financiamento.toString();
                descricaoFormaPagamento += " parcelas no valor de R$ " + window.document.getElementById(id+"_txtValorParcela").value + "</font>";
                descricaoFormaPagamento += "<br />TAC: R$ " + window.document.getElementById(id+"_txtTAC").value;
                descricaoFormaPagamento += "<br />Juros ao mês: " + window.document.getElementById(id+"_txtJurosMes").value + "%";
                descricaoFormaPagamento += "&nbsp;&nbsp;Juros ao ano: " + window.document.getElementById(id+"_txtJurosAno").value + "%";
                descricaoFormaPagamento += "<br />Valor total a prazo: R$ " + window.document.getElementById(id+"_txtValorFinalFinanciamento").value;
            window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaDadosFinanciamento").innerHTML = descricaoFormaPagamento;
            
            //redimensionar janela
            var cod = getCodeById(id);
            var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
                myDetails.style.height = (window.document.getElementById("divDetalhesVeiculo_"+cod).offsetHeight + 40) + "px";
                
        }
    }
    
    function desbloquearProposta(id, obj) {
        window.document.getElementById(id+"_pnlFazerProposta").style.display = (obj.checked? "block":"none");
        window.document.getElementById(id+"_pnlFazerPropostaBloqueado").style.display = (obj.checked? "none":"block");
    }
    
    function formatarNumero(valor){
        //arredondamento
        return Math.round(parseFloat(valor)*100)/100;
    }
    
    function formatarNumeroPadrao(valor){
        var retorno = formatarNumero(valor).toString();
        //0
        //0.0
        //0.00
        var parte_inteira = "0";
        var parte_decimal = "00";

        if(retorno.indexOf(".")<0) { parte_inteira = retorno; }
        else { 
            parte_inteira = retorno.substring(0, retorno.indexOf(".")); 
            parte_decimal = retorno.substring(retorno.indexOf(".")+1, retorno.length); 
        }
        if(parte_decimal.length==1) { parte_decimal = parte_decimal + "0"; }
        
        retorno = formatarMilhar(parte_inteira) + "," + parte_decimal;
        return retorno;
    }
    function formatarMilhar(valor) {
        var retorno = valor.toString();
        
        if(valor.toString().length>3) { 
            var comprimento = valor.toString().length;
            retorno = "";
            
            for(var i=comprimento; i>0; i--) {
                if(retorno.length == 3 || retorno.length == 7 || retorno.length == 11 || retorno.length == 15) {
                    retorno = "." + retorno;
                }
                retorno = valor.substring(i-1,i) + retorno;
            }
        }
        return retorno;
    }
    function formatarMeuValor(obj) {
        obj.value = formatarNumeroPadrao(converterNumerico(obj.value));
    }

    //UserControl/FinanciamentoSemi.ascx - fim
    //---------------------------------------------------------------------------------------
    
    
    
    
    //---------------------------------------------------------------------------------------
    //UserControl/FinanciamentoProposta.ascx - início
    
    function mascararTelefone(obj){
        var chrDigito = String.fromCharCode(event.keyCode);
	    if(isNaN(chrDigito) || chrDigito == " ") {return false;}
	    
	    var strTelefone = obj.value.replace("(", "").replace(")", "").replace("-", "").replace(" ","");
        if (strTelefone.length == 10) {return false;}
            strTelefone = strTelefone + chrDigito;
	    
	    var ddd = "";
	    var telefone = "";
	    
	    if(strTelefone.length > 2) {
	        ddd = strTelefone.substring(0, 2);
	        telefone = strTelefone.substring(2, strTelefone.length);
	        
	        if(telefone.length > 4) {
	            telefone = telefone.substring(0, 4) + "-" + telefone.substring(4, telefone.length);
	        }
	    }
	    else {
	        ddd = strTelefone;
	    }

	    obj.value = "(" + ddd + ") " + telefone;

        return false;
    }
    
    function enviarProposta(id,tpv,cod) {
        //ctl00_Meio_ucResultadosBusca_gvResultadosNovos_ctl02_ucDetalhesVeiculoNovo_ucFinanciamentoSemi_ucFinanciamentoProposta
        //ctl00_Meio_ucResultadosBusca_gvResultadosNovos_ctl02_ucDetalhesVeiculoNovo_ucFinanciamentoSemi_ucFinanciamentoProposta_txtPropostaNome
        
        var vloja = window.document.getElementById(id+"_ddlCompanhia").value;
        var vnome = window.document.getElementById(id+"_txtPropostaNome").value;
        var vmail = window.document.getElementById(id+"_txtPropostaEmail").value;
        var vfone = window.document.getElementById(id+"_txtPropostaTelefone").value;
        var vfcel = window.document.getElementById(id+"_txtPropostaTelefoneCelular").value;
        var vfcom = window.document.getElementById(id+"_txtPropostaTelefoneComercial").value;
        var vesta = window.document.getElementById(id+"_ddlEstado").value;
                
        //validar informações preenchidas
        if(vnome.trim() == "") { alert("Preencha o nome."); return; }
        if(vmail.trim() == "") { alert("Preencha o email."); return; }
        if(vmail.indexOf("@") == -1 || vmail.indexOf(".") == -1) { alert("Email inválido."); return; } 
        if(vfone.trim() == "") { alert("Preencha o telefone."); return; }
        if(vfone.indexOf("(") == -1 || vfone.indexOf(")") == -1) { alert("Telefone inválido."); return; }        
        if(vesta == "") { alert("Preencha o estado."); return; }
        
        var idp = id.replace("_ucFinanciamentoProposta","");
        
        //ctl00_Meio_ucResultadosBusca_gvResultadosNovos_ctl02_ucDetalhesVeiculoNovo_ucFinanciamentoSemi_rbtFinanciamento
        var vfinan = (window.document.getElementById(idp+"_rbtFinanciamento").checked?"1":"0");
        var ventrada = window.document.getElementById(idp+"_txtValorEntrada").value;
        var vnomcons = window.document.getElementById(idp+"_txtNomeConsorcio").value;
        var vgrucons = window.document.getElementById(idp+"_txtGrupoConsorcio").value;
        var vcotcons = window.document.getElementById(idp+"_txtCotaConsorcio").value;
        var vvlrcons = window.document.getElementById(idp+"_txtValorConsorcio").value;
        var vcodavus = window.document.getElementById(idp+"_hCodigoAvaliacaoMeuUsado").value;
        var vvrusado = window.document.getElementById(idp+"_txtValorMeuUsado").value;
        var vvrtroco = window.document.getElementById(idp+"_txtValorTrocoDesejado").value;
        var vcodcond = window.document.getElementById(idp+"_ddlParcelas").value;
        
        UserControl_FinanciamentoProposta.GravarProposta(tpv,cod,vnome,vmail,vfone,vfcel,vfcom,vloja,vfinan,ventrada,vnomcons,vgrucons,vcotcons,vvlrcons,vcodavus,vvrusado,vvrtroco,vcodcond,vesta,enviarProposta_callback);
    
        function enviarProposta_callback(response) {
            if(response.error != null) {
                alert(response.error);
                return;
            }
            //alert("Proposta enviada com sucesso!");
            //alert("Prezado(a) " + vnome + ",\n\nSua proposta foi enviada! Um de nossos executivos de venda entrará em contato.");
            if(tpv == "cn" || tpv == "mn")
            { window.parent.document.location.replace("PropostaEnviadaNovos.aspx?nom=" + vnome);}
            else
            { window.parent.document.location.replace("PropostaEnviadaSemi.aspx?nom=" + vnome);}

            //exibirEtapa(idp,1);
            //exibirDetalhesVeiculo(tpv,cod,0);
            //window.parent.document.location.replace("MinhaLista.aspx");
        }
    }

    
    //UserControl/FinanciamentoProposta.ascx - fim
    //---------------------------------------------------------------------------------------
    
    
    


    //---------------------------------------------------------------------------------------
    //UserControl/VisualizarImagensVeiculo.ascx - início
    
    function avancarImagem(id){
        var hidden = window.document.getElementById(id+"_hBtVerAvancarImagem");
        if(hidden.value != "0") {
            
            var container = window.document.getElementById(id+"_pnlFotos");
            var imagens = container.getElementsByTagName("img");
            var total = parseInt(window.document.getElementById(id+"_lblTotalImagens").innerText);
            
            if(imagens.length > 0) {
                
                for(var i=0; i<imagens.length; i++) {
                    if(imagens[i].style.display!="none") { 
                    
                        //achei a imagem visível, escondo-a
                        imagens[i].style.display="none"; 
                        
                        //mostro a próxima, certificando-me que existe
                        try {
                            exibirImagem(imagens[i+1]);
                            window.document.getElementById(id+"_lblImagemAtual").innerText = (i+2);
                        }
                        catch(e) {
                            exibirImagem(imagens[0]);
                            window.document.getElementById(id+"_lblImagemAtual").innerText = "1";
                        }
                        
                        break;
                    }
                }
            }
            //setInterval("avancarImagem('" + id + "');",3000);
            setTimeout("avancarImagem('" + id + "');",2500);
        }
    }
    
    function exibirImagem(img) {
        img.filters[0].Apply();
        img.style.display="block";
        img.filters[0].Play();
    }
    
    function animarImagem(id) {
        var hidden = window.document.getElementById(id+"_hBtVerAvancarImagem");
        hidden.value = "1";
        avancarImagem(id);
    }
    function pausarImagem(id) {
        var hidden = window.document.getElementById(id+"_hBtVerAvancarImagem");
        hidden.value = "0";
    }
    
    
    //UserControl/VisualizarImagensVeiculo.ascx - fim 
    //---------------------------------------------------------------------------------------

    
    
    
    
    function getCoords(){
        var coords = [0,0];

        var x, y;
        if (self.pageYOffset) // all except Explorers
        {
            x = self.pageXOffset; // not used in event code
            y = self.pageYOffset; // not used in event code
        }
        else if(document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
        {
            x = document.documentElement.scrollLeft;
            y = document.documentElement.scrollTop;
        }
        else if (document.body) // all other Explorers
        {
            x = document.body.scrollLeft;
            y = document.body.scrollTop;
        }
        coords[0] = x;
        coords[1] = y;

        return coords;
    }
    
    /*
    if (!document.all) document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = getCoords;
    var coords = [0,0];

    function getCoords(e){
        var x, y;
        if (self.pageYOffset) // all except Explorers
        {
            x = self.pageXOffset; // not used in event code
            y = self.pageYOffset; // not used in event code
        }
        else if(document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
        {
            x = document.documentElement.scrollLeft;
            y = document.documentElement.scrollTop;
        }
        else if (document.body) // all other Explorers
        {
            x = document.body.scrollLeft;
            y = document.body.scrollTop;
        }
        coords[0] = (document.all) ? x + event.clientX : e.pageX;
        coords[1] = (document.all) ? y + event.clientY : e.pageY;

        return true;
    }
    */
    
    function createIframeDiv(){
        var divFrames = document.getElementById( "iframeAssDiv" )
        var form =  document.getElementsByTagName("form")[0] 
        if( ! divFrames ){
	        if( form ){
		        var divFrame = document.createElement( "div" ) //document.createElement( "iframe" )
		        divFrame.style.position = "absolute"
		        divFrame.id = "iframeAssDiv"
		        divFrame.frameborder = 0
		        divFrame.style.width = document.body.offsetWidth - 5
		        divFrame.style.height = document.body.offsetHeight - 5
		        divFrame.style.left = 0
		        divFrame.style.top = 0
		        divFrame.style.backgroundColor = "#000000"
		        divFrame.style.filter = "alpha(opacity=70)"
		        divFrame.style.zIndex = 10000;
		        form.appendChild( divFrame )
	        }
        }
    }

    function closeIframeDiv(){	
        var divFrame = document.getElementById( "iframeAssDiv" )
        var form = document.getElementsByTagName("form")[0]
        if( divFrame ){
	        if( form ){
		        form.removeChild( divFrame )	
		        delete divFrame
	        }
        }
    }
