/*----------------------------------------------------------------------------->
FECHAMENTO
02/10/2009 http://wb4b.5pmweb.com?def=1&task=3833 Adicionado pagamento dinamico.
-------------------------------------------------------------------------------> */
function calcular_pagamento_composto( arquivo_fechamento, pagamento_valor_1 ) {
    PC_UnCheckPayments();
    var now = new Date(); //Variavel utilizada para forçar o post da página e não deixá-la em cache    
	var parametros = { 'acao' : 'pagamento_composto', 'pag_val_1' : pagamento_valor_1, 'arquivo_fechamento' : arquivo_fechamento,  'rnd' : now.getTime() };
    new Ajax.Request(arquivo_fechamento, {method: 'get', parameters : $H(parametros).toQueryString(), requestHeaders: {Accept: 'application/json'}, onLoading: function() {loading(imagens)}, onSuccess: function(req) { $('htbPagamentoComposto').innerHTML = req.responseText } } );
}

function calcular_valecompra( arquivo_fechamento, imagens, vale_compra ) {
    var url = arquivo_fechamento + "?acao=aplicar_valecompra&vcompra="+vale_compra;
    var now = new Date(); //Variavel utilizada para forçar o post da página e não deixá-la em cache
    url = url + "&rnd=" + now.getTime();
    new Ajax.Request(url, {method: 'get', requestHeaders: {Accept: 'application/json'}, onLoading: function() {loading(imagens)}, onSuccess: function(req) {window.location=arquivo_fechamento} } );
}

var messagePaymentType = "Você clicou no botão '{1}' da(o) {2}. Por favor, clique no botão referente a forma de pagamento escolhida.";
var pagamentoCartaoCreditoMarcado    = "";
var pagamentoEmAndamento = 0;
var pagamentoValido = false;

