<style>
    .nav-tabs-fillup>li>a:after {
        background: none repeat scroll 0 0 #ed9421 !important;
        border: 1px solid #ed9421 !important;
    }
    .AddRow{
        background: #e5e5e5;
        padding: 5px !important;
        border-radius: 6px;
        margin-bottom: 10px;
    }
    .AddButtons span{
        cursor:pointer;
    }
    .wrong{
        border: 1px solid rgba(255, 0, 0, 0.2) !important;
        background: rgba(255, 0, 0, 0.05) !important;
        /*        width:100%;*/
    }
    .expiry_width{
        width:300px!important;
    }
</style>
<div class="modal fade" data-backdrop="static" id="add_production_process" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog ">
        <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 h-labels bold hidden"><?php echo CommonLanguage::getMessage('add_production_process'); ?></h5>
                <h5 class="edit-label h-labels bold hidden"><?php echo CommonLanguage::getMessage('edit_production_process'); ?></h5>
                <div id="TemplateValidationAlert"></div>
            </div>
            <div class="modal-body">
                <form id="production_process_form" method="POST" onsubmit="return false">
                    <div class="panel panel-transparent ">
                        <div class="tab-content">
                            <div class="row">
                                <div class="col-md-12 " style="margin:5px;">
                                    <div class="col-md-3">
                                        <label><?php print CommonLanguage::getMessage('template_name'); ?></label><span class="red-star">*</span>
                                        <input type="hidden"  id="template_id" name="template_id"   class="full-width" required>
                                    </div>
                                    <div class="col-md-3">
                                        <label><?php print CommonLanguage::getMessage('Currency'); ?></label><span class="red-star">*</span>
                                        <div id="CurrencyIDContainer"  >
                                            <div class="form-group form-material floating ">
                                                <div class="input-group-btn DropDownForForms" id="CurrencyDropDown" data-symbol="<?php echo smc_session()['local_currency_symbol']; ?>">
                                                    <button style="color:white !important;" type="button" class="btn bg-success-dark btn-block dropdown-toggle text-white" data-toggle="dropdown" aria-expanded="false">
                                                        <span><strong><?php echo smc_session()['local_currency_symbol'] ?></strong></span>
                                                        <input type="hidden"  value="<?php echo smc_session()['local_currency'] ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID" required/>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div><label><?php print CommonLanguage::getMessage('Date'); ?></label></div>
                                        <input type="text" id="process_date" name="process_date" value="<?php echo $today; ?>" class="form-control full-width" required/>
                                    </div>
                                    <div class="col-md-3">
                                        <div><label><?php print CommonLanguage::getMessage('line'); ?>
                                                <span class="red-star hidden line_red_star">*</span></label></div>
                                        <input type="hidden" id="line_id" name="line_id" value="" class="full-width"/>
                                    </div>
                                </div>
                                <div class="col-md-12 form-group">
                                    <div class="col-md-3">
                                            <label><?php print CommonLanguage::getMessage('qty'); ?></label>
                                            <input type="number" min="0" step="any" id="process_qty" name="process_qty" value="1" class="form-control full-width"/>
                                        </div>
                                    <div class="col-md-3 m  <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                        <br>
                                        <label><?php echo CommonLanguage::getMessage('total_costs') ?>:</label>
                                        <span id="total_cost">0</span>
                                    </div>
                                    <div class="col-md-3">
                                        <label><?php print CommonLanguage::getMessage('status'); ?></label> 
                                        <input type="hidden" id="states_name" name="states_name" value="" class="full-width"/>
                                    </div>
                                    <div class="col-md-3">
                                        <label><?php print CommonLanguage::getMessage('production_color'); ?></label> <label id="production_color_edit"></label>
                                        <input type="hidden" id="production_color" name="production_color" style="width: 100%;" value="" class="full-width"/>
                                     </div>
                                </div>
                                
                                <div class="col-md-12 form-group">
                                    
                                
                                    <div class="col-md-6">
                                        <label><?php echo CommonLanguage::getMessage('note') ?></label>
                                        <textarea class="form-control " id="process_note" rows="3"  style=" word-wrap: break-word; resize:vertical "></textarea>
                                    </div>
                                </div>
                                <div id="all_items" class="hidden hide-close">
                                    <div class="col-md-12">
                                        <div class='col-md-3'>
                                            <h3><?php echo CommonLanguage::getMessage('production_of') ?></h3>
                                        </div>
                                        <div class='col-md-3'>
                                            <label><?php echo CommonLanguage::getMessage('optional') ?></label>
                                            <input id="optional_prod_items" type="hidden" class="full-width"/>
                                        </div>
                                        <div class='col-md-3 m-t-25 '>
                                            <button style="color:white !important;" id="add_prod_row" class="btn bg-success-dark white"  type="button"><?php echo CommonLanguage::getMessage('add') ?></button>
                                        </div>

                                    </div>
                                    <div class="col-md-12">
                                        <div class="col-md-3 ">
                                            <label><?php echo CommonLanguage::getMessage('Item') ?></label>
                                        </div>
                                        <div class="col-md-9">
                                            <div class="col-md-1">
                                                <label><?php echo CommonLanguage::getMessage('Total_Quantity') ?></label>
                                            </div>
                                            <div  class="col-md-1 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                                <label><?php echo CommonLanguage::getMessage('unit_cost') ?></label>
                                            </div>
                                            <div class="col-md-2 <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 1 ? '' : 'hidden' ?>">
                                                <label><?php echo CommonLanguage::getMessage('lot') ?></label>
                                            </div>
                                            <div class="col-md-2 <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 1 ? '' : 'hidden' ?>">
                                                <label><?php echo CommonLanguage::getMessage('serial') ?></label>
                                            </div>
                                            <div class="col-md-2">
                                                <label><?php echo CommonLanguage::getMessage('Depot') ?></label>
                                            </div>
                                            <div class="col-md-2">
                                                <label><?php echo CommonLanguage::getMessage('Expiry_Date') ?></label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-12"  id="out_items">
                                        <div class="col-md-12 AddRow m-b-10 form-group"  >
                                            <div class="col-md-3 ">
                                                <span class="out_prod_name"></span>
                                            </div>
                                            <div class="col-md-9  out_items_expiry">
                                                <div class="row  out_items_expiry_row  m-t-10" data-prod="" data-uom="">
                                                    <div class="col-md-12 ">
                                                        <div class="col-md-1 " style="display: flex;">
                                                            <span class="edit_row_qty fa fa-pencil cursor hidden"></span>&nbsp;
                                                            <input type="text" class="out_qty cur_val form-control" data-indx="0"/>
                                                        </div>
                                                        <div class="col-md-1 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                                            <input type="text" class="out_cost form-control"/>
                                                        </div>
                                                        <div class="col-md-2 <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 1 ? '' : 'hidden' ?>">
                                                            <input type="text" class="out_lot form-control"/>
                                                        </div>
                                                        <div class="col-md-2 <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 1 ? '' : 'hidden' ?>">
                                                            <input type="text" class="out_serial form-control"/>
                                                        </div>
                                                        <div class="col-md-2">
                                                            <input class="full-width" name="out_depot" type="hidden" value="<?php echo smc_session()['default_depot_id'] ?>" data-select-name="<?php echo smc_session()['default_depot_name'] ?>" />
                                                        </div>
                                                        <div class="col-md-2">
                                                            <input type="text" class="out_expiry_date form-control" name="out_expiry_date"/>
                                                        </div>
                                                        <div class="col-md-1 AddButtons m-t-10">
                                                            <span class="fa fa-plus-circle" style="color:#ed9421;margin-right:25px"></span>
                                                            <span class="fa fa-minus-circle" style="color:#ed9421;"></span>
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <div class='col-md-3'>
                                            <h3><?php echo CommonLanguage::getMessage('needed_items') ?></h3>
                                        </div>
                                        <div class='col-md-3'>
                                            <label><?php echo CommonLanguage::getMessage('optional') ?></label>
                                            <input id="optional_need_items" type="hidden" class="full-width"/>
                                        </div>
                                        <div class='col-md-3 m-t-25 '>
                                            <button style="color:white !important;" id="add_needed_row" class="btn bg-success-dark white" type="button"><?php echo CommonLanguage::getMessage('add') ?></button>
                                        </div>

                                    </div>
                                    <div class="col-md-12">
                                        <div class="col-md-3 ">
                                            <label><?php echo CommonLanguage::getMessage('Item') ?></label>
                                        </div>
                                        <div class="col-md-9">
                                            <div class="col-md-1">
                                                <label><?php echo CommonLanguage::getMessage('Total_Quantity') ?></label>
                                            </div>
                                            <div class="col-md-1 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                                <label><?php echo CommonLanguage::getMessage('unit_cost') ?></label>
                                            </div>
                                            <div class="col-md-1 <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 1 ? '' : 'hidden' ?>">
                                                <label><?php echo CommonLanguage::getMessage('lot') ?></label>
                                            </div>
                                            <div class="col-md-1 <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 1 ? '' : 'hidden' ?>">
                                                <label><?php echo CommonLanguage::getMessage('serial') ?></label>
                                            </div>
                                            <div class="col-md-3">
                                                <label><?php echo CommonLanguage::getMessage('Depot') ?></label>
                                            </div>
                                            <div class="col-md-3">
                                                <label><?php echo CommonLanguage::getMessage('Expiry_Date') ?></label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-12"  id="in_items">
                                        <div class="col-md-12 AddRow m-b-10 form-group"  >
                                            <div class="col-md-3 ">
                                                <span class="in_prod_name"></span>
                                            </div>
                                            <div class="col-md-9 in_items_expiry">
                                                <div class="row  in_items_expiry_row  m-t-10" data-prod="" data-uom="">
                                                    <div class="col-md-12 ">
                                                        <div class="col-md-1" style="display: flex;">
                                                            <span class="edit_row_qty fa fa-pencil cursor hidden"></span>&nbsp;
                                                            <input type="text" class="in_qty cur_val form-control" data-indx="1"/>
                                                        </div>
                                                        <div class="col-md-1 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                                            <input type="text" class="in_cost form-control"/>
                                                        </div>
                                                        <div class="col-md-1 <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 1 ? '' : 'hidden' ?>">
                                                            <input type="hidden" class="in_lot full-width"/>
                                                        </div>
                                                        <div class="col-md-1 <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 1 ? '' : 'hidden' ?>">
                                                            <input type="hidden" class="in_serial full-width"/>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <input class="full-width" name="in_depot" type="hidden" value="<?php echo smc_session()['default_depot_id'] ?>" data-select-name="<?php echo smc_session()['default_depot_name'] ?>" />
                                                        </div>
                                                        <div class="col-md-3">
                                                            <input type="hidden" class="in_expiry_date full-width" name="in_expiry_date"/>
                                                        </div>
                                                        <div class="col-md-1 AddButtons m-t-10">
                                                            <span class="fa fa-plus-circle" style="color:#ed9421;margin-right:25px"></span>
                                                            <span class="fa fa-minus-circle" style="color:#ed9421;"></span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                            <!--</div>-->
                            <!--<div class="tab-pane slide-left " id="slide2">-->
                            <div class="hidden "  id="temp_ex">
                                <h3><?php echo CommonLanguage::getMessage('template_expenses') ?></h3>
                                <div id="template_expenses">
                                    <div class="col-md-12 AddRow m-b-10 form-group"  >
                                        <div class="col-md-12">
                                            <div class="col-xs-5 ">
                                                <label><?php echo CommonLanguage::getMessage('account_name') ?></label>
                                                <!--<input type="hidden" class=" full-width" name="account_id"/>-->
                                                <br><span class="exp_account_name"></span>
                                            </div>
                                            <div class="col-xs-2 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                                <label><?php echo CommonLanguage::getMessage('Cost') ?></label>
                                                <input type="text" class="expense_cost form-control"/>
                                            </div>
                                            <div class="col-xs-2">
                                                <div class="checkbox check-primary  ">
                                                    <input type="checkbox" class="is_total" id="is_total1" />
                                                    <label class="total_label" for="is_total1"><?php echo CommonLanguage::getMessage('total_items') ?></label>
                                                </div>
                                            </div>
                                            <div class="col-xs-2 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : 'hidden';   ?>">
                                                <label><?php echo CommonLanguage::getMessage('total_costs') ?></label>
                                                <input type="text" class="row_cost form-control"/>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="hidden" id="production_emp_type_div">
                                <h3><?php echo CommonLanguage::getMessage('production_emp_type'); ?></h3>
                                <div class="row">
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('type_name'); ?></label>
                                    </div> 
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('Employee'); ?></label>
                                    </div>
                                    <div class="col-md-3 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : '';   ?>">
                                        <label><?php echo CommonLanguage::getMessage('Cost'); ?></label>
                                    </div>
                                    <div class="col-md-3 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : '';   ?>">
                                        <label><?php echo CommonLanguage::getMessage('total_costs'); ?></label>
                                    </div>
                                </div>
                                <div class="AddRow" data-id="">
                                    <div class="row    m-b-10 form-group">
                                        <div class="col-md-3">
                                            <span class="production_emp_type_title" ></span>
                                        </div>
                                        <div class="col-md-9 production_emp_type_div">
                                            <div class="row production_emp_type_row m-t-10">
                                                <div class="col-md-12">
                                                    <div class="col-md-3">
                                                        <input type="hidden" name="production_emp_id" class="full-width production_emp_id"/>
                                                    </div>
                                                    <div class="col-md-3 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : ' ';   ?>">
                                                        <input type="number" step="any" min="0" name="production_emp_cost" class="form-control production_emp_cost"/>
                                                    </div>
                                                    <div class="col-md-3 <?php echo $permissions->hasPermission('display_production_cost') == 1 ? ' ' : ' ';   ?>">
                                                        <input type="number" step="any" min="0" name="production_emp_total_cost" class="form-control production_emp_total_cost" readonly/>
                                                    </div>
                                                    <div class="col-md-1 AddButtons">
                                                        <span class="fa fa-plus-circle m-t-10" style="color:#ed9421;"></span>
                                                        <span class="fa fa-minus-circle m-t-10" style="color:#ed9421;"></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"   >  <?php print CommonLanguage::getMessage('Close'); ?></button>
                <button style="color:white !important;"  class="btn bg-success-dark text-white" id="submit_pro"  >   <?php print CommonLanguage::getMessage('Save'); ?> </button>
            </div>
            <?php echo Forms::ModalLoader('TemplateIsBusy') ?>
        </div>
    </div>
