﻿//---------------------------------------------------------------------------------------    
//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
//style="display:none;"
function exibirDetalhesVeiculo(tp,cod,exibir,cia,fp,themeAtual,ve)
{    
    if(exibir == 1) 
    {       
        createIframeVeiculo(tp,cod,exibir,cia,fp,themeAtual,ve);
        adicionarAMinhaLista(tp,cod); 
        try{
            if(themeAtual=='&intercar'){Dealers_intercar_intercar.ContagemCliquesMaisDetalhes(tp,parseInt(cod));}
            if(themeAtual=='&web'){WebHome_PrincipalMaster.ContagemCliquesMaisDetalhes(tp,parseInt(cod));}
        }catch(err){}
    }
    else 
    {
        closeIframeVeiculo(tp,cod);
    }
    
    var trVisit = document.getElementById("ctl00_trVisitados");
    
    if(exibir == 1 && trVisit != null) 
    {   
        trVisit.style.display = "inline";                
    }
    else if(trVisit != null)
    {
        trVisit.style.display = "none";   
    }
}

function exibirPropostaModelo(tpv,ver,b,exibir)
{
    if(exibir == 1) 
    {   
        createIframePropostaModelo(tpv,ver,b);
    }
    else
    {
        closeIframePropostaModelo(ver);
    }
}

function exibirPropostaVeiculo(tp,cod,exibir,cia,themeAtual) 
{    
    if(exibir == 1) 
    {   
        createIframeProposta(tp,cod,cia,themeAtual);
        adicionarAMinhaLista(tp,cod);         
        try{
            if(themeAtual=='&intercar'){Dealers_intercar_intercar.ContagemCliquesMaisDetalhes(tp,parseInt(cod));}
            if(themeAtual=='&web'){WebHome_PrincipalMaster.ContagemCliquesMaisDetalhes(tp,parseInt(cod));}
        }catch(err){}
    }
    else 
    {
        closeIframeProposta(tp,cod);
    }
    
    var trVisit = document.getElementById("ctl00_trVisitados");
    
    if(exibir == 1 && trVisit != null) 
    {   
        trVisit.style.display = "inline";                
    }
    else if(trVisit != null)
    {
        trVisit.style.display = "none";   
    }
}

function createIframeVeiculo(tp,cod,exibir,cia,fp,themeAtual,ve)
{    
    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.filter = "alpha(opacity=70)";
	            myBackground.style.opacity = 0.7;		            
	            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.zIndex = 10000;
	            myBackground.overflow = "auto";
	        
	            form.appendChild( myBackground );
	        
            var myDetails = document.createElement( "iframe" );
                myDetails.style.backgroundColor = "#FFF";
                myDetails.style.overflow = "hidden";
                myDetails.id = "iframeDetalhesVeiculo_"+cod;
                myDetails.style.position = "absolute";
                myDetails.align = "center";
                myDetails.frameBorder = 0;
                myDetails.style.width = "566px";
                myDetails.style.height = "550px";
                
                myDetails.style.left = (screen.width / 2) - 283 + "px";
                myDetails.style.top = (getCoords()[1] + 50) + "px";                    
                myDetails.style.zIndex = 10001;
                myDetails.scrolling = "yes"
                myDetails.src = "PopVeiculo.aspx?cod="+cod+"&tpv="+tp + (cia==null? "" : "&cia="+cia) + (fp==null? "" : "&fp="+fp) + (themeAtual==null? "" : "&thm="+themeAtual) + (ve==null? "" : "&ve="+ve);
                myDetails.style.filter = "alpha(opacity=100)";
                form.appendChild( myDetails );
        }
    }
}

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 createIframePropostaModelo(tpv,ver,b)
{
    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.filter = "alpha(opacity=70)";
	            myBackground.style.opacity = 0.7;		            
	            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.zIndex = 10000;
	            myBackground.overflow = "auto";

	            form.appendChild( myBackground );

            var myDetails = document.createElement( "iframe" );
                myDetails.id = "iframePropostaModelo_"+ver;
                myDetails.style.position = "absolute";
                myDetails.setAttribute("class", "clsIframePropostaModelo");
                myDetails.align = "center";
                myDetails.frameBorder = 0;
                myDetails.style.width = "566px";
                myDetails.style.height = "620px";

                myDetails.style.left = (screen.width / 2) - 283 + "px";
                myDetails.style.top = (getCoords()[1] + 50) + "px";
                myDetails.style.zIndex = 10001;
                myDetails.scrolling = "yes"
                
                myDetails.src = "PopProposta.aspx?ver="+ver+"&tpv="+tpv+"&b="+b;
                form.appendChild( myDetails );
        }
    }
}

