<style>
    .p-0{
        padding:0 !important;
    }
    .nav-tabs-fillup>li>a:after {
        background: none repeat scroll 0 0 #4c0870 !important;
        border: 1px solid #4c0870 !important;
    }
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php print CommonLanguage::getMessage('machine_expenses'); ?></div>
        </div>
        <div class="panel-body">
            <?php
            if ($permissions->hasPermission('add_machine_expenses')) {
                echo Forms::FloatingAddButton('4c0870', '#add_machine_expenses', CommonLanguage::getMessage('add'));
            }
            ?>
            <table class="table table-bordered maintenance-table" id="tableWithSearch" >
                <thead>
                    <tr>
                        <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('expense_nb'); ?></th>
                        <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('line'); ?></th>
                        <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('machine'); ?></th>
                        <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('note'); ?></th>
                        <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('Date'); ?></th>
                        <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('Action'); ?></th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
                <tfoot>
                <th>
                    <?php if ($permissions->hasPermission('delete_multi_machine_expenses')) { ?>
                        <button class="btn bg-success-dark m-b-10 full-width white" id="delete_all"><?php echo CommonLanguage::getMessage('Delete'); ?></button>
                    <?php } ?>
                </th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<div class="modal fade bs-example-modal-md " data-backdrop="static" id="add_machine_expenses" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog " style='width:75%;' >
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label bold"><?php echo CommonLanguage::getMessage('machine_expenses'); ?></h5>
                <div id="assignAlert"></div>
            </div>
            <div class="modal-body">
                <form id="assignForm" class="form-group">
                    <div class="row m-b-10">
                        <div class=" col-md-12 m-t-10 " >
                            <div class="col-md-3">
                                <label class="labelText"><?php print CommonLanguage::getMessage('line'); ?><span class="red-star">*</span></label>
                                <input type="hidden" class="full-width" id="line_id" name="line_id" required/>
                            </div>
                            <div class="col-md-3">
                                <label class="labelText"><?php print CommonLanguage::getMessage('Name'); ?><span class="red-star">*</span></label>
                                <input type="hidden" class="full-width" id="product_id" name="product_id" required/>
                            </div>
                            <div class="col-md-3">
                                <label class="labelText"><?php print CommonLanguage::getMessage('Depot'); ?><span class="red-star">*</span></label>
                                <input type="hidden" class="full-width" id="Depot_ID" name="Depot_ID" required/>
                            </div>
                            <div class=' date col-md-3 '>
                                <label><?php echo CommonLanguage::getMessage('Date'); ?><span class="red-star">*</span></label>
                                <input type='text' class="form-control" name="datetimepicker1" id="datetimepicker1" autocomplete="off" required />
                            </div>
                        </div>
                        <div class="col-md-12 m-t-10 p-0" > 
                            <label class="labelText"><?php print CommonLanguage::getMessage('note'); ?></label>
                            <textarea class="form-control note"   rows="3" style="overflow: hidden; word-wrap: break-word; resize:vertical "></textarea>
                        </div>
                    </div>
                    <div class="panel panel-transparent ">
                        <ul class="nav nav-tabs nav-tabs-fillup">
                            <li class="active">
                                <a data-toggle="tab" href="#slide1"><span><?php print CommonLanguage::getMessage('parts'); ?></span></a>
                            </li>
                            <li >
                                <a data-toggle="tab" href="#slide2"><span><?php print CommonLanguage::getMessage('expenses'); ?></span></a>
                            </li>
                        </ul>
                        <div class="tab-content">
                            <div class="tab-pane slide-left active" id="slide1">
                                <div class="row prod-div ">
                                    <div class=" col-md-12 m-t-10 " >
                                        <div class="col-md-4"><label><?php print CommonLanguage::getMessage('product'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('UOM'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('qty'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('cost') . ' <span class="red-star">( ' . smc_session()['local_currency_symbol'] . ' )</span>'; ?></label></div>
                                    </div>
                                    <div class=" col-md-12 m-t-10 p-0 part-row" >
                                        <div class="col-md-3">
                                            <input type="hidden" class="full-width part_product_id" name="part_product_id" required/>
                                        </div>
                                        <div class="col-md-2 ">
                                            <input class="full-width uom_id" name="uom_id" type="hidden" />
                                        </div>
                                        <div class="col-md-3 ">
                                            <input class="form-control qty" name="qty" type="number" step='any' min='0' />
                                        </div>
                                        <div class="col-md-3 ">
                                            <input class="form-control cost" name="cost" type="number" step='any' min='0' />
                                        </div>
                                        <div class="col-md-1 AddButtons">
                                            <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                            <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane slide-left " id="slide2">
                                <div class="row exp-div ">
                                    <div class=" col-md-12 m-t-10 " >
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('supplier'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('account'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('amount'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-3"><label><?php print CommonLanguage::getMessage('currency'); ?><span class="red-star">*</span></label></div>
                                        <div class="col-md-2"><label><?php print CommonLanguage::getMessage('job'); ?></label></div>
                                    </div>
                                    <div class=" col-md-12 m-t-10 p-0 exp-row" >
                                        <div class="col-md-2">
                                            <input type="hidden" class="full-width supplier_id" name="supplier_id" required/>
                                        </div>
                                        <div class="col-md-2 ">
                                            <input class="full-width account_id" name="account_id" type="hidden" />
                                        </div>
                                        <div class="col-md-2 ">
                                            <input class="form-control amount" name="amount" type="number" step='any' min='0' />
                                        </div>
                                        <div class="col-md-3 ">
                                            <input class="full-width currency_id" name="currency_id" type="hidden"  />
                                        </div>
                                        <div class="col-md-2 ">
                                            <input class="full-width job_id" name="job_id" type="hidden"  />
                                        </div>
                                        <div class="col-md-1 AddButtons">
                                            <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                            <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button style="color:white !important;" type="button" class="btn bg-success-dark text-white" id="assignBtn"><?php print CommonLanguage::getMessage('Save') ?></button>
            </div>
        </div>
    </div>
</div>
<div class=" col-md-12 m-t-10 p-0 exp-row-temp hidden" >
    <div class="col-md-2">
        <input type="hidden" class="full-width supplier_id" name="supplier_id" required/>
    </div>
    <div class="col-md-2 ">
        <input class="full-width account_id" name="account_id" type="hidden" />
    </div>
    <div class="col-md-2 ">
        <input class="form-control amount" name="amount" type="number" step='any' min='0' />
    </div>
    <div class="col-md-3 ">
        <input class="full-width currency_id" name="currency_id" type="hidden"  />
    </div>
    <div class="col-md-2 ">
        <input class="full-width job_id" name="job_id" type="hidden"  />
    </div>
    <div class="col-md-1 AddButtons">
        <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
        <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
    </div>
</div>
<div class=" col-md-12 m-t-10 p-0 part-row-temp hidden" >
    <div class="col-md-3">
        <input type="hidden" class="full-width part_product_id" name="part_product_id" required/>
    </div>
    <div class="col-md-2 ">
        <input class="full-width uom_id" name="uom_id" type="hidden" />
    </div>
    <div class="col-md-3 ">
        <input class="form-control qty" name="qty" type="number" step='any' min='0' />
    </div>
    <div class="col-md-3 ">
        <input class="form-control cost" name="cost" type="number" step='any' min='0' />
    </div>
    <div class="col-md-1 AddButtons">
        <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
        <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
    </div>
</div>
<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('product_sections')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            machine_exp_alert = <?php echo json_encode(CommonLanguage::getMessage('machine_exp_alert')); ?>,
            is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>;
    var IsEdit = false, IDToEdit = 0, delete_arr = [];
    $(function () {
        build_select2($("input[name=line_id]"), "xhr/CommonSearch?col_name=line_name&col_id=line_id&table=tbl_line");
        build_select2($("input[name=job_id]"), "xhr/CommonSearch?col_name=job_name&col_id=job_id&table=tbl_accounting_jobs");
        build_select2($("#product_id"), "xhr/MachineLineSearch?Status_ID=1&line_id=" + $('#line_id').val());
        build_select2($("input.supplier_id"), "xhr/supplierSearch")
        build_select2($("input.account_id"), "xhr/accIDSearch?type=payment")
        build_select2($("input.currency_id"), "xhr/CurrencySearch")
        build_select2($("input.part_product_id"), ("xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0"));
        build_select2($("input.uom_id"), "xhr/productuomSearch?pid=" + $("input.part_product_id").val())
        build_select2($("#Depot_ID"), "xhr/depotSearch")

        $("#product_id").on("change", function () {
            $("input.part_product_id").val('').trigger('change');
            build_select2($("input.part_product_id"), "xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0");
        });
        $("input[name=line_id]").on('change', function () {
            $("#product_id,input.part_product_id").val('').trigger('change');
            build_select2($("#product_id"), "xhr/MachineLineSearch?Status_ID=1&line_id=" + $(this).val());
            build_select2($("input.part_product_id"), "xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0");
        });
        $(".prod-div").on("change", "input.part_product_id", function (e) {
            if ($(this).val()) {
                var parent = $(this).parents(".part-row"),
                        uom = $(this).parents(".part-row").find("input.uom_id"),
                        product_id = $(this).select2('data').part_product_id;
                uom.val('').attr("data-select-name", "");
                build_select2(uom, "xhr/productuomSearch?pid=" + product_id)
                $.ajax({
                    url: "InventoryAjax/getCurrentProductCost",
                    method: "GET",
                    dataType: 'json',
                    data: {product_id: product_id},
                    complete: function (v1, v2) {
                        if (v2 == "success") {
                            $('input.cost', parent).val(v1.responseJSON)
                        }
                    }
                });
            }
        })
        $(".prod-div").on("click", ".AddButtons > .fa-plus-circle", function (e) {
            $(".AddButtons > .fa-minus-circle").css("display", "")
            var NewItem = $(".part-row-temp").clone().appendTo($(".prod-div"));
            NewItem.removeClass("part-row-temp hidden").addClass("part-row")
            NewItem.find("input").val('');
            $(".select2-container", NewItem).empty().remove()
            NewItem.find("input.part_product_id").val('').removeAttr("data-select-name");
            build_select2(NewItem.find("input.part_product_id"), ("xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0"))
            build_select2(NewItem.find("input.uom_id"), "xhr/productuomSearch?pid=" + NewItem.find("input.part_product_id").val())
            $(".select2-container", NewItem).show()
        })
        $(".prod-div").on("click", ".AddButtons > .fa-minus-circle", function (e) {
            if ($(".part-row").length == 1) {
                $(".part-row input").val("")
                $("input.part_product_id").val('').removeAttr("data-select-name", "");
                build_select2($("input.part_product_id"), ("xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0"))
                build_select2($("input.uom_id"), "xhr/productuomSearch?pid=" + $("input.part_product_id").val())
            } else {
                $(this).closest(".part-row").empty().remove();
            }
        })
        $(".exp-div").on("click", ".AddButtons > .fa-plus-circle", function (e) {
            $(".AddButtons > .fa-minus-circle").css("display", "")
            var NewItem = $(".exp-row-temp").clone().appendTo($(".exp-div"));
            NewItem.removeClass("exp-row-temp hidden").addClass("exp-row")
            NewItem.find("input").val('');
            $(".select2-container", NewItem).empty().remove()
            NewItem.find("input.supplier_id,input.account_id,input.currency_id,input.job_id").val('').removeAttr("data-select-name");
            build_select2(NewItem.find("input.supplier_id"), "xhr/supplierSearch")
            build_select2(NewItem.find("input.account_id"), "xhr/accIDSearch?type=payment")
            build_select2(NewItem.find("input.currency_id"), "xhr/CurrencySearch")
            build_select2($("input[name=job_id]", NewItem), "xhr/CommonSearch?col_name=job_name&col_id=job_id&table=tbl_accounting_jobs");

            $(".select2-container", NewItem).show()
        })
        $(".exp-div").on("click", ".AddButtons > .fa-minus-circle", function (e) {
            if ($(".exp-row").length == 1) {
                $(".exp-row input").val("")
                $("input.supplier_id,input.account_id,input.currency_id,input.job_id").val('').removeAttr("data-select-name");
                build_select2($("input.supplier_id"), "xhr/supplierSearch")
                build_select2($("input.account_id"), "xhr/accIDSearch?type=payment")
                build_select2($("input.currency_id"), "xhr/CurrencySearch")
                build_select2($("input[name=job_id]"), "xhr/CommonSearch?col_name=job_name&col_id=job_id&table=tbl_accounting_jobs");

            } else {
                $(this).closest(".exp-row").empty().remove();
            }
        })
        $("#datetimepicker1").datetimepicker({format: 'YYYY-MM-DD HH:mm:ss'});
        $(".floatingContainer").on("click", function () {
            IsEdit = false;
            IDToEdit = 0;
        })
        RebuildDataTable(title, [0, 1, 2, 3, 4], "MaintenanceAjax/machine_expenses_ajax")
        $("#assignBtn").on("click", function () {
            $("#assignBtn").attr("disabled", "disabled")
            $("#assignAlert").removeClass('hidden')
            if ($("#datetimepicker1").val() == '' || $("#product_id").val() == '' || $("#Depot_ID").val() == '') {
                $("#assignAlert").attr("class", "alert alert-danger").html(Required_Fields)
                $("#assignBtn").removeAttr("disabled")

                return false;
            }
            var DataArr = {
                line_id: $("#line_id").val(),
                product_id: $("#product_id").val(),
                value_date_time: $("#datetimepicker1").val(),
                note: $(".note").val(),
                Depot_ID: $("#Depot_ID").val(),
                is_actual: is_actual,
                parts: [],
                expenses: []
            };
            var is_part_empty = false;
            $(".part-row").each(function () {
                var parent = $(this), not_empty_count = 0;//required-fields
                $('input:not(.select2-focusser)', parent).each(function () {
                    if ($(this).val() != '')
                        not_empty_count++;
                });

                if (not_empty_count != 0 && not_empty_count < 4)
                    is_part_empty = true;
                if ($(this).find('input.part_product_id').val() != ''
                        && $(this).find('input.uom_id').val() != '' && $(this).find('.qty').val() != '' && $(this).find('.qty').val() != 0
                        && $(this).find('.cost').val() != '') {
                    console.log($(this).find('input.part_product_id').select2('data'));
                    DataArr.parts.push({
                        part_product_id: $(this).find('input.part_product_id').val(), //part_id
                        product_id: $(this).find('input.part_product_id').select2('data').part_product_id, //product_id
                        is_service: $(this).find('input.part_product_id').select2('data').is_service,
                        uom_id: $(this).find('input.uom_id').val(),
                        qty: $(this).find('.qty').val(),
                        cost: $(this).find('.cost').val()
                    })
                }
            })

            var is_exp_empty = false;
            $(".exp-row").each(function () {
                var parent = $(this), not_empty_count = 0;//required-fields
                $('input:not(.select2-focusser,.job_id)', parent).each(function () {
                    if ($(this).val())
                        not_empty_count++;
                });
                if (not_empty_count != 0 && not_empty_count < 4)
                    is_exp_empty = true;
                if ($(this).find('input.supplier_id').val() != ''
                        && $(this).find('input.account_id').val() != '' && $(this).find('.amount').val() != '' && $(this).find('.amount').val() != 0
                        && $(this).find('input.currency_id').val() != '') {
                    DataArr.expenses.push({
                        supplier_id: $(this).find('input.supplier_id').val(),
                        account_id: $(this).find('input.account_id').val(),
                        amount: $(this).find('.amount').val(),
                        job_id: $(this).find('input.job_id').val(),
                        currency_id: $(this).find('input.currency_id').val()
                    })
                }
            })

            if ((DataArr.expenses.length == 0 && DataArr.parts.length == 0)
                    || is_exp_empty
                    || is_part_empty) {
                $("#assignAlert").attr("class", "alert alert-danger").html(machine_exp_alert)
                $("#assignBtn").removeAttr("disabled")
                return false;
            }
            DataArr.expense_id = IDToEdit;
            DataArr.is_edit = (IsEdit ? 1 : 0);
            $.ajax({
                url: "MaintenanceAjax/add_edit_machine_expenses",
                method: "POST",
                data: DataArr,
                complete: function (v1, v2) {
                    if (v2 == "success" && v1.responseText == 'OK') {
                        $("#assignAlert").attr("class", "alert alert-success").html(Submitted_Successfully)
                        RebuildDataTable(title, [0, 1, 2, 3, 4], "MaintenanceAjax/machine_expenses_ajax")
                        setTimeout(function () {
                            $("#assignAlert").addClass('hidden')
                            $("#add_machine_expenses").modal("hide")
                        }, 5000)
                    } else {
                        $("#assignAlert").attr("class", "alert alert-danger").html(Failed_Submit)
                        $("#assignBtn").removeAttr("disabled")
                    }
                }
            })
        })
        $("#tableWithSearch tbody").on('click', '.edit_exp', function () {
            IsEdit = true;
            IDToEdit = $(this).attr('data-id');
            //get_property_value_by_id
            $.ajax({
                url: "MaintenanceAjax/get_product_expense_by_id",
                method: "GET",
                dataType: 'json',
                data: {id: IDToEdit},
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var data = v1.responseJSON;
//                        console.log(data)
                        $("#line_id").val(data['main']['line_id']).attr("data-select-name", data['main']['line_name']);
                        build_select2($("input[name=line_id]"), "xhr/CommonSearch?col_name=line_name&col_id=line_id&table=tbl_line");
                        $("#product_id").val(data['main']['Product_ID']).attr("data-select-name", data['main']['product_full_name'])
                        build_select2($("#product_id"), ("xhr/MachineLineSearch?Status_ID=1&is_edited=" + data['main']['Product_ID'] + "&line_id=" + data['main']['line_id']));
                        $("#Depot_ID").val(data['main']['Depot_ID']).attr("data-select-name", data['main']['Depot_Name'])
                        build_select2($("#Depot_ID"), "xhr/depotSearch")
                        $("#datetimepicker1").val(data['main']['expense_date_time'])
                        $(".note").val(data['main']['note'])
                        $('.part-row').remove()
                        $('.exp-row').remove()
                        if (data['details'].length > 0) {
                            for (var i = 0; i < data['details'].length; i++) {
                                var parts = data['details'][i];
                                var temp = $(".part-row-temp").clone();
                                temp.appendTo($(".prod-div"));
                                temp.removeClass('part-row-temp hidden').addClass('part-row')
                                $(".select2-container", temp).empty().remove()
                                $("input.part_product_id", temp).val(parts['part_product_id']).attr("data-select-name", parts['product_part_note'])
                                        .attr("data-other-data", JSON.stringify({is_service: parts['is_service'], part_product_id: parts['Product_ID']}))
                                $("input.uom_id", temp).val(parts['UOM_ID']).attr("data-select-name", parts['UOM_Name'])
                                $("input.qty", temp).val(parts['current_quantity'])
                                $("input.cost", temp).val(parts['cost'])
                                build_select2(temp.find("input.part_product_id"), ("xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0"))
                                build_select2(temp.find("input.uom_id"), "xhr/productuomSearch?pid=" + temp.find("input.part_product_id").val())
                                $(".select2-container", temp).show()
                            }
                        } else {
                            var temp = $(".part-row-temp").clone();
                            temp.appendTo($(".prod-div"));
                            temp.removeClass('part-row-temp hidden').addClass('part-row')
                            $(".select2-container", temp).empty().remove()
                            $("input.part_product_id,input.uom_id", temp).val('').attr("data-select-name", '')
                            $("input.qty,input.cost", temp).val('')
                            build_select2(temp.find("input.part_product_id"), ("xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0"))
                            build_select2(temp.find("input.uom_id"), "xhr/productuomSearch?pid=" + temp.find("input.part_product_id").val())
                            $(".select2-container", temp).show()
                        }
                        if (data['expenses'].length > 0) {
                            for (var i = 0; i < data['expenses'].length; i++) {
                                var parts = data['expenses'][i];
                                var temp = $(".exp-row-temp").clone();
                                temp.appendTo($(".exp-div"));
                                temp.removeClass('exp-row-temp hidden').addClass('exp-row')
                                $(".select2-container", temp).empty().remove()
                                $("input.supplier_id", temp).val(parts['Supplier_ID']).attr("data-select-name", parts['Supplier_Name'])
                                $("input.job_id", temp).val(parts['job_id']).attr("data-select-name", parts['job_name'])
                                $("input.account_id", temp).val(parts['Account_ID']).attr("data-select-name", parts['Account_Name'] + ' - ' + parts['Account_Code'])
                                $("input.currency_id", temp).val(parts['Currency_ID']).attr("data-select-name", parts['Currency_Name'])
                                $("input.amount", temp).val(parts['amount'])
                                build_select2(temp.find("input.supplier_id"), "xhr/supplierSearch")
                                build_select2($("input[name=job_id]", temp), "xhr/CommonSearch?col_name=job_name&col_id=job_id&table=tbl_accounting_jobs");

                                build_select2(temp.find("input.account_id"), "xhr/accIDSearch?type=payment")
                                build_select2(temp.find("input.currency_id"), "xhr/CurrencySearch")
                                $(".select2-container", temp).show()
                            }
                        } else {
                            var temp = $(".exp-row-temp").clone();
                            temp.appendTo($(".exp-div"));
                            temp.removeClass('exp-row-temp hidden').addClass('exp-row')
                            $(".select2-container", temp).empty().remove()
                            $("input.supplier_id,input.account_id,input.currency_id,input.job_id", temp).val('').attr("data-select-name", '')
                            $("input.amount", temp).val('')
                            build_select2(temp.find("input.supplier_id"), "xhr/supplierSearch")
                            build_select2($("input[name=job_id]", temp), "xhr/CommonSearch?col_name=job_name&col_id=job_id&table=tbl_accounting_jobs");

                            build_select2(temp.find("input.account_id"), "xhr/accIDSearch?type=payment")
                            build_select2(temp.find("input.currency_id"), "xhr/CurrencySearch")
                            $(".select2-container", temp).show()
                        }
                        $("#add_machine_expenses").modal("show")
                        //                        $('.value-row').remove()
                        //                        $(".value-div").removeClass("hidden")
                        //                        if (data['details'].length > 0) {
                        //                            for (var i = 0; i < data['details'].length; i++) {
                        //                                var prop = data['details'][i];
                        //                                var temp = $(".value-row-temp").clone();
                        //                                temp.appendTo($(".value-div"));
                        //                                temp.removeClass('value-row-temp hidden').addClass('value-row')
                        //                                $(".property_id", temp).attr("data-id", prop['property_id']).val(prop['property_name'])
                        //                                $(".property_value", temp).val(prop['property_value'])
                        //                                $("#add_machine_expenses").modal("show")
                        //                            }
                        //                        }
                    }
                }
            })
        })
        $("#tableWithSearch").on("click", ".delete_exp", function () {
            delete_arr = [];
            delete_arr.push($(this).attr('data-id'))
            IncludeDeleteModal(common_delete_modal, {ids: delete_arr}, function () {
                RebuildDataTable(title, [0, 1, 2, 3, 4], "MaintenanceAjax/machine_expenses_ajax")
            }, "MaintenanceAjax/delete_product_expense");
        })
        $("#delete_all").on("click", function () {
            delete_arr = [];
            $("#tableWithSearch .exp_del_td:checked").each(function () {
                delete_arr.push($(this).attr("data-id"));
            })
            if ($("#tableWithSearch .exp_del_td:checked").length > 0) {
                IncludeDeleteModal(common_delete_modal, {ids: delete_arr}, function () {
                    RebuildDataTable(title, [0, 1, 2, 3, 4], "MaintenanceAjax/machine_expenses_ajax")
                }, "MaintenanceAjax/delete_product_expense")
            }
        })
    })
    $("#add_machine_expenses").on("hidden.bs.modal", function () {
        $(".exp-row:gt(0),.part-row:gt(0)").remove()
        $(".exp-row input").val("")
        $("input.supplier_id,input.account_id,input.currency_id,input.job_id").val('').removeAttr("data-select-name");
        build_select2($("#product_id"), ("xhr/MachinePartSearch?type=1&Status_ID=1"));
        build_select2($("input.supplier_id"), "xhr/supplierSearch")
        build_select2($("input[name=job_id]"), "xhr/CommonSearch?col_name=job_name&col_id=job_id&table=tbl_accounting_jobs");

        build_select2($("input.account_id"), "xhr/accIDSearch?type=payment")
        build_select2($("input.currency_id"), "xhr/CurrencySearch")
        $(".part-row input").val("")
        $("input.part_product_id").val('').removeAttr("data-select-name", "");
        build_select2($("input.part_product_id"), ("xhr/PartSearch?Product_ID=" + $("#product_id").val() + "&is_product=0"))
        build_select2($("input.uom_id"), "xhr/productuomSearch?pid=" + $("input.part_product_id").val())
    })
    $(".prod-div").on("change", "input.uom_id", function () {
        //get_current_cost
        var tr = $(this).parents(".part-row"),
                pid = tr.find("input.part_product_id").select2('data').part_product_id,
                uom = tr.find("input.uom_id").val();
        $.ajax({
            url: "MaintenanceAjax/get_current_cost",
            method: "GET",
            dataType: 'json',
            data: {pid: pid, uom: uom},
            complete: function (v1, v2) {
                if (v2 == "success") {
                    tr.find("input.cost").val(v1.responseJSON)
                }
            }
        })
    })
</script>