//Função que controla a validação de acordo com o botão selecionado
function ValidatePaymentType( tbPag, cartaoCreditoTipo, nomeBotao, nomePagamento ) { //Tabela do botão selecionado / Parcelas do pagamento (null quando não houver)
    var pagamentoCartaoCreditoMarcado = false;
    var pagamentoTipoMarcado          = false;
    var pagamentoDescricao            = desabilitaPagamento(tbPag);
    if ( typeof(nomePagamento)!="undefined" && nomePagamento != '') {
    	pagamentoDescricao = nomePagamento;
    }

    var error_detected = false;
    var error_message = "";

    if ( typeof(nomeBotao)=="undefined" || nomeBotao == null ) {
        nomeBotao = "Fechar Compra";
    }

    //Verifica se foi selecionado algum tipo de pagamento do grupo (CARTÃO, BOLETO...)
    if ( !CheckPaymentType( $(tbPag) ) && tbPag != "htbPagamentoComposto" ) {
        tmp_msg = messagePaymentType.replace( '{1}', nomeBotao );
        error_message = tmp_msg.replace( '{2}', pagamentoDescricao );
        error_message += '\n';
        error_detected = true;
    }

    //Cartão de crédito habilitado
    if ( $("htbCreditCard") != null && !$("htbCreditCard").disabled ) {
        cartaoCreditoMarcado = CheckCreditCard("htbBandeiraCartao" + cartaoCreditoTipo );
        if ( cartaoCreditoMarcado > 0 ) {
            if ( cartaoCreditoMarcado != 11 ) {
                //Verifica se alguma parcela foi selecionada

                var parcelValue = 0;
                if ( $("htcParcelas" + cartaoCreditoTipo) ) {
                    parcelValue = CheckParcelCreditCard( "htcParcelas" + cartaoCreditoTipo );
                }
                else {
                    parcelValue = CheckParcelCreditCard( "tbParcela" + cartaoCreditoMarcado );
                }

                if ( !parseInt(parcelValue) ) {
                    error_message += "* Favor selecionar o número de parcelas";
                    error_message += '\n';
                    error_detected = true;
                }
            }
            if ( $("htbBandeiraCartao" + cartaoCreditoTipo ) == $("htbBandeiraCartaoLoja") ) {
                //Valida o numero de cartão de crédito, data de validade, etc
                erro_cartao = ValidateCreditCard(cartaoCreditoMarcado, "");
                if ( erro_cartao != "" ) {
                    error_message += erro_cartao;
                    error_detected = true;
                }
            }
        }
        else {
            error_message += "* Favor selecionar uma bandeira de Cartão de Crédito";
            error_message += '\n';
            error_detected = true;
        }
    }
    else {
        if( $("htbCreditCard") ) {
            $("htbCreditCard").disabled = ($("htbCreditCard") != null && !$("htbCreditCard").disabled);
        }
    }

    if(tbPag == "htbCompraProgramada"){
        var parcelValue = 0;
        parcelValue = CheckParcelCreditCard( "tbParcelaBoletoParcelado" );

// RSS - 22/12/2009 - http://wb4b.5pmweb.com?def=1&task=6175
// Utilizei o $ do prototype para garantir a compatibilidade e a simplicidade do código
//        termoCompromisso = document.getElementById("termoCompromisso");
//
//        if (!termoCompromisso && !termoCompromisso.checked){
        if ($('termoCompromisso') && !$('termoCompromisso').checked){
        	error_message += "* Favor ler e aceitar os termos de compromisso";
        	error_message += '\n';
        	error_detected =true;
        }

        if ( !parseInt(parcelValue) ) {
            error_message += "* Favor selecionar o número de parcelas";
            error_message += '\n';
            error_detected = true;
        }
    }

    if(tbPag == "htbPagamentoDinamico1"){
    	var parcelValue = 0;
    	parcelValue = CheckParcelCreditCard( "tbParcelaDinamico1" );
    	
    	if ( !parseInt(parcelValue) ) {
    		error_message += "* Favor selecionar o número de parcelas";
    		error_message += '\n';
    		error_detected = true;
    	}
    }
    if(tbPag == "htbPagamentoDinamico2"){
    	var parcelValue = 0;
    	parcelValue = CheckParcelCreditCard( "tbParcelaDinamico2" );
    	
    	if ( !parseInt(parcelValue) ) {
    		error_message += "* Favor selecionar o número de parcelas";
    		error_message += '\n';
    		error_detected = true;
    	}
    }

    if ( pagamentoEmAndamento == 0) {
        //Desabilita os outros meios de pagamento
        if ( $("htbValeCompra") != null ) { $("htbValeCompra").disabled = false; }
        if ( $("htbCreditCard") != null ) { $("htbCreditCard").disabled = false; }
        if ($("htbOnLine") != null ) {
            $("htbOnLine").disabled = false;
        }
        else {
            if ($("htbOnLineBradesco") != null ) { $("htbOnLineBradesco").disabled = false; }
            if ($("htbOnLineBB") != null )       { $("htbOnLineBB").disabled = false; }
        }

        if ($("htbBoleto") != null ) {
            $("htbBoleto").disabled = false;
            if( $('boleto_vencimento') &&  !consisteData($('boleto_vencimento').value) ) {
                error_message += "* Digite uma data válida para o vencimento do boleto";
                error_message += '\n';
                error_detected = true;
            }
        }

        if ($("htbDeposito") != null ) { $("htbDeposito").disabled = false; }

        if ($("htbFinan") != null ) {
            $("htbFinan").disabled = false;
        }
        else {
            if ($("htbFinanBradesco") != null ) { $("htbFinanBradesco").disabled = false; }
            if ($("htbFinanItau") != null )     { $("htbFinanItau").disabled = false; }
            if ($("htbFinanReal") != null )     { $("htbFinanReal").disabled = false; }
            if ($("htbFinanLoja") != null )     { $("htbFinanLoja").disabled = false; }
        }

        if ($("htbCheque") != null )  { $("htbCheque").disabled = false; }
        if ($("htbEntrega") != null ) { $("htbEntrega").disabled = false; }
        if ($("htbPagamentoDinamico1") != null ) { $("htbPagamentoDinamico1").disabled = false; }
        if ($("htbPagamentoDinamico2") != null ) { $("htbPagamentoDinamico2").disabled = false; }

        if ($("htbPagamentoComposto") != null && tbPag == "htbPagamentoComposto" ) {
            $("htbPagamentoComposto").disabled = false;

            PC_UnCheckPayments();

            // Verifica se foi selecionado algum tipo de pagamento do grupo (CARTÃO, BOLETO...)
            if ( !( PC_CheckPaymentType( $(tbPag), 1) && PC_CheckPaymentType( $(tbPag), 2) ) ) {
                error_message += "* Por favor, selecione duas formas de pagamento para o seu pedido";
                error_message += '\n';
                error_detected = true;
            }
            else {

                cartaoMarcado_1 = PC_CheckCreditCard(1);
                if ( cartaoMarcado_1 > 0 ) {
                    parcelaCartao_1 = $("parcela_" + cartaoMarcado_1 + "_1");
                    if ( parcelaCartao_1 ) {
                        erro_cartao_1 = "";
                        if ( cartaoMarcado_1 != 6 ) {
                            //Valida o numero de cartão de crédito, data de validade, etc
                            erro_cartao_1 = ValidateCreditCard(cartaoMarcado_1, "_1");
                        }
                        // Verifica se alguma parcela foi selecionada
                        error_parcela_1 = !parseInt(parcelaCartao_1.value);

                        if ( error_parcela_1 || erro_cartao_1 != "" ) {
                            error_message += "\nVerifique os problemas abaixo na primeira forma de pagamento\n";

                            if ( erro_cartao_1 )
                                error_message += erro_cartao_1;

                            if (  error_parcela_1 )
                                error_message += "* Favor selecionar o número de parcelas da primeira forma de pagamento" + "\n";

                            error_message += '\n';
                            error_detected = true;
                        }
                    }
                }

                cartaoMarcado_2 = PC_CheckCreditCard(2);
                if ( cartaoMarcado_2 > 0 ) {
                    parcelaCartao_2 = $("parcela_" + cartaoMarcado_2 + "_2");
                    if ( parcelaCartao_2 ) {
                        //Valida o numero de cartão de crédito, data de validade, etc
                        erro_cartao_2 = "";
                        if ( cartaoMarcado_2 != 6 ) {
                            erro_cartao_2 = ValidateCreditCard(cartaoMarcado_2, "_2");
                        }

                        // Verifica se alguma parcela foi selecionada
                        error_parcela_2 = !parseInt(parcelaCartao_2.value);
                        if ( error_parcela_2 || erro_cartao_2 != "" ) {
                            error_message += "\nVerifique os problemas abaixo na segunda forma de pagamento\n";

                            if ( erro_cartao_2 )
                                error_message += erro_cartao_2;

                            if (  error_parcela_2 )
                                error_message += "* Favor selecionar o número de parcelas da segunda forma de pagamento" + "\n";

                            error_message += '\n';
                            error_detected = true;
                        }
                    }
                }
            }
        }

        if( !error_detected ) {
            pagamentoValido = true;
            if ( ! pagamentoEmAndamento ) {
                $("frmPagamento").submit();
            }
            pagamentoEmAndamento = 1;
        }
    }
    else {
        error_message = "Aguarde pois seu pedido já está sendo processado.";
        error_message += '\n';
    }

    if ( error_message ) {
        alert(error_message);
    }
}

