﻿function jDetalhesPgtoPedido() {

    try {
        document.domain = "vaibrasil.com.br";
    }
    catch (e) {
        try {
            document.domain = "10.14.47.145";
        }
        catch (e) { };
    };

    var This = this;
    var jDS;
    var tpl;
    var codPedido;
    var valorTotal;
    var codBandeiraCC;
    var jDSReserva, jDTheader = null;
    var OpcaoEscolhida, textoEscolha;
    var JDTdadosAgencia;
    var valorTotalEscolhido;
    var email;
    var codHistoricoClearSale;
    var listaCodTarifasAereo = [];
    var codPedidoVB;
    var termosCondicoes;
    
    var containsPgtoOff = false;

    var render = {

        email: function(numeroCartaoCredito, AgenciaEmail, nomeOpcao, textoEscolha, valorTotalEscolhido) {
            tpl.tpl_resumoReservaEmail.nomePacote = jDTheader.getDrValue(0, "titulo");
            tpl.tpl_resumoReservaEmail.duracao = jDTheader.getDrValue(0, "descricao");
            tpl.tpl_resumoReservaEmail.validade = jDTheader.getDrValue(0, "validade");
            tpl.tpl_resumoReservaEmail.operadora = jDTheader.getDrValue(0, "operadora");
            tpl.tpl_resumoReservaEmail.dtSaida = jDTheader.getDrValue(0, "DataSaida");

            // destinos
            tpl.tpl_resumoReservaEmail.destinos = render.listaDestinosHoteis(jDS);

            tpl.tpl_resumoReservaEmail.nPedido = jDS.getDrValue("Geral", 0, "CodPedidoPacote");

            // hoteis
            tpl.tpl_resumoReservaEmail.trHospedagens = render.listaPax(jDS);

            //-- dados responsavel            
            if (PubLogin.getSession('Nome') != "")
                tpl.tpl_resumoReservaEmail.nomeResponsavel = PubLogin.getSession('Nome');
            else
                tpl.tpl_resumoReservaEmail.nomeResponsavel = "Não informado";

            if (PubLogin.getSession('Email') != "")
                tpl.tpl_resumoReservaEmail.emailResponsavel = PubLogin.getSession('Email');
            else
                tpl.tpl_resumoReservaEmail.emailResponsavel = "Não informado";

            if (PubLogin.getSession('TelefoneResidencial') != "")
                tpl.tpl_resumoReservaEmail.foneResponsavel = PubLogin.getSession('TelefoneResidencial');
            else
                tpl.tpl_resumoReservaEmail.foneResponsavel = "Não informado";

            if (PubLogin.getSession('TelefoneCelular') != "")
                tpl.tpl_resumoReservaEmail.celularResponsavel = PubLogin.getSession('TelefoneCelular');
            else
                tpl.tpl_resumoReservaEmail.celularResponsavel = "Não informado";

            listaCodTarifasAereo = [];
            var totAereo = parseInt(jDS.getTotRegs("Aereo"));
            if (totAereo > 0) {
                //tpl.tpl_resumoReservaEmail.displayAereo = '';
                var sbAereo = new StringBuilder();

                sbAereo.append('<tr><td style="border-top: solid 1px #CCCCCC; padding: 3px;"><b>Aéreo</b></td></tr>');
                sbAereo.append('<tr style="display:[displayAereo];"><td style="padding: 3px;">');
                sbAereo.append('<table style="font-family:Arial, Helvetica, sans-serif; font-size: 12px; color:#000000;">');
                //                sbAereo.append('<tr><td style="width:200px;"><b>Cidade Origem</b></td><td style="width:200px;"><b>Cidade Destino</b></td>');
                //                sbAereo.append('<td style="width:100px;"><b>Cia Aérea</b></td><td style="width:100px;"><b>Classe</b></td></tr>');

                for (var a = 0; a < totAereo; a++) {
                    listaCodTarifasAereo.push(parseInt(jDS.getDrValue("Aereo", a, "CodTarifaAereo")));

                    tpl.tpl_trAereo.cidadeOrigem = jDS.getDrValue("Aereo", a, "CidadeOrigem");
                    tpl.tpl_trAereo.cidadeDestino = jDS.getDrValue("Aereo", a, "CidadeDestino");
                    tpl.tpl_trAereo.ciasAereas = jDS.getDrValue("Aereo", a, "CiaAerea");
                    //tpl.tpl_trAereo.classe = jDS.getDrValue("Aereo", a, "Classe");
                    sbAereo.append(tpl.tpl_trAereo.getHtml());
                };
                //tpl.tpl_resumoReservaEmail.trAereo = sbAereo.toString();
                sbAereo.append('</table> </td></tr>');

                tpl.tpl_resumoReservaEmail.conteudoAereo = sbAereo.toString();
            }
            else {
                //tpl.tpl_resumoReservaEmail.displayAereo = 'none';
                //$('divTituloRodv').style.display = 'none';
                //$('divTableRodo').style.display = 'none';
                tpl.tpl_resumoReservaEmail.conteudoAereo = '';
            };

            // RODOVIARIO
            if (parseInt(jDS.getTotRegs("Rodoviario")) > 0) {
                tpl.tpl_resumoReservaEmail.conteudoRodoviario = render.rodoviario();
            } else {
                tpl.tpl_resumoReservaEmail.conteudoRodoviario = '';
            };

            tpl.tpl_resumoReservaEmail.trServicosOpcionais = render.servicosOpcionaisInclusos(jDS, true);
            tpl.tpl_resumoReservaEmail.trServicosInclusos = render.servicosOpcionaisInclusos(jDS, false);

            tpl.tpl_resumoReservaEmail.operadora = $get('idOperadora');
            tpl.tpl_resumoReservaEmail.agencia = AgenciaEmail;
            tpl.tpl_resumoReservaEmail.email = email;

            //-- Nome da Opcão de Pgto
            //var total = parseInt(jDS.getTotRegs("OpcoesPgto"));
            //var nomeOpcao = "";
            //for (var i = 0; i < total; i++) {
            //    if (codBandeiraCC == jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC"))
            //        nomeOpcao = jDS.getDrValue("OpcoesPgto", i, "Nome");
            //};

            tpl.tpl_resumoReservaEmail.opcaoPagamento = nomeOpcao;
            tpl.tpl_resumoReservaEmail.formaPagamento = textoEscolha; //jDS.getDrValue("OpcoesPgto", 0, "TotalVezes") + "x " + jDS.getDrValue("OpcoesPgto", 0, "SemJuros");
            //tpl.tpl_resumoReservaEmail.numeroCartao = numeroCartaoCredito;
            tpl.tpl_resumoReservaEmail.moeda = "R$";
            tpl.tpl_resumoReservaEmail.valorTotal = parseFloat(valorTotalEscolhido).formatNumber(2, true); //(jDS.getDrValue("Geral", 0, "ValorTotal") != "" ? parseFloat(jDS.getDrValue("Geral", 0, "ValorTotal")).formatNumber(2, true) : "N/D");

            return tpl.tpl_resumoReservaEmail.getHtml();
        },

        main: function() {
            if (parseInt(jDS.getTotRegs("Geral")) > 0) {
                tpl.tpl_main.resumoReserva = render.renderResumoReserva(codPedido);

                valorTotal = jDS.getDrValue("Geral", 0, "ValorTotal");

                tpl.tpl_main.totalGeral = parseFloat(jDS.getDrValue("Geral", 0, "ValorTotal")).formatNumber(2, true);
                tpl.tpl_main.termosCondicoes = termosCondicoes = jDTheader.getDrValue(0, "termosCondicoes");

                //--- comentado pois sera utilizada nova tela de pagamento
                //tpl.tpl_main.trOpcoesPgto = render.listaOpcoesPgto();
                //tpl.tpl_main.trParcelamento = render.listaParcelamentos();
                //----------------------------------------------------------

                //tpl.tpl_main.proximo = 'javascript:DetalhesPacote.goTo.roteiros('+ codPedido +');';
            }
            else {
                tpl.tpl_main.resumoReserva = render.renderResumoReserva(codPedido);

                valorTotal = "";

                tpl.tpl_main.totalGeral = "";
                tpl.tpl_main.termosCondicoes = "";
                tpl.tpl_main.trOpcoesPgto = "";
                tpl.tpl_main.trParcelamento = "";
            }
            return tpl.tpl_main.getHtml();
        },
        servicosOpcionaisInclusos: function(jDSReserva, pOpcional) {
            var sb = new StringBuilder();
            var total = parseInt(jDSReserva.getTotRegs("Servicos"));
            var totalServicos = 0;

            for (var i = 0; i < total; i++) {
                var inclusoOpcional = jDSReserva.getDrValue("Servicos", i, "Incluso_Opcional");
                var servico = jDSReserva.getDrValue("Servicos", i, "Titulo");

                if (inclusoOpcional == 'true' && pOpcional == true) {
                    tpl.tpl_servicosOpcionais.opcionais = servico;
                    sb.append(tpl.tpl_servicosOpcionais.getHtml());
                    totalServicos++;
                }
                else {
                    if (inclusoOpcional == 'false' && pOpcional == false) {
                        tpl.tpl_servicosOpcionais.opcionais = servico;
                        sb.append(tpl.tpl_servicosOpcionais.getHtml());
                        totalServicos++;
                    };
                };
            };

            if (totalServicos == 0) {
                tpl.tpl_servicosOpcionais.opcionais = "Nenhum Serviço " + (pOpcional == true ? "Opcional" : "Incluso");
                sb.append(tpl.tpl_servicosOpcionais.getHtml());
            };

            return sb.toString();
        },
        renderResumoReserva: function(pCodPedido) {
            //-- É obrigado a pesquisar toda vez q entra nesta funcao, se nao ela vai sempre pega o pacote olhado anteriormente
            jDS = new jDataset(clDetalhesPedido.getDetalhesPedido(pCodPedido).value); ;
            //            if (jDS == undefined)
            //                jDS = new jDataset(clDetalhesPedido.getDetalhesPedido(pCodPedido).value);

            if (parseInt(jDS.getTotRegs("Geral")) > 0) {
                tpl.tpl_resumoReserva.nPedido = jDS.getDrValue("Geral", 0, "CodPedidoPacote");
                tpl.tpl_resumoReserva.trServicosOpcionais = render.servicosOpcionaisInclusos(jDS, true);
                tpl.tpl_resumoReserva.trServicosInclusos = render.servicosOpcionaisInclusos(jDS, false);
                tpl.tpl_resumoReserva.liDestinosHoteis = render.listaDestinosHoteis(jDS);
                tpl.tpl_resumoReserva.trPax = render.listaPax(jDS);
                tpl.tpl_resumoReserva.trServicos = render.listaServicos(jDS);
                tpl.tpl_resumoReserva.pagamento = jDS.getDrValue("OpcoesPgto", 0, "Nome");

                // AEREO
                listaCodTarifasAereo = [];
                var totAereo = parseInt(jDS.getTotRegs("Aereo"));
                if (totAereo > 0) {
                    tpl.tpl_resumoReserva.displayAereo = '';

                    var sbAereo = new StringBuilder();
                    for (var a = 0; a < totAereo; a++) {
                        listaCodTarifasAereo.push(parseInt(jDS.getDrValue("Aereo", a, "CodTarifaAereo")));

                        tpl.tpl_trAereo.cidadeOrigem = jDS.getDrValue("Aereo", a, "CidadeOrigem");
                        tpl.tpl_trAereo.cidadeDestino = jDS.getDrValue("Aereo", a, "CidadeDestino");
                        tpl.tpl_trAereo.ciasAereas = jDS.getDrValue("Aereo", a, "CiaAerea");
                        tpl.tpl_trAereo.classe = jDS.getDrValue("Aereo", a, "Classe");
                        sbAereo.append(tpl.tpl_trAereo.getHtml());
                    };
                    tpl.tpl_resumoReserva.trAereo = sbAereo.toString();
                }
                else {
                    tpl.tpl_resumoReserva.displayAereo = 'none';
                };

                // RODOVIARIO
                if (parseInt(jDS.getTotRegs("Rodoviario")) > 0) {
                    //rodoviario
                    tpl.tpl_resumoReserva.displayRodoviario = '';
                    tpl.tpl_resumoReserva.opcaoRodoviario = jDS.getDrValue("Rodoviario", 0, "opcao");
                    tpl.tpl_resumoReserva.cidadeOrigemRodoviario = jDS.getDrValue("Rodoviario", 0, "origem");
                    tpl.tpl_resumoReserva.cidadeDestinoRodoviario = jDS.getDrValue("Rodoviario", 0, "destino");
                    tpl.tpl_resumoReserva.classeRodoviario = jDS.getDrValue("Rodoviario", 0, "classe");
                }
                else {
                    tpl.tpl_resumoReserva.displayRodoviario = 'none';
                };

                // RODOVIARIO
                if (parseInt(jDS.getTotRegs("Rodoviario")) > 0) {
                    tpl.tpl_resumoReservaEmail.conteudoRodoviario = render.rodoviario();
                }
                else {
                    tpl.tpl_resumoReservaEmail.conteudoRodoviario = '';
                }

                //tpl.tpl_resumoReserva.formaPagamento = jDS.getDrValue("OpcoesPgto", 0, "TotalVezes") + "x " + jDS.getDrValue("OpcoesPgto", 0, "SemJuros");
                //tpl.tpl_resumoReserva.valorTotalReserva = (jDS.getDrValue("Geral", 0, "ValorTotal") != "" ? parseFloat(jDS.getDrValue("Geral", 0, "ValorTotal")).formatNumber(2, true) : "N/D");

                var jDTOpPag = new jDatatable(clDetalhesPedido.dadosOpcaoPagamento(pCodPedido).value);
                var nomeOpcao = jDTOpPag.getDrValue(0, "NomeOpcao");
                var textoEscolha = "";
                var valorParcela = jDTOpPag.getDrValue(0, "ValorParcela");
                var valorEntrada = jDTOpPag.getDrValue(0, "ValorEntrada");
                var qtdParcelas = jDTOpPag.getDrValue(0, "QuantidadeParcelas");
                var valorTotalEscolhido = jDTOpPag.getDrValue(0, "Valor");
                var coefParcelamento = jDTOpPag.getDrValue(0, "CoeficienteParcelamento");
                var textoAux = "";
                if (valorEntrada == 0) {
                    if (valorEntrada == 0) { //--- sem entrada
                        textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                        if (coefParcelamento == 0) { //--- sem juros
                            textoAux += ' sem juros';
                        }
                        else { //--- com juros
                            textoAux += ' com juros';
                        };
                    } else { //--- com entrada
                        textoAux = 'Entrada de R$ ' + parseFloat(valorEntrada).formatNumber(2, true);
                        if (textoAux != '') {
                            textoAux += ' + ' + qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                        } else {
                            textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                        };
                        if (coefParcelamento == 0) { //--- sem juros
                            textoAux += ' sem juros';
                        } else { //--- com juros
                            textoAux += ' com juros';
                        };
                    };
                    textoEscolha = textoAux;
                }
                else { //--- com entrada
                    textoAux = 'Entrada de R$ ' + parseFloat(valorEntrada).formatNumber(2, true);
                    if (textoAux != '') {
                        textoAux += ' + ' + qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                    }
                    else {
                        textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                    };
                    if (coefParcelamento == 0) { //--- sem juros
                        textoAux += ' sem juros';
                    }
                    else { //--- com juros
                        textoAux += ' com juros';
                    };
                };
                textoEscolha = textoAux;

                tpl.tpl_resumoReserva.pagamento = nomeOpcao;
                tpl.tpl_resumoReserva.formaPgto = textoEscolha;
                tpl.tpl_resumoReserva.valorTotal = "R$ " + parseFloat(valorTotalEscolhido).formatNumber(2, true);


                var JDTdadosAgencia = new jDatatable(clDetalhesPedido.dadosAgencia_Operadora(pCodPedido).value);
                tpl.tpl_resumoReserva.agencia = '<b>Agência: </b>' + JDTdadosAgencia.getDrValue(0, "Agencia");
                tpl.tpl_resumoReserva.telefone = '<b> Telefone: </b>' + jsCommon.exec.formataTelefoneAgencias(JDTdadosAgencia.getDrValue(0, "Telefone"));
                tpl.tpl_resumoReserva.email = '<b>Email: </b>' + JDTdadosAgencia.getDrValue(0, "Email");
                tpl.tpl_resumoReserva.operadora = JDTdadosAgencia.getDrValue(0, "Operadora"); // $get('idOperadora');
                
                if (jDS.getDrValue("Geral", 0, "Observacoes") != '')
                    tpl.tpl_resumoReserva.observacoes = '<b>* Observações: ' + jDS.getDrValue("Geral", 0, "Observacoes") + ' </b>';
                else
                    tpl.tpl_resumoReserva.observacoes = '';

                if (jDS.getDrValue("Status", 0, "Descricao") == 'Finalizado - Operadora' || jDS.getDrValue("Status", 0, "Descricao") == 'Finalizado - Agencia')
                    tpl.tpl_resumoReserva.displayStatusBotaoImprimir = '';
                else
                    tpl.tpl_resumoReserva.displayStatusBotaoImprimir = 'none';
            };

            //clDetalhesPacote.enviarEmail();

            return tpl.tpl_resumoReserva.getHtml();
        },
        rodoviario: function(jDSReserva) {
            var sb = new StringBuilder();

            tpl.tpl_rodoviario.displayRodoviario = '';
            tpl.tpl_rodoviario.opcaoRodoviario = ""; //jDS.getDrValue("Rodoviario", 0, "opcao");
            tpl.tpl_rodoviario.cidadeOrigemRodoviario = ""; //jDS.getDrValue("Rodoviario", 0, "origem");
            tpl.tpl_rodoviario.cidadeDestinoRodoviario = ""; //jDS.getDrValue("Rodoviario", 0, "destino");
            tpl.tpl_rodoviario.classeRodoviario = ""; //jDS.getDrValue("Rodoviario", 0, "classe"); 

            sb.append(tpl.tpl_rodoviario.getHtml());

            return sb.toString();
        },
        parcelamentoPedidos: function() {
            return render.listaParcelamentos();
        },
        listaServicos: function(jDSReserva) {
            var sb = new StringBuilder();

            for (var i = 0; i < parseInt(jDSReserva.getTotRegs("Servicos")); i++) {
                var inclusoOpcional = jDSReserva.getDrValue("Servicos", i, "Incluso_Opcional");
                var servico = jDSReserva.getDrValue("Servicos", i, "Titulo");

                if (inclusoOpcional == 'true') {
                    tpl.trServicos.Inclusos = servico;
                    tpl.trServicos.Opcionais = '';
                }
                else {
                    tpl.trServicos.Inclusos = '';
                    tpl.trServicos.Opcionais = servico;
                }

                sb.append(tpl.trServicos.getHtml());
            };
            return sb.toString();
        },
        listaDestinosHoteis: function(jDSReserva) {
            var sb = new StringBuilder();

            for (var i = 0; i < parseInt(jDSReserva.getTotRegs("Hoteis")); i++) {
                tpl.liDestinosHoteis.cidadeDestino = jDSReserva.getDrValue("Hoteis", i, "CidadeDestino");
                tpl.liDestinosHoteis.nomeHotel = jDSReserva.getDrValue("Hoteis", i, "NomeHotel");
                tpl.liDestinosHoteis.opcao = jDSReserva.getDrValue("Hoteis", i, "TipoAcomodacao") + ' / ' +
                    jDSReserva.getDrValue("Hoteis", i, "TipoAlimentacao");

                sb.append(tpl.liDestinosHoteis.getHtml());
            };
            return sb.toString();
        },
        listaPax: function(jDSReserva) {
            var sb = new StringBuilder();
            var t = 0;
            for (var i = 0; i < parseInt(jDSReserva.getTotRegs("Pax")); i++) {
                var tipoPax;

                if (jDSReserva.getDrValue("Pax", i, "TipoPax") == "ADT") { tipoPax = "Adulto" };
                if (jDSReserva.getDrValue("Pax", i, "TipoPax") == "CHD") { tipoPax = "Criança" };
                if (jDSReserva.getDrValue("Pax", i, "TipoPax") == "INF") { tipoPax = "Bebê" };
                if (jDSReserva.getDrValue("Pax", i, "TipoPax") == "SNR") { tipoPax = "Melhor Idade" };

                t++;
                //tpl.trPax.numPessoa = i+1;
                tpl.trPax.nomePessoa = jDSReserva.getDrValue("Pax", i, "Nome") + ' ' + jDSReserva.getDrValue("Pax", i, "Sobrenome");
                tpl.trPax.adultoInfantil = tipoPax; //jDSReserva.getDrValue("Pax", i, "TipoPax");

                sb.append(tpl.trPax.getHtml());
            };
            tpl.tpl_resumoReserva.numeroPessoas = t;
            return sb.toString();
        },
        listaOpcoesPgto: function() {
            var sb = new StringBuilder();

            /*
            Verifica se contém o COD 13 - Pagamento OffLine
            */
            var indiceContainsPgtoOff;

            var total = parseInt(jDS.getTotRegs("OpcoesPgto"));
            for (var i = 0; i < total; i++) {
                //-- 13 - Pgto OFFLINE
                if (13 == jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC")) {
                    containsPgtoOff = true;
                    indiceContainsPgtoOff = i;
                };
            };

            if (containsPgtoOff) {
                tpl.trOpcoesPgto.onSelectOptPgto = 'javascript:DetalhesPgtoPedido.goTo.onSelectOptPgto(this.value);';
                tpl.trOpcoesPgto.srcImagem = jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "imagem");
                tpl.trOpcoesPgto.rbValueOptPgto = jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "codBandeiraCC");
                tpl.trOpcoesPgto.rbNomeOptPgto = jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "Nome");

                // marca o primeiro como checked. 
                tpl.trOpcoesPgto.checked = 'checked = "checked"';
                codBandeiraCC = jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "codBandeiraCC");

                var totX = '';

                if (jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "SemJuros") != 'À Vista') {
                    totX = jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "TotalVezes");
                    totX = '<span id="spanOptPgto"><br />' + totX + 'x '
                        + jDS.getDrValue("OpcoesPgto", indiceContainsPgtoOff, "SemJuros") + '</span>';
                };

                tpl.trOpcoesPgto.jurosOptPgto = totX;
                sb.append(tpl.trOpcoesPgto.getHtml());
            }
            else {
                var arrayBandeiras = [];
                for (var i = 0; i < parseInt(jDS.getTotRegs("OpcoesPgto")); i++) {
                    if (!arrayBandeiras.contains(jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC"))) {
                        arrayBandeiras.push(jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC"));

                        tpl.trOpcoesPgto.onSelectOptPgto = 'javascript:DetalhesPgtoPedido.goTo.onSelectOptPgto(this.value);';
                        tpl.trOpcoesPgto.srcImagem = jDS.getDrValue("OpcoesPgto", i, "imagem");
                        tpl.trOpcoesPgto.rbValueOptPgto = jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC");
                        tpl.trOpcoesPgto.rbNomeOptPgto = jDS.getDrValue("OpcoesPgto", i, "Nome");


                        if (i == 0) {
                            // marca o primeiro como checked. 
                            tpl.trOpcoesPgto.checked = 'checked = "checked"';
                            codBandeiraCC = jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC");
                        }
                        else {
                            tpl.trOpcoesPgto.checked = '';
                        };

                        var totX = '';

                        if (jDS.getDrValue("OpcoesPgto", i, "SemJuros") != 'À Vista') {
                            totX = jDS.getDrValue("OpcoesPgto", i, "TotalVezes");
                            totX = '<span id="spanOptPgto"><br />' + totX + 'x '
                            + jDS.getDrValue("OpcoesPgto", i, "SemJuros") + '</span>';
                        };

                        tpl.trOpcoesPgto.jurosOptPgto = totX;
                        sb.append(tpl.trOpcoesPgto.getHtml());
                    };
                };
            };
            return sb.toString();
        },
        listaParcelamentos: function() {
            var valorEntrada = 0;
            var sb = new StringBuilder();
            sb.append("<table>");

            var primeiroCheck = false;
            for (var i = 0; i < parseInt(jDS.getTotRegs("Parcelamentos")); i++) {
                // exibe somente o selecionado
                if (codBandeiraCC == jDS.getDrValue("Parcelamentos", i, "codBandeiraCC")) {

                    var percentualEntrada = (jDS.getDrValue("Parcelamentos", i, "ValorEntrada") == "" || jDS.getDrValue("Parcelamentos", i, "ValorEntrada") == undefined ? 0 : parseFloat(jDS.getDrValue("Parcelamentos", i, "ValorEntrada")));
                    var taxaJuros = parseFloat(jDS.getDrValue("Parcelamentos", i, "CoeficienteParcelamento"));
                    var numParcelas = parseInt(jDS.getDrValue("Parcelamentos", i, "numeroParcela"));
                    //var txtJuros = jDS.getDrValue("Parcelamentos", i, "JurosTXT");
                    var txtJuros = (taxaJuros > 0 ? "Com Juros" : "Sem Juros");
                    var valorParcela = parseFloat(valorTotal) / numParcelas;
                    var valorJuros = valorParcela * (taxaJuros / 100);
                    var valorFinalParcela = valorParcela + valorJuros;


                    if (percentualEntrada == 0) {
                        var txtParcelas = ((numParcelas == 1) ? '' : numParcelas + 'x ') + 'R$' + valorFinalParcela.formatNumber(2, true) + ' ' + txtJuros;
                        var valorTotalJuros = valorTotal;
                    }
                    else {
                        var valorEntrada = (valorTotal * percentualEntrada / 100);
                        var valorParcelado = (valorTotal - valorEntrada);
                        var valorParcela = parseFloat(valorParcelado) / numParcelas;
                        var valorJuros = valorParcela * (taxaJuros / 100);
                        var valorParcelaJuros = valorParcela + valorJuros;
                        var valorTotalJuros = (valorParcelaJuros * numParcelas) + valorEntrada;
                        var txtParcelas = ((numParcelas == 1) ? 'R$' + parseFloat(valorTotal).formatNumber(2, true) + ' ' + txtJuros : 'Entrada R$' + valorEntrada.formatNumber(2, true) + ' + ' + numParcelas + 'x ' + 'R$' + valorParcelaJuros.formatNumber(2, true) + ' ' + txtJuros);
                    }

                    tpl.trParcelamentos.checked = (primeiroCheck == false ? "checked='checked'" : "");
                    tpl.trParcelamentos.rbValueParcelas = jDS.getDrValue("Parcelamentos", i, "CodPacote_BandeiraCC") + '#' + txtParcelas + '#' + valorTotalJuros;
                    tpl.trParcelamentos.rbParcelas = txtParcelas;
                    tpl.trParcelamentos.i = i;
                    sb.append(tpl.trParcelamentos.getHtml());

                    primeiroCheck = true;
                };
            };
            sb.append("</table>");
            return sb.toString();
        }
    };
    
    var ctrlRefs = {
        siteConteudo: function() { return $('siteConteudo'); },
        parcelamentoPedidos: function() { return $('divParcelamentoPedidos'); }
    };
    
    // Criado o metodo de CallBack para poder colocar a pelicula e removido no momento correto
    // Task: D-27397
    var callbacks = {
        pelicula: function()
        {
            $('fmLogin').innerHTML = '';
            $("fundoLogin").style.display='none';
        }
    };

    var startEnv = {
        main: function() {
            if (jDTheader == null)
                jDTheader = DetalhesPacote.exec.getJDTheader(codPedido);

            jDS = new jDataset(clDetalhesPedido.getDetalhesPedido(codPedido).value);
            $html("pagamento", render.main());
            $("pagamento").style.display = '';

            $("servicos").style.display = 'none';
            $("aereo").style.display = 'none';
            $("rodoviario").style.display = 'none';
            $("hotel_1").style.display = 'none';
            $("hotel_2").style.display = 'none';
            //$html("tituloPacotes", "Pagamento");
            if (termosCondicoes != "")
                $("divTermosCondicoes").style.display = '';

            //--- comentado pois sera utilizada nova tela de pagamento
            //if (!containsPgtoOff)
            //    $('tableDadosCartao').style.display = "";

            //-- Passo 5
            $html("passo4", "<b>Configure sua Viagem</b>");
            $html("passo5", '<b style="color:#FFFFFF;">Pagamento</b>');
            $("tablePassoPasso").style.backgroundImage = 'url("css/img/pct_passo_5.jpg")';


            //--- comentado pois sera utilizada nova tela de pagamento
            //-- Formata o CPF em tempo de execução - by Jorge Aires - 17-12-09
            //$('txtCPF').onkeydown = function(event)
            //{
            //    var tecla = event || window.event;
            //    if (tecla != 8)
            //    {
            //        var valorTmp = $get('txtCPF');
            //        valorTmp = valorTmp.replace('.','');
            //        valorTmp = valorTmp.replace('.','');
            //        valorTmp = valorTmp.replace('.','');
            //        valorTmp = valorTmp.replace('-','');
            //        
            //        $('txtCPF').value = valorTmp.mask('###.###.###-##');
            //    };
            //};            

            //-- Seta valor do Header
            $html('valorPacoteHeader', parseFloat(valorTotal).formatNumber(2, true));

            //-- AGENCIAS
            initAgenciaPacote(codPedido);
        },
        onSelectOptPgto: function(codBandCC) {
            codBandeiraCC = codBandCC;
            $html(ctrlRefs.parcelamentoPedidos(), render.listaParcelamentos());
            //$('rbParcelas').checked = true;
        }
    };

    var openModalDialog = function(theURL, winName) 
    {
        window.showModalDialog(theURL, winName, "dialogwidth: 820px; dialogheight: 500px; resizable: no");
//        if (result != undefined && result  > 0)
//        {
//            codPedidoVB = result;
//            This.goTo.resumoReserva(result);
//        }
//        else
//        {
//            //alert("Desculpe-nos! Não foi possível realizar seu pedido");
//        };
        if (clDetalhesPedido.verificarStatusPedido(codPedidoVB, "P").value > 0)
        {
            try
            {
                $("fundoLogin").style.display = "";
				var tplCommon = new Template('Common');
				$('fmLogin').innerHTML = tplCommon.tpl_peliculaFechamento.getHtml();
				$('fmLogin').style.display = '';
    		}
    		catch(e) {}
    		
            This.goTo.resumoReserva(codPedidoVB);
        };
    };

    this.goTo = {
        main: function(codPed) {
            codPedido = codPed;

            $('tituloHospedagem').style.display = 'none';

            startEnv.main();
            //$('rbParcelas').checked = true;
            clDetalhesPedido.insertStatusPedido(
                codPed,
                new statusPedido().Em_processo_compra_Login,
                PubLogin.getSession('CodUsuario'),
                'Login efetuado.'
            );
        },

        onSelectOptPgto: function(codBandCC) {
            startEnv.onSelectOptPgto(codBandCC);
        },

        voltarServicos: function() {
            //-- Exclui hoteis pacotes existentes
            clHotelPacote.excluirExistentes(codPedido);

            $("hotel_1").style.display = '';
            $("hotel_2").style.display = '';
            $("aereo").style.display = '';
            $("rodoviario").style.display = '';
            $("servicos").style.display = '';
            $("pagamento").style.display = 'none';
            $("agencia").style.display = 'none';
            //$html("tituloPacotes", "Configure sua Viagem");

            //-- Passo 4
            $html("passo4", '<b style="color:#FFFFFF;">Configure sua Viagem</b>');
            $html("passo5", '<b>Pagamento</b>');
            $("tablePassoPasso").style.backgroundImage = 'url("css/img/pct_passo_4.jpg")';
        },
        telaPagamento: function() {
            //-- Agencia
            if (AgenciaPacote.exec.isAgenciaSelecionada() == false) {
                alert('Selecione uma agência.');
                return false;
            };

            //-- Se chegou aqui, começa a reserva
            if ($('chk_termos').checked) {

                /********************************************
            
    			NOVA ESTRUTURA ESTOQUE AÉREO 
                                    
                *********************************************/

                listaCodTarifasAereo = [];
                var totAereo = parseInt(jDS.getTotRegs("Aereo"));
                if (totAereo > 0) {
                    for (var a = 0; a < totAereo; a++) {
                        listaCodTarifasAereo.push(parseInt(jDS.getDrValue("Aereo", a, "CodTarifaAereo")));
                    };

                    //-- Verifico se tem estoque de aéreo, se não tiver, não pode finalizar o pedido
                    var temEstoqueIda = true, temEstoqueVolta = true;
                    var resIda = 0;
                    var resVolta = 0;
                    var totPax = parseInt(jDS.getTotRegs("Pax"));
                    var dataIda = jDS.getDrValue("Geral", 0, "DataSaida");
                    var dataVolta = jDS.getDrValue("Geral", 0, "DataVolta");

                    //-- Primeiro faz um IF para saber se tem pelo menos a tarifa de ida, assim já sabe que no pacote tem opção aéreo
                    if ((listaCodTarifasAereo.length >= 2) && (listaCodTarifasAereo[0] != undefined && listaCodTarifasAereo[1] != undefined)) {
                        var temEstoqueIda = true, temEstoqueVolta = true;

                        resIda = clDetalhesPedido.verificarQtdAssentosDisponiveis(listaCodTarifasAereo[0], dataIda, dataIda).value;
                        resVolta = clDetalhesPedido.verificarQtdAssentosDisponiveis(listaCodTarifasAereo[1], dataVolta, dataVolta).value;

                        if (resIda <= 0)
                            temEstoqueIda = false;

                        if (resVolta <= 0)
                            temEstoqueVolta = false;
                    };

                    if (!((temEstoqueIda && temEstoqueVolta) && (((resIda - totPax) >= 0) && ((resVolta - totPax) >= 0))))
                    //(!(temEstoqueIda && temEstoqueVolta) && (((resIda - totPax) <= 0) && ((resVolta - totPax) <= 0)))
                    {
                        alert("Desculpe-nos! Caro cliente, não há mais disponibilidade para esta data de saída.");
                        //--- SOLICITADO A TROCA DA PAGINA DE REDIRECIONAMENTO PARA QUANDO NAO TEM ESTOQUE DE AEREO - DEFEITO -> ID: D - 53944
                        //window.location = "pacotesNew.vxlpub?to=d&codPacote=" + jDS.getDrValue("Geral", 0, "CodPacote");
                        window.location = "homeVB.vxlpub?undefined";
                        return;
                    };
                };

                var codEmpresa = parseInt(jDS.getDrValue("Geral", 0, "CodEmpresaOperadora"));
                var codPedidoPacote = parseInt(jDS.getDrValue("Geral", 0, "CodPedidoPacote"));
                var codUsuario = PubLogin.getSession('CodUsuario');
                var hashPgto = clDetalhesPedido.getUrlPgtoPacote_VB(codUsuario, valorTotal.toString().replace(".", ","), codEmpresa, codPedidoPacote).value;

                codPedidoVB = codPedidoPacote;
                openModalDialog(hashPgto, "");
                //window.open(hashPgto, "", "HEIGHT=600,WIDTH=820");
            } else {
                alert('Você deve aceitar os termos e condições do pacote.');
            };
        },

        resumoReserva: function(codPedidoPacote) {
            window.scroll(0, 0);
            ccCode = "";

            //            if ( $('rbParcelas').checked == false)
            //            {
            //              alert('Selecione uma Opção de Pagamento');
            //              return false;
            //            };

            /*if (!containsPgtoOff) {
            if ($get('txtNomeImpresso') == "") {
            alert('Informe o nome impresso no Cartão');
            return false;
            };

                if ($get('txtCPF') == "") {
            alert('Informe o CPF do usuário');
            return false;
            }
            else {
            if (!$get('txtCPF').isCPF()) {
            alert('CPF do usuário incorreto');
            return false;
            };
            };

                if ($get('txtNumCartaoCredito') == "") {
            alert('Informe o número do Cartão de Crédito');
            return false;
            }
            else {
            if (codBandeiraCC == 2) {
            if ($get('txtNumCartaoCredito').isMasterCard()) {
            ccCode = "MC";
            }
            else {
            alert('Cartão de Crédito inválido.');
            return false;
            };
            }
            else {
            if ($get('txtNumCartaoCredito').isVisa()) {
            ccCode = "VI"
            }
            else {
            alert('Cartão de Crédito inválido.');
            return false;
            };
            };
            };

                //-- Cod Segurança
            if ($get('txtCodSeguranca') == "") {
            alert('Informe o código de segurança do cartão');
            $('txtCodSeguranca').focus();
            return false;
            };

                //-- Valida Validade Cartão
            var mesCartao = parseInt($get('validadeMes'));
            var anoCartao = parseInt($get('validadeAno'));
            var ano = new Date().toString("dd/MM/yyyy");
            var mesAtual = parseInt(ano.toString().split("/")[1]);
            var anoAtual = parseInt(ano.toString().split("/")[2]);

                if (anoCartao <= anoAtual) {
            if (mesCartao < mesAtual) {
            alert("Validade do Cartão Inválida");
            return false;
            };
            };
            };*/

            //-- Agencia
            if (AgenciaPacote.exec.isAgenciaSelecionada() == false) {
                alert('Selecione uma agência.');
                return false;
            };

            //-- Se chegou aqui, começa a reserva 
            if ($('chk_termos').checked) {
                //--- foi mudado a verificacao d estoque aereo para ocorrer antes de ir para a tela d pagamento


                //                /********************************************
                //            
                //                        NOVA ESTRUTURA ESTOQUE AÉREO 
                //                                    
                //                ***************************************e******/

                //                listaCodTarifasAereo = [];
                //                var totAereo = parseInt(jDS.getTotRegs("Aereo"));
                //                if (totAereo > 0) {
                //                    for (var a = 0; a < totAereo; a++) {
                //                        listaCodTarifasAereo.push(parseInt(jDS.getDrValue("Aereo", a, "CodTarifaAereo")));
                //                    };

                //                    //-- Verifico se tem estoque de aéreo, se não tiver, não pode finalizar o pedido
                //                    var temEstoqueIda = true, temEstoqueVolta = true;
                //                    var resIda = 0;
                //                    var resVolta = 0;
                //                    var totPax = parseInt(jDS.getTotRegs("Pax"));
                //                    var dataIda = jDS.getDrValue("Geral", 0, "DataSaida");
                //                    var dataVolta = jDS.getDrValue("Geral", 0, "DataVolta");

                //                    //-- Primeiro faz um IF para saber se tem pelo menos a tarifa de ida, assim já sabe que no pacote tem opção aéreo
                //                    if ((listaCodTarifasAereo.length >= 2) && (listaCodTarifasAereo[0] != undefined && listaCodTarifasAereo[1] != undefined)) {
                //                        var temEstoqueIda = true, temEstoqueVolta = true;

                //                        resIda = clDetalhesPedido.verificarQtdAssentosDisponiveis(listaCodTarifasAereo[0], dataIda, dataIda).value;
                //                        resVolta = clDetalhesPedido.verificarQtdAssentosDisponiveis(listaCodTarifasAereo[1], dataVolta, dataVolta).value;

                //                        if (resIda <= 0)
                //                            temEstoqueIda = false;

                //                        if (resVolta <= 0)
                //                            temEstoqueVolta = false;
                //                    };

                //                    if (!((temEstoqueIda && temEstoqueVolta) && (((resIda - totPax) >= 0) && ((resVolta - totPax) >= 0))))
                //                    //(!(temEstoqueIda && temEstoqueVolta) && (((resIda - totPax) <= 0) && ((resVolta - totPax) <= 0)))
                //                    {
                //                        alert("Desculpe-nos! Caro cliente, não há mais disponibilidade para esta data de saída.");
                //                        window.location = "pacotesNew.vxlpub?to=d&codPacote=" + jDS.getDrValue("Geral", 0, "CodPacote");
                //                        return;
                //                    };
                //                };
                /********************************************
            
    			CONTINUA O FLUXO NORMALMENTE
                                    
                *********************************************/

                //-- Loading

                //Comentado esta linha para colocar a película
                //$("divLoading").style.display = '';

                // Criado o metodo de CallBack para poder colocar a pelicula e removido no momento correto
                // Task: D-27397

                // na Área do Agente (B2B), $("fundoLogin") é nulo
                try {
                    $("fundoLogin").style.display = "";
                    var tplCommon = new Template('Common');
                    $('fmLogin').innerHTML = tplCommon.tpl_peliculaFechamento.getHtml();
                    $('fmLogin').style.display = '';
                } catch (e) {

                };

                //OpcaoEscolhida = $get('rbParcelas');
                //NomeOpcaoEscolhida = $('rbParcelas').name;

                //for (var i = 0; i < document.getElementsByName('rbParcelas').length; i++) {
                //    if (document.getElementsByName('rbParcelas')[i].checked) {
                //        var splitEscolha = document.getElementsByName('rbParcelas')[i].value.split('#');
                //        var codEscolha = splitEscolha[0];
                //        textoEscolha = splitEscolha[1];
                //        valorTotalEscolhido = splitEscolha[2];
                //        break;
                //    }
                //}


                //  PARÂMETRO DE ENTRADA:
                //              string Reanalise - Flag que indica se é novo ou já existe - FALSE = Novo
                //              string TotalAmount - Valor Total
                //              string CPF - CPF Obrigatório
                //              string ccTipo - Sigla do cartão de crédito => VI - Visa; MC - MasterCard
                //              string ccNumero - Númeto do Cartão de crédito
                //              string ccNome - Nome no cartão
                //              int ccExpMes - Mês de validade
                //              int ccExcAno - Ano de validade

                //if (!containsPgtoOff) {
                //----------------- >>>>>>>>> CLER SALE - BY Luciano <<<<<<<<<< ---------------//
                //  var statusClearSale = VTPInterface.verificaStatusClearSale("false", codPedido, ($get('hTotalGeral')).replace('.', '').replace(',', '.'),
                //                           $get('txtCPF'), ccCode, $get('txtNumCartaoCredito'), $get('txtNomeImpresso'), $get('validadeMes'), $get('validadeAno')).value;

                //  codHistoricoClearSale = VTPInterface.gravaDadosClearSale("PedidoPacoteB2C", statusClearSale).value;	    
                //--------------------------------------------------------------------------------------//
                //};

                //--- FOI SOLICITADO PARA RETIRAR O TRATAMENTO DO CLEARSALE - TASK: TK-262749
                //--- Considera APROVADO quem tiver no mínimo ALTO ou que retorne -1 pois esta empresa nao possui verificacao do clear sale ativada 
                //--- ou que retorne 0 pois o clear sale esta desligado ou quando for pagamento na agencia
                //if (statusClearSale <= 2 || containsPgtoOff) {
                //var numCartaoCredito = $get('txtNumCartaoCredito');
                //var titularCartaoCredito = $get('txtNomeImpresso');
                //var cpfCartaoCredito = $get('txtCPF');
                //var validadeCartaoCredito = new Date(parseInt($get('validadeAno')), parseInt($get('validadeMes')) - 1, 1, 23, 59, 59, 0);
                //validadeCartaoCredito = validadeCartaoCredito.addMonths(1).addDays(-1);
                //var codSeguranca = $get('txtCodSeguranca');

                //debugger;
                //clLogin.setTelaAcaoSession('Pagamento'); // seta o nome da tela na session

                //var resUpdateEmail = clDetalhesPedido.updatePedidosNumeroCartaoCredito(codPedido, codEscolha, numCartaoCredito, titularCartaoCredito, cpfCartaoCredito, validadeCartaoCredito, codSeguranca, codHistoricoClearSale);

                //SALVAR A OPCAO DE PARCELAMENTO NA ETAPA DE PACOTE DINÂMICO
                if (codPedidoPacote > 0) {//resUpdateEmail.value == true) {
                    $("resumoReserva").style.display = '';
                    $("opcoesPagamento").style.display = 'none';
                    $("agencia").style.display = 'none';

                    //$html("tituloPacotes", "Resumo da Reserva do Pacote");

                    $('tituloPacotes').style.display = '';

                    //-- Nome da Opcão de Pgto
                    //var total = parseInt(jDS.getTotRegs("OpcoesPgto"));
                    //var nomeOpcao = "";
                    //for (var i = 0; i < total; i++) {
                    //    if (codBandeiraCC == jDS.getDrValue("OpcoesPgto", i, "codBandeiraCC")) {
                    //        nomeOpcao = jDS.getDrValue("OpcoesPgto", i, "Nome");
                    //    };
                    //};

                    var jDTOpPag = new jDatatable(clDetalhesPedido.dadosOpcaoPagamento(codPedidoPacote).value);
                    var nomeOpcao = jDTOpPag.getDrValue(0, "NomeOpcao");
                    var textoEscolha = "";
                    var valorParcela = jDTOpPag.getDrValue(0, "ValorParcela");
                    var valorEntrada = jDTOpPag.getDrValue(0, "ValorEntrada");
                    var qtdParcelas = jDTOpPag.getDrValue(0, "QuantidadeParcelas");
                    var valorTotalEscolhido = jDTOpPag.getDrValue(0, "Valor");
                    var coefParcelamento = jDTOpPag.getDrValue(0, "CoeficienteParcelamento");

                    if (qtdParcelas == 1) { //--- A vista
                        var textoAux = "";
                        //                        textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                        //                        if (coefParcelamento == 0) { //--- sem juros
                        //                            textoAux += ' sem juros';
                        //                        } else { //--- com juros
                        //                            textoAux += ' com juros';
                        //                        };
                        if (valorEntrada == 0) { //--- sem entrada
                            textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                            if (coefParcelamento == 0) { //--- sem juros
                                textoAux += ' sem juros';
                            }
                            else { //--- com juros
                                textoAux += ' com juros';
                            };
                        } else { //--- com entrada
                            textoAux = 'Entrada de R$ ' + parseFloat(valorEntrada).formatNumber(2, true);
                            if (textoAux != '') {
                                textoAux += ' + ' + qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                            } else {
                                textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                            };
                            if (coefParcelamento == 0) { //--- sem juros
                                textoAux += ' sem juros';
                            } else { //--- com juros
                                textoAux += ' com juros';
                            };
                        };
                        textoEscolha = textoAux;
                    } else { //--- Parcelado
                        var textoAux = "";
                        //Entrada de R$ 1.380,00 + 3x de R$1.105,53 com juros
                        if (valorEntrada == 0) { //--- sem entrada
                            textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                            if (coefParcelamento == 0) { //--- sem juros
                                textoAux += ' sem juros';
                            }
                            else { //--- com juros
                                textoAux += ' com juros';
                            };
                        } else { //--- com entrada
                            textoAux = 'Entrada de R$ ' + parseFloat(valorEntrada).formatNumber(2, true);
                            if (textoAux != '') {
                                textoAux += ' + ' + qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                            } else {
                                textoAux += qtdParcelas + 'x de R$ ' + parseFloat(valorParcela).formatNumber(2, true);
                            };
                            if (coefParcelamento == 0) { //--- sem juros
                                textoAux += ' sem juros';
                            } else { //--- com juros
                                textoAux += ' com juros';
                            };
                        };
                        textoEscolha = textoAux;
                    };

                    $html('tdPagamento', nomeOpcao);
                    $html('tdFormaPagamento', textoEscolha);
                    //$('tdTotalReserva').innerHTML = 'R$ ' + parseFloat(valorTotalEscolhido).formatNumber(2, true);
                    $html('tdTotalReserva', 'R$ ' + parseFloat(valorTotalEscolhido).formatNumber(2, true));

                    var emails = [];

                    emails.push(PubLogin.getSession('Email')); //-- Email do usuário logado
                    emails.push(clDetalhesPedido.getEmailEmpresa(DetalhesPacote.codOperadoraPacote).value); //-- Email da Operadora
                    emails.push(clDetalhesPedido.getEmailHospedagem(codPedidoVB).value); //-- Email da Operadora

                    //-- Pega os e-mails das agencias envolvidas
                    var agencias = AgenciaPacote.exec.getAgenciasSelecionadas();
                    for (var i = 0; i < agencias.length; i++)
                        emails.push(clDetalhesPedido.getEmailEmpresa(agencias[i]).value);

                    var agenciaSelecionada = agencias[0];
                    JDTdadosAgencia = new jDatatable(clDetalhesPacote.getNomeEmpresa(agenciaSelecionada).value);
                    var AgenciaEmail = JDTdadosAgencia.getDrValue(0, "NomeFantasia") + '</td></tr><tr><td style="padding: 3px;"><b> Telefone: </b>' + jsCommon.exec.formataTelefoneAgencias(JDTdadosAgencia.getDrValue(0, "Telefone"));
                    email = JDTdadosAgencia.getDrValue(0, "EmailRecebimentoPedidos");
                    $html('idAgencia', '<b>Agência: </b>' + JDTdadosAgencia.getDrValue(0, "NomeFantasia"));
                    $html('idTelefone', '<b> Telefone: </b>' + jsCommon.exec.formataTelefoneAgencias(JDTdadosAgencia.getDrValue(0, "Telefone")));
                    $html('idEmail', '<b>Email: </b>' + email);

                    //-- preenche operadora
                    var JDTdadosOperadora = new jDatatable(clDetalhesPedido.dadosAgencia_Operadora(codPedido).value);
                    $html('td1', '<b>Operadora: </b>' + JDTdadosOperadora.getDrValue(0, "Operadora"));

                    //-- MSG sucesso Reserva
                    //$html('sucessoReserva', 'Parabéns! Sua reserva foi efetuada com sucesso. <br />Foi enviada por e-mail uma cópia da sua solicitação de reserva.<br />');

                    //-- Encoder conteudo email
                    Encoder.EncodeType = "numerical";
                    Encoder.EncodeType = "entity";
                    var encoded = Encoder.htmlEncode(render.email($get('txtNumCartaoCredito'), AgenciaEmail, nomeOpcao, textoEscolha, valorTotalEscolhido));


                    // $html('idAgenciaEmailTeste',JDTdadosAgencia.getDrValue(0, "NomeFantasia")+ '<b> Telefone:</b>'+ jsCommon.exec.formataTelefoneAgencias(JDTdadosAgencia.getDrValue(0, "Telefone")));
                    // ENVIA EMAIL            
                    clDetalhesPedido.enviarEmail(encoded, emails, "Pacote");

                    // SALVA PEDIDO PACOTE AGENCIA
                    clDetalhesPedido.salvarPedidoPacote_Agencia(codPedido, agencias);


                    /************************************************************************
                    //-- BAIXA DE ESTOQUE DE AÉREO - NOVA ESTRUTURA | Wagner Vieira 1/10/2010
                    *************************************************************************/
                    var totPaxes = parseInt(jDS.getTotRegs("Pax"));
                    var dataIda = jDS.getDrValue("Geral", 0, "DataSaida");

                    for (var x = 0; x < listaCodTarifasAereo.length; x++) {
                        if (x > 0)
                            dataIda = jDS.getDrValue("Geral", 0, "DataVolta");

                        clDetalhesPedido.salvarMovEstoque(listaCodTarifasAereo[x], totPaxes, dataIda, dataIda, 1, parseInt(PubLogin.getSession('CodUsuario')), 1);
                    };



                    $html('valorPacoteHeader', parseFloat(valorTotalEscolhido).formatNumber(2, true));
                    //--***************************************************************--//
                    //--Verifica estoque e atribui estado de bloqueio ou extra bloqueio--//
                    //--Caso tenha estoque disponível se atribui estado de bloqueio--//
                    //--Se não se atribui estado de extra bloqueio--//

                    // Criado o metodo de CallBack para poder colocar a pelicula e removido no momento correto
                    // Task: D-27397
                    clDetalhesPedido.verificadorEstoque_UpdatePedidosStatus(codPedido, parseInt(PubLogin.getSession('CodUsuario')), callbacks.pelicula);
                    //--***************************************************************--//

                    //-- Passo Final
                    $html("passo4", '<b>Configure sua Viagem</b>');
                    $html("passo5", '<b>Pagamento</b>');
                    $("tablePassoPasso").style.backgroundImage = 'url("css/img/pct_passo_final.jpg")';
                };

                //-- Loading
                $("divLoading").style.display = 'none';
                return true;

                //                } else {
                //                    //--- Trata as respostas de erro do Clear Sale
                //                    if (statusClearSale == 3 || statusClearSale == 4) {
                //                        alert('Seu pedido não foi aprovado! Por favor, atualize seus dados cadastrais ou informe outro cartão de crédito.');
                //                    }
                //                    if (statusClearSale == 5) {
                //                        alert('Seu pedido não foi aprovado! Por favor, atualize seus dados cadastrais antes de realizar uma nova compra.');
                //                    }

                //                    // na Área do Agente (B2B), $("fundoLogin") é nulo
                //                    try {
                //                        $('fmLogin').innerHTML = '';
                //                        $("fundoLogin").style.display = 'none';
                //                    } catch (e) {

                //                    };
                //                };
            } else {
                alert('Você deve aceitar os termos e condições do pacote.');
            };
        },

        fechar: function() {
            $redirect('homeVB.vxlpub');
        },

        renderResumoReserva: function(pCodPedido) {
            return render.renderResumoReserva(pCodPedido);
        },

        callbacks: function() {
            callbacks.pelicula;
            // Criado o metodo de CallBack para poder colocar a pelicula e removido no momento correto
            // Task: D-27397
        }
    };
    
    this.constructor = new function()
    {
        tpl = new Template("PgtoPacote");
        
        if(jsCommon == undefined)
            jsCommon = new jCommon();
    };
};

