<?php
if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
if ($IsEdit && empty($edit_arr['Main']['Auto_ID'])) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this consumption! 
        <br>
        This consumption is not available.
    </div>
    <?php
    return;
}

$consumption_inv_fields_hide = smc_session()['default_setting']['consumption_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['consumption_fields_to_hide']) : [];
?>
<style type="text/css">
    #InventoryPurchaseTable thead tr th{
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #items_table th{
        background: #4c0870;
        color: #fff;

    }
    #InventoryPurchaseTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
        padding: 5px 9px 12px;
        /*font-size:12px;*/
        /*padding:0;*/
        /*padding-bottom:5px;*/
        height: 40px;
    }


    #InventoryPurchaseTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #InventoryPurchaseTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput,#TTCInvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;


    }
    #Shipping,#extra_cost{
        display: inline-block;
        width: 55%;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;


    }
    #InvoiceVAT,#total_profit{
        display: inline-block;
        width: 92px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
        margin-left: 23px;

    }
    /*    #InventoryPurchaseTable .Hint{
    position: absolute;
    font-size: 10px;
    font-weight: bold;
    height: 20px;
    line-height: 20px;
    bottom: 2px;
    right: 4px;
    color: rgb(153, 153, 153);
    }*/
    #InventoryPurchaseTable .Hint{
        position: absolute;
        font-size: 10px;
        display: block;
        font-weight: bold;
        height: 12px;
        line-height: 11px;
        cursor: default;
        background: #ccc;
        padding: 0 2px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        bottom: 3px;
        right: 1px;
        left: 1px;
        color: #4c0870;
    }
    #InventoryPurchaseTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    /*    #InventoryPurchaseTable .Disc{
    width:70px;
    }*/
    .wrong{
        border: 1px solid rgba(255, 0, 0, 0.2) !important;
        background: rgba(255, 0, 0, 0.05) !important;
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    /*    .select2-container > .select2-choice{
    background-color: #e5e5e5;
    width: 150px;
    }*/
    #InventoryPurchaseTable .select2-container .select2-choice {
        background-image: none;
        border-radius: 2px;
        border: 1px solid rgba(0,0,0,0.07);
        padding: 5px 9px 16px;
        transition: border 0.2s linear 0s;
        height: 40px;
        background-color: #e5e5e5;
        width: 150px;
    }
    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;

    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .hideme{

        display:none;
    }
    .select2-container > .select2-choice {

        width: 100% !important;

    }
    .supInv{
        display:inline-flex;
    }
    .invoice{
        padding-top:0 !important;
    }
    #Truck{
        width:48%;
        margin-right:2%
    }
    .right-div .form-group{
        margin-bottom:0px;
    }
    .diff_class,.expiry_width{
        width:300px!important;
    }

    #items-modal .modal-header{
        padding-top:0;
    }
    #items_table td{
        padding:2px 5px ;
    }
    /*    #items_table tr.odd td{ background: white;  border:1px lightgrey;}
    #items_table tr.even td{ background: #ccc; border:1px lightgrey; }*/

    .tags{
        cursor:pointer;
    }
    .inputDiv {
        background-color: transparent;
        font-size: large;
        border: none;
        border-radius: 0;
    }
    .inputDiv input {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        opacity: 0.01;
        cursor: pointer;
    }
    #TagsTable td:not(:first-child){
        padding:0;
    }
    .tagSelected,.inputDiv:hover{
        background-color:#6DC0F9  !important;
        border-color:#6DC0F9  !important;
        color:white;
    }
    .removeTags{
        text-align:center;
        vertical-align:middle !important;
        width:10%;
        cursor:pointer;
    }
    #InventoryPurchaseTable td span.mylabel{
        font-size:10px !important;
        display: inline-table !important;
        white-space:normal !important;
        line-height: 21px !important;
    }
    #InventoryPurchaseTable .bootstrap-tagsinput .tag [data-role="remove"] {
        font-size:13px !important;

    }
    #InventoryPurchaseTable .bootstrap-tagsinput{
        max-height: 40px;
        overflow: hidden;

    }
</style>

