AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.80
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/public_html/lrsys_apps/dialogo/ui/lib/orders/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/public_html/lrsys_apps/dialogo/ui/lib/orders/edit.js
/* global optionsProducts */
var ind_decimal = $("#_dec_point").val();
var ind_mil = $("#_mil_point").val();
var curr_code = $("#_curr_code").val();

$(document).ready(function () {

    var subTotalGeral = $("#total_product").attr("data-value");
    var totalFinal = $("#total").attr("data-value");
    var qtdAnterior = ["1.000"];
    var qtdCorrente = 1;
    var validaDecimal;
    $('.amount').autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 2, aSign: curr_code + ' '});

    var optionsProducts = '';
    var editProduct = false;
    var rowNum = $("#row").val();
    loadProducts();
    $(".progress").hide();
    $("#emsg").hide();

    //correção para setar os qtdanterior o valor inicial do input qtd
    var qty = document.getElementsByName('qty[]');
    for (i = 0; i < qty.length; i++) {
        qtdAnterior[qty[i].id] = qty[i].value;
    }


    var _url = $("#_url").val();
    var _msg_add_new_segment = $("#_msg_add_new_nature_operation").val();

    var address_tax_address = '';
    var address_billing_address = '';


    var $submit = $("#submit");
    var $ibox_form = $('#ibox_form');

    $submit.on('click', function (e) {
        e.preventDefault();
        $ibox_form.block({message: block_msg});
        $.post(_url + "orders/post-edit/", $("#ib_form").serialize())
                .done(function (data) {
                    if ($.isNumeric(data)) {
                        window.location = _url + 'orders/view/' + data;
                    } else {
                        $ibox_form.unblock();
                        var body = $("html, body");
                        body.animate({scrollTop: 0}, '1000', 'swing');
                        $("#emsgbody").html(data);
                        $("#emsg").show("slow");
                        loadProducts();
                    }
                });
    });



/////////////ADD NATURE OPERATION
    var ib_form_bootbox = "<form class=\"form-horizontal push-10\" method=\"post\" onsubmit=\"return false;\">\n    <div class=\"form-group\">\n        <div class=\"col-xs-12\">\n            <div class=\"form-material floating\">\n                <input class=\"form-control\" type=\"text\" id=\"nature_name\" name=\"nature_name\">\n                <label for=\"envato_api_key\">" + _L['Name'] + "</label>\n                           </div>\n        </div>\n    </div>\n\n</form>";
    $("#add_new_nature").click(function (e) {
        e.preventDefault();
        var box = bootbox.dialog({
            title: _L['Add New Nature Of Operation'],
            message: ib_form_bootbox,
            buttons: {
                success: {
                    label: _L['Save'],
                    className: "btn-primary",
                    callback: function () {
                        var name_val = $('#nature_name').val();
                        $.post(_url + "nature_operation/add-post/", {name: name_val})
                                .done(function (data) {
                                    if ($.isNumeric(data)) {
                                        loadNatureOperation('');
                                    } else {
                                        bootbox.alert(data);
                                    }
                                });
                    }
                }
            },
            show: false
        }
        );

        box.modal('show');
    });


    loadNatureOperation(1);


    /////////////////////ADD CONTACT

    ///////////////////////////////////////////
//////aciona o modal para adicionar o contato, evento de abertura do modal
    var $modal = $('#ajax-modal');
    $("#contact_add").click(function (e) {
        e.preventDefault();
        // create the backdrop and wait for next modal to be triggered
        $('body').modalmanager('loading');
        setTimeout(function () {
            $modal.load(_url + 'contacts/modal_add/', '', function () {
                $modal.modal();
                initModalAddContact();
            });

        }, 1000);
    });
    //////////////////////Acao de Salvar do Modal////////////////////////////
    $modal.on('click', '#modal_contact_submit', function (e) {
        e.preventDefault();
        // $('#ibox_form').block({message: block_msg});
        var _url = $("#_url").val();
        $.post(_url + 'contacts/add-post/', $("#modal_rform").serialize())
                .done(function (data) {
                    var _url = $("#_url").val();
                    if ($.isNumeric(data)) {
                        // location.reload();
//                    var is_recurring = $('#is_recurring').val();
//                    if(is_recurring == 'yes'){
//                        window.location = _url + 'invoices/add/recurring/' + data + '/';
//                    }
//                    else{
//                        window.location = _url + 'invoices/add/1/' + data + '/';
//                    }
                        $modal.modal('hide');
                        loadContacts();
                    } else {
                        //$('#ibox_form').unblock();
                        $("#modal_emsgbody").html(data);
                        $("#modal_emsg").show("slow");
                        document.location.href = "#modal_rform";
                    }
                });
    });
    loadContacts();


    /////////////////////////EDIT CONTACT//////////////////