//-- FUNCAO ENCODER
Encoder = {

	// When encoding do we convert characters into html or numerical entities
	EncodeType : "entity",  // entity OR numerical

	isEmpty : function(val){
		if(val){
			return ((val===null) || val.length==0 || /^\s+$/.test(val));
		}else{
			return true;
		}
	},
	// Convert HTML entities into numerical entities
	HTML2Numerical : function(s){
		var arr1 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		var arr2 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		return this.swapArrayVals(s,arr1,arr2);
	},	

	// Convert Numerical entities into HTML entities
	NumericalToHTML : function(s){
		var arr1 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		var arr2 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		return this.swapArrayVals(s,arr1,arr2);
	},


	// Numerically encodes all unicode characters
	numEncode : function(s){
		
		if(this.isEmpty(s)) return "";

		var e = "";
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (c < " " || c > "~")
			{
				c = "&#" + c.charCodeAt() + ";";
			}
			e += c;
		}
		return e;
	},
	
	// HTML Decode numerical and HTML entities back to original values
	htmlDecode : function(s){

		var c,m,d = s;
		
		if(this.isEmpty(d)) return "";

		// convert HTML entites back to numerical entites first
		d = this.HTML2Numerical(d);
		
		// look for numerical entities &#34;
		arr=d.match(/&#[0-9]{1,5};/g);
		
		// if no matches found in string then skip
		if(arr!=null){
			for(var x=0;x<arr.length;x++){
				m = arr[x];
				c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
				// if its a valid number we can decode
				if(c >= -32768 && c <= 65535){
					// decode every single match within string
					d = d.replace(m, String.fromCharCode(c));
				}else{
					d = d.replace(m, ""); //invalid so replace with nada
				}
			}			
		}

		return d;
	},		

	// encode an input string into either numerical or HTML entities
	htmlEncode : function(s,dbl){
			
		if(this.isEmpty(s)) return "";

		// do we allow double encoding? E.g will &amp; be turned into &amp;amp;
		dbl = dbl | false; //default to prevent double encoding
		
		// if allowing double encoding we do ampersands first
		if(dbl){
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}
		}

		// convert the xss chars to numerical entities ' " < >
		s = this.XSSEncode(s,false);
		
		if(this.EncodeType=="numerical" || !dbl){
			// Now call function that will convert any HTML entities to numerical codes
			s = this.HTML2Numerical(s);
		}

		// Now encode all chars above 127 e.g unicode
		s = this.numEncode(s);

		// now we know anything that needs to be encoded has been converted to numerical entities we
		// can encode any ampersands & that are not part of encoded entities
		// to handle the fact that I need to do a negative check and handle multiple ampersands &&&
		// I am going to use a placeholder

		// if we don't want double encoded entities we ignore the & in existing entities
		if(!dbl){
			s = s.replace(/&#/g,"##AMPHASH##");
		
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}

			s = s.replace(/##AMPHASH##/g,"&#");
		}
		
		// replace any malformed entities
		s = s.replace(/&#\d*([^\d;]|$)/g, "$1");

		if(!dbl){
			// safety check to correct any double encoded &amp;
			s = this.correctEncoding(s);
		}

		// now do we need to convert our numerical encoded string into entities
		if(this.EncodeType=="entity"){
			s = this.NumericalToHTML(s);
		}

		return s;					
	},

	// Encodes the basic 4 characters used to malform HTML in XSS hacks
	XSSEncode : function(s,en){
		if(!this.isEmpty(s)){
			en = en || true;
			// do we convert to numerical or html entity?
			if(en){
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&quot;");
				s = s.replace(/</g,"&lt;");
				s = s.replace(/>/g,"&gt;");
			}else{
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&#34;");
				s = s.replace(/</g,"&#60;");
				s = s.replace(/>/g,"&#62;");
			}
			return s;
		}else{
			return "";
		}
	},

	// returns true if a string contains html or numerical encoded entities
	hasEncoded : function(s){
		if(/&#[0-9]{1,5};/g.test(s)){
			return true;
		}else if(/&[A-Z]{2,6};/gi.test(s)){
			return true;
		}else{
			return false;
		}
	},

	// will remove any unicode characters
	stripUnicode : function(s){
		return s.replace(/[^\x20-\x7E]/g,"");
		
	},

	// corrects any double encoded &amp; entities e.g &amp;amp;
	correctEncoding : function(s){
		return s.replace(/(&amp;)(amp;)+/,"$1");
	},


	// Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
	swapArrayVals : function(s,arr1,arr2){
		if(this.isEmpty(s)) return "";
		var re;
		if(arr1 && arr2){
			//ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
			// array lengths must match
			if(arr1.length == arr2.length){
				for(var x=0,i=arr1.length;x<i;x++){
					re = new RegExp(arr1[x], 'g');
					s = s.replace(re,arr2[x]); //swap arr1 item with matching item from arr2	
				}
			}
		}
		return s;
	},

	inArray : function( item, arr ) {
		for ( var i = 0, x = arr.length; i < x; i++ ){
			if ( arr[i] === item ){
				return i;
			}
		}
		return -1;
	}

};