function createIframeProposta(tp,cod,cia,themeAt)
{
    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.filter = "alpha(opacity=70)";
	            myBackground.style.opacity = 0.7;		            
	            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.zIndex = 10000;
	            myBackground.overflow = "auto";
	        
	            form.appendChild( myBackground );
	        
            var myDetails = document.createElement( "iframe" );
                myDetails.id = "iframePropostaVeiculo_"+cod;
                myDetails.style.position = "absolute";
                myDetails.align = "center";
                myDetails.frameBorder = 0;
                myDetails.style.width = "566px";
                myDetails.style.height = "620px";

//                if (tp != null && tp == "cn")
//                    myDetails.style.height = "570px";                   
//                else
//                    myDetails.style.height = "634px";
                    
                myDetails.style.left = (screen.width / 2) - 283 + "px";
                myDetails.style.top = (getCoords()[1] + 50) + "px";                    
                myDetails.style.zIndex = 10001;
                myDetails.scrolling = "yes"
                
                myDetails.src = "PopProposta.aspx?cod="+cod+"&tpv="+tp + (cia==null? "" : "&cia="+cia)+ (themeAt==null? "" : "&thm="+themeAt);
                form.appendChild( myDetails );
        }
    }
}

function closeIframePropostaModelo(ver)
{
    var form = window.parent.document.getElementsByTagName("form")[0];
    var myBackground = window.parent.document.getElementById( "myBackground" );
    var myDetails = window.parent.document.getElementById( "iframePropostaModelo_"+ver );
    
    if( myBackground && myDetails)
    {
        if( form )
        {
            form.removeChild( myDetails );
	        delete myDetails;

	        form.removeChild( myBackground );
	        delete myBackground;
        }
    }
}

function closeIframeProposta(tp,cod)
{
    var form = window.parent.document.getElementsByTagName("form")[0];
    var myBackground = window.parent.document.getElementById( "myBackground" );
    var myDetails = window.parent.document.getElementById( "iframePropostaVeiculo_"+cod );
    
    if( myBackground && myDetails)
    {
        if( form )
        {
            form.removeChild( myDetails );
	        delete myDetails;

	        form.removeChild( myBackground );
	        delete myBackground;
        }
    }
}