<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.js?v=<?php echo trusto_VERSION; ?>"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.compatibility.js"></script>
<div id="PurchaseDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
<form method="POST" action="" onsubmit="return false" id="InvoiceForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id = "PurchaseSuccess" class = "hidden"></div>
                <div class = "invoice ">
                    <div class = "container-sm-height">
                        <div class = "row-sm-height">
                            <div class = "col-md-9 col-sm-height sm-no-padding">
                                <div class = "row " style = "display:flex;">
                                    <div class = "col-md-6">
                                        <h2 class = "font-montserrat all-caps hint-text"><?php echo $title; ?> </h2>
                                    </div>
                                </div>

                                <div class='row form-group'>
                                    <div class="input-group  col-md-4 center-margin pull-left " >
                                        <label><?php print CommonLanguage::getMessage('choose_customer'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo "Inventory/CustomerList?is_pop=1" ?>" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="search_supplier full-width" id="search_supplier" name="search_supplier" type="hidden" value="<?= ($IsEdit) ? $edit_arr['Main']['Customer_ID'] : ''; ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['Person']['Name'] : ""); ?>' />
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class='row form-group'>
                                    <div id="SupplierInfo" class="col-md-4">
                                        <div class="col-md-12">
                                            <input type="hidden" name="Supplier_ID" value="<?php echo ($IsEdit) ? ($edit_arr['Main']['Customer_ID'] ) : '' ?>" required id="Supplier_ID" />
                                            <div id="SupplierInfoContent" class="<?php echo ($IsEdit) ? '' : 'hidden' ?>">
                                                <strong><span class='Name' id='Supplier_Name' data-id='<?php echo ($IsEdit ) ? $edit_arr['Person']['Name'] : '' ?>' data-account-name='<?php echo ($IsEdit ) ? $edit_arr['Person']['Name'] : '' ?>' data-account-id='<?php echo ($IsEdit ) ? $edit_arr['Person']['Account_ID'] : '' ?>' data-account-code='<?php echo ($IsEdit ) ? $edit_arr['Person']['Account_Code'] : '' ?>'><?php echo ($IsEdit) ? $edit_arr['Person']['Name'] : '' ?></span><span class='fa fa-eye m-l-5 openFrame <?php echo $permissions->hasPermission($is_actual ? 'ActualLedger' : 'ledger') ? '' : 'hidden' ?>' data-src='ACC/ledger?is_pop=1/<?php echo $IsEdit ? $edit_arr['Person']['Account_Code'] : '' ?>' style='color:#8a7dbe;cursor:pointer'></span></strong>
                                                <div><strong><?php echo CommonLanguage::getMessage('company'); ?>: </strong><span class='Company'><?php echo ($IsEdit) ? $edit_arr['Person']['Company'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('Email'); ?>: </strong><span class='Email'><?php echo ($IsEdit) ? $edit_arr['Person']['Email'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('Phone'); ?>: </strong><span class='Phone'><?php echo ($IsEdit) ? $edit_arr['Person']['Phone'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('address'); ?>: </strong><span class='Address'><?php echo ($IsEdit) ? $edit_arr['Person']['Address'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('country'); ?>: </strong><?php echo ($IsEdit) ? $edit_arr['Person']['Country_Name'] : '' ?></div>
                                            </div>
                                        </div>

                                    </div>
                                </div>
                            </div>
                            <div class="right-div col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                <div class="sm-m-t-20">
                                    <h4><?php print CommonLanguage::getMessage('consumption'); ?> #
                                        <?php
                                        echo $IsEdit ? $edit_arr['Main']['ID'] : '--';
                                        ?></h4>
                                </div>
                                <div  class="form-group " >
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="PurchaseInvoiceDate" name="PurchaseInvoiceDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Date'] : $today); ?>" />
                                    <!--<span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>-->
                                </div>
                                <div  id="depot" class="form-group " >
                                    <!--<div class="col-md-12">-->
                                    <label><?php print CommonLanguage::getMessage('Depot'); ?></label>
                                    <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                    <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" 
                                           data-old="<?php echo ($IsEdit) ? $edit_arr['Main']['depot_id'] : ''; ?>" 
                                           value="<?= ($IsEdit) ? $edit_arr['Main']['depot_id'] : (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" 
                                           data-select-name='<?= json_encode(($IsEdit ) ? $all_depots[$edit_arr['Main']['depot_id']]['Depot_Name'] : (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name'])) ?>' />
                                </div>
                                <div style="" class="form-group">
                                    <label><?php print CommonLanguage::getMessage('salesman'); ?></label>
                                    <input  id="PIC_ID" name="PIC_ID" class="full-width PIC_ID" type="hidden" value="<?= ($IsEdit && !empty($edit_arr['Main']['Sales_ID'])) ? $edit_arr['Main']['Sales_ID'] : '' ?>" data-select-name='<?= ($IsEdit && !empty($edit_arr['Main']['Employee_Name'])) ? $edit_arr['Main']['Employee_Name'] : ''; ?>' />
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table " id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"style="width:3%"></th>
                                    <th class="text-center <?php echo (in_array(0, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center <?php echo (in_array(7, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('customer_code'); ?></th>
                                    <th class="text-center <?php echo (in_array(1, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:20%"><?php print CommonLanguage::getMessage('product_name'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?>" style="width:6%"><?php print CommonLanguage::getMessage('Expiry_Date'); ?></th>
                                    <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                    <th class="text-center <?php echo (in_array(2, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('UOM'); ?></th>

                                    <th class="text-center <?php echo (in_array(5, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('lot'); ?></th>
                                    <th class="text-center <?php echo (in_array(6, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('serial'); ?></th>

                                    <th class="text-center <?php echo (in_array(4, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:20%"><?php print CommonLanguage::getMessage('description'); ?></th>

                                    <th class="text-center <?php echo (in_array(3, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('Depot'); ?></th>
                                    <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                        <th class="text-center"style="width:5%"></th>
                                        <th class="text-center"style="width:10%"></th>
                                    <?php } ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit) {
                                    $data_array = $edit_arr['Details'];
                                    if (!empty($data_array)) {
                                        foreach ($data_array as $item) {
                                            $uoms = explode('/', $item['Product_UOM']);
                                            //                                                                                                                                die(print_r($uoms));
                                            ?>

                                            <tr data-is-lot="<?php echo $item['is_lot'] ?>" data-is-serial="<?php echo $item['is_serial'] ?>" data-conv="<?php echo $item['uom_con'] ?>" data-qty="<?php echo ($item['depot_qty'] + $edit_arr['item_loc'][$item['product_id']][$item['depot_id']]) ?>"
                                                data-id="<?php echo $item['product_id'] ?>"
                                                data-prod-status ="<?php echo $item['Status_ID'] ?>" 
                                                data-expiry="<?php echo $item['is_expiry']; ?>"
                                                data-entry ="<?php echo $IsEdit ? $item['entry_id'] : '' ?>"
                                                data-is-service ="<?php echo $item['is_service'] ?>"
                                                data-depot-val="<?php echo $item['depot_id'] ?>">
                                                <td>  <span class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                                <td class="<?php echo (in_array(0, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan " value = "<?php echo $item['Bar_Code'] ?>" ></td>
                                                <td class="<?php echo (in_array(7, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete person_code  " ></td>
                                                <td class="<?php echo (in_array(1, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item['Name'] ?>" >
                                                    <span class="Hint">
                                                        <span class="fa fa-sticky-note m-l-5 openFrame open_detailed_sold_items" 
                                                              data-src="Inventory/DetailedInvoiceProductReport?is_pop=1&product_id=<?php echo $item['product_id'] ?>&product_name=<?php echo $item['Name'] ?>&customer_id=<?php echo $edit_arr['Main']['Customer_ID'] ?>&customer_name=<?php echo $edit_arr['Person']['Name'] ?>" 
                                                              data-main-url="Inventory/DetailedInvoiceProductReport?is_pop=1&product_id=<?php echo $item['product_id'] ?>&product_name=<?php echo $item['Name'] ?>" style="color:#6c5ab3;cursor:pointer;float:right;"></span>
                                                        <span class="fa fa-eye m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=<?php echo $item['product_id'] ?>&product_name=<?php echo $item['Name'] ?>" style="color:#6c5ab3;cursor:pointer;float:right;"></span>
                                                        <span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/<?php echo $item['product_id'] ?>?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span></span></td>
                                                <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?> "><input  name="expiry_date"  class="full-width expiry_date <?php echo $item['is_expiry'] == 1 ? '' : 'hidden'; ?>" value="<?php echo $item['is_expiry'] == 1 ? $item['expiry_date'] : ''; ?>" data-select-name="<?php echo $item['is_expiry'] == 1 ? $item['expiry_date'] : ''; ?>" type="hidden" /></td>
                                                <td><input type="text" class="form-control Quantity isnumber" value = "<?php echo $item['item_quantity_current'] ?>" ><span class="Hint"><?php echo ($IsEdit ? ($item['depot_qty'] + $edit_arr['item_loc'][$item['product_id']][$item['depot_id']]) : $item['depot_qty']) . ' in stock' ?></span></td>
                                                <td class="<?php echo (in_array(2, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>" >
                                                    <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2" >
                                                        <?php for ($i = 0; $i < count($uoms); $i++) { ?>
                                                            <option value="<?php echo $uoms[$i]; ?>" <?php echo $uoms[$i] == $item['uom_id'] ? 'selected' : '' ?>><?php echo $all_uom[$uoms[$i]]['UOM_Name']; ?></option>
                                                        <?php } ?>
                                                    </select>
                                                </td>
                                                <td class="<?php echo (in_array(5, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <input type="hidden" class="full-width lot_nb hidden" value = "<?php echo $item['lot_nb'] ?>" data-select-name="<?php echo $item['lot_nb']; ?>">
                                                </td>
                                                <td class="<?php echo (in_array(6, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <input type="hidden" class="full-width serial_nb hidden" value = "<?php echo $item['serial_nb'] ?>"  data-select-name="<?php echo $item['serial_nb']; ?>">
                                                </td>

                                                <td class="<?php echo (in_array(4, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note" value = "<?php echo $item['product_description'] ?>"></td>

                                                <td class="<?php echo (in_array(3, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_depot_id" class="full-width" value="<?php echo (!empty($item['depot_id']) && $item['depot_id'] != $edit_arr['Main']['depot_id']) ? $item['depot_id'] : ''; ?>" data-select-name="<?php echo (!empty($item['depot_id']) && $item['depot_id'] != $edit_arr['Main']['depot_id']) ? $item['Depot_Name'] : ''; ?>" /></td>

                                                <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                                    <td class="tags"><i class="fa fa-tag fa-2x"></i></td>
                                                    <td class="tag-main-td">
                                                        <div class=" bootstrap-tagsinput">
                                                            <?php
                                                            if (!empty($item['criteria'])) {
                                                                foreach ($item['criteria'] as $criteria) {
                                                                    ?>
                                                                    <span class="tag label label-info mylabel" data-content="<?php echo $criteria['criteria_detail_name'] ?>" 
                                                                          data-criteria-id="<?php echo $criteria['criteria_id'] ?>" data-note="<?php echo $criteria['criteria_note'] ?>" 
                                                                          data-entry="<?php echo $criteria['criteria_detail_id'] ?>">
                                                                        <?php echo $criteria['criteria_detail_name'] ?><span data-role="remove"></span></span>
                                                                    <?php
                                                                }
                                                            } else {
                                                                echo'No Tags';
                                                            }
                                                            ?>
                                                        </div>
                                                    </td>

                                                <?php } ?>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>
                                    <tr data-conv="1">
                                        <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                        <td class="<?php echo (in_array(0, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan "></td>
                                        <td class="<?php echo (in_array(7, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete person_code  " ></td>
                                        <td><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?> "><input  name="expiry_date"  class="full-width expiry_date hidden" type="hidden"/></td>

                                        <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                        <td>
                                            <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                <?php foreach ($all_uom as $uom): ?>
                                                    <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>

                                        <td class="<?php echo (in_array(5, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="hidden" class="full-width lot_nb hidden" value = ""></td>
                                        <td class="<?php echo (in_array(6, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="hidden" class="full-width serial_nb hidden" value = "">
                                        </td>


                                        <td class="<?php echo (in_array(4, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note" ></td>
                                        <td class="<?php echo (in_array(3, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_depot_id" class="full-width"/></td>

                                        <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                            <td class="tags"><i class="fa fa-tag  fa-2x"></i></td>
                                            <td class="tag-main-td"><div class=" bootstrap-tagsinput"> No Tags </div></td>
                                        <?php } ?>
                                    </tr>
                                <?php } else {
                                    ?>
                                    <tr data-conv="1">
                                        <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                        <td class="<?php echo (in_array(0, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan "></td>
                                        <td class="<?php echo (in_array(7, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete person_code  " ></td>
                                        <td class="<?php echo (in_array(1, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?> "><input  name="expiry_date"  class="full-width expiry_date hidden" type="hidden"/></td>
                                        <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                        <td>
                                            <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                <?php foreach ($all_uom as $uom): ?>
                                                    <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>

                                        <td class="<?php echo (in_array(5, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="hidden" class="full-width lot_nb hidden" value = "">
                                        </td>
                                        <td class="<?php echo (in_array(6, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="hidden" class="full-width serial_nb hidden" value = "">
                                        </td>


                                        <td class="<?php echo (in_array(4, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note"></td>

                                        <td class="<?php echo (in_array(3, $consumption_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_depot_id" class="full-width"/></td>

                                        <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                            <td class="tags"><i class="fa fa-tag  fa-2x"></i></td>
                                            <td class="tag-main-td"><div class=" bootstrap-tagsinput"> No Tags </div></td>
                                        <?php } ?>
    <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <button class=" btn btn-primary btn-cons m-b-10 pull-right disabled"  id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>

                    </div>
                    <hr>
                    <div>
                        <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Legal_Name']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Province']; ?> <?php echo $org_details[0]['Organization_Country']; ?> - <?php echo $org_details[0]['Organization_City']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right">CR: <?php echo $org_details[0]['Organization_Commercial_Registry']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Phone'); ?>: <?php echo $org_details[0]['Organization_Phone']; ?></span>
                        <span class="m-l-40 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Email'); ?>: <?php echo $org_details[0]['Organization_Email']; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>