function ValidadorOnSubmit() {
    return false ; //pagamentoValido;
}

function PC_UnCheckPayments() {
    //desmarca todas as formas de pagamento unicas (CARTÃO, BOLETO...)
    var coll = document.getElementsByTagName("input");
    for ( var i=0; i< coll.length ; i++ ) {
        if ( coll.item(i).type == 'radio' ) {
            if ( ( coll.item(i).name == 'rbt_creditcard' || coll.item(i).name == 'rbt_parcela' || coll.item(i).name == 'rbt_pagamento') && coll.item(i).checked ) {
                coll.item(i).checked = false;
                break;
            }
        }
    }
}

function PC_CheckPaymentType( tbPag, tipo ) {
    var pagamentoTipoMarcado = false;

    //Verifica se foi selecionado algum tipo de pagamento do grupo Pagamento Composto
    var coll = tbPag.getElementsByTagName("input");
    for ( var i=0; i< coll.length ; i++ ) {
        if ( coll.item(i).type == 'radio' ) {
            if ( coll.item(i).name == ('rbt_pagamento_'+tipo) && coll.item(i).checked &&
                    coll.item(i).name == ('rbt_pagamento_'+tipo) && coll.item(i).checked ) {
                pagamentoTipoMarcado = true;
                break;
            }
        }
    }
    return pagamentoTipoMarcado;
}