</div>
<script type="text/javascript">
    var Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            default_depot_id = <?php echo json_encode(smc_session()['default_depot_id']); ?>,
            default_depot_name = <?php echo json_encode(smc_session()['default_depot_name']); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    var variables = [], id_val = [], id_content = [], calculated_vars = [], loop_count = 0, max_loop = 500, row_val = {};
    $(function () {
 
        build_select2($("#line_id"), "xhr/CommonSearch?col_name=line_name&col_id=line_id&table=tbl_line");
        $('#states_name').val('Pending').attr('data-select-name','Pending')
        build_select2($("#states_name"), "xhr/CommonSearch?col_name=state_name&col_id=state_name&table=tbl_production_process_states");
        build_select2($("#production_color"), "xhr/commonSearch?table=tbl_production_color&col_id=id&col_name=position_name");
        
       
        $('#s2id_production_color').css('width','100%')
        build_select2($("#template_id"), ("xhr/templateSearch"));
        //                        build_select2($("input[name=production_emp_type_id]"), "xhr/searchProductionEmpType?template_id="+$("#template_id").val());
        build_select2($("input[name=production_emp_id]"), ("xhr/employeeSearch"));
        build_select2($("input[name=out_depot],input[name=in_depot]"), "xhr/depotSearch")
        new Switchery($("#create_trans").get(0), {color: $.Pages.getColor("primary")})
        $("#process_date").datepicker({autoclose: true});
        $("#out_items").on('click', ".AddButtons .fa-plus-circle", function () {
            var Parent = $(this).parents(".out_items_expiry_row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".select2-container").remove();
            NewItem.find(".out_qty").val('');
//            $("input[name=out_expiry_date]", NewItem).val('').attr('data-select-name', '')
//            build_select2($("input[name=out_expiry_date]", NewItem), "xhr/get_product_expiry?product_id=" + Parent.attr('data-prod'), '', 'expiry_width');
//            build_select2($("input.out_lot", NewItem), "xhr/get_product_lot?product_id=" + Parent.attr('data-prod'), '', 'expiry_width');
//            build_select2($("input.out_serial", NewItem), "xhr/get_product_serial?product_id=" + Parent.attr('data-prod'), '', 'expiry_width');
            NewItem.find(".out_expiry_date").datepicker({autoclose: true})

            build_select2(NewItem.find("input[name=out_depot]"), "xhr/depotSearch");
            $(".select2-container", NewItem).show();
            NewItem.find(".out_qty").attr("data-indx", get_next_indx());
        });
        $("#in_items").on('click', ".AddButtons .fa-plus-circle", function () {
            var Parent = $(this).parents(".in_items_expiry_row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".select2-container").remove();
            NewItem.find(".in_qty").val('');
            $("input[name=in_expiry_date]", NewItem).val('').attr('data-select-name', '')
            build_select2($("input[name=in_expiry_date]", NewItem), function () {
                return "xhr/get_product_expiry?product_id=" + Parent.attr('data-prod') + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
            }, '', 'expiry_width');
            build_select2($("input.in_lot", NewItem), function () {
                return "xhr/get_product_lot?product_id=" + Parent.attr('data-prod') + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
            }, '', 'expiry_width');
            build_select2($("input.in_serial", NewItem), function () {
                return "xhr/get_product_serial?product_id=" + Parent.attr('data-prod') + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
            }, '', 'expiry_width');

            build_select2(NewItem.find("input[name=in_depot]"), "xhr/depotSearch");
            $(".select2-container", NewItem).show();
            NewItem.find(".in_qty").attr("data-indx", get_next_indx());
        });
        $("#out_items").on('click', ".AddButtons .fa-minus-circle", function () {
            var identifier = $(this).parents(".AddRow").attr("data-identifier");
            calculated_vars = [];
            loop_count = 0;
            var parent = $(this).parents('.out_items_expiry')
            if ($(".out_items_expiry_row", parent).length != 1) {
                $(this).closest(".out_items_expiry_row").empty().remove();
            }
            calculate_formulas(identifier);
        });
        $("#in_items").on('click', ".AddButtons .fa-minus-circle", function () {
            var identifier = $(this).parents(".AddRow").attr("data-identifier");
            calculated_vars = [];
            loop_count = 0;
            var parent = $(this).parents('.in_items_expiry')
            if ($(".in_items_expiry_row", parent).length != 1) {
                $(this).closest(".in_items_expiry_row").empty().remove();
            }
            calculate_formulas(identifier);
        });
        $("#states_name").on("change", function() {
            if (enable_project_production_process == 1) {
                if ($("#states_name").val() == 'Finished') {
                    $(".production_process_div").removeClass('hidden')
                     
                } else {
                    $(".production_process_div").addClass('hidden')
                }
            }
        })

        $("#add_needed_row").on("click", function () {
            if ($("#optional_need_items").val() == '')
                return;
            var cloned_row = $("#in_items .AddRow:eq(0)").clone(),
                    data = $("#optional_need_items").select2('data');
            cloned_row.find(".select2-container").remove();
            cloned_row.appendTo($("#in_items"))
            cloned_row.attr("data-identifier", data.identifier)
            cloned_row.attr("data-formula", data.formula)
            cloned_row.attr("data-service", data.is_service)
            cloned_row.find("span.in_prod_name").text(data.Product_Name + ' (' + data.current_quantity + ' ' + data.UOM_Name + ')')
            cloned_row.find(".in_items_expiry_row").attr("data-prod", data.id).attr("data-uom", data.UOM_ID)
            if (data.formula != '') {
                cloned_row.find(".edit_row_qty").removeClass('hidden')
                cloned_row.find("input.in_qty").prop('readonly', true)
            } else {
                cloned_row.find(".edit_row_qty").addClass('hidden')
                cloned_row.find("input.in_qty").prop('readonly', false)
            }
            cloned_row.find("input.in_qty").val(data.current_quantity).attr("data-indx", get_next_indx()).attr("data-qty", data.current_quantity)
            cloned_row.find("input.in_cost").val(data.current_cost)
            cloned_row.find("input[name=in_depot]").val(data.Depot_ID).attr("data-select-name", data.Depot_Name)
            build_select2(cloned_row.find("input[name=in_depot]"), "xhr/depotSearch");

            $(".select2-container", cloned_row).show();
            $("#optional_need_items").val('').attr("data-select-name", "").trigger("change")
            trigger_qty_change(cloned_row.find("input.in_qty"))
        })
        $("#add_prod_row").on("click", function () {
            if ($("#optional_prod_items").val() == '')
                return;
            var cloned_row = $("#out_items .AddRow:eq(0)").clone(),
                    data = $("#optional_prod_items").select2('data');
            cloned_row.find(".select2-container").remove();
            cloned_row.appendTo($("#out_items"))
            cloned_row.attr("data-identifier", data.identifier)
            cloned_row.attr("data-formula", data.formula)
            cloned_row.attr("data-service", data.is_service)
            cloned_row.find("span.out_prod_name").text(data.Product_Name + ' (' + data.current_quantity + ' ' + data.UOM_Name + ')')
            cloned_row.find(".out_items_expiry_row").attr("data-prod", data.id).attr("data-uom", data.UOM_ID)
            if (data.formula != '') {
                cloned_row.find(".edit_row_qty").removeClass('hidden')
                cloned_row.find("input.out_qty").prop('readonly', true)
            } else {
                cloned_row.find(".edit_row_qty").addClass('hidden')
                cloned_row.find("input.out_qty").prop('readonly', false)
            }
            cloned_row.find("input.out_qty").val(data.current_quantity).attr("data-indx", get_next_indx()).attr("data-qty", data.current_quantity)
            cloned_row.find("input.out_cost").val(data.current_cost)
            cloned_row.find("input[name=out_depot]").val(data.Depot_ID).attr("data-select-name", data.Depot_Name)
            build_select2(cloned_row.find("input[name=out_depot]"), "xhr/depotSearch");

            $(".select2-container", cloned_row).show();
            $("#optional_prod_items").val('').attr("data-select-name", "").trigger("change")
            trigger_qty_change(cloned_row.find("input.out_qty"))
        })

        $('#add_production_process').on('hidden.bs.modal', function () {
            $('#production_emp_type_div').addClass('hidden');
            $('#production_emp_type_div .production_emp_type_row:gt(0)').remove()
            $('#production_emp_type_div .production_emp_type_row input').val('').trigger('change')
        });
        $("#all_items").on("change", "input.out_depot", function () {
            $(this).parents(".out_items_expiry_row").attr("data-depot-val", $(this).val())
        })

        $("#all_items").on("change", "input.in_depot", function () {
            $(this).parents(".in_items_expiry_row").attr("data-depot-val", $(this).val())
        })

        $("#submit_pro").on("click", function () {
            if (!$("#production_process_form").valid())
                return;
            var is_active = true;
            if (!$("#template_id").val()) {
                $("#TemplateValidationAlert").attr("class", "alert alert-danger").show().html(Required_Fields)
                $("#add_production_process").scrollTop(0)
                return false;
            }
            
             var Data = {
                template_id: $("#template_id").val(),
                Currency_ID: $("#CurrencyDropDown button input").val(),
                date: $("#process_date").val(),
                total_cost: $("#total_cost").attr("data-cost"),
                process_note: $("#process_note").val(),
                process_qty: $("#process_qty").val(),
                line_id: $("#line_id").val(),
                states_name: $("#states_name").val(),
                production_color: $("#production_color").val(),

                expense_arr: [],
                items: [],
                production_employee_type: []
            }
            var valid_neg_qty = true, validate_req = true;
            $("input").removeClass("wrong")
            $("#out_items .AddRow").each(function () {
                var parent = $(this);
                if ($('span.out_prod_name', $(this)).attr('data-prod-status') == "0")
                    is_active = false;
                $('.out_items_expiry_row', $(this)).each(function () {
                    var cur_qty = parseFloat($(this).find(".out_qty").val()) || 0;
                    if (cur_qty >= 0) {
                        Data.items.push({
                            is_service: parent.attr("data-service"),
                            item_id: $(this).attr("data-prod"),
                            item_uom: $(this).attr("data-uom"),
                            item_qty: $(this).find(".out_qty").val(),
                            initial_qty: $(this).find(".out_qty").attr("data-qty"),
                            item_cost: $(this).find(".out_cost").val(),
                            item_lot: $(this).find("input.out_lot").val(),
                            item_serial: $(this).find("input.out_serial").val(),
                            item_depot: $(this).find("input[name=out_depot]").val(),
                            operation: '+',
                            expiry_date: $(this).find("input[name=out_expiry_date]").val(),
                            formula: parent.attr("data-formula"),
                            identifier: parent.attr("data-identifier"),
                        });

                        if (activate_lot == 1 && $(this).attr("data-is-lot") == 1 && $(this).find("input.out_lot").val() == '') {
                            validate_req = false
                            $(this).find(".out_lot").addClass("wrong")

                        } else if (activate_serial == 1 && $(this).attr("data-is-serial") == 1 && $(this).find("input.out_serial").val() == '') {
                            validate_req = false;
                            $(this).find(".out_serial").addClass("wrong")
                        } else if (activate_expiry_date == 1 && $(this).attr("data-is-expiry") == 1 && $(this).find("input[name=out_expiry_date]").val() == '') {
                            validate_req = false;
                            $(this).find("input[name=out_expiry_date]").addClass("wrong")
                        }
                    } else {
                        valid_neg_qty = false;
                        $(this).find(".out_qty").addClass("wrong")
                    }
                });
            });
            $("#in_items .AddRow").each(function () {
                var parent = $(this);
                if ($('span.in_prod_name', $(this)).attr('data-prod-status') == "0")
                    is_active = false;
                $('.in_items_expiry_row', $(this)).each(function () {
                    var cur_qty = parseFloat($(this).find(".in_qty").val()) || 0;
                    if (cur_qty >= 0) {
                        Data.items.push({
                            is_service: parent.attr("data-service"),
                            item_id: $(this).attr("data-prod"),
                            item_uom: $(this).attr("data-uom"),
                            item_qty: $(this).find(".in_qty").val(),
                            initial_qty: $(this).find(".in_qty").attr("data-qty"),
                            item_cost: $(this).find(".in_cost").val(),
                            item_lot: $(this).find("input.in_lot").val(),
                            item_serial: $(this).find("input.in_serial").val(),
                            item_depot: $(this).find("input[name=in_depot]").val(),
                            operation: '-',
                            expiry_date: $(this).find("input[name=in_expiry_date]").val(),
                            formula: parent.attr("data-formula"),
                            identifier: parent.attr("data-identifier"),
                        });
                        if (activate_lot == 1 && $(this).attr("data-is-lot") == 1 && $(this).find("input.in_lot").select2("data") == null) {
                            validate_req = false;
                            $(this).find(".in_lot").addClass("wrong")

                        } else if (activate_serial == 1 && $(this).attr("data-is-serial") == 1 && $(this).find("input.in_serial").select2("data") == null) {
                            validate_req = false;
                            $(this).find(".in_serial").addClass("wrong")
                        } else if (activate_expiry_date == 1 && $(this).attr("data-is-expiry") == 1 && $(this).find("input[name=in_expiry_date]").select2("data") == null) {
                            validate_req = false;
                            $(this).find("input[name=in_expiry_date]").addClass("wrong")
                        }
                    } else {
                        valid_neg_qty = false;
                        $(this).find(".in_qty").addClass("wrong")
                    }
                });
            });
            if (!valid_neg_qty) {
                $("#TemplateValidationAlert").attr("class", "alert alert-danger").empty().html('<?php echo CommonLanguage::getMessage('negative_value') ?>');
                $("#add_production_process").scrollTop(0)
                return;
            }
//            console.log(validate_req)
            if (!validate_req) {
                $("#TemplateValidationAlert").attr("class", "alert alert-danger").empty().html('<?php echo CommonLanguage::getMessage('Required_Fields') ?>');
                $("#add_production_process").scrollTop(0)
                return;
            }
            $("#template_expenses .AddRow").each(function () {
                if ($(this).attr("data-account") != '' && $(this).find(".expense_cost").val() != '' && $(this).find(".expense_cost").val() != 0) {
                    Data.expense_arr.push({
                        account_id: $(this).attr("data-account"),
                        expense_cost: $(this).find(".expense_cost").val(),
                        total_cost: $(this).find(".row_cost").val(),
                        is_total: $(this).find(".is_total").is(":checked") ? 1 : 0
                    })
                }
            });
            validate = true;
            $("#production_emp_type_div .AddRow").each(function () {
                var current_main_row = $(this);
                $(".production_emp_type_row", current_main_row).each(function () {
                    if ($(this).find("input.production_emp_id").val()) {
                        Data.production_employee_type.push({
                            type_id: current_main_row.attr('data-id'),
                            employee_id: $(this).find("input.production_emp_id").val(),
                            cost: $(this).find("input.production_emp_cost").val(),
                        });
                    } else {
                        if ($(this).find("input.production_emp_id").val() == '' && $(this).find("input.production_emp_cost").val() != ''
                                && $(this).find("input.production_emp_cost").val() != 0) {
                            $(this).find("input.production_emp_id").addClass("wrong")
                            validate = false;
                        }
                    }
                });

            });
            if (!validate) {
                $("#TemplateValidationAlert").attr("class", "alert alert-danger").empty().html('<?php echo CommonLanguage::getMessage('check_emps') ?>');
                $("#add_production_process").scrollTop(0)
                return;
            }
            if (IsEdit) {
                Data.process_id = IDToEdit;
            }
            if (!is_active) {
                $("#TemplateValidationAlert").attr("class", "alert alert-danger").empty().html('<?php echo CommonLanguage::getMessage('alert_status_item'); ?>');
                $("#add_production_process").scrollTop(0)
                return;
            }
            $("#TemplateIsBusy").removeClass('hidden');
            $.ajax({
                url: IsEdit ? "InventoryAjax/update_production_process" : "InventoryAjax/add_production_process",
                method: "POST",
                data: Data,
                dataType: "json",
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseJSON[0] == 'OK') {
                        $("#TemplateValidationAlert").attr("class", "alert alert-success").empty().html(Submitted_Successfully);
                        setTimeout(function () {
                            $("#add_production_process").modal('hide')
                            $("#TemplateValidationAlert").hide()
                            $("#in_items .AddRow:gt(0),#out_items .AddRow:gt(0),#template_expenses .AddRow:gt(0)").remove()
                            $("input.in_qty,input.out_qty,input.expense_cost").val('')
                            $("input[name=in_product],input[name=out_product],input[name=in_uom],input[name=out_uom],input[name=account_id]").val('').attr("data-select-name", "");
                            build_select2($("#template_id"), ("xhr/templateSearch"))
                            $("#slide2").removeClass("active")
                            $("#slide1").addClass("active")
                        }, 1500)
                        RebuildDataTable(title, [0, 1], "InventoryAjax/production_process_list")
                    } else {
                        if (v1.responseJSON[0] == 'expiry_error') {
                            $.each(v1.responseJSON[1], function (indx, row) {
                                $(".in_items_expiry_row[data-prod=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input[name=in_expiry_date][value=" + row['expiry_date'] + "]").addClass("wrong")
                            })
                            $("#TemplateValidationAlert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_expiry_exist') ?>')

                        } else
                        if (v1.responseJSON[0] == 'serial_error') {
                            $.each(v1.responseJSON[1], function (indx, row) {
                                $(".in_items_expiry_row[data-prod=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]    input.is_serial[value=" + row['serial_nb'] + "]").addClass("wrong")
                            })
                            $("#TemplateValidationAlert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_serial_exist') ?>')

                        } else
                        if (v1.responseJSON[0] == 'lot_error') {
                            $.each(v1.responseJSON[1], function (indx, row) {
                                $(".in_items_expiry_row[data-prod=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]    input.in_lot[value=" + row['lot_nb'] + "]").addClass("wrong")
                            })
                            $("#TemplateValidationAlert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_lot_exist') ?>')

                        } else
                        if (v1.responseJSON[0] == 'qty_error') {
                            $.each(v1.responseJSON[1], function (indx, row) {
                                $(".in_items_expiry_row[data-prod=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input.in_qty").addClass("wrong")
                            })
                            $("#TemplateValidationAlert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_qty_exist') ?>')

                        } else {
                            $("#TemplateValidationAlert").attr("class", "alert alert-danger").empty().html(v1.responseJSON[1][0]);
                        }
                    }
                    $("#add_production_process").scrollTop(0)
                    $("#TemplateIsBusy").addClass('hidden');
                }
            })
            $("#NewProductUploadImagePreview").attr("src", "img/profiles/product.png");
        })
        $("#template_id").on("change", function () {
            template_id = $(this).val();
            build_select2($("input[name=production_emp_type_id]"), "xhr/searchProductionEmpType?template_id=" + $("#template_id").val());
            $("#out_items .AddRow").each(function () {
                $('.out_items_expiry_row:gt(0)', $(this)).remove();
            })
            $("#in_items .AddRow").each(function () {
                $('.in_items_expiry_row:gt(0)', $(this)).remove();
            });
            if (template_id) {
                $.ajax({
                    url: "InventoryAjax/get_production_template_id",
                    method: "GET",
                    dataType: "json",
                    data: {id: template_id, with_optional: 0},
                    complete: function (v1, v2) {
                        if (v2 == 'success') {
                            var mydata = v1.responseJSON;
                            variables = mydata['variables'];
                            id_val = mydata['id_val'];
                            id_content = mydata['id_content'];
                            $("#CurrencyDropDown button input").val(mydata['main']['Currency_ID'])
                            $("#CurrencyDropDown button span").html(mydata['main']['Currency_Name'] + " - " + mydata['main']['Currency_Symbol'])
                            if (mydata['main']['is_line_required'] == 1) {
                                $('.line_red_star').removeClass('hidden')
                            } else {
                                $('.line_red_star').addClass('hidden')
                            }
                            $('#line_id').attr('required', mydata['main']['is_line_required'] == 1 ? true : false)
                            $("#CurrencyDropDown").attr("data-symbol", mydata['main']['Currency_Symbol']);

                            var details = mydata['details'];
                            var out_row = $("#out_items .AddRow:eq(0)").clone(),
                                    in_row = $("#in_items .AddRow:eq(0)").clone();
                            $("#out_items,#in_items").empty();
                            $("#out_items .AddRow .out_items_expiry .out_items_expiry_row:eq(1),#in_items  .AddRow .in_items_expiry .in_items_expiry_row:eq(1)").remove();
                            build_select2($("#optional_need_items"), "xhr/opt_temp_prod_search?is_needed=1&template_id=" + template_id)
                            build_select2($("#optional_prod_items"), "xhr/opt_temp_prod_search?is_needed=0&template_id=" + template_id)
                            for (var i = 0; i < details.length; i++) {

                                if (details[i]['operation'] == "+") {
                                    out_row = (out_row === null ? $("#out_items .AddRow:eq(0)").clone() : out_row);
                                    $("#out_items").append(out_row)
                                    $(".select2-container", out_row).empty().remove()
                                    out_row.attr("data-formula", details[i]['formula'])
                                    out_row.attr("data-identifier", details[i]['new_identifier'])
                                    out_row.find('div.out_items_expiry_row').attr("data-prod", details[i]['Product_ID'])
                                    out_row.find('div.out_items_expiry_row').attr("data-uom", details[i]['UOM_ID'])
                                    out_row.find('div.out_items_expiry_row').attr("data-depot-val", details[i]['UOM_ID'])
                                    out_row.find('div.out_items_expiry_row').attr("data-is-lot", details[i]['is_lot'])
                                    out_row.find('div.out_items_expiry_row').attr("data-is-serial", details[i]['is_serial'])
                                    out_row.find('div.out_items_expiry_row').attr("data-is-expiry", details[i]['is_expiry'])
                                    out_row.find(".out_prod_name").attr("data-prod-status", details[i]['Depot_ID'])
                                    out_row.find(".out_prod_name").html(details[i]['Product_Name'] + " (" + details[i]['current_quantity'] + " " + details[i]['UOM_Name'] + ")")
                                    out_row.find("input[name=out_depot]").val(details[i]['Depot_ID']).attr("data-select-name", details[i]['Depot_Name'])
                                    build_select2(out_row.find("input[name=out_depot]"), "xhr/depotSearch")
                                    out_row.find(".out_qty").val(details[i]['current_quantity']).attr("data-indx", i)
                                    if (details[i]['formula'] != '') {
                                        out_row.find(".out_qty").prop('readonly', true)
                                        out_row.find(".edit_row_qty").removeClass('hidden')
                                    }
//                                    out_row.find(".out_lot").val(details[i]['lot_nb'])
//                                    out_row.find(".out_serial").val(details[i]['serial_nb']);
                                    out_row.attr('data-service', details[i]['is_service'])
                                    if (details[i]['is_lot'] == 1) {
                                        out_row.find(".out_lot").removeClass("hidden")
//                                        build_select2($("input.out_lot", out_row), "xhr/get_product_lot?product_id=" + details[i]['Product_ID'], '', 'expiry_width');
                                    } else {
                                        out_row.find(".out_lot").addClass("hidden")
                                    }
                                    if (details[i]['is_serial'] == 1) {
//                                        build_select2($("input.out_serial", out_row), "xhr/get_product_serial?product_id=" + details[i]['Product_ID'], '', 'expiry_width');
                                        out_row.find(".out_serial").removeClass("hidden")
                                    } else {
                                        out_row.find(".out_serial").addClass("hidden")
                                    }
                                    out_row.find(".out_qty").attr("data-qty", details[i]['current_quantity'])
                                    out_row.find(".out_cost").val(parseFloat(details[i]['current_cost']) || 0);
                                    if (details[i]['is_expiry'] == 1) {
                                        out_row.find("input[name=out_expiry_date]").datepicker({autoclose: true})
//                                        build_select2($("input[name=out_expiry_date]", out_row), "xhr/get_product_expiry?product_id=" + details[i]['Product_ID'], '', 'expiry_width');
                                        out_row.find("input[name=out_expiry_date]").removeClass('hidden')
                                    } else {
                                        out_row.find("input[name=out_expiry_date]").addClass('hidden')
                                    }

                                    $(".select2-container", out_row).show();
                                    out_row = null;
                                } else {
                                    in_row = (in_row === null ? $("#in_items .AddRow:eq(0)").clone() : in_row);
                                    $("#in_items").append(in_row)
                                    $(".select2-container", in_row).empty().remove()
                                    in_row.attr("data-formula", details[i]['formula'])
                                    in_row.attr("data-identifier", details[i]['new_identifier'])
                                    in_row.find('div.in_items_expiry_row').attr("data-prod", details[i]['Product_ID'])
                                    in_row.find('div.in_items_expiry_row').attr("data-uom", details[i]['UOM_ID'])
                                    in_row.find('div.in_items_expiry_row').attr("data-depot-val", details[i]['Depot_ID'])
                                    in_row.find('div.in_items_expiry_row').attr("data-is-lot", details[i]['is_lot'])
                                    in_row.find('div.in_items_expiry_row').attr("data-is-serial", details[i]['is_serial'])
                                    in_row.find('div.in_items_expiry_row').attr("data-is-expiry", details[i]['is_expiry'])
                                    in_row.find(".in_prod_name").attr("data-prod-status", details[i]['Status_ID'])
                                    in_row.find(".in_prod_name").html(details[i]['Product_Name'] + " (" + details[i]['current_quantity'] + " " + details[i]['UOM_Name'] + ")")
                                    in_row.find("input[name=in_depot]").val(details[i]['Depot_ID']).attr("data-select-name", details[i]['Depot_Name'])
                                    build_select2(in_row.find("input[name=in_depot]"), "xhr/depotSearch")
                                    in_row.find(".in_qty").val(details[i]['current_quantity']).attr("data-indx", i)
//                                    in_row.find(".in_lot").val(details[i]['lot_nb']);
                                    in_row.attr('data-service', details[i]['is_service'])
                                    if (details[i]['is_lot'] == 1) {
                                        in_row.find(".in_lot").removeClass("hidden")
                                        build_select2($("input.in_lot", in_row), function () {
                                            return "xhr/get_product_lot?product_id=" + this.parents('.in_items_expiry_row').attr("data-prod") + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
                                        }, '', 'expiry_width');

                                    } else {
                                        in_row.find(".in_lot").addClass("hidden")
                                    }

                                    if (details[i]['is_serial'] == 1) {
                                        in_row.find(".in_serial").removeClass("hidden")
                                        build_select2($("input.in_serial", in_row), function () {
                                            return "xhr/get_product_serial?product_id=" + this.parents('.in_items_expiry_row').attr("data-prod") + '&depot=' + $("input[name=in_depot]",this.parents('.in_items_expiry_row')).val();
                                        }, '', 'expiry_width');

                                    } else {
                                        in_row.find(".in_serial").addClass("hidden")
                                    }
//                                    in_row.find(".in_serial").val(details[i]['serial_nb'])
                                    in_row.find(".in_qty").attr("data-qty", details[i]['current_quantity'])
                                    if (details[i]['formula'] != '') {
                                        in_row.find(".in_qty").prop('readonly', true)
                                        in_row.find(".edit_row_qty").removeClass('hidden')
                                    }
                                    in_row.find(".in_cost").val(details[i]['current_cost'])
                                    if (details[i]['is_expiry'] == 1) {
                                        build_select2($("input[name=in_expiry_date]", in_row), function () {
                                            return "xhr/get_product_expiry?product_id=" + this.parents('.in_items_expiry_row').attr("data-prod") + '&depot=' + $("input[name=in_depot]", this.parents('.in_items_expiry_row')).val();
                                        }, '', 'expiry_width');
                                        in_row.find("input[name=in_expiry_date]").removeClass('hidden')
                                    } else {
                                        in_row.find("input[name=in_expiry_date]").addClass('hidden')
                                    }
                                    $(".select2-container", in_row).show();
                                    in_row = null;
                                }
                            }
                            var expenses = mydata['expense'];
                            var ex_row = $("#template_expenses .AddRow:eq(0)").clone();
                            $("#template_expenses").empty();
                            if (expenses.length > 0) {

                                for (var i = 0; i < expenses.length; i++) {
                                    ex_row = (ex_row === null ? $("#template_expenses .AddRow:eq(0)").clone() : ex_row);
                                    $("#template_expenses").append(ex_row)
                                    $(".select2-container", ex_row).empty().remove()
                                    ex_row.attr("data-account", expenses[i]['Account_ID'])
                                    ex_row.find("span.exp_account_name").html(expenses[i]['Account_Name'] + " (" + expenses[i]['cost'] + " " + mydata['main']['Currency_Symbol'] + ")")
                                    ex_row.find(".expense_cost").val(expenses[i]['cost'])
                                    if (expenses[i]['is_total'] == 1) {
                                        ex_row.find(".is_total").prop("checked", true)
                                    } else {
                                        ex_row.find(".is_total").removeAttr("checked")
                                    }
                                    $(".select2-container", in_row).show()
                                    calculate_expense_row_cost(ex_row)
                                    ex_row = null;
                                }
                            } else {
                                $("#template_expenses").append(ex_row)
                                ex_row.find("span.exp_account_name").html("")
                                $(".select2-container", ex_row).empty().remove()
                                ex_row.find("input").val("")
                                ex_row.find("input[name=account_id]").attr("data-select-name", '')
                                build_select2($("input[name=account_id]"), "xhr/allAccountsSearch")
                                $(".select2-container", in_row).show()
                            }
                            $("#all_items,#temp_ex").removeClass("hidden")
                            calculate_produced_cost()

                            var production_emp_type_arr = mydata['production_emp_type'],
                                    production_emp_type_row = $("#production_emp_type_div .AddRow:eq(0)").clone();
                            if (production_emp_type_arr.length > 0) {
                                $("#production_emp_type_div .AddRow").remove();
                                $('#production_emp_type_div').removeClass('hidden');
                                for (var i = 0; i < production_emp_type_arr.length; i++) {
                                    production_emp_type_row = production_emp_type_row == null ? $("#production_emp_type_div .AddRow:eq(0)").clone() : production_emp_type_row;
                                    $("#production_emp_type_div").append(production_emp_type_row);
                                    production_emp_type_row.attr('data-id', production_emp_type_arr[i]['id']);
                                    $('span.production_emp_type_title', production_emp_type_row).html(production_emp_type_arr[i]['text']);
                                    $(".select2-container", production_emp_type_row).remove();
                                    $("input", production_emp_type_row).val('');
                                    build_select2($("input[name=production_emp_id]", production_emp_type_row), ("xhr/employeeSearch"));
                                    $(".select2-container", production_emp_type_row).show();
                                    production_emp_type_row = null;
                                }
                            } else {
                                $('#production_emp_type_div').addClass('hidden')
                                $('#production_emp_type_div .AddRow:gt(0),#production_emp_type_div .AddRow .production_emp_type_row:gt(0)').remove();
                                $('#production_emp_type_div .production_emp_type_row input').val('').trigger('change');
                            }
                        }
                    }
                });
            } else {
                $('#all_items,#production_emp_type_div').addClass('hidden')
                $('#production_emp_type_div .production_emp_type_row:gt(0)').remove()
                $('#production_emp_type_div .production_emp_type_row input').val('').trigger('change')
            }
        });
        $('#template_expenses').on('change', '.is_total', function () {
            calculate_expense_row_cost($(this).parents(".AddRow"))
            calculate_produced_cost()
        })
        $("#process_qty").on("keyup change", function () {
            var pr_qty = parseFloat($(this).val());
            $('#template_expenses .is_total').each(function () {
                calculate_expense_row_cost($(this).parents(".AddRow"))
            });
            $("#out_items .AddRow[data-formula='']").each(function () {
                var qty_input = $(this).find(".out_qty");
                qty_input.val(parseFloat(qty_input.attr("data-qty")) * pr_qty);
                trigger_qty_change(qty_input)
            });
            $("#in_items .AddRow[data-formula='']").each(function () {
                var qty_input = $(this).find(".in_qty");
                qty_input.val(parseFloat(qty_input.attr("data-qty")) * pr_qty);
                trigger_qty_change(qty_input)
            });
            calculate_emp_total_cost()
            calculate_produced_cost()
        })
        $("#in_items").on("keyup", ".in_cost", function () {
            calculate_produced_cost();
        })
        $("#out_items").on("keyup", ".out_qty", function () {
            trigger_qty_change($(this));
            calculate_produced_cost();
        });
        $("#in_items").on("keyup", ".in_qty", function () {
//            console.log('here')
            trigger_qty_change($(this));
            calculate_produced_cost();
        });

        $("#template_expenses").on("keyup", ".expense_cost", function () {
            calculate_expense_row_cost($(this).parents(".AddRow"))
            calculate_produced_cost()
        })
        $("#template_expenses").on("keyup", ".row_cost", function () {
            calculate_produced_cost()
        });
        $("#production_emp_type_div").on("click", ".AddButtons .fa-plus-circle", function (e) {
            var Parent = $(this).parents(".production_emp_type_row"),
                    NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".select2-container").remove();
            NewItem.find("input").val('');
            build_select2($("input[name=production_emp_id]", NewItem), ("xhr/employeeSearch"));
            $(".select2-container", NewItem).show();
        });
        $("#production_emp_type_div").on("click", ".AddButtons .fa-minus-circle", function (e) {
            var parent = $(this).closest('.production_emp_type_div')
            if ($(".production_emp_type_row", parent).length > 1)
                $(this).closest(".production_emp_type_row").empty().remove();
            else {
                $(this).closest(".production_emp_type_row").find("input").val('');
                $(this).closest(".production_emp_type_row").find(".production_emp_id").attr("data-select-name", "").trigger("change")
            }
            calculate_produced_cost()
        });

        $("#production_emp_type_div").on("input", "input[name=production_emp_cost]", function () {
            calculate_emp_total_cost()
            calculate_produced_cost()
        })



        $("#all_items").on("click", ".edit_row_qty", function () {
            var tr = $(this).parents(".AddRow");
            $("input.cur_val", tr).prop('readonly', false)
            tr.attr("data-formula", "")
        })
    })

    function calculate_emp_total_cost() {
        $(".production_emp_type_row").each(function () {
            var tr = $(this),
                    cost = parseFloat($("input[name=production_emp_cost]", tr).val() || 0),
                    main_qty = parseFloat($("#process_qty").val() || 0),
                    total = cost * main_qty;
            $("input[name=production_emp_total_cost]", tr).val(total == 0 ? '' : total)
        })
    }

    function calculate_expense_row_cost(row) {
        var tr_unit_cost = parseFloat(row.find(".expense_cost").val()) || 0,
                process_qty = parseFloat($("#process_qty").val()) || 1,
                row_cost = !row.find(".is_total").is(":checked") ? (process_qty * tr_unit_cost) : tr_unit_cost;
        row.find(".row_cost").val(row_cost)
    }

    function calculate_produced_cost() {
        var prod_cost = 0;
        $("#in_items .in_items_expiry_row").each(function () {
            prod_cost += ((parseFloat($(this).find("input.in_cost").val()) || 0) * (parseFloat($(this).find("input.in_qty").val()) || 0));
        })
        $("#template_expenses .AddRow").each(function () {
            prod_cost += parseFloat($(this).find(".row_cost").val()) || 0;
        })
        $(".production_emp_type_row").each(function () {
            var tr = $(this);
            prod_cost += parseFloat($("input[name=production_emp_total_cost]", tr).val() || 0);
        })
        prod_cost = public_round_number(prod_cost);
        $("#total_cost").html(prod_cost + " " + $("#CurrencyDropDown").attr("data-symbol")).attr("data-cost", prod_cost)
        var out_length = $("#out_items .AddRow").length;
        $("#out_items .AddRow").each(function () {
            $("#out_items .AddRow .out_cost").val(((prod_cost / (parseFloat($(this).find(".out_qty").val()) * out_length)) || 0).toFixed(3))
        })
    }

    function trigger_qty_change(me, is_auto) {
        if (typeof (is_auto) == undefined || !is_auto) {
            calculated_vars = [];
            loop_count = 0;
        }
        var identifier = me.parents(".AddRow").attr("data-identifier");
        calculate_formulas(identifier);
    }

    function calculate_formulas(identifier) {
        var id_arr = variables[identifier];
        if (id_arr == undefined)
            id_arr = [];
//        console.log(id_arr)
        $.each(id_arr, function (indx, id) {
            try {
                loop_count++;
                calculate_id_value(id);
            } catch (e) {
                alert(e)
                return false;   //break
            }
        });
        //
        if (loop_count > max_loop)
            alert('too many recursions..');
        else {
            //

//            $.each(id_val, function (indx, value) {
//                var tr = $(".AddRow[data-identifier=" + indx + "][data-formula!='']"),
//                        sum = 0;
//                value = parseFloat(value) || 0;
//
//                $(".AddRow[data-identifier=" + indx + "][data-formula='']").each(function () {
//                    sum += (parseFloat($("input.cur_val", $(this)).val()) || 0)
//                });
//
//                if (loop_count > max_loop)
//                    return false;   //break
//                $("input.cur_val", tr).val(round_number((value - sum), 3));
//                if (!calculated_vars.includes(indx)) {//to check if value set before then do not trigger the change of value
//                    calculated_vars.push(indx);
//                    trigger_qty_change($("input.cur_val", tr), true);
//                }
//            });
//console.log(row_val)
            $.each(row_val, function (indx, value) {
//                console.log(indx+'==='+value)
                if (value == '')
                    return true;
                value = parseFloat(value) || 0;
                if (loop_count > max_loop)
                    return false;   //break
                $("input.cur_val[data-indx=" + indx + "]").val(round_number(value, 3));
                if (!calculated_vars.includes(indx)) {//to check if value set before then do not trigger the change of value
                    calculated_vars.push(indx);
                    trigger_qty_change($("input.cur_val[data-indx=" + indx + "]"), true);
                }
            });

        }
    }


    function calculate_id_value(identifier) {
        console.log(identifier)
        //
        id_val[identifier] = 0;
        $(".AddRow[data-identifier=" + identifier + "] input.cur_val").each(function () {
            var parent = $(this).parents(".AddRow");
            if (parent.attr("data-formula") != '') {
                var id_arr = id_content[identifier];
                if (id_arr != undefined) {
                    $.each(id_arr, function (indx, id) {
                        id_val[id] = calculate_id_value(id)
                    });
                }
                var formula = parent.attr("data-formula");
                $.each(id_val, function (indx, value) {
                    formula = formula.replace(new RegExp(indx, "g"), value)
                });
                try {
                    id_val[identifier] += eval(formula);
                    row_val[$(this).attr("data-indx")] = eval(formula);
                } catch (e) {
                    alert("Error Evaluate Formula: [Identifier: " + identifier + "]\r\nMain Formula: " + parent.attr("data-formula") + "\r\nEval Formula: " + formula + "\r\nError: " + e)
                    throw 'error_eval_formula';
                }
            } else {
//                console.log(parent.attr("data-identifier") + '====' + (parseFloat($(this).val()) || 0))
                id_val[parent.attr("data-identifier")] += (parseFloat($(this).val()) || 0)
                row_val[$(this).attr("data-indx")] = (parseFloat($(this).val()) || 0)
            }
        });
        return id_val[identifier];
    }

    function get_next_indx() {
        var maximum = 0;
        $('input.cur_val').each(function () {
            var value = parseFloat($(this).attr('data-indx'));
            maximum = (value > maximum) ? value : maximum;
        });
//        console.log(maximum)
        return (maximum + 1);
    }

</script>