function FazerPropostaAVista(cod,id,etapaAtual)
{
    if (window.document.getElementById("divDetalhesVeiculoDestaque_"+cod) != null)
        window.document.getElementById("divDetalhesVeiculoDestaque_"+cod).style.display = "none";
    
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaEntrada").innerHTML = "";
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaEntrada").parentNode.parentNode.style.display = "none";
    
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaConsorcio").innerHTML = "";
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaConsorcio").parentNode.parentNode.style.display = "none";
    
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaUsado").innerHTML = "";
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaUsado").parentNode.parentNode.style.display = "none";
    
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaTroco").innerHTML = "";
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaTroco").parentNode.parentNode.style.display = "none";

    window.document.getElementById(id+"_lblFinanciamentoValorEntrada").innerHTML = "";
    window.document.getElementById(id+"_lblFinanciamentoValorEntrada").parentNode.parentNode.style.display = "none";
    
    window.document.getElementById(id+"_lblFinanciamentoValorConsorcio").innerHTML = "";
    window.document.getElementById(id+"_lblFinanciamentoValorConsorcio").parentNode.parentNode.style.display = "none";
    
    window.document.getElementById(id+"_lblFinanciamentoValorUsado").innerHTML = "";
    window.document.getElementById(id+"_lblFinanciamentoValorUsado").parentNode.parentNode.style.display = "none";
    
    window.document.getElementById(id+"_lblFinanciamentoValorTroco").innerHTML = "";
    window.document.getElementById(id+"_lblFinanciamentoValorTroco").parentNode.parentNode.style.display = "none";
       
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaFormaPagamento").innerHTML = "A Negociar";
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblExibirValor").innerHTML = "";
    window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaDadosFinanciamento").innerHTML = "";
    
    var linkVoltar = window.document.getElementById("lnkVoltar").href;
    window.document.getElementById("lnkVoltar").href = linkVoltar.replace(",1", "," + etapaAtual);
    
    var container = window.document.getElementById("divDetalhesVeiculoFinanciamento_" + cod);
        container.style.display = "block";
    var divs = container.getElementsByTagName("div");
        for(var i=0; i<divs.length; i++) 
        {
            if(divs[i].id.indexOf("divEtapa1")>-1) { divs[i].style.display="none"; }
            if(divs[i].id.indexOf("divEtapa2")>-1) { divs[i].style.display="none"; }
            if(divs[i].id.indexOf("divEtapa3")>-1) { divs[i].style.display="block"; }
        }
    
    var containerLojaMaisProxima = window.document.getElementById("box_seminovos_"+cod);     
    if (containerLojaMaisProxima != null && containerLojaMaisProxima.style.display == "block")
    {
        containerLojaMaisProxima.style.display = "none";
    }
    
    var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
    if (myDetails != null)
        myDetails.style.height = (window.document.getElementById("divDetalhesVeiculo_"+cod).offsetHeight + 50) + "px";
}

// 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 comoChegar(cod)
{    
    window.open("Pop_ComoChegar.aspx?loja=" + cod,"","width=638px,height=735px,menubar=0,scrollbars=yes");
}

function imprimir(tp,cod)
{
    window.open("ImprimirVeiculo.aspx?tpv=" + tp + "&cod=" + cod,"","width=620,height=522,menubar=0,scrollbars=yes");
}

function indicarAmigo(tp,cod)
{
    window.open("PopIndique.aspx?tpv=" + tp + "&cod=" + cod,"","width=620,height=795,menubar=0,scrollbars=yes");
}