//Retorna o cartão que foi selecionado (zero caso não tenha sido marcado nenhum)
function PC_CheckCreditCard( tipo ) {
    returnValue = 0;

    visa = $("rbt_cc_visa_" + tipo);
    vele = $("rbt_cc_vele_" + tipo);
    mast = $("c_rbt_cc_mast_" + tipo);
    dinr = $("c_rbt_cc_dinr_" + tipo);
    amex = $("c_rbt_cc_amex_" + tipo);
	hipercard = $("c_rbt_cc_hipercard_" + tipo);

    if ( visa && visa.checked ) { returnValue = visa.value; }
    if ( vele && vele.checked ) { returnValue = vele.value; }
    if ( mast && mast.checked ) { returnValue = mast.value; }
    if ( dinr && dinr.checked ) { returnValue = dinr.value; }
    if ( amex && amex.checked ) { returnValue = amex.value; }
	if ( hipercard && hipercard.checked ) { returnValue = hipercard.value; }
    return returnValue;
}

function pc_abre_opcao(tblPag, opcPag, numTipo, radioButton ) {
    if ( ! pagamentoEmAndamento ) {
        tbPag = tblPag + opcPag + "_" + numTipo;
        htbCartao       = tblPag + "_" + numTipo;

        set_style_none("htbCartaoCliente_" + numTipo, tblPag + "_" + numTipo );
        set_style_none("htbCartaoLoja_" + numTipo, tblPag + "_" + numTipo );
        if ( htbCartao == "htbCartaoCliente_" + numTipo ) {
            set_style_none("htbCartaoClienteVisa_" + numTipo, tbPag );
            set_style_none("htbCartaoClienteMast_" + numTipo, tbPag );
            set_style_none("htbCartaoClienteDinr_" + numTipo, tbPag );
            set_style_none("htbCartaoClienteAmex_" + numTipo, tbPag );
            set_style_none("htbCartaoClienteVisaElectron_" + numTipo, tbPag );
			set_style_none("htbCartaoClienteHipercard_" + numTipo, tbPag );
            $(htbCartao).style.display = "";
        }
        if ( htbCartao == "htbCartaoLoja_" + numTipo ) {
            set_style_none("htbCartaoLojaVisa_" + numTipo, tbPag );
            set_style_none("htbCartaoLojaMast_" + numTipo, tbPag );
            set_style_none("htbCartaoLojaDinr_" + numTipo, tbPag );
            set_style_none("htbCartaoLojaAmex_" + numTipo, tbPag );
			set_style_none("htbCartaoLojaHipercard_" + numTipo, tbPag );
            $(htbCartao).style.display = "";
        }
        set_style_none("htbBradesco_" + numTipo, tbPag );
        set_style_none("htbBB_" + numTipo, tbPag );
        set_style_none("htbItau_" + numTipo, tbPag );
        set_style_none("htbBoleto_" + numTipo, tbPag );
        set_style_none("htbDeposito_" + numTipo, tbPag );
        set_style_none("htbFinanBradesco_" + numTipo, tbPag );
        set_style_none("htbFinanItau_" + numTipo, tbPag );
        set_style_none("htbFinanReal_" + numTipo, tbPag );
        set_style_none("htbFinanLoja_" + numTipo, tbPag );
        set_style_none("htbCheque_" + numTipo, tbPag );
        set_style_none("htbCheque_" + numTipo, tbPag );
        set_style_none("htbEntrega_" + numTipo, tbPag );
        set_style_none("htbPagamentoDinamico1_" + numTipo, tbPag );
        set_style_none("htbPagamentoDinamico2_" + numTipo, tbPag );

        PC_UnCheckPayments();
        descerPagina( "htbPagamentoComposto" );

        $(tbPag).style.display = "";
        $(radioButton).checked = true;
    }
    else {
        error_message = "Aguarde pois seu pedido já está sendo processado.";
        alert(error_message)
    }
}