//////aciona o modal para adicionar o contato, evento de abertura do modal
    var $modal = $('#ajax-modal');
    $("#contact_edit").click(function (e) {
        e.preventDefault();
        // create the backdrop and wait for next modal to be triggered
        $('body').modalmanager('loading');
        setTimeout(function () {
            $modal.load(_url + 'contacts/modal_edit_contact_address/', {cid: $("#client").val()}, function () {
                $modal.modal();
                initModalEditContact();
            });
        }, 1000);
    });
    //////////////////////Acao de Salvar do Modal////////////////////////////
    $modal.on('click', '#modal_edit_address_contact_submit', function (e) {
        e.preventDefault();
        // $('#ibox_form').block({message: block_msg});
        var _url = $("#_url").val();
        $.post(_url + 'contacts/edit-address-post/', $("#modal_edit_address_rform").serialize())
                .done(function (data) {
                    if ($.isNumeric(data)) {
                        //esconde a modal, e recarrega os valores dos selects, que podem ter sido adicionados
                        $modal.modal('hide');
                        update_address();
                    } else {
                        //$('#ibox_form').unblock();
                        $("#modal_edit_address_emsgbody").html(data);
                        $("#modal_edit_address_emsg").show("slow");
                        document.location.href = "#modal_rform";

                    }
                });
    });


    function update_address() {
        address_tax_address = '';
        address_billing_address = '';
        var adrs = $("#ta_address");
        adrs.html("");
        var _url = $("#_url").val();
        var cid = $('#client').val();
        if (cid != '') {
            $.post(_url + 'contacts/all-address/', {
                cid: cid

            })
                    .done(function (data) {
                        if (data.length>0 ) {
                            if (data[0].status == 'OK' || data[1].status == 'OK') {
                                address_tax_address = data[0];
                                address_billing_address = data[1];

                                adrs.html(data[0].address + " " + data[0].number + " " + data[0].complement +
                                        "\n" + data[0].city + " " + data[0].zip + "\n" + data[0].state + "\n" + data[0].country
                                        );
                                $("#type_address").removeClass('hide');
                                if (address_tax_address.billing_address == 'Y' || address_billing_address.billing_address == 'Y') {

                                    $(".type_address_billing").removeClass('hide');
                                } else {
                                    $(".type_address_billing").removeClass('hide');
                                    $(".type_address_billing").addClass('hide');
                                }
                                //remove a classe, para garantir que possui somente uma classe hide no spam
                                $("#spam-edit-client").removeClass('hide');
                                $("#spam-edit-client").addClass('hide');
                            } else {
                                $("#spam-edit-client").removeClass('hide');
                                adrs.html("");
                                $("#type_address").removeClass('hide');
                                $("#type_address").addClass('hide');
                            }
                        } else {
                            $("#spam-edit-client").removeClass('hide');
                            adrs.html("");
                            $("#type_address").removeClass('hide');
                            $("#type_address").addClass('hide');
                        }
                    });
        }

    }

    $('#client').on("change", function (e) {
        if ($(this).val() != '') {
            update_address();
        } else {
            $("#type_address").removeClass('hide');
            $("#type_address").addClass('hide');
            $("#spam-edit-client").removeClass('hide');
            $("#spam-edit-client").addClass('hide');


        }

        checkPrice();
    });

    $('#delivery_type').on("change", function (e) {
        checkPrice();
    });


    ////////////////////////////////////////////////////////////////
    $('.exchange_address').on("change", function (e) {
        if ($(this).val() === 'other') {
            $("#div_zip").show();
            $("#ta_address").hide();
        } else {
            $("#div_zip").hide();
            $("#ta_address").show();
            var data = "";
            if ($(this).val() == 'billing_address') {
                data = address_billing_address;
            } else {
                data = address_tax_address;
            }
            $("#ta_address").html(data.address + " " + data.number + " " + data.complement +
                    "\n" + data.city + " " + data.zip + "\n" + data.state + "\n" + data.country
                    );
        }
    });
    $("#div_zip").hide();


    ////////////////cidade endereço////////////////////////////////
    $('#city').html('<option value="state" selected>' + _L['Select State'] + '</option>');
    //função para listar cidades do estado selecionado
    $('#state').on('change', function () {
        buscaCity($(this).val(), "city");
    });


    function buscaCity(state, valor) {
        if (state) {
            $.getJSON($("#_url").val() + 'ajax/city', {state_id: state}, function (j) {
                var options = '<option value="city">' + _L['Select City'] + '</option>';
                for (var i = 0; i < j.length; i++) {
                    options += '<option value="' + j[i].id + '">' + j[i].city_name + '</option>';
                }

                $('#city').html(options);
                $('#city').select2("val", valor);
            });
        } else {
            //select_state contem o texto padrão campo hidden na page
            $('#city').html('<option value="state">' + _L['Select State'] + '</option>');
            $('#city').select2("val", "state");
        }
    }

    ///////////////////////BUSCA CEP////////////
    $('#zip').blur(function (e) {
        e.preventDefault();
        //esmaece a div e coloca o loading
        //vai esse block_msg nao sei da onde, mas fica o  loading
        $("#div_zip").block({message: block_msg});
        //cria o bootbox para cadastrar novo grupo
        $.post(_url + "ajax/zip", {zip: $("#zip").val()})
                .done(function (data) {
                    if (data[0].status == 'OK') {
                        $('#state').select2("val", data[0].state_id);
                        $("#address").val(data[0].address);
                        $("#neighborhood").val(data[0].neighborhood);
                        //necessário chamar aqui para garantir a busca das cidade pelo estado
                        //e atribuir a cidade selecionada
                        buscaCity(data[0].state_id, data[0].city_id);
                    } else {
                        alert(data[0].status);
                    }
                    $('#div_zip').unblock();
                });


    });


    ///////////////////FIM TRATAMENTO CLIENTE
    loadSalesman();
    loadConveyor();


    //tratamento dos itens
    $('.amount').autoNumeric('init');
    var _url = $("#_url").val();
    var $invoice_items = $('#invoice_items');
    var item_remove = $('#item-remove');
    item_remove.hide();
    var $modal = $('#ajax-modal');

    function loadOptions(id) {
        var options = '';
        loadProducts();
        var products = document.getElementsByName('id_product[]');
        for (var i = 0; i < optionsProducts.length; i++) {
            var registrado = false;
            for (j = 0; j < products.length; j++) {
                if (optionsProducts[i].id == products[j].value) {
                    registrado = true;
                }
            }

            if (optionsProducts[i].id == id || !registrado) {
                options += '<option value="' + i + '" data-product-id="' + optionsProducts[i].id + '">' + optionsProducts[i].description + '</option>';
            }
        }
        return options;

    }

    $('#item-add').on('click', function () {


        var optionsProduct = loadOptions("");
        if (!editProduct && optionsProduct.length > 0) {
            $(".qtyl").attr("readonly", "readonly");
            $(".product_select").attr("disabled", "disabled");
            $(".edit_product").removeClass('hide');
            $(".ok_product").addClass('hide');

            $invoice_items.find('tbody')
                    .append(
                            '<tr class="itm_nm_ftura "><td class="middle"><span id="product_code' + rowNum + '"></td>\n\
                       <td class="middle"><input type="hidden" data-row="' + rowNum + '" class="id_product" id="id_product_' + rowNum + '" name="id_product[]"><input type="hidden" id="i_' + rowNum + '" name="desc[]"><select data-row="' + rowNum + '"  id="select_product_' + rowNum + '" name="product[]"  class="form-control product_select"><select>\n\
                       <span class="text-red hide" id="msg_stock_' + rowNum + '"></spam></td>  \n\
                       <td class="middle"><input class="itm_nm_ftura" type="hidden"  id="unit_itm' + rowNum + '">\n\
                       <input type="text" data-net-weight="0.00" data-gross-weight="0.00" readonly class="form-control qtyl qtyVal' + rowNum + '"  value="1' + ind_decimal + '000" name="qty[]" id="' + rowNum + '">\n\
                       <input type="hidden" name="qtdBe[]" id="qtdBe' + rowNum + '" value="1' + ind_decimal + '000"></td><td class="middle">\n\
                       <input type="text" id="item_price' + rowNum + '"  value="' + curr_code + ' 0' + ind_decimal + '00" class="form-control item_price' + rowNum + ' am" name="amount[]"  readonly></td> \n\\n\
                       <td class="middle">\n\
                       <input type="text" id="item_discount' + rowNum + '"  value="' + curr_code + ' 0' + ind_decimal + '00" class="form-control item_discount item_discount' + rowNum + ' am" name="item_discount[]"></td> \n\
                       <td class="ltotal middle"><input type="text" value="' + curr_code + ' 0' + ind_decimal + '00"  id="lvtotal' + rowNum + '" class="form-control lvtotal lvtotal' + rowNum + ' am" readonly ></td>  <td class="middle col-xs-1">  <span class="btn btn-success btn-xs ok_product" id="ok_product' + rowNum + '" data-row="' + rowNum + '" ><i class="fa fa-check"></i> </span>   <span class="btn btn-success btn-xs edit_product hide" id="edit_product' + rowNum + '"  data-row="' + rowNum + '" ><i class="fa fa-edit"></i> </span> <span class="btn btn-danger btn-xs delete_product" data-row="' + rowNum + '" ><i class="fa fa-trash"></i> </span></td></tr>'
                            );
            $('[data-toggle="tooltip"]').tooltip();
            $(".product_select").select2({theme: "bootstrap"});
            editProduct = true;

            $("#select_product_" + rowNum).html('<option disabled="disabled" selected>' + _L['Select'] + '</option>' + optionsProduct);
            $("#select_product_" + rowNum).focus();
            $('#' + rowNum).autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 0, aSign: ''});


            $("#select_product_" + rowNum).on('change', function ()
            {
                $('#msg_stock_' + $(this).attr("data-row")).addClass('hide');

                // $("#select_product_" + rowNum).html('<option disabled="disabled" selected>' + _L['Select'] + '</option>' + loadOptions($(this).val()));
                $('#id_product_' + $(this).attr("data-row") + '').val(optionsProducts[$(this).val()].id);

                var qtd_itn = $('#' + $(this).attr("data-row") + '').val().replace(" " + optionsProducts[$(this).val()].item_sifr, "").replace(ind_mil, "").replace(ind_decimal, '.');
                editProduct = false;
                //remove os dados do produto da soma, caso o usuário esteja trocando o produto selecionadao
                subTotalGeral = parseFloat(subTotalGeral) - parseFloat($("#lvtotal" + $(this).attr("data-row")).val().replace(curr_code + " ", "").replace(ind_mil, "").replace(ind_decimal, '.'));

                $('#total_product').val((subTotalGeral + "").replace('.', ind_decimal));

                updateTotais();

                var valorTotalProduct = parseFloat(qtd_itn) * parseFloat((optionsProducts[$(this).val()].price + "").replace(ind_mil, "").replace(ind_decimal, '.'));
                $("#product_img" + $(this).attr("data-row")).attr('src', optionsProducts[$(this).val()].image);
                $("#product_code" + $(this).attr("data-row")).html(optionsProducts[$(this).val()].id);
                $("#unit_itm" + $(this).attr("data-row")).val(optionsProducts[$(this).val()].item_sifr);
                $("#item_price" + $(this).attr("data-row")).val(optionsProducts[$(this).val()].price);
                $("#lvtotal" + $(this).attr("data-row")).val((valorTotalProduct + "").replace('.', ind_decimal));
                $("#i_" + $(this).attr("data-row")).val(optionsProducts[$(this).val()].description);


                $('.am').autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 2, aSign: curr_code + ' '});
                $('.am').trigger('blur');
                //acrecenta o peso do produto no total de pesos

                updateWeight($(this).attr("data-row"), qtd_itn);


                //remove o disable do campo de quantidade após selecionar um produto
                $("#" + $(this).attr("data-row")).removeAttr('readonly');

                if (optionsProducts[$(this).val()].item_unit == 0) {
                    $('#' + $(this).attr("data-row") + '').autoNumeric('update', {aSep: ind_mil, aDec: ind_decimal, mDec: 3, aSign: ' ' + optionsProducts[$(this).val()].item_sifr, pSign: 's'});
                } else {
                    $('#' + $(this).attr("data-row") + '').autoNumeric('update', {aSep: ind_mil, aDec: ind_decimal, mDec: 0, aSign: ' ' + optionsProducts[$(this).val()].item_sifr, pSign: 's'});
                }

                admItens(rowNum, valorTotalProduct);


                checkPrice();
            });

            rowNum++;

        } else if (optionsProduct.length == 0) {
            bootbox.alert(_L['There are no items to add']);
        } else {
            bootbox.alert(_L['Select the item first.']);
        }
    });



    $invoice_items.on("click", ".edit_product", function (e) {
        $("#" + $(this).attr("data-row")).removeAttr('readonly');
        $("#select_product_" + $(this).attr("data-row")).removeAttr('disabled');
        var optionsProduct = loadOptions(optionsProducts[$("#select_product_" + $(this).attr("data-row")).val()].id);
        $("#select_product_" + $(this).attr("data-row")).html('<option disabled="disabled" selected>' + _L['Select'] + '</option>' + optionsProduct);
        $("#ok_product" + $(this).attr("data-row")).removeClass('hide');
        $("#edit_product" + $(this).attr("data-row")).addClass('hide');
    });

    $invoice_items.on("click", ".ok_product", function (e) {
        if ($("#select_product_" + $(this).attr("data-row")).val() != null) {
            $("#" + $(this).attr("data-row")).attr('readonly', 'readonly');
            $("#select_product_" + $(this).attr("data-row")).attr('disabled', 'disabled');
            $("#edit_product" + $(this).attr("data-row")).removeClass('hide');
            $("#ok_product" + $(this).attr("data-row")).addClass('hide');
        } else {
            bootbox.alert(_L['Select the item first.']);
        }
    });

    $invoice_items.on("click", ".delete_product", function (e) {

        var net_weight = $("#net_weight").val().replace(ind_mil, "").replace(ind_decimal, '.');
        var gross_weight = $("#gross_weight").val().replace(ind_mil, "").replace(ind_decimal, '.');
        if (net_weight.length == 0) {
            net_weight = 0;
        }
        if (gross_weight.length == 0) {
            gross_weight = 0;
        }
        gross_weight = parseFloat(gross_weight) - parseFloat($("#" + $(this).attr("data-row")).attr("data-gross-weight"));
        if (gross_weight < 0) {
            gross_weight = 0;
        }
        $("#gross_weight").val((gross_weight + "").replace('.', ind_decimal));

        net_weight = parseFloat(net_weight) - parseFloat($("#" + $(this).attr("data-row")).attr("data-net-weight"));
        if (net_weight < 0) {
            net_weight = 0;
        }
        $("#net_weight").val((net_weight + "").replace('.', ind_decimal));



        var val = $('.lvtotal' + $(this).attr("data-row")).val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.');
        $(this).closest('tr').remove();
        subTotalGeral = parseFloat(subTotalGera) - parseFloat(val);
        //  retornaDesconto();
        $('#total_product').val((parseFloat(subTotalGeral) + "").replace('.', ind_decimal));
        updateTotais();
        //atualiza pesos
        $('.amount').autoNumeric('update', {});
        $('.am').autoNumeric('update', {});
    });




    $invoice_items.on('blur', '.qtyl', function () {
        // verifico o preço do produto
        checkPrice();
    });

    $invoice_items.on('blur', '.item_discount', function () {
        // verifico o preço do produto
        checkPrice();
    });

    function updateTotalValue(id)
    {
    
        this.id = id;
        if ($('.qtyVal' + this.id).val() == "")
            return;
        var unit = $("#unit_itm" + this.id).val();
        var qtd_itn = parseFloat($('.qtyVal' + this.id).val().replace(" " + unit, "").replace(ind_mil, "").replace(ind_decimal, '.'));

        $('#qtdBe' + this.id).val(qtd_itn);
        var preco_itn = parseFloat($('.item_price' + this.id).val().replace(curr_code + " ", "").replace(ind_mil, "").replace(ind_decimal, '.'));
        var discount_itn = parseFloat($('.item_discount' + this.id).val().replace(curr_code + " ", "").replace(ind_mil, "").replace(ind_decimal, '.'));

        var valorTotal = qtd_itn * (preco_itn - discount_itn);

        $('.lvtotal' + this.id).val((valorTotal + "").replace('.', ind_decimal));
        var id = parseInt(this.id);
        (qtdAnterior[id]) ? qtdAnterior[id] = qtdAnterior[id] : qtdAnterior[id] = "1.000";
        var valorAnterior = parseFloat(qtdAnterior[id]) * preco_itn;

        var subTotalCorrente = "0.000";
        subTotalCorrente = parseFloat(subTotalGeral - valorAnterior).toFixed(2);
        subTotalGeral = parseFloat((parseFloat(subTotalCorrente) + parseFloat(valorTotal))).toFixed(2);
        $('#total_product').val((subTotalGeral + "").replace('.', ind_decimal));

        qtdAnterior[id] = qtd_itn;
        updateTotais();
        updateWeight(id, qtd_itn);


        editProduct = false;
        $('.amount').autoNumeric('update', {});
        $('.am').autoNumeric('update', {});
    }



    function updateWeight(row, qtd_itn) {
        var net_weight = $("#net_weight").val().replace(ind_mil, "").replace(ind_decimal, '.');
        var gross_weight = $("#gross_weight").val().replace(ind_mil, "").replace(ind_decimal, '.');
        if (net_weight.length == 0) {
            net_weight = 0;
        }
        if (gross_weight.length == 0) {
            gross_weight = 0;
        }
        gross_weight = parseFloat(gross_weight) - parseFloat($("#" + row).attr("data-gross-weight"));
        if (gross_weight < 0) {
            gross_weight = 0;
        }
        $("#gross_weight").val((gross_weight + "").replace('.', ind_decimal));
        net_weight = parseFloat(net_weight) - parseFloat($("#" + row).attr("data-net-weight"));
        if (net_weight < 0) {
            net_weight = 0;
        }
        $("#net_weight").val((net_weight + "").replace('.', ind_decimal));

        var gross_weight_product = parseFloat(qtd_itn) * parseFloat(optionsProducts[ $("#select_product_" + row).val()].gross_weight);
        $("#gross_weight").val(((parseFloat(gross_weight) + gross_weight_product) + "").replace('.', ind_decimal));
        $("#" + row).attr("data-gross-weight", gross_weight_product);

        var net_weight_product = parseFloat(qtd_itn) * parseFloat(optionsProducts[ $("#select_product_" + row).val()].net_weight);
        $("#net_weight").val(((parseFloat(net_weight) + net_weight_product) + "").replace('.', ind_decimal));
        $("#" + row).attr("data-net-weight", net_weight_product);
        //update na formatação do campo
        $('.amount').autoNumeric('update', {});
        $('.am').autoNumeric('update', {});
    }

    function admItens(item_id, item_price) {

        var unit = $("#unit_itm" + item_id).val();
        var preco_itn = ("" + item_price).replace(curr_code + " ", "");
        //   (idsItnsSlcd == "") ? idsItnsSlcd += item_id : idsItnsSlcd += "," + item_id;
        subTotalGeral = parseFloat(subTotalGeral) + parseFloat(preco_itn);
        $('#total_product').val((subTotalGeral + '').replace('.', ind_decimal));


        //  retornaDesconto();
        updateTotais();
    }

    function updateTotais() {
       
        var elemento = document.getElementsByName('id_product[]');
        $('#number_itens').val(elemento.length);
        $('#qtd_volumes').val(elemento.length);


        var qtds = document.getElementsByName('qty[]');
        var qtd = 0;
        for (i = 0; i < qtds.length; i++) {
            var unit = $("#unit_itm" + qtds[i].id).val();
            var qtd_itn = $('.qtyVal' + qtds[i].id).val().replace(" " + unit, "").replace(ind_mil, "").replace(ind_decimal, '.');

            qtd = parseFloat(qtd_itn) + parseFloat(qtd);
        }
        $('#qtd_itens').val(qtd);

        var discount = $("#discount").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.');
        if (discount.length === 0) {
            discount = 0;
        }

        var freight = $("#freight").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.');
        if (freight.length === 0) {
            freight = 0;
        }
        //pega o tipo d edesconto pelo valor do span, ao lado do componente
        if ($('#span_type_disc').html() === '%') {
            discount = (parseFloat(discount) * parseFloat($("#total_product").val().replace(curr_code, "").replace(' ', "").replace(ind_mil, "").replace(ind_decimal, '.'))) / 100;
        }
        $("#total").val((parseFloat(($("#total_product").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')) - parseFloat(discount) + parseFloat(freight)).toFixed(2) + "").replace('.', ind_decimal));
        $('.amount').autoNumeric('update', {});
        //regra para nao alterar as condições de parcelas, quando nao mecher em nada que nao tenha alterado o     

        //HOUVE ALTERAÇÃO DE VALOR, então atualiza a distribuição de parcelas
        if (parseFloat($("#total").attr("data-value")) != (parseFloat(($("#total_product").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')) - parseFloat(discount) + parseFloat(freight)).toFixed(2))) {
            $("#updateDataAmountDivided").val(1);
        }


        if ($("#updateDataAmountDivided").val() == 1) {
            if ($("#cdtpgto").val() == 3) {
                var parcelas = document.getElementsByName('price[]');
                $(".divided_price").val(curr_code + " " + formatMonetary((parseFloat(parseFloat(($("#total_product").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')) - parseFloat(discount) + parseFloat(freight)) / parcelas.length).toFixed(2) + "").replace('.', ind_decimal)));
                $(".divided_price").attr("data-value", (parseFloat(parseFloat(($("#total_product").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')) - parseFloat(discount) + parseFloat(freight)) / parcelas.length).toFixed(2) + "").replace('.', ind_decimal));
                $(".divided_price").attr("data-fixed", 0);
                $("#price_0").removeAttr("readonly");
            } else {
                $("#price_0").val($("#total").val());
                $("#price_0").attr("readonly", "readonly");
            }
        }

    }

    $('.exchange_type_discount').on("change", function (e) {
        if ($(this).val() === 'p') {
            $('#span_type_disc').html("%");
        } else {
            $('#span_type_disc').html(curr_code);
        }
        updateTotais();

    });


    $('.updateTotais').on("blur", function (e) {
        updateTotais();
    });

    ///fim do tratamento dos itens

    /// Transportador / Volumes tratamento de acordo com a forma de envio

    $('#shipping_method').on("change", function (e) {
        if ($(this).val() === '1') {
            $(".not_ship_method_3").show();
            $(".not_ship_method_1").hide();
        } else if ($(this).val() === '3') {
            $(".not_ship_method_1").show();
            $(".not_ship_method_3").hide();
        } else {
            $(".not_ship_method_1").show();
            $(".not_ship_method_3").show();
        }
    });

    if ($('#shipping_method').val() === '1') {
        $(".not_ship_method_3").show();
        $(".not_ship_method_1").hide();
    } else if ($('#shipping_method') === '3') {
        $(".not_ship_method_1").show();
        $(".not_ship_method_3").hide();
    } else {
        $(".not_ship_method_1").show();
        $(".not_ship_method_3").show();
    }

    ///////////////////TAG/////////////////////////

    //adicionando o memsa ação de grupo para tag

    var ib_form_bootbox_tag = "<form class=\"form-horizontal push-10\" method=\"post\" onsubmit=\"return false;\">\n    <div class=\"form-group\">\n        <div class=\"col-xs-12\">\n            <div class=\"form-material floating\">\n                <input class=\"form-control\" type=\"text\" id=\"tag_name\" name=\"tag_name\">\n                <label>" + _L['Tags'] + "</label>\n                           </div>\n        </div>\n    </div>\n\n</form>";

    $("#add_new_tag").click(function (e) {
        e.preventDefault();
        //cria o bootbox para cadastrar novo grupo
        bootbox.dialog({
            title: _L['Add New Tag'],
            message: ib_form_bootbox_tag,
            buttons: {
                success: {
                    label: "Save",
                    className: "btn-primary",
                    callback: function () {
                        var tag_name_val = $('#tag_name').val();
                        if (tag_name_val != '') {
                            $.post(_url + "tags/add-post-orders/", {tag: tag_name_val})
                                    .done(function (data) {
                                        if ($.isNumeric(data)) {
                                            loadTags();
                                            $('#tag_name').val("");
                                        } else {
                                            bootbox.alert(data);
                                            $('#tag_name').val("");
                                        }
                                    });
                        }
                    }
                }
            },
            show: true
        });
    });

    //aciona o método ao inciar
    loadTags();

    ///////////////////
    function loadProducts() {
        $.getJSON($("#_url").val() + 'ps/ajax-list', function (j) {
            optionsProducts = j;
        });
    }
    ;

    // Função para atualizar os preços customizados dos produtos
    function changePrice(price, e, margin_discount)
    {
  
        // altero o valor do produto
        $('#item_price' + e).val((price.replace('.', ',')));

        // verifico se o desconto oferecido é permitido
        var discount_itn = parseFloat($('.item_discount' + e).val().replace(curr_code + " ", "").replace(ind_mil, "").replace(ind_decimal, '.'));
        price = parseFloat(price.replace(',', '.'));

        if (discount_itn > (margin_discount / 100) * price)
        {
            $('.item_discount' + e).val(0);
            if (margin_discount > 0)
            {
                alert('O desconto não pode ser maior do que ' + margin_discount + '% do valor do produto.');
            } else
            {
                alert('Para este produto não é permitido dar desconto.');
            }
        }

        return true;
    }
    ;

    function checkPrice()
    {
        var product_id = null;
        var produts_details = null;
        var price = null;
        var account_id = $('#client').val();
        var delivery_type = $('#delivery_type').val();

        $('.id_product').each(function (f) {
            var e = $(this).attr('data-row');
            product_id = $(this).val();
            var qtd = $('.qtyVal' + e).val();

            var unit = $("#unit_itm" + e).val();
            var qtd = parseFloat(qtd.replace(" " + unit, "").replace(ind_mil, "").replace(ind_decimal, '.'));
            var custom_price = false;
            var margin_discount = 0;
            if (product_id > 0)
            {
                //carrega os dados do produto
                $.getJSON($("#_url").val() + 'ps/ajax-list/' + product_id, function (p) {
                    produts_details = p;
                    produts_details = produts_details[0];
                    var stockRegistrado = 0;
                    //verifica o estoque reristado já para o pedido
                    for (var key in qtdItensPedido) {
                        if (key == product_id) {
                            stockRegistrado += qtdItensPedido[key];
                        }
                    }



                    //meensagem e validação do estoque
                    var stock_av = "";
                    if (produts_details.item_unit == 1) {
                        $('.qtyVal' + e).autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 0, aSign: ' ' + produts_details.item_sifr, pSign: 's'});
                        stock_av = _L['stock available:'] + (parseFloat(produts_details.current_stock) + stockRegistrado).toFixed(0) + " " + produts_details.item_sifr;
                    } else {
                        $('.qtyVal' + e).autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 3, aSign: ' ' + produts_details.item_sifr, pSign: 's'});
                        stock_av = _L['stock available:'] + (parseFloat(produts_details.current_stock) + stockRegistrado) + " " + produts_details.item_sifr;
                    }
                    $('#msg_stock_' + e).html(stock_av);

                    if ((qtd) > parseFloat(produts_details.current_stock) + stockRegistrado) {
                        $('#msg_stock_' + e).removeClass('hide');
                    } else {
                        $('#msg_stock_' + e).addClass('hide');
                    }



                    //atribui os pesos dos itens
                    $('.qtyVal' + e).attr('data-net-weight', produts_details.net_weight);
                    $('.qtyVal' + e).attr('data-gross-weight', produts_details.gross_weight);



                    for (var j = 0; j < produts_details.custom_prices.length; j++)
                    {
                        price = produts_details.custom_prices[j].sales_price;
                        margin_discount = produts_details.custom_prices[j].margin_discount;

                        // Verifico o tipo de entrega
                        if (delivery_type === produts_details.custom_prices[j].type_delivery ||
                                produts_details.custom_prices[j].type_delivery === 'All' && custom_price == false)
                        {

                            // verifico se o account_id do cliente bate com o do preço
                            for (var k = 0; k < produts_details.custom_prices[j].account_ids.length; k++)
                            {
                                if (account_id > 0 && account_id == produts_details.custom_prices[j].account_ids[k])
                                {
                                    // ATUALIZAR O VALOR DO PRODUTO NO GRID
                                    changePrice(price, e, margin_discount);
                                    custom_price = true;
                                }
                            }

                            if (custom_price == false)
                            {
                                // verifico se o Segmento do cliente bate com o do preço
                                var segment_id = $('#client').find(":selected").attr('data-segment');
                                for (var k = 0; k < produts_details.custom_prices[j].segment_ids.length; k++)
                                {
                                    if (segment_id > 0 && segment_id == produts_details.custom_prices[j].segment_ids[k])
                                    {
                                        // ATUALIZAR O VALOR DO PRODUTO NO GRID
                                        changePrice(price, e, margin_discount);
                                        custom_price = true;
                                    }
                                }
                            }

                            if (custom_price == false)
                            {
                                //verifco a quantidade
                                if (qtd >= produts_details.custom_prices[j].quantity)
                                {
                                    // ATUALIZAR O VALOR DO PRODUTO NO GRID
                                    changePrice(price, e, margin_discount);
                                    custom_price = true;
                                }
                            }
                        }
                    }

                    // se não tem preço especial, coloco o preço default
                    if (custom_price == false)
                    {
                        // se não bater com nenhum custom price, coloca o preço defaul
                        margin_discount = produts_details.margin_discount;
                        changePrice(produts_details.price, e, margin_discount);
                    }

                    // atualizo os valores dos produtos
                    updateTotalValue(e);
                    return true;
                });
            }
        });
        return true;
    }
    ;

    $('#delivery_type').on("change", function (e) {
        //   console.log($(this).val());
        if ($(this).val() === 'Withdrawal')
        {
            $(".delivery-type-delivery").hide();
        } else
        {
            $(".delivery-type-delivery").show();
        }
    });







    $('.am').autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 2, aSign: curr_code + ' '});
    $('.am').trigger('blur');




    //método de pagamento
    $('#mtdopgto').on("change", function (e) {
        //regra que define o campo condição de pagamento ERP-437
        if ($(this).val() < 0) {
            $("#cdtpgto").val(3).trigger("change");
            $("#cdtpgto").attr('disabled', 'disabled');
            $(".multiplas").removeClass("hide");
        } else {
            $("#cdtpgto").removeAttr('readonly');
            $("#cdtpgto").removeAttr('disabled');
            $(".multiplas").addClass("hide");
        }
        if ($(this).val() > 0) {
            $('.destiny_payment_account').removeClass('hide');
            findDataSelect("#destiny_payment_account", "settings/pmethods-list-accounts/" + $(this).val(), $("#_lan_select_account").val());
        } else {
            $('.destiny_payment_account').addClass('hide');
            $('#destiny_payment_account').val('').trigger("change");
        }
        validaCheck();
    });


    $("#especification_payment").on("blur change click", ".days", function (e) {
        var data_row = $(this).attr("data-row");
        $.post(_url + "orders/days_to_date", {date: $("#sales_date").val(), days: $(this).val()})
                .done(function (data) {
                    $("#duedate_" + data_row).val(data);
                });
    });


    $("#especification_payment").on("blur change click", ".due_date_especification_payment", function (e) {
        var data_row = $(this).attr("data-row");
        $.post(_url + "orders/date_to_days", {date: $("#sales_date").val(), date_divided: $(this).val()})
                .done(function (data) {
                    $("#days_" + data_row).val(data);
                });
    });

//recalcula o valor das parcelas não fixadas
    $("#especification_payment").on("blur", ".divided_price", function (e) {
        if ($(this).attr("data-value") != parseFloat($(this).val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.'))) {
            $(this).attr("data-value", parseFloat($(this).val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')));
            $(this).attr("data-fixed", '1');

            var total = (parseFloat($("#total").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')).toFixed(2));
            var parcelas = document.getElementsByName('price[]');
            var i = 0;
            var cont_ParcelasDivided = 0;
            var total_fixed = 0;
            for (i = 0; i < parcelas.length; i++) {
                if ($("#price_" + i).attr("data-fixed") == 1) {
                    total_fixed = parseFloat(parseFloat(total_fixed) + parseFloat(($("#price_" + i).val() + "").replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.'))).toFixed(2);
                } else {
                    cont_ParcelasDivided++;
                }
            }

            if (cont_ParcelasDivided > 0 && parseFloat(total_fixed) < parseFloat(total)) {
                var new_divided = (parseFloat(total) - parseFloat(total_fixed)) / parseFloat(cont_ParcelasDivided);
                for (i = 0; i < parcelas.length; i++) {
                    if ($("#price_" + i).attr("data-fixed") == 0) {
                        $("#price_" + i).val(curr_code + " " + formatMonetary(parseFloat(new_divided).toFixed(2)));
                        $("#price_" + i).attr('data-value', parseFloat(new_divided).toFixed(2));
                    }
                }

            } else {
                //nesse caso não há nenhuma parcela disponível para atribuir o valor
                updateTotais();
            }
        }
    });


    function validaCheck() {
        if ($("#mtdopgto").val() == 2) {//para cheque
            if ($("#cdtpgto").val() == 3) {//parcelado
                $("#icon_cheque").addClass("hide");
                $(".multiplas").removeClass("hide");
                $(".mtdopgto_condition").val(2).trigger("change");
                $(".mtdopgto_condition").attr("disabled", 'disabled');
                $(".destiny_payment_account").addClass("hide");
                findDataSelect(".destiny_payment_account_condition", "settings/pmethods-list-accounts/2", $("#_lan_select_account").val());
                $("#price_0").removeAttr("readonly");
            } else {
                $(".destiny_payment_account").removeClass("hide");
                $("#icon_cheque").removeClass("hide");
                $(".multiplas").addClass("hide");
                $("#price_0").attr("readonly", "readonly");
            }
        } else {
            $("#icon_cheque").addClass("hide");
            $(".mtdopgto_condition").removeAttr("disabled");

        }
        if ($("#cdtpgto").val() == 1) {//á vista
            $(".div_especification_payment").addClass("hide");
        }
    }

    $("#icon_cheque").on("click", function (e) {
        e.preventDefault();
        $('#modal_check #check_kind_of_person').on('change', function () {
            if ($(this).val() == "PJ") {
                $('#modal_check #div_cpf').addClass("hide");
                $('#modal_check #div_cnpj').removeClass("hide");
            } else {
                $('#modal_check #div_cpf').removeClass("hide");
                $('#modal_check #div_cnpj').addClass("hide");
            }
        });

        $("#modal_add")[0].reset();
        if ($("#check_edited").val() == 1) {
            //ja teve os dados registrados, então ele não pega do cliente, e sim do registro
            $("#modal_check #check_kind_of_person").val($("#check_kind_of_person").val()).trigger("change");
            if ($("#check_kind_of_person").val() == "PF") {
                $("#modal_check #check_cpf").val($("#check_cpf_cnpj").val());
            } else {
                $("#modal_check #check_cnpj").val($("#check_cpf_cnpj").val());
            }
            $("#modal_check #check_name").val($("#check_name").val());
            $("#modal_check #check_code1").val($("#check_code1").val());
            $("#modal_check #check_code2").val($("#check_code2").val());
            $("#modal_check #check_code3").val($("#check_code3").val());
        } else if ($('#client').val() != "") {
            if ($('#client').find(":selected").attr('data-kind_of_person') == 'PJ') {
                $("#modal_check #check_kind_of_person").val('PJ').trigger("change");
                $("#modal_check #check_cnpj").val($('#client').find(":selected").attr('data-cpf_cnpj'));
            } else {
                $("#modal_check #check_kind_of_person").val('PF').trigger("change");
                $("#modal_check #check_cpf").val($('#client').find(":selected").attr('data-cpf_cnpj'));
            }
            $("#modal_check #check_name").val($('#client').find(":selected").attr('data-name'));
        } else {
            $("#modal_check #check_kind_of_person").val('PF').trigger("change");
        }
        $("#modal_check .check_code1").mask("999?99999");
        $("#modal_check .check_code2").mask("999?9999999");
        $("#modal_check .check_code3").mask("999?999999999");
        $("#modal_check .cpf").mask("999.999.999-99");
        $("#modal_check .cnpj").mask("99.999.999/9999-99");
        $('#modal_check').modal('show');

        $("#modal_check #registerCheck").on('click', function () {
            $("#check_name").val($("#modal_add #check_name").val());
            $("#check_kind_of_person").val($("#modal_add #check_kind_of_person").val());
            if ($("#modal_add #check_kind_of_person").val() == 'PF') {
                $("#check_cpf_cnpj").val($("#modal_add #check_cpf").val());
            } else {
                $("#check_cpf_cnpj").val($("#modal_add #check_cnpj").val());
            }
            $("#check_code1").val($("#modal_add #check_code1").val());
            $("#check_code2").val($("#modal_add #check_code2").val());
            $("#check_code3").val($("#modal_add #check_code3").val());
            $("#check_edited").val(1); //registra que informou os dados dessa informaçção de cheque, para update
            $('#modal_check').modal('hide');
        });

    });

    $('#cdtpgto').on("change", function (e) {
        if ($(this).val() == 2) {
            clearTableEspecificationPayment();
            //$("#duedate_0").val($("#sales_date").val());
            $("#days_0").val("30");
            $.post(_url + "orders/days_to_date", {date: $("#sales_date").val(), days: 30})
                    .done(function (data) {
                        $("#duedate_0").val(data);
                    });

            $("#price_0").val($("#total").val());
            //$("#price_0").attr('readonly','readonly');
            $("#div_especification_payment").removeClass("hide");
            $(".div_divided").addClass("hide");
            $("#price_0").attr("readonly", "readonly");
        } else if ($(this).val() == 1) {
            clearTableEspecificationPayment();
            $("#duedate_0").val($("#sales_date").val());
            $("#days_0").val("0");
            $("#price_0").val($("#total").val());
            $("#div_especification_payment").addClass("hide");
            $(".div_divided").addClass("hide");
        } else if ($(this).val() == 3) {
            $("#price_0").removeAttr("readonly", "readonly");
            $(".div_divided").removeClass("hide");
            if ($("#divided_condition").val() != "") {
                $("#div_especification_payment").removeClass("hide");
            } else {
                $("#div_especification_payment").addClass("hide");
            }
        } else {
            $("#div_especification_payment").addClass("hide");
            $(".div_divided").addClass("hide");
        }
        validaCheck();
    });

    function clearTableEspecificationPayment() {
        $('#especification_payment tr').each(function () {
            var tr = $(this).closest('tr');
            if (tr.attr("data-row") != 'fixed') {
                $(this).closest('tr').remove();
            }
        });
    }
    //itens das parcelas
    $('.divided').on("click", function (e) {
        e.preventDefault();
        $("#divided_condition").val($(this).attr("data-value")).trigger("blur");
    });
    //botao gerar parcelas
    $('#btn-gerar-divided').on("click", function (e) {
        e.preventDefault();
        $("#divided_condition").trigger("blur");
    });


    $('#divided_condition').on("blur", function (e) {
        e.preventDefault();
        verify_divided_conditions($('#divided_condition').val());
        $("#div_especification_payment").removeClass("hide");

    });


    function verify_divided_conditions(val) {

        $.post(_url + "orders/order_divids", {date: $("#sales_date").val(), price: $("#total").val(), divided_condition: $("#divided_condition").val(), mtdopgto: $("#mtdopgto").val()})
                .done(function (data) {
                    $("#div_especification_payment").html(data);
                    $('.amount').autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 2, aSign: curr_code + ' '});
                    $("#especification_payment").on("click blur change", ".days", function (e) {
                        var data_row = $(this).attr("data-row");
                        $.post(_url + "orders/days_to_date", {date: $("#sales_date").val(), days: $(this).val()})
                                .done(function (data) {
                                    $("#duedate_" + data_row).val(data);
                                });
                    });


                    $("#especification_payment").on("click blur change", ".due_date_especification_payment", function (e) {
                        var data_row = $(this).attr("data-row");
                        $.post(_url + "orders/date_to_days", {date: $("#sales_date").val(), date_divided: $(this).val()})
                                .done(function (data) {
                                    $("#days_" + data_row).val(data);
                                });
                    });

                    $(".datepicker").datepicker();


                    $("#especification_payment").on("change", ".mtdopgto_condition", function (e) {
                        if ($(this).val() > 0) {
                            findDataSelect("#destiny_payment_account_" + $(this).attr("data-row"), "settings/pmethods-list-accounts/" + $(this).val(), $("#_lan_select_account").val());
                            if ($(this).val() == 2) {//para cheque
                                $("#icon_cheque_" + $(this).attr("data-row")).removeClass("hide");
                            } else {
                                $("#icon_cheque_" + $(this).attr("data-row")).addClass("hide");
                            }
                        } else {
                            $('#destiny_payment_account' + $(this).attr("data-row")).val('').trigger("change");
                        }
                    });
                    //recalcula o valor das parcelas não fixadas
                    $("#especification_payment").on("blur", ".divided_price", function (e) {
                        if ($(this).attr("data-value") != parseFloat($(this).val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.'))) {
                            $(this).attr("data-value", parseFloat($(this).val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')));
                            $(this).attr("data-fixed", '1');

                            var total = (parseFloat($("#total").val().replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.')).toFixed(2));
                            var parcelas = document.getElementsByName('price[]');
                            var i = 0;
                            var cont_ParcelasDivided = 0;
                            var total_fixed = 0;
                            for (i = 0; i < parcelas.length; i++) {
                                if ($("#price_" + i).attr("data-fixed") == 1) {
                                    total_fixed = parseFloat(parseFloat(total_fixed) + parseFloat(($("#price_" + i).val() + "").replace(curr_code, "").replace(ind_mil, "").replace(ind_decimal, '.'))).toFixed(2);
                                } else {
                                    cont_ParcelasDivided++;
                                }
                            }

                            if (cont_ParcelasDivided > 0 && parseFloat(total_fixed) < parseFloat(total)) {
                                var new_divided = (parseFloat(total) - parseFloat(total_fixed)) / parseFloat(cont_ParcelasDivided);
                                for (i = 0; i < parcelas.length; i++) {
                                    if ($("#price_" + i).attr("data-fixed") == 0) {
                                        $("#price_" + i).val(curr_code + " " + formatMonetary(parseFloat(new_divided).toFixed(2)));
                                        $("#price_" + i).attr('data-value', parseFloat(new_divided).toFixed(2));
                                    }
                                }

                            } else {
                                //nesse caso não há nenhuma parcela disponível para atribuir o valor
                                updateTotais();
                            }
                        }
                    });


                    $("#especification_payment").on("click", ".edit_check_data", function (e) {
                        e.preventDefault();
                        $('#modal_check #check_kind_of_person').on('change', function () {
                            if ($(this).val() == "PJ") {
                                $('#modal_check #div_cpf').addClass("hide");
                                $('#modal_check #div_cnpj').removeClass("hide");
                            } else {
                                $('#modal_check #div_cpf').removeClass("hide");
                                $('#modal_check #div_cnpj').addClass("hide");
                            }
                        });

                        $("#modal_add")[0].reset();

                        $("#modal_check #update_row").val($(this).attr('data-row'));
                        if ($("#check_edited_" + $(this).attr('data-row')).val() == 1) {
                            //ja teve os dados registrados, entãio ele não pega do cliente, e sim do registro
                            $("#modal_check #check_kind_of_person").val($("#check_kind_of_person_" + $(this).attr('data-row')).val()).trigger("change");
                            if ($("#check_kind_of_person_" + $(this).attr('data-row')).val() == "PF") {
                                $("#modal_check #check_cpf").val($("#check_cpf_cnpj_" + $(this).attr('data-row')).val());
                            } else {
                                $("#modal_check #check_cnpj").val($("#check_cpf_cnpj_" + $(this).attr('data-row')).val());
                            }
                            $("#modal_check #check_name").val($("#check_name_" + $(this).attr('data-row')).val());
                            $("#modal_check #check_code1").val($("#check_code1_" + $(this).attr('data-row')).val());
                            $("#modal_check #check_code1").val($("#check_code2_" + $(this).attr('data-row')).val());
                            $("#modal_check #check_code1").val($("#check_code3_" + $(this).attr('data-row')).val());

                        } else
                        if ($('#client').val() != "") {
                            if ($('#client').find(":selected").attr('data-kind_of_person') == 'PJ') {
                                $("#modal_check #check_cnpj").val($('#client').find(":selected").attr('data-cpf_cnpj'));
                                $("#modal_check #check_kind_of_person").val('PJ').trigger("change");
                            } else {
                                $("#modal_check #check_cpf").val($('#client').find(":selected").attr('data-cpf_cnpj'));
                                $("#modal_check #check_kind_of_person").val('PF').trigger("change");
                            }
                            $("#modal_check #check_name").val($('#client').find(":selected").attr('data-name'));
                        } else {
                            $("#modal_check #check_kind_of_person").val('PF').trigger("change");
                        }
                        $("#modal_check .check_code1").mask("999?99999");
                        $("#modal_check .check_code2").mask("999?9999999");
                        $("#modal_check .check_code3").mask("999?999999999");
                        $("#modal_check .cpf").mask("999.999.999-99");
                        $("#modal_check .cnpj").mask("99.999.999/9999-99");
                        $('#modal_check').modal('show');

                        $("#modal_check #registerCheck").on('click', function () {

                            var rowCheck = $("#modal_add #update_row").val();
                            $("#check_name_" + rowCheck).val($("#modal_add #check_name").val());
                            $("#check_kind_of_person_" + rowCheck).val($("#modal_add #check_kind_of_person").val());
                            if ($("#modal_add #check_kind_of_person").val() == 'PF') {
                                $("#check_cpf_cnpj_" + rowCheck).val($("#modal_add #check_cpf").val());
                            } else {
                                $("#check_cpf_cnpj_" + rowCheck).val($("#modal_add #check_cnpj").val());
                            }
                            $("#check_code1_" + rowCheck).val($("#modal_add #check_code1").val());
                            $("#check_code2_" + rowCheck).val($("#modal_add #check_code2").val());
                            $("#check_code3_" + rowCheck).val($("#modal_add #check_code3").val());

                            $("#check_edited_" + rowCheck).val(1);

                            $('#modal_check').modal('hide');
                        });


                    });
                    validaCheck();
                });
    }

    $("#especification_payment").on("change", ".mtdopgto_condition", function (e) {
        if ($(this).val() > 0) {
            findDataSelect("#destiny_payment_account_" + $(this).attr("data-row"), "settings/pmethods-list-accounts/" + $(this).val(), $("#_lan_select_account").val());
            if ($(this).val() == 2) {//para cheque
                $("#icon_cheque_" + $(this).attr("data-row")).removeClass("hide");
            } else {
                $("#icon_cheque_" + $(this).attr("data-row")).addClass("hide");
            }
        } else {
            $('#destiny_payment_account' + $(this).attr("data-row")).val('').trigger("change");
        }
    });


    $("#especification_payment").on("click", ".edit_check_data", function (e) {
        e.preventDefault();
        $('#modal_check #check_kind_of_person').on('change', function () {
            if ($(this).val() == "PJ") {
                $('#modal_check #div_cpf').addClass("hide");
                $('#modal_check #div_cnpj').removeClass("hide");
            } else {
                $('#modal_check #div_cpf').removeClass("hide");
                $('#modal_check #div_cnpj').addClass("hide");
            }
        });


        $("#modal_check #update_row").val($(this).attr('data-row'));
        if ($("#check_edited_" + $(this).attr('data-row')).val() == 1) {
            //ja teve os dados registrados, entãio ele não pega do cliente, e sim do registro
            $("#modal_check #check_kind_of_person").val($("#check_kind_of_person_" + $(this).attr('data-row')).val()).trigger("change");
            if ($("#check_kind_of_person_" + $(this).attr('data-row')).val() == "PF") {
                $("#modal_check #check_cpf").val($("#check_cpf_cnpj_" + $(this).attr('data-row')).val());
            } else {
                $("#modal_check #check_cnpj").val($("#check_cpf_cnpj_" + $(this).attr('data-row')).val());
            }
            $("#modal_check #check_name").val($("#check_name_" + $(this).attr('data-row')).val());
            $("#modal_check #check_code1").val($("#check_code1_" + $(this).attr('data-row')).val());
            $("#modal_check #check_code2").val($("#check_code2_" + $(this).attr('data-row')).val());
            $("#modal_check #check_code3").val($("#check_code3_" + $(this).attr('data-row')).val());

        } else
        if ($('#client').val() != "") {
            if ($('#client').find(":selected").attr('data-kind_of_person') == 'PJ') {
                $("#modal_check #check_cnpj").val($('#client').find(":selected").attr('data-cpf_cnpj'));
                $("#modal_check #check_kind_of_person").val('PJ').trigger("change");
            } else {
                $("#modal_check #check_cpf").val($('#client').find(":selected").attr('data-cpf_cnpj'));
                $("#modal_check #check_kind_of_person").val('PF').trigger("change");
            }
            $("#modal_check #check_name").val($('#client').find(":selected").attr('data-name'));
        } else {
            $("#modal_check #check_kind_of_person").val('PF').trigger("change");
        }
        $("#modal_check .check_code1").mask("999?99999");
        $("#modal_check .check_code2").mask("999?9999999");
        $("#modal_check .check_code3").mask("999?999999999");
        $("#modal_check .cpf").mask("999.999.999-99");
        $("#modal_check .cnpj").mask("99.999.999/9999-99");
        $('#modal_check').modal('show');

        $("#modal_check #registerCheck").on('click', function () {

            var rowCheck = $("#modal_add #update_row").val();
            $("#check_name_" + rowCheck).val($("#modal_add #check_name").val());
            $("#check_kind_of_person_" + rowCheck).val($("#modal_add #check_kind_of_person").val());
            if ($("#modal_add #check_kind_of_person").val() == 'PF') {
                $("#check_cpf_cnpj_" + rowCheck).val($("#modal_add #check_cpf").val());
            } else {
                $("#check_cpf_cnpj_" + rowCheck).val($("#modal_add #check_cnpj").val());
            }
            $("#check_code1_" + rowCheck).val($("#modal_add #check_code1").val());
            $("#check_code2_" + rowCheck).val($("#modal_add #check_code2").val());
            $("#check_code3_" + rowCheck).val($("#modal_add #check_code3").val());

            $("#check_edited_" + rowCheck).val(1);

            $('#modal_check').modal('hide');
        });


    });


    if ($("#cdtpgto").val() == 3) {
        $("#price_0").removeAttr("readonly");
        var parcelas = document.getElementsByName('price[]');
        for (i = 0; i < parcelas.length; i++) {
            findDataSelect("#destiny_payment_account_" + i, "settings/pmethods-list-accounts/" + $("#mtdopgto_" + i).val(), $("#_lan_select_account").val());
        }
    } else {
        findDataSelect("#destiny_payment_account", "settings/pmethods-list-accounts/" + $("#mtdopgto").val(), $("#_lan_select_account").val());
    }


    //////PAYMENT




});
// FIM DO DOCUMENT.READY


function loadNatureOperation(select) {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'nature_operation/ajax-list', function (j) {
        //options = '<option value="">' + _L['Select Nature Of Operation'] + '</option>';
        options = '';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '" >' + j[i].name + '</option>';
        }
        $('#nature_operation').html(options);

        if (select !== '') {
            $("#nature_operation").select2('val', select);
        }

    });
}

function loadContacts() {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'contacts/ajax-list', function (j) {
        options = '<option value="">' + _L['Select Client'];
        +'</option>';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '" \n\
            data-segment="' + j[i].segment_id + '"\n\
            data-kind_of_person="' + j[i].kind_of_person + '"\n\
            data-name="' + j[i].name + '"\n\
            data-cpf_cnpj="' + j[i].cpf_cnpj
                    + '" >' + j[i].name_email + '</option>';
        }
        $('#client').html(options);
        $('#client').select2('val', $("#selectedContact").val());

    });
}



function loadSalesman() {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'contacts/ajax-listbygroup/Salesman', function (j) {
        options = '<option value="">' + _L['Select Salesman'];
        +'</option>';

        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '">' + j[i].account + '</option>';
        }
        $('#salesman').html(options);
        $('#salesman').select2('val', $("#selectedSalesman").val());

    });
}

function loadTags() {
    var tag2 = $("#tag_selecionada").val();
    var tag = tag2.split(',');

    //carrega os dados das tags ao iniciar
    $.getJSON($("#_url").val() + 'tags/orders', function (j) {
        var options = '';
        for (var i = 0; i < j.length; i++) {
            var selected = '';
            for (var k = 0; k < tag.length; k++) {

                if (j[i].text == tag[k]) {
                    selected = 'selected';
                }
            }
            options += '<option ' + selected + ' value="' + j[i].text + '">' + j[i].text + '</option>';
        }
        $('#tags').select2('destroy');
        $('#tags').html(options);
        $('#tags').select2();

    });
}

function loadConveyor() {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'contacts/ajax-listbygroup/Conveyor', function (j) {
        options = '<option value="">' + _L['Select Conveyor'];
        +'</option>';

        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '">' + j[i].account + '</option>';
        }
        $('#conveyor_id').html(options);
        $('#conveyor_id').select2('val', $("#selectedConveyor").val());

    });
}

Anon7 - 2022
AnonSec Team