function exibirDetalhesVeiculoFinanciamento(cod, exibir) 
{
    
    var container = window.document.getElementById("divDetalhesVeiculoFinanciamento_" + cod);
        container.style.display = ( exibir==1? "block" : "none" );
    
    var containerLojaMaisProxima = window.document.getElementById("box_seminovos_"+cod);     
    
    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"; }
        }
    
    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"; }
        }
    }
    
    if (containerLojaMaisProxima.style.display == "block")
    {
        containerLojaMaisProxima.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("iframeDetalhesVeiculo_"+cod ).src= "PopVeiculo.aspx?cod="+cod+"&tpv="+tp //"VisualizarVeiculo.aspx?tpv=" + tp + "&cod=" + cod;
    /* if(UserControl_DetalhesVeiculo != null)
    {
        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 +"');",5500);
        }
    }
}


//UserControl/DetalhesVeiculo.ascx - fim
//---------------------------------------------------------------------------------------    

//---------------------------------------------------------------------------------------    
//UserControl/FinanciamentoSemi.ascx - início

function exibirDadosModoPagamento(modo,id,obj)
{
    var container = window.document.getElementById("divDados" + modo + "Veiculo_" + id);
    var inputs = container.getElementsByTagName("input");
    
    if(obj.checked)
    {            
        for(var i=0; i<inputs.length; i++) 
        {
            if(inputs[i].getAttribute("type") != "checbox")
            inputs[i].disabled = false;
        }
    }    
    else
    {
        for(var i=0; i<inputs.length; i++) 
        { 
            if(inputs[i].getAttribute("type") != "checbox")
            inputs[i].disabled = true;
        }
    }
    
    
    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].id != (id+"_txtValorEntrada"))
            {
                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(); }
        }
    }
    else if(modo=="Entrada")
    {
        calcularValoresPagamento(id);
    }
    
    var cod = getCodeById(id);
    var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
    myDetails.style.height = document.getElementById("bodyDetalheVeiculo").offsetHeight + "px"
    //(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(event,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(typeof(rbtModoPagamento) != "undefined" && 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 ComEntrada          = window.document.getElementById(id+"_chkComEntrada").checked;
    var ValorEntrada        = ComEntrada ? converterNumerico(window.document.getElementById(id+"_txtValorEntrada").value) : 0.0;
    
    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_lblExibirValor").innerHTML = "";
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblPropostaDadosFinanciamento").innerHTML = "";
    }
    else 
    {
        window.document.getElementById(id+"_ucFinanciamentoProposta_lblExibirValor").innerHTML = "";
        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");     
          
   
    if(etapa==1 || etapa==0) 
    {
        limparDadosPagamento(id);
    }
    
    if(etapa == 3)
    {            
        if((!window.document.getElementById(id+"_rbtAVista").checked) && String(window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ddlParcelas").value).trim() == "")
        {
            window.document.getElementById("divEtapa2_2_"+id).style.display = "block" ;
            window.document.getElementById("divEtapa3_"+id).style.display = "none";
            window.document.getElementById("divDetalhesVeiculoDestaque_"+cod).style.display = "block";
            alert('Selecione o número de Parcelas');               
        }
        else
        {
            window.document.getElementById("divEtapa3_"+id).style.display = (etapa==3 ? "block" : "none");
            adicionarClique(getTypeById(id), cod);     
//            document.getElementById("imgTopoDetalheVeiculo").src = "imagens/NovoLayout/titConfirmacaoProposta.jpg";
        }
    }
    
    var myDetails = window.parent.document.getElementById("iframeDetalhesVeiculo_"+cod);
    myDetails.style.height = document.getElementById("bodyDetalheVeiculo").offsetHeight + "px"; //(window.document.getElementById("divDetalhesVeiculo_"+cod).offsetHeight + 40) + "px";
}

function adicionarClique(tipo, cod)
{
    UserControl_FinanciamentoSemi.ContagemCliquesFazerProposta(tipo, parseInt(cod), ContagemCliquesFazerProposta_CallBack);            
}

function ContagemCliquesFazerProposta_CallBack(response)
{
    if (response.error != null)
    {
        alert("Ocorreu um erro! " + response.error); 
        return;
    }         
}

function calcularValoresPagamento(id) {
    
    var ValorVeiculo        = window.document.getElementById(id+"_txtValorVeiculo").value;
    
    var ComEntrada          = window.document.getElementById(id+"_chkComEntrada").checked;
    var ValorEntrada        = ComEntrada ? window.document.getElementById(id+"_txtValorEntrada").value : '0.0';
    
    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:680px; dialogHeight:760px; scroll:no;");
    
    var txtPropostaNome = window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ucFinanciamentoProposta_txtPropostaNome");
    var txtPropostaTelefone = window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ucFinanciamentoProposta_txtPropostaTelefone");
    var txtPropostaEmail = window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ucFinanciamentoProposta_txtPropostaEmail");
   
    if(valorAvaliado != null) 
    {
        hCodigoAvaliacaoMeuUsado.value = valorAvaliado[0];
        txtValorMeuUsado.value = valorAvaliado[1];
        txtPropostaNome.value = valorAvaliado[2];
        txtPropostaTelefone.value = valorAvaliado[3];
        txtPropostaEmail.value = valorAvaliado[4];
         
        txtValorMeuUsado.onchange();
         
    }
}

function avaliarMeuUsado(id, cod_estado, cod_marca)
{
    var txtValorMeuUsado = window.document.getElementById(id+"_txtValorMeuUsado");
    var hCodigoAvaliacaoMeuUsado = window.document.getElementById(id+"_hCodigoAvaliacaoMeuUsado");
    
    var strUrl = "AvaliacaoVeiculoUsado.aspx";
    if (cod_estado != null)
        strUrl += "?uf=" + cod_estado;
    if (cod_marca != null)
    {
        strUrl += (cod_estado != null ? "&" : "?");
        strUrl += "marca=" + cod_marca;
    }
        
    var valorAvaliado = window.showModalDialog(strUrl,"","dialogWidth:680px; dialogHeight:760px; scroll:no;");
    
    var txtPropostaNome = window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ucFinanciamentoProposta_txtPropostaNome");
    var txtPropostaTelefone = window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ucFinanciamentoProposta_txtPropostaTelefone");
    var txtPropostaEmail = window.document.getElementById("dlVeiculo_ctl00_ucDetalhesVeiculo_FinanciamentoSemi1_ucFinanciamentoProposta_txtPropostaEmail");
   
    if(valorAvaliado != null) 
    {
        hCodigoAvaliacaoMeuUsado.value = valorAvaliado[0];
        txtValorMeuUsado.value = valorAvaliado[1];
        txtPropostaNome.value = valorAvaliado[2];
        txtPropostaTelefone.value = valorAvaliado[3];
        txtPropostaEmail.value = valorAvaliado[4];
         
        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;
    }
    
    if(strTemp.length > 12) { return false; }
    
    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("Selecione", "");
            
            var opcoes = response.value[1].split('|');
            
            var form =  document.getElementById("tdPar");
            
            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]);   
                    
                    
                    
                    var myBackground = document.createElement("div");
                    myBackground.style.cssFloat = "left";
                    
                    myBackground.style.styleFloat = "left";
                    myBackground.id = "parcela_"+ i;
                    myBackground.style.width = "50px";
                    myBackground.style.height = "18px";
                    myBackground.innerHTML = opcao[1];       
                    myBackground.style.zIndex = 10000;
                    
                    if (i == 1) // primeiro
                    {
                        myBackground.style.paddingLeft = "0px";
                    }
                    else if (i == opcoes.length -1) // ultimo
                    {
                        
                        myBackground.style.paddingLeft = "0px";
                    }
                    else // a rapa
                    {
                        myBackground.style.paddingLeft = "0px";
                    }
                    
                    if(form != null)
                        form.appendChild( myBackground );
                    
                }
            }
            
            /*$(function() {
	                $("#slider").slider({
		                value:parseInt(select.options[1].value),
		                min: 1, //parseInt(select.options[1].value),
		                max: select.options.length -1, // parseInt(select.options[select.options.length-1].value),
            			step: 1,
		                slide: function(event, ui) 
		                {
		                
		                    //alert(select.options[ui.value].value);
		                    
		                    for (i=1; i <= select.options.length -1; i++)
		                        try{
		                            $("#parcela_"+i).css({"font-size" : "12px", "color" : "#02477E"});
		                        }catch(e){}
		                    
		                    //alert(ui.value);
		                    //alert(document.getElementById("parcela_" + ui.value));
		                    
		                    $("#parcela_" + ui.value).css({"font-size" : "16px", "color" : "#ce0000"} );    
		                    
			                $("#amount").val(select.options[ui.value].value);
			                
			                $("#dlVeiculo_ctl00_ucDetalhesVeiculo_ucFinanciamentoSemi_ddlParcelas").val(select.options[ui.value].value);
			                $("#dlVeiculo_ctl00_ucDetalhesVeiculo_ucFinanciamentoSemi_ddlParcelas").change();
			            
		                }
	                });
	                $("#amount").val($("#slider").slider("value"));
                });*/
        }
    }
    
}

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 valorCompostoEntrada = 0.0;
    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 ComEntrada          = window.document.getElementById(id+"_chkComEntrada").checked;
        var ValorEntrada        = ComEntrada ? converterNumerico(window.document.getElementById(id+"_txtValorEntrada").value) : 0.0;        
        var txtValorConsorcio = window.document.getElementById(id+"_txtValorConsorcio");
        var txtValorMeuUsado = window.document.getElementById(id+"_txtValorMeuUsado");
        
        valorCompostoEntrada = ValorEntrada + converterNumerico(txtValorConsorcio.value) + converterNumerico(txtValorMeuUsado.value);
        var txtValorCompostoEntrada = formatarNumeroPadrao(valorCompostoEntrada);            
        UserControl_FinanciamentoSemi.CarregarCondicoesFinanciamento(getTypeById(id), getCodeById(id), obj.options[obj.selectedIndex].value, txtValorFinanciar.value, txtValorCompostoEntrada, carregarDadosFinanciamento_callback);
    }
    
    function carregarDadosFinanciamento_callback(response) 
    {
        if(response.error != null) 
        {
            alert(response.error); return false;
        }


        var vlr_calculado_entrada = response.value.Nm_vlr_calculado_entrada;
        var diferenca_entrada = vlr_calculado_entrada - valorCompostoEntrada;
        
        //Se houve ajuste no valor da entrada devido ao percentual mínimo 
        //configurado para o plano de financiamento
        if (diferenca_entrada > 0)
        {
            var valor_a_financiar = converterNumerico(window.document.getElementById(id+"_lblFinanciamentoValorAPagar").innerHTML);          
            valor_a_financiar = valor_a_financiar - diferenca_entrada;
            window.document.getElementById(id+"_lblFinanciamentoValorAPagar").innerHTML = formatarNumeroPadrao(valor_a_financiar);                        
            window.document.getElementById(id+"_lblFinanciamentoValorEntrada").innerHTML = formatarNumeroPadrao(vlr_calculado_entrada);
        }
        
        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 = document.getElementById("bodyDetalheVeiculo").offsetHeight + "px";
        // (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 enviarPropostaModelo(id,tpv,ver)
{
    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 vesta = window.document.getElementById(id+"_ddlEstado").value;
    var vcid = window.document.getElementById(id+"_ddlCidade").value;
    
    var vfcel = '';
    var vfcom = '';        
    //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; }
    if(vcid == "") { alert("Preencha a cidade."); return; }
       
    UserControl_PropostaModelo.GravarProposta(tpv,ver,vnome,vmail,vfone,vfcel,vfcom,vloja,vesta,vcid,enviarProposta_callback);

    function enviarProposta_callback(response) 
    {
        if(response.error != null) 
        {
            alert(response.error);
            return;
        }

        window.parent.document.location.replace("ConfirmEnvioProposta.aspx?marca=mvagusta");
    }
}


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;
    var vcid = window.document.getElementById(id+"_ddlCidade").value;
    
    var vfcel = '';
    var vfcom = '';        
    //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; }
    if(vcid == "") { alert("Preencha a cidade."); 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 comentrada = window.document.getElementById(idp+"_chkComEntrada").checked;
    var ventrada = comentrada ? window.document.getElementById(idp+"_txtValorEntrada").value : '0.0';
        
    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, vcid,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 mostrarImagem(id, foto)
{
    //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")
                {
                   imagens[i].style.display="none";                       
                }
                exibirImagem(imagens[foto]);
                window.document.getElementById(id+"_lblImagemAtual").innerText = (foto+1);
                /*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 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 + "');",5500);
    }
}

function exibirImagem(img) 
{
    img.style.backgroundColor="white";
    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
        }
    }
}

//outros
function createBackground(){
    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 );
        }
    }
}

function closeBackground(){
    var form = window.parent.document.getElementsByTagName("form")[0];
    var myBackground = window.parent.document.getElementById( "myBackground" );
    
    if( myBackground ){
        if( form ){
	        form.removeChild( myBackground );
	        delete myBackground;
        }
    }
}

function createFrame(url,w,h,s) {
    var form = window.parent.document.getElementsByTagName("form")[0];
    var myFrame = document.createElement( "iframe" );
        myFrame.id = "myFrame";
        myFrame.style.position = "absolute";
        myFrame.align = "center";
        myFrame.frameBorder = 0;
        myFrame.style.width = w+"px";
        myFrame.style.height = h+"px";
        myFrame.style.left = ((getPageSize()[2] - w) / 2) + "px";
        myFrame.style.top = (getCoords()[1] + 50) + "px";
        myFrame.style.zIndex = 10001;
        myFrame.src = url;
        myFrame.allowTransparent = true;
        
        if(typeof(s)!="undefined")
            myFrame.scrolling = s;
            
        form.appendChild( myFrame );
}

function closeFrame() {
    var form = window.parent.document.getElementsByTagName("form")[0];
    var myFrame = window.parent.document.getElementById("myFrame");
    
    if( myFrame){
        if( form ){
            form.removeChild( myFrame );
	        delete myFrame;
        }
    }
}