function CheckPaymentType( tbPag ) {
    var pagamentoTipoMarcado = false;
    var coll = tbPag.getElementsByTagName("input");

    //Verifica se foi selecionado algum tipo de pagamento do grupo (CARTÃO, BOLETO...)
    for ( var i=0; i< coll.length ; i++ ) {
        if ( coll.item(i).type == 'radio' ) {
            if ( coll.item(i).name == 'rbt_pagamento' && coll.item(i).checked ) {
                pagamentoTipoMarcado = true;
                break;
            }
        }
    }
    return pagamentoTipoMarcado;
}

//Retorna o cartão que foi selecionado (zero caso não tenha sido marcado nenhum)
function CheckCreditCard( cartaoCreditoTipo ) {
    var returnValue = 0;
    var pagamentoCartaoCreditoMarcado = false;
    var coll = $(cartaoCreditoTipo).getElementsByTagName("input");

    //verifica se foi marcado algum cartão
    for ( var i=0; i< coll.length ; i++ ) {
        if ( coll.item(i).type == 'radio' ) {
            if ( coll.item(i).name == 'rbt_creditcard' && coll.item(i).checked ) {
                returnValue = coll.item(i).value;
                pagamentoCartaoCreditoMarcado = true;
                break;
            }
        }
    }
    return returnValue;
}

//Retorna a parcela do cartão que foi selecionado (zero caso não tenha sido marcada nenhuma)
function CheckParcelCreditCard( tabelaParcela ) {
    var paymentParcelValue = 0;
    if ($(tabelaParcela) == null) {
    	return -1;
    }
    var tabelaParcelaAux = $(tabelaParcela).getElementsByTagName("input");

    for ( var i=0; i < tabelaParcelaAux.length; i++ ) {
        if ( tabelaParcelaAux.item(i).type == 'radio' && tabelaParcelaAux.item(i).checked ) {
            paymentParcelValue = tabelaParcelaAux.item(i).value;
            break;
        }
    }
    return paymentParcelValue;
}

function MarkPaymentType( cartaoCreditoTipo, pagamentoCartaoCredito, pagamentoTipoID ) {
    var coll = $(pagamentoCartaoCredito);
    coll.checked = true;

    //verifica se foi marcado algum cartão
    var coll = $( "htbBandeiraCartao" + cartaoCreditoTipo ).getElementsByTagName("input");
    for ( var i=0; i < coll.length; i++ ) {
        if ( coll.item(i).type == 'radio' ) {
            if ( coll.item(i).name == 'rbt_creditcard' && $('tbParcela' + coll.item(i).value) ) {
                $('tbParcela' + coll.item(i).value).style.display = "none";
            }
        }
    }
    if ( $('tbParcela' + pagamentoTipoID) ) {
        $('tbParcela' + pagamentoTipoID).style.display = "";
    }
}

function set_style_none(target_div, test_div) {
    if ( $(target_div) != null && !($(target_div)==$(test_div)) )
        $(target_div).style.display="none";
}

var scrollInt;
var scrTime, scrSt, scrDist, scrDur, scrInt;

/* SCROLL FUNCTIONS */
function scrollPage() {
    scrTime += scrInt;
    if (scrTime < scrDur) {
        window.scrollTo( 0, easeInOut(scrTime,scrSt,scrDist,scrDur) );
    } else {
        window.scrollTo( 0, scrSt+scrDist );
        clearInterval(scrollInt);
    }
}

