<?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 && $IsSales && !empty($edit_arr['Main']['sale_app_id']) && smc_session()['default_setting']['edit_sales_order_from_app'] == 0) { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this sales order!
        <br>
        This sales order from application.
    </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 order!
        <br>
        This order is not available.
    </div>
<?php
    die();
}
$autofill_cost = smc_session()['default_setting']['auto_fill_cost'] != '' ? explode(",", smc_session()['default_setting']['auto_fill_cost']) : [];
$autofill_zerocost = smc_session()['default_setting']['auto_fill_zero_cost'] != '' ? explode(",", smc_session()['default_setting']['auto_fill_zero_cost']) : [];

$sales_inv_fields_hide = smc_session()['default_setting']['sales_quotation_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['sales_quotation_fields_to_hide']) : [];
$purchase_inv_fields_hide = smc_session()['default_setting']['purchase_quotation_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['purchase_quotation_fields_to_hide']) : [];
//  item_driver_id
// echo "<pre>";print_r($drivers_item_list);
// foreach($drivers_item_list as $driver){
//      echo "<h1> driver_name ".$driver['driver_name']."</h1>";
// }
?>
<style type="text/css">
    .diff_class {
        width: 200px !important;
    }

    #InventoryPurchaseTable thead tr th {
        color: #555;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }

    #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 {
        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;
    }

    #InvoiceVAT {
        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;
    }

    #InventoryPurchaseTable input.wrong {
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        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;
    }

    .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;
    }

    .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;
    }

    .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">
                            <input type="hidden" name="due_date_period" id="due_date_period" value="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['due_date_period'] : ''; ?>" />
                            <input type="hidden" name="current_invoice_type" id="current_invoice_type" value="<?php echo $current_invoice_type; ?>" />

                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <div class="row " style="display:flex;">
                                    <div class="col-md-12">
                                        <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($IsSales ? 'choose_customer' : 'choose_supplier'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1" : "Inventory/ViewVendorList?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 || $is_qto || $is_revision ? $edit_arr['Main']['Person_ID'] : (''); ?>" data-select-name='<?= json_encode(($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Name'] : ""); ?>' />
                                    </div>
                                    <!--                                    <div class="Account_Code col-md-4">
<label><?php print CommonLanguage::getMessage('accounts'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
<input class=" full-width" id="Account_Code" name="Account_Code" type="hidden" value="<?= $IsEdit ? $edit_arr['Main']['Account_ID'] : smc_session()['user_accounts'][$IsSales ? 'sales_account_id' : 'purchase_account_id']; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Main']['Account_Name'] : smc_session()['user_accounts'][$IsSales ? 's_name' : 'p_name']); ?>' />
</div>-->
                                    <div class="col-md-3 <?php echo ($IsSales && $permissions->hasPermission('change_class')) ? '' : 'hidden' ?>">
                                        <label><?php echo CommonLanguage::getMessage('pricing_class'); ?></label>
                                        <input type="text" id="pricing_class" class=" full-width" value="<?php echo (($IsSales && ($IsEdit || $is_qto || $is_revision)) ? $edit_arr['Main']['Class_ID'] : smc_session()['pricing_class_id']) ?>" data-select-name="<?php echo ($IsSales && ($IsEdit || $is_qto || $is_revision)) ? $edit_arr['Main']['Class_Name'] : smc_session()['pricing_class_name'] ?>">
                                    </div>
                                    <div class="col-md-3 <?php echo ($IsSales && smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 1) ? '' : 'hidden' ?>">
                                        <label><?php echo CommonLanguage::getMessage('supplier_pricing_class'); ?></label>
                                        <input type="text" id="supplier_pricing_class" class=" full-width" value="<?php echo (($IsSales && ($IsEdit || $is_qto || $is_revision)) ? $edit_arr['Main']['supp_class_id'] : '') ?>" data-select-name="<?php echo ($IsSales && ($IsEdit || $is_qto || $is_revision)) ? $edit_arr['Main']['supp_class_name'] : '' ?>">
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="row form-group">
                                    <div class="col-md-4" id="SupplierInfo">
                                        <div class="col-md-12 <?php echo $IsSales && !in_array(25, $sales_inv_fields_hide) ? '' : 'hidden' ?>">
                                            <label><?php echo CommonLanguage::getMessage('customer_name_alias') ?></label>
                                            <input type="text" class="form-control" id="customer_name_alias" value="<?php echo ($IsEdit || $is_qto) ? $edit_arr['Main']['customer_name_alias'] : '' ?>" />
                                        </div>
                                        <div class="col-md-12 <?php echo $IsSales && !in_array(26, $sales_inv_fields_hide) ? '' : 'hidden' ?>">
                                            <label><?php echo CommonLanguage::getMessage('customer_address_alias') ?></label>
                                            <input type="text" class="form-control" id="customer_address_alias" value="<?php echo ($IsEdit || $is_qto) ? $edit_arr['Main']['customer_address_alias'] : '' ?>" />
                                        </div>
                                        <div class="col-md-12">
                                            <input type="hidden" name="Supplier_ID" value="<?php echo ($IsEdit || $is_qto || $is_revision) ? ($edit_arr['Main']['Person_ID']) : '' ?>" required id="Supplier_ID" />
                                            <div id="SupplierInfoContent" class="<?php echo ($IsEdit || $is_qto || $is_revision) ? '' : 'hidden' ?>">
                                                <strong><span class='Name' id='Supplier_Name' data-id='<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Name'] : '' ?>'><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Name'] : '' ?></span></strong>
                                                <div><strong><?php echo CommonLanguage::getMessage('company'); ?>: </strong><span class='Company'><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Company'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('Email'); ?>: </strong><span class='Email'><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Email'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('Phone'); ?>: </strong><span class='Phone'><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Phone'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('vat'); ?>: </strong><span class='vat'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['person_vat'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('cr'); ?>: </strong><span class='cr'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['person_cr']  : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('address'); ?>: </strong><span class='Address'><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Address'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('country'); ?>: </strong><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Country_Name'] : '' ?></div>
                                                <div id='Finance_Account' data-id='<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Account_ID'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('financial_nb'); ?>: </strong><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Person']['Account_Code'] : '' ?></div>
                                                <div id='Class_ID' style='display:none;'><?php echo (($IsEdit || $is_qto || $is_revision) && $IsSales) ? $edit_arr['Person']['Class_ID'] : '' ?></div>
                                                <div id='Class_Currency' style='display:none;'><?php echo (($IsEdit || $is_qto || $is_revision) && $IsSales) ? $edit_arr['Person']['Class_Currency'] : '' ?></div>
                                            </div>
                                        </div>
                                        <!--                                    <div id="SupplierAccInfo" class="<?php echo ($IsEdit || $is_qto || $is_revision) ? '' : 'hidden' ?>">
<div id='Account_CodeDiv' value='<?php echo $IsEdit ? $edit_arr['Main']['Account_Code'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('account_code') ?>: </strong><?php echo $IsEdit ? $edit_arr['Main']['Account_Name'] . ' - ' . $edit_arr['Main']['Account_Code'] : '' ?></div>
</div>-->
                                    </div>
                                    <div class="col-md-3 <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && !$is_revision) ? '' : 'hidden'; ?>">
                                        <label><?php print CommonLanguage::getMessage('posponted_status') ?></label>
                                        <select class="full-width" id="postponed_status_id" name="postponed_status_id" data-init-plugin="select2">
                                            <option value=""><?php echo CommonLanguage::getMessage('select') ?></option>
                                            <option value="1" <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_status_id']) && $edit_arr['Main']['postponed_status_id'] == 1) ? 'selected' : ''; ?>><?php echo CommonLanguage::getMessage('Request') ?></option>
                                            <option value="2" <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_status_id']) && $edit_arr['Main']['postponed_status_id'] == 2) ? 'selected' : ''; ?>><?php echo CommonLanguage::getMessage('production_line') ?></option>
                                            <option value="3" <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_status_id']) && $edit_arr['Main']['postponed_status_id'] == 3) ? 'selected' : ''; ?>><?php echo CommonLanguage::getMessage('production_done') ?></option>
                                            <option value="4" <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_status_id']) && $edit_arr['Main']['postponed_status_id'] == 4) ? 'selected' : ''; ?>><?php echo CommonLanguage::getMessage('delivered') ?></option>
                                            <option value="5" <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_status_id']) && $edit_arr['Main']['postponed_status_id'] == 5) ? 'selected' : ''; ?>><?php echo CommonLanguage::getMessage('on_request') ?></option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && !$is_revision) ? '' : 'hidden'; ?>">
                                        <label><?php echo CommonLanguage::getMessage('posponted_date'); ?></label>
                                        <input type="text" name="postponed_date_time" id="postponed_date_time" class="form-control" value="<?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_date_time'])) ? $edit_arr['Main']['postponed_date_time'] : ''; ?>" />
                                    </div>
                                </div>
                                <div class="row form-group <?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && !$is_revision) ? '' : 'hidden'; ?>">
                                    <div class="col-md-6">
                                        <label><?php print CommonLanguage::getMessage('posponted_note') ?></label>
                                        <textarea id="postponed_note" name="postponed_note" class="form-control"><?php echo (smc_session()['default_setting']['activate_postponed_sales_order'] == 1 && $IsSales && !$is_qto && $IsEdit && !empty($edit_arr['Main']['postponed_note'])) ? $edit_arr['Main']['postponed_note'] : ''; ?></textarea>
                                    </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($IsSales ? 'invoice' : 'purchase_voucher'); ?> #
                                <?php
                                echo $IsEdit ? $edit_arr['Main']['ID'] : '--';
                                ?></h4>