<div class="modal fade" id="items-modal"  role="dialog" aria-labelledby="mySmallModalLabel" 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>
                <h4 class="modal-title text-center"></h4>
            </div>
            <div class="modal-body form-group">
                <div id="items-alert"></div>
                <div class="row m-b-10">
                    <div class="col-md-12">
                        <div  class="col-md-3 ">
                            <label><?php print CommonLanguage::getMessage('family'); ?></label>
                            <input id="family_filter"  type="hidden" class=" full-width"  />
                        </div>
                        <div  class="col-md-3 ">
                            <label><?php print CommonLanguage::getMessage('Category'); ?></label>
                            <input id="category_filter"  type="hidden" class="full-width"  />
                        </div>

                        <div  class="col-md-3">
                            <label><?php print CommonLanguage::getMessage('Name'); ?></label>
                            <input id="name_filter" type="text" class="form-control" />
                        </div>
                        <div  class="col-md-3 m-t-25">
                            <button id="generate_items" class="btn btn-primary"><?php echo CommonLanguage::getMessage('generate') ?></button>
                        </div>
                    </div>
                </div>
                <div class="row m-b-10">
                    <div class="col-md-12">
                        <div  class="col-md-3 ">
                            <label><?php print CommonLanguage::getMessage('price'); ?></label>
                            <input id="fill_price"  type="number" step="any" min="0" class=" full-width form-control"  />
                        </div>

                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="">
                            <table class="table table-hover demo-table-search full-width table-striped" id="items_table" >
                                <thead>
                                    <tr>
                                        <th class="text-center" style="width:5%" ><?php echo CommonLanguage::getMessage('Code'); ?></th>
                                        <th class="text-center" style="width:5%" ><?php echo CommonLanguage::getMessage('Name'); ?></th>
                                        <th class="text-center" style="width:5%" ><?php echo CommonLanguage::getMessage('UOM'); ?></th>
                                        <th class="text-center" style="width:5%" ><?php echo CommonLanguage::getMessage('Quantity'); ?></th>
                                        <th class="text-center" style="width:5%" ><?php echo CommonLanguage::getMessage('Price'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>

                            </table>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="col-md-10 ">
                            <div id="limit_alert">

                            </div>
                        </div>
                        <div class="col-md-2 pull-right">
                            <button id="fill_items" class="btn btn-primary  full-width"><?php echo CommonLanguage::getMessage('proceed') ?></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="tagsModal" data-backdrop="static" data-id="" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <div class="row">
                    <h4 class="text-center"><i class="fa fa-tags"></i> <?php print CommonLanguage::getMessage('criteria') ?></h4>
                </div>
            </div>
            <div class="modal-body">
                <?php echo Forms::AlertDiv('tag_Alert'); ?>
                <div class="row criteria-detail-div">      
                </div>
            </div>
            <div class="modal-footer">
                <div class="col-md-12 row ">
                    <button id="cancelTag" type="submit" data-dismiss="modal" class="btn btn-danger btn-cons"><i class="fa fa-times"></i> <?php print CommonLanguage::getMessage('Close') ?></button>
                    <button id="addTag" type="submit" class="btn bg-complete-light btn-cons"><i class="fa fa-check"></i> <?php print CommonLanguage::getMessage('Save') ?></button>
                </div>
            </div>
            <?php echo Forms::ModalLoader('Criteria_Loader'); ?>
        </div>
    </div>
</div>
<select required id="Select_UOM" name="Select_UOM"  class="full-width Select_UOM hidden" data-init-plugin="select2">
    <?php foreach ($all_uom as $uom): ?>
        <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
    <?php endforeach; ?>
</select>


<script>
    var CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
            EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email')); ?>,
            RequiredField = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
            AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
            CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country')); ?>,
            FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            depot_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_depot_first')); ?>,
            customer_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_customer_first')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            have_not_saved = <?php echo json_encode(CommonLanguage::getMessage('have_not_saved')); ?>,
            limit_alert = <?php echo json_encode(CommonLanguage::getMessage('limit_alert')); ?>,
            empty_items_alert = <?php echo json_encode(CommonLanguage::getMessage('empty_items_alert')); ?>,
            negative_sales = <?php echo json_encode(smc_session()['default_setting']['negative_sales']); ?>,
            display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : 0,
            loc_inv_data = IsEditMode ? <?php echo json_encode(!empty($edit_arr['item_loc']) ? $edit_arr['item_loc'] : array()) ?> : [];
    activate_expiry_date = <?php echo json_encode(smc_session()['default_setting']['activate_expiry_date']); ?>,
            uom_arr = <?php echo json_encode($all_uom); ?>;
    var inv_nb = <?php echo json_encode(CommonLanguage::getMessage('consumption_nb')); ?>;
    var max_criteria_column = 5;
    var CheckSubmit = true,
            has_ledger_perm = <?php echo $permissions->hasPermission('ledger') ? 'true' : 'false'; ?>,
            has_stock_trans_perm = <?php echo json_encode($permissions->hasPermission('stock_transactions')); ?>,
            has_det_sales_rep_perm = <?php echo json_encode($permissions->hasPermission($is_actual ? 'detailed_sold_items' : 'act_detailed_sold_items')); ?>,
            has_edit_prod_perm = <?php echo json_encode($permissions->hasPermission('EditProduct')); ?>,
            activate_lot = <?php echo json_encode((in_array(5, $consumption_inv_fields_hide) && smc_session()['default_setting']['activate_product_lot_nb'] == 1) ? 0 : 1); ?>,
            activate_serial = <?php echo json_encode((in_array(6, $consumption_inv_fields_hide) && smc_session()['default_setting']['activate_product_serial_nb'] == 1) ? 0 : 1); ?>,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>;

    $(window).ready(function (e) {
        $(window).scannerDetection({
            focusInputClass: 'input-barcode-scan', minLength: default_barcode_length
        });
        $(window).bind('scannerDetectionComplete', 'input.CODE', function (e, data) {
            ID = data.string;
            var parent = $(data.my_event.target).parents('tr')
            searchScannedItem(ID, parent);
        }).bind('scannerDetectionError', function (e, data) {
        }).bind('scannerDetectionReceive', function (e, data) {
        });
    })
    $(function () {
        build_select2($("#shipping_company_id"), "xhr/CommonSearch?col_name=shipping_company_name&col_id=shipping_company_id&table=tbl_shipping_company");
        build_select2($("input[name=PIC_ID]"), "xhr/employeeSearch?customer_id=" + $(".search_supplier").val())


        $("#search_supplier").on("change", function () {
            if ($(this).val() && $(this).select2("data")['selected_emp'] == 1)
                $("input[name=PIC_ID]").val($(this).select2("data")['emp_id']).attr("data-select-name", $(this).select2("data")['emp_name']).trigger("change")
            else
                $("input[name=PIC_ID]").val('').attr("data-select-name", '')

            build_select2($("input[name=PIC_ID]"), "xhr/employeeSearch?customer_id=" + $("#search_supplier").val())

        });

        build_select2($("#search_supplier"), "xhr/customerSearch?auto_salesman=1" + (IsEditMode ? "&is_edited=" + $(".search_supplier").val() : "?Status_ID=1"))

        build_select2($("input[name=current_depot_id]"), "xhr/depotSearch")
        build_select2($(".Depot_Loc"), "xhr/depotSearch", 0, 'diff_class')

        build_select2($("#family_filter"), "xhr/CommonSearch?col_name=family_name&col_id=family_id&table=tbl_inventory_family");
        build_select2($("#category_filter"), "xhr/CommonSearch?col_name=Cat_Name&col_id=Cat_ID&table=tbl_product_cat");


        $("#InventoryPurchaseTable tbody").delegate("> tr input:not(.AutoComplete,.ttc_price )", "keyup", function (e) {

            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
            $("tr", Parent).each(function (e) {
                if ($("tr", Parent).length > 1) {
                    var IsEmpty = true;
                    $(this).find("input").each(function () {
                        if ($(this).val() != "")
                            IsEmpty = false;
                    })
                    if (IsEmpty == true) {
                        if ($(this).index() <= $("#InventoryPurchaseTable tbody tr").length - 2) {
                            me.parents("tr").prev().find(".Disc").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input", Parent).each(function (e) {
                if ($(this).val() != "")
                    IsLastOneEmpty = false;
            })
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                Parent.append(ClonedRow);
                fix_cloned_row(ClonedRow)

                //                $(".deleteRowRequest").removeClass("hidden")
                //ClonedSelect.find('select.UOM_ID option:selected').removeAttr('selected');
                //ClonedSelect.find('select.UOM_ID option:first').attr('selected','selected');
                //ClonedSelect.find('select.UOM_ID').trigger('change');
                /* ClonedRow HERE | Reset The select tag here hahah */
//                UpdateTable()
                UpdateSubmitButtonStatus()
            }
        })


        $("#InventoryPurchaseTable ").on("click", ".deleteRowRequest", function () {//to delete a row
            var numItems = $('#InventoryPurchaseTable tr').length; //number of rows
            if (numItems > 2) {//only if number of rows is more than one row remove the deleted row
                $(this).parents("tr").remove()
            }
        })
        $("#InventoryPurchaseTable").on("change", "input[name=current_depot_id]", function () {
            var me = $(this).parents('tr');
            var current_depot = $(this).val() != '' ? $(this).val() : $("#Depot_Loc").val();
            $(this).parents('tr').attr("data-depot-val", current_depot)
            var item_arr = {items: [me.attr("data-id")], depot_id: current_depot}
            $.ajax({
                url: "InventoryAjax/ReturnQtyPerDepot",
                data: item_arr,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        $.each(Data, function (index, value) {
                            var tr_conv = parseFloat(me.attr("data-conv"));
                            var stock_qty = parseFloat(value['qty']) || 0;
                            if (IsEditMode && value['Product_ID'] in loc_inv_data) {
                                if (item_arr.depot_id in loc_inv_data[value['Product_ID']])
                                    stock_qty += parseFloat(loc_inv_data[value['Product_ID']][item_arr.depot_id]) || 0;
                            }
                            var qty_hint = AddCommas(parseFloat(stock_qty / tr_conv).toFixed(3)) + " in stock";
                            me.find(".Quantity").next().text(qty_hint).attr("title", qty_hint)
                            me.find("input.ProductName").next().text(value['loc'])
                            me.attr("data-qty", (stock_qty / tr_conv))
                        })
                        UpdateSubmitButtonStatus()

                    }
                }
            })
        })


        $("#search_supplier").on("change", function () {
            $("#SupplierInfoContent").removeClass('hidden')

            if ($("#Depot_Loc").val() == '') {
                $("#choose_items").attr("disabled", "disabled")
            } else {
                $("#choose_items").removeAttr("disabled")
            }
            var Data = {
                id: $(this).val(),
                mode: true
            }

            $.ajax({
                url: "InventoryAjax/addPurchaseAjax",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        $("#SupplierInfoContent").empty();
                        var Content = "";
                        Content += "<strong><span class='Name' id='Supplier_Name' data-account-name='" + Data[0]['Account_Name'] + "' data-account-id='" + Data[0]['Account_ID'] + "' data-account-code='" + Data[0]['Account_Code'] + "' data-id='" + Data[0]['Customer_Name'] + "'>" + Data[0]['Customer_Name'] + "</span>" + (has_ledger_perm ? "<span class='fa fa-eye m-l-5 openFrame' data-src='ACC/ledger?is_pop=1/" + Data[0]['Account_Code'] + "' style='color:#8a7dbe;cursor:pointer'></span>" : "") + "</strong>";
                        Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Customer_Company'] + "</span></div>";
                        Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Customer_Email'] + "</span></div>";
                        Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Customer_Phone'] + "</span></div>";
                        Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Customer_Address'] + "</span></div>";
                        Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";

                        $("#SupplierInfoContent").append(Content)
                        $("#Supplier_ID-error").remove()
                        $("#Supplier_ID").removeClass("error").val(Data[0]['Customer_ID']);
                        $("#InvoiceDiscountInput").val(Data[0]['Customer_Discount']);
                        $("#card_tax").attr("data-tax", Data[0]['tax_amount'])

                        if (has_det_sales_rep_perm)
                            update_open_frame_sold_items();

                    }
                }
            })

        });

        $("#Depot_Loc").on("change", function () {
            //alert($(this).val())
            var Content = "";

            if ($(this).attr("id") == 'Depot_Loc') {
                var item_arr = {items: [], depot_id: $("#Depot_Loc").val()}
                $("#InventoryPurchaseTable tbody tr").each(function (e) {
                    if ($(this).attr("data-id") != 0 && $(this).find("input[name=current_depot_id]").val() == "") {
                        $(this).attr("data-depot-val", $("#Depot_Loc").val())
                        item_arr.items.push($(this).attr("data-id"))
                    }
                })
                $.ajax({
                    url: "InventoryAjax/ReturnQtyPerDepot",
                    data: item_arr,
                    dataType: 'json',
                    complete: function (v1, v2) {
                        if (v2 == "success") {
                            var Data = (v1.responseJSON);
                            $.each(Data, function (index, value) {
                                var me = $("#InventoryPurchaseTable tbody tr[data-id='" + value['Product_ID'] + "']");
                                me.each(function () {
                                    if ($(this).find("input[name=current_depot_id]").val() == "") {
                                        var tr_conv = parseFloat($(this).attr("data-conv"));
                                        var stock_qty = parseFloat(value['qty']) || 0;
                                        if (IsEditMode && value['Product_ID'] in loc_inv_data) {
                                            if (item_arr.depot_id in loc_inv_data[value['Product_ID']])
                                                stock_qty += parseFloat(loc_inv_data[value['Product_ID']][item_arr.depot_id]) || 0;
                                        }
                                        var qty_hint = AddCommas(parseFloat(stock_qty / tr_conv).toFixed(3)) + " in stock";
                                        $(this).find(".Quantity").next().text(qty_hint).attr("title", qty_hint)
                                        $(this).find("input.ProductName").next().text(value['loc'])
                                        me.attr("data-qty", (stock_qty / tr_conv))

                                    }
                                });
                                UpdateSubmitButtonStatus()
                            })
                        }
                    }
                })
            }
        })


        if (!$("#InventoryPurchaseTable").hasClass('hideme')) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                EnableAutoComplete($(".AutoComplete.CODE", $(this)));
                EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
                EnableAutoComplete($(".AutoComplete.person_code", $(this)));
                if ($(this).attr('data-expiry') == 1 && activate_expiry_date == 1) {
                    build_select2($("input.expiry_date", $(this)), function (el) {
                        var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                        return 'xhr/get_product_expiry?product_id=' + this.parents("tr").attr('data-id') + '&depot=' + depot_id;
                    }, '', 'expiry_width');
                }
                if ($(this).attr('data-is-lot') == 1 && activate_lot == 1) {
                    build_select2($("input.lot_nb", $(this)), function (el) {
                        var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                        return 'xhr/get_product_lot?product_id=' + this.parents("tr").attr('data-id') + '&depot=' + depot_id;
                    }, '', 'expiry_width');
                    $("input.lot_nb", $(this)).removeClass("hidden");
                } else
                    $("input.lot_nb", $(this)).addClass("hidden");
                //
                if ($(this).attr('data-is-serial') == 1 && activate_serial == 1) {
                    build_select2($("input.serial_nb", $(this)), function (el) {
                        var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                        return 'xhr/get_product_serial?product_id=' + this.parents("tr").attr('data-id') + '&depot=' + depot_id;
                    }, '', 'expiry_width');
                    $("input.serial_nb", $(this)).removeClass("hidden");
                } else
                    $("input.serial_nb", $(this)).addClass("hidden");
            });
        } else {
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.CODE"));
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.ProductName"));
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.person_code"));
        }
        build_select2($("input[name=current_depot_id]"), "xhr/depotSearch")

        $("#PurchaseInvoiceDate").datepicker({autoclose: true});

        $("#InventoryPurchaseTable tbody").delegate("> tr input", "keydown", function (e) {
            CheckSubmit = false;
            var me = $(this)
            if (e.which == 8) {
                if (me.val() == "" && !me.hasClass("CODE")) {
                    me.parents("td").prev().find("input").focus()
                }
            }
        });
        $("#InventoryPurchaseTable").on("change", "select.UOM_ID", function () {
            var me = $(this).parents("tr");
            var depot_id = me.find('input[name=current_depot_id]').val() != '' ? me.find('input[name=current_depot_id]').val() : $("#Depot_Loc").val();
            var UOMData = {pid: $(this).parents("tr").attr("data-id"),
                uid: $(this).val(), depot_id: depot_id, class_id: '', currency_id: local_currency};
            $.ajax({
                url: "InventoryAjax/ReturnProductUOMPriceCon",
                data: UOMData,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        me.attr('data-conv', v1.responseJSON['conversion_amount'])
                        var stock_qty = (parseFloat(v1.responseJSON['qty']) || 0) * (parseFloat(v1.responseJSON['conversion_amount']) || 0);
                        //                        console.log('prod: ' + UOMData.pid)
                        //                        console.log('depot: ' + depot_id)
                        if (IsEditMode && UOMData.pid in loc_inv_data) {
                            if (depot_id in loc_inv_data[UOMData.pid])
                                stock_qty += parseFloat(loc_inv_data[UOMData.pid][depot_id]) || 0;
                        }
                        stock_qty = stock_qty / v1.responseJSON['conversion_amount'];
                        var qty_hint = AddCommas(parseFloat(stock_qty).toFixed(3)) + " in stock";
                        me.find("input.Quantity").next().text(qty_hint).attr("qty_hint")
                        me.attr("data-qty", stock_qty)
                    }
                }
            })


        })
        $("#InvoiceForm").validate({
            ignore: ".ignore",
            rules: {
                PurchaseInvoiceDate: {required: true, date: true},
                PurchaseInvoiceDueDate: {date: true}
            }
        })
        $("#InvoiceSubmitButton").on("click", function () {
            ApplyPostMethod()
        });
        UpdateSubmitButtonStatus()



        $("#PIC_ID").on("change", function () {
            $.ajax({
                url: "InventoryAjax/get_salesman_depot",
                data: {salesman_id: $(this).val()},
                dataType: 'json',
                complete: function (v1, v2) {

                    if (v2 == "success") {
                        var data = v1.responseJSON;
                        if ('depot_id' in data > 0) {
                            $("#Depot_Loc").val(data['depot_id']).attr("data-select-name", data['Depot_Name']).trigger("change")
                        }
                    }
                }
            })
        })
        $("#InventoryPurchaseTable").on("click", ".tags", function () {
            var tr = $(this).parents("tr");
            if (tr.attr("data-id") == undefined)
                return;
            getProductCriteria(tr.attr("data-id"), getCurrentTags(tr), tr)
            $("#tagsModal").attr("data-id", tr.index())
        })
        $(".criteria-detail-div").on("click", '.removeTags', function () {
            $(this).parents("tr").find("input:checked").removeAttr("checked")
            removeTags()
        });
        $(".criteria-detail-div").on("click", '#TagsTable input', function () {
            removeTags()
        });
        $(".criteria-detail-div").on("click", '#TagsTable input[type=checkbox]', function () {
            var max_count = $(this).attr('max-count'),
                    criteria_id = $(this).attr("data-criteria-id"),
                    current_selected_length = $('td.tagSelected input[data-criteria-id=' + criteria_id + ']').length

            if (current_selected_length > parseInt(max_count)) {

                $(this).parents('td.inputDiv').removeClass('tagSelected');
                this.checked = false
            }
        })
        $("#addTag").on("click", function () {
            updateTags()
        });
        $("#InventoryPurchaseTable").on("click", "[data-role=remove]", function () {
            var item = $(this).parents("tr").attr("data-ref"), Parent = $(this).parents("tr");
            $(this).parents("span.tag").remove()
            if ($("span.tag", Parent).length == 0) {
                $("tr:eq(" + item + ")").find('div.bootstrap-tagsinput').html('No Tags')
            }
        })
    });
    function getCurrentTags(currentTR) {
        var tags = [], tag_notes = [];
        $("td.tag-main-td .mylabel", currentTR).each(function () {
            tags.push($(this).attr("data-entry"));
            if ($(this).attr("data-note") != undefined) {
                tag_notes[$(this).attr("data-criteria-id")] = $(this).attr("data-note")
            }
        });
        //        console.log(tag_notes)
        return [tags, tag_notes];
    }
    function getProductCriteria(product_id, criteria_data, SelectedTR) {
        current_criteria = criteria_data[0];
        current_criteria_notes = criteria_data[1];
        //        console.log(criteria_data)
        $("#tagsModal").modal('show')
        $("#tagsModal .criteria-detail-div").empty();
        CommonViewById('RestaurantAjax/getProductCriteria', {Product_ID: product_id, currency_id: local_currency, is_all: 1, category_id: SelectedTR.attr('data-category-id')}, '#Criteria_Loader', function (Response) {
            if (Object.keys(Response).length > 0) {
                var tagTable = ' <table class="col-md-12 table table-bordered table-responsive" id="TagsTable">',
                        product_criteria = '', general_criteria = '';
                //                console.log(Response)
                $.each(Response, function (key1, value) {
                    var all_details = Response[key1]['detail'], content = '', type = Response[key1]['criteria_type'] == 2 ? 'radio' : 'checkbox',
                            up_to_condition = 'Choose ' + (Response[key1]['criteria_type'] == 2 ? '1' : ' UP to ' + Response[key1]['criteria_max_count'] + ' ');
                    var rows_nb = Math.ceil(all_details.length / max_criteria_column);
                    content += '<tr max-count="' + Response[key1]['criteria_max_count'] + '" data-type="' + type + '">' +
                            '<td class="tag_note_td" rowspan="' + rows_nb + '" style="width:15%;"><textarea class="tag-note form-control" rows="1">' + (current_criteria_notes[Response[key1]['criteria_id']] || '') + '</textarea></td>' +
                            '<th class="tag_note_cond" rowspan="' + rows_nb + '"  style="width:12%"><div><span>' + up_to_condition + '</span></div></th>' +
                            '<th rowspan="' + rows_nb + '" class=" ' + (Response[key1]['product_id'] == 0 ? 'btn-primary' : 'btn-info') + ' removeTags">' +
                            '<div><i class="fa fa-times"></i> <span>' + Response[key1]['criteria_name'] + '</span></div> </th>';
                    var row_col_index = 0;

                    $.each(all_details, function (key2, value) {
                        if (row_col_index == max_criteria_column) {
                            content += '</tr><tr>';
                            row_col_index = 0;
                        }
                        row_col_index++;
                        content += '<td style="vertical-align:middle;text-align:center;" class="inputDiv ' + ($.inArray(all_details[key2]['criteria_detail_id'], current_criteria) !== -1 ? 'tagSelected' : '') + '">' +
                                '<div class="btn btn-style inputDiv" style="width:100%">' + all_details[key2]['criteria_detail_name'] +
                                '<input type="' + type + '" max-count="' + Response[key1]['criteria_max_count'] + '" data-criteria-id="' + Response[key1]['criteria_id'] + '" data-entry="' + all_details[key2]['criteria_detail_id'] + '" tag-price="' + all_details[key2]['criteria_detail_price'] + '" tag-name="' + all_details[key2]['criteria_detail_name'] +
                                '" data-ref ="" data-tag = "" ' + ($.inArray(all_details[key2]['criteria_detail_id'], current_criteria) !== -1 ? 'checked' : '') + ' value="' + all_details[key2]['criteria_detail_id'] + '" name="' + $.trim(Response[key1]['criteria_name']) + '" id="" class="form-control multiple-checkbox"></div>' +
                                '</td>';
                    });
                    if (row_col_index < max_criteria_column)
                        content += '<td colspan="' + (max_criteria_column - row_col_index) + '">&nbsp;</td>';
                    content += '</tr>';
                    if (Response[key1]['product_id'] == 0)
                        general_criteria += content;
                    else
                        product_criteria += content;
                });
                tagTable += product_criteria + general_criteria + '</table>';
                $('#tagsModal .criteria-detail-div').append($(tagTable))
                $.each(current_criteria_notes, function (note_id, entry_id) {
                    if (entry_id != undefined) {
                        $("input[data-entry=" + note_id + "]").closest(".tag-note").val(entry_id)
                    }
                    //                        console.log(note_id + '==' + entry_id)
                })
                $('#addTag').attr('disabled', false)
            } else {
                $("#tagsModal .criteria-detail-div").append(' <div class="col-md-12 m-t-10 alert alert-warning">No criteria related to this item</div>');
                $('#addTag').attr('disabled', true)
            }
        });
    }
    function removeTags() {
        $("#TagsTable td,#TagsTable button").removeClass("tagSelected")
        $("#TagsTable tr input:checked").parents('td').addClass("tagSelected")
        $("#TagsTable tr input:checked").parents('button').addClass("tagSelected")
        //        UpdateTable($("#OrderTable > tbody:last"))

    }
    function updateTags() {
        var item = $("#tagsModal").attr("data-id");
        var tr = $("#InventoryPurchaseTable tbody tr:eq(" + item + ")");
        $("#InventoryPurchaseTable tbody tr:eq(" + item + ") div.bootstrap-tagsinput").empty();
        var total_added_tag_vat = 0, row_title = '';
        $("#tagsModal .criteria-detail-div input:checked").each(function () {
            var tag_name = $(this).attr("tag-name"),
                    entry = $(this).val(),
                    criteria_id = $(this).attr("data-criteria-id"),
                    note = $(this).parents("tr").find(".tag-note").val();
            row_title += tag_name + '\n';
            var label_tag = '<span class="tag label label-info mylabel" data-content="' + tag_name + '" data-criteria-id="' + criteria_id + '" data-note="' + note + '"  data-entry="' + entry + '">' + tag_name + '<span data-role="remove"></span></span>';
            $("#InventoryPurchaseTable tbody tr:eq(" + item + ") div.bootstrap-tagsinput").append($(label_tag));
        });
        $("#InventoryPurchaseTable tbody tr:eq(" + item + ")").attr("title", row_title);
        $("#tagsModal").modal("hide")
    }
    function searchScannedItem(barcode, TR) {
        var get_parameters = 'Status_ID=1&barcode=' + barcode + '&depot_id=' + ($('input[name=current_depot_id]', TR).val() ? $('input[name=current_depot_id]', TR).val() : $('#Depot_Loc').val());
        get_parameters += '&type=1&class_id=&customer_id=' + $("#search_supplier").val();

        $.ajax({
            url: "POSAjax/searchBarcodeforPOS?" + get_parameters,
            method: 'GET',
            dataType: 'json',
            complete: function (v1, v2) {
                var Data = v1.responseJSON;
                if ($.type(Data) === "object") {
                    $("select[name=UOM_ID]", TR).empty();
                    TR.attr("data-id", Data.ID)
                    TR.attr("data-qty", Data.stock_qty)
                    TR.attr("data-expiry", Data.is_expiry);
                    TR.find("input.CODE").val(Data.Bar_Code);
                    TR.find("input.ProductName").val(Data.Name)
                    TR.attr("data-is-service", Data.is_service)
                    TR.attr("data-is-lot", Data.is_lot)
                    TR.attr("data-is-serial", Data.is_serial)
                    TR.attr("data-depot-val", $("#Depot_Loc").val())
                    var units_arr = Data.Product_UOM.split("/");
                    for (var i = 0; i < units_arr.length; i++) {
                        $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == Data.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                    }
                    TR.find("select[name=UOM_ID]").select2();
                    var qty_hint = AddCommas(parseFloat(Data.stock_qty).toFixed(3)) + " in stock";
                    if (event.which != 9)
                        TR.find("input.Quantity").focus().next().text(qty_hint).attr("title", qty_hint)
                    else
                        TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                    var product_hint = '';
                    if (display_shelf_locations == 1) {
                        product_hint += Data.loc;
                    }
                    if (has_det_sales_rep_perm) {
                        product_hint += '<span class="fa fa-eye m-l-5 openFrame open_detailed_sold_items" data-src="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + Data.ID + '&product_name=' + Data.Name + '&customer_id=' + $("#search_supplier").val() + '&customer_name=' + $("#search_supplier").select2('data').text + '"  data-main-url="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + Data.ID + '&product_name=' + Data.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    if (has_stock_trans_perm) {
                        product_hint += '<span class="fa fa-note-o m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=' + Data.ID + '&product_name=' + Data.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    if (has_edit_prod_perm) {
                        product_hint += '<span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/' + Data.ID + '?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }

                    TR.find("input.ProductName").next().html(product_hint);


                    if (Data.is_expiry == 0)
                        TR.find(".expiry_date").addClass("hidden")
                    else {
                        TR.find(".expiry_date").removeClass("hidden");
                        TR.find("input.expiry_date").attr('data-select-name', '').val('')
                        build_select2(TR.find("input.expiry_date"), function (el) {
                            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                            return 'xhr/get_product_expiry?product_id=' + Data.ID + '&depot=' + depot_id;
                        }, '', 'expiry_width');
                    }
                    if (Data.is_lot == 1)
                        build_select2(TR.find("input.lot_nb"), function (el) {
                            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                            return 'xhr/get_product_lot?product_id=' + Data.ID + '&depot=' + depot_id;
                        }, '', 'expiry_width');
                    if (Data.is_serial == 1)
                        build_select2(TR.find("input.serial_nb"), function (el) {
                            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                            return 'xhr/get_product_serial?product_id=' + Data.ID + '&depot=' + depot_id;
                        }, '', 'expiry_width');

                    var qty_hint = AddCommas(parseFloat(Data.stock_qty).toFixed(3)) + " in stock";
                    TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                    return false;
                }
            }
        });
    }

    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                //autoFocus: true,  // we stop it as in barcode if scan it take the first selected before build new results
                source: function (request, response) {
                    var depot_id = $('input[name=current_depot_id]', who.parents('tr')).val() ? $('input[name=current_depot_id]', who.parents('tr')).val() : $('#Depot_Loc').val(),
                            customer_id = $("#search_supplier").val(),
                            product_id = who.parents('tr').attr('data-id'),
                            product_status_id = who.parents('tr').attr('data-prod-status'),
                            status_cond = !IsEditMode ? '&Status_ID=1' : (product_status_id == 0 ? ('&is_edited=' + product_id) : '&Status_ID=1');
                    $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : (who.hasClass("person_code") ? "3" : "2")) + "&is_sales=1&ClassID=&depot_id=" + depot_id + "&type=1&customer_id=" + customer_id + status_cond, request, function (s, status, xhr) {
                        var response_length = Object.keys(s).length;
                        if (response_length == 1) {
                            $(who).trigger({type: 'keypress', which: 13});
                        }
                        response(s);
                    });
                },
                minLength: 0,
                select: function (event, ui) {
                    var TR = $(this).parents("tr");
                    var old_prod_id = TR.attr("data-id")
                    TR.attr("data-id", ui.item.ID)

                    var stock_qty = ui.item.Quantity;
                    if (IsEditMode && ui.item.ID in loc_inv_data) {
                        if ($("#Depot_Loc").val() in loc_inv_data[ui.item.ID])
                            stock_qty += loc_inv_data[ui.item.ID][$("#Depot_Loc").val()]
                    }
                    //                        TR.attr("data-qty", ui.item.Quantity)
                    TR.attr("data-qty", stock_qty)
                    TR.attr("data-item-disc", ui.item.Product_Limit_Discount)
                    TR.attr("data-expiry", ui.item.is_expiry)
                    TR.attr("data-conv", ui.item.uom_conv)
                    TR.attr("data-is-service", ui.item.is_service)
                    TR.attr("data-is-lot", ui.item.is_lot)
                    TR.attr("data-is-serial", ui.item.is_serial)
                    TR.attr("data-depot-val", $("#Depot_Loc").val())
                    TR.find("input.expiry_date,input.lot_nb,input.serial_nb").attr('data-select-name', '').val('')
                    if (ui.item.is_expiry == 0)
                        TR.find("input.expiry_date").addClass("hidden")
                    else {
                        TR.find("input.expiry_date").removeClass("hidden");

                        build_select2(TR.find("input.expiry_date"), function (el) {
                            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                            return 'xhr/get_product_expiry?product_id=' + ui.item.ID + '&depot=' + depot_id;
                        });
                    }

                    if (ui.item.is_lot == 1 && activate_lot == 1) {
                        TR.find("input.lot_nb").removeClass("hidden");
                        build_select2(TR.find("input.lot_nb"), function (el) {
                            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                            return 'xhr/get_product_lot?product_id=' + ui.item.ID + '&depot=' + depot_id;
                        }, '', 'expiry_width');
                    } else
                        TR.find("input.lot_nb").addClass("hidden");
                    if (ui.item.is_serial == 1 && activate_serial == 1) {
                        TR.find("input.serial_nb").removeClass("hidden");
                        build_select2(TR.find("input.serial_nb"), function (el) {
                            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                            return 'xhr/get_product_serial?product_id=' + ui.item.ID + '&depot=' + depot_id;
                        }, '', 'expiry_width');

                    } else
                        TR.find("input.serial_nb").addClass("hidden");
                    TR.find("input.CODE").val(ui.item.Bar_Code)
                    TR.find("input.Disc").val(ui.item.disc)
                    TR.find("input.ProductName").val(ui.item.Name)
                    //                         if (ui.item.person_code != '')
                    TR.find("input.person_code").val(ui.item.person_code)

                    $("select[name=UOM_ID]", TR).empty();

                    var product_hint = '';
                    if (display_shelf_locations == 1) {
                        product_hint += ui.item.loc;
                    }
                    if (has_det_sales_rep_perm) {
                        product_hint += '<span class="fa fa-sticky-note m-l-5 openFrame open_detailed_sold_items" data-src="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '&customer_id=' + $("#search_supplier").val() + '&customer_name=' + ($("#search_supplier").val() ? $("#search_supplier").select2('data').text : '') + '" data-main-url="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    if (has_stock_trans_perm) {
                        product_hint += '<span class="fa fa-eye m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    if (has_edit_prod_perm) {
                        product_hint += '<span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/' + ui.item.ID + '?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    TR.find("input.ProductName").next().html(product_hint)
                    var qty_hint = AddCommas(parseFloat(stock_qty).toFixed(3)) + " in stock";
                    if (event.which != 9)
                        TR.find("input.Quantity").focus().next().text(qty_hint).attr("title", qty_hint)
                    else
                        TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)

                    TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                    var units_arr = ui.item.Product_UOM.split("/");
                    for (var i = 0; i < units_arr.length; i++) {
                        $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                    }
                    TR.find("select[name=UOM_ID]").select2();

                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width() * (this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = this.element.hasClass("CODE") ? (item.Bar_Code) : (this.element.hasClass("person_code") ? item.person_code : (item.Cat_Name + item.Name + ' - ' + item.Code));
                //                        $(this).focus().trigger({ type : 'keypress', which : 13 });
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }


    }
    function ApplyPostMethod() {
        $("#ProfitProceedModal").modal("hide")
        $("#PurchaseSuccess").attr("class", "hidden");
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                    Data = {
                        is_actual: is_actual ? 1 : 0,
                        unique_id: unique_id,
                        Customer_ID: $("#Supplier_ID").val(),
                        Customer_Name: $("#Supplier_Name").val(),
                        consumption_date: $("#PurchaseInvoiceDate").val(),
                        consumption_description: $("#consumption_description").val(),
                        Sales_ID: $("input[name=PIC_ID]").val(),
                        Depot_ID: $("input[name=Depot_Loc]").val(),
                        consumption_auto_id: ID_Edit,
                        Products: []
                    };


            var total_cost_percent = 0, is_negative_value = false;
            $("#InventoryPurchaseTable tbody tr").each(function (e) {
                var me = $(this),
                        tags = [],
                        item_qty = me.find(".Quantity").val();

                $("td.tag-main-td .mylabel", $(this)).each(function () {
                    tags.push({
                        quantity: item_qty,
                        criteria_detail_id: $(this).attr("data-entry"),
                        criteria_note: $(this).attr("data-note") || ''
                    });
                });
                if (me.find(".Quantity").val() != '' && me.find(".Quantity").val() != 0 && me.find(".ProductName").val() != '') {
                    Data.Products.push({
                        uom_id: me.find("select.UOM_ID").val(),
                        product_id: me.attr("data-id"),
                        item_quantity: me.find(".Quantity").val(),
                        product_description: me.find(".item_note").val(),
                        depot_id: me.find("input[name=current_depot_id]").val(),
                        expiry_date: me.find("input.expiry_date").val(),
                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        entry_id: me.attr("data-entry") || 0,
                        is_service: me.attr("data-is-service") || 0,
                        criteria_details: tags,
                    });

                    if (me.attr("data-id") == '0' || me.attr("data-id") == '' || me.attr("data-id") == undefined || me.find("select.UOM_ID").val() == '') {
                        me.find(".CODE").addClass("wrong")
                        me.find(".ProductName").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_expiry_date == 1 && me.attr("data-expiry") == 1 && me.find("input.expiry_date").val() == "") {
                        me.find(".expiry_date").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_lot == 1 && me.attr("data-is-lot") == 1 && me.find("input.lot_nb").select2('data') == null) {
                        me.find(".lot_nb").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_serial == 1 && me.attr("data-is-serial") == 1 && me.find("input.serial_nb").select2('data') == null) {
                        me.find(".serial_nb").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (parseFloat($("input.Quantity ", me).val()) < 0) {
                        is_negative_value = true;
                    }
                }
            })

            if (!IsValidated) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }

            if (Data.Products.length == 0) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_negative_value) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('negative_value'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            $("#PurchaseDisabler").show();
            $("#InvoiceSubmitButton").attr("disabled", "disabled");
            //            return;
            $.ajax({
                url: "InventoryAjax/submit_consumption",
                method: "POST",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {

                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[2] + '</strong>')
                            CheckSubmit = true;
                        } else {
                            if (v1.responseJSON[0] == 'expiry_error') {
                                $.each(v1.responseJSON[1], function (indx, row) {
                                    $("#InventoryPurchaseTable tbody tr[data-id=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input.expiry_date[value=" + row['expiry_date'] + "]").addClass("wrong")
                                })
                                $("#PurchaseSuccess").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) {
                                    $("#InventoryPurchaseTable tbody tr[data-id=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input.serial_nb[value=" + row['serial_nb'] + "]").addClass("wrong")
                                })
                                $("#PurchaseSuccess").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) {
                                    $("#InventoryPurchaseTable tbody tr[data-id=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input.lot_nb[value=" + row['lot_nb'] + "]").addClass("wrong")
                                })
                                $("#PurchaseSuccess").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) {
                                    $("#InventoryPurchaseTable tbody tr[data-id=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input.Quantity").addClass("wrong")
                                })
                                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_qty_exist') ?>')

                            } else {
                                $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])

                                CheckSubmit = false;
                            }
                            $("#InvoiceSubmitButton").removeAttr("disabled")
                        }
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        $("#InvoiceSubmitButton").removeAttr("disabled")
                        CheckSubmit = false;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#PurchaseDisabler").hide();
                }
            })
        } else {
            $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
            $(document.body).animate({scrollTop: 0}, 800)
        }
    }
    function UpdateSubmitButtonStatus() {
        var Rows = $("#InventoryPurchaseTable tbody tr"), DoDisable = false
        if (Rows.length > 0) {
            if (Rows.length == 1) {
                if ($.trim($("input.CODE", Rows).val()) != "" && $.trim($("input.ProductName", Rows).val()) != "" && $.trim($("input.Quantity", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }
        $(".Quantity").removeClass('wrong')
        $("#InventoryPurchaseTable tbody tr").each(function () {
            var pid = $(this).attr("data-id"),
                    depot_id = $("input[name=current_depot_id]", $(this)).val() != '' ? $("input[name=current_depot_id]", $(this)).val() : $("#Depot_Loc").val();
//                     console.log('neg'+negative_sales)        
            if (negative_sales == 0) {
                var inv_qty = 0;
                $("#InventoryPurchaseTable tbody tr[data-id=" + pid + "]").each(function () {
                    var cur_depot_id = $("input[name=current_depot_id]", $(this)).val() != '' ? $("input[name=current_depot_id]", $(this)).val() : $("#Depot_Loc").val();
                    if (cur_depot_id == depot_id)
                        inv_qty += (parseFloat($(this).find(".Quantity").val()) || 0) * (parseFloat($(this).attr("data-conv")) || 0);
                })
                var conv = (parseFloat($(this).attr("data-conv")) || 0);
                if (inv_qty > parseFloat($(this).attr('data-qty')) * conv) {
//                    console.log(inv_qty + '====' + (parseFloat($(this).attr('data-qty')) * conv))
                    $(this).find(".Quantity").addClass("wrong");
                    DoDisable = true;
                }
            }
        });

        if (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }
    $(document).ready(function () {
        window.onbeforeunload = function (e) {
            if (!CheckSubmit) {
                var message = have_not_saved, e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }
    });
    function update_open_frame_sold_items() {
        var customer_id, customer_name = '';
        if ($('#search_supplier').val()) {
            customer_id = $('#search_supplier').val();
            customer_name = $('#search_supplier').select2('data').text;
        }
        $('.open_detailed_sold_items').each(function () {
            $(this).attr('data-src', $(this).attr('data-main-url') + (customer_id != '' ? ('&customer_id=' + customer_id + '&customer_name=' + customer_name) : ''));
        });
    }
    function fix_cloned_row(ClonedRow) {
        ClonedRow.find("input").val("")
        ClonedRow.attr("data-conv", "1")
        ClonedRow.removeAttr("data-id")
        ClonedRow.attr("data-expiry", "0")
        ClonedRow.attr("data-entry", "0")
        ClonedRow.attr("data-is-service", "0")
        ClonedRow.attr("data-is-lot", "0")
        ClonedRow.attr("data-is-serial", "0")
        ClonedRow.attr("data-depot-val", "")
        EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
        EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
        EnableAutoComplete($(".AutoComplete.person_code", ClonedRow).removeClass("AutoAdded"));
        $(".Hint,.Total", ClonedRow).html("")
        ClonedRow.find(".mylabel").remove()
        ClonedRow.find('div.bootstrap-tagsinput').html('No Tags')
        //                $(".expiry_date", ClonedRow).removeClass('hidden').datepicker({autoclose: true});
        ClonedRow.removeAttr("data-prod-status")
        //                $(".Hint", ClonedRow).html("")
        $("input.ProductName,input.CODE,input.Quantity,select.UOM_ID,input[name=current_depot_id]", ClonedRow).removeAttr("disabled")
        $("input", ClonedRow).removeClass("wrong")
        $(".deleteRowRequest ", ClonedRow).removeClass("hidden")
        $(".select2-container", ClonedRow).empty().remove()
        $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2();
        ClonedRow.find("input.expiry_date,input.lot_nb,input.serial_nb").addClass('hidden')
        ClonedRow.find("input.expiry_date,input[name=current_depot_id],input.lot_nb,input.serial_nb").attr('data-select-name', '').val('')
        build_select2($("input[name=current_depot_id]", ClonedRow), "xhr/depotSearch")

        build_select2(ClonedRow.find("input.expiry_date"), function (el) {
            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
            return 'xhr/get_product_expiry?product_id=' + $(".AutoComplete.ProductName", ClonedRow).attr('data-id') + '&depot=' + depot_id;
        });
        build_select2(ClonedRow.find("input.lot_nb"), function (el) {
            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
            return 'xhr/get_product_lot?product_id=' + $(".AutoComplete.ProductName", ClonedRow).attr('data-id') + '&depot=' + depot_id;
        });
        build_select2(ClonedRow.find("input.serial_nb"), function (el) {
            var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
            return 'xhr/get_product_serial?product_id=' + $(".AutoComplete.ProductName", ClonedRow).attr('data-id') + '&depot=' + depot_id;
        });



        $(".select2-container", ClonedRow).show()
    }
</script>