/* EASING FUNCTIONS */
function easeInOut(t,b,c,d) {
    return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;
}

function descerPagina( elementoTop ) {
    // set scroll target
    if (window.scrollY)
        scrSt = window.scrollY;
    else if (document.documentElement.scrollTop)
        scrSt = document.documentElement.scrollTop;
    else
        scrSt = document.body.scrollTop;

    scrDist = ( $(elementoTop).offsetTop + 70 ) - scrSt;
    scrDur = 500;
    scrTime = 0;
    scrInt = 10;

    // set interval
    clearInterval(scrollInt);
    scrollInt = setInterval( scrollPage, scrInt );
}

function abre_opcao(tbPag, rdButton, tblTipo, tipoCC, rbtCC, tipoPagID, scrDistElement ) {
    if ( ! pagamentoEmAndamento ) {
        set_style_none("htbCreditCard", tbPag );
        set_style_none("htbOnLineBradesco", tbPag );
        set_style_none("htbOnLineBB", tbPag );
        set_style_none("htbOnLineItau", tbPag );
        set_style_none("htbBoleto", tbPag );
        set_style_none("htbDeposito", tbPag );
        set_style_none("htbFinanBradesco", tbPag );
        set_style_none("htbFinanItau", tbPag );
        set_style_none("htbFinanReal", tbPag );
        set_style_none("htbFinanLoja", tbPag );
        set_style_none("htbCheque", tbPag );
        set_style_none("htbCheque", tbPag );
        set_style_none("htbEntrega", tbPag );
        set_style_none("htbPagamentoDinamico1", tbPag );
        set_style_none("htbPagamentoDinamico2", tbPag );
        set_style_none("htbPagamentoComposto", tbPag );
        set_style_none("htbCompraProgramada", tbPag );

        $(tbPag).style.display="";

        if ( $(rdButton) )
            $(rdButton).checked = true;

        elementoTop = tbPag;
        if ( scrDistElement != "" ) {
            elementoTop = scrDistElement;
        }
        descerPagina( elementoTop );

        if ( tblTipo ) {
            d_cli = "htbBandeiraCartaoCliente" + tipoCC;
            d_loj = "htbBandeiraCartaoLoja" + tipoCC;

            set_style_none("htbBandeiraCartaoClienteVisa", d_cli );
            set_style_none("htbBandeiraCartaoClienteVisaElectron", d_cli );

            set_style_none("htbBandeiraCartaoClienteMast", d_cli );
            set_style_none("htbBandeiraCartaoClienteAmex", d_cli );
            set_style_none("htbBandeiraCartaoClienteHiper", d_cli );
            set_style_none("htbBandeiraCartaoClienteDinr", d_cli );
			
			set_style_none("htbBandeiraCartaoClienteHipercard", d_cli );

            set_style_none("htbBandeiraCartaoLojaHiper", d_loj );
            set_style_none("htbBandeiraCartaoLojaVisa", d_loj );
            set_style_none("htbBandeiraCartaoLojaMast", d_loj );
            set_style_none("htbBandeiraCartaoLojaAmex", d_loj );
            set_style_none("htbBandeiraCartaoLojaDinr", d_loj );
			set_style_none("htbBandeiraCartaoLojaHipercard", d_loj );

            set_style_none("htbBandeiraCartaoCliente", "htbBandeiraCartao" + tblTipo );
            set_style_none("htbBandeiraCartaoLoja", "htbBandeiraCartao" + tblTipo );

            $("htbBandeiraCartao" + tblTipo + tipoCC).style.display="";
            $("htbBandeiraCartao" + tblTipo ).style.display="";

            $(rbtCC).checked = true;
            MarkPaymentType(tblTipo , rbtCC, tipoPagID );
        }
    }
    else {
        error_message = "Aguarde pois seu pedido já está sendo processado.";
        alert(error_message)
    }
}