</div>-->

                                <div style="display: flex">
                                    <div class="form-group " style="width: 48%;margin-right:2%;">
                                        <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 class="form-group  <?php echo (!$IsSales && in_array(13, $purchase_inv_fields_hide)) ? 'hidden' : '' ?>" style="width: 50%;">
                                        <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                        <input id="PurchaseInvoiceDueDate" name="PurchaseInvoiceDueDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Due_Date'] : $today); ?>" required>
                                        <!--<span class="input-group-addon primary"><i class="fa fa-calendar-o"></i></span>-->
                                    </div>
                                </div>

                                <div id="depot" class="form-group  <?php echo ($IsSales && in_array(10, $sales_inv_fields_hide)) ? 'hidden' : ''; ?>" style="display: flex;">
                                    <!--<div class="col-md-12">-->
                                    <div style="width: 48%;margin-right:2%;" class=" <?php echo $permissions->hasPermission('Depots') ? '' : 'hidden'; ?> ">
                                        <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" <?php echo $permissions->hasPermission($IsSales ? 'change_invoice_depot' : 'change_depot') ? '' : 'disabled' ?> data-old="<?php echo $IsEdit ? $edit_arr['Main']['Depot_ID'] : ''; ?>" value="<?= ($IsEdit || $is_qto || $is_revision) ? $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 || $is_qto || $is_revision) ? $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="width: 50%;" class="<?php echo (!$IsSales && in_array(16, $purchase_inv_fields_hide)) ? 'hidden' : '' ?>">
                                        <div class="form-group ">
                                            <label><?php print CommonLanguage::getMessage('exchange_rate'); ?></label>
                                            <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?> value="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['current_rate'] : '' ?>" />
                                        </div>
                                    </div>
                                    <!--</div>-->
                                </div>
                                <div id="CurrencyIDContainer" class=" m-t-10">
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['Currency_Symbol'] : ''; ?>">
                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><strong><?php echo ($IsEdit || $is_qto || $is_revision) ? ($edit_arr['Main']['Currency_Name'] . ' - ' . $edit_arr['Main']['Currency_Symbol']) : CommonLanguage::getMessage('select') ?></strong></span>
                                                <input type="hidden" value="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['Currency_ID'] : $DefaultCurrencyID ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID" />
                                            </button>
                                            <ul class="dropdown-menu">
                                                <?php echo $CurList ?>
                                                <li class="divider"></li>
                                                <li><a class="LoadMore">More..</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <?php if (!$IsQuotation) { ?>
                                    <div style="display:flex;" class="<?php echo (!$IsSales && in_array(12, $purchase_inv_fields_hide)) ? 'hidden' : '' ?>">
                                        <div class="form-group  full-width">
                                            <label><?php print CommonLanguage::getMessage('Delivery_Date'); ?></label>
                                            <input id="delivery_date" name="delivery_date" class="form-control" autocomplete="off" value="<?php echo ($IsEdit ? $edit_arr['Main']['delivery_date'] : ''); ?>" />
                                        </div>
                                    </div>
                                <?php } ?>
                                <div class="form-group " style="display: flex;">
                                    <div class="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 0 || (!$IsSales && in_array(14, $purchase_inv_fields_hide)) ? 'hidden' : '' ?>" style="width: 48%;margin-right:2%;">
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" value="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['job_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_qto) ? $edit_arr['Main']['job_name'] : '' ?>" />
                                    </div>
                                    <div class="<?php echo smc_session()['default_setting']['activate_project'] == 0 || (!$IsSales && in_array(15, $purchase_inv_fields_hide)) ? 'hidden' : '' ?>" style="width: 50%;">
                                        <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                        <input type="hidden" class="full-width" id="project_id" value="<?php echo (($IsEdit || $is_qto || $is_revision) && !empty($edit_arr['Main']['project_id'])) ? $edit_arr['Main']['project_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['project_name'] : '' ?>" />
                                    </div>

                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <div id="ProdLoader" class="text-center alert <?php echo ($IsEdit || $is_qto || $is_revision) ? 'hideme' : '' ?>" style="height:100%;background-color:#E2DEEF">
                            <h3><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer_first' : 'choose_supplier_first'); ?> </h3>
                        </div>
                        <table class="table  <?php echo ($IsEdit || $is_qto || $is_revision) ? '' : 'hideme' ?>" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center" style="width:5%"></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage($IsSales ? 'customer_code' : 'supplier_code'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_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" style="width:5%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                    
                                    <th class="text-center <?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>" style="width:5%"><?php print CommonLanguage::getMessage('n_width'); ?></th>
                                    <th class="text-center <?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>" style="width:5%"><?php print CommonLanguage::getMessage('n_height'); ?></th>
                                    <th class="text-center <?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>" style="width:5%"><?php print CommonLanguage::getMessage('n_total'); ?></th>

                                    
                                    <th class="text-center <?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('lot'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('serial'); ?></th>


                                    <th class="text-center <?php echo ($IsSales && in_array(31, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('from_time'); ?> <span id="wrong_time" style="color: red;font-size: 10px;"> </span></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(32, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('to_time'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(33, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('date'); ?></th>

                                    <th class="text-center <?php echo ($IsSales && in_array(30, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('driver'); ?></th>



                                    <th class="text-center <?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('description'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('unit_price'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:5%"><?php print CommonLanguage::getMessage('discount_percent'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(5, $sales_inv_fields_hide)) || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('vat'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(6, $sales_inv_fields_hide)) || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('vat_percent'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('class'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('Cost'); ?><i class="fa fa-info-circle" title="<?php echo CommonLanguage::getMessage('cost_per_unit') ?>"></i></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('other_cost'); ?><i class="fa fa-info-circle" title="<?php echo CommonLanguage::getMessage('cost_per_unit') ?>"></i></th>

                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('total'); ?></th>
                                    <?php if (smc_session()['default_setting']['is_tag_active'] == 1 && $IsSales) { ?>
                                        <th class="text-center" style="width:5%"></th>
                                        <th class="text-center" style="width:10%"></th>
                                    <?php } ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit || $is_qto || $is_revision) {
                                    $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['Product_Quantity'] ?>" data-vat="<?php echo $item['VAT'] ?>" data-id="<?php echo $item['Product_ID'] ?>" unit_price="<?php echo $item['Product_Net_Price'] ?>" data-prod-status="<?php echo $item['Status_ID']; ?>" data-item-disc="<?php echo $item['Product_Limit_Discount'] ?>" data-entry="<?php echo $item['Entery_ID'] ?>">
                                                <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 ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_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 ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete person_code  "></td>

                                                <td class="<?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName " value="<?php echo $item['Name'] ?>"><span class="Hint"></span></td>
                                                <td><input type="text" class="form-control Quantity isnumber" value="<?php echo $item['Item_Quantity_Current'] ?>"><span class="Hint"></span></td>
                                                
                                                
                                                <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_width isnumber" value = "<?php echo $item['n_width'] ?>"></td>
                                                <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_height isnumber" value = "<?php echo $item['n_height'] ?>"></td>
                                                <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" disabled class="form-control n_total  isnumber" value = "<?php echo $item['n_total'] ?>"></td>

                                                
                                                
                                                <td class=" <?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_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 ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <input type="text" class="form-control lot_nb hidden" value="<?php echo $item['lot_nb'] ?>">
                                                </td>
                                                <td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <input type="text" class="form-control serial_nb hidden" value="<?php echo $item['serial_nb'] ?>">
                                                </td>


                                                <td class=" <?php echo ($IsSales && in_array(31, $sales_inv_fields_hide)) || $IsQuotation  || !$IsSales? 'hidden' : ''; ?> "><input type="time" class="form-control from_time" value="<?php echo $item['from_time'] ?>"></td>
                                                <td class=" <?php echo ($IsSales && in_array(32, $sales_inv_fields_hide)) || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> "><input type="time" class="form-control to_time" value="<?php echo $item['to_time'] ?>"></td>
                                                <td class=" <?php echo ($IsSales && in_array(33, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales? 'hidden' : ''; ?> "><input type="date" class="form-control modify_date" value="<?php echo $item['modify_date'] ?>"></td>

                                                <td class="  <?php echo ($IsSales && in_array(30, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales? 'hidden' : ''; ?> ">
                                                    <select name="item_driver_id" class="full-width item_driver_id " data-init-plugin="select2">
                                                        <option value=""><?php print CommonLanguage::getMessage('select'); ?></option>
                                                        <?php foreach ($drivers_item_list as $driver) { ?>
                                                            <option value="<?php echo $driver['driver_id']; ?>" <?php echo $driver['driver_id'] == $item['driver_id'] ? 'selected' : '' ?>><?php echo $driver['driver_name']; ?></option>
                                                        <?php } ?>
                                                    </select>
                                                </td>


                                                <td class="<?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note" value="<?php echo $item['product_description'] ?>"></td>


                                                <td class=" <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"> <input type="text" class="form-control UnitPrice isnumber" <?php echo ($IsSales && !$permissions->hasPermission('change_sales_unit_price')) ? 'disabled' : '' ?> value="<?php echo $item['Product_Net_Price'] ?>"><span class="Hint"></span></td>
                                                <td class=" <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"> <input type="text" class="form-control Disc" <?php echo ($IsSales && !$permissions->hasPermission('sales_discount_on_item')) ? 'disabled' : '' ?> value="<?php echo $item['Product_Discount'] ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(5, $sales_inv_fields_hide))  || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && ($item['VAT'] == 1 || smc_session()['allow_purchase_vat_edit'] == 1)) ? '' : 'disabled' ?> value="<?php echo $item['vat_amount'] ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(6, $sales_inv_fields_hide))  || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && ($item['VAT'] == 1 || smc_session()['allow_purchase_vat_edit'] == 1)) ? '' : 'disabled' ?> value="<?php echo $item['vat_percent'] ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="full-width supp-class" value="<?php echo !empty($item['supp_class_id']) ? $item['supp_class_id'] : '' ?>" data-select-name="<?php echo !empty($item['supp_class_name']) ? $item['supp_class_name'] : '' ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="form-control item-cost isnumber" value="<?php echo !empty($item['item_cost']) ? $item['item_cost'] : '' ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="form-control item-other-cost isnumber" value="<?php echo !empty($item['other_cost']) ? $item['other_cost'] : '' ?>"></td>
                                                <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                                <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                                <?php if (smc_session()['default_setting']['is_tag_active'] == 1 && $IsSales) { ?>
                                                    <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-price="<?php echo $criteria['criteria_price'] ?>" 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 ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan"></td>
                                        <td class="<?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete person_code  "></td>

                                        <td class="<?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>


                                        <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_width isnumber"></td>
                                        <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_height isnumber"></td>
                                        <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_total isnumber"></td>



                                        <td class=" <?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <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 ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="text" class="form-control lot_nb hidden" value="">
                                        </td>
                                        <td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="text" class="form-control serial_nb hidden" value="">
                                        </td>

                                        <td class=" <?php echo ($IsSales && in_array(31, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> "><input type="time" class="form-control from_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(32, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> "><input type="time" class="form-control to_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(33, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> "><input type="date" class="form-control modify_date"></td>
                                        <td class="  <?php echo ($IsSales && in_array(30, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?>   ">
                                            <select name="item_driver_id" class="full-width item_driver_id " data-init-plugin="select2">
                                                <option value=""><?php print CommonLanguage::getMessage('select'); ?></option>
                                                <?php foreach ($drivers_item_list as $driver) : ?>
                                                    <option value="<?php echo $driver['driver_id']; ?>"><?php echo $driver['driver_name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>




                                        <td class="<?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note"></td>
                                        <td class=" <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber" <?php echo ($IsSales && !$permissions->hasPermission('change_sales_unit_price')) ? 'disabled' : '' ?>><span class="Hint"></span></td>
                                        <td class=" <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"> <input type="text" class="form-control Disc" <?php echo ($IsSales && !$permissions->hasPermission('sales_discount_on_item')) ? 'disabled' : '' ?> value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(5, $sales_inv_fields_hide)) || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?> value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(6, $sales_inv_fields_hide)) || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo ($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="full-width supp-class"></td>
                                        <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="form-control item-cost isnumber"></td>
                                        <td class="<?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="form-control item-other-cost isnumber"></td>
                                        <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                        <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                        <?php if (smc_session()['default_setting']['is_tag_active'] == 1 && $IsSales) { ?>
                                            <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 ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan"></td>
                                        <td class="<?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete person_code  "></td>

                                        <td class="<?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>


                                        <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_width isnumber"></td>
                                        <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_height isnumber"></td>
                                        <td class="<?php echo $IsQuotation || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_total isnumber"></td>


                                        <td class=" <?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <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 ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="text" class="form-control lot_nb hidden" value="">
                                        </td>
                                        <td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="text" class="form-control serial_nb hidden" value="">
                                        </td>


                                        <td class=" <?php echo ($IsSales && in_array(31, $sales_inv_fields_hide))   || $IsQuotation || !$IsSales? 'hidden' : ''; ?>  "><input type="time" class="form-control from_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(32, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?>  "><input type="time" class="form-control to_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(33, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> "><input type="date" class="form-control modify_date"></td>


                                        <td class=" <?php echo ($IsSales && in_array(30, $sales_inv_fields_hide))  || $IsQuotation || !$IsSales ? 'hidden' : ''; ?> ">
                                            <select name="item_driver_id" class="full-width item_driver_id " data-init-plugin="select2">
                                                <option value=""><?php print CommonLanguage::getMessage('select'); ?></option>
                                                <?php foreach ($drivers_item_list as $driver) : ?>
                                                    <option value="<?php echo $driver['driver_id']; ?>"><?php echo  $driver['driver_name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>



                                        <td class="<?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note"></td>

                                        <td class=" <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber" <?php echo ($IsSales && !$permissions->hasPermission('change_sales_unit_price')) ? 'disabled' : '' ?>><span class="Hint"></span></td>

                                        <td class=" <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"> <input type="text" class="form-control Disc" <?php echo ($IsSales && !$permissions->hasPermission('sales_discount_on_item')) ? 'disabled' : '' ?> value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(5, $sales_inv_fields_hide)) || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?> value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(6, $sales_inv_fields_hide)) || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo ($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="full-width supp-class"></td>
                                        <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="form-control item-cost isnumber"></td>
                                        <td class="<?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || !$IsSales || smc_session()['default_setting']['activate_costing_in_sales_quotation'] == 0 ? 'hidden' : ''; ?>"><input type="text" class="form-control item-other-cost isnumber"></td>
                                        <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                        <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                        <?php if (smc_session()['default_setting']['is_tag_active'] == 1 && $IsSales) { ?>
                                            <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 } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height">
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-6 col-sm-height   " style="border-left: 1px solid #eee;border-right: 1px solid #eee;padding-right:0">
                                <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="col-md-12 p-0 m-b-10">

                                        <div <?php echo ($IsSales && in_array(19, $sales_inv_fields_hide)) || (!$IsQuotation) || (!$IsSales) ? 'hidden' : ''; ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('Po'); ?></label>
                                            <input id="po" name="po" value="<?php echo (((!$IsQuotation || $IsSales) && $IsEdit) ? $edit_arr['Main']['po'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(20, $sales_inv_fields_hide)) || (!$IsQuotation) || (!$IsSales) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('project_name'); ?></label>
                                            <input id="project_name_inv" value="<?php echo ((!$IsQuotation || $IsSales) && $IsEdit) ? $edit_arr['Main']['project_name_inv'] : ($is_qto && $IsEdit ? $edit_arr['Main']['project_name_inv'] : '') ?>" name="project_name_inv " class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(21, $sales_inv_fields_hide)) || (!$IsQuotation) || (!$IsSales) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('project_code'); ?></label>
                                            <input id="project_code" name="project_code" value="<?php echo ((!$IsQuotation || $IsSales) && $IsEdit) ? $edit_arr['Main']['project_code'] : ($is_qto && $IsEdit ? $edit_arr['Main']['project_code'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(22, $sales_inv_fields_hide)) || (!$IsQuotation) || (!$IsSales) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('job'); ?></label>
                                            <input id="job_inv" name="job_inv" value="<?php echo ((!$IsQuotation || $IsSales) && $IsEdit) ? $edit_arr['Main']['job_inv'] : ($is_qto && $IsEdit ? $edit_arr['Main']['job_inv'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(23, $sales_inv_fields_hide)) || (!$IsQuotation) || (!$IsSales) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('our_ref'); ?></label>
                                            <input id="our_ref" name="our_ref" value="<?php echo ((!$IsQuotation || $IsSales) && $IsEdit) ? $edit_arr['Main']['our_ref'] : ($is_qto && $IsEdit ? $edit_arr['Main']['our_ref'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(24, $sales_inv_fields_hide)) || (!$IsQuotation) || (!$IsSales) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('supply_date'); ?></label>
                                            <input id="supply_date" type="date" name="supply_date" value="<?php echo ((!$IsQuotation || $IsSales) && $IsEdit) ? $edit_arr['Main']['supply_date'] : ($is_qto && $IsEdit ? $edit_arr['Main']['supply_date'] : '') ?>" class="form-control" />
                                        </div>
                                        <!-- customer customize   -->
                                        <div <?php echo ($IsSales  && $IsQuotation && in_array(27, $sales_inv_fields_hide)) || ($IsSales && !$IsQuotation && in_array(27, $sales_inv_fields_hide))  || ((!$IsSales && $IsQuotation && in_array(17, $purchase_inv_fields_hide)))  || (!$IsSales && !$IsQuotation && in_array(17, $purchase_inv_fields_hide)) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('from_place'); ?></label>
                                            <input id="from_place" name="from_place" value="<?php echo ($IsEdit) ? $edit_arr['Main']['from_place'] : '' ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && $IsQuotation && in_array(28, $sales_inv_fields_hide))  || ($IsSales && !$IsQuotation && in_array(28, $sales_inv_fields_hide))   || ((!$IsSales && $IsQuotation && in_array(18, $purchase_inv_fields_hide)))  || (!$IsSales && !$IsQuotation && in_array(18, $purchase_inv_fields_hide)) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('to_place'); ?></label>
                                            <input id="to_place" name="to_place" value="<?php echo ($IsEdit) ? $edit_arr['Main']['to_place'] : '' ?>" class="form-control" />
                                        </div>

                                        <div <?php echo ($IsSales  && $IsQuotation && in_array(29, $sales_inv_fields_hide))  || ($IsSales && !$IsQuotation && in_array(29, $sales_inv_fields_hide))  || ((!$IsSales && $IsQuotation && in_array(19, $purchase_inv_fields_hide))) || (!$IsSales && !$IsQuotation && in_array(19, $purchase_inv_fields_hide)) ? 'hidden' : '';  ?> class="form-group col-md-6  p-l-0 p-r-5">
                                            <label><?php print CommonLanguage::getMessage('driver'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/driver_list/1?is_pop=1" title="<?php echo CommonLanguage::getMessage('driver_list'); ?>" style="color:#6c5ab3;cursor:pointer"></span>
                                            <input id="driver_id" type="hidden" name="driver_id" value="<?php echo ($IsEdit) ?  $edit_arr['Main']['driver_id'] : ''; ?>" data-select-name="<?php echo ($IsEdit) ? $edit_arr['Main']['driver_name'] : ''; ?>" class="full-width" />
                                        </div>

                                    </div>

                                </div>
                                <div class="col-sm-12  " style="padding-right:0">
                                    <textarea id="invoice_note" name="invoice_note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?> ..."><?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['Invoice_Description'] : '' ?></textarea>
                                </div>
                            </div>
                            <div class="col-sm-3 col-sm-height col-middle clearfix sm-p-b-15" style="text-align:center">
                                <div class="col-md-12" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10"> <?php print CommonLanguage::getMessage('shipping'); ?><input type="text" class="form-control ignore" id="Shipping" value="<?php echo ($IsEdit) ? $edit_arr['Main']['shipping'] : 0 ?>" /> </h5>

                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('vat_ten'); ?><span class="form-control ignore" id="InvoiceVAT"></span> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold"> <?php print CommonLanguage::getMessage('invoice_discount'); ?><input type="text" class="form-control ignore " <?php echo ($IsSales && !$permissions->hasPermission('sales_discount_on_invoice')) ? 'disabled' : '' ?> id="InvoiceDiscountInput" value="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['Discount'] : 0 ?>" /> %</h5>
                                    <h5 class="no-margin"><?php print CommonLanguage::getMessage('discount'); ?><input type="text" class="form-control ignore" id="TotalDiscAmount" <?php echo ($IsSales && !$permissions->hasPermission('sales_discount_on_invoice')) ? 'disabled' : '' ?> value="<?php echo ($IsEdit || $is_qto || $is_revision) ? $edit_arr['Main']['discount_amount'] : 0 ?>" /></h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10" <?php echo (!$IsSales ? '' : 'hidden') ?>> <?php print CommonLanguage::getMessage('extra_cost'); ?><input type="text" class="form-control ignore" id="extra_cost" value="<?php echo ($IsEdit) ? (!$IsSales ? $edit_arr['Main']['extra_cost'] : 0) : 0 ?>" /> </h5>

                                    <!--<h3 class="no-margin"><span class="CurrencyIndicator"></span>&nbsp;<span id="InvoiceTotalAfterDiscount">0</span></h3>-->
                                    <!--<h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('item_discount'); ?></h5>-->
                                    <!--<h3 class="no-margin"><span class="CurrencyIndicator"></span>&nbsp;<span id="DiscountVal">0</span></h3>-->
                                </div>
                            </div>
                            <div class="col-sm-3 text-right bg-menu col-sm-height padding-15" style="text-align:left !important">
                                <div style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseInvoiceTotalDetails">0</span></h1>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('taxable_amount'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseTaxableAmount">0</span></h1>
                                    <h5 <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?> class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('local_amount'); ?></h5>
                                    <h1 <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?> class="no-margin text-white "><span class=""><?php echo smc_session()['local_currency_symbol'] ?></span>&nbsp;<span id="Local_Total">0</span></h1>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php if (!$is_revision) { ?>
                        <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:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>
                            <!--                        <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled <?php // echo $IsEdit ? 'hidden' : ''                                                                                                                       
                                                                                                                            ?>" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>
    <button class=" btn btn-success-darker btn-cons m-b-10 pull-right disabled <?php echo $IsEdit ? 'hidden' : '' ?>" id="PrintBtn1" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print_delv'); ?></span></button>-->
                            <?php if (smc_session()['default_setting']['print_template_settings'] == 0 || smc_session()['default_setting']['print_template_settings'] == 1 || !$IsSales) { ?>
                                <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>
                                <?php
                            } else {
                                foreach ($templates as $temp) {
                                ?>
                                    <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled check_temp_key" data-id="<?php print $temp['template_id']; ?>" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print $temp['template_name']; ?></span></button>

                            <?php
                                }
                            }
                            ?>

                            <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled <?php echo $IsQuotation ? 'hidden' : ((($IsSales && $permissions->hasPermission('sales_order_go_invoice')) || ($permissions->hasPermission('sales_order_go_invoice') && !$IsSales)) ? '' : 'hidden') ?>" id="go_invoice_btn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-retweet"></i> <span class="bold"><?php print CommonLanguage::getMessage('go_invoice'); ?></span></button>

                        </div>
                    <?php } ?>
                    <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 bs-example-modal-md" id="CustomerProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('confirm_customer_change') ?></p>
                        <p><?php print CommonLanguage::getMessage('proceed_change_price') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary yes-btn" style="width:auto"><?php echo CommonLanguage::getMessage('yes') ?></button>
                <button type="button" class="btn btn-danger  pull-left no-btn" data-dismiss="modal"><?php echo CommonLanguage::getMessage('no') ?> </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade bs-example-modal-md" id="SupplierProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('confirm_supplier_change') ?></p>
                        <p><?php print CommonLanguage::getMessage('proceed_change_cost') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary supp-yes-btn" style="width:auto"><?php echo CommonLanguage::getMessage('yes') ?></button>
                <button type="button" class="btn btn-danger  pull-left " data-dismiss="modal"><?php echo CommonLanguage::getMessage('no') ?> </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade bs-example-modal-md" id="DiscountProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('dicount_inv_alert') ?></p>
                        <p><?php print CommonLanguage::getMessage('enter_new_disc') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">

                <button type="button" class="btn btn-primary " data-dismiss="modal" style="width:auto"><?php echo CommonLanguage::getMessage('proceed') ?></button>
            </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>

<div class="modal fade bs-example-modal-md" id="SuppProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('confirm_supp_change') ?></p>
                        <p><?php print CommonLanguage::getMessage('proceed_change_supp') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary supp-proceed" style="width:auto"><?php echo CommonLanguage::getMessage('yes') ?></button>
                <button type="button" class="btn btn-danger  pull-left " data-dismiss="modal"><?php echo CommonLanguage::getMessage('no') ?> </button>
            </div>

        </div>
    </div>
</div>
<div class="modal fade slide-up" id="choose_template_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content-wrapper">
            <div class="modal-content">
                <div class="modal-header clearfix text-left">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                    </button>
                    <h5 class="add-label bold"></h5>
                </div>
                <div class="modal-body">
                    <div class="row ">
                        <?php foreach ($templates as $temp) { ?>
                            <div class="col-md-4">
                                <button type="button" class="btn btn-primary  check_temp_key  full-width" data-id="<?php echo $temp['template_id']; ?>"> <?php echo $temp['template_name']; ?></button>
                            </div>
                        <?php } ?>
                    </div>

                </div>
            </div>
        </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>
<select id="select_item_driver" name="select_item_driver" class="full-width select_item_driver hidden" data-init-plugin="select2">
    <option value=""><?php print CommonLanguage::getMessage('select'); ?></option>
    <?php foreach ($drivers_item_list as $driver) : ?>
        <option value="<?php echo $driver['driver_id']; ?>"><?php echo $driver['driver_name']; ?></option>
    <?php endforeach; ?>
</select>

<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
        CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
        EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email')); ?>,
        customer_vatLang = <?php echo json_encode(CommonLanguage::getMessage('vat')); ?>,
        Customer_CRLang = <?php echo json_encode(CommonLanguage::getMessage('cr')); ?>,

        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')); ?>,
        accountCodeLang = <?php echo json_encode(CommonLanguage::getMessage('account_code')); ?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
        account_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_account_first')); ?>,
        depot_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_depot_first')); ?>,
        supplier_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_supplier_first')); ?>,
        customer_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_customer_first')); ?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
        wrong_time = <?php echo json_encode(CommonLanguage::getMessage('wrong_time')); ?>,
        //            cost_percent_validate = <?php echo json_encode(CommonLanguage::getMessage('cost_percent_validate')); ?>,
        default_vat = <?php echo json_encode(smc_session()['vat_percent']); ?>,
        purchase_restrict_product_supplier = <?php echo json_encode(smc_session()['default_setting']['purchase_restrict_product_supplier']); ?>,
        negative_sales = <?php echo json_encode(smc_session()['default_setting']['order_negative_sales']); ?>;
    var IsSalesMode = <?php echo $IsSales ? "true" : "false"; ?>,
        IsQuotation = <?php echo $IsQuotation ? 1 : 0; ?>,
        IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
        is_qto = <?php echo $is_qto ? "true" : "false"; ?>,
        is_revision = <?php echo $is_revision ? "true" : "false"; ?>,
        is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
        CurrencyRate = <?php echo json_encode($Extable); ?>,
        ID_Edit = (IsEditMode || is_qto) ? <?php echo json_encode($id); ?> : '',
        max_discount = <?php echo json_encode(smc_session()['user_accounts']['max_discount']); ?>,
        ignore_zero_item_disc = <?php echo json_encode(smc_session()['default_setting']['ignore_zero_item_disc']) ?>,
        display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
        local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
        uom_arr = <?php echo json_encode($all_uom); ?>;
    var inv_nb = <?php echo json_encode(CommonLanguage::getMessage('order') . ' #'); ?>;
    var TotalInvoice = 0,
        TotalDiscount = 0,
        TotalInvoiceWithoutDiscount = 0,
        vatVal = 0,
        totalvat = 0,
        taxAmount = 0,
        is_td_total = 0,
        is_ttc = <?php echo json_encode($IsEdit ? (isset($edit_arr['Main']['is_ttc']) ? $edit_arr['Main']['is_ttc'] : smc_session()['default_setting']['activate_ttc']) : ($IsSales ? smc_session()['class_is_ttc'] : smc_session()['default_setting']['activate_ttc'])); ?>,
        percent_flag = 0,
        total_qty = 0,
        global_round = <?php echo json_encode($currency_round); ?>,
        max_criteria_column = 5;
    var CheckSubmit = true,
        has_vat_permission = <?php echo $permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') ? 'true' : 'false'; ?>,
        has_sales_cost_perm = <?php echo $permissions->hasPermission('view_sales_last_cost') ? 'true' : 'false'; ?>,
        has_purchase_cost_perm = <?php echo $permissions->hasPermission('view_purchase_last_cost') ? 'true' : 'false'; ?>,
        has_sales_last_price = <?php echo json_encode($permissions->hasPermission('view_sales_last_price')); ?>,
        allow_purchase_vat_edit = <?php echo json_encode(smc_session()['allow_purchase_vat_edit']); ?>,
        activate_lot = <?php echo json_encode(($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 0 : 1); ?>,
        activate_serial = <?php echo json_encode(($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 0 : 1); ?>,
        auto_fill_cost = <?php echo json_encode(in_array('1', $autofill_cost) ? 1 : 0); ?>,
        auto_fill_zerocost = <?php echo json_encode(in_array('1', $autofill_zerocost) ? 1 : 0); ?>,
        print_template_settings = <?php echo json_encode(smc_session()['default_setting']['print_template_settings']); ?>,
        unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>;
    //    var CCustID = 0, CCustName = '';
    if (IsSalesMode) {
        $("#SupplierInv").removeClass("supInv")
        $("#SupplierInv").addClass("hideme")
    }

    $(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() {
        $("#postponed_date_time").datetimepicker({
            format: 'YYYY-MM-DD HH:mm:ss'
        })
        $('#delivery_date').datetimepicker({
            format: 'YYYY-MM-DD HH:mm',
            useCurrent: false
        });
        build_select2($("input[name=PIC_ID]"), "xhr/employeeSearch")
        build_select2($(".search_supplier"), (IsSalesMode ? "xhr/customerSearch" : "xhr/supplierSearch") + (IsEditMode ? "?is_edited=" + $(".search_supplier").val() : "?Status_ID=1"));
        build_select2($("#Account_Code"), ("xhr/accIDSearch?type=" + (IsSalesMode ? 'sales' : 'purchase')))
        build_select2($("#Shipping_Code"), ("xhr/accIDSearch?type=" + (IsSalesMode ? 'sales' : 'purchase')))
        build_select2($(".Depot_Loc"), "xhr/depotSearch")
        build_select2($("#cash_account"), ("xhr/accIDSearch?type=cash"))
        build_select2($("#check_account"), ("xhr/accIDSearch?type=check"))
        build_select2($("#credit_account"), ("xhr/accIDSearch?type=credit_card"))
        build_select2($("#pricing_class"), "xhr/PricingClassSearch")
        build_select2($("#supplier_pricing_class"), "xhr/PricingClassSearch?type=1")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        build_select2($("input.supp-class"), "xhr/PricingClassSearch?type=1", false, 'diff_class')
        //        build_select2($("#job_id"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs")
        apply_autocomplete($("#inv_truck"), 'xhr/searchInvTruck', function(event, ui, who) {
            who.val(ui.item.truck);
        });
        new Switchery($("#pending").get(0), {
            color: $.Pages.getColor("primary")
        })
        $(".CurrencyIndicator").html($("#CurrencyDropDown").attr("data-symbol"))
        $("#current_rate").on("keyup", function() {
            UpdateTable()
        })
        //        $("#PrintBtn").on("click", function () {
        //            var myurl = "Inventory/ViewQuotationOrder/" + (IsQuotation == 1 ? 'quotation' : 'order') + (is_actual ? "/act" : "") + "/" + ID_Edit;
        //            printExternal(myurl)
        //        })
        build_select2($("#driver_id"), "xhr/CommonSearch?col_name=driver_name&col_id=driver_id&table=tbl_drivers");

        $("#PrintBtn").on("click", function() {
            if (print_template_settings == 0 || !IsSalesMode) {
                var myurl = "Inventory/ViewQuotationOrder/" + (IsQuotation == 1 ? 'quotation' : 'order') + (is_actual ? "/act" : "") + "/" + ID_Edit;
                printExternal(myurl)
            } else {
                $("#choose_template_modal").modal("show")
            }
        })
        $(".check_temp_key").on("click", function() {
            var myurl = "Inventory/ViewQuotationOrder/" + (IsQuotation == 1 ? 'quotation' : 'order') + (is_actual ? "/act" : "") + "/" + ID_Edit + '&template_id=' + $(this).attr("data-id");
            printExternal(myurl)
        })




        $("#go_invoice_btn").on("click", function() {
            window.location = site_link + "Inventory/addpurchase/order/" + (IsSalesMode ? 'sales/' : '') + (is_actual == 1 ? 'act/' : '') + ID_Edit;
        })

        $("#InventoryPurchaseTable").on("change", "input.UnitPrice,input.VATPerItem,input.vat_percent,input.ttc_price,input.Disc", function() {
            console.log('input.UnitPrice change')
            console.log($(this).val())
            val = $(this).val()
            mytr = $(this).parents("tr");

            mytr.find(".VATPerItem").val(public_round_number(mytr.find(".VATPerItem").val()))

            mytr.find(".UnitPrice").val(public_round_number(mytr.find(".UnitPrice").val()))

            mytr.find(".vat_percent").val(public_round_number(mytr.find(".vat_percent").val()))

            mytr.find(".ttc_price").val(public_round_number(mytr.find(".ttc_price").val()))
            mytr.find(".Disc").val(public_round_number(mytr.find(".Disc").val()))

        })


        $("#InventoryPurchaseTable").on("change", "input.supp-class", function() {
            var me = $(this).parents('tr');
            var item_arr = {
                items: [{
                    pid: me.attr("data-id"),
                    uid: $("select[name=UOM_ID]", me).val()
                }],
                class_id: ($(this).val() != '' ? $(this).val() : $("#supplier_pricing_class").val())
            }
            $.ajax({
                url: "InventoryAjax/ReturnPriceByClass",
                data: item_arr,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        $.each(Data, function(index, value) {
                            $("#Class_Currency").html(value['class_currency_id'])
                            //                            console.log(value['Product_Price']+'==='+$("#Class_Currency").text()+'==='+ $("#CurrencyDropDown input").val())
                            me.find("input.item-cost").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? value['Product_Price'] : public_round_number(ConvertCurrency2(value['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))

                        })

                        UpdateTable()
                    }
                }
            })
        })


        $("#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()
                UpdateTable()
                //                $(".Quantity").trigger('keyup')
            }
        })
        $("#InventoryPurchaseTable").on("change", "select.UOM_ID", function() {
            var me = $(this).parents("tr");
            if (IsSalesMode) {
                var UOMData = {
                    pid: $(this).parents("tr").attr("data-id"),
                    uid: $(this).val(),
                    depot_id: $("#Depot_Loc").val(),
                    class_id: $("#pricing_class").val(),
                    supp_class: (me.find('input.supp-class').val() != '' ? me.find('input.supp-class').val() : $("#supplier_pricing_class").val())
                };
            } else {
                var UOMData = {
                    pid: $(this).parents("tr").attr("data-id"),
                    uid: $(this).val(),
                    depot_id: $("#Depot_Loc").val()
                };
            }
            $.ajax({
                url: "InventoryAjax/ReturnProductUOMPriceCon",
                data: UOMData,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        me.attr('data-conv', v1.responseJSON['conversion_amount'])
                        if (IsSalesMode) {
                            var tag_price = 0;
                            $(".mylabel", me).each(function() {
                                var cur_price = parseFloat($(this).attr("data-price")) || 0;
                                //                                        $(this).attr("data-price", tag_price)
                                tag_price += cur_price;
                            });
                            var unit_price = parseFloat(v1.responseJSON['Product_Price']) || 0;
                            me.find("input.UnitPrice").val(unit_price + tag_price)
                            me.find("input.UnitPrice").val(parseFloat(ConvertCurrency2(unit_price, v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val())) + tag_price)
                            me.find("input.item-cost").val(ConvertCurrency2(v1.responseJSON['supp_cost'], local_currency, $("#CurrencyDropDown input").val()))
                        }
                        me.find("input.Disc").val(v1.responseJSON['disc'])
                        me.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(v1.responseJSON['qty']))) + " in stock")
                        setTimeout('UpdateTable()', 100)
                    }
                }
            })
        })
        //        $("#cost_dist_method").on("change", function () {
        //            if ($(this).val() == 2) {
        //                $(".cost-cell").removeClass("hidden")
        //            } else {
        //                $(".cost-cell").addClass("hidden")
        //                $(".cost_percent").val(0)
        //            }
        //        })
        //        $("#InvoicePaymentSetup .InputSpinner .btn").on('click', function (e) {
        //            e.preventDefault();
        //            var Input = $("input", $(this).parent().parent()), V = parseInt(Input.val())
        //            Input.val($(this).hasClass("more") ? V + 1 : V == 0 ? 0 : V - 1)
        //            UpdatePurchaseInvoiceTotalPaid()
        //        })
        //        $("#InvoicePaymentSetup").find("input.form-control").on("keyup", function () {
        //            UpdatePurchaseInvoiceTotalPaid()
        //        })
        //        if (IsEditMode )
        //            $("#InvoicePaymentSetup").find("input.form-control").trigger('keyup')
        $("#pricing_class").on("change", function(e) {
            if ($(this).val() == '') {
                if (activate_ttc == 0) {
                    is_ttc = 0;
                } else {
                    is_ttc = 1;
                }
                $("#Class_Currency").html($("#CurrencyDropDown input").val())
                return false;
            }
            $.ajax({
                url: "POSAjax/ReturnClassCurrency",
                data: {
                    class_id: $("#pricing_class").val()
                },
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var data = v1.responseJSON;
                        is_ttc = data['is_ttc'];
                        $("#Class_Currency").html(data['Currency_ID']);
                        $("#card_tax").attr("data-tax", data['tax_amount'])
                    }
                }
            })
        })
        $("#pricing_class").on("select2-selecting", function(e) {
            var flag = false;
            //            console.log(e.val)
            if (e.val == undefined)
                return false;
            if ($(this).val() != '' && e.val != $(this).val()) {
                $("#InventoryPurchaseTable tbody tr").each(function() {
                    if ($(this).attr("data-id") != 0 && $(this).attr("data-id") != undefined) {
                        flag = true;
                    }
                })
            }
            if (flag) {
                $("#CustomerProceedModal").modal("show")
            }
        })
        $(".yes-btn").on("click", function() {
            var item_arr = {
                items: [],
                class_id: $("#pricing_class").val()
            }
            $("#InventoryPurchaseTable tbody tr").each(function(e) {
                if ($(this).attr("data-id") > 0) {
                    item_arr.items.push({
                        pid: $(this).attr("data-id"),
                        uid: $("select[name=UOM_ID]", $(this)).val(),
                        index: $(this).index()
                    })
                }
            })
            $.ajax({
                url: "InventoryAjax/ReturnPriceByClass",
                data: item_arr,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        for (var i = 0; i < Data.length; i++) {
                            var me = $("#InventoryPurchaseTable tbody tr:eq(" + Data[i]['index'] + ")");
                            //                            me.find("input.UnitPrice").val(Data[i]['Product_Price'])
                            var tag_price = 0;
                            $(".mylabel", $(this)).each(function() {
                                var cur_price = parseFloat($(this).attr("data-price")) || 0;
                                //                                        $(this).attr("data-price", tag_price)
                                tag_price += cur_price;
                            });
                            me.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ((parseFloat(Data[i]['Product_Price']) || 0) + tag_price) : public_round_number((parseFloat(ConvertCurrency2(Data[i]['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val())) || 0) + tag_price))
                        }
                        UpdateTable()
                    }
                }
            })
            $("#CustomerProceedModal").modal("hide")
        })

        $("#search_supplier").on("select2-selecting", function(e) {

            if (purchase_restrict_product_supplier == 1 && !IsSalesMode && $(this).val() != '' && e.val != $(this).val()) {
                var flag = false;
                $("#InventoryPurchaseTable tbody tr").each(function() {
                    if ($(this).attr("data-id") != 0 && $(this).attr("data-id") != undefined) {
                        flag = true;
                    }
                })
                if (flag) {
                    $("#SuppProceedModal").modal("show")
                }
            }
        })

        $(".supp-proceed").on("click", function() {
            $("#InventoryPurchaseTable tbody tr:gt(0)").empty()
            empty_row($("#InventoryPurchaseTable tbody tr:eq(0)"))
            $("#SuppProceedModal").modal("hide")
        })


        $("#supplier_pricing_class").on("select2-selecting", function(e) {
            var flag = false;
            //            console.log(e.val)
            if (e.val == undefined)
                return false;
            if (($(this).val() != '' && e.val != $(this).val()) || e.val != '') {
                $("#InventoryPurchaseTable tbody tr").each(function() {
                    if ($(this).attr("data-id") != 0 && $(this).attr("data-id") != undefined) {
                        flag = true;
                    }
                })
            }
            if (flag) {
                $("#SupplierProceedModal").modal("show")
            }
        })
        $(".supp-yes-btn").on("click", function() {
            var item_arr = {
                items: [],
                class_id: $("#supplier_pricing_class").val()
            }
            $("#InventoryPurchaseTable tbody tr").each(function(e) {
                if ($(this).attr("data-id") > 0) {
                    item_arr.items.push({
                        pid: $(this).attr("data-id"),
                        uid: $("select[name=UOM_ID]", $(this)).val(),
                        index: $(this).index()
                    })
                }
            })
            $.ajax({
                url: "InventoryAjax/ReturnPriceByClass",
                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:eq(" + Data[i]['index'] + ")");
                            me.each(function() {
                                if ($(this).find("input.supp-class").val() == "") {
                                    $(this).find("input.item-cost").val(value['class_currency_id'] == $("#CurrencyDropDown input").val() ? value['Product_Price'] : public_round_number(ConvertCurrency2(value['Product_Price'], value['class_currency_id'], $("#CurrencyDropDown input").val())))

                                    //                                        var tr_conv = parseFloat($(this).attr("data-conv"));
                                    //                                        $(this).find(".Quantity").next().text(AddCommas(parseFloat(value['qty'] / tr_conv).toXFixed(3)) + " in stock")
                                    //                                        $(this).find("input.ProductName").next().text(value['loc'])
                                }
                            });
                        })
                        //                        for (var i = 0; i < Data.length; i++) {
                        //                            var me = $("#InventoryPurchaseTable tbody tr[data-id='" + Data[i]['Product_ID'] + "']");
                        //                            //                            me.find("input.UnitPrice").val(Data[i]['Product_Price'])
                        //                            me.find("input.item-cost").val(Data[i]['class_currency_id'] == $("#CurrencyDropDown input").val() ? Data[i]['Product_Price'] : ConvertCurrency2(Data[i]['Product_Price'], Data[i]['class_currency_id'], $("#CurrencyDropDown input").val()).toXFixed(2))
                        //                        }
                        UpdateTable()
                    }
                }
            })
            $("#SupplierProceedModal").modal("hide")
        })
        $("#search_supplier").on("change", function() {
            $("#SupplierInfoContent").removeClass('hidden')
            if ($(this).val() == '') {
                $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else
            if ($("#Account_Code").val() == '') {
                $("#ProdLoader > h3").empty().html(account_firstLang)
            } else if ($("#Depot_Loc").val() == '') {
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
            var Data = {
                id: $(this).val(),
                mode: IsSalesMode
            }
            $.ajax({
                url: "InventoryAjax/addPurchaseAjax",
                data: Data,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        if (IsSalesMode) {
                            $("#SupplierInfoContent").empty();
                            var Content = "";
                            Content += "<strong><span class='Name' id='Supplier_Name' data-id='" + Data[0]['Customer_Name'] + "'>" + Data[0]['Customer_Name'] + "</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>" + customer_vatLang + ": </strong><span class='Phone'>" + Data[0]['customer_vat'] + "</span></div>";
                            Content += "<div><strong>" + Customer_CRLang + ": </strong><span class='Phone'>" + Data[0]['Customer_CR'] + "</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>";
                            Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                            Content += "<div id='Class_ID' style='display:none;'>" + Data[0]['Class_ID'] + "</div>";
                            Content += "<div id='Class_Currency' style='display:none;'>" + Data[0]['Class_Currency'] + "</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'])
                            percent_flag = 1;
                            $("#pricing_class").val(Data[0]['Class_ID']);
                            $("#due_date_period").val(Data[0]['customer_due_date_period']);
                            updateDueDate(Data[0]['customer_due_date_period']);
                            $("#pricing_class").attr("data-select-name", Data[0]['Class_Name'])
                            build_select2($("#pricing_class"), "xhr/PricingClassSearch")
                            $("#pricing_class").trigger("change")
                            $("#pricing_class").trigger("select2-selecting")
                            //                            $("#CurrencyDropDown button span strong").html(Data[0]['Cur_Name'])
                            //                            $("#CurrencyDropDown button span strong").html(Data[0]['Cur_Name'] + ' - ' + Data[0]['Cur_Symbol'])
                            //                            $("#CurrencyDropDown button input").val(Data[0]['Class_Currency'])
                            //                            $(".CurrencyIndicator").html(Data[0]['Cur_Symbol'])
                        } else {
                            $("#SupplierInfoContent").empty();
                            var Content = "";
                            Content += "<strong><span class='Name' id='Supplier_Name' data-id='" + Data[0]['Supplier_Name'] + "'>" + Data[0]['Supplier_Name'] + "</span></strong>";
                            Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Supplier_Company'] + "</span></div>";
                            Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Supplier_Email'] + "</span></div>";
                            Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_Phone'] + "</span></div>";
                            Content += "<div><strong>" + customer_vatLang + ": </strong><span class='Phone'>" + Data[0]['supplier_vat'] + "</span></div>";
                            Content += "<div><strong>" + Customer_CRLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_CR'] + "</span></div>";

                            Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Supplier_Address'] + "</span></div>";
                            Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                            Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                            $("#SupplierInfoContent").html(Content)
                            $("#Supplier_ID-error").remove()
                            $("#Supplier_ID").removeClass("error").val(Data[0]['Supplier_ID']);
                            $("#due_date_period").val(Data[0]['supplier_due_date_period']);
                            updateDueDate(Data[0]['supplier_due_date_period'])
                        }
                    }
                }
            })
        })
        $("#CurrencyDropDown .dropdown-menu > li").on("click", function() {
            setTimeout(function() {
                UpdateTable()
            }, 300)
        })


        $("#Account_Code,#Depot_Loc").on("change", function() {
            var accName = $.trim($("#s2id_Account_Code").text());
            //alert($(this).val())
            $('#Account_CodeDiv').remove()
            var Content = "";
            if ($("#Account_Code").val() != 0) {
                Content += "<div id='Account_CodeDiv' value='" + $("#Account_Code").val() + "'><strong>" + accountCodeLang + ": </strong>" + accName + "</div>";
                $("#SupplierAccInfo").append(Content).removeClass('hidden')
            }
            if ($("#Account_Code").val() == '') {
                $("#ProdLoader > h3").empty().html(account_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else
            if ($("#search_supplier").val() == '') {
                $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
            } else if ($("#Depot_Loc").val() == '') {
                //                alert()
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
            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) {
                        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'] + "']"),
                                    tr_conv = parseFloat(me.attr("data-conv"));
                                me.find(".Quantity").next().text(AddCommas(public_round_number(parseFloat(value['qty'] / tr_conv))) + " in stock")
                                me.find("input.ProductName").next().text(value['loc'])
                                me.attr("data-qty", (value['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-is-lot') == 1 && activate_lot == 1)
                    $("input.lot_nb", $(this)).removeClass("hidden");
                else
                    $("input.lot_nb", $(this)).addClass("hidden");

                if ($(this).attr('data-is-serial') == 1 && activate_serial == 1)
                    $("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"));
        }
        $("#PurchaseInvoiceDueDate,#PurchaseInvoiceDate,.check_due_date").datepicker({
            autoclose: true
        });
        $('#PurchaseInvoiceDate').on("changeDate", function(e) {
            updateDueDate($('#due_date_period').val());
        });
        $("#InventoryPurchaseTable tbody").on("keyup", ".vat_percent,.VATPerItem", function(e) {
            var cur_tr_vat = public_round_number(parseFloat($(this).val())) || 0,
                cur_tr_total = public_round_number(parseFloat($(this).parents("tr").find(".Total").attr("myval"))) || 0;
            if ($(this).hasClass("vat_percent")) {
                var cur_val = public_round_number(cur_tr_total * cur_tr_vat / 100);

                $(this).parents("tr").find(".VATPerItem").val(cur_val ? cur_val : '')
                setTimeout("UpdateTable()", 100);
            } else {
                var cur_val = public_round_number(cur_tr_vat / cur_tr_total * 100);
                $(this).parents("tr").find(".vat_percent").val(cur_val ? cur_val : '')
                $(this).parents("tr").find(".vat_percent").trigger("keyup")
            }
        })
        $("#InventoryPurchaseTable").delegate(".Quantity,.n_height,.n_width,.UnitPrice,.Disc,.from_time,.to_time", "blur keydown", function(e) {
            is_td_total = 0;
            var me = $(this),
                TR = me.parents("tr"),
                n_height = TR.find('input.n_height').val(),
                n_width = TR.find('input.n_width').val(),
                n_Quantity= TR.find('input.Quantity').val(),
                n_total,
                from_time = TR.find('input.from_time').val(),
                to_time = TR.find('input.to_time').val();
            var TimeDiff;

            n_total = round_number(n_width*n_height*n_Quantity);
            n_total = Math.round((n_total + Number.EPSILON) * 100) / 100
            TR.find('input.n_total').val(n_total);

            //            console.log(me)
            //            console.log(e)
            setTimeout("UpdateTable()", 100);
            if (e.which == 13 && e.type == "keydown") {
                if (me.hasClass("Quantity")) {
                    TR.find(".UnitPrice").focus()
                } else if (me.hasClass("UnitPrice")) {
                    TR.find(".Disc").focus()
                } else {
                    TR.next().find(".CODE").focus()
                }
            }
            if (TR.index() < $("#InventoryPurchaseTable tbody").children().length - 1) {
                if ($.trim(me.val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null) {
                    me.addClass("wrong")
                } else {
                    me.removeClass("wrong")
                }
            }
            if (from_time != '' && to_time != '') {

                console.log('from_time')
                console.log(from_time)
                console.log('to_time')
                console.log(to_time)
                var timeStart = new Date("01/01/2007 " + from_time);
                var timeEnd = new Date("01/01/2007 " + to_time);

                if (timeStart < timeEnd) {
                    TR.find(".from_time").removeClass("wrong")
                    TR.find(".to_time").removeClass("wrong")
                    $('#wrong_time').html('')

                    var difference = timeEnd - timeStart;
                    difference = difference / 60 / 60 / 1000;
                    console.log('difference')
                    console.log(difference)
                    TR.find(".Quantity").val(difference).trigger("keyup")

                } else if (timeStart > timeEnd) {
                    $('#wrong_time').html(wrong_time)
                }
            }

            if (IsSalesMode) {
                if (me.hasClass("Quantity")) {
                    if (parseFloat(me.val()) > parseFloat(TR.attr('data-qty'))) {
                        me.addClass("wrong")
                    }
                }
                //                else
                //                if (me.hasClass("Disc")) {
                //                    if (parseFloat($(this).val()) > parseFloat(me.parents("tr").attr("data-disc"))) {
                //                        $(this).val(me.parents("tr").attr("data-disc"))
                //                    }
                //                }
                if (me.hasClass("Disc")) {
                    var item_disc = parseFloat(TR.attr('data-item-disc'));
                    check_discount(me, item_disc)
                    //                    if (item_disc > 0) {
                    //                        if (parseFloat(me.val()) > Math.min(parseFloat(max_discount), item_disc))
                    //                            $(this).val(Math.min(parseFloat(max_discount), item_disc))
                    //                        else if (parseFloat(me.val()) > parseFloat(max_discount))
                    //                            $(this).val(parseFloat(max_discount))
                    //                    }
                    //                    if (parseFloat(me.val()) > parseFloat(max_discount)) {
                    //                        me.addClass("wrong")
                    //
                    //                    }
                }
            }
            //            $("#InvoiceDiscountInput").trigger("keyup")
        });
        if (IsEditMode || is_qto || is_revision)
            UpdateTable(); //$(".Quantity").trigger('keydown')
        $("#InvoiceDiscountInput").on(" keyup", function() {
            //            if (percent_flag != 2) {
            percent_flag = 1;
            check_discount($(this), max_discount)
            $("#TotalDiscAmount").val(public_round_number(TotalInvoice * (parseFloat($(this).val()) / 100)) || 0)
            setTimeout("UpdateTable()", 100)
            //            }
        })
        $("#Shipping,#TotalDiscAmount").on("keyup", function() {
            if ($(this).attr("id") == 'TotalDiscAmount') {
                percent_flag = 2;
                //                check_discount($("#InvoiceDiscountInput"), max_discount)
                if (parseFloat($(this).val()) > (TotalInvoice * max_discount / 100))
                    $(this).val(public_round_number(TotalInvoice * max_discount / 100))
                $("#InvoiceDiscountInput").val(public_round_number(parseFloat($(this).val()) / TotalInvoice * 100) || 0)
                //                }
            }
            setTimeout("UpdateTable()", 100)
        })
        $("#InventoryPurchaseTable tbody").delegate("> tr input", "keydown", function(e) {
            is_td_total = 0;
            CheckSubmit = false;
            var me = $(this)
            if (e.which == 8) {
                if (me.val() == "" && !me.hasClass("CODE")) {
                    me.parents("td").prev().find("input").focus()
                } else if (me.val() == "" && me.hasClass("CODE")) {
                    if (me.parents("tr").prev()) {
                        me.parents("tr").prev().find(".Disc").focus()
                    }
                }
            }
        })
        $("#InventoryPurchaseTable tbody").delegate("> tr input:not(.AutoComplete,.ttc_price )", "keyup", function(e) {
            is_td_total = 0;
            //        if($(this).hasClass("total-td"))
            //            return;
            //        console.log('here')
            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;
            })
            //            console.log(IsLastOneEmpty)
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                ClonedRow.find("input").val("")
                ClonedRow.attr("data-conv", "1")
                ClonedRow.attr("data-last-price", "0")
                ClonedRow.attr("data-last-cost", "0")
                ClonedRow.attr("data-entry", "0")
                Parent.append(ClonedRow);
                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')
                //                $(".Hint", ClonedRow).html("")
                $("input", ClonedRow).removeClass("wrong")
                $("input.lot_nb,input.serial_nb", ClonedRow).addClass("hidden")
                $(".select2-container", ClonedRow).empty().remove()
                $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
                $(".item_driver_id", ClonedRow).empty().html($("#select_item_driver").html()).show().select2()
                ClonedRow.removeAttr("data-id data-prod-status")
                build_select2($("input.supp-class", ClonedRow), "xhr/PricingClassSearch?type=1", false, 'diff_class')
                $(".select2-container", ClonedRow).show()
                //                $(".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()
                //				setTimeout("openmodal()",800)
            }
        })
        $("#CurrencyDropDown li").click(function() {
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            global_round = $(this).attr("data-round")
            if ($(this).attr("value") == local_currency) {
                $("#current_rate").val(1).attr("disabled", "disabled")
            } else
                $("#current_rate").val("").removeAttr("disabled")
            cur_id = $(this).attr("value");
            $("#InventoryPurchaseTable tbody tr").each(function() {
                if ($(this).attr("data-id") != '' && $(this).attr("data-id") != undefined) {
                    var last_cost = ConvertCurrency2(parseFloat($(this).attr("data-last-cost") || 0), local_currency, cur_id),
                        last_price = ConvertCurrency2(parseFloat($(this).attr("data-last-price") || 0), local_currency, cur_id);
                    var unit_price_hint_text = '';
                    if (has_sales_last_price && IsSalesMode)
                        unit_price_hint_text += "Price: " + (!last_price ? "0" : AddCommas(public_round_number(parseFloat(last_price))));
                    if (has_sales_cost_perm)
                        unit_price_hint_text += (unit_price_hint_text == '' ? '' : ' | ') + "Cost: " + (!last_cost ? "0" : AddCommas(parseFloat(public_round_number(last_cost))));
                    $(this).find("input.UnitPrice").next().text(unit_price_hint_text).attr('title', unit_price_hint_text);
                }
            })
            setTimeout("UpdateSubmitButtonStatus()", 100)
        })
        var Def = $("#CurrencyDropDown li").filter(function() {
            return $(this).attr("value") == $("#CurrencyDropDown input").val()
        })
        if (Def.length > 0) {
            $(".CurrencyIndicator").html(Def.attr("MySymbol"))
            $("> button > span", $("#CurrencyDropDown")).html(Def.text())
        }
        $("#InvoiceForm").validate({
            ignore: ".ignore",
            rules: {
                PurchaseInvoiceDate: {
                    required: true,
                    date: true
                },
                PurchaseInvoiceDueDate: {
                    date: true
                }
            }
        })
        $("#InvoiceSubmitButton").on("click", ApplyPostMethod);
        UpdateSubmitButtonStatus()
        $("#InventoryPurchaseTable").on("input", ".ttc_price ", function() {
            var myval = parseFloat($(this).val()) || 0,
                mytr = $(this).parents("tr"),
                //                    myqty = parseFloat(mytr.find(".Quantity").val()) || 0,
                vat_percent = parseFloat(mytr.find(".vat_percent").val()) || 0,
                vat_amount = myval * (vat_percent / 100) / (1 + (vat_percent / 100)),
                amt_no_vat = myval - vat_amount,
                disc_percent = parseFloat(mytr.find(".Disc").val()) || 0,
                unit_amt = amt_no_vat * (1 + (disc_percent / 100));
            //                    (myval*(1-(disc_percent/100))+(vat_percent/100))+myval
            mytr.find(".VATPerItem").val(public_round_number(vat_amount))
            $(this).attr("MyVal", myval)
            is_td_total = 1;
            //            console.log((myval-vat_amount))
            mytr.find(".UnitPrice").val(myval - vat_amount) //.trigger("keydown")
            UpdateTable()
        })

        $("#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() {
            //            if (checkPrintDisbaled())
            //                return;
            $(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 tagPr = parseFloat($(this).parents('.mylabel').attr('data-price') || 0),
                item = $(this).parents("tr").attr("data-ref"),
                singlePr = parseFloat($(this).parents("tr").find('.UnitPrice').val()) || 0,
                //curPr = parseFloat($(this).parents("tr").find("span.price").attr("curprice")),
                Parent = $(this).parents("tr"),
                qty = parseFloat(Parent.find('input.Quantity').val()) || 0,
                vat_amount = parseFloat(Parent.find('input.VATPerItem').val()) || 0,
                vat2_amount = parseFloat(Parent.find('input.vat2_amount').val()) || 0,
                single_vat_amount = qty == 0 ? 0 : ((vat_amount + vat2_amount) / qty),
                vat_percent = parseFloat(Parent.find('input.vat_percent').val()) || 0,
                vat2_percent = parseFloat(Parent.find('input.vat2_percent').val()) || 0,
                removed_vat2_tag = tagPr * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                removed_vat_tag = (tagPr - removed_vat2_tag) * (vat_percent / 100) / (1 + (vat_percent / 100));
            //            var finalCur = parseFloat(curPr),
            var checked_price;
            //            console.log(is_ttc+'============')
            if (is_ttc == 1)
                checked_price = (singlePr - tagPr + removed_vat_tag + removed_vat2_tag) < 0 ? 0 : (singlePr - tagPr + removed_vat_tag + removed_vat2_tag);
            else
                checked_price = (singlePr - tagPr) < 0 ? 0 : (singlePr - tagPr);
            //$(this).parents("tr").find("span.price").attr("curprice", finalCur)
            $(this).parents("tr").find("input.UnitPrice").val(checked_price)
            //$(this).parents("tr").attr("data-price-single",(singlePr-tagPr))
            var ttc_checked_price = checked_price;
            if (is_ttc == 1)
                ttc_checked_price += (single_vat_amount - removed_vat_tag - removed_vat2_tag);
            $(this).parents("tr").find('input.ttc_price').val(ttc_checked_price);

            //delete ItemTags[item].types_arr[$(this).parents("span.tag").attr("data-type")]
            $(this).parents("span.tag").remove()
            UpdateTable()
            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: $("#CurrencyDropDown input").val(),
            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() {
        //        console.log('here')
        var item = $("#tagsModal").attr("data-id");
        //        ItemTags[item] = {Item_ID: item, types_arr: []};
        var tr = $("#InventoryPurchaseTable tbody tr:eq(" + item + ")"),
            total_tr_tag = parseFloat(tr.find('input.UnitPrice').val()) || 0,
            vat_percent = parseFloat(tr.find('input.vat_percent').val()) || 0,
            vat2_percent = parseFloat(tr.find('input.vat2_percent').val()) || 0,
            qty = parseFloat(tr.find('input.Quantity').val()) || 0;
        var total_removed_tag_vat = 0;
        //        console.log($(".mylabel", tr))
        $(".mylabel", tr).each(function() {
            //            console.log('heree')
            var tag_price = parseFloat($(this).attr("data-price") || 0),
                tag_vat2 = tag_price * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                tag_vat = (tag_price - tag_vat2) * (vat_percent / 100) / (1 + (vat_percent / 100));
            //               console.log('tag-vat:'+tag_vat)
            total_tr_tag -= (is_ttc == 1 ? (tag_price - tag_vat - tag_vat2) : tag_price);
            total_removed_tag_vat += (tag_vat + tag_vat2);
            //            console.log(tag_vat + '===' + tag_vat2 + '===' + total_removed_tag_vat)
        });
        var totalTRPrice = total_tr_tag < 0 ? 0 : total_tr_tag
        tr.find('input.UnitPrice').val(totalTRPrice)
        $("#InventoryPurchaseTable tbody tr:eq(" + item + ") div.bootstrap-tagsinput").empty();
        //var totalTRPrice = parseFloat($("#OrderTable tbody tr[data-ref=" + item + "]").attr("data-price-single"));
        var total_added_tag_vat = 0,
            row_title = '';
        $("#tagsModal .criteria-detail-div input:checked").each(function() {
            var tag_name = $(this).attr("tag-name"),
                tag_price = parseFloat($(this).attr("tag-price") || 0),
                entry = $(this).val(),
                criteria_id = $(this).attr("data-criteria-id"),
                note = $(this).parents("tr").find(".tag-note").val(),
                vat_tag2 = tag_price * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                vat_tag = (tag_price - vat_tag2) * (vat_percent / 100) / (1 + (vat_percent / 100));


            total_added_tag_vat += (vat_tag + vat_tag2);
            totalTRPrice += (is_ttc == 1 ? (parseFloat(tag_price - vat_tag - vat_tag2)) : parseFloat(tag_price));
            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-price="' + tag_price + '" 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)
        $("#InventoryPurchaseTable tbody tr:eq(" + item + ") .UnitPrice").val(totalTRPrice);
        var vat_amount = parseFloat($("#InventoryPurchaseTable tbody tr:eq(" + item + ") .VATPerItem").val() || 0);

        vat_amount += parseFloat($("#InventoryPurchaseTable tbody tr:eq(" + item + ") .vat2_amount").val() || 0);
        var single_vat_amount = qty == 0 ? 0 : (vat_amount / qty);
        //        console.log(vat_amount + '====' + total_added_tag_vat)
        //we need to subtract remove tag vat amount since vat-amount on tr include the tag vat
        single_vat_amount -= total_removed_tag_vat;
        var ttc_single = is_ttc == 1 ? (totalTRPrice + single_vat_amount + total_added_tag_vat) : totalTRPrice;
        $("#InventoryPurchaseTable tbody tr:eq(" + item + ") .ttc_price").val(ttc_single);
        UpdateTable()
        $("#tagsModal").modal("hide")
    }

    function searchScannedItem(barcode, TR) {
        var get_parameters = 'Status_ID=1&barcode=' + barcode + '&depot_id=' + $('#Depot_Loc').val();
        if (IsSalesMode) {
            get_parameters += '&type=1&class_id=' + $("#pricing_class").val() + '&customer_id=' + $(".search_supplier").val();
        } else {
            get_parameters += '&type=2';
        }
        $.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-vat", (is_actual ? 0 : Data.VAT))
                    TR.attr("data-qty", Data.stock_qty)
                    TR.attr("data-last-price", Data.last_price)
                    TR.attr("data-last-cost", Data.last_cost)
                    TR.find("input.CODE").val(Data.Bar_Code)
                    TR.attr("data-prod-status", Data.Status_ID)
                    TR.find("input.ProductName").val(Data.Name)
                    TR.find("input.vat_percent").val((Data.VAT == 1 && !is_actual) ? Data.vat_percent : 0)
                    TR.find("input.VATPerItem").val('0')

                    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>')
                    }
                    $("select[name=UOM_ID]", TR).select2();
                    if (display_shelf_locations == 1) {
                        TR.find("input.ProductName").next().text(Data.loc);
                    }
                    if (event.which != 9)
                        TR.find("input.Quantity").focus().next().text(AddCommas(public_round_number(parseFloat(Data.stock_qty))) + " in stock")
                    else
                        TR.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(Data.stock_qty))) + " in stock")
                    if (IsSalesMode) {
                        TR.attr("data-item-disc", Data.Product_Limit_Discount)
                        TR.attr("data-tax", Data.is_tax)
                        check_discount(TR.find(".Disc"), parseFloat(Data.Product_Limit_Discount))

                        if (Data.VAT == 0 || is_actual) {
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                        } else {
                            TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                        }
                        TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data.Price : public_round_number(ConvertCurrency2(Data.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))
                        var unit_price_hint_text = '';
                        if (has_sales_last_price)
                            unit_price_hint_text += "Price: " + (!Data.last_price ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(Data.last_price, local_currency, $("#CurrencyDropDown input").val())))));
                        if (has_sales_cost_perm)
                            unit_price_hint_text += (unit_price_hint_text == '' ? '' : ' | ') + "Cost: " + (!Data.last_cost ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(Data.last_cost, local_currency, $("#CurrencyDropDown input").val())))));
                        TR.find("input.UnitPrice").next().text(unit_price_hint_text).attr('title', unit_price_hint_text);

                        //                        if (has_sales_cost_perm) {
                        //                            TR.find("input.UnitPrice").next().text("last cost: " + (!Data.last_cost ? "0" : AddCommas(parseFloat(ConvertCurrency2(Data.last_cost, local_currency, $("#CurrencyDropDown input").val())).toXFixed(3))));
                        //                        }
                        //                        if (has_sales_last_price) {
                        //                            TR.find("input.UnitPrice").next().text("last price: " + (!Data.last_price ? "0" : AddCommas(parseFloat(ConvertCurrency2(Data.last_price, local_currency, $("#CurrencyDropDown input").val())).toXFixed(3))));
                        //                        }
                        TR.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(Data.stock_qty))) + " in stock")
                    } else {
                        if ((Data.VAT == 0 || allow_purchase_vat_edit || is_actual) && has_vat_permission)
                            TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                        else
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                        if (has_purchase_cost_perm) {
                            TR.find("input.UnitPrice").next().text("last cost: " + (!Data.last_cost ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(Data.last_cost, local_currency, $("#CurrencyDropDown input").val()))))));
                        }
                        //                        TR.find("input.Quantity")/*.focus()*/.prev().text((Data.Quantity) + " in stock");
                    }
                    UpdateTable()
                    return false;
                }
            }
        })
    }

    function UpdateTable() {
        var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        vatVal = 0, totalvat = 0, taxAmount = 0, total_qty = 0;
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0, card_tax = 0
        $("#InventoryPurchaseTable tbody tr").each(function() {
            UpdateTotalForRow($(this))
        })
        if (IsSalesMode) {
            $("#card_tax").val(public_round_number(parseFloat(card_tax)))
        }
        //        console.log(percent_flag)
        if (percent_flag == 1)
            $("#TotalDiscAmount").val(public_round_number(TotalInvoice * parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
        if (percent_flag == 2) {
            $("#InvoiceDiscountInput").val(public_round_number(parseFloat($("#TotalDiscAmount").val()) / TotalInvoice * 100) || 0)
            if (parseFloat($("#InvoiceDiscountInput").val()) > 100) {
                $("#TotalDiscAmount").val('').trigger("keyup")
                $("#DiscountProceedModal").modal("show")
            }
        }
        var totalDiscountValue = public_round_number(parseFloat($("#TotalDiscAmount").val())) || 0;
        var TotalInvoiceDisounted = TotalInvoice - totalDiscountValue;
        setTimeout("UpdateSubmitButtonStatus()", 100)
        var ftotal = public_round_number(TotalInvoiceDisounted + totalvat + shipping + card_tax),
            finalTotal = 0;
        if (global_round > 0) {
            var roundTo = global_round,
                diff = ftotal % roundTo;
            var finalTotal = Math.floor(ftotal / roundTo);
            if (diff >= (roundTo / 2)) {
                finalTotal++;
            }
            finalTotal = finalTotal * roundTo;
        } else {
            finalTotal = ftotal;
        }
        $("#PurchaseInvoiceTotalDetails").attr({
            "MyValueNotDiscounted": public_round_number(TotalInvoice + shipping),
            "MyValueDiscounted": public_round_number(TotalInvoiceDisounted + totalvat + shipping + card_tax)
        }).text(AddCommas(public_round_number(finalTotal)))
        if ($("#current_rate").val() != '')
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(finalTotal * $("#current_rate").val()))))
        else
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(ConvertCurrency2(finalTotal, $("#CurrencyDropDown input").val(), local_currency)))))
    }

    function EnableAutoComplete(who) {
        if (IsSalesMode) {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function(request, response) {
                        //                        var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                        var classID = $("#pricing_class").val(),
                            supp_class = (who.parents('tr').find('input.supp-class').val() != '' ? who.parents('tr').find('input.supp-class').val() : $("#supplier_pricing_class").val()),
                            depot_id = $("#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=" + (IsSalesMode ? 1 : 0) + "&ClassID=" + classID + '&supp_class=' + supp_class + '&depot_id=' + depot_id + '&type=1&customer_id=' + customer_id + status_cond, request, function(s, status, xhr) {
                            response(s);
                            //                            getProducts
                        });
                    },
                    minLength: 0,
                    select: function(event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.ID)
                        var old_prod_id = TR.attr("data-id")
                        console.log(ui.item);
                        TR.attr("data-vat", (is_actual ? 0 : ui.item.VAT))
                        TR.attr("data-is-service", (ui.item.is_service))
                        TR.attr("data-qty", ui.item.Quantity)
                        TR.attr("data-item-disc", ui.item.Product_Limit_Discount)
                        TR.attr("data-prod-status", ui.item.Status_ID)
                        TR.attr("data-tax", ui.item.is_tax)
                        TR.attr("data-last-cost", ui.item.LAST_COST)
                        TR.attr("data-last-price", ui.item.last_price)
                        check_discount(TR.find(".Disc"), parseFloat(ui.item.Product_Limit_Discount))
                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.find("input.ProductName").val(ui.item.Name)
                        TR.find("input.person_code").val(ui.item.person_code)

                        TR.find("input.n_width").val(ui.item.n_width)
                        TR.find("input.n_height").val(ui.item.n_height)


                        TR.find("input.vat_percent").val((ui.item.VAT == 1 && !is_actual) ? ui.item.vat_percent : 0)
                        TR.find("input.VATPerItem").val('0')
                        TR.find("input.item-cost").val(ConvertCurrency2(ui.item.supp_cost, local_currency, $("#CurrencyDropDown input").val()))
                        TR.attr('data-supp-cost', ConvertCurrency2(ui.item.supp_cost, local_currency, $("#CurrencyDropDown input").val()))
                        TR.find("input.Disc").val(ui.item.disc)
                        //                        console.log(ui.item.supp_cost+'==='+local_currency+'===='+$("#CurrencyDropDown input").val())
                        if (ui.item.VAT == 0 || is_actual) {
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                        } else {
                            TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                        }
                        var tag_price = 0;
                        if (old_prod_id == ui.item.ID) {
                            //                            console.log(old_prod_id + '===' + ui.item.ID)

                            $(".mylabel", TR).each(function() {
                                var cur_price = parseFloat($(this).attr("data-price")) || 0;
                                //                                console.log(cur_price + '=====')
                                //                                        $(this).attr("data-price", tag_price)
                                tag_price += cur_price;
                            });
                        } else {
                            $(".mylabel", TR).remove()
                            TR.find('div.bootstrap-tagsinput').html('No Tags')
                        }
                        TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? (ui.item.Price + tag_price) : public_round_number(ConvertCurrency2(ui.item.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()) + tag_price))
                        $("select[name=UOM_ID]", TR).empty();
                        var unit_price_hint = '';
                        if (has_sales_cost_perm) {
                            unit_price_hint += "C: " + (!ui.item.LAST_COST ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val())))));
                        }
                        if (has_sales_last_price) {
                            unit_price_hint += " | P: " + (!ui.item.last_price ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.last_price, local_currency, $("#CurrencyDropDown input").val())))));
                        }
                        TR.find("input.UnitPrice").next().text(unit_price_hint);
                        if (display_shelf_locations == 1) {
                            TR.find("input.ProductName").next().text(ui.item.loc);
                        }
                        if (ui.item.is_lot == 1 && activate_lot == 1)
                            TR.find(".lot_nb").removeClass("hidden");
                        else
                            TR.find(".lot_nb").addClass("hidden");

                        if (ui.item.is_serial == 1 && activate_serial == 1)
                            TR.find(".serial_nb").removeClass("hidden");
                        else
                            TR.find(".serial_nb").addClass("hidden");

                        if (event.which != 9)
                            TR.find("input.Quantity").focus().next().text(AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock")
                        else
                            TR.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock")
                        TR.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock")
                        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();
                        UpdateTable()
                        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));
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }
        } else {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function(request, response) {
                        var depot_id = $("#Depot_Loc").val(),
                            customer_id = $("#search_supplier").val();

                        $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : (who.hasClass("person_code") ? "3" : "2")) + '&is_purchase=' + (IsSalesMode ? 0 : 1) + '&depot_id=' + depot_id + '&type=2' + '&customer_id=' + customer_id, request, function(s, status, xhr) {
                            response(s);
                        });
                    },
                    minLength: 0,
                    select: function(event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.ID)
                        TR.attr("data-vat", (is_actual ? 0 : ui.item.VAT))
                        TR.attr("data-qty", ui.item.Quantity)

                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.attr("data-last-cost", ui.item.LAST_COST)
                        TR.attr("data-last-price", ui.item.last_price)
                        TR.find("input.vat_percent").val((ui.item.VAT == 1 && !is_actual) ? ui.item.vat_percent : 0)
                        TR.find("input.VATPerItem").val('0')
                        if ((ui.item.VAT == 0 || allow_purchase_vat_edit || is_actual) && has_vat_permission)
                            TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                        else
                            //                        if (ui.item.VAT == 0) {
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disavled")
                        //                        }  {
                        //                            
                        //                        }
                        TR.find("input.ProductName").val(ui.item.Name)
                        TR.find("input.person_code").val(ui.item.person_code)


                        TR.find("input.n_width").val(ui.item.n_width)
                        TR.find("input.n_height").val(ui.item.n_height)

                        $("select[name=UOM_ID]", TR).empty();
                        if (auto_fill_cost == 1) {
                            TR.find("input.UnitPrice").val(public_round_number(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val()), 4))
                        }
                        if (auto_fill_cost == 0 && auto_fill_zerocost == 1) {
                            TR.find("input.UnitPrice").val('0')
                        }
                        if (has_purchase_cost_perm) {
                            TR.find("input.UnitPrice").next().text("last cost: " + (!ui.item.LAST_COST ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val()))))));
                        }
                        if (event.which != 9)
                            TR.find("input.Quantity").focus().next().text(AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock")
                        else
                            TR.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock")
                        if (display_shelf_locations == 1) {
                            TR.find("input.ProductName").next().text(ui.item.loc);
                        }
                        if (ui.item.is_lot == 1 && activate_lot == 1)
                            TR.find(".lot_nb").removeClass("hidden");
                        else
                            TR.find(".lot_nb").addClass("hidden");

                        if (ui.item.is_serial == 1 && activate_serial == 1)
                            TR.find(".serial_nb").removeClass("hidden");
                        else
                            TR.find(".serial_nb").addClass("hidden");
                        //                        TR.find("input.Quantity")/*.focus()*/.prev().text((ui.item.Quantity) + " in stock");
                        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>')
                        }
                        $("select[name=UOM_ID]", TR).select2()
                        UpdateTable()
                        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));
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }
        }
        //        textarea can't remove character when used backspace
        //        $(document).keydown(function (e) {
        //            if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
        //                e.preventDefault()
        //            }
        //        })
    }

    function ApplyPostMethod() {
        $("#PurchaseSuccess").attr("class", "hidden");
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                Data = {
                    Depot_ID: $("#Depot_Loc").val(),
                    Invoice_VAT: $("#InvoiceVAT").html().replace(/,/g, ""),
                    CurrencySymbole: $(".CurrencyIndicator").html(),
                    IsSales: IsSalesMode ? 1 : 0,
                    is_quotation: IsQuotation,
                    is_qto: is_qto,
                    discount_amount: $("#TotalDiscAmount").val(),
                    order_delivery_date: $("#delivery_date").val(),
                    is_actual: is_actual ? 1 : 0,
                    Invoice_Currency_Rate: $("#current_rate").val(),
                    Invoice_Description: $("#invoice_note").val(),
                    po: $('#po').val(),
                    project_name_inv: $('#project_name_inv').val(),
                    project_code: $('#project_code').val(),
                    job_inv: $('#job_inv').val(),
                    our_ref: $('#our_ref').val(),
                    supply_date: $('#supply_date').val(),
                    driver_id: $('#driver_id').val(),
                    to_place: $('#to_place').val(),
                    from_place: $('#from_place').val(),
                    job_id: $("#job_id").val(),
                    project_id: $("#project_id").val(),
                    unique_id: unique_id,
                    extra_cost: $("#extra_cost").val(),
                    postponed_status_id: $("#postponed_status_id").val(),
                    postponed_date_time: $("#postponed_date_time").val(),
                    postponed_note: $("#postponed_note").val(),
                    customer_name_alias: $("#customer_name_alias").val(),
                    customer_address_alias: $("#customer_address_alias").val(),
                    shipping: $("#Shipping").val(),
                    current_invoice_type: $("#current_invoice_type").val(),
                    Products: []
                };
            Data.Customer_ID = $("#Supplier_ID").val();
            Data.Customer_Name = $("#Supplier_Name").attr("data-id")
            Data.Invoice_Date = $("#PurchaseInvoiceDate").val();
            Data.Invoice_Due_Date = $("#PurchaseInvoiceDueDate").val() ? $("#PurchaseInvoiceDueDate").val() : $("#PurchaseInvoiceDate").val();
            Data.Invoice_Currency = $("#CurrencyDropDown input").val();
            Data.Invoice_Discount = $("#InvoiceDiscountInput").val();
            Data.Invoice_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
            Data.Invoice_Sub_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
            Data.Class_ID = $("#pricing_class").val();
            Data.supp_class_id = $("#supplier_pricing_class").val();
            //            if (IsSalesMode) {
            //
            //                Data.products = [];
            //            } else {
            //                Data.Supplier_Invoice_ID = $("#Supplier_Invoice").val();
            //                Data.Supplier_ID = $("#Supplier_ID").val();
            //                Data.Supplier_Name = $("#Supplier_Name").attr("data-id")
            //                Data.Purchase_Date = $("#PurchaseInvoiceDate").val();
            //                Data.Purchase_Due_Date = $("#PurchaseInvoiceDueDate").val() ? $("#PurchaseInvoiceDueDate").val() : $("#PurchaseInvoiceDate").val();
            //                Data.Currency_ID = $("#CurrencyDropDown input").val();
            //                Data.Purchase_Discount = $("#InvoiceDiscountInput").val();
            //                Data.Purchase_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
            //                Data.Purchase_Sub_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
            //                Data.total_qty = total_qty;
            //            }
            if (IsEditMode) {
                Data.ID_Auto = ID_Edit;
            }
            if (is_qto) {
                Data.quotation_id = ID_Edit;
            }
            var total_cost = 0,
                is_negative_value = false;
            $("#InventoryPurchaseTable tbody tr").each(function(e) {
                var me = $(this);
                var qty = parseFloat(me.find(".Quantity").val() || 0);
                total_cost += (parseFloat(me.find("input.item-cost").val() || 0) * qty);
                total_cost += (parseFloat(me.find("input.item-other-cost").val() || 0) * qty);
                //                if (e < $(this).parent().children().length - 1) {
                var 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_price: $(this).attr("data-price"),
                        criteria_note: $(this).attr("data-note") || ''
                    });
                });
                if (me.find(".Quantity").val() != '' && me.find(".Quantity").val() != 0 && me.find(".ProductName").val() != '' && me.find('.UnitPrice').val() != '') {
                    Data.Products.push({
                        UOM_ID: me.find("select.UOM_ID").val(),
                        Product_ID: me.attr("data-id"),
                        Product_Code: me.find(".CODE").val(),
                        Product_Name: me.find(".ProductName").val(),
                        Item_Quantity: me.find(".Quantity").val(),
                        Item_Price: me.find(".UnitPrice").val(),
                        Currency_ID: $("#CurrencyDropDown input").val(),
                        Item_Discount: me.find(".Disc").val(),
                        vat_percent: me.find("input.vat_percent").val() || 0,
                        vat_val: me.find("input.VATPerItem ").val() || 0,
                        Product_Total_Price: me.find(".Total").attr("myval"),
                        product_description: me.find(".item_note").val(),

                        from_time: me.find(".from_time").val(),
                        to_time: me.find(".to_time").val(),
                        modify_date: me.find(".modify_date").val(),
                        driver_id: me.find("select.item_driver_id").val(),

                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        class_id: $("input.supp-class", me).val(),
                        item_cost: $("input.item-cost", me).val() || 0,
                        other_cost: $("input.item-other-cost", me).val() || 0,
                        entry_id: me.attr("data-entry") || 0,
                        criteria_details: tags,
                        n_total : me.find("input.n_total").val(),
                        n_width: me.find("input.n_width").val(),
                        n_height: me.find("input.n_height").val(),

                    });
                    //                    }
                    me.find(".ProductName,.Quantity,.UnitPrice").each(function() {
                        if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                            $(this).addClass("wrong")
                            CheckSubmit = false;
                            IsValidated = false;
                        } else {
                            $(this).removeClass("wrong")
                        }
                    })
                    //                    console.log('data-id:'+me.attr("data-id")+'==uom'+me.find("select.UOM_ID").val())
                    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 (parseFloat($("input.Disc ", me).val()) < 0 ||
                        parseFloat($("input.vat_percent ", me).val()) < 0 || ($.trim($('input.Disc', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.Disc', me).val() != '' && $('input.Disc', me).val() != 0) || ($.trim($('input.vat_percent', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.vat_percent', me).val() != '' && $('input.vat_percent', me).val() != 0)) {
                        is_negative_value = true;
                    }

                }
            })
            Data.total_cost = total_cost;
            if (!IsValidated)
                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;
            }
            if ($('#PurchaseInvoiceDueDate').val() < $('#PurchaseInvoiceDate').val()) {
                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('duedate_greater_currentdate'); ?>');
                $(document.body).animate({
                    scrollTop: 0
                }, 800)
                return;
            }

            $("#PurchaseDisabler").show();
            $.ajax({
                url: IsEditMode ? "InventoryAjax/editPurchaseOrderAjax" : "InventoryAjax/purchaseOrderAjax",
                method: "POST",
                data: Data,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            //                            if (!IsEditMode) {
                            ID_Edit = v1.responseJSON[1];
                            $("#PrintBtn,#go_invoice_btn,.check_temp_key").removeClass("disabled")
                            //                            }
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[2] + '</strong>')
                            $("#InvoiceSubmitButton").attr("disabled", "disabled")
                            CheckSubmit = true;
                        } else {
                            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])
                            CheckSubmit = false;
                        }
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        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 UpdateTotalForRow(who) {
        //        alert(who.attr('data-vat'))
        var Single_Price = parseFloat(who.find(".UnitPrice").val()) || 0,
            Qty = parseFloat(who.find(".Quantity").val()) || 0,
            Total = Single_Price * Qty,
            Discount = parseFloat(who.find(".Disc").val()) || 0,
            Net_Total = (Total * (1 - Discount / 100)) || 0,
            net_total_with_invdisc = Net_Total * (1 - parseFloat($("#InvoiceDiscountInput").val() || 0) / 100);
        if (IsSalesMode) {
            var ctax = who.attr("data-tax") == 1 ? Qty * parseFloat($("#card_tax").attr("data-tax") || 0) : 0;
            card_tax += ctax
            //            console.log(Qty +'*'+ parseFloat($("#card_tax").attr("data-tax")))
        }
        TotalInvoiceWithoutDiscount += Total;
        TotalDiscount += Discount;
        TotalInvoice += Net_Total;
        total_qty += Qty;
        who.attr('Unit_Price', Single_Price)
        var tr_vat_percent = (who.attr('data-vat') == 1 || (allow_purchase_vat_edit && !IsSalesMode)) ? (parseFloat(who.find("input.vat_percent").val()) || 0) : 0,
            TRvalue = (((who.attr('data-vat') == 1) || (allow_purchase_vat_edit && !IsSalesMode)) && tr_vat_percent > 0) ? (parseFloat(net_total_with_invdisc)) : 0;
        //        if ( Qty != 0) {
        //        console.log(TRvalue + "*" + tr_vat_percent + "/100=" + (TRvalue * tr_vat_percent / 100))
        vatVal = (TRvalue * tr_vat_percent / 100) || 0;
        totalvat += vatVal;
        taxAmount += TRvalue;
        //        who.find(".Total").attr("MyVal", net_total_with_invdisc.toXFixed(3)).text(AddCommas((net_total_with_invdisc + vatVal).toXFixed(3)))
        if (is_td_total == 0) {
            var ttc_price = public_round_number(Single_Price * (1 + (tr_vat_percent / 100)));
            who.find('.ttc_price').val(ttc_price > 0 ? ttc_price : '')
        }
        var mytdtotal = public_round_number(net_total_with_invdisc + vatVal);
        who.find(".Total").attr("MyVal", public_round_number(net_total_with_invdisc)).html(mytdtotal)
        //        }
        //alert(totalvat)
        who.find('.VATPerItem').val(public_round_number(vatVal) > 0 ? public_round_number(vatVal) : '');
        $('#PurchaseTaxableAmount').html(AddCommas(public_round_number(taxAmount)))
        $("#InvoiceVAT").html(AddCommas(public_round_number(totalvat)))
        //        }
        //        else{
        //            who.find('.VATPerItem').val('0')
        ////            $('#PurchaseTaxableAmount').html(AddCommas(taxAmount))
        ////            $("#InvoiceVAT").html(AddCommas(totalvat.toXFixed(3)))
        //        }
    }

    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()) != "" && $.trim($("input.UnitPrice", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }
        if ($.trim($("#CurrencyDropDown > button > input").val()) == "")
            DoDisable = true;
        if (IsSalesMode) {
            $("#InventoryPurchaseTable tbody tr").each(function() {

                if (negative_sales == 0 && $(this).attr("data-is-service") == 0) {
                    if (parseFloat($(this).find(".Quantity").val()) > parseFloat($(this).attr('data-qty'))) {
                        DoDisable = true;
                    }
                }
                if (parseFloat($(this).find(".Disc").val()) > parseFloat(max_discount)) {
                    DoDisable = true;
                }
            })
        }
        // document.title = Rows.length
        if (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }
    //    $("#SubmitExpiry").on("click", function () {
    //
    //
    //        var Data = {
    //            Product_ID: $("#Product_ID").val(),
    //            type: IsSalesMode ? 2 : 1,
    //            Unit_Cost: IsSalesMode ? 0 : $("#Unit_Price").val(),
    //            Depot_ID: $("select.Depot_Loc").val(),
    //            Category_ID: $("#Category_ID").val(),
    //            Currency_ID: IsSalesMode ? 0 : $("#CurrencyDropDown input").val(),
    //            Expiry: []
    //        }
    //
    //        $("#Add > .AddRow").each(function () {
    //            var me = $(this);
    //            Data.Expiry.push({
    //                Expiry_Date: me.find(".Product_ExpiryDate").val(),
    //                Product_Quantity: me.find(".Product_Quantity").val()
    //
    //            })
    //
    //
    //        })
    //
    //        $.ajax({
    //            url: "InventoryAjax/addPurchaseAjax",
    //            method: "POST",
    //            data: Data,
    //            complete: function (v1, v2) {
    //                if (v2 == "success" && v1.responseText == "OK") {
    //
    //
    //                    $("#ExpirySuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
    //
    //                    setTimeout(function () {
    //                        $("#add_Expiry").modal('hide')
    //                        $("#ExpirySuccess").addClass('hidden')
    //                        $('.AddRow').not('div:first').remove()
    //                        $('.AddRow > .fa-minus-circle').not('div:first').css("display", "none")
    //                    }, 800)
    //
    //
    //                } else {
    //                    $("#ExpirySuccess").attr("class", "alert alert-danger").html(Failed_Submit)
    //                }
    //
    //            }
    //        })
    //        $('#Add  input').val('')
    //
    //
    //
    //    })
    //    $("#Closemodal").on("click", function () {
    //        $('#add_Expiry').modal('hide')
    //        $('.AddRow').not('div:first').remove()
    //        $('.AddRow > .fa-minus-circle').not('div:first').css("display", "none")
    //        $('#Add  input').val('')
    //
    //
    //
    //    })
    //    function printExternalInv(url) {
    //        $("#print_iframe").remove();
    //        $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:800px;height:800px;display:none;' src='" + url + "' onload='document.getElementById(\"print_iframe\").contentWindow.print();'  ></iframe>").appendTo("body");
    //
    //
    //    }
    $(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 printExternalInv(url, btn_id) {
        $("#print_iframe").remove();
        $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:800px;height:800px;display:none;' src='" + url + "' onload='document.getElementById(\"print_iframe\").contentWindow.document.getElementById(\"" + btn_id + "\").click();'  ></iframe>").appendTo("body");
    }

    function check_discount(me, item_disc) {
        if (item_disc > 0 || ignore_zero_item_disc != 1) {
            if (parseFloat(me.val()) > Math.min(parseFloat(max_discount), item_disc))
                me.val(Math.min(parseFloat(max_discount), item_disc))
        } else if (parseFloat(me.val()) > parseFloat(max_discount))
            me.val(parseFloat(max_discount))
    }

    function updateDueDate(nb_days) {
        if (nb_days && nb_days != 0 && $('#PurchaseInvoiceDate').val()) {
            var date2 = $('#PurchaseInvoiceDate').datepicker('getDate');
            date2.setDate(date2.getDate() + parseInt(nb_days));
            $('#PurchaseInvoiceDueDate').datepicker('setDate', date2);
        }
    }

    function empty_row(ClonedRow) {
        ClonedRow.find("input").val("")
        ClonedRow.attr("data-conv", "1")
        ClonedRow.removeAttr("data-id")
        ClonedRow.attr("data-expiry", "0")
        ClonedRow.attr("data-last-price", "0")
        ClonedRow.attr("data-last-cost", "0")
        ClonedRow.attr("data-delivery-cost", "0")
        ClonedRow.attr("data-entry", "0")
        ClonedRow.attr("data-delivery-id", "0")
        ClonedRow.attr("data-cost", "0")
        ClonedRow.attr("data-is-service", "0")
        ClonedRow.attr("data-is-option", "0")
        ClonedRow.attr("recipe-qty", "")
        ClonedRow.attr("data-ref", "")
        $(".option-tr", $(ClonedRow)).addClass("hidden")

        $(".Hint,.Total", ClonedRow).html("")
        ClonedRow.find(".mylabel").remove()
        ClonedRow.find('div.bootstrap-tagsinput').html('No Tags')
        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")
        $(".select2-container.UOM_ID", ClonedRow).empty().remove()
        $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2();
        $(".item_driver_id", ClonedRow).empty().html($("#select_item_driver").html()).show().select2()
        //        build_select2($("input.item-class", ClonedRow), "xhr/PricingClassSearch?type=1")

        //        $(".UOM_ID", ClonedRow).select2();
        ClonedRow.find("input.expiry_date,input[name=current_depot_id],input[name=current_vehicle_id],input[name=current_employee_id]").attr('data-select-name', '').val('')
        $(".select2-container.UOM_ID", ClonedRow).show()
    }
</script>