var cep = '';
var tipoentrega = '';

$( function () {
    //calcula as forma de parcelamento
    calculaParcelamento(cep, tipoentrega);

    $(".forma_envio").click( function() {
        calculaParcelamento( $("#cep_usuario").val(), $(this).val() );
    });

    if ( $("#frete_tabela_dados .frete").css("display") == 'undefined' ) {
        $("#frete_total .frete").hide();
    } else {
        $("#frete_total .frete").show();
    }

    $("#frete_tabela_dados .forma_envio").click( function() {
        $("#frete_total .sinal").text(" + ");
        $("#frete_total .valor_frete").text($(this).parent().parent().find("span.maior").text());
    });

    $("#frete_tabela_pgto .forma_pagamento").click( function() {
        if ( $.trim($(this).val()) == '1' ) {
            $("#frete_total .maior .verde").text($(this).parents().find("#frmpedido").find("#pagamento_valorboleto").attr('alt'));
        } else {
            $("#frete_total .maior .verde").text($(this).parents().find("#frmpedido").find("#pagamento_valorcartao").attr('alt'));
        }
    });

    //trata a submissao do formulario
    $("#frmpedido .submitform").click( function() {

        var formapagamento = 0;
        var formaenvio = 0;
        var msg = '';

        $("#frete_tabela_pgto .forma_pagamento").each( function() {
            if ( $(this).is(":checked") ) formapagamento = $(this).val();
        });

        if ( formapagamento == 0 ) msg += "Selecione a forma de pagamento \n";

        if ( $("#frete_tabela_dados .frete").is(":visible") ) {
            $("#frete_tabela_dados .frete .forma_envio").each( function() {
                if ( $(this).is(":checked") ) {
                    formaenvio = $(this).val();
                }
            });
            if ( formaenvio == 0 ) msg += "Selecione a forma de envio \n";
        }
        
        if ( msg != '' ) {
            alert(msg);
            return false;
        } else {
            $("#frmpedido").submit();
        }

    });


});


function calculaParcelamento( cep, tipoentrega )
{
    var htmloption = '';
    var htmloptionboleto = '';
    $.getJSON(
        root_path+"/ajax/calculaFrete.ajax/",
        {
            cep: cep,
            tipoentrega: tipoentrega
        },
        function(data) {
            if ( data.records > 0 ) {
                var c=0;
                $.each( data.rows, function(i,item) {
                    if ( c == 0 ) htmloptionboleto = "<option value=" + item[3] + "> " + item[0] + "x de R$ " + item[3] +  "</option>";
                    htmloption += "<option value=" + item[0] + "> " + item[0] + "x de R$ " + item[1] +  " " + item[2] + "</option>";
                    c++;
                });
            }
            $("#parcelado").empty().append( htmloption );
            $("#boleto").empty().append( htmloptionboleto );
        });
}