function set_element_disabled(html_element, test_element) {
    if ($(html_element) != null ) {
        $(html_element).disabled = !($(html_element) == $(test_element));
        if ( ! $(html_element).disabled ) {
            return true;
        }
    }
    return false;
}

function desabilitaPagamento(tbPag) {
    var pgtDesc = "";

    //Desabilita os outros meios de pagamento
    if ( set_element_disabled("htbValeCompra", tbPag) ) { pgtDesc = "Vale-Compra"; }
    if ( set_element_disabled("htbCreditCard", tbPag) ) { pgtDesc = "Cartão de Crédito"; }

    if ( set_element_disabled("htbOnLine", tbPag ) ) {
        pgtDesc = "Transferência Eletrônica";
    }
    else {
        if ( set_element_disabled("htbOnLineBradesco", tbPag ) ) { pgtDesc = "Transferência Eletrônica Bradesco"; }
        if ( set_element_disabled("htbOnLineBB", tbPag ) ) { pgtDesc = "Transferência Eletrônica Banco do Brasil"; }
        if ( set_element_disabled("htbOnLineItau", tbPag ) ) { pgtDesc = "Transferência Eletrônica Itaú Shopline"; }
    }

    if ( set_element_disabled("htbBoleto", tbPag ) ) { pgtDesc = "Boleto Bancário"; }
    if ( set_element_disabled("htbDeposito", tbPag ) ) { pgtDesc = "Depósito Bancário"; }

    if ( set_element_disabled("htbFinan", tbPag ) ) {
        pgtDesc = "Financiamento Online";
    }
    else {
        if ( set_element_disabled("htbFinanBradesco", tbPag ) ) { pgtDesc = "Financiamento Bradesco"; }
        if ( set_element_disabled("htbFinanItau", tbPag ) ) { pgtDesc = "Financiamento Itaú Shopline"; }
        if ( set_element_disabled("htbFinanReal", tbPag ) ) { pgtDesc = "Financiamento ABN"; }
        if ( set_element_disabled("htbFinanLoja", tbPag ) ) { pgtDesc = "Financiamento Online"; }
    }

    if ( set_element_disabled("htbCheque", tbPag ) ) { pgtDesc = "Cheque"; }
    if ( set_element_disabled("htbEntrega", tbPag ) ) { pgtDesc = "Contra entrega"; }
    if ( set_element_disabled("htbPagamentoDinamico1", tbPag ) ) { pgtDesc = "Pagamento Dinamico1"; }
    if ( set_element_disabled("htbPagamentoDinamico2", tbPag ) ) { pgtDesc = "Pagamento Dinamico2"; }
    if ( set_element_disabled("htbPagamentoComposto", tbPag ) ) { pgtDesc = "Pagamento Composto"; }

    return pgtDesc;
}

function ValidateCreditCard( cartaoCreditoTipo, tipo ) {
    var strReturn = "";
    var yearBase = 2000;

    if ( $('txtCC_Numero'+tipo).value != '' ) {
        if (checkCC($('txtCC_Numero'+tipo).value, cartaoCreditoTipo) != 0) { strReturn += "* Cartão de Crédito inválido\n"; }
    }
    else {
        strReturn += "* Informe o número do cartão de crédito;\n";
    }

    if ( $('txtCC_CVC'+tipo).value == '' )  { strReturn += "* Informe o código de segurança do seu cartão;\n"; }
    if ( $('txtCC_Nome'+tipo).value == '' ) { strReturn += "* Informe o nome do titular do cartão de crédito;\n"; }

    if ( $('txtCC_Mes'+tipo).value != '' ) {
        if ( $('txtCC_Mes'+tipo).value > 12 ) { strReturn += "* Mês Inválido\n"; }
    }
    else {
        strReturn += "* Informe o mês de validade do cartão de crédito;\n";
    }

    if ( $('txtCC_Ano'+tipo).value != '' ) {
        if ( !(isDigit($('txtCC_Mes'+tipo).value) && isDigit($('txtCC_Ano'+tipo).value)) ) {
            strReturn += "* Data Inválida;\n";
        }
        else {
            var dateTime = new Date();
            if ( yearBase + parseInt($('txtCC_Ano'+tipo).value) > dateTime.getFullYear() + 10 )
                strReturn += "* Ano da validade está incorreto, por favor, verifique-o logo abaixo do número do cartão;\n";

            if ( yearBase + Number($('txtCC_Ano'+tipo).value) < Number(dateTime.getFullYear()))
                strReturn += "* Cartão Expirado;\n";
            else if ( (yearBase + Number($('txtCC_Ano'+tipo).value) == Number(dateTime.getFullYear())) && (Number($('txtCC_Mes'+tipo).value) < Number(dateTime.getMonth()) + 1))
                strReturn += "* Cartão Expirado;\n";
        }
    }
    else {
        strReturn += "* Informe o ano de validade do cartão de crédito;\n";
    }

    if ( $('txtCC_Endereco'+tipo) == '' ) { strReturn += "* Informe o Endereço do titular do cartão de crédito;\n"; }

    if ( $('txtCC_CepA'+tipo).value != '' && $('txtCC_CepB'+tipo).value != '' ) {
        cep = new String( Trim( $('txtCC_CepA'+tipo).value + "-" + $('txtCC_CepB'+tipo).value) );
        if( !consisteCEP ( cep ) ) { strReturn += "* Digite um CEP válido (ex.: 99999-999);\n"; }
    }
    else {
        strReturn += "* Informe o CEP do titular do cartão de crédito;\n";
    }
    return strReturn;
}

function isDigit(num) {
    var regex = /^\d{1,2}$/;
    return regex.test(num);
}

function checkCC( ccnumber, cctype) {
    var re;
    re = / /gi;
    ccnumber = ccnumber.replace(re, '');

    if (ccnumber.charAt(0) == '0')
        ccnumber = ccnumber.substr(1, ccnumber.length );

    switch (cctype) {
        case '6' : cclength = [13,16]; ccprefix = [4];     ccid = 1; break;
        case '7' : cclength = [16];    ccprefix = [51,52,53,54,55]; ccid = 2; break;
        case '9' : cclength = [15];    ccprefix = [34,37]; ccid = 3; break;
        case '8' : cclength = [14];    ccprefix = [300,301,302,303,304,305,36,38]; break;
        case '24': cclength = [15,16]; ccprefix = [3,2131,1800]; break;
//      case 'C' : cclength = [19];    ccprefix = [507860]; break
    }

    if ( cctype > 0 ) {
        if (cctype == '24') {
            result = ValidCC_HCRD(ccnumber);
        }
        else {
            prefixvalid=false;
            lengthvalid=false;

            for (var i=0; i < ccprefix.length; i++) {
                if (ccnumber.indexOf(ccprefix[i])==0)
                    prefixvalid=true;
            }

            for (var i=0; i < cclength.length; i++) {
                if (ccnumber.length == cclength[i])
                    lengthvalid=true;
            }

            result=0;
            if (! prefixvalid )
                result=result+1;

            if (! lengthvalid )
                result=result+2;

            qsum=0;
            for (var x=0; x < ccnumber.length; x++) {
                ch=ccnumber.substr(ccnumber.length - x - 1,1);
                if (x % 2 != 0) {
                    sum = 2*parseInt(ch);
                    qsum = qsum +(sum % 10);
                    if (sum > 9)
                        qsum = qsum + 1;
                }
                else
                    qsum = qsum + parseInt(ch);
            }

            if (qsum % 10 != 0)
                result = result + 4;

            if (cclength.length = 0)
                result = result + 8;
        }
        return result;
    }
}

function ValidCC_HCRD(psVal) {
    if ((psVal.length != 13) || ((psVal.substr(0,1) != '1') && (psVal.substr(0,1) != '4') && (psVal.substr(0,1) != '6')) )
        return 1;
    else
        return 0;
}
