<?php if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php echo $check_lock ?>
    </div>
<?php
    return;
}
if ($IsEdit && $IsSales && !empty($edit_arr['Main']['invoice_app_id']) && smc_session()['default_setting']['edit_sales_invoice_from_app'] == 0) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong> <?php print CommonLanguage::getMessage(' you_can_not_edit_this_invoice');  ?> !
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_from_application');  ?>
    </div>
<?php
    return;
}
if ($IsEdit && $IsSales && !empty($edit_arr['Main']['reason_id'])) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>:
        </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_voided'); ?> .
    </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><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_not_available'); ?> .
    </div>
<?php
    return;
}
if ($IsEdit && $IsSales && !empty($edit_arr['Main']['subscription_fees_id'])) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_related_to_customer_subscription'); ?> .
    </div>
<?php
    return;
}
if ($IsEdit && $IsSales && !empty($edit_arr['Main']['ticketing_id'])) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_related_to_ticketing'); ?> .
    </div>
<?php
    return;
}
if ($IsEdit && $IsSales && $edit_arr['Main']['table_id'] != 0) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_related_to_table'); ?> .
    </div>
<?php
    return;
}
if ($IsEdit && $edit_arr['Main']['sales_purchase_id'] > 0 && !$IsOrder && !$is_delivery && !$is_note && !$is_copy && !$is_return) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_related_to_a_sales_purchase'); ?> .
    </div>
<?php
    return;
}
if (count($related_payments) > 0 && !$is_data_collector && !$IsOrder && !$is_delivery && !$is_note && !$is_copy && !$is_return) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong><?php print CommonLanguage::getMessage('you_can_not_edit_this_invoice'); ?>!
        <br>
        <?php print CommonLanguage::getMessage('this_invoice_is_closed_by_the_following_payments'); ?> :
        <?php echo implode(', ', $related_payments); ?>
    </div>
<?php
    return;
}
if (empty($edit_arr['Details']) && $is_delivery) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php print CommonLanguage::getMessage('danger'); ?>: </strong>
        <?php print CommonLanguage::getMessage('this_order_do_not_have_any_delivered_quantities'); ?> .
    </div>
<?php
    return;
}

$sales_inv_fields_req = smc_session()['default_setting']['sales_invoice_required_fields'] != '' ? explode(",", smc_session()['default_setting']['sales_invoice_required_fields']) : [];
$sales_inv_fields_hide = smc_session()['default_setting']['sales_invoice_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['sales_invoice_fields_to_hide']) : [];

$purchase_inv_fields_hide = smc_session()['default_setting']['purchase_invoice_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['purchase_invoice_fields_to_hide']) : [];
$purchase_noqty_fields_hide = smc_session()['default_setting']['purchase_noqty_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['purchase_noqty_fields_to_hide']) : [];
$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']) : [];

$has_sales_cost_perm = $permissions->hasPermission($is_actual ? 'actual_view_sales_last_cost' : 'view_sales_last_cost');
$has_sales_last_price = $permissions->hasPermission($is_actual ? 'actual_view_sales_last_price' : 'view_sales_last_price');
$has_purchase_cost_perm = $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_view_purchase_last_cost' : 'actual_view_purchase_last_cost') : ($is_noqty ? 'pur_noqty_view_purchase_last_cost' : 'view_purchase_last_cost'));
?>
<style type="text/css">
    #InventoryPurchaseTable thead tr th {
        color: #555;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }

    #items_table th {
        background: #4c0870;
        color: #fff;

    }

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


    #InventoryPurchaseTable tbody tr td {
        border: 0;
        padding: 3px 1px;
        position: relative;
        /*display: block;*/
    }

    #InventoryPurchaseTable tbody tr:first-child td {
        padding-top: 10px;
    }

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


    }

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


    }

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

    }

    /*    #InventoryPurchaseTable .Hint{
    position: absolute;
    font-size: 10px;
    font-weight: bold;
    height: 20px;
    line-height: 20px;
    bottom: 2px;
    right: 4px;
    color: rgb(153, 153, 153);
    }*/
    #InventoryPurchaseTable .Hint {
        position: absolute;
        font-size: 10px;
        display: block;
        font-weight: bold;
        height: 12px;
        line-height: 11px;
        cursor: default;
        background: #ccc;
        padding: 0 2px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        bottom: 3px;
        right: 1px;
        left: 1px;
        color: #4c0870;
    }

    #InventoryPurchaseTable .TotalTD {
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }

    /*    #InventoryPurchaseTable .Disc{
    width:70px;
    }*/
    .wrong {
        border: 1px solid rgba(255, 0, 0, 0.2) !important;
        background: rgba(255, 0, 0, 0.05) !important;
        /*        width:100%;*/
    }

    .DropDownForForms>.dropdown-menu {
        width: 100%;
        height: 200px;
        max-height: 200px;
        overflow-y: scroll;
    }

    .DropDownForForms>.dropdown-menu {
        height: auto;
        cursor: pointer;
        overflow-y: auto;
    }

    .DropDownForForms>button {
        position: relative;
        z-index: 999;
    }

    .DropDownForForms>button>input {
        position: absolute;
        left: 5;
        top: 0;
        width: 90%;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
        padding: 0;
        border: 0;
        background: transparent;
    }

    .Disabled {
        cursor: default;
        opacity: 0.5;
    }

    #AdvanceValue {
        width: 102px;
        display: inline-block;
    }

    .datepicker thead tr .dow {
        color: #4c0870 !important;
    }

    .datepicker table tr td.day:hover {
        background: #4c0870 !important;
        color: #fff;
    }

    .datepicker table tr td.active {
        background-color: #4c0870 !important;
    }

    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }

    .datepicker table tr td span.active {
        background-color: #4c0870 !important;
    }

    .datepicker table tr td span:hover {
        background-color: #4c0870 !important;
        color: #fff;
    }

    datepicker thead tr .next:before,
    .datepicker thead tr .prev:before {
        color: #4c0870 !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }

    .datepicker thead tr .next:before,
    .datepicker thead tr .prev:before {
        color: #4c0870 !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }

    /*    .select2-container > .select2-choice{
    background-color: #e5e5e5;
    width: 150px;
    }*/
    #InventoryPurchaseTable .select2-container .select2-choice {
        background-image: none;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.07);
        padding: 5px 9px 16px;
        transition: border 0.2s linear 0s;
        height: 40px;
        background-color: #e5e5e5;
        width: 150px;
    }

    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }

    .InputSpinner {
        width: 60px;
    }

    .InputSpinner>.form-control {
        border-color: rgb(221, 221, 221);
        height: 36px;
        margin: 0;
        padding: 0;
        text-align: center;

    }

    .InputSpinner>.input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }

    .InputSpinner>.input-group-btn-vertical>.btn {
        height: 19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }

    .InputSpinner>.input-group-btn-vertical>.btn:first-child {
        border-top-right-radius: 4px;
    }

    .InputSpinner>.input-group-btn-vertical>.btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }

    .InputSpinner>.input-group-btn-vertical i {
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top: -9px;
        font-size: 18px;
    }

    .InputSpinner .input-group-btn-vertical .btn.btn-default {
        font-size: 10px;
        padding: 6px 10px;
    }

    #InvoicePaymentSetup .table tbody>tr:last-child>td {
        border: 0;
    }

    .hideme {

        display: none;
    }

    .select2-container>.select2-choice {

        width: 100% !important;

    }

    .supInv {
        display: inline-flex;
    }

    .invoice {
        padding-top: 0 !important;
    }

    #Truck {
        width: 48%;
        margin-right: 2%
    }

    .right-div .form-group {
        margin-bottom: 0px;
    }

    .diff_class,
    .expiry_width {
        width: 300px !important;
    }

    #items-modal .modal-header {
        padding-top: 0;
    }

    #items_table td {
        padding: 2px 5px;
    }

    /*    #items_table tr.odd td{ background: white;  border:1px lightgrey;}
    #items_table tr.even td{ background: #ccc; border:1px lightgrey; }*/

    .tags {
        cursor: pointer;
    }

    .inputDiv {
        background-color: transparent;
        font-size: large;
        border: none;
        border-radius: 0;
    }

    .inputDiv input {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        opacity: 0.01;
        cursor: pointer;
    }

    #TagsTable td:not(:first-child) {
        padding: 0;
    }

    .tagSelected,
    .inputDiv:hover {
        background-color: #6DC0F9 !important;
        border-color: #6DC0F9 !important;
        color: white;
    }

    .removeTags {
        text-align: center;
        vertical-align: middle !important;
        width: 10%;
        cursor: pointer;
    }

    #InventoryPurchaseTable td span.mylabel {
        font-size: 10px !important;
        display: inline-table !important;
        white-space: normal !important;
        line-height: 21px !important;
    }

    #InventoryPurchaseTable .bootstrap-tagsinput .tag [data-role="remove"] {
        font-size: 13px !important;

    }

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

    }

    .op-div:not(.temp-op-div) {
        display: grid !important;
    }

    .pulsate {
        content: '';
        display: block;
        /*
        position: absolute;
        top: 0;
        */
        left: 0;
        right: 0;
        bottom: 0;
        animation: pulse 1s ease infinite;
        border-radius: 50%;
        border: 4px double lighten(red, 20%);
    }

    @keyframes pulse {
        0% {
            transform: scale(1);
            opacity: 1;
        }

        60% {
            transform: scale(1.3);
            opacity: 0.4;
        }

        100% {
            transform: scale(1.4);
            opacity: 0;
        }
    }

    .badge {

        border-radius: 50%;
        color: #fff;
    }

    .ship_div>div {
        padding: 5px !important;
    }

    .p-l-0 {
        padding-left: 0 !important;
    }

    .p-r-5 {
        padding-right: 5px !important;
    }
</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">
                <?php
                if ($is_main_transfer != 0 && $IsSales && !$is_data_collector && !$IsOrder && !$is_delivery && !$is_note && !$is_copy && !$is_return) {
                ?>
                    <div class="alert alert-danger" role="alert">
                        <button class="close" data-dismiss="alert"></button>
                        <strong>Danger: </strong>you can not edit this invoice!
                        <br>
                        This invoice is transfered to the main branch.
                    </div>
                <?php
                    die();
                }
                ?>
                <?php
                if ($is_branch_transfer != 0 && $IsSales && !$is_data_collector && !$IsOrder && !$is_delivery && !$is_note && !$is_copy && !$is_return) {
                ?>
                    <div class="alert alert-danger" role="alert">
                        <button class="close" data-dismiss="alert"></button>
                        <strong>Danger: </strong>you can not edit this invoice!
                        <br>
                        This invoice is transfered to the branch.
                    </div>
                <?php
                    die();
                }
                ?>
                <div id="PurchaseSuccess" class="hidden"></div>
                <div class="invoice ">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <input type="hidden" name="current_order_id" id="current_order_id" value="<?php echo $order_id; ?>" />
                            <input type="hidden" name="due_date_period" id="due_date_period" value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note) ? $edit_arr['Person']['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-6">
                                        <h2 class="font-montserrat all-caps hint-text"><?php echo $title;
                                                                                        ?> </h2>
                                    </div>
                                    <?php if ($IsSales) { ?>
                                        <div class="col-md-3" style="padding-top:2%">

                                            <div class="pending_invoices ">
                                                <select name="pending_invoices" id="pending_invoices" onchange="location = this.value;" class="full-width pending_invoices " data-init-plugin="select2">
                                                    <option value="0"> <?php print CommonLanguage::getMessage('pending_invoices'); ?></option>

                                                    <?php foreach ($pending_invoices as $item) : ?>
                                                        <option value="<?php echo SITE_LINK . 'Inventory/addpurchase' . ($IsSales ? '/sales/' : '/') . $item['id']; ?>"><?php echo $item['invoice']; ?></option>
                                                    <?php
                                                    endforeach;
                                                    ?>

                                                </select>
                                            </div>
                                        </div> <?php } ?>
                                </div>

                                <div class='row form-group'>
                                    <div class="input-group  col-md-4 center-margin pull-left " style="display:block;">
                                        <label><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer' : 'choose_supplier'); ?></label><span class="red-star">*</span><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" <?php echo $IsSales && (($IsEdit && !empty($edit_arr['Main']['pos_customer_id'])) || (isset($invoice_type_details['customer_id']) && !empty($invoice_type_details['prevent_change_cust']))) ? 'disabled' : '' ?> value="<?= ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main'][$IsSales ? 'Customer_ID' : 'Supplier_ID'] : (($IsOrder || $is_delivery || $is_note) ? $edit_arr['Main']['Person_ID'] : (isset($invoice_type_details['customer_id']) ? $invoice_type_details['customer_id'] : '')); ?>" data-select-name='<?= json_encode(($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return || $is_note) ? $edit_arr['Person']['Name'] : (!empty($invoice_type_details['customer_name']) ? $invoice_type_details['customer_name'] : '')); ?>' />
                                    </div>
                                    <br>
                                    <div class="Account_Code col-md-4">
                                        <label><?php print CommonLanguage::getMessage('accounts'); ?></label><span class="red-star">*</span><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" <?php echo ((isset($invoice_type_details['account_id']) && !empty($invoice_type_details['prevent_change_sales']))) ? 'disabled' : '' ?> value="<?= ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['Account_ID'] : (!empty($invoice_type_details['account_id']) ? $invoice_type_details['account_id'] : smc_session()['user_accounts'][$IsSales ? 'sales_account_id' : 'purchase_account_id']); ?>" data-select-name='<?= json_encode(($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['Account_Name'] : (!empty($invoice_type_details['account_id']) ? $invoice_type_details['Account_Name'] . ' -' . $invoice_type_details['Account_Code'] : smc_session()['user_accounts'][$IsSales ? 's_name' : 'p_name'])); ?>' required />
                                    </div>

                                    <div class="col-md-4 <?php echo (($IsSales && $permissions->hasPermission($is_actual ? 'actual_sales_change_class' : 'change_class')) || !$IsSales) ? '' : 'hidden' ?>">
                                        <label><?php echo CommonLanguage::getMessage('pricing_class'); ?></label>
                                        <input type="text" id="pricing_class" class=" full-width" <?php echo ((isset($invoice_type_details['class_id']) && !empty($invoice_type_details['prevent_change_class']))) ? 'disabled' : '' ?> value="<?php echo ($IsSales ? (($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? (!empty($edit_arr['Main']['Class_ID']) ? $edit_arr['Main']['Class_ID'] : '') : (!empty($invoice_type_details['class_id']) ? $invoice_type_details['class_name'] : smc_session()['pricing_class_id'])) : (($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? (!empty($edit_arr['Main']['Class_ID']) ? $edit_arr['Main']['Class_ID'] : (!empty($invoice_type_details['class_id']) ? $invoice_type_details['class_name'] : '')) : '')) ?>" data-select-name="<?php echo ($IsSales ? (($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? $edit_arr['Main']['Class_Name'] : (!empty($invoice_type_details['class_id']) ? $invoice_type_details['class_name'] : smc_session()['pricing_class_name'])) : (($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? $edit_arr['Main']['Class_Name'] : (!empty($invoice_type_details['class_id']) ? $invoice_type_details['class_name'] : ''))) ?>">

                                    </div>


                                    <div class="clearfix"></div>
                                </div>
                                <div class='row form-group'>
                                    <div id="SupplierInfo" class="col-md-4">
                                        <div class="col-md-12 <?php echo $IsSales && !in_array(20, $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 || $IsOrder) ? $edit_arr['Main']['customer_name_alias'] : '' ?>" />
                                        </div>
                                        <div class="col-md-12 <?php echo $IsSales && !in_array(21, $sales_inv_fields_hide) ? '' : 'hidden' ?>">
                                            <label><?php echo CommonLanguage::getMessage('customer_address_alias') ?></label>
                                            <textarea type="text" class="form-control" id="customer_address_alias"><?php echo ($IsEdit || $IsOrder) ? $edit_arr['Main']['customer_address_alias'] : '' ?></textarea>
                                        </div>

                                        <div class="col-md-12">
                                            <input type="hidden" name="Supplier_ID" value="<?php echo ($IsEdit || $is_copy || $is_return) ? ($edit_arr['Main'][$IsSales ? 'Customer_ID' : 'Supplier_ID']) : (($IsOrder || $is_delivery || $is_note) ? $edit_arr['Main']['Person_ID'] : '') ?>" required id="Supplier_ID" />
                                            <div id="SupplierInfoContent" class="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return || $is_note) ? '' : 'hidden' ?>">
                                                <strong><span class='Name' id='Supplier_Name' data-id='<?php echo ($IsEdit || $IsOrder || $is_copy || $is_return) ? $edit_arr['Person']['Name'] : '' ?>' data-account-name='<?php echo ($IsEdit || $IsOrder || $is_copy || $is_return) ? $edit_arr['Person']['Name'] : '' ?>' data-account-id='<?php echo ($IsEdit || $IsOrder || $is_copy || $is_return) ? $edit_arr['Person']['Account_ID'] : '' ?>' data-account-code='<?php echo ($IsEdit || $IsOrder || $is_copy || $is_return) ? $edit_arr['Person']['Account_Code'] : '' ?>'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return || $is_note) ? $edit_arr['Person']['Name'] : '' ?></span><span class='fa fa-eye m-l-5 openFrame <?php echo $permissions->hasPermission($is_actual ? 'ActualLedger' : 'ledger') ? '' : 'hidden' ?>' data-src='ACC/ledger?is_pop=1/<?php echo $IsEdit ? $edit_arr['Person']['Account_Code'] : '' ?>' style='color:#8a7dbe;cursor:pointer'></span></strong>
                                                <div><strong><?php echo CommonLanguage::getMessage('company'); ?>: </strong><span class='Company'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return || $is_note) ? $edit_arr['Person']['Company'] : '' ?></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('Email'); ?>: </strong><span class='Email'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['Email'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('Phone'); ?>: </strong><span class='Phone'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['Phone'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('address'); ?>: </strong><span class='Address'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['Address'] : '' ?></span></div>
                                                <div><strong><?php echo CommonLanguage::getMessage('country'); ?>: </strong><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['Country_Name'] : '' ?></div>
                                                <div id='Finance_Account' data-id='<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['Account_ID'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('financial_nb'); ?>: </strong><?php echo ($IsEdit || $IsOrder || $is_copy || $is_return) ? $edit_arr['Person']['Account_Code'] : '' ?></div>
                                                <div id='Class_ID' style='display:none;'><?php echo (($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && $IsSales) ? $edit_arr['Person']['Class_ID'] : '' ?></div>
                                                <div id='Class_Currency' style='display:none;'><?php echo (($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && $IsSales) ? $edit_arr['Person']['Class_Currency'] : '' ?></div>
                                                <?php if (!empty($edit_arr['Person']['main_shipping_address']) && ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && $IsSales && (smc_session()['default_setting']['show_main_shipping_address'] == 1)) { ?>

                                                    <div><strong><?php echo CommonLanguage::getMessage('shipping_main_address'); ?>: </strong><?php echo (($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && $IsSales) ? $edit_arr['Person']['main_shipping_address'] : '' ?></div>
                                                <?php } ?>

                                            </div>
                                            <div id="SupplierAccInfo" class="<?php echo ($IsEdit || $is_copy || $is_return) ? '' : 'hidden' ?>">
                                                <div id='Account_CodeDiv' value='<?php echo ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['Account_Code'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('account_code') ?>: </strong><?php echo ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['Account_Name'] . ' - ' . $edit_arr['Main']['Account_Code'] : '' ?></div>
                                            </div>
                                        </div>

                                    </div>
                                    <div class="col-md-4 <?php echo $IsSales && !in_array(17, $sales_inv_fields_hide) ? '' : 'hidden' ?> <?php echo ($permissions->hasPermission($IsSales ? ($is_actual ? 'actual_sales_order_to_inv' : 'sales_order_to_inv') : ($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_order_to_inv' : 'actual_purchase_order_to_inv') : ($is_noqty ? 'purchase_order_to_inv' : 'purchase_order_to_inv')))) ? '' : 'hidden'; ?>">
                                        <label><?php echo CommonLanguage::getMessage('order') ?></label>
                                        <input type="hidden" class="full-width" id="order_filter" />
                                    </div>
                                    <div class="col-md-4 <?php echo $IsSales ? '' : 'hidden'; ?>">
                                        <label><?php echo CommonLanguage::getMessage('customer_branch'); ?><span id="customer_branch_label" class="red-star hidden">*</span></label>
                                        <input type="hidden" class="full-width" id="customer_branch_id" name="customer_branch_id" value="<?php echo ($IsSales && !empty($edit_arr['Main']['customer_branch_id'])) ? $edit_arr['Main']['customer_branch_id'] : ''; ?>" data-select-name="<?php echo ($IsSales && !empty($edit_arr['Main']['customer_branch_name'])) ? $edit_arr['Main']['customer_branch_name'] : ''; ?>" />
                                    </div>
                                    <div class="col-md-4 <?php echo $IsSales && !in_array(22, $sales_inv_fields_hide) ? '' : 'hidden' ?>">
                                        <label><?php echo CommonLanguage::getMessage('road_customer'); ?></label>
                                        <input type="hidden" class="full-width" id="pos_customer_id" name="pos_customer_id" <?php echo $IsEdit && $IsSales && empty($edit_arr['Main']['pos_customer_id']) ? 'disabled' : '' ?> value="<?php echo ($IsSales && !empty($edit_arr['Main']['pos_customer_id'])) ? $edit_arr['Main']['pos_customer_id'] : ''; ?>" data-select-name="<?php echo ($IsSales && !empty($edit_arr['Main']['pos_customer_name'])) ? $edit_arr['Main']['pos_customer_name'] : ''; ?>" />
                                    </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 class="form-group supInv" id="SupplierInv">
                                    <h4> <?php print CommonLanguage::getMessage($IsSales ? 'inv_user_ref' : 'supplier_invoice'); ?>#</h4>
                                    <input id="Supplier_Invoice" name="Supplier_Invoice" class="form-control" value="<?php echo (!$IsSales && $IsEdit) ? $edit_arr['Main']['Supplier_Invoice_ID'] : ($IsSales && $IsEdit ? $edit_arr['Main']['invoice_user_reference'] : '') ?>" style="width: 35%;margin-top: 11px;margin-left: 15px;" />
                                </div>
                                <div class="col-md-12 p-0 m-b-10">

                                    <div class="form-group col-md-6  p-l-0 p-r-5">
                                        <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                        <input id="PurchaseInvoiceDate" name="PurchaseInvoiceDate" class="form-control" value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return ? $edit_arr['Main']['Date'] : $today); ?>" />
                                        <!--<span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>-->
                                    </div>
                                    <div class="form-group p-r-5  p-l-0 col-md-6 <?php echo (($IsSales && !in_array(31, $sales_inv_fields_hide)) || (!$IsSales && !in_array(20, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && !in_array(20, $purchase_noqty_fields_hide)) ? '' : 'hidden') ?>">
                                        <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                        <input id="PurchaseInvoiceDueDate" name="PurchaseInvoiceDueDate" class="form-control" value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return ? $edit_arr['Main']['Due_Date'] : $today); ?>" required>
                                        <!--<span class="input-group-addon primary"><i class="fa fa-calendar-o"></i></span>-->
                                    </div>
                                    <div class="form-group p-r-5 p-l-0 col-md-6 <?php echo ((!$IsSales && !in_array(16, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && !in_array(16, $purchase_noqty_fields_hide)) ? '' : 'hidden') ?>">
                                        <label><?php print CommonLanguage::getMessage('Delivery_Date'); ?></label>
                                        <input id="delivery_date" name="delivery_date" class="form-control" value="<?php echo ($IsEdit && !empty($edit_arr['Main']['delivery_date']) ? $edit_arr['Main']['delivery_date'] : $today); ?>">
                                        <!--<span class="input-group-addon primary"><i class="fa fa-calendar-o"></i></span>-->
                                    </div>
                                    <!--                                </div>
                                                                    <div  id="depot" class="form-group " >-->
                                    <div class="form-group col-md-6 p-l-0 p-r-5 <?php echo $permissions->hasPermission('Depots') ? '' : 'hidden'; ?>">
                                        <!--<div class="col-md-12">-->
                                        <label><?php print CommonLanguage::getMessage('Depot'); ?></label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>

                                        <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" <?php echo $permissions->hasPermission($IsSales ? ($is_actual ? 'actual_change_invoice_depot' : 'change_invoice_depot') : ($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_change_depot' : 'actual_purchase_change_depot') : ($is_noqty ? 'pur_noqty_change_depot' : 'change_depot'))) ? '' : 'disabled' ?> data-old="<?php echo ($IsEdit) ? $edit_arr['Main']['Depot_ID'] : ''; ?>" value="<?= ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Main']['Depot_ID'] : (!empty($invoice_type_details['depot_id']) ? $invoice_type_details['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 || $IsOrder || $is_copy || $is_return) ? $all_depots[$edit_arr['Main']['Depot_ID']]['Depot_Name'] : (!empty($invoice_type_details['depot_id']) ? $invoice_type_details['depot_code'] . ' - ' . $invoice_type_details['depot_name'] : (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name']))) ?>' />

                                    </div>

                                    <!--</div>-->

                                    <!--                                </div>
                                                                    <div  id="depot" class="form-group " style="display: flex;">-->
                                    <!--<div class="col-md-12">-->
                                    <div class="col-md-6  p-l-0 p-r-5 <?php echo (($IsSales && !in_array(23, $sales_inv_fields_hide)) || (!$IsSales && !in_array(18, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && !in_array(18, $purchase_noqty_fields_hide)) ? '' : 'hidden') ?>">
                                        <label><?php print CommonLanguage::getMessage('exchange_rate'); ?><span class="red-star">(<?php echo smc_session()['local_currency_symbol'] ?>)</span></label>
                                        <input type="number" step="any" min="0.0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo $IsEdit ? ($edit_arr['Main']['Currency_ID'] == smc_session()['local_currency'] ? 'disabled' : '') : ($DefaultCurrencyID == smc_session()['local_currency'] ? 'disabled' : '') ?> value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Main']['current_rate'] : '' ?>" />


                                    </div>
                                    <div class="col-md-6  p-l-0 p-r-5  <?php echo (($IsSales && !in_array(24, $sales_inv_fields_hide)) || (!$IsSales && !in_array(19, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && !in_array(19, $purchase_noqty_fields_hide)) ? '' : 'hidden') ?>">
                                        <div class="form-group ">
                                            <label><?php print CommonLanguage::getMessage('exchange_rate'); ?><span class="red-star">(<?php echo smc_session()['second_currency']['symbol'] ?>)</span></label>
                                            <input type="number" step="any" min="0.0" id="second_currency_rate" name="second_currency_rate" class="form-control full-width second_currency_rate" <?php echo $IsEdit ? ($edit_arr['Main']['Currency_ID'] == smc_session()['default_setting']['second_currency'] ? 'disabled' : '') : ($DefaultCurrencyID == smc_session()['default_setting']['second_currency'] ? 'disabled' : '') ?> value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && !empty($edit_arr['Main']['second_currency_rate']) ? $edit_arr['Main']['second_currency_rate'] : '' ?>" />
                                        </div>
                                    </div>
                                    <!--</div>-->

                                    <!--</div>-->
                                    <?php if ($IsSales) { ?>
                                        <!--<div style="display: flex">-->
                                        <div id="Truck" class="form-group col-md-6  p-l-0 p-r-5  <?php echo $IsSales && in_array(32, $sales_inv_fields_hide) ? 'hidden' : '' ?>">
                                            <label><?php print CommonLanguage::getMessage('truck'); ?></label>
                                            <input id="inv_truck" name="inv_truck" class="form-control full-width inv_truck" value="<?php echo ($IsEdit || $is_copy) ? $edit_arr['Main']['truck'] : '' ?>" />
                                        </div>
                                        <div class="form-group col-md-6  p-l-0 p-r-5 <?php echo smc_session()['user_details']['limit_customer_invoice'] == 1 ? 'hidden' : ''; ?>  ">
                                            <label><?php print CommonLanguage::getMessage('salesman'); ?></label>
                                            <input id="PIC_ID" name="PIC_ID" class="full-width PIC_ID" type="hidden" value="<?= (($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && !empty($edit_arr['Main']['Sales_ID'])) ? $edit_arr['Main']['Sales_ID'] : (!empty($edit_arr['Person']['selected_emp']) && !empty($edit_arr['Person']['emp_id']) ? $edit_arr['Person']['emp_id'] : '') ?>" data-select-name='<?= json_encode((($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) && !empty($edit_arr['Main']['Employee_Name'])) ? $edit_arr['Main']['Employee_Name'] : (!empty($edit_arr['Person']['selected_emp']) && !empty($edit_arr['Person']['emp_name']) ? $edit_arr['Person']['emp_name'] : '')) ?>' />
                                        </div>

                                    <?php } ?>
                                </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 || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $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 || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? ($edit_arr['Main']['Currency_Name'] . ' - ' . $edit_arr['Main']['Currency_Symbol']) : CommonLanguage::getMessage('select') ?></strong></span>
                                                <input type="hidden" value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $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>
                                <div class="form-group " style="display: flex;">
                                    <!--<div class="col-md-12">-->
                                    <div style="width: 48%;margin-right:2%;" class="<?php echo (smc_session()['default_setting']['activate_accounting_job'] == 0 || ($IsSales && in_array(29, $sales_inv_fields_hide))) ? 'hidden' : '' ?>">
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" value="<?php echo (($IsEdit || $is_copy || $is_return) && !empty($edit_arr['Main']['job_id'])) ? $edit_arr['Main']['job_id'] : (!empty(smc_session()['user_accounts']['job_id']) ? smc_session()['user_accounts']['job_id'] : '') ?>" data-select-name="<?= ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['job_name'] : (!empty(smc_session()['user_accounts']['job_name']) ? smc_session()['user_accounts']['job_name'] : '') ?>" />
                                    </div>
                                    <?php if (!$IsSales) { ?>
                                        <div class="form-group " <?php echo $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_change_dist_method' : 'actual_purchase_change_dist_method') : ($is_noqty ? 'pur_noqty_change_dist_method' : 'change_dist_method')) ? '' : 'hidden' ?> style="width: 50%;">
                                            <label><?php print CommonLanguage::getMessage('cost_dist_method'); ?></label>
                                            <select id="cost_dist_method" class="full-width" data-init-plugin="select2">
                                                <option value="0" <?php echo ($IsEdit || $is_copy) ? ($edit_arr['Main']['cost_dist_method'] == 0 ? 'selected' : '') : (smc_session()['default_setting']['cost_dist_method'] == 0 ? 'selected' : '') ?>><?php echo CommonLanguage::getMessage('Quantity') ?></option>
                                                <option value="1" <?php echo ($IsEdit || $is_copy) ? ($edit_arr['Main']['cost_dist_method'] == 1 ? 'selected' : '') : (smc_session()['default_setting']['cost_dist_method'] == 1 ? 'selected' : '') ?>><?php echo CommonLanguage::getMessage('Price') ?></option>
                                                <option value="2" <?php echo ($IsEdit || $is_copy) ? ($edit_arr['Main']['cost_dist_method'] == 2 ? 'selected' : '') : (smc_session()['default_setting']['cost_dist_method'] == 2 ? 'selected' : '') ?>><?php echo CommonLanguage::getMessage('maunual_percent') ?></option>
                                            </select>
                                        </div>
                                    <?php } ?>
                                </div>
                                <div class="form-group " style="display: flex;">

                                    <div class="<?php echo (smc_session()['default_setting']['activate_project'] == 0 || ($IsSales && in_array(30, $sales_inv_fields_hide))) ? 'hidden' : '' ?>" style="width: 48%;margin-right:2%;">
                                        <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                        <input type="hidden" class="full-width" id="project_id" value="<?php echo (($IsEdit || $is_copy || $is_return) && !empty($edit_arr['Main']['project_id'])) ? $edit_arr['Main']['project_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['project_name'] : '' ?>" />
                                    </div>
                                    <div style="width:50%" class="<?php echo ($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales ? 'hidden' : '' ?>">
                                        <label><?php echo CommonLanguage::getMessage('contra') ?></label>
                                        <input type="hidden" class="full-width" id="contra_id" value="<?php echo (($IsEdit || $is_copy) && !empty($edit_arr['Main']['contra_id'])) ? $edit_arr['Main']['contra_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_copy) ? $edit_arr['Main']['contra_name'] : '' ?>" />
                                    </div>

                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="row m-b-10">
                        <div class="col-md-2">
                            <button class="btn btn-primary" id="choose_items" <?php echo ($IsEdit || $is_copy || $is_return) ? '' : 'disabled'; ?>>
                                <?php echo CommonLanguage::getMessage('choose_items') ?>
                            </button>
                        </div>
                        <div class="col-md-2 form-group  <?php echo ($permissions->hasPermission($IsSales ? ($IsEdit ? 'enable_vat_edit_actual_sales_invoice' : 'enable_vat_actual_sales_invoice') : ($IsEdit ? 'enable_vat_edit_actual_purchase' : ($is_noqty ? 'pur_noqty_enable_vat_actual_purchase' : 'enable_vat_actual_purchase'))) && $is_actual) ? '' : 'hidden'; ?> " style="margin-right: 42px;">
                            <label><?php print CommonLanguage::getMessage('enable_vat'); ?></label>
                            <input type="checkbox" id="enable_tva" name="enable_tva" />
                        </div>
                    </div>
                    <div class="table-responsive">
                        <div id="ProdLoader" class="text-center alert <?php echo ($IsEdit || $is_data_collector || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? '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_data_collector || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? '' : 'hideme' ?>" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center" style="width:3%"></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['collect_points_inv'] ? 'hidden' : ''; ?>" style="width:5%"><?php print CommonLanguage::getMessage('is_collected_points'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(0, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(12, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(12, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(1, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:20%"><?php print CommonLanguage::getMessage('product_name'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?>" style="width:6%"><?php print CommonLanguage::getMessage('Expiry_Date'); ?></th>
                                    <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                    <th class="text-center <?php echo (!$IsSales || $permissions->hasPermission('effect_qty_link_product') == 0 || ($IsSales && in_array(51, $sales_inv_fields_hide)) )   ? 'hidden' : ''; ?> " style="width:5%"><?php print CommonLanguage::getMessage('link_qty'); ?></th>
                                    
                                    <th class="text-center <?php echo $is_noqty || !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 $is_noqty || !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 $is_noqty || !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)) || (!$IsSales && $is_noqty && in_array(2, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(8, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(9, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('serial'); ?></th>


                                    <th class="text-center <?php echo ($IsSales && in_array(48, $sales_inv_fields_hide))    || !$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(49, $sales_inv_fields_hide))   || !$IsSales ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('to_time'); ?></th>

                                    <th class="text-center <?php echo ($IsSales && in_array(50, $sales_inv_fields_hide))    || (!$IsSales  && in_array(28, $purchase_inv_fields_hide))  ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('date'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(47, $sales_inv_fields_hide))    || (!$IsSales  && in_array(30, $purchase_inv_fields_hide))  ? '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)) || (!$IsSales && $is_noqty && in_array(7, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:20%"><?php print CommonLanguage::getMessage('description'); ?></th>

                                    <th class="text-center <?php echo ($IsSales && in_array(10, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(11, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('Depot'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(8, $sales_inv_fields_hide)) || (!$IsSales && in_array(29, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('vehicle'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(9, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('Employee'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(7, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('commission'); ?></th>

                                    <th class="text-center <?php echo (!$IsSales && in_array(10, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(10, $purchase_noqty_fields_hide)) || $IsSales ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('class'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(3, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:8%"><?php print CommonLanguage::getMessage('unit_price'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>" style="width:8%"><?php print CommonLanguage::getMessage('ttc_price'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(5, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(6, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('vat_percent'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(19, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(15, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('vat2_amount'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(14, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('vat2_percent'); ?></th>
                                    <th class="text-center <?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('additional_cost'); ?></th>
                                    <th class="text-center <?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>" style="width:12%"></th>
                                    <th class="text-center cost-cell <?php echo ($IsEdit || $is_copy) ? ((!empty($edit_arr['Main']['cost_dist_method']) && $edit_arr['Main']['cost_dist_method'] == 2 && $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_add_extra_cost' : 'actual_purchase_add_extra_cost') : ($is_noqty ? 'pur_noqty_add_extra_cost' : 'add_extra_cost')) && !$IsSales) ? '' : 'hidden') : ((smc_session()['default_setting']['cost_dist_method'] == 2 && $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_add_extra_cost' : 'actual_purchase_add_extra_cost') : ($is_noqty ? 'pur_noqty_add_extra_cost' : 'add_extra_cost')) && !$IsSales) ? '' : 'hidden') ?>" style="width:12%"><?php print CommonLanguage::getMessage('cost_percent'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && smc_session()['default_setting']['activate_sales_profit_margin'] == 1 && !in_array(12, $sales_inv_fields_hide) && $permissions->hasPermission($is_actual ? 'act_view_profit' : 'view_profit')) ? '' : 'hidden' ?>" style="width:12%"><?php print CommonLanguage::getMessage('profit'); ?></th>
                                    <th class="text-center <?php echo (($IsSales && in_array(41, $sales_inv_fields_hide)) || (!$IsSales && in_array(24, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(25, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>" 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 } ?>
                                    <th class="text-center option-main-td  <?php echo !empty($item['options']) ? '' : 'hidden' ?>" style="width:5%"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit || $is_data_collector || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) {
                                    $data_array = ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Details'] : $collector_data['products'];
                                    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 ((!empty($item['depot_qty']) ? $item['depot_qty'] : $item['Product_Quantity']) + (!empty($edit_arr['item_loc']) ? $edit_arr['item_loc'][$item['Product_ID']][$item['depot_id']] : 0)) ?>" data-vat="<?php echo $item['VAT'] ?>" data-id="<?php echo $item['Product_ID'] ?>" unit_price="<?php echo $item['Product_Net_Price'] ?>" data-delivery-id="<?php echo $is_delivery ? $item['Invoice_ID_Auto'] : ($IsEdit ? $item['Delivery_Report_ID'] : ($is_note ? $edit_arr['Main']['Auto_ID'] : '')) ?>" data-item-disc="<?php echo $item['Product_Limit_Discount'] ?>" data-cost="<?php echo !empty($item['unit_cost']) ? $item['unit_cost'] : 0 ?>" data-delivery-cost="<?php echo !empty($item['Delivery_Report_ID']) && !$is_copy && !$is_return ? $item['unit_cost'] : '' ?>" data-tax="<?php echo $IsSales ? $item['is_tax'] : 0 ?>" unit-tax="<?php echo $IsSales ? $item['unit_tax'] : 0 ?>" data-prod-status="<?php echo $item['Status_ID'] ?>" data-expiry="<?php echo $item['is_expiry']; ?>" data-entry="<?php echo $IsEdit ? $item['Entery_ID'] : '' ?>" data-is-service="<?php echo $item['is_service'] ?>" data-is-option="<?php echo !empty($item['has_option']) ? $item['has_option'] : 0 ?>" recipe-qty="<?php echo !empty($item['recipe_qty']) ? $item['recipe_qty'] : 0 ?>" data-ref="<?php echo uniqid() ?>" data-last-qty="<?php echo !empty($item['def_in_qty']) ? $item['def_in_qty'] : 0 ?>" data-depot-val="<?php echo $item['depot_id'] ?>" data-option-arr='<?php echo json_encode(!empty($item['options']) ? $item['options'] : []) ?>' data-cost-arr='<?php echo json_encode(!empty($item['cost_arr']) ? $item['cost_arr'] : []) ?>'>
                                                <td> <span class="fa fa-minus-circle deleteRowRequest <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'hidden' : '' ?>" style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                                
                                                <th class="text-center <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['collect_points_inv'] ? 'hidden' : ''; ?>" style="width:5%"><input type="checkbox" class="is_collected_points" <?php echo (($IsEdit && $item['is_collected_points'] == 1)) ? 'checked' : ''?>/></th>

                                                <td class="<?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(0, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan " value="<?php echo $item['Bar_Code'] ?>" <?php echo $IsEdit && !empty($item['Delivery_Report_ID']) ? 'disabled' : '' ?>></td>
                                                <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(12, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(12, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(1, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName" value="<?php echo $item['Name'] ?>" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?>>
                                                    <span class="Hint">
                                                        <span class="fa fa-sticky-note m-l-5 openFrame open_detailed_sold_items" data-src="Inventory/DetailedInvoiceProductReport?is_pop=1&product_id=<?php echo $item['Product_ID'] ?>&product_name=<?php echo $item['Name'] ?>&customer_id=<?php echo $edit_arr['Main']['Customer_ID'] ?>&customer_name=<?php echo $edit_arr['Person']['Name'] ?>" data-main-url="Inventory/DetailedInvoiceProductReport?is_pop=1&product_id=<?php echo $item['Product_ID'] ?>&product_name=<?php echo $item['Name'] ?>" style="color:#6c5ab3;cursor:pointer;float:right;"></span>
                                                        <span class="fa fa-eye m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=<?php echo $item['Product_ID'] ?>&product_name=<?php echo $item['Name'] ?>" style="color:#6c5ab3;cursor:pointer;float:right;"></span>
                                                        <span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/<?php echo $item['Product_ID'] ?>?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span></span>
                                                </td>
                                                <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?> "><input name="expiry_date" class="full-width expiry_date <?php echo $item['is_expiry'] == 1 ? '' : 'hidden'; ?>" value="<?php echo $item['is_expiry'] == 1 ? $item['expiry_date'] : ''; ?>" data-select-name="<?php echo $item['is_expiry'] == 1 ? $item['expiry_date'] : ''; ?>" type="<?php $IsSales ? 'hidden' : 'text'; ?>" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?> /></td>
                                                <td class="number_formatted_tooltip qty_tooltip block_tooltip"><input type="text" class="form-control Quantity isnumber number_formatted" data-tooltip="qty_tooltip" value="<?php echo $item['Item_Quantity_Current'] ?>" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?>><span class="Hint"><?php echo ($IsEdit ? ($item['depot_qty'] + (!empty($edit_arr['item_loc']) ? $edit_arr['item_loc'][$item['Product_ID']][$item['depot_id']] : 0)) / $item['uom_con'] : $item['depot_qty']) . empty($item['depot_qty']) ? $item['Product_Quantity'] . ' in stock' : ' in stock' ?></span></td>
                                                
                                                <td class="number_formatted_tooltip qty_tooltip block_tooltip   <?php echo (!$IsSales || $permissions->hasPermission('effect_qty_link_product') == 0 || ($IsSales && in_array(51, $sales_inv_fields_hide)) )   ? 'hidden' : ''; ?> "><input type="text" class="form-control qty_link isnumber number_formatted"  value="<?php echo $item['qty_link'] ?>" ></td>

                                                
                                                <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo $is_noqty || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_width isnumber number_formatted"  value="<?php echo $item['n_width'] ?>" ></td>
                                                <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo $is_noqty || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_height isnumber number_formatted"  value="<?php echo $item['n_height'] ?>" ></td>
                                                <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo $is_noqty || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" disabled class="form-control n_total isnumber number_formatted"  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)) || (!$IsSales && $is_noqty && in_array(2, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <select required name="UOM_ID" class="full-width UOM_ID " data-init-plugin="select2" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?>>
                                                        <?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)) || (!$IsSales && $is_noqty && in_array(8, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <input data-select-name="<?php echo $item['is_lot'] == 1 ? $item['lot_nb'] : ''; ?>" type="<?php echo $IsSales ? 'hidden' : 'text'; ?>" class="<?php echo $IsSales ? 'full-width' : 'form-control'; ?> lot_nb hidden" value="<?php echo $item['lot_nb'] ?>" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?>>
                                                </td>
                                                <td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(9, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>">
                                                    <input data-select-name="<?php echo $item['is_serial'] == 1 ? $item['serial_nb'] : ''; ?>" type="<?php echo $IsSales ? 'hidden' : 'text'; ?>" class="<?php echo $IsSales ? 'full-width' : 'form-control'; ?> serial_nb hidden" value="<?php echo $item['serial_nb'] ?>" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?>>
                                                </td>




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

                                                <td class=" <?php echo ($IsSales && in_array(50, $sales_inv_fields_hide))    || (!$IsSales  && in_array(28, $purchase_inv_fields_hide))  ? 'hidden' : ''; ?> "><input type="date" class="form-control modify_date" value="<?php echo $item['modify_date'] ?>"></td>
                                                <td class="  <?php echo ($IsSales && in_array(47, $sales_inv_fields_hide)) || (!$IsSales  && in_array(30, $purchase_inv_fields_hide))  ? '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)) || (!$IsSales && $is_noqty && in_array(7, $purchase_noqty_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(10, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(11, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_depot_id" class="full-width" value="<?php echo (!empty($item['depot_id']) && $item['depot_id'] != $edit_arr['Main']['Depot_ID']) ? $item['depot_id'] : ''; ?>" data-select-name="<?php echo (!empty($item['depot_id']) && $item['depot_id'] != $edit_arr['Main']['Depot_ID']) ? $item['Depot_Name'] : ''; ?>" <?php echo (($IsEdit && !empty($item['Delivery_Report_ID'])) || $is_delivery) ? 'disabled' : '' ?> /></td>
                                                <td class="<?php echo ($IsSales && in_array(8, $sales_inv_fields_hide)) ||  (!$IsSales && in_array(29, $purchase_inv_fields_hide))  ? 'hidden' : ''; ?>"><input type="hidden" name="current_vehicle_id" class="full-width" value="<?php echo (!empty($item['vehicle_id'])) ? $item['vehicle_id'] : ''; ?>" data-select-name="<?php echo ( !empty($item['vehicle_id'])) ? $item['Vehicle_Name'] : ''; ?>" /></td>
                                                <td class="<?php echo ($IsSales && in_array(9, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>"><input type="hidden" name="current_employee_id" class="full-width" value="<?php echo ($IsSales && !empty($item['employee_id'])) ? $item['employee_id'] : ''; ?>" data-select-name="<?php echo ($IsSales && !empty($item['employee_id'])) ? $item['Employee_Name'] : ''; ?>" /></td>
                                                <td class="<?php echo ($IsSales && in_array(7, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>"><input type="text" class="form-control commission isnumber" value="<?php echo ($IsSales && !empty($item['commission'])) ? $item['commission'] : ''; ?>"></td>

                                                <td class="<?php echo ((!$IsSales && in_array(10, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(10, $purchase_noqty_fields_hide)) || $IsSales) ? 'hidden' : ''; ?>"><input type="hidden" class="item-class full-width" 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="number_formatted_tooltip price_tooltip block_tooltip <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(3, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber number_formatted" data-tooltip="price_tooltip" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_change_sales_unit_price' : 'change_sales_unit_price') && !$item['force_change_price']) ? 'disabled' : '' ?> value="<?php echo $item['Product_Net_Price'] ?>"><span class="Hint">
                                                        <?php
                                                        echo ($IsSales ? ((!empty($item['last_price']) && $has_sales_last_price ? 'P: ' . CommonFunctions::formatNumber($item['last_price']) . ' | ' : '') .
                                                            (!empty($item['LAST_COST']) && $has_sales_cost_perm ? 'C: ' . CommonFunctions::formatNumber($item['LAST_COST']) : '')) : (!empty($item['LAST_COST']) && $has_purchase_cost_perm ? 'C: ' . CommonFunctions::formatNumber($item['LAST_COST']) : ''));
                                                        ?>
                                                    </span></td>
                                                <td class="number_formatted_tooltip ttcprice_tooltip block_tooltip <?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>"><input type="text" class="form-control ttc_price isnumber number_formatted" data-tooltip="ttcprice_tooltip" <?php echo ($IsSales && !$permissions->hasPermission('change_sales_unit_price')) ? 'disabled' : '' ?> value="<?php echo $item['Product_Net_Price'] + $item['vat_amount'] ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control Disc isnumber" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_sales_discount_on_item' : '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)) || (!$IsSales && $is_noqty && in_array(5, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem isnumber " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_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)) || (!$IsSales && $is_noqty && in_array(6, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_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(19, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(15, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_amount isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && ($item['VAT'] == 1 && smc_session()['allow_purchase_vat_edit'] == 1)) ? '' : 'disabled' ?> value="<?php echo !empty($item['vat2_amount']) ? $item['vat2_amount'] : '' ?>"></td>
                                                <td class="<?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(14, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_percent isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && ($item['VAT'] == 1 && smc_session()['allow_purchase_vat_edit'] == 1)) ? '' : 'disabled' ?> value="<?php echo !empty($item['vat2_percent']) ? $item['vat2_percent'] : '' ?>"></td>
                                                <td class="<?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><input type="text" class="form-control additional_cost isnumber" value="<?php echo !empty($item['additional_cost']) ? $item['additional_cost'] : '' ?>"></td>
                                                <td class="<?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><span class="fa fa-pencil extra_icon"></span></td>
                                                <td class=" cost-cell <?php echo (!$IsSales && $edit_arr['Main']['cost_dist_method'] == 2 && $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_add_extra_cost' : 'actual_purchase_add_extra_cost') : ($is_noqty ? 'pur_noqty_add_extra_cost' : 'add_extra_cost'))) ? '' : 'hidden' ?>"><input type="text" class="form-control cost_percent isnumber" value="<?php echo !empty($item['cost_percent']) ? $item['cost_percent'] : '' ?>"></td>
                                                <td class="  <?php echo ($IsSales && smc_session()['default_setting']['activate_sales_profit_margin'] == 1 && !in_array(12, $sales_inv_fields_hide) && $permissions->hasPermission($is_actual ? 'act_view_profit' : 'view_profit')) ? '' : 'hidden' ?>"><input type="text" readonly class=" form-control item_profit isnumber"></td>
                                                <td class="TotalTD <?php echo (($IsSales && in_array(41, $sales_inv_fields_hide)) || (!$IsSales && in_array(24, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(25, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></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 }
                                                if ($IsSales) { ?>
                                                    <td class="option-main-td  <?php echo !empty($item['options']) ? '' : 'hidden' ?>">
                                                        <span class="red-star "><i class="fa fa-th-list option-tr cursor <?php echo !empty($item['options']) ? '' : 'hidden' ?>" style="font-size:18px;"></i></span>
                                                    </td>
                                                <?php } ?>
                                                <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                            </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>
                                        <th class="text-center <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['collect_points_inv'] ? 'hidden' : ''; ?>" style="width:5%"><input type="checkbox" class="is_collected_points" <?php echo (($IsEdit && $item['is_collected_points'] == 1)) ? 'checked' : ''?> /></th>
                                        <td class="<?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(0, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan "></td>
                                        <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(12, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(12, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(1, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?> "><input name="expiry_date" class="full-width expiry_date hidden" type="<?php $IsSales ? 'hidden' : 'text'; ?>" /></td>

                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip"><input type="text" class="form-control Quantity isnumber number_formatted" data-tooltip="qty_tooltip"><span class="Hint"></span></td>
                                        
                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo (!$IsSales || $permissions->hasPermission('effect_qty_link_product') == 0 || ($IsSales && in_array(51, $sales_inv_fields_hide)) )   ? 'hidden' : ''; ?>  "><input type="text" class="form-control qty_link isnumber number_formatted"  ></td>

                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo $is_noqty || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_width isnumber number_formatted"  ></td>
                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo $is_noqty || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" class="form-control n_height isnumber number_formatted"  ></td>
                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo $is_noqty || !smc_session()['default_setting']['enable_kabalan_height_width'] ? 'hidden' : ''; ?>"><input type="text" disabled class="form-control n_total isnumber number_formatted"  ></td>
                                        
                                        <td class="<?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(2, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(8, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="<?php echo $IsSales ? 'hidden' : 'text'; ?>" class="<?php echo $IsSales ? 'full-width' : '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)) || (!$IsSales && $is_noqty && in_array(9, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input type="<?php echo $IsSales ? 'hidden' : 'text'; ?>" class="<?php echo $IsSales ? 'full-width' : 'form-control'; ?> serial_nb hidden" value="">
                                        </td>



                                        <td class=" <?php echo ($IsSales && in_array(48, $sales_inv_fields_hide))   || !$IsSales ? 'hidden' : ''; ?> "><input type="time" class="form-control from_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(49, $sales_inv_fields_hide))   || !$IsSales ? 'hidden' : ''; ?> "><input type="time" class="form-control to_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(50, $sales_inv_fields_hide))      || (!$IsSales  && in_array(28, $purchase_inv_fields_hide))  ? 'hidden' : ''; ?> "><input type="date" class="form-control modify_date"></td>
                                        <td class="  <?php echo ($IsSales && in_array(47, $sales_inv_fields_hide))    || (!$IsSales  && in_array(30, $purchase_inv_fields_hide))  ? '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)) || (!$IsSales && $is_noqty && in_array(7, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note"></td>
                                        <td class="<?php echo ($IsSales && in_array(10, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(11, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_depot_id" class="full-width" /></td>
                                        <td class="<?php echo ($IsSales && in_array(8, $sales_inv_fields_hide)) || (!$IsSales && in_array(29, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_vehicle_id" class="full-width" /></td>
                                        <td class="<?php echo ($IsSales && in_array(9, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>"><input type="hidden" name="current_employee_id" class="full-width" /></td>
                                        <td class="<?php echo ($IsSales && in_array(7, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>"><input type="text" class="form-control commission isnumber" value=""></td>

                                        <td class="<?php echo ((!$IsSales && in_array(10, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(10, $purchase_noqty_fields_hide)) || $IsSales) ? 'hidden' : ''; ?>"><input type="hidden" class="item-class full-width"></td>

                                        <td class="number_formatted_tooltip price_tooltip block_tooltip<?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(3, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber number_formatted" data-tooltip="price_tooltip" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_change_sales_unit_price' : 'change_sales_unit_price')) ? 'disabled' : '' ?>><span class="Hint"></span></td>
                                        <td class="number_formatted_tooltip ttcprice_tooltip block_tooltip <?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>"><input type="text" class="form-control ttc_price isnumber number_formatted" data-tooltip="ttcprice_tooltip" <?php echo ($IsSales && !$permissions->hasPermission('change_sales_unit_price')) ? 'disabled' : '' ?> value="<?php echo $item['Product_Net_Price'] + $item['vat_amount'] ?>"></td>
                                        <td class="<?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control Disc" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_sales_discount_on_item' : '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)) || (!$IsSales && $is_noqty && in_array(5, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_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)) || (!$IsSales && $is_noqty && in_array(6, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo ($IsSales && in_array(19, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(15, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_amount " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(14, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><input type="text" class="form-control additional_cost isnumber"></td>
                                        <td class="<?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><span class="fa fa-pencil extra_icon"></span></td>

                                        <td class="cost-cell <?php echo (!$IsSales && $edit_arr['Main']['cost_dist_method'] == 2 && $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_add_extra_cost' : 'actual_purchase_add_extra_cost') : ($is_noqty ? 'pur_noqty_add_extra_cost' : 'add_extra_cost'))) ? '' : 'hidden' ?>"><input type="text" class="form-control cost_percent "></td>
                                        <td class="  <?php echo ($IsSales && smc_session()['default_setting']['activate_sales_profit_margin'] == 1 && !in_array(12, $sales_inv_fields_hide) && $permissions->hasPermission($is_actual ? 'act_view_profit' : 'view_profit')) ? '' : 'hidden' ?>"><input type="text" readonly class=" form-control item_profit isnumber"></td>

                                        <td class="TotalTD <?php echo (($IsSales && in_array(41, $sales_inv_fields_hide)) || (!$IsSales && in_array(24, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(25, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></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 }
                                        if ($IsSales) { ?>
                                            <td class="option-main-td hidden">
                                                <span class="red-star "><i class="fa fa-th-list option-tr cursor hidden" style="font-size:18px;"></i></span>
                                            </td>
                                        <?php } ?>
                                        <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                    </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>                                       
                                        <th class="text-center <?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['collect_points_inv'] ? 'hidden' : ''; ?>" style="width:5%"><input type="checkbox" class="is_collected_points" <?php echo (($IsEdit && $item['is_collected_points'] == 1)) ? 'checked' : ''?> /></th>
                                        <td class="<?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(0, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan "></td>
                                        <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(12, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(12, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(1, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?> "><input name="expiry_date" class="full-width expiry_date hidden" type="<?php $IsSales ? 'hidden' : 'text'; ?>" /></td>
                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip"><input type="text" class="form-control Quantity isnumber number_formatted" data-tooltip="qty_tooltip"><span class="Hint"></span></td>
                                        
                                        <td class="number_formatted_tooltip qty_tooltip block_tooltip <?php echo (!$IsSales || $permissions->hasPermission('effect_qty_link_product') == 0  || ($IsSales && in_array(51, $sales_inv_fields_hide)))   ? 'hidden' : ''; ?> "><input type="text" class="form-control qty_link isnumber number_formatted"  > </td>

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

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

                                        <td class=" <?php echo ($IsSales && in_array(48, $sales_inv_fields_hide))    || !$IsSales ? 'hidden' : ''; ?>  "><input type="time" class="form-control from_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(49, $sales_inv_fields_hide))   || !$IsSales ? 'hidden' : ''; ?>  "><input type="time" class="form-control to_time"></td>
                                        <td class=" <?php echo ($IsSales && in_array(50, $sales_inv_fields_hide))    || (!$IsSales  && in_array(28, $purchase_inv_fields_hide))  ? 'hidden' : ''; ?> "><input type="date" class="form-control modify_date"></td>


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

                                        <td class="<?php echo ($IsSales && in_array(10, $sales_inv_fields_hide)) || (!$IsSales && in_array(11, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(11, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_depot_id" class="full-width" /></td>
                                        <td class="<?php echo ($IsSales && in_array(8, $sales_inv_fields_hide)) || (!$IsSales && in_array(29, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="hidden" name="current_vehicle_id" class="full-width" /></td>
                                        <td class="<?php echo ($IsSales && in_array(9, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>"><input type="hidden" name="current_employee_id" class="full-width" /></td>
                                        <td class="<?php echo ($IsSales && in_array(7, $sales_inv_fields_hide)) || (!$IsSales) ? 'hidden' : ''; ?>"><input type="text" class="form-control commission isnumber" value=""></td>
                                        <td class="<?php echo ((!$IsSales && in_array(10, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(10, $purchase_noqty_fields_hide)) || $IsSales) ? 'hidden' : ''; ?>"><input type="hidden" class="item-class full-width"></td>

                                        <td class="number_formatted_tooltip price_tooltip block_tooltip <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(3, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber number_formatted" data-tooltip="price_tooltip" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_change_sales_unit_price' : 'change_sales_unit_price')) ? 'disabled' : '' ?>><span class="Hint"></span></td>
                                        <td class="number_formatted_tooltip ttcprice_tooltip block_tooltip <?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>"><input type="text" class="form-control ttc_price isnumber number_formatted" data-tooltip="ttcprice_tooltip" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_change_sales_unit_price' : 'change_sales_unit_price')) ? 'disabled' : '' ?> value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(4, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control Disc" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_sales_discount_on_item' : '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)) || (!$IsSales && $is_noqty && in_array(5, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_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)) || (!$IsSales && $is_noqty && in_array(6, $purchase_noqty_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo ($IsSales && in_array(19, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(15, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_amount" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(14, $purchase_noqty_fields_hide)) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?>></td>
                                        <td class="<?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><input type="text" class="form-control additional_cost isnumber"></td>
                                        <td class="<?php echo (($IsSales && in_array(40, $sales_inv_fields_hide)) || (!$IsSales && in_array(23, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(26, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><span class="fa fa-pencil extra_icon"></span></td>

                                        <td class="cost-cell <?php echo (!$IsSales && smc_session()['default_setting']['cost_dist_method'] == 2 && $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_add_extra_cost' : 'actual_purchase_add_extra_cost') : ($is_noqty ? 'pur_noqty_add_extra_cost' : 'add_extra_cost'))) ? '' : 'hidden' ?>"><input type="text" class="form-control cost_percent "></td>
                                        <td class="  <?php echo ($IsSales && smc_session()['default_setting']['activate_sales_profit_margin'] == 1 && !in_array(12, $sales_inv_fields_hide) && $permissions->hasPermission($is_actual ? 'act_view_profit' : 'view_profit')) ? '' : 'hidden' ?>"><input type="text" readonly class=" form-control item_profit isnumber"></td>
                                        <td class="TotalTD <?php echo (($IsSales && in_array(41, $sales_inv_fields_hide)) || (!$IsSales && in_array(24, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(25, $purchase_noqty_fields_hide))) ? 'hidden' : ''; ?>"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></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 }
                                        if ($IsSales) { ?>
                                            <td class="option-main-td hidden">
                                                <span class="red-star "><i class="fa fa-th-list option-tr cursor hidden" style="font-size:18px;"></i></span>
                                            </td>
                                        <?php } ?>
                                        <!--<td class="TotalTD"><input type="text" class="form-control td-total Total" /></td>-->
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height form-group <?php echo (!$IsSales && $is_noqty) ? '' : 'hidden' ?>">
                        <div class="row row-sm-height ship_div" style="border: 1px solid rgba(230,230,230,0.7);">

                            <div class="col-md-3 ">
                                <label><?php echo CommonLanguage::getMessage('shipping_nb') ?></label>
                                <input type="text" class="form-control ignore " id="ship_bill_nb" value="<?php echo ($IsEdit) && !empty($edit_arr['Main']['ship_bill_nb']) ? $edit_arr['Main']['ship_bill_nb'] : '' ?>" />
                            </div>
                            <div class="col-md-3">
                                <label><?php echo CommonLanguage::getMessage('shipping_date') ?></label>
                                <input type="text" class="form-control ignore " id="ship_date" value="<?php echo ($IsEdit) && !empty($edit_arr['Main']['ship_date']) ? $edit_arr['Main']['ship_date'] : '' ?>" />
                            </div>
                            <div class="col-md-3">
                                <label><?php echo CommonLanguage::getMessage('container_nb') ?></label>
                                <input type="text" class="form-control ignore " id="container_nb" value="<?php echo ($IsEdit) && !empty($edit_arr['Main']['container_nb']) ? $edit_arr['Main']['container_nb'] : '' ?>" />
                            </div>
                            <div class="col-md-3">
                                <label><?php echo CommonLanguage::getMessage('container_size') ?></label>
                                <input type="text" class="form-control ignore " id="container_size" value="<?php echo ($IsEdit) && !empty($edit_arr['Main']['container_size']) ? $edit_arr['Main']['container_size'] : '' ?>" />
                            </div>
                            <div class="col-md-3">
                                <label><?php echo CommonLanguage::getMessage('ctn_nb') ?></label>
                                <input type="text" class="form-control ignore " id="ctn_nb" value="<?php echo ($IsEdit) && !empty($edit_arr['Main']['ctn_nb']) ? $edit_arr['Main']['ctn_nb'] : '' ?>" />
                            </div>
                            <div class="col-md-3">
                                <label><?php echo CommonLanguage::getMessage('ctn_date') ?></label>
                                <input type="text" class="form-control ignore " id="ctn_date" value="<?php echo ($IsEdit) && !empty($edit_arr['Main']['ctn_date']) ? $edit_arr['Main']['ctn_date'] : '' ?>" />
                            </div>
                            <!--                            <div class="col-md-3">
                                                            <label><?php // echo CommonLanguage::getMessage('ctn_amount')                                                                                                         
                                                                    ?></label>
                                                            <input type="text" class="form-control ignore " id="ctn_amount" value="<?php // echo ($IsEdit) ? $edit_arr['Main']['ctn_amount'] : ''                                                                                                         
                                                                                                                                    ?>"/>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <label><?php // echo CommonLanguage::getMessage('ctn_currency')                                                                                                         
                                                                    ?></label>
                                                            <input type="hidden" class="full-width" id="ctn_currency" value="<?php // echo ($IsEdit) ? $edit_arr['Main']['ctn_currency'] : ''                                                                                                         
                                                                                                                                ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['Main']['ctn_currency_name'] : '') ?>'/>
                                                        </div>-->

                        </div>
                    </div>
                    <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="col-sm-12 <?php echo $IsSales && !in_array(42, $sales_inv_fields_hide) ? '' : 'hidden' ?> " style="padding-right:0">
                                    <style type="text/css">
                                        .tg {
                                            border-collapse: collapse;
                                            border-spacing: 0;
                                        }

                                        .tg td {
                                            border-color: black;
                                            border-style: solid;
                                            border-width: 1px;
                                            font-family: Arial, sans-serif;
                                            font-size: 14px;
                                            overflow: hidden;
                                            padding: 10px 5px;
                                            word-break: normal;
                                        }

                                        .tg th {
                                            border-color: black;
                                            border-style: solid;
                                            border-width: 1px;
                                            font-family: Arial, sans-serif;
                                            font-size: 14px;
                                            font-weight: normal;
                                            overflow: hidden;
                                            padding: 10px 5px;
                                            word-break: normal;
                                        }

                                        .tg .tg-l0f3 {
                                            background-color: #67fd9a;
                                            text-align: center;
                                            vertical-align: top
                                        }

                                        .tg .tg-jwtr {
                                            background-color: #38fff8;
                                            text-align: center;
                                            vertical-align: top
                                        }

                                        .tg .tg-3oug {
                                            background-color: #fd6864;
                                            text-align: center;
                                            vertical-align: top
                                        }

                                        .tg .tg-j6lv {
                                            background-color: #96fffb;
                                            text-align: center;
                                            vertical-align: top
                                        }

                                        .tg .tg-wohh {
                                            background-color: #9698ed;
                                            text-align: center;
                                            vertical-align: top
                                        }

                                        .tg .tg-7ygo {
                                            background-color: #fffe65;
                                            text-align: center;
                                            vertical-align: top
                                        }

                                        .tg-l0f4 {
                                            background-color: #fd6864;
                                        }

                                        .tg-jwtr2 {
                                            background-color: #9698ed;
                                        }
                                    </style>
                                    <table style="width: 100%;" class="tg">

                                        <tbody>
                                            <tr>
                                                <td class="tg-7ygo"></td>
                                                <td class="tg-7ygo">SPH</td>
                                                <td class="tg-7ygo">CYL.</td>
                                                <td class="tg-7ygo">AXIS.</td>
                                                <td class="tg-7ygo">IPD</td>
                                                <td class="tg-7ygo">ADD</td>

                                            </tr>
                                            <tr>
                                                <td class="tg-l0f3">R</td>
                                                <td class="tg-l0f3"><input type="text" name="r_d_sph" id="r_d_sph" value="<?php echo $IsEdit ?  $edit_arr['Main']['r_d_sph'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-l0f3"><input type="text" name="c_d_cyl" id="c_d_cyl" value="<?php echo $IsEdit ?  $edit_arr['Main']['c_d_cyl'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-l0f3"><input type="text" name="c_d_ax" id="c_d_ax" value="<?php echo $IsEdit ?  $edit_arr['Main']['c_d_ax'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-l0f3"><input type="text" name="c_d_sph" id="c_d_sph" value="<?php echo $IsEdit ?  $edit_arr['Main']['c_d_sph'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-l0f3"><input type="text" name="l_d_cyl" id="l_d_cyl" value="<?php echo $IsEdit ?  $edit_arr['Main']['l_d_cyl'] : ""; ?>" class="form-control ignore "></td>
                                            </tr>
                                            <tr>
                                                <td class="tg-jwtr">L</td>
                                                <td class="tg-jwtr"><input type="text" name="r_r_sph" id="r_r_sph" value="<?php echo $IsEdit ?  $edit_arr['Main']['r_r_sph'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-jwtr"><input type="text" name="c_r_cyl" id="c_r_cyl" value="<?php echo $IsEdit ?  $edit_arr['Main']['c_r_cyl'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-jwtr"><input type="text" name="c_r_ax" id="c_r_ax" value="<?php echo $IsEdit ?  $edit_arr['Main']['c_r_ax'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-jwtr"><input type="text" name="c_r_sph" id="c_r_sph" value="<?php echo $IsEdit ?  $edit_arr['Main']['c_r_sph'] : ""; ?>" class="form-control ignore "></td>
                                                <td class="tg-jwtr"><input type="text" name="l_r_cyl" id="l_r_cyl" value="<?php echo $IsEdit ?  $edit_arr['Main']['l_r_cyl'] : ""; ?>" class="form-control ignore "></td>
                                            </tr>
                                            <tr>
                                                <td class="tg-l0f4">C.L/R</td>
                                                <td class="tg-l0f4"><input type="text" name="cl_r_sph" id="cl_r_sph" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_r_sph'] : ""; ?>"></td>
                                                <td class="tg-l0f4"><input type="text" name="cl_r_cyl" id="cl_r_cyl" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_r_cyl'] : ""; ?>"></td>
                                                <td class="tg-l0f4"><input type="text" name="cl_r_axis" id="cl_r_axis" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_r_axis'] : ""; ?>"></td>
                                                <td class="tg-l0f4"><input type="text" name="cl_r_ipd" id="cl_r_ipd" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_r_ipd'] : ""; ?>"></td>
                                            </tr>
                                            <tr>
                                                <td class="tg-jwtr2">C.L/L</td>
                                                <td class="tg-jwtr2"><input type="text" name="cl_l_sph" id="cl_l_sph" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_l_sph'] : ""; ?>"></td>
                                                <td class="tg-jwtr2"><input type="text" name="cl_l_cyl" id="cl_l_cyl" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_l_cyl'] : ""; ?>"></td>
                                                <td class="tg-jwtr2"><input type="text" name="cl_l_axis" id="cl_l_axis" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_l_axis'] : ""; ?>"></td>
                                                <td class="tg-jwtr2"><input type="text" name="cl_l_ipd" id="cl_l_ipd" class="form-control ignore " value="<?php echo $IsEdit ?  $edit_arr['Main']['cl_l_ipd'] : ""; ?>"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </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="col-md-12 p-0 m-b-10">

                                        <div <?php echo ($IsSales && in_array(34, $sales_inv_fields_hide)) || !$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 (!$IsSales && $IsEdit) ? $edit_arr['Main']['po'] : ($IsSales && $IsEdit ? $edit_arr['Main']['po'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(35, $sales_inv_fields_hide)) || !$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 (!$IsSales && $IsEdit) ? $edit_arr['Main']['project_name_inv'] : ($IsSales && $IsEdit ? $edit_arr['Main']['project_name_inv'] : '') ?>" name="project_name_inv " class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(36, $sales_inv_fields_hide)) || !$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 (!$IsSales && $IsEdit) ? $edit_arr['Main']['project_code'] : ($IsSales && $IsEdit ? $edit_arr['Main']['project_code'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(37, $sales_inv_fields_hide)) || !$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 (!$IsSales && $IsEdit) ? $edit_arr['Main']['job_inv'] : ($IsSales && $IsEdit ? $edit_arr['Main']['job_inv'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(38, $sales_inv_fields_hide)) || !$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 (!$IsSales && $IsEdit) ? $edit_arr['Main']['our_ref'] : ($IsSales && $IsEdit ? $edit_arr['Main']['our_ref'] : '') ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(39, $sales_inv_fields_hide)) || !$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 (!$IsSales && $IsEdit) ? $edit_arr['Main']['supply_date'] : ($IsSales && $IsEdit ? $edit_arr['Main']['supply_date'] : '') ?>" class="form-control" />
                                        </div>
                                        <!-- customer customize   -->
                                        <div <?php echo ($IsSales && in_array(44, $sales_inv_fields_hide)) || (!$IsSales && in_array(25, $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 || $is_copy || $is_return || $IsOrder) ? $edit_arr['Main']['from_place'] : '' ?>" class="form-control" />
                                        </div>
                                        <div <?php echo ($IsSales && in_array(45, $sales_inv_fields_hide)) || (!$IsSales && in_array(26, $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 || $is_copy || $is_return || $IsOrder) ? $edit_arr['Main']['to_place'] : '' ?>" class="form-control" />
                                        </div>

                                        <div <?php echo ($IsSales && in_array(46, $sales_inv_fields_hide)) ||   (!$IsSales && in_array(27, $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 || $is_copy || $is_return || $IsOrder) ?  $edit_arr['Main']['driver_id'] : ''; ?>" data-select-name="<?php echo ($IsEdit || $is_copy || $is_return || $IsOrder) ? $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'); ?> ..." aria-invalid="false"><?php echo ($IsEdit || $is_copy || $is_return || $IsOrder) ? $edit_arr['Main']['Invoice_Description'] : '' ?></textarea>
                                </div>
                                <div class="col-sm-12  <?php echo (empty($invoice_type_details['hide_payment']) || ($IsSales && $permissions->hasPermission($is_actual ? 'act_sales_show_payment_box' : 'sales_show_payment_box')) ? '' : 'hidden') ?>" style="padding-right:0">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" title="<?php echo CommonLanguage::getMessage('library_COA'); ?>" style="color:#6c5ab3;cursor:pointer"></span>
                                        <?php if (($IsSales && $permissions->hasPermission($is_actual ? 'addActualReceipt' : 'addReceipt')) || (!$IsSales && $permissions->hasPermission($is_actual ? 'addActualPayment' : 'addPaymentAccount'))) { ?>
                                            <span class="fa fa-money m-l-5 openFrame" title="<?php echo CommonLanguage::getMessage($IsSales ? 'receipt' : 'payment'); ?>" id="payment_receipt_shortcut" data-main-url="ACC/addpayment<?php echo ($IsSales ? '/Receipt' : '') . ($is_actual ? '/act' : ''); ?>?is_pop=1" data-src="ACC/addpayment<?php echo ($IsSales ? '/Receipt' : '') . ($is_actual ? '/act' : ''); ?>?is_pop=1" style="color:#6c5ab3;cursor:pointer"></span>
                                        <?php }
                                        if ($IsSales && $permissions->hasPermission('new_schedule_bills')) { ?>
                                            <span class="fa fa-money m-l-5 openFrame" id="schedule_bill_shortcut" data-main-url="ACC/schedule_bills?is_pop=1" title="<?php echo CommonLanguage::getMessage('schedule_bills'); ?>" data-src="ACC/schedule_bills?is_pop=1" style="color:#6c5ab3;cursor:pointer"></span>
                                        <?php } ?>
                                    </h5>
                                    <div id="InvoicePaymentSetup" class="no-print">
                                        <div class="Body">
                                            <div class="">
                                                <ul class="nav nav-tabs">
                                                    <li class="active"><a data-toggle="tab" href="#SetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#SetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#SetPaidFormTab_3"><i class="fa fa-cc-visa"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('credit_card'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#other_acc_tab"><i class="fa fa-usd"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('other_amount'); ?></a></li>
                                                </ul>
                                                <div class="tab-content" style="padding:0;overflow:visible">
                                                    <div id="SetPaidFormTab_1" class="tab-pane fade in active">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner cash_tooltip number_formatted_tooltip" style="width:120px">
                                                                            <input type="text" class="form-control number_formatted" data-tooltip="cash_tooltip" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['Transaction_Amount'] : '0' ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <input class="cash_account full-width" id="cash_account" name="cash_account" type="hidden" <?php echo ((isset($invoice_type_details['cash_account_id']) && !empty($invoice_type_details['prevent_change_cash']))) ? 'disabled' : '' ?> value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['Account_ID'] : (!empty($invoice_type_details['cash_account_id']) ? $invoice_type_details['cash_account_id'] : smc_session()['user_accounts']['cash_account_id']) ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['P_Name'] : (!empty($invoice_type_details['cash_account_id']) ? $invoice_type_details['cash_account_name'] . ' - ' . $invoice_type_details['cash_account_code'] : smc_session()['user_accounts']['c_name']) ?>' />
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('user_ref'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control cash_user_ref" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['user_ref'] : '' ?>" /></td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="SetPaidFormTab_2" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner number_formatted_tooltip check_tooltip" style="width:120px">
                                                                            <input type="text" class="form-control number_formatted" data-tooltip="check_tooltip" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Transaction_Amount'] : "0" ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <!--                                                                    <div class="input-group-btn DropDownForForms Closable">-->
                                                                        <input class="check_account full-width" id="check_account" name="check_account" type="hidden" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Account_ID'] : smc_session()['user_accounts']['cheque_account_id'] ?>" data-select-name='<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['P_Name'] : "" ?>' />

                                                                        <!--                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span>< ?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" class="form-control" onkeyup="return false" onkeydown="return false"/>
</button>
<ul class="dropdown-menu">
< ?php for ($x = 0; $x < count($Checks); $x++) { ?>
<li value="< ?php echo $Checks[$x]["Account_Code"]; ?>"><a>< ?php echo $Checks[$x]["Payment_Type_Name"]; ?></a></li>
< ?php } ?>
</ul>-->
                                                                        <!--                                                                    </div>-->
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check'); ?>#</span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control CheckNumValue" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['check_nb'] : '' ?>" /></td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check_due_date'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control check_due_date" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['due_date'] : '' ?>" /></td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('value_date'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control value_date" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['value_date'] : '' ?>" /></td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('user_ref'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control check_user_ref" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['user_ref'] : '' ?>" /></td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="SetPaidFormTab_3" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner number_formatted_tooltip credit_tooltip" style="width:120px">
                                                                            <input type="text" class="form-control number_formatted" data-tooltip="credit_tooltip" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['Transaction_Amount'] : "" ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <!--                                                                    <div class="input-group-btn DropDownForForms Closable">-->
                                                                        <input class="credit_account full-width" id="credit_account" name="credit_account" type="hidden" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['Account_ID'] : "" ?>" data-select-name='<?php echo (($IsEdit || $is_copy) && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['P_Name'] : "" ?>' />

                                                                        <!--                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span>< ?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" class="form-control" onkeyup="return false" onkeydown="return false"/>
</button>
<ul class="dropdown-menu">
< ?php for ($x = 0; $x < count($CreditCards); $x++) { ?>
<li value="< ?php echo $CreditCards[$x]["Account_Code"]; ?>"><a>< ?php echo $CreditCards[$x]["Payment_Type_Name"]; ?></a></li>
< ?php } ?>
</ul>-->
                                                                        <!--                                                                    </div>-->
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('user_ref'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control credit_user_ref" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['user_ref'] : '' ?>" /></td>
                                                                </tr>
                                                                <!--                                                            <tr>
<td><span class="SpanInTableInPayment">< ?php print CommonLanguage::getMessage('approval_code'); ?></span></td>
<td style="text-align:center"><input type="text" class="form-control CardApproval" /></td>
</tr>-->
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="other_acc_tab" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner number_formatted_tooltip other_tooltip" style="width:120px">
                                                                            <input type="text" id="other_amount" class="form-control number_formatted" data-tooltip="other_tooltip" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('others', $edit_arr['Payment'])) ? $edit_arr['Payment']['others']['Transaction_Amount'] : "" ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <input class="other_acc_id full-width" id="other_acc_id" name="other_acc_id" type="hidden" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('others', $edit_arr['Payment'])) ? $edit_arr['Payment']['others']['Account_ID'] : "" ?>" data-select-name='<?php echo (($IsEdit || $is_copy) && array_key_exists('others', $edit_arr['Payment'])) ? $edit_arr['Payment']['others']['P_Name'] : "" ?>' />
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('user_ref'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control" id="other_user_ref" value="<?php echo (($IsEdit || $is_copy) && array_key_exists('others', $edit_arr['Payment'])) ? $edit_arr['Payment']['others']['user_ref'] : '' ?>" /></td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="alert alert-danger <?php echo $IsEdit && !empty($edit_arr['Person']['other_pay_acc_id']) && smc_session()['default_setting']['activate_autofill_other_amount'] == 1 ? '' : 'hidden' ?>"><?php echo CommonLanguage::getMessage('check_other_amt_alert') ?></div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3 col-sm-height   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 <?php echo ($IsSales && smc_session()['default_setting']['activate_sales_profit_margin'] == 1 && $permissions->hasPermission($is_actual ? 'act_view_profit' : 'view_profit')) ? '' : 'hidden' ?>"><?php print CommonLanguage::getMessage('total_profit'); ?><span class="form-control ignore" id="total_profit"></span> </h5>
                                    <?php if ($IsSales) { ?>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10  <?php echo ($IsSales && !in_array(27, $sales_inv_fields_hide) ? '' : 'hidden') ?>"> <?php print CommonLanguage::getMessage('shipping_company_name'); ?>
                                            <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/shipping_companies?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                            <input class=" full-width" id="shipping_company_id" name="shipping_company_id" type="hidden" value="<?= (($IsEdit || $is_copy) && !empty($edit_arr['Main']['shipping_company_id'])) ? $edit_arr['Main']['shipping_company_id'] : ''; ?>" data-select-name='<?= json_encode((($IsEdit || $is_copy) && !empty($edit_arr['Main']['shipping_company_name'])) ? $edit_arr['Main']['shipping_company_name'] : ''); ?>' />
                                        </h5>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10 <?php echo ((($IsEdit || $is_copy) && !empty($edit_arr['Main']['ship_comp_acc_id'])) ? '' : 'hidden'); ?>  shipping_account_data" data-main-shipping-account-id="<?php echo ((($IsEdit || $is_copy) && !empty($edit_arr['Main']['ship_comp_acc_id'])) ? $edit_arr['Main']['ship_comp_acc_id'] : ''); ?>"><input type="checkbox" id="is_invoice_total_on_shipping" <?php echo ((($IsEdit || $is_copy) && !empty($edit_arr['Main']['is_invoice_total_on_shipping'])) ? 'checked' : ''); ?> /><?php echo CommonLanguage::getMessage('is_invoice_total_on_shipping'); ?></h5>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10 <?php echo ((($IsEdit || $is_copy) && !empty($edit_arr['Main']['ship_comp_acc_id'])) ? '' : 'hidden'); ?>  shipping_account_data" data-main-shipping-account-id="<?php echo ((($IsEdit || $is_copy) && !empty($edit_arr['Main']['ship_comp_acc_id'])) ? $edit_arr['Main']['ship_comp_acc_id'] : ''); ?>"><input type="checkbox" id="trans_on_change_status" <?php echo ((($IsEdit || $is_copy) && !empty($edit_arr['Main']['trans_on_change_status'])) ? 'checked' : ''); ?> /><?php echo CommonLanguage::getMessage('generate_trans_on_status'); ?></h5>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10  <?php echo ($IsSales && !in_array(26, $sales_inv_fields_hide) ? '' : 'hidden') ?>"> <?php print CommonLanguage::getMessage('shipping_note'); ?>
                                            <input class="form-control" id="shipping_note" name="shipping_note" value="<?= (($IsEdit || $is_copy) && !empty($edit_arr['Main']['shipping_note'])) ? $edit_arr['Main']['shipping_note'] : ''; ?>" />
                                        </h5>

                                    <?php } ?>


                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10  <?php echo (($IsSales && !in_array(27, $sales_inv_fields_hide)) || !$IsSales ? '' : 'hidden') ?>"> <?php print CommonLanguage::getMessage('shipping_code'); ?>
                                        <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="Shipping_Code" name="Shipping_Code" type="hidden" value="<?= (($IsEdit || $is_copy) && !empty($edit_arr['Main']['shipping_id'])) ? $edit_arr['Main']['shipping_id'] : smc_session()['user_accounts'][$IsSales ? 'sales_ship_account_id' : 'pur_ship_account_id']; ?>" data-select-name='<?= json_encode((($IsEdit || $is_copy) && !empty($edit_arr['Main']['shipping_name'])) ? $edit_arr['Main']['shipping_name'] : smc_session()['user_accounts'][$IsSales ? 'ss_name' : 'ps_name']); ?>' />
                                    </h5>


                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10  <?php echo (($IsSales && !in_array(28, $sales_inv_fields_hide)) || !$IsSales ? '' : 'hidden') ?>"> <?php print CommonLanguage::getMessage('shipping'); ?><input type="text" class="form-control ignore" id="Shipping" value="<?php echo ($IsEdit || $is_copy || $IsOrder) ? $edit_arr['Main']['shipping'] : 0 ?>" /> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10" <?php echo (!$IsSales && $permissions->hasPermission($is_actual ? ($is_noqty ? 'pur_noqty_actual_purchase_add_extra_cost' : 'actual_purchase_add_extra_cost') : ($is_noqty ? 'pur_noqty_add_extra_cost' : 'add_extra_cost')) ? '' : 'hidden') ?>> <span id="main_extra_icon" class="fa fa-plus-circle <?php echo smc_session()['default_setting']['extra_cost_type'] == 1 ? '' : 'hidden' ?>" style="color: #8a7dbe;cursor: pointer;"></span>&nbsp;<?php print CommonLanguage::getMessage('extra_cost'); ?><input type="text" class="form-control ignore" id="extra_cost" <?php echo smc_session()['default_setting']['extra_cost_type'] == 1 ? 'readonly' : '' ?> value="<?php echo ($IsEdit || $is_copy || $IsOrder) ? (!$IsSales ? $edit_arr['Main']['extra_cost'] : 0) : 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>
                                    <?php if ($IsSales && smc_session()['default_setting']['activate_card_tax'] == 1) { ?>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('card_tax'); ?> <input type="text" class="form-control" id="card_tax" value="<?php echo ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['tax_amount'] : 0 ?>" data-tax="<?php echo ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['class_tax'] : 0 ?>" /></h5>
                                    <?php } ?>
                                    <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($is_actual ? 'actual_sales_discount_on_invoice' : 'sales_discount_on_invoice')) ? 'disabled' : '' ?> id="InvoiceDiscountInput" value="<?php echo ($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? $edit_arr['Main']['Discount'] : 0 ?>" /> %</h5>

                                    <div class="disc_div <?php echo ($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? (!empty($edit_arr['Main']['is_ttc']) ? 'hidden' : '') : (($IsSales && smc_session()['class_is_ttc']) || (!$IsSales && smc_session()['default_setting']['activate_ttc']) ? 'hidden' : '') ?>">
                                        <h5 class="no-margin number_formatted_tooltip disc_amt_tooltip"><?php print CommonLanguage::getMessage('discount'); ?><input type="text" class="form-control ignore number_formatted" data-tooltip="disc_amt_tooltip" id="TotalDiscAmount" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_sales_discount_on_invoice' : 'sales_discount_on_invoice')) ? 'disabled' : '' ?> value="<?php echo ($IsEdit || $is_copy || $is_return) ? $edit_arr['Main']['discount_amount'] : 0 ?>" /></h5>
                                    </div>
                                    <div class="ttc_disc_div <?php echo ($IsEdit || $IsOrder || $is_delivery || $is_copy || $is_return) ? (!empty($edit_arr['Main']['is_ttc']) ? '' : 'hidden') : (($IsSales && smc_session()['class_is_ttc']) || (!$IsSales && smc_session()['default_setting']['activate_ttc']) ? '' : 'hidden') ?>">
                                        <!--<h5 class="font-montserrat all-caps small no-margin hint-text bold " > <?php print CommonLanguage::getMessage('ttc_discount'); ?><input type="text" class="form-control ignore " <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_sales_discount_on_invoice' : 'sales_discount_on_invoice')) ? 'disabled' : '' ?> id="TTCInvoiceDiscountInput" value="<?php echo $IsEdit ? $edit_arr['Main']['Discount'] : 0 ?>"/> %</h5>-->
                                        <h5 class="no-margin number_formatted_tooltip ttcdisc_amt_tooltip"><?php print CommonLanguage::getMessage('ttc_discount'); ?><input type="text" class="form-control ignore number_formatted" data-tooltip="ttcdisc_amt_tooltip" id="TTCTotalDiscAmount" <?php echo ($IsSales && !$permissions->hasPermission($is_actual ? 'actual_sales_discount_on_invoice' : 'sales_discount_on_invoice')) ? 'disabled' : '' ?> /></h5>
                                    </div>
                                    <!--<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;background-color: white;">
                                <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('total_paid'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseInvoiceTotalPaid">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 id="local_curr_symbol"><?php echo smc_session()['local_currency_symbol'] ?></span>&nbsp;<span id="Local_Total">0</span></h1>
                                    <div class="<?php echo smc_session()['default_setting']['view_total_qty_in_invoices'] ? '' : 'hidden' ?>">
                                        <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('Total_Quantity'); ?></h5>
                                        <h1 class="no-margin text-white "><span class=""></span>&nbsp;<span id="total_qty">0</span></h1>
                                    </div>
                                </div>
                            </div>

                        </div>

                        <div class="row row-sm-height b-a b-grey <?php echo ($IsSales && in_array(43, $sales_inv_fields_hide)) || !$IsSales ? 'hidden' : '';  ?>" id="signature_div">
                            <div class="col-sm-6 text-right bg-menu col-sm-height padding-15" style="text-align:left !important;background-color: white;">
                                <div class="container">
                                    <div class="row">
                                        <div class="col-md-8 col-md-offset-2">
                                            <h1 style="text-align: center;"><?php print CommonLanguage::getMessage('signature'); ?></h1>
                                            <hr>
                                            <div id="canvasDiv" style="border-style: inset;"></div>
                                            <br>
                                            <button type="button" class="btn btn-danger" id="reset-btn">Clear</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="container-sm-height">

                        <?php if (!($is_main_transfer != 0 && $IsSales)) { ?>
                            <button class=" btn btn-primary btn-cons m-b-10 pull-right disabled" id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>
                        <?php } ?>
                        <?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_invoice'); ?></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-success-darker btn-cons m-b-10 pull-right disabled   <?php echo $IsEdit ? ' ' : '' ?>" id="PrintBtn1" 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_delv'); ?></span></button>
                        <?php if ($IsSales && $permissions->hasPermission($is_actual ? 'actual_print_paid_amount' : 'print_paid_amount') && smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 0) { ?>
                            <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled " id="print_paid_amount" 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_paid_amount'); ?></span></button>
                        <?php } ?>

                        <?php if (($IsSales &&$permissions->hasPermission('editInvoice')) || (!$IsSales &&$permissions->hasPermission('editPurchase'))) { ?>
                        <button class=" btn btn-success-darker btn-cons m-b-10 pull-right disabled" id="EditBtn" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="fa fa-print"></i> <span class="bold">Edit</span></button>
                        <?php } ?>


                        <?php if ($permissions->hasPermission('signature')) { ?>
                            <button class=" btn btn-primary btn-cons m-b-10 pull-right  <?php echo ($IsSales && in_array(43, $sales_inv_fields_hide)) || !$IsSales ? 'hidden' : '';  ?> " id="open_signature" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('signature'); ?></span></button>
                        <?php } ?>

                        <div class="pull-right form-group  <?php echo (!$IsSales || ($IsEdit && $IsSales && $edit_arr['Main']['Invoice_Status'] != 3)) ? 'hidden' : '' ?>" style="margin-right: 42px;">
                            <div class="input-group"><label><?php print CommonLanguage::getMessage('pending'); ?></label></div>


                            <div class="input-group"><input type="checkbox" id="pending" name="pending" <?php echo (  ($IsEdit && $IsSales && $edit_arr['Main']['Invoice_Status'] == 3)) ? 'checked' : '' ?> /></div>
                        </div>

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

</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="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 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('discount_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 bs-example-modal-md" id="ProfitProceedModal" 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('sales_profit_alert') . ' <span class="red-star">' . smc_session()['default_setting']['sales_profit_margin_percent'] . ' % ?</span>' ?></p>
                        <p><?php print CommonLanguage::getMessage('Proceed') . ' ?' ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger " data-dismiss="modal" style="width:auto"><?php echo CommonLanguage::getMessage('Cancel') ?></button>
                <button type="button" class="btn btn-primary " id="proceed_profit" style="width:auto"><?php echo CommonLanguage::getMessage('proceed') ?></button>
            </div>

        </div>
    </div>
</div>
<div class="modal fade" id="items-modal" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i></button>
                <h4 class="modal-title text-center"></h4>
            </div>
            <div class="modal-body form-group">
                <div id="items-alert"></div>
                <div class="row m-b-10">
                    <div class="col-md-12">
                        <div class="col-md-3 ">
                            <label><?php print CommonLanguage::getMessage('family'); ?></label>
                            <input id="family_filter" type="hidden" class=" full-width" />
                        </div>
                        <div class="col-md-3 ">
                            <label><?php print CommonLanguage::getMessage('Category'); ?></label>
                            <input id="category_filter" type="hidden" class="full-width" />
                        </div>

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

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

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

                            </div>
                        </div>
                        <div class="col-md-2 pull-right">
                            <button id="fill_items" class="btn btn-primary  full-width"><?php echo CommonLanguage::getMessage('proceed') ?></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade 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>

<div class="modal fade " id="extra_cost_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <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"><?php echo CommonLanguage::getMessage('extra_cost') ?></h5>
                </div>
                <div class="modal-body">
                    <div id="extra_cost_alert"></div>
                    <div class="row ">

                        <div id="extra_main_div">
                            <div class="col-md-12 form-group">
                                <div class="col-md-2">
                                    <label><?php echo CommonLanguage::getMessage('Type') ?></label>
                                </div>
                                <div class="col-md-1">
                                    <label><?php echo CommonLanguage::getMessage('Amount') ?></label>
                                </div>
                                <div class="col-md-2">
                                    <label><?php echo CommonLanguage::getMessage('Currency') ?></label>
                                </div>
                                <div class="col-md-1">
                                    <label><?php echo CommonLanguage::getMessage('Rate') ?><span class="red-star">&nbsp;(<?php echo smc_session()['local_currency_symbol'] ?>)</span></label>
                                </div>
                                <div class="col-md-2">
                                    <label><?php echo CommonLanguage::getMessage('debit_account') ?></label>
                                </div>
                                <div class="col-md-2">
                                    <label><?php echo CommonLanguage::getMessage('credit_account') ?></label>
                                </div>
                                <div class="col-md-1">
                                    <label><?php echo CommonLanguage::getMessage('note') ?></label>
                                </div>

                            </div>
                            <?php
                            //                            if (!$IsSales && $IsEdit && !empty($edit_arr['extra_cost'])) {
                            //                                foreach ($edit_arr['extra_cost'] as $ex_row) {
                            ?>
                            <!--                                    <div class="col-md-12 extra_row m-b-10">
                                                                    <div class="col-md-2">
                                                                        <select class="full-width extra_cost_type" data-init-plugin="select2">
                            
                                                                            <option value="0" <?php echo $ex_row['type'] == 0 ? 'selected' : '' ?>><?php echo CommonLanguage::getMessage('extra_cost'); ?></option>
                                                                            <option  value="1" <?php echo $ex_row['type'] == 1 ? 'selected' : '' ?>  ><?php echo CommonLanguage::getMessage('ctn'); ?></option>
                                                                            <option  value="2" <?php echo $ex_row['type'] == 2 ? 'selected' : '' ?>  ><?php echo CommonLanguage::getMessage('fob'); ?></option>
                                                                        </select>                                           
                                                                    </div>
                                                                    <div class="col-md-1">
                                                                        <input class="extra_cost_amount form-control" type="number" min="0" step="any" value="<?php echo $ex_row['amount'] ?>" />
                                                                    </div>
                                                                    <div class="col-md-2">
                                                                        <select class="full-width extra_cost_currency" data-init-plugin="select2">
                            
                                                                            <option mysymbol="" value="0"  ><?php echo CommonLanguage::getMessage('Select'); ?></option>
                            <?php foreach ($currency_list as $currency) : ?>
                                                                                                                                    <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" value="<?php echo $currency['Currency_ID']; ?>" <?php echo $currency['Currency_ID'] == $ex_row['currency_id'] ? 'selected' : '' ?>><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
<?php endforeach; ?>
                                                                        </select>                          
                                                                    </div>
                                                                    <div class="col-md-1">
                                                                        <input type="number" class="extra_cost_rate form-control" <?php echo $ex_row['currency_id'] == smc_session()['local_currency'] ? 'disabled' : '' ?> min="0" step="any" value="<?php echo $ex_row['current_rate'] ?>"/>
                                                                    </div>
                                                                    <div class="col-md-2">
                                                                        <input type="hidden" class="extra_cost_debit_acc full-width" value="<?php echo $ex_row['debit_acc_id'] ?>" data-select-name='<?= json_encode($ex_row['debit_acc_name']) ?>' />
                                                                    </div>
                                                                    <div class="col-md-2">
                                                                        <input type="hidden" class="extra_cost_credit_acc full-width"  value="<?php echo $ex_row['credit_acc_id'] ?>" data-select-name='<?= json_encode($ex_row['credit_acc_name']) ?>'/>
                                                                    </div>
                                                                    <div class="col-md-1">
                                                                        <input type="text" class="note form-control"  value="<?php echo $ex_row['note'] ?>" />
                                                                    </div>
                                                                    <div class="col-md-1 AddButtons">
                                                                        <span class="fa fa-plus-circle add_extra_row" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                                                        <span class="fa fa-minus-circle del_extra_row" style="color:#ed9421;margin-top:15px;"></span>
                                                                    </div>
                                                                </div>-->
                            <?php
                            //                                }
                            //                            }else {
                            ?>
                            <div class="col-md-12 extra_row m-b-10">
                                <div class="col-md-2">
                                    <select class="full-width extra_cost_type" data-init-plugin="select2">

                                        <option mysymbol="" value="0"><?php echo CommonLanguage::getMessage('extra_cost'); ?></option>
                                        <option mysymbol="" value="1"><?php echo CommonLanguage::getMessage('ctn'); ?></option>
                                        <option mysymbol="" value="2"><?php echo CommonLanguage::getMessage('fob'); ?></option>
                                    </select>
                                </div>
                                <div class="col-md-1">
                                    <input class="extra_cost_amount form-control" type="number" min="0" step="any" />
                                </div>
                                <div class="col-md-2">
                                    <select class="full-width extra_cost_currency" data-init-plugin="select2">

                                        <option mysymbol="" value="0" selected><?php echo CommonLanguage::getMessage('Select'); ?></option>
                                        <?php foreach ($currency_list as $currency) : ?>
                                            <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-1">
                                    <input type="number" class="extra_cost_rate form-control" min="0" step="any" />
                                </div>
                                <div class="col-md-2">
                                    <input type="hidden" class="extra_cost_debit_acc full-width" />
                                </div>
                                <div class="col-md-2">
                                    <input type="hidden" class="extra_cost_credit_acc full-width" />
                                </div>
                                <div class="col-md-1">
                                    <input type="text" class="note form-control" />
                                </div>
                                <div class="col-md-1 AddButtons">
                                    <span class="fa fa-plus-circle add_extra_row" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                    <span class="fa fa-minus-circle del_extra_row" style="color:#ed9421;margin-top:15px;"></span>
                                </div>
                            </div>
                            <?php // }  
                            ?>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary " id="proceed_extra_cost" style="width:auto"><?php echo CommonLanguage::getMessage('proceed') ?></button>

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

<?php include 'Views/POS/product_options_modal.php'; ?>
<script>
    $(document).ready(() => {
        var canvasDiv = document.getElementById('canvasDiv');
        var canvas = document.createElement('canvas');
        canvas.setAttribute('id', 'canvas');
        canvasDiv.appendChild(canvas);
        $("#canvas").attr('height', $("#canvasDiv").outerHeight());
        $("#canvas").attr('width', $("#canvasDiv").width());
        if (typeof G_vmlCanvasManager != 'undefined') {
            canvas = G_vmlCanvasManager.initElement(canvas);
        }

        context = canvas.getContext("2d");
        $('#canvas').mousedown(function(e) {
            var offset = $(this).offset()
            var mouseX = e.pageX - this.offsetLeft;
            var mouseY = e.pageY - this.offsetTop;

            paint = true;
            addClick(e.pageX - offset.left, e.pageY - offset.top);
            redraw();
        });

        $('#canvas').mousemove(function(e) {
            if (paint) {
                var offset = $(this).offset()
                //addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                addClick(e.pageX - offset.left, e.pageY - offset.top, true);
                console.log(e.pageX, offset.left, e.pageY, offset.top);
                redraw();
            }
        });

        $('#canvas').mouseup(function(e) {
            paint = false;
        });

        $('#canvas').mouseleave(function(e) {
            paint = false;
        });

        var clickX = new Array();
        var clickY = new Array();
        var clickDrag = new Array();
        var paint;

        function addClick(x, y, dragging) {
            clickX.push(x);
            clickY.push(y);
            clickDrag.push(dragging);
        }

        $("#reset-btn").click(function() {
            context.clearRect(0, 0, window.innerWidth, window.innerWidth);
            clickX = [];
            clickY = [];
            clickDrag = [];
        });

        // $(document).on('click', '#btn-save', function() {
        //     var mycanvas = document.getElementById('canvas');
        //     var img = mycanvas.toDataURL("image/png");
        //     anchor = $("#signature");
        //     anchor.val(img);
        //     //$("#signatureform").submit();

        // });

        var drawing = false;
        var mousePos = {
            x: 0,
            y: 0
        };
        var lastPos = mousePos;

        canvas.addEventListener("touchstart", function(e) {
            mousePos = getTouchPos(canvas, e);
            var touch = e.touches[0];
            var mouseEvent = new MouseEvent("mousedown", {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            canvas.dispatchEvent(mouseEvent);
        }, false);


        canvas.addEventListener("touchend", function(e) {
            var mouseEvent = new MouseEvent("mouseup", {});
            canvas.dispatchEvent(mouseEvent);
        }, false);


        canvas.addEventListener("touchmove", function(e) {

            var touch = e.touches[0];
            var offset = $('#canvas').offset();
            var mouseEvent = new MouseEvent("mousemove", {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            canvas.dispatchEvent(mouseEvent);
        }, false);



        // Get the position of a touch relative to the canvas
        function getTouchPos(canvasDiv, touchEvent) {
            var rect = canvasDiv.getBoundingClientRect();
            return {
                x: touchEvent.touches[0].clientX - rect.left,
                y: touchEvent.touches[0].clientY - rect.top
            };
        }


        var elem = document.getElementById("canvas");

        var defaultPrevent = function(e) {
            e.preventDefault();
        }
        elem.addEventListener("touchstart", defaultPrevent);
        elem.addEventListener("touchmove", defaultPrevent);


        function redraw() {
            //
            lastPos = mousePos;
            for (var i = 0; i < clickX.length; i++) {
                context.beginPath();
                if (clickDrag[i] && i) {
                    context.moveTo(clickX[i - 1], clickY[i - 1]);
                } else {
                    context.moveTo(clickX[i] - 1, clickY[i]);
                }
                context.lineTo(clickX[i], clickY[i]);
                context.closePath();
                context.stroke();
            }
        }
    })
</script>

<script>
    var 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')); ?>,
        discount_alert = <?php echo json_encode(CommonLanguage::getMessage('discount_alert')); ?>,
        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')); ?>,
        cost_percent_validate = <?php echo json_encode(CommonLanguage::getMessage('cost_percent_validate')); ?>,
        have_not_saved = <?php echo json_encode(CommonLanguage::getMessage('have_not_saved')); ?>,
        choose_filter_alert = <?php echo json_encode(CommonLanguage::getMessage('choose_filter_alert')); ?>,
        limit_alert = <?php echo json_encode(CommonLanguage::getMessage('limit_alert')); ?>,
        empty_items_alert = <?php echo json_encode(CommonLanguage::getMessage('empty_items_alert')); ?>,
        default_vat = <?php echo json_encode(smc_session()['vat_percent']); ?>,
        negative_sales = <?php echo json_encode(smc_session()['default_setting']['negative_sales']); ?>,
        activate_sales_profit_margin = <?php echo json_encode(smc_session()['default_setting']['activate_sales_profit_margin']); ?>,
        fill_purchase_duedate_from_bill = <?php echo json_encode(smc_session()['default_setting']['fill_purchase_duedate_from_bill']); ?>,
        profit_percent = <?php echo json_encode(smc_session()['default_setting']['sales_profit_margin_percent']); ?>;
    var IsSalesMode = <?php echo $IsSales ? "true" : "false"; ?>,
        IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
        IsOrderMode = <?php echo $IsOrder ? "true" : "false"; ?>,
        is_delivery = <?php echo $is_delivery ? "true" : "false"; ?>,
        is_note = <?php echo $is_note ? "true" : "false"; ?>,
        is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
        is_copy = <?php echo $is_copy ? "true" : "false"; ?>,
        is_return = <?php echo $is_return ? "true" : "false"; ?>,
        is_noqty = <?php echo $is_noqty ? "true" : "false"; ?>,
        is_data_collector = <?php echo $is_data_collector ? "true" : "false"; ?>;
    var CurrencyRate = <?php echo json_encode($Extable); ?>,
        ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
        loc_inv_data = IsEditMode ? <?php echo json_encode(!empty($edit_arr['item_loc']) ? $edit_arr['item_loc'] : array()) ?> : [];
    file_id = is_data_collector ? <?php echo json_encode($file_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']); ?>,
        local_currency_symbol = <?php echo json_encode(smc_session()['local_currency_symbol']); ?>,
        second_currency = <?php echo json_encode(smc_session()['default_setting']['second_currency']); ?>,
        second_currency_symbol = <?php echo json_encode(smc_session()['second_currency']['symbol']); ?>,
        activate_expiry_date = <?php echo json_encode(smc_session()['default_setting']['activate_expiry_date']); ?>,
        activate_ttc = <?php echo json_encode(smc_session()['default_setting']['activate_ttc']); ?>,
        activate_second_vat = <?php echo json_encode(smc_session()['default_setting']['activate_second_vat']); ?>,
        purchase_restrict_product_supplier = <?php echo json_encode(smc_session()['default_setting']['purchase_restrict_product_supplier']); ?>,
        uom_arr = <?php echo json_encode($all_uom); ?>;
    var inv_nb = <?php echo json_encode($IsSales ? CommonLanguage::getMessage('invoice_nb') : CommonLanguage::getMessage('purchase') . ' #'); ?>;
    var TotalInvoice = 0,
        TotalDiscount = 0,
        primary_total = 0,
        total_profit = 0,
        TotalInvoiceWithoutDiscount = 0,
        vatVal = 0,
        totalvat = 0,
        vat1_total, vat2_total = 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,
        wrong_time = <?php echo json_encode(CommonLanguage::getMessage('wrong_time')); ?>

        ;
    var CheckSubmit = true,
        has_vat_permission = <?php echo $permissions->hasPermission($IsSales ? 'sales_vat' : ($is_noqty ? 'pur_noqty_purchase_vat' : 'purchase_vat')) ? 'true' : 'false'; ?>,
        has_sales_cost_perm = <?php echo $has_sales_cost_perm ? 'true' : 'false'; ?>,
        has_ledger_perm = <?php echo $permissions->hasPermission('ledger') ? 'true' : 'false'; ?>,
        has_purchase_cost_perm = <?php echo $has_purchase_cost_perm ? 'true' : 'false'; ?>,
        has_sales_last_price = <?php echo json_encode($has_sales_last_price); ?>,
        has_stock_trans_perm = <?php echo json_encode($permissions->hasPermission('stock_transactions')); ?>,
        has_det_sales_rep_perm = <?php echo json_encode($permissions->hasPermission($is_actual ? 'act_detailed_sold_items' : 'detailed_sold_items')); ?>,
        has_edit_prod_perm = <?php echo json_encode($permissions->hasPermission('EditProduct')); ?>,
        change_sales_unit_price = <?php echo json_encode($permissions->hasPermission($is_actual ? 'actual_change_sales_unit_price' : 'change_sales_unit_price')); ?>,
        allow_purchase_vat_edit = <?php echo json_encode(smc_session()['allow_purchase_vat_edit']); ?>,
        auto_fill_cost = <?php echo json_encode(in_array('0', $autofill_cost) ? 1 : 0); ?>,
        auto_fill_zerocost = <?php echo json_encode(in_array('0', $autofill_zerocost) ? 1 : 0); ?>,
        print_template_settings = <?php echo json_encode(smc_session()['default_setting']['print_template_settings']); ?>,
        purchase_show_all_accounts = <?php echo json_encode(smc_session()['default_setting']['purchase_show_all_accounts']); ?>,
        show_ret_cancel_alert_sales = <?php echo json_encode(smc_session()['default_setting']['show_ret_cancel_alert_sales']); ?>,
        sales_show_all_accounts = <?php echo json_encode(smc_session()['default_setting']['sales_show_all_accounts']); ?>,
        show_main_shipping_address = <?php echo json_encode(smc_session()['default_setting']['show_main_shipping_address']); ?>,
        default_round_type = <?php echo json_encode(smc_session()['default_setting']['round_type']); ?>,
        activate_autofill_other_amount = <?php echo json_encode(smc_session()['default_setting']['activate_autofill_other_amount']); ?>,
        stop_autofill_other_amount = IsEditMode ? 1 : 0,
        activate_lot = <?php echo json_encode(($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) || (!$IsSales && $is_noqty && in_array(8, $purchase_noqty_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)) || (!$IsSales && $is_noqty && in_array(9, $purchase_noqty_fields_hide)) ? 0 : 1); ?>,
        unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>,
        cash_customer_arr = <?php echo json_encode($cash_customer_arr); ?>,
        is_sec_vat = <?php echo (smc_session()['default_setting']['activate_second_vat'] && smc_session()['default_setting']['activate_second_vat_purchase'] && !$IsSales) || (smc_session()['default_setting']['activate_second_vat'] && $IsSales) ? 'true' : 'false' ?>,
        is_full_paid = <?php echo json_encode(((!$IsEdit || ($IsEdit && smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 0)) && !empty($invoice_type_details['is_full_paid']) ? $invoice_type_details['is_full_paid'] : 0)) ?>,
        old_pays_lang = <?php echo json_encode(($IsEdit && smc_session()['default_setting']['generate_pay_rec_from_inv_pur'] == 1 && !empty($invoice_type_details['is_full_paid']) ? CommonLanguage::getMessage('old_pays_not_updated') : '')) ?>,
        enable_autofill_product_in_invoice = <?php echo json_encode((smc_session()['default_setting']['enable_autofill_product_in_invoice'] == 1 ? '1' : '0')) ?>,
        product_barcode_for_autofill_in_invoice = <?php echo json_encode(smc_session()['default_setting']['product_barcode_for_autofill_in_invoice']) ?>,
        invoice_type_details = <?php echo json_encode($invoice_type_details); ?>,
        is_trigger_cust_change = <?php echo json_encode($IsSales && !$IsEdit && !empty($invoice_type_details) && !is_null($invoice_type_details['customer_id']) && !empty($invoice_type_details['prevent_change_cust']) ? 1 : 0) ?>,
        sales_inv_fields_req = <?php echo json_encode($sales_inv_fields_req); ?>,
        block_title = <?php echo json_encode(CommonLanguage::getMessage('choose_items_nb', null, false)); ?>,
        group_id = <?php echo json_encode($IsSales && !empty($invoice_type_details['customer_group_id']) ? $invoice_type_details['customer_group_id'] : (!empty($invoice_type_details['supplier_group_id']) ? $invoice_type_details['supplier_group_id'] : 0)); ?>,
        check_prod_options = <?php echo json_encode(CommonLanguage::getMessage('check_prod_options')); ?>,
        person_has_other_acc = 0,
        global_cost_arr = <?php echo json_encode(!$IsSales && $IsEdit && !empty($edit_arr['extra_cost']) ? $edit_arr['extra_cost'] : array()) ?>,
        extra_cost_row = '';
    //    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() {

        //$("#PIC_ID").val(58);
        <?php echo smc_session()['user_details']['limit_customer_invoice'] == 1 ? '$("#PIC_ID").val(' . smc_session()['user_details']['Employee_ID'] . ')' : ''; ?>

        //     searchScannedItem('18446fsa',$("#InventoryPurchaseTable tbody tr:eq(0)"))
        if (is_trigger_cust_change) {
            trigger_change_cust_supp()
        }
        //        console.log(invoice_type_details)
        if (IsSalesMode) {
            build_select2($("#shipping_company_id"), "xhr/CommonSearch?col_name=shipping_company_name&col_id=shipping_company_id&table=tbl_shipping_company");
            build_select2($("input[name=PIC_ID]"), "xhr/employeeSearch?customer_id=" + $(".search_supplier").val() + ('salesman_ids' in invoice_type_details ? '&emp_ids=' + invoice_type_details['salesman_ids'] : ''))
            build_select2($("#customer_branch_id"), "xhr/searchCustomerBranch?customer_id=" + $(".search_supplier").val())
            build_select2($("#pos_customer_id"), "xhr/poscustomerSearch")

            $('#search_supplier').on('change', function() {
                $('#customer_branch_id').val('');
                build_select2($('#customer_branch_id'), 'xhr/searchCustomerBranch?customer_id=' + $("#search_supplier").val());
            });

        }
        $("#pos_customer_id").on("change", function() {
            if ($(this).val() != '') {
                $("#search_supplier").val(0).attr("data-select-name", cash_customer_arr['Account_Name'])
                build_select2($("#search_supplier"), (IsSalesMode ? ("xhr/customerSearch?auto_salesman=1") : "xhr/supplierSearch?_tmp=1") + (IsEditMode ? "&is_edited=" + $(".search_supplier").val() : "&Status_ID=1") + (group_id != 0 ? "&group=" + group_id : ""))
                $("#search_supplier").prop("disabled", true)
            } else {
                $("#search_supplier").val('').attr("data-select-name", '')
                build_select2($("#search_supplier"), (IsSalesMode ? ("xhr/customerSearch?auto_salesman=1") : "xhr/supplierSearch?_tmp=1") + (IsEditMode ? "&is_edited=" + $(".search_supplier").val() : "&Status_ID=1") + (group_id != 0 ? "&group=" + group_id : ""))
                $("#search_supplier").prop("disabled", false)

            }
            trigger_change_cust_supp()
        })

        $("#search_supplier").on("change", function() {
            if ($(this).val() != '') {
                $("#pos_customer_id").prop("disabled", true)
            } else {
                $("#pos_customer_id").prop("disabled", false)
            }


            trigger_change_cust_supp()

            //            console.log($("#search_supplier").val())
            //            console.log($(this).select2("data"))
            //            console.log($("#search_supplier").select2("data"))

        });
        //        setTimeout(function(){
        //              $("#search_supplier").trigger("change")
        //        },1500)

        //        $("input[name=PIC_ID]").on("change",function(){
        //            ($(this).select2("data")['selected']==1)
        //            $("input[name=PIC_ID]").val($(this).select2("data")['id']).attr("data-select-name",$(this).select2("data")['text']).trigger("change")
        //        })
        build_select2($("#search_supplier"), (IsSalesMode ? ("xhr/customerSearch?auto_salesman=1") : "xhr/supplierSearch?_tmp=1") + (IsEditMode ? "&is_edited=" + $(".search_supplier").val() : "&Status_ID=1") + (group_id != 0 ? "&group=" + group_id : ""))

        if (IsSalesMode) {
            build_select2($("#Account_Code,#Shipping_Code"), ("xhr/accIDSearch?type=" + (sales_show_all_accounts == 1 ? 'Payment' : 'sales')))
        } else {
            build_select2($("#Account_Code,#Shipping_Code"), ("xhr/accIDSearch?type=" + (purchase_show_all_accounts == 1 ? 'Payment' : 'purchase')))

        }
        build_select2($("#other_acc_id"), ("xhr/accIDSearch?type=Payment"))
        build_select2($(".extra_cost_debit_acc,.extra_cost_credit_acc"), ("xhr/accIDSearch?type=Payment"))

        build_select2($("#driver_id"), "xhr/CommonSearch?col_name=driver_name&col_id=driver_id&table=tbl_drivers");



        build_select2($("#order_filter"), "xhr/search_orders?is_act=" + (is_actual ? '1' : '0') + '&is_sales=' + (IsSalesMode ? '1' : '0'))
        build_select2($("input[name=current_depot_id]"), "xhr/depotSearch" + ('depot_options_ids' in invoice_type_details ? '?depots=' + invoice_type_details['depot_options_ids'] : ''))
        build_select2($("input[name=current_vehicle_id]"), "xhr/TruckSearch")
        build_select2($("input[name=current_employee_id]"), "xhr/employeeSearch")
        build_select2($(".Depot_Loc"), "xhr/depotSearch" + ('depot_options_ids' in invoice_type_details ? '?depots=' + invoice_type_details['depot_options_ids'] : ''), 0, 'diff_class')
        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?type=" + (IsSalesMode ? 0 : 1) + ('class_options_ids' in invoice_type_details ? '&classes=' + invoice_type_details['class_options_ids'] : ''))
        build_select2($("input.item-class"), "xhr/PricingClassSearch?type=1")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        build_select2($("#contra_id"), "xhr/contraSearch")
        build_select2($("#family_filter"), "xhr/CommonSearch?col_name=family_name&col_id=family_id&table=tbl_inventory_family");
        build_select2($("#category_filter"), "xhr/CommonSearch?col_name=Cat_Name&col_id=Cat_ID&table=tbl_product_cat");
        //        build_select2($("#ctn_currency"), "xhr/CommonSearch?col_id=Currency_ID&col_name=Currency_Name&table=tbl_common_currency")
        //        //
        apply_autocomplete($("#inv_truck"), 'xhr/searchInvTruck', function(event, ui, who) {
            who.val(ui.item.truck);
        });
        new Switchery($("#pending").get(0), {
            color: $.Pages.getColor("primary")
        })
        new Switchery($("#enable_tva").get(0), {
            color: $.Pages.getColor("primary")
        })
        $(".CurrencyIndicator").html($("#CurrencyDropDown").attr("data-symbol"))

        $("#other_amount").on("input", function() {
            stop_autofill_other_amount = 1;
        })
        $("#is_invoice_total_on_shipping,#trans_on_change_status").on("click", function() {
            if ($(this).is(":checked")) {
                if ($(this).attr("id") == 'is_invoice_total_on_shipping')
                    $("#trans_on_change_status").prop("checked", false)
                else
                    $("#is_invoice_total_on_shipping").prop("checked", false)
            }
        })
        $("#second_currency_rate,#current_rate").on("keyup", function() {
            change_local_total($("#CurrencyDropDown input").val())
        })
        $("#extra_main_div").on("click", " .fa-plus-circle", function(e) {
            $("#extra_main_div  .fa-minus-circle").css("display", "inline-block")
            var Parent = $(this).parents(".extra_row"),
                NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".select2-container").remove();
            NewItem.find('input').val('')
            NewItem.find("select.extra_cost_currency").val(0).select2()
            NewItem.find("select.extra_cost_type").val(0).select2()
            build_select2($(".extra_cost_debit_acc,.extra_cost_credit_acc", NewItem), ("xhr/accIDSearch?type=Payment"))

            $(".select2-container", NewItem).show();
        });
        $("#extra_main_div").on("click", ".fa-minus-circle", function(e) {
            if ($(".extra_row").length == 1) {
                $('.extra_row input').val('')
                $("select.extra_cost_currency").val(0).select2()
                $("select.extra_cost_type").val(0).select2()
            } else {
                $(this).closest(".extra_row").empty().remove();
            }

        });
        $("#extra_main_div").on("change", "select.extra_cost_currency", function() {
            var rate = ConvertCurrency2(1, $(this).val(), local_currency);
            $(".extra_cost_rate", $(this).parents(".extra_row")).val(rate)
            if ($(this).val() == local_currency)
                $(".extra_cost_rate", $(this).parents(".extra_row")).prop("disabled", true)
            else
                $(".extra_cost_rate", $(this).parents(".extra_row")).prop("disabled", false)

        })
        $("#main_extra_icon").on("click", function() {
            $("#extra_cost_modal .extra_row:gt(0)").remove()
            $("#extra_cost_modal .extra_row:eq(0) input").val("")
            $("#extra_cost_modal .extra_row:eq(0) select.extra_cost_currency").val(0).select2()
            $("#extra_cost_modal .extra_row:eq(0) select.extra_cost_type").val(0).select2()
            build_select2($("#extra_cost_modal .extra_row:eq(0) .extra_cost_debit_acc,#extra_cost_modal .extra_row:eq(0) .extra_cost_credit_acc"), ("xhr/accIDSearch?type=Payment"))

            if (global_cost_arr != '') {
                fill_cost_modal(global_cost_arr)
            }
            $("#extra_cost_modal").attr("data-main", 1).modal("show")

        })
        $("#InventoryPurchaseTable").on("click", "span.extra_icon", function() {
            $("#extra_cost_modal .extra_row:gt(0)").remove()
            $("#extra_cost_modal .extra_row:eq(0) input").val("")
            $("#extra_cost_modal .extra_row:eq(0) select.extra_cost_currency").val(0).select2()
            $("#extra_cost_modal .extra_row:eq(0) select.extra_cost_type").val(0).select2()
            build_select2($("#extra_cost_modal .extra_row:eq(0) .extra_cost_debit_acc,#extra_cost_modal .extra_row:eq(0) .extra_cost_credit_acc"), ("xhr/accIDSearch?type=Payment"))

            var tr = $(this).parents("tr");
            extra_cost_row = tr;
            if (tr.attr("data-cost-arr") != '' && tr.attr("data-cost-arr") != undefined) {
                fill_cost_modal(JSON.parse(tr.attr("data-cost-arr")));
            }
            $("#extra_cost_modal").attr("data-main", 0).modal("show")

        })
        $("#proceed_extra_cost").on("click", function() {
            var is_main = $("#extra_cost_modal").attr("data-main");
            trigger_proceed_extra_cost(is_main);
        })

        $("#extra_cost_modal").on("modal.bs.modal", function() {
            $("#extra_cost_alert").addClass("hidden")
        })

        $("#order_filter").on("change", function() {
            var href = site_link + 'Inventory/addpurchase/order/' + (is_actual ? 'act/' : '') + (IsSalesMode ? 'sales/' : '') + $(this).val();
            window.location = href;
        })

        $("#choose_items").on("click", function() {
            $("#items-alert").addClass("hidden")
            var rows = $("#items_table").dataTable().fnGetNodes();
            for (var i = 0; i < rows.length; i++) {
                $(rows[i]).find('.qty_input,.price_input').val('')
            }
            $("#items-modal").modal("show")
        })
        $("#generate_items").on("click", function() {
            //            if ($("#category_filter").val() == '' && $("#family_filter").val() == '' && $("#name_filter").val() == '') {
            //                $("#items-alert").attr("class", "alert alert-danger").html(choose_filter_alert)
            //                return false;
            //            }
            var data = {
                category: $("#category_filter").val(),
                family: $("#family_filter").val(),
                name: $("#name_filter").val(),
                is_sales: IsSalesMode ? 1 : 0
            }
            $.ajax({
                url: "InventoryAjax/get_products_to_build",
                data: data,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        $("#items_table").DataTable().destroy();
                        $("#items_table tbody").empty().html(v1.responseJSON['html'])
                        if (v1.responseJSON['show_alert'] == 1) {
                            $("#limit_alert").attr("class", "alert alert-danger").html(limit_alert.replace('[[rows]]', v1.responseJSON['row_count']))
                        }
                        RebuildDataTable('<?php echo CommonLanguage::getMessage('items') ?>', [], "", {}, '#items_table', '')
                    }
                }
            });
        })

        $("#fill_items").on("click", function() {
            var data = {
                class_id: $("#pricing_class").val(),
                depot_id: $("#Depot_Loc").val(),
                is_sales: IsSalesMode ? 1 : 0,
                customer_id: IsSalesMode ? $("#search_supplier").val() : '',
                product_ids: [],
                empty_products: []
            };
            var rows = $("#items_table").dataTable().fnGetNodes();
            for (var i = 0; i < rows.length; i++) {
                var qty = parseFloat($(rows[i]).find('.qty_input').val()) || 0;
                if (qty > 0) {
                    data.product_ids.push($(rows[i]).find('.qty_input').attr("data-id"))
                    if ($(rows[i]).find('.price_input').val() == '')
                        data.empty_products.push($(rows[i]).find('.qty_input').attr("data-id"))
                }
            }
            if (data.product_ids.length == 0) {
                $("#items-alert").attr("class", "alert alert-danger").html(empty_items_alert)
                $("#items-modal").animate({
                    scrollTop: 0
                }, 800)
                return false;
            }
            console.log('data fill_items')
            console.log(data)
            $.ajax({
                url: "InventoryAjax/build_products_with_prices",
                data: data,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        console.log('build_products_with_prices')
                        console.log(v1.responseJSON)

                        $.each(v1.responseJSON, function(pid, row) {
                            var TR = $("#InventoryPurchaseTable tbody tr:first-child").clone();
                            $("#InventoryPurchaseTable tbody").append(TR);
                            fix_cloned_row(TR)
                            //                            EnableAutoComplete($(".AutoComplete.CODE", TR).removeClass("AutoAdded"));
                            //                            EnableAutoComplete($(".AutoComplete.ProductName", TR).removeClass("AutoAdded"));
                            //                            $(".select2-container", TR).empty().remove()
                            TR.attr("data-id", pid)
                            //                            TR.attr("data-entry", '')
                            TR.attr("data-vat", (is_actual ? 0 : row.VAT))
                            TR.attr("data-qty", row.Quantity)
                            TR.attr("data-item-disc", row.Product_Limit_Discount)
                            TR.attr("data-tax", row.is_tax)
                            TR.attr("data-expiry", row.is_expiry)
                            TR.attr("data-last-cost", row.LAST_COST)
                            TR.attr("data-last-price", row.last_price)
                            TR.attr("data-conv", row.uom_conv)
                            TR.attr("data-is-service", row.is_service)
                            TR.attr("data-is-option", row.has_optional)
                            TR.attr("recipe-qty", row.recipe_qty)
                            TR.attr("data-depot-val", $("#Depot_Loc").val())
                            TR.attr("data-is-lot", row.is_lot)
                            TR.attr("data-is-serial", row.is_serial)
                            var ref = Math.round(Date.now() + Math.random());
                            TR.attr("data-ref", ref)
                            if (row.has_optional == 1) {
                                //                            build_optional_link(ref)
                                $(".option-tr,.option-main-td", $(TR)).removeClass("hidden")
                            } else {
                                $(".option-tr,.option-main-td", $(TR)).addClass("hidden")
                            }
                            TR.find(".Disc").val(row.disc);
                            if ($("#Class_Currency").text() != '') {
                                TR.attr("data-cost", $("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? row.current_cost : public_round_number(ConvertCurrency2(row.current_cost, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))
                            } else {
                                TR.attr("data-cost", row.current_cost)

                            } //                        TR.attr("data-cost", ConvertCurrency2(row.current_cos, v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val())t)
                            TR.find("input.expiry_date,input.lot_nb,input.serial_nb").attr('data-select-name', '').val('')

                            if (row.is_expiry == 0)
                                TR.find(".expiry_date").addClass("hidden")
                            else {
                                TR.find(".expiry_date").removeClass("hidden");

                                //                                build_select2(TR.find("input.expiry_date"), 'xhr/get_product_expiry?product_id=' + row.ID, '', 'expiry_width');
                            }

                            if (row.is_lot == 1 && activate_lot == 1)
                                TR.find(".lot_nb").removeClass("hidden");
                            else
                                TR.find(".lot_nb").addClass("hidden");
                            if (row.is_serial == 1 && activate_serial == 1)
                                TR.find(".serial_nb").removeClass("hidden");
                            else
                                TR.find(".serial_nb").addClass("hidden");
                            check_discount(TR.find(".Disc"), parseFloat(row.Product_Limit_Discount))
                            TR.find("input.CODE").val(row.Bar_Code)
                            TR.find("input.ProductName").val(row.Name)
                            TR.find("input.vat_percent").val((row.VAT == 1 && !is_actual) ? row.vat_percent : 0)
                            TR.find("input.vat2_percent").val((row.VAT == 1 && !is_actual && is_sec_vat) ? row.vat2_percent : 0)
                            TR.find("input.VATPerItem").val('0')
                            if (row.VAT == 0 || is_actual || !is_sec_vat) {
                                TR.find("input.vat_percent,input.VATPerItem,input.vat2_percent,input.vat2_amount").attr("disabled", "disabled")
                            } else {
                                TR.find("input.vat_percent,input.VATPerItem,input.vat2_percent,input.vat2_amount").removeAttr("disabled")
                            }
                            if ($('#enable_tva').is(":checked") && is_actual && row.VAT == 1) {
                                TR.find("input.vat_percent,input.VATPerItem,input.vat2_percent,input.vat2_amount").attr('disabled', false);
                                TR.find("input.vat_percent").val(Data.vat_percent);
                                TR.find("input.vat2_percent").val(Data.vat2_percent);
                                TR.attr("data-vat", Data.VAT);
                            }
                            if (row.force_change_price == 1) {
                                TR.find("input.UnitPrice").removeAttr("disabled")
                            } else {
                                if (change_sales_unit_price)
                                    TR.find("input.UnitPrice").removeAttr("disabled")
                                else
                                    TR.find("input.UnitPrice").attr("disabled", "disabled")
                            }

                            var myprice = $(".price_input[data-id=" + pid + "]").val() != '' ? $(".price_input[data-id=" + pid + "]").val() : row.Price;
                            if (is_ttc == 1) {
                                if ($(".price_input[data-id=" + pid + "]").val() == '') {
                                    TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? myprice : ConvertCurrency2(myprice, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()))
                                } else {
                                    //                                    alert('here')
                                    var myval = parseFloat($(".price_input[data-id=" + pid + "]").val()) || 0;
                                    fill_price_by_ttc(TR, myval)
                                }
                            } else {
                                TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? myprice : ConvertCurrency2(myprice, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()))

                            }
                            $("select[name=UOM_ID]", TR).empty();
                            var unit_price_hint_text = '';
                            if (has_sales_last_price)
                                unit_price_hint_text += "P: " + (!row.last_price ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(row.last_price, local_currency, $("#CurrencyDropDown input").val())))));
                            if (has_sales_cost_perm)
                                unit_price_hint_text += (unit_price_hint_text == '' ? '' : ' | ') + "C: " + (!row.LAST_COST ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(row.LAST_COST, local_currency, $("#CurrencyDropDown input").val())))));
                            TR.find("input.UnitPrice").next().text(unit_price_hint_text).attr('title', unit_price_hint_text);
                            var product_hint = '';
                            if (display_shelf_locations == 1) {
                                product_hint += row.loc;
                            }
                            if (has_det_sales_rep_perm) {
                                product_hint += '<span class="fa fa-sticky-note m-l-5 openFrame open_detailed_sold_items" data-src="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + row.ID + '&product_name=' + row.Name + '&customer_id=' + $("#search_supplier").val() + '&customer_name=' + $("#search_supplier").select2('data').text + '" data-main-url="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + row.ID + '&product_name=' + row.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                            }
                            if (has_stock_trans_perm) {
                                product_hint += '<span class="fa fa-eye m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=' + row.ID + '&product_name=' + row.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                            }
                            if (has_edit_prod_perm) {
                                product_hint += '<span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/' + row.ID + '?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                            }
                            TR.find('input.Quantity').val($(".qty_input[data-id=" + pid + "]").val())
                            TR.find("input.ProductName").next().html(product_hint)
                            var qty_hint = AddCommas(public_round_number(parseFloat(row.Quantity))) + " in stock";
                            //                            if (event.which != 9)
                            TR.find("input.Quantity").text(qty_hint).attr("title", qty_hint)
                            //                            else
                            //                                TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)

                            TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                            var units_arr = row.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] == row.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                            }
                            TR.find("select[name=UOM_ID]").select2();
                            //                        if ($('#card_tax').attr('data-tax') > 0 && TR.attr('data-tax') == 1) {
                            //                        console.log(row.total_tax)
                            TR.attr('unit-tax', parseFloat(ConvertCurrency2(row.total_tax, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())));
                            //                        } else {
                            //                            TR.attr('unit-tax', 0)
                            //                        }
                            build_select2($("input.item-class", TR), "xhr/PricingClassSearch?type=1")
                            TR.find("input.expiry_date,input[name=current_depot_id],input[name=current_vehicle_id],input[name=current_employee_id]").attr('data-select-name', '').val('')
                            build_select2($("input[name=current_depot_id]", TR), "xhr/depotSearch" + ('depot_options_ids' in invoice_type_details ? '?depots=' + invoice_type_details['depot_options_ids'] : ''))

                            if (IsSalesMode) {
                                if ('oldest_expiry' in row) {
                                    TR.find("input.expiry_date").val(row['oldest_expiry']['expiry_date']).attr("data-select-name", row['oldest_expiry']['expiry_text'] + ' ' + row['def_view_uom_name']);
                                    TR.attr("data-expiry-val", row['oldest_expiry']['expiry_date']);
                                }
                                build_select2(TR.find("input.expiry_date"), function(el) {
                                    var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                                    return 'xhr/get_product_expiry?product_id=' + row.ID + '&depot=' + depot_id;
                                }, '', 'expiry_width');
                                build_select2(TR.find("input.lot_nb"), function(el) {
                                    var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                                    return 'xhr/get_product_lot?product_id=' + row.ID + '&depot=' + depot_id;
                                }, '', 'expiry_width');
                                build_select2(TR.find("input.serial_nb"), function(el) {
                                    var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                                    return 'xhr/get_product_serial?product_id=' + row.ID + '&depot=' + depot_id;
                                }, '', 'expiry_width');
                                build_select2($("input[name=current_vehicle_id]", TR), "xhr/TruckSearch")
                                build_select2($("input[name=current_employee_id]", TR), "xhr/employeeSearch")


                            } else {
                                $("input.expiry_date", TR).datepicker({
                                    autoclose: true
                                });
                            }
                            build_select2($("input[name=current_vehicle_id]", TR), "xhr/TruckSearch")

                            //                            $(".select2-container", TR).show()
                        })
                        $("input.Quantity:last").trigger('keyup')
                        UpdateTable()
                        $("#items-modal").modal("hide")
                        //                        return false;
                    }
                }
            })
        }) 

        $("#fill_price").on("input", function() {
            var rows = $("#items_table").dataTable().fnGetNodes();
            for (var i = 0; i < rows.length; i++) {
                $(rows[i]).find('.price_input').val($("#fill_price").val());
            }
        })



        $("#current_rate").on("keyup", function() {
            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()
            }
            setTimeout("UpdateTable()", 100)
            if (percent_flag == 2) {
                if (is_ttc == 1) {
                    $("#TTCTotalDiscAmount").trigger("keyup")
                } else {
                    $("#TotalDiscAmount").trigger("keyup")
                }
            } else {
                $("#InvoiceDiscountInput").trigger("keyup")
            }
        })
        $("#InventoryPurchaseTable").on("change", "input[name=current_depot_id]", function() {
            var me = $(this).parents('tr'),
                current_depot = ($(this).val() != '' ? $(this).val() : $("#Depot_Loc").val());
            var item_arr = {
                items: [me.attr("data-id")],
                depot_id: current_depot
            };
            $(this).parents("tr").attr("data-depot-val", current_depot)
            if ($("input.lot_nb", me).val() != '' || $("input.serial_nb", me).val() != '' || $("input.expiry_date", me).val() != '') {
                toastr.error('<?php echo CommonLanguage::getMessage('serial_lot_expiry_alert') ?>')
                $("input.lot_nb,input.serial_nb,input.expiry_date", me).val('').attr("data-select-name", "").trigger('change')
            }
            $.ajax({
                url: "InventoryAjax/ReturnQtyPerDepot",
                data: item_arr,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        $.each(Data, function(index, value) {
                            var tr_conv = parseFloat(me.attr("data-conv"));
                            var stock_qty = parseFloat(value['qty']) || 0;
                            if (IsEditMode && value['Product_ID'] in loc_inv_data) {
                                if (item_arr.depot_id in loc_inv_data[value['Product_ID']])
                                    stock_qty += parseFloat(loc_inv_data[value['Product_ID']][item_arr.depot_id]) || 0;
                            }
                            var qty_hint = AddCommas(public_round_number(parseFloat(stock_qty / tr_conv))) + " in stock";
                            me.find(".Quantity").next().text(qty_hint).attr("title", qty_hint)
                            me.find("input.ProductName").next().text(value['loc'])
                            me.attr("data-qty", (stock_qty / tr_conv))
                        })
                        UpdateSubmitButtonStatus()

                    }
                }
            })
        })

        //#public_round_number
        $("#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.is_collected_points", function() {
            console.log('is_collected_points')

            val = $(this).val()
            mytr = $(this).parents("tr");
            
            if ($("input.is_collected_points").is(":checked")) {
               // valdisc = 100;
                mytr.find(".Disc").val(100);
            }else{ 
                mytr.find(".Disc").val(0);
            } 
            UpdateTable()
        }) 

        // $("#InventoryPurchaseTable").on("keyup", "input.UnitPrice,input.VATPerItem,input.vat_percent,input.ttc_price", function() {        
        //     console.log('input.UnitPrice change')
        //     console.log($(this).val())
        //     val = $(this).val()
        //     $(this).val(public_round_number(val))
        // })

        $("#InventoryPurchaseTable").on("change", "select.UOM_ID", function() {
            var me = $(this).parents("tr"),
                class_id = $("#pricing_class").val(),
                currency_id = $("#CurrencyDropDown input").val();
            //            if (IsSalesMode) {
            var depot_id = me.find('input[name=current_depot_id]').val() != '' ? me.find('input[name=current_depot_id]').val() : $("#Depot_Loc").val();
            var UOMData = {
                pid: $(this).parents("tr").attr("data-id"),
                uid: $(this).val(),
                depot_id: depot_id,
                class_id: class_id,
                currency_id: currency_id
            };
            //            } 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'])
                        var cost = ConvertCurrency2(v1.responseJSON['current_cost'], v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val());
                        me.attr('data-cost', (parseFloat(v1.responseJSON['conversion_amount'] || 0) * parseFloat(cost || 0)))
                        if (IsSalesMode || (class_id != '' && class_id != 0)) {
                            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)
                        }
                        var last_cost = parseFloat(ConvertCurrency2(v1.responseJSON['local_cost'], local_currency, $("#CurrencyDropDown input").val())) * (parseFloat(v1.responseJSON['conversion_amount'] || 0));
                        me.find("input.UnitPrice").next().text("last cost: " + AddCommas(public_round_number(last_cost)));
                        var stock_qty = (parseFloat(v1.responseJSON['qty']) || 0) * (parseFloat(v1.responseJSON['conversion_amount']) || 0);
                        //                        console.log('prod: ' + UOMData.pid)
                        //                        console.log('depot: ' + depot_id)
                        if (IsEditMode && UOMData.pid in loc_inv_data) {
                            if (depot_id in loc_inv_data[UOMData.pid])
                                stock_qty += parseFloat(loc_inv_data[UOMData.pid][depot_id]) || 0;
                        }
                        stock_qty = stock_qty / v1.responseJSON['conversion_amount'];
                        var qty_hint = AddCommas(public_round_number(parseFloat(stock_qty))) + " in stock";
                        me.find("input.Quantity").next().text(qty_hint).attr("qty_hint")
                        me.find("input.Disc").val(v1.responseJSON['disc'])
                        me.attr("data-qty", stock_qty)
                        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 || is_data_collector || IsOrderMode || is_delivery || is_note || is_copy || is_return)
            $("#InvoicePaymentSetup").find("input.form-control").trigger('keyup')
        $("#pricing_class").on("change", function(e) {
            if ($(this).val() == '') {
                if (activate_ttc == 0) {
                    is_ttc = 0;
                    $(".ttc_disc_div").addClass("hidden")
                    $(".disc_div").removeClass("hidden")
                } else {
                    is_ttc = 1;
                    $(".ttc_disc_div").removeClass("hidden")
                    $(".disc_div").addClass("hidden")
                }
                $("#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'];
                        if (data['is_ttc'] == 0) {
                            $(".ttc_disc_div").addClass("hidden")
                            $(".disc_div").removeClass("hidden")
                        } else {
                            $(".ttc_disc_div").removeClass("hidden")
                            $(".disc_div").addClass("hidden")
                        }
                        $("#Class_Currency").html(data['Currency_ID']);
                        //                        var mytax = ConvertCurrency2(data['tax_amount'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val())
                        //                                    console.log($("#Class_Currency").text())            
                        //            $("#card_tax").attr("data-tax", mytax)

                    }
                }
            })

        })
        $("#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")
        })
        $("#pricing_class").on("select2-selecting", function(e) {
            var flag = false;
            //            console.log(e.val)
            if (e.val == undefined && is_data_collector)
                return false;
            if ((IsSalesMode && $(this).val() != '' && e.val != $(this).val()) || (!IsSalesMode && e.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);
                        $.each(Data, function(index, value) {
                            var me = $("#InventoryPurchaseTable tbody tr:eq(" + value['index'] + ")");
                            me.each(function() {
                                if ($(this).find("input.item-class").val() == "") {
                                    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;
                                    });
                                    $(this).find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ((parseFloat(value['Product_Price']) || 0) + tag_price) : public_round_number((parseFloat(ConvertCurrency2(value['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val())) || 0) + tag_price))

                                    //                                        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++) {
                        ////                            if()
                        //                            var me = $("#InventoryPurchaseTable tbody tr[data-id='" + Data[i]['Product_ID'] + "']");
                        ////                            console.log(Data[i]['Product_Price'] + '===' + $("#Class_Currency").text() + '===' + $("#CurrencyDropDown input").val())
                        //                            //                            me.find("input.UnitPrice").val(Data[i]['Product_Price'])
                        //                            me.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data[i]['Product_Price'] : ConvertCurrency2(Data[i]['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val()).toXFixed(2))
                        //
                        //                        }
                        UpdateTable()
                    }
                }
            })
            $("#CustomerProceedModal").modal("hide")
        })
        $("#InventoryPurchaseTable").on("change", "input.item-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() : $("#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.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? value['Product_Price'] : public_round_number(ConvertCurrency2(value['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))

                        })

                        UpdateTable()
                    }
                }
            })
        })
        //        $("#search_supplier").on("change", function () {
        //           
        //
        //        })
        $("#CurrencyDropDown .dropdown-menu > li").on("click", function() {
            setTimeout(function() {
                trigger_proceed_extra_cost_currency();
                //                $("#proceed_extra_cost").trigger("click")

                UpdateTable()
            }, 300)
        })


        $("#EditBtn").on("click", function(){
           if (IsSalesMode){
            window.location.href = "Inventory/addpurchase/sales/" + Invoice_ID ;
           }else {
            window.location.href = "Inventory/addpurchase/" + Invoice_ID;
           } 
           
        })


        $("#PrintBtn").on("click", function() {
            if (print_template_settings == 0 || !IsSalesMode) {
                var myurl = IsSalesMode ? "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val() : "Inventory/ViewInvoice/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
                printExternalInv(myurl, 'invoice_print_btn')
            } else {
                $("#choose_template_modal").modal("show")
            }
        })
        $(".check_temp_key").on("click", function() {
            var myurl = IsSalesMode ? "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val() + '&template_id=' + $(this).attr("data-id") : "Inventory/ViewInvoice/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val() + '&template_id=' + $(this).attr("data-id");
            printExternalInv(myurl, 'invoice_print_btn')
        })
        $("#PrintBtn1").on("click", function() {
            var myurl = IsSalesMode ? "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val() : "Inventory/ViewInvoice/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
            printExternalInv(myurl, 'delivery_print_btn')
        });
        $("#print_paid_amount").on("click", function() {
            var myurl = "Inventory/print_paid_amount/" + Invoice_ID;
            printExternal(myurl)
        })
        $("#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()
                    },
                    validate = false;
                $("#InventoryPurchaseTable tbody tr").each(function(e) {
                    if ($(this).attr("data-id") != 0 && $(this).find("input[name=current_depot_id]").val() == "") {
                        $(this).attr("data-depot-val", $("#Depot_Loc").val())
                        item_arr.items.push($(this).attr("data-id"))
                        if ($("input.lot_nb", $(this)).val() != '' || $("input.serial_nb", $(this)).val() != '' || $("input.expiry_date", $(this)).val() != '') {
                            validate = true;
                            $("input.lot_nb,input.serial_nb,input.expiry_date", $(this)).val('').attr("data-select-name", "").trigger('change')
                        }
                    }
                })
                if (validate) {
                    toastr.error('<?php echo CommonLanguage::getMessage('serial_lot_expiry_alert') ?>')

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

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

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

                } else {
                    $("input.expiry_date", $(this)).datepicker({
                        autoclose: true
                    });
                }
                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"));
        }
        build_select2($("input[name=current_depot_id]"), "xhr/depotSearch" + ('depot_options_ids' in invoice_type_details ? '?depots=' + invoice_type_details['depot_options_ids'] : ''))
        if (IsSalesMode) {

            build_select2($("input[name=current_vehicle_id]"), "xhr/TruckSearch")
            build_select2($("input[name=current_employee_id]"), "xhr/employeeSearch")

        }else{
            build_select2($("input[name=current_vehicle_id]"), "xhr/TruckSearch")
        }

        $("#PurchaseInvoiceDueDate,#PurchaseInvoiceDate,.check_due_date,.value_date,#ship_date,#ctn_date,#delivery_date").datepicker({
            autoclose: true
        });
        if (fill_purchase_duedate_from_bill == 1 && !IsSalesMode) {
            $('#ship_date').on("changeDate", function(e) {
                updateDueDate($('#due_date_period').val());
            });
        } else {
            $('#PurchaseInvoiceDate').on("changeDate", function(e) {
                updateDueDate($('#due_date_period').val());
            });
        }
        $("#InventoryPurchaseTable tbody").on("input", ".vat_percent,.VATPerItem", function(e) {
            var cur_tr_vat = parseFloat($(this).val()) || 0,
                cur_tr_total = parseFloat($(this).parents("tr").find(".Total").attr("myval")) || 0;
            cur_tr_vat = public_round_number(cur_tr_vat)
            cur_tr_total = public_round_number(cur_tr_total)

            if ($(this).hasClass("vat_percent")) {
                var cur_val = cur_tr_total * cur_tr_vat / 100;
                cur_val = public_round_number(cur_val)

                //                console.log(cur_val)

                $(this).parents("tr").find(".VATPerItem").val(cur_val ? cur_val : '')
                UpdateTable()
                //                setTimeout("UpdateTable()", 100);
            } else {
                var cur_val = cur_tr_vat / cur_tr_total * 100;
                cur_val = public_round_number(cur_val)

                $(this).parents("tr").find(".vat_percent").val(cur_val ? cur_val : '')
                $(this).parents("tr").find(".vat_percent").trigger("input")
            }
        }) 
        $("#InventoryPurchaseTable tbody").on("input", ".vat2_percent,.vat2_amount", function(e) {
            var cur_tr_vat = parseFloat($(this).val()) || 0,
                cur_tr_total = parseFloat($(this).parents("tr").find(".Total").attr("myval")) || 0,
                vat1_amount = parseFloat($(this).parents("tr").find(".VATPerItem").val()) || 0;
            if ($(this).hasClass("vat2_percent")) {
                var cur_val = (cur_tr_total + vat1_amount) * cur_tr_vat / 100;
                $(this).parents("tr").find(".vat2_amount").val(cur_val ? cur_val : '')
                UpdateTable()
                //                setTimeout("UpdateTable()", 100);
            } else {
                var cur_val = cur_tr_vat / (cur_tr_total + vat1_amount) * 100;
                $(this).parents("tr").find(".vat2_percent").val(cur_val ? cur_val : '')
                $(this).parents("tr").find(".vat2_percent").trigger("input")
            }

        })
        $("#InventoryPurchaseTable").on("change", ".item_note", function(e) {
            if (enable_autofill_product_in_invoice == 1) {
                var me = $(this),
                    TR = me.parents("tr");
                searchScannedItem(product_barcode_for_autofill_in_invoice, TR);
            }
        });

        $("#InventoryPurchaseTable").delegate(".Quantity,.n_height,.n_width,.UnitPrice,.Disc,.from_time,.to_time", "blur keydown", function(e) {
            is_td_total = 0;
            console.log('Quantity111')
            var me = $(this),
                TR = me.parents("tr"),
                from_time = TR.find('input.from_time').val(),
                to_time = TR.find('input.to_time').val(),
                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;

            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);

            var TimeDiff;
            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 != '') {

                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")
                //                    }
                //                }
                if (me.hasClass("Disc")) {
                    var item_disc = parseFloat(TR.attr('data-item-disc'));
                    check_discount(me, item_disc)
                }
            }
        });
        if (IsEditMode || is_data_collector || IsOrderMode || is_delivery || is_copy || is_return)
            UpdateTable(); //$(".Quantity").trigger('keydown')
        $("#InvoiceDiscountInput").on(" keyup", function() {
            percent_flag = 1;
            check_discount($(this), max_discount)
            $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($(this).val()) / 100) || 0)
            $("#TTCTotalDiscAmount").val(primary_total * (parseFloat($(this).val()) / 100) || 0)
            setTimeout("UpdateTable()", 100)

        })
        
        $("#TTCTotalDiscAmount").on("keyup", function() {
            //            console.log('gfdf')
            var mytotal = primary_total;
            percent_flag = 2;
            if (parseFloat($(this).val()) > (mytotal * max_discount / 100))
                $(this).val((mytotal * max_discount / 100))
            $("#InvoiceDiscountInput").val((parseFloat($(this).val()) / mytotal * 100) || 0)
            //            console.log(primary_total+'====='+$("#InvoiceDiscountInput").val())
            $("#TotalDiscAmount").val((TotalInvoice * (parseFloat($(this).val()) / mytotal * 100) / 100) || 0)
            //            $("#InvoiceDiscountInput").trigger("keyup")
            //                }
            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((TotalInvoice * max_discount / 100))
                $("#InvoiceDiscountInput").val((parseFloat($(this).val()) / TotalInvoice * 100) || 0)
                $("#TTCTotalDiscAmount").val(primary_total * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
                //        }
                //                $("#TTCTotalDiscAmount").val(primary_total * ((parseFloat($(this).val()) / TotalInvoice * 100) || 0 / 100) || 0)
                //                                console.log(primary_total * ((parseFloat($(this).val()) / TotalInvoice * 100) || 0 / 100) || 0)
                //                }
            }
            setTimeout("UpdateTable()", 100)
        })
        if (IsEditMode || IsOrderMode || is_delivery || is_copy || is_return) {
            setTimeout(function() {
                $("#InvoiceDiscountInput").trigger("keyup")
            }, 300)

        }
        $("#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;
            })
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                Parent.append(ClonedRow);
                fix_cloned_row(ClonedRow)

                //                $(".deleteRowRequest").removeClass("hidden")
                //ClonedSelect.find('select.UOM_ID option:selected').removeAttr('selected');
                //ClonedSelect.find('select.UOM_ID option:first').attr('selected','selected');
                //ClonedSelect.find('select.UOM_ID').trigger('change');
                /* ClonedRow HERE | Reset The select tag here hahah */
                UpdateTable()
            }
        })
        $("#CurrencyDropDown li").click(function() {
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            global_round = $(this).attr("data-round")
            cur_id = $(this).attr("value");
            if ($(this).attr("value") == local_currency) {
                $("#current_rate").val(1).attr("disabled", "disabled")
            } else
                $("#current_rate").val("").removeAttr("disabled")
            if ($(this).attr("value") == second_currency) {
                $("#second_currency_rate").val(1).attr("disabled", "disabled")
            } else
                $("#second_currency_rate").val("").removeAttr("disabled")
            $("#InventoryPurchaseTable tbody tr").each(function() {
                if ($(this).attr("data-id") != '' && $(this).attr("data-id") != undefined) {
                    var conv = parseFloat($(this).attr('data-conv') || 0);
                    var last_cost = ConvertCurrency2((parseFloat($(this).attr("data-last-cost") || 0) * conv), 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 += "P: " + (!last_price ? "0" : AddCommas(public_round_number(parseFloat(last_price))));
                    if (has_sales_cost_perm)
                        unit_price_hint_text += (unit_price_hint_text == '' ? '' : ' | ') + "C: " + (!last_cost ? "0" : AddCommas(public_round_number(parseFloat(last_cost))));
                    $(this).find("input.UnitPrice").next().text(unit_price_hint_text).attr('title', unit_price_hint_text);
                }
            })
            change_local_total(cur_id);
            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", function() {
            if (activate_sales_profit_margin == 1 && IsSalesMode) {
                var net_total = parseFloat($("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted") || 0),
                    current_profit_percent = total_profit / net_total * 100;
                if (current_profit_percent < profit_percent)
                    $("#ProfitProceedModal").modal("show")
                else
                    ApplyPostMethod()
            } else
                ApplyPostMethod()
        });
        $("#signature_div").hide();
        var count = 0;
        $("#open_signature").on("click", function() {
            if (count == 0) {
                $("#signature_div").show();
                count = 1;
            } else {
                $("#signature_div").hide();
                count = 0;
            }

        });


        $("#proceed_profit").on("click", ApplyPostMethod);
        UpdateSubmitButtonStatus()

        $("#InventoryPurchaseTable").on("input", ".ttc_price ", function() {
            var myval = parseFloat($(this).val()) || 0,
                mytr = $(this).parents("tr");
            fill_price_by_ttc(mytr, myval)
            UpdateTable()
        });
        fillShortcutFields();
        $('#shipping_company_id').on('change', function() {
            if ($('#shipping_company_id').val()) {
                CommonViewById('InventoryAjax/getShippingCompanyData', {
                        shipping_company_id: $('#shipping_company_id').val()
                    },
                    '#PurchaseDisabler',
                    function(response) {
                        if (response.shipping_company_fees)
                            $('#Shipping').val(response.shipping_company_fees).trigger('keyup');
                        if (response.shipping_account_id && response.shipping_account_id != 0) {
                            $('#Shipping_Code').val(response.shipping_account_id);
                            $('#Shipping_Code').attr('data-select-name', response.shipping_account_name).trigger('change');
                        }
                        if (response.sales_account_id && response.sales_account_id != 0) {
                            $('#Account_Code').val(response.sales_account_id);
                            $('#Account_Code').attr('data-select-name', response.sales_account_name).trigger('change');
                        } else {
                            $('#Account_Code').val('<?php echo smc_session()['user_accounts']['sales_account_id']; ?>');
                            $('#Account_Code').attr('data-select-name', '<?php echo smc_session()['user_accounts']['s_name']; ?>').trigger('change');
                        }
                        if (response.main_account_id && response.main_account_id) {
                            $('.shipping_account_data').removeClass('hidden').attr('data-main-shipping-account-id', response.main_account_id);
                            $('#is_invoice_total_on_shipping').prop('checked', response.is_invoice_total_on_shipping == 1 ? true : false)
                            $('#trans_on_change_status').prop('checked', response.trans_on_change_status == 1 ? true : false)
                        }
                    });
            } else {
                $('#Account_Code').val('<?php echo smc_session()['user_accounts']['sales_account_id']; ?>');
                $('#Account_Code').attr('data-select-name', '<?php echo smc_session()['user_accounts']['s_name']; ?>').trigger('change');
                $('.shipping_account_data').addClass('hidden').attr('data-main-shipping-account-id', '');
                $('#is_invoice_total_on_shipping').prop('checked', false);
                $('#trans_on_change_status').prop('checked', false);
            }
        });
        $('#enable_tva').on('change', function() {
            if ($(this).is(":checked")) {
                $('input.VATPerItem,input.vat_percent').attr('disabled', false);
            } else {
                $('input.VATPerItem,input.vat_percent').attr('disabled', true);
                $("#InventoryPurchaseTable tbody tr").each(function() {
                    var parent = $(this);
                    $('input.vat_percent,input.VATPerItem', parent).val(0);
                    parent.attr('data-vat', 0);
                    UpdateTotalForRow($(this));
                });
                UpdateTable();
            }
        });
        
        $("#PIC_ID").on("change", function() {
            $.ajax({
                url: "InventoryAjax/get_salesman_depot",
                data: {
                    salesman_id: $(this).val()
                },
                dataType: 'json',
                complete: function(v1, v2) {

                    if (v2 == "success") {
                        var data = v1.responseJSON;
                        //                        console.log(data.length)
                        //                        console.log(data.length)
                        if ('depot_id' in data > 0) {
                            //                            console.log(data['depot_id'])
                            //                            console.log(data['Depot_Name'])
                            $("#Depot_Loc").val(data['depot_id']).attr("data-select-name", data['Depot_Name']).trigger("change")
                        }


                    }
                }
            })
        })

        $("#InventoryPurchaseTable").on("click", ".tags", function() {
            var tr = $(this).parents("tr");
            if (tr.attr("data-id") == undefined)
                return;
            getProductCriteria(tr.attr("data-id"), getCurrentTags(tr), tr)
            $("#tagsModal").attr("data-id", tr.index())
        })
        $(".criteria-detail-div").on("click", '.removeTags', function() {
            //            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')
            }
        })

        $("#product_options_modal #next_btn").on("click", function() {
            var check_required = false,
                option_arr = [];
            $("#op_main_div .op-block").each(function() {
                var max = parseFloat($(this).attr("data-qty")) || 0,
                    is_required = $(this).attr("data-required"),
                    total = 0;
                $(this).find('.op-div').each(function() {
                    var qty = parseFloat($(this).find('input.op-spinner').val()) || 0;
                    total += qty
                    if (qty > 0) {
                        option_arr.push({
                            product_id: $(this).attr("data-id"),
                            option_id: $(this).attr("data-option-id"),
                            uom_id: $(this).attr("data-uom"),
                            qty: qty,
                            //                        product_name: $(this).find('.op-prod-name').text(),
                        })
                    }
                })
                if ((is_required == 1 && max != total) || total > max)
                    check_required = true;

            })
            if (check_required) {
                $("#option_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_required_qty') ?>')
                $("#product_options_modal").scrollTop(0)
                return;
            }
            var ref = $("#product_options_modal").attr("data-ref"),
                tr = $("#InventoryPurchaseTable tbody tr[data-ref=" + ref + "]"),
                tr_qty = (parseFloat(tr.find("input.Quantity").val()) || 0) * (parseFloat(tr.attr("data-conv")) || 0);
            tr.attr("data-last-qty", tr_qty)
            tr.attr("data-option-arr", JSON.stringify(option_arr))
            $("#product_options_modal").modal("hide")
        })

        $("body").on("click", ".spinner-icons > span", function(e) {
            //        alert()
            var parent = $(this).parents('.spinner-icons');

            //            alert()
            var input = $(this).parents('.spinner-icons').find('input'),
                cur_val = parseFloat(input.val()) || 0,
                max = parseFloat(input.attr("max")) || undefined;
            if ($(this).hasClass("fa-minus"))
                input.val((cur_val - 1) <= 0 ? 0 : cur_val - 1)
            else {

                input.val((max != undefined && (cur_val + 1) > max) ? max : (cur_val + 1))
            }
            //            console.log(input.val())
            if (parent.hasClass('option-spinner')) {
                var max_qty = $(this).parents('.op-block').attr("data-qty"),
                    total_qty = 0;
                $(this).parents('.op-block').find('input.op-spinner').each(function() {
                    total_qty += parseFloat($(this).val()) || 0;
                })
                if (total_qty > max_qty) {
                    input.val(input.attr('data-old') || 0)
                }
            }
            input.attr('data-old', input.val())
        })

        $("#InventoryPurchaseTable tbody").on("click", ".option-tr", function() {
            var tr = $(this).parents("tr"),
                ref = tr.attr("data-ref"),
                option_arr = tr.attr("data-option-arr") != undefined ? JSON.parse(tr.attr("data-option-arr")) : [];
            //                    console.log(option_arr)
            build_optional_link(ref, function(arr) {
                $.each(arr, function(indx, row) {
                    $(".op-div[data-id=" + row['product_id'] + "][data-option-id=" + row['option_id'] + "]").find('input.op-spinner').val(row['qty'])
                });
            }, [option_arr]);

            $("#product_options_modal").attr("data-ref", ref)
        })
    });

    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")

    }

    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 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=' + ($('input[name=current_depot_id]', TR).val() ? $('input[name=current_depot_id]', TR).val() : $('#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-tax", Data.is_tax)
                    TR.attr("data-expiry", Data.is_expiry);
                    TR.attr("data-last-cost", Data.last_cost);
                    TR.find("input.CODE").val(Data.Bar_Code);
                    TR.find("input.ProductName").val(Data.Name)
                    TR.attr("data-is-service", Data.is_service)
                    TR.find("input.vat_percent").val((Data.VAT == 1 && !is_actual) ? Data.vat_percent : 0)
                    TR.find("input.vat2_percent").val((Data.VAT == 1 && !is_actual && is_sec_vat) ? Data.vat2_percent : 0)
                    TR.find("input.VATPerItem,input.vat2_amount").val('0')
                    TR.attr("data-depot-val", $("#Depot_Loc").val())
                    if (Data.VAT == 0 || is_actual) {
                        TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                        if (!is_sec_vat)
                            TR.find("input.vat2_percent,input.vat2_amount").attr("disabled", "disabled")
                    } else {
                        TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                        if (is_sec_vat)
                            TR.find("input.vat2_percent,input.vat2_amount").removeAttr("disabled")
                    }

                    if ($('#enable_tva').is(":checked") && Data.VAT == 1 && is_actual) {
                        TR.find("input.vat_percent,input.VATPerItem").attr('disabled', false);
                        TR.find("input.vat_percent").val(Data.vat_percent);
                        TR.attr("data-vat", Data.VAT);
                    }
                    var units_arr = Data.Product_UOM.split("/");
                    for (var i = 0; i < units_arr.length; i++) {
                        $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == Data.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                    }
                    TR.find("select[name=UOM_ID]").select2();
                    var qty_hint = AddCommas(public_round_number(parseFloat(Data.stock_qty))) + " in stock";
                    if (event.which != 9)
                        TR.find("input.Quantity").focus().next().text(qty_hint).attr("title", qty_hint)
                    else
                        TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                    var product_hint = '';
                    if (display_shelf_locations == 1) {
                        product_hint += Data.loc;
                    }
                    if (has_det_sales_rep_perm && IsSalesMode) {
                        product_hint += '<span class="fa fa-eye m-l-5 openFrame open_detailed_sold_items" data-src="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + Data.ID + '&product_name=' + Data.Name + '&customer_id=' + $("#search_supplier").val() + '&customer_name=' + $("#search_supplier").select2('data').text + '"  data-main-url="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + Data.ID + '&product_name=' + Data.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    if (has_stock_trans_perm) {
                        product_hint += '<span class="fa fa-note-o m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=' + Data.ID + '&product_name=' + Data.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }
                    if (has_edit_prod_perm) {
                        product_hint += '<span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/' + Data.ID + '?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                    }

                    TR.find("input.ProductName").next().html(product_hint);
                    if (Data.is_expiry == 0)
                        TR.find(".expiry_date").addClass("hidden")
                    else
                        TR.find(".expiry_date").removeClass("hidden")

                    if (IsSalesMode) {
                        TR.attr("data-item-disc", Data.Product_Limit_Discount)
                        TR.attr("data-cost", $("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data.current_cost : public_round_number(parseFloat(ConvertCurrency2(Data.current_cost, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()))))
                        TR.find("input.expiry_date,input.lot_nb,input.serial_nb").attr('data-select-name', '').val('')

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

                        check_discount(TR.find(".Disc"), parseFloat(Data.Product_Limit_Discount))


                        if (Data.force_change_price == 1) {
                            TR.find("input.UnitPrice").removeAttr("disabled")
                        } else {
                            if (change_sales_unit_price)
                                TR.find("input.UnitPrice").removeAttr("disabled")
                            else
                                TR.find("input.UnitPrice").attr("disabled", "disabled")
                        }
                        TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data.Price : public_round_number(parseFloat(ConvertCurrency2(Data.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()))));
                        var unit_price_hint_text = '';
                        if (has_sales_last_price)
                            unit_price_hint_text += "P: " + (!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 == '' ? '' : ' | ') + "C: " + (!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);
                        var qty_hint = AddCommas(public_round_number(parseFloat(Data.stock_qty))) + " in stock";
                        TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)

                        UpdateTable()
                        return false;
                    } else {
                        if (Data.is_expiry == 1)
                            TR.find("input.expiry_date").datepicker({
                                autoclose: true
                            });
                        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()))))));
                        }
                        UpdateTable()
                        return false;
                    }
                }
            }
        });
    }

    function UpdateTable() {
        var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        vatVal = 0, totalvat = 0, taxAmount = 0, total_qty = 0, vat1_total = 0, vat2_total = 0;
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0, card_tax = 0, primary_total = 0, total_profit = 0

        $("#InventoryPurchaseTable tbody tr").each(function() {
            var who = $(this);
            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;
            var tr_vat_percent = (who.attr('data-vat') == 1 || (allow_purchase_vat_edit && !IsSalesMode)) ? (parseFloat(who.find("input.vat_percent").val()) || 0) : 0,
                tr_vat2_percent = ((who.attr('data-vat') == 1 && is_sec_vat) || (allow_purchase_vat_edit && !IsSalesMode)) ? (parseFloat(who.find("input.vat2_percent").val()) || 0) : 0;
            if (is_td_total == 0) {
                var ttc_price = Single_Price * (1 + (tr_vat_percent / 100));
                //                                 console.log(ttc_price * (1 + (tr_vat2_percent / 100)))

                ttc_price = (ttc_price * (1 + (tr_vat2_percent / 100)));
                who.find('.ttc_price').val(ttc_price > 0 ? ttc_price : '')
            }
            TotalInvoice += Net_Total;
            primary_total += parseFloat(who.find('.ttc_price').val() || 0) * Qty * (1 - Discount / 100);
        });
        //
        //        console.log(percent_flag)
        if (percent_flag == 1) {
            $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
            $("#TTCTotalDiscAmount").val(primary_total * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
        }
        if (percent_flag == 2) {
            if (is_ttc == 1) {
                $("#InvoiceDiscountInput").val((parseFloat($("#TTCTotalDiscAmount").val()) / primary_total * 100) || 0)
                $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
            } else {
                $("#InvoiceDiscountInput").val((parseFloat($("#TotalDiscAmount").val()) / TotalInvoice * 100) || 0)
                $("#TTCTotalDiscAmount").val(primary_total * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
            }
        }

        //
        $("#InventoryPurchaseTable tbody tr").each(function() {
            UpdateTotalForRow($(this))
        });

        $("#total_profit").text(AddCommas(public_round_number(parseFloat(total_profit))))
        if (IsSalesMode) {
            $("#card_tax").val(public_round_number(parseFloat(card_tax)))
        }
        if (parseFloat($("#InvoiceDiscountInput").val()) > 100) {
            $("#TotalDiscAmount").val('').trigger("keyup");
            $("#DiscountProceedModal").modal("show");
        }
        var totalDiscountValue = parseFloat($("#TotalDiscAmount").val()) || 0;
        var TTCtotalDiscountValue = parseFloat($("#TTCTotalDiscAmount").val()) || 0;
        var TotalInvoiceDisounted = TotalInvoice - totalDiscountValue;
        setTimeout("UpdateSubmitButtonStatus()", 100)
        //        console.log(primary_total+'=='+is_ttc+'==='+TTCtotalDiscountValue+'==='+totalDiscountValue)
        var ftotal = primary_total - TTCtotalDiscountValue + shipping + card_tax,
            finalTotal = 0;
        //        console.log('ftotal= ' + ftotal)
        //        console.log('global_round= ' + global_round)
        if (global_round > 0) {
            var roundTo = global_round,
                diff = ftotal % roundTo;
            var finalTotal = Math.floor(ftotal / roundTo);
            //            ($difference >= ($round_to / 2) && empty($default_round_type)) || $default_round_type == 1
            if ((diff >= (roundTo / 2) && default_round_type == 0) || default_round_type == 1) {
                finalTotal++;
            }
            finalTotal = finalTotal * roundTo;
        } else {
            finalTotal = ftotal;
        }
        //        console.log('finalTotal= ' + finalTotal)
        $("#PurchaseInvoiceTotalDetails").attr({
            "MyValueNotDiscounted": public_round_number(TotalInvoice + shipping),
            "MyValueDiscounted": public_round_number(TotalInvoiceDisounted + totalvat + shipping + card_tax),
            "final-total": public_round_number(finalTotal)
        }).text(AddCommas(public_round_number(finalTotal))) //do not round to 3 digits in .text() since the value is used in transactions and should be the same as the used attr
        change_local_total($("#CurrencyDropDown input").val())
        //        console.log(is_full_paid)
        if (is_full_paid == 1) {
            //            console.log(A1+A2+A3)
            $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(public_round_number(finalTotal)).trigger("keyup")
            //            UpdatePurchaseInvoiceTotalPaid()
        }
        if (activate_autofill_other_amount == 1 && stop_autofill_other_amount == 0 && person_has_other_acc == 1) {
            var A1 = parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val()) || 0,
                A2 = parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val()) || 0,
                A3 = parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val()) || 0,
                paid = (A1 + A2 + A3);
            $("#other_amount").val(public_round_number(finalTotal) - paid).trigger('keyup');

        }

    }

    function change_local_total(currency_id) {
        var inv_total = parseFloat($("#PurchaseInvoiceTotalDetails").attr("myvaluediscounted") || 0);
        if (currency_id == local_currency)
            var second_currency_rate = $("#second_currency_rate").val();
        else if (second_currency == currency_id)
            second_currency_rate = $("#current_rate").val();
        else second_currency_rate = -1;
        if (currency_id != local_currency) {
            if ($("#current_rate").val() != '')
                $("#Local_Total").html(AddCommas(public_round_number(parseFloat(inv_total * $("#current_rate").val()))))
            else
                $("#Local_Total").html(AddCommas(public_round_number(parseFloat(ConvertCurrency2(inv_total, currency_id, local_currency, second_currency_rate)))))
            $("#local_curr_symbol").text(local_currency_symbol)
        } else {
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(ConvertCurrency2(inv_total, currency_id, second_currency, second_currency_rate)))))
            $("#local_curr_symbol").text(second_currency_symbol)
        }
        fillShortcutFields();
    }

    function EnableAutoComplete(who) {
        //        var old_prod_id = who.attr("data-id");

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

                        var stock_qty = ui.item.Quantity;
                        if (IsEditMode && ui.item.ID in loc_inv_data) {
                            if ($("#Depot_Loc").val() in loc_inv_data[ui.item.ID])
                                stock_qty += loc_inv_data[ui.item.ID][$("#Depot_Loc").val()]
                        }
                        TR.attr("data-vat", (is_actual ? 0 : ui.item.VAT))
                        //                        TR.attr("data-qty", ui.item.Quantity)
                        TR.attr("data-qty", stock_qty)
                        TR.attr("data-item-disc", ui.item.Product_Limit_Discount)
                        TR.attr("data-tax", ui.item.is_tax)
                        TR.attr("data-expiry", ui.item.is_expiry)
                        TR.attr("data-last-cost", ui.item.LAST_COST)
                        TR.attr("data-last-price", ui.item.last_price)
                        TR.attr("data-conv", ui.item.uom_conv)
                        TR.attr("data-is-service", ui.item.is_service)
                        TR.attr("data-is-option", ui.item.has_optional)
                        TR.attr("recipe-qty", ui.item.recipe_qty)
                        TR.attr("data-depot-val", $("#Depot_Loc").val())
                        TR.attr("data-is-lot", ui.item.is_lot)
                        TR.attr("data-is-serial", ui.item.is_serial)
                        var ref = Math.round(Date.now() + Math.random());
                        TR.attr("data-ref", ref)
                        if (ui.item.has_optional == 1) {
                            //                            build_optional_link(ref)
                            $(".option-tr,.option-main-td", $(TR)).removeClass("hidden")
                        } else {
                            $(".option-tr,.option-main-td", $(TR)).addClass("hidden")
                        }
                        TR.attr("data-cost", $("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ui.item.current_cost : public_round_number(ConvertCurrency2(ui.item.current_cost, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))
                        //                        TR.attr("data-cost", ConvertCurrency2(ui.item.current_cos, v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val())t)
                        if (ui.item.is_expiry == 0)
                            TR.find("input.expiry_date").addClass("hidden")
                        else {
                            TR.find("input.expiry_date").removeClass("hidden");
                            TR.find("input.expiry_date").attr('data-select-name', '').val('')
                            if ('oldest_expiry' in ui.item) {
                                TR.find("input.expiry_date").val(ui.item['oldest_expiry']['expiry_date']).attr("data-select-name", ui.item['oldest_expiry']['expiry_text'] + ' ' + ui.item['def_view_uom_name']);
                            }
                            build_select2(TR.find("input.expiry_date"), function(el) {
                                var depot_id = $('input[name=current_depot_id]', this.parents("tr")).val() != '' ? $('input[name=current_depot_id]', this.parents("tr")).val() : $("#Depot_Loc").val();
                                return 'xhr/get_product_expiry?product_id=' + ui.item.ID + '&depot=' + depot_id;
                            }, '', 'expiry_width');

                        }

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

                        check_discount(TR.find(".Disc"), parseFloat(ui.item.Product_Limit_Discount))
                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.find("input.Disc").val(ui.item.disc)
                        TR.find("input.ProductName").val(ui.item.Name)
                        //                         if (ui.item.person_code != '')
                        TR.find("input.person_code").val(ui.item.person_code)

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


                        TR.find("input.vat_percent").val((ui.item.VAT == 1 && !is_actual) ? ui.item.vat_percent : 0)
                        TR.find("input.vat2_percent").val((ui.item.VAT == 1 && !is_actual && is_sec_vat) ? ui.item.vat2_percent : 0)
                        TR.find("input.VATPerItem,input.vat2_amount").val('0')
                        if (ui.item.VAT == 0 || is_actual) {
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                            if (!is_sec_vat)
                                TR.find("input.vat2_percent,input.vat2_amount").attr("disabled", "disabled")
                        } else {
                            TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                            if (is_sec_vat)
                                TR.find("input.vat2_percent,input.vat2_amount").removeAttr("disabled")
                        }
                        if ($('#enable_tva').is(":checked") && ui.item.VAT == 1 && is_actual) {
                            TR.find("input.vat_percent,input.VATPerItem,input.vat2_percent,input.vat2_amount").attr('disabled', false);
                            TR.find("input.vat_percent").val(ui.item.vat_percent);
                            TR.find("input.vat2_percent").val(ui.item.vat2_percent);
                            TR.attr("data-vat", ui.item.VAT);
                        }
                        if (ui.item.force_change_price == 1) {
                            TR.find("input.UnitPrice").removeAttr("disabled")
                        } else {
                            if (change_sales_unit_price)
                                TR.find("input.UnitPrice").removeAttr("disabled")
                            else
                                TR.find("input.UnitPrice").attr("disabled", "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')
                        }
                        //                        console.log(tag_price + '===')
                        if (IsOrderMode == false)
                            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_text = '',
                            unit_price_title = '';
                        if (has_sales_last_price) {
                            unit_price_hint_text += "P: " + (!ui.item.last_price ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.last_price, local_currency, $("#CurrencyDropDown input").val())))));
                            unit_price_title += "Price: " + (!ui.item.last_price ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.last_price, local_currency, $("#CurrencyDropDown input").val())))));
                        }
                        if (has_sales_cost_perm) {
                            unit_price_hint_text += (unit_price_hint_text == '' ? '' : ' | ') + "C: " + (!ui.item.LAST_COST ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val())))));
                            unit_price_title += (unit_price_title == '' ? '' : ' | ') + "Cost: " + (!ui.item.LAST_COST ? "0" : AddCommas(public_round_number(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val())))));
                        }
                        TR.find("input.UnitPrice").next().text(unit_price_hint_text).attr('title', unit_price_title);
                        var product_hint = '';
                        if (display_shelf_locations == 1) {
                            product_hint += ui.item.loc;
                        }
                        if (has_det_sales_rep_perm) {
                            product_hint += '<span class="fa fa-sticky-note m-l-5 openFrame open_detailed_sold_items" data-src="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '&customer_id=' + $("#search_supplier").val() + '&customer_name=' + $("#search_supplier").select2('data').text + '" data-main-url="Inventory/DetailedInvoiceProductReport' + (is_actual ? '/act' : '') + '?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                        }
                        if (has_stock_trans_perm) {
                            product_hint += '<span class="fa fa-eye m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                        }
                        if (has_edit_prod_perm) {
                            product_hint += '<span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/' + ui.item.ID + '?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                        }
                        TR.find("input.ProductName").next().html(product_hint)
                        var qty_hint = AddCommas(public_round_number(parseFloat(stock_qty))) + " in stock";
                        if (event.which != 9)
                            TR.find("input.Quantity").focus().next().text(qty_hint).attr("title", qty_hint)
                        else
                            TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)

                        TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                        var units_arr = ui.item.Product_UOM.split("/");
                        for (var i = 0; i < units_arr.length; i++) {
                            $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                        }
                        TR.find("select[name=UOM_ID]").select2();
                        //                        if ($('#card_tax').attr('data-tax') > 0 && TR.attr('data-tax') == 1) {
                        //                        console.log(ui.item.total_tax)
                        TR.attr('unit-tax', parseFloat(ConvertCurrency2(ui.item.total_tax, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())));
                        //                        } else {
                        //                            TR.attr('unit-tax', 0)
                        //                        }
                        is_td_total = 0;
                        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));
                    //                        $(this).focus().trigger({ type : 'keypress', which : 13 });
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }

        } else {

            if (!who.hasClass("AutoAdded")) {

                who.autocomplete({
                    source: function(request, response) {
                        var classID = (who.parents('tr').find('input.item-class').val() != '' ? who.parents('tr').find('input.item-class').val() : $("#pricing_class").val()),
                            depot_id = $('input[name=current_depot_id]', who.parents('tr')).val() ? $('input[name=current_depot_id]', who.parents('tr')).val() : $('#Depot_Loc').val(),
                            product_id = who.parents('tr').attr('data-id'),
                            customer_id = $("#search_supplier").val(),
                            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_purchase=" + (IsSalesMode ? 0 : 1) + "&ClassID=" + classID + '&depot_id=' + depot_id + '&type=2' + '&customer_id=' + customer_id + status_cond, 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.attr("data-last-cost", ui.item.LAST_COST)
                        TR.find("input.CODE").val(ui.item.Bar_Code);
                        TR.attr("data-conv", ui.item.uom_conv)
                        TR.attr("data-is-service", ui.item.is_service)
                        TR.attr("data-is-option", ui.item.has_optional)
                        TR.attr("recipe-qty", ui.item.recipe_qty)
                        TR.attr("data-depot-val", $("#Depot_Loc").val())
                        TR.attr("data-is-lot", ui.item.is_lot)
                        TR.attr("data-is-serial", ui.item.is_serial)
                        var ref = Math.round(Date.now() + Math.random());
                        TR.attr("data-ref", ref)
                        if (ui.item.has_optional == 1) {
                            //                            build_optional_link(ref)
                            $(".option-tr,.option-main-td", $(TR)).removeClass("hidden")
                        } else {
                            $(".option-tr,.option-main-td", $(TR)).addClass("hidden")
                        }
                        TR.find("input.vat_percent").val((ui.item.VAT == 1 && !is_actual) ? ui.item.vat_percent : 0)
                        TR.find("input.vat2_percent").val((ui.item.VAT == 1 && !is_actual && is_sec_vat) ? ui.item.vat2_percent : 0)
                        TR.find("input.VATPerItem,input.vat2_amount").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")
                            if (!is_sec_vat)
                                TR.find("input.vat2_percent,input.vat2_amount").removeAttr("disabled")
                        } else {
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled");
                            if (is_sec_vat)
                                TR.find("input.vat2_percent,input.vat2_amount").attr("disabled", "disabled");
                        }
                        if ($('#enable_tva').is(":checked") && ui.item.VAT == 1 && is_actual) {
                            TR.find("input.vat_percent,input.VATPerItem,input.vat2_percent,input.vat2_amount").attr('disabled', false);
                            TR.find("input.vat_percent").val(ui.item.vat_percent);
                            TR.find("input.vat2_percent").val(ui.item.vat2_percent);
                            TR.attr("data-vat", ui.item.VAT);
                        }
                        TR.attr("data-expiry", ui.item.is_expiry)
                        if (ui.item.is_expiry == 0)
                            TR.find(".expiry_date").addClass("hidden")
                        else {
                            TR.find(".expiry_date").removeClass("hidden")
                            TR.find("input.expiry_date").datepicker({
                                autoclose: true
                            });
                        }

                        if (ui.item.is_lot == 1 && activate_lot == 1) {
                            TR.find(".lot_nb").removeClass("hidden");
                            //                            build_select2(TR.find("input.lot_nb"), 'xhr/get_product_lot?product_id=' + ui.item.ID, '', 'expiry_width');

                        } else
                            TR.find(".lot_nb").addClass("hidden");
                        if (ui.item.is_serial == 1 && activate_serial == 1) {
                            TR.find(".serial_nb").removeClass("hidden");
                            //                            build_select2(TR.find("input.serial_nb"), 'xhr/get_product_serial?product_id=' + ui.item.ID, '', 'expiry_width');

                        } else
                            TR.find(".serial_nb").addClass("hidden");
                        //
                        TR.find("input.ProductName").val(ui.item.Name)
                        //                        if (ui.item.person_code != '')
                        TR.find("input.person_code").val(ui.item.person_code)
                        
                        TR.find("input.is_collected_points").val(ui.item.is_collected_points)
                        TR.find("input.n_width").val(ui.item.n_width)
                        TR.find("input.n_height").val(ui.item.n_height)
                        TR.find("input.qty_link").val(ui.item.qty_link)


                        $("select[name=UOM_ID]", TR).empty();
                        var myclass = (TR.find('input.item-class').val() != '' ? TR.find('input.item-class').val() : $("#pricing_class").val())
                        if (myclass != '' && myclass != 0) {
                            $("#Class_Currency").html(ui.item.class_curency)
                            TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ui.item.Price : public_round_number(ConvertCurrency2(ui.item.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))
                            //                            TR.find("input.ttc_price").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ui.item.Price : ConvertCurrency2(ui.item.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()).toXFixed(2))

                        }
                        if (auto_fill_cost == 1) {
                            TR.find("input.UnitPrice").val(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val()))
                        }
                        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()))))));
                        }
                        var qty_hint = AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock";
                        if (event.which != 9)
                            TR.find("input.Quantity").focus().next().text(qty_hint).attr("title", qty_hint)
                        else
                            TR.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                        var product_hint = '';
                        if (display_shelf_locations == 1) {
                            product_hint += ui.item.loc;
                        }
                        if (has_stock_trans_perm) {
                            product_hint += '<span class="fa fa-eye m-l-5 openFrame " data-src="Stock/stock_transactions?is_pop=1&product_id=' + ui.item.ID + '&product_name=' + ui.item.Name + '" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                        }
                        if (has_edit_prod_perm) {
                            product_hint += '<span class="fa fa-pencil m-l-5 openFrame " data-src="Inventory/ViewProduct/' + ui.item.ID + '?is_pop=1&modal=1" style="color:#6c5ab3;cursor:pointer;float:right;"></span>';
                        }
                        TR.find("input.ProductName").next().html(product_hint);
                        //                        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()
                        is_td_total = 0;
                        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")
            }

        }
        /* $(document).keydown(function (e) {
         if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
         e.preventDefault()
         }
         })*/

    }

    function ApplyPostMethod() {
        var mycanvas = document.getElementById('canvas');
        var img = mycanvas.toDataURL("image/png");
        anchor = $("#signature");
        anchor.val(img);

        $("#ProfitProceedModal").modal("hide")
        $("#PurchaseSuccess").attr("class", "hidden");
        $("#InventoryPurchaseTable tbody tr input").removeClass("wrong")
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                Data = {
                    signature_image: img,
                    r_d_sph: $("#r_d_sph").val(),
                    c_d_cyl: $("#c_d_cyl").val(),
                    c_d_ax: $("#c_d_ax").val(),

                    c_d_sph: $("#c_d_sph").val(),
                    l_d_cyl: $("#l_d_cyl").val(),
                    l_d_ax: $("#l_d_ax").val(),

                    r_r_sph: $("#r_r_sph").val(),
                    c_r_cyl: $("#c_r_cyl").val(),
                    c_r_ax: $("#c_r_ax").val(),

                    c_r_sph: $("#c_r_sph").val(),
                    l_r_cyl: $("#l_r_cyl").val(),
                    l_r_ax: $("#l_r_ax").val(),




                    cl_r_sph: $("#cl_r_sph").val(),
                    cl_r_cyl: $("#cl_r_cyl").val(),
                    cl_r_axis: $("#cl_r_axis").val(),
                    cl_r_ipd: $("#cl_r_ipd").val(),

                    cl_l_sph: $("#cl_l_sph").val(),
                    cl_l_cyl: $("#cl_l_cyl").val(),
                    cl_l_axis: $("#cl_l_axis").val(),
                    cl_l_ipd: $("#cl_l_ipd").val(),




                    Cash_Amount: $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
                    Cash_Account: $("#cash_account").val(),
                    cash_user_ref: $(".cash_user_ref").val(),
                    Check_Amount: $("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
                    Check_Account: $("#check_account").val(),
                    check_user_ref: $(".check_user_ref").val(),
                    Card_Amount: $("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
                    Card_Account: $("#credit_account").val(),
                    Other_Amount: $("#other_amount").val(),
                    Other_Account: $("#other_acc_id").val(),
                    other_user_ref: $("#other_user_ref").val(),
                    check_due_date: $(".check_due_date").val(),
                    value_date: $(".value_date").val(),
                    Check_Num: $("#SetPaidFormTab_2 .CheckNumValue").eq(0).val(),
                    Card_Code: $("#SetPaidFormTab_3 .CardApproval").eq(0).val(),
                    Depot_ID: $("#Depot_Loc").val(),
                    Invoice_VAT: $("#InvoiceVAT").html().replace(/,/g, ""),
                    vat1_total: $("#InvoiceVAT").attr("vat1_total"),
                    vat2_total: $("#InvoiceVAT").attr("vat2_total"),
                    currency_round: (parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(/,/g, "")) - $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted")) || 0,
                    Account_Code: $('#Account_Code').val(),
                    CurrencySymbole: $(".CurrencyIndicator").html(),
                    IsSalesMode: IsSalesMode ? 1 : 0,
                    pending_status: $("#pending").is(":checked") ? 3 : 4,
                    shipping: $("#Shipping").val(),
                    shipping_account: $("#Shipping_Code").val(),
                    discount_amount: $("#TotalDiscAmount").val(),
                    is_actual: is_actual ? 1 : 0,
                    Invoice_Currency_Rate: $("#current_rate").val(),
                    second_currency_rate: $("#second_currency_rate").val(),
                    Invoice_Description: $("#invoice_note").val(),
                    order_id: $('#current_order_id').val(),
                    job_id: $("#job_id").val(),
                    project_id: $("#project_id").val(),
                    Class_ID: $("#pricing_class").val(),
                    customer_branch_id: $("#customer_branch_id").val(),
                    current_invoice_type: $("#current_invoice_type").val(),
                    customer_branch_name: $("#customer_branch_id").val() ? $("#customer_branch_id").select2('data').text : '',
                    customer_name_alias: $("#customer_name_alias").val(),
                    customer_address_alias: $("#customer_address_alias").val(),
                    unique_id: unique_id,
                    ship_bill_nb: $("#ship_bill_nb").val(),
                    ship_date: $("#ship_date").val(),
                    container_nb: $("#container_nb").val(),
                    container_size: $("#container_size").val(),
                    ctn_nb: $("#ctn_nb").val(),
                    ctn_date: $("#ctn_date").val(),
                    //                        ctn_amount: $("#ctn_amount").val(),
                    //                        ctn_currency: $("#ctn_currency").val(),
                    Products: []

                };
                
            if (IsSalesMode) {
                Data.invoice_user_reference = $('#Supplier_Invoice').val();
                Data.po = $('#po').val();
                Data.project_name_inv = $('#project_name_inv').val();
                Data.project_code = $('#project_code').val();
                Data.job_inv = $('#job_inv').val();
                Data.our_ref = $('#our_ref').val();
                Data.supply_date = $('#supply_date').val();
                Data.from_place = $('#from_place').val();
                Data.to_place = $('#to_place').val();
                Data.driver_id = $('#driver_id').val();
                Data.Customer_ID = $("#Supplier_ID").val();
                Data.Customer_Account = $("#Finance_Account").attr("data-id")
                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 = parseFloat($("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted") || 0) - parseFloat($("#Shipping").val() || 0);
                Data.Invoice_Sub_Total = parseFloat($("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted") || 0) - parseFloat($("#Shipping").val() || 0);
                Data.Invoice_Paid_Amount = $("#AdvanceValue").val();
                Data.truck = $("#inv_truck").val();
                Data.is_data_collector = is_data_collector ? 1 : 0;
                Data.tax_amount = $("#card_tax").val() || 0;
                Data.Sales_ID = $("input[name=PIC_ID]").val();
                Data.shipping_company_id = $('#shipping_company_id').val()
                Data.pos_customer_id = $('#pos_customer_id').val()
                Data.contra_id = $('#contra_id').val()
                Data.shipping_note = $('#shipping_note').val();
                Data.is_invoice_total_on_shipping = $('#is_invoice_total_on_shipping').is(":checked") ? 1 : 0;
                Data.trans_on_change_status = $('#trans_on_change_status').is(":checked") ? 1 : 0;
                if ($('#shipping_company_id').val()) {
                    Data.shipp_comp_acc_id = $('.shipping_account_data').attr('data-main-shipping-account-id');
                }
                Data.products = [];
            } else {
                Data.Supplier_Invoice_ID = $("#Supplier_Invoice").val();
                Data.po = $("#po").val();
                Data.project_name_inv = $("#project_name_inv").val();
                Data.project_code = $("#project_code").val();
                Data.job_inv = $("#job_inv").val();
                Data.our_ref = $("#our_ref").val();
                Data.supply_date = $("#supply_date").val();
                Data.from_place = $("#from_place").val();
                Data.to_place = $("#to_place").val();
                Data.driver_id = $('#driver_id').val();
                Data.Supplier_ID = $("#Supplier_ID").val();
                Data.Supplier_Account = $("#Finance_Account").attr("data-id")
                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 = parseFloat($("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted") || 0) - parseFloat($("#Shipping").val() || 0);
                Data.Purchase_Sub_Total = parseFloat($("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted") || 0) - parseFloat($("#Shipping").val() || 0);
                Data.Purchase_Paid_Amount = $("#AdvanceValue").val();
                Data.total_qty = total_qty;
                Data.extra_cost = $("#extra_cost").val();
                Data.cost_dist_method = $("#cost_dist_method").val();
                Data.is_noqty = is_noqty ? 1 : 0;
                Data.extra_cost_arr = global_cost_arr;
                //                $(".extra_row").each(function () {
                //                    var from_currency = $(this).find("select.extra_cost_currency").val(),
                //                            amount = parseFloat($(this).find(".extra_cost_amount").val()) || 0,
                //                            type = parseFloat($(this).find("select.extra_cost_type").val()) || 0,
                //                            ex_rate = parseFloat($(this).find(".extra_cost_rate").val()) || 0;
                //                    if (from_currency != '' && from_currency != '0' && amount > 0 && ex_rate > 0) {
                //
                //                        Data.extra_cost_arr.push({
                //                            amount: amount,
                //                            currency_id: from_currency,
                //                            rate: ex_rate,
                //                            type: type,
                //                            debit_acc_id: $(this).find("input.extra_cost_debit_acc").val(),
                //                            credit_acc_id: $(this).find("input.extra_cost_credit_acc").val(),
                //                            note: $(this).find("input.note").val()
                //                        })
                //                    }
                //                })
            }
            //                        console.log(Data.currency_round)
            //                        return false;
            if (IsEditMode) {
                Data.Invoice_ID_Auto = ID_Edit;
                Data.Old_Depot_ID = $("#Depot_Loc").attr('data-old')
            }
            if (is_data_collector) {
                Data.file_id = file_id;
            }

            var total_cost_percent = 0,
                is_negative_value = false,
                validate_option = true;
            $("#InventoryPurchaseTable tbody tr").each(function(e) {
                var me = $(this);
                total_cost_percent += parseFloat(me.find(".cost_percent").val()) || 0;
                var tags = [],
                    item_qty = me.find(".Quantity").val(),
                    default_qty = (parseFloat(item_qty) || 0) * (parseFloat(me.attr("data-conv") || 0));
                if (me.attr("data-is-option") == 1 && me.attr("data-last-qty") != default_qty) {
                    validate_option = false;
                    me.find('.option-tr').addClass("pulsate")
                }
                $("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,
                        vat2_percent: me.find("input.vat2_percent ").val() || 0,
                        vat2_amount: me.find("input.vat2_amount").val() || 0,
                        Product_Total_Price: me.find(".Total").attr("myval"),
                        product_description: me.find(".item_note").val(),
                        cost_percent: me.find(".cost_percent").val(),

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

                        depot_id: me.find("input[name=current_depot_id]").val(),
                        vehicle_id: me.find("input[name=current_vehicle_id]").val(),
                        employee_id: me.find("input[name=current_employee_id]").val(),
                        commission: me.find("input.commission").val(),
                        expiry_date: me.find("input.expiry_date").val(),
                        total_tax: (parseFloat(me.attr('unit-tax')) || 0) * parseFloat(me.find(".Quantity").val()),
                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        class_id: $("input.item-class", me).val(),
                        delivery_id: me.attr("data-delivery-id"),
                        delivery_cost: me.attr("data-delivery-cost") || 0,
                        entry_id: me.attr("data-entry") || 0,
                        is_service: me.attr("data-is-service") || 0,
                        criteria_details: tags,
                        options_arr: me.attr("data-option-arr"),
                        cost_arr: me.attr("data-cost-arr"),
                        additional_cost: me.find("input.additional_cost").val(),
                        n_total : me.find("input.n_total").val(),
                        n_width: me.find("input.n_width").val(),
                        n_height: me.find("input.n_height").val(),
                        qty_link: me.find("input.qty_link").val(),
                        is_collected_points: me.find("input.is_collected_points").is(":checked") ? 1 : 0
                        
                    });
                    me.find(".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")
                        }
                    })
                    if (me.attr("data-id") == '0' || me.attr("data-id") == '' || me.attr("data-id") == undefined || me.find("select.UOM_ID").val() == '') {
                        me.find(".CODE").addClass("wrong")
                        me.find(".ProductName").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_expiry_date == 1 && me.attr("data-expiry") == 1 && me.find("input.expiry_date").val() == "") {
                        me.find(".expiry_date").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_lot == 1 && me.attr("data-is-lot") == 1 && ((IsSalesMode && me.find("input.lot_nb").select2("data") == null) || (!IsSalesMode && me.find("input.lot_nb").val() == ""))) {
                        me.find(".lot_nb").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    //                    console.log(me.find("input.serial_nb").select2("data"))
                    //                    console.log((IsSalesMode && me.find("input.serial_nb").select2("data") == null))
                    if (activate_serial == 1 && me.attr("data-is-serial") == 1 && ((IsSalesMode && me.find("input.serial_nb").select2("data") == null) || (!IsSalesMode && me.find("input.serial_nb").val() == ""))) {
                        me.find(".serial_nb").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (parseFloat($("input.Quantity ", me).val()) < 0 || parseFloat($("input.UnitPrice ", me).val()) < 0 || parseFloat($("input.Disc ", me).val()) < 0 || parseFloat($("input.VATPerItem ", me).val()) < 0 || parseFloat($("input.vat_percent ", me).val()) < 0 || parseFloat($("input.cost_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) || ($.trim($('input.cost_percent', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.cost_percent', me).val() != '' && $('input.cost_percent', me).val() != 0) || ($.trim($('input.commission', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.commission', me).val() != '' && $('input.commission', me).val() != 0)) {
                        is_negative_value = true;
                    }
                    if ((me.find("input.commission").val() && !me.find("input[name=current_employee_id]").val() && me.find("input.commission").val() > 0) || (!me.find("input.commission").val() && me.find("input[name=current_employee_id]").val())) {
                        //                        console.log('hello guys')
                        me.find("input.commission").addClass(me.find("input.commission").val() ? "" : "wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }

                }
            })
            //            console.log(Data)
            //           
            if (!validate_option) {
                $("#PurchaseSuccess").attr("class", "alert alert-danger").html(check_prod_options)
                $(document.body).animate({
                    scrollTop: 0
                }, 800)
                return;
            }
            if ($("#extra_cost").val() != '' && parseFloat($("#extra_cost").val()) > 0 && $("#cost_dist_method").val() == 2) {
                if (total_cost_percent != 100) {
                    $("#PurchaseSuccess").attr("class", "alert alert-danger").html(cost_percent_validate)
                    $(document.body).animate({
                        scrollTop: 0
                    }, 800)
                    return false;
                }

            }
            if ($("#Account_Code").val() == '' || $("#Account_Code").val() == 0)
                IsValidated = false;
            if (!IsValidated) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
                $(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;
            }
            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 (IsSalesMode && $('.shipping_account_data').attr('data-main-shipping-account-id') && $('#is_invoice_total_on_shipping').is(":checked")) {
                var A1 = parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val()) || 0,
                    A2 = parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val()) || 0,
                    A3 = parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val()) || 0,
                    A4 = parseFloat($("#other_amount").val()) || 0;
                if ((A1 + A2 + A3 + A4) > (parseFloat($('#PurchaseInvoiceTotalDetails').attr('myvaluediscounted') || 0) - parseFloat($('#Shipping').val()))) {
                    $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('paid_amount_less_total'); ?>');
                    $(document.body).animate({
                        scrollTop: 0
                    }, 800)
                    return;
                }

            }
            //            console.log('here')
            //                         return false;

            $("#PurchaseDisabler").show();
            $("#InvoiceSubmitButton").attr("disabled", "disabled");
            //            return;
            $.ajax({
                url: IsEditMode ? "InventoryAjax/editInvoice" : "InventoryAjax/addPurchaseAjax",
                method: "POST",
                data: Data,
                dataType: 'json',
                complete: function(v1, v2) {
                    console.log('v1')
                    console.log(v1)
                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            //                            if (!IsEditMode) {
                            Invoice_ID = v1.responseJSON[1];
                            if (parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val()) > 0 || parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val()) > 0 || parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val()) > 0 || parseFloat($("#other_amount").val()) > 0)
                                $("#print_paid_amount").removeClass("disabled")
                            $("#PrintBtn,#PrintBtn1,#EditBtn,.check_temp_key").removeClass("disabled")
                            //                            }
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[2] + ' / ' + old_pays_lang + '</strong>')


                            CheckSubmit = true;
                        } else {
                            if (v1.responseJSON[0] == 'expiry_error') {
                                $.each(v1.responseJSON[1], function(indx, row) {
                                    $("#InventoryPurchaseTable tbody tr[data-id=" + row['Product_ID'] + "][data-depot-val=" + row['Depot_ID'] + "]  input.expiry_date[value=" + row['expiry_date'] + "]").addClass("wrong")
                                })
                                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_expiry_exist') ?>')

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

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

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

                            } else {
                                $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])
                                CheckSubmit = false;
                            }
                            $("#InvoiceSubmitButton").removeAttr("disabled")
                        }
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[2] + ' / ' + old_pays_lang + '</strong>')

                        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) {
        
       /* var Discount;
            if ($("input.is_collected_points").is(":checked")) {
                Discount = parseFloat(who.find(".Disc").val(100));
            }else{ 
                Discount = parseFloat(who.find(".Disc").val()) || 0;
            } */

        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,
            cost = parseFloat(who.attr("data-cost") || 0),
            net_total_with_invdisc = Net_Total * (1 - ((parseFloat($("#InvoiceDiscountInput").val() || 0)) / 100));
        var profit = net_total_with_invdisc - (cost * Qty);
        total_profit += profit;
        who.find("input.item_profit").val(profit == 0 ? '' : AddCommas(public_round_number(profit)))
        who.find("input.item_profit").attr('data-profit', profit)
        if (IsSalesMode) {
            var ctax = who.attr("data-tax") == 1 ? Qty * parseFloat(who.attr("unit-tax") || 0) : 0;
            card_tax += ctax
        }
        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,
            tr_vat2_percent = ((who.attr('data-vat') == 1 && is_sec_vat) || (allow_purchase_vat_edit && !IsSalesMode)) ? (parseFloat(who.find("input.vat2_percent").val()) || 0) : 0,
            TRvalue = (((who.attr('data-vat') == 1) || (allow_purchase_vat_edit && !IsSalesMode))) ? (parseFloat(net_total_with_invdisc)) : 0;
        vatVal = tr_vat_percent > 0 ? ((TRvalue * tr_vat_percent / 100) || 0) : 0;
        vatVal2 = (tr_vat2_percent > 0 && is_sec_vat) ? (((TRvalue + vatVal) * tr_vat2_percent / 100) || 0) : 0;
        totalvat += (vatVal + vatVal2);
        vat1_total += vatVal;
        vat2_total += vatVal2;
        taxAmount += TRvalue;
        //        if (is_td_total == 0) {
        //            var ttc_price = roundX_number(Single_Price * (1 + (tr_vat_percent / 100)));
        //            who.find('.ttc_price').val(ttc_price > 0 ? ttc_price : '')
        //        }
        //primary_total += parseFloat(who.find('.ttc_price').val() || 0) * Qty * (1 - Discount / 100);
        var mytdtotal = public_round_number(net_total_with_invdisc + vatVal + vatVal2);
        who.find(".Total").attr("myval", net_total_with_invdisc).html(public_round_number(mytdtotal, 3))
        $("#total_qty").html(total_qty)
        who.find('.VATPerItem').val(public_round_number(vatVal) > 0 ? public_round_number(vatVal) : '');
        //        console.log(vatVal2)
        who.find('.vat2_amount').val(public_round_number(vatVal2) > 0 ? public_round_number(vatVal2) : '');
        $('#PurchaseTaxableAmount').html(AddCommas(public_round_number(taxAmount)))
        $("#InvoiceVAT").html(AddCommas(public_round_number(totalvat))).attr('vat1_total', vat1_total).attr("vat2_total", vat2_total)

    }

    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 (parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(/,/g, "")) > parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(/,/g, ""))) {
            //            alert('Paid'+parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(",", ""))+' Total'+parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(",", "")))
            DoDisable = true;
        }
        //console.log(negative_sales)
        if (IsSalesMode) {
            $(".Quantity").removeClass('wrong')
            $("#InventoryPurchaseTable tbody tr").each(function() {
                var pid = $(this).attr("data-id"),
                    depot_id = $("input[name=current_depot_id]", $(this)).val() != '' ? $("input[name=current_depot_id]", $(this)).val() : $("#Depot_Loc").val();
                //         console.log('neg'+negative_sales)        
                if (negative_sales == 0 && $(this).attr("data-is-service") == 0) {

                    var inv_qty = 0;
                    $("#InventoryPurchaseTable tbody tr[data-id=" + pid + "]").each(function() {
                        var cur_depot_id = $("input[name=current_depot_id]", $(this)).val() != '' ? $("input[name=current_depot_id]", $(this)).val() : $("#Depot_Loc").val();
                        if (cur_depot_id == depot_id)
                            inv_qty += (parseFloat($(this).find(".Quantity").val()) || 0) * (parseFloat($(this).attr("data-conv")) || 0);
                    })
                    var conv = (parseFloat($(this).attr("data-conv")) || 0);
                    if (inv_qty > parseFloat($(this).attr('data-qty')) * conv) {
                        //                        console.log(inv_qty + '====' + (parseFloat($(this).attr('data-qty')) * conv))
                        $(this).find(".Quantity").addClass("wrong");
                        DoDisable = true;
                    }
                    //                    if (parseFloat($(this).find(".Quantity").val()) > parseFloat($(this).attr('data-qty'))) {
                    //                        $(this).find(".Quantity").addClass("wrong");
                    //                        DoDisable = true;
                    //                    }
                }

                if (parseFloat($(this).find(".Disc").val()) > parseFloat(max_discount)) {
                    $(this).find(".Disc").addClass("wrong");
                    DoDisable = true;
                }



            })
        }

        // document.title = Rows.length
        if (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }

    function InputMustBeAtleastN(who, N) {
        if (parseInt(who.value) < N || !parseInt(who.value))
            who.value = N;
        UpdatePurchaseInvoiceTotalPaid();
    }

    function UpdatePurchaseInvoiceTotalPaid() {
        var A1 = public_round_number(parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val())) || 0,
            A2 = public_round_number(parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val())) || 0,
            A3 = public_round_number(parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val())) || 0;
        if (activate_autofill_other_amount == 1 && stop_autofill_other_amount == 0 && person_has_other_acc == 1) {
            var paid = (A1 + A2 + A3),
                total = public_round_number(parseFloat($("#PurchaseInvoiceTotalDetails").attr("final-total"))) || 0;
            $("#other_amount").val(total - paid);

        }
        var A4 = public_round_number(parseFloat($("#other_amount").eq(0).val())) || 0;
        $("#PurchaseInvoiceTotalPaid").text(AddCommas(A1 + A2 + A3 + A4));
        UpdateSubmitButtonStatus();
        if ((A1 + A2 + A3 + A4) >= parseFloat($("#PurchaseInvoiceTotalDetails").attr("myvaluediscounted")))
            $("#PurchaseInvoiceDueDate").removeAttr("required")
        else
            $("#PurchaseInvoiceDueDate").attr("required", "required")

    }
    $(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) {
        var me = fill_purchase_duedate_from_bill == 1 && !IsSalesMode ? $('#ship_date') : $('#PurchaseInvoiceDate');
        if (nb_days && me.val()) {
            var date2 = me.datepicker('getDate');
            date2.setDate(date2.getDate() + parseInt(nb_days));
            $('#PurchaseInvoiceDueDate').datepicker('setDate', date2);
            $('#delivery_date').datepicker('setDate', date2);
        }
    }

    function fillShortcutFields() {
        var amount = parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(/,/g, "")),
            currency_id = $('input[name=Currency_ID]').val(),
            currency_name = $('#CurrencyDropDown button span').html(),
            parameters = '&amount=' + amount + '&currency_id=' + currency_id + '&currency_name=' + currency_name;
        if ($('#search_supplier').val()) {
            parameters += '&account_id=' + $('#Supplier_Name').attr('data-account-id') + '&account_name=' + $('#Supplier_Name').attr('data-account-name') + '&account_code=' + $('#Supplier_Name').attr('data-account-code');
            if (IsSalesMode)
                parameters += '&customer_id=' + $('#search_supplier').val() + '&customer_name=' + $('#search_supplier').select2('data').text
        }
        var schedule_bills_main_url = $('#schedule_bill_shortcut').attr('data-main-url'),
            payment_receipt_main_url = $('#payment_receipt_shortcut').attr('data-main-url');
        $('#schedule_bill_shortcut').attr('data-src', schedule_bills_main_url + parameters);
        $('#payment_receipt_shortcut').attr('data-src', payment_receipt_main_url + parameters);
    }

    function update_open_frame_sold_items() {
        var customer_id, customer_name = '';
        if ($('#search_supplier').val()) {
            customer_id = $('#search_supplier').val();
            customer_name = $('#search_supplier').select2('data').text;
        }
        $('.open_detailed_sold_items').each(function() {
            $(this).attr('data-src', $(this).attr('data-main-url') + (customer_id != '' ? ('&customer_id=' + customer_id + '&customer_name=' + customer_name) : ''));
        });
    }


    function fill_price_by_ttc(mytr, ttc_price) {
        var myval = parseFloat(ttc_price) || 0,
            //                    mytr = $(this).parents("tr"),
            //                    myqty = parseFloat(mytr.find(".Quantity").val()) || 0,
            vat_percent = parseFloat(mytr.find(".vat_percent").val()) || 0,
            vat2_percent = parseFloat(mytr.find(".vat2_percent").val()) || 0,
            vat2_amount = myval * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
            vat_amount = (myval - vat2_amount) * (vat_percent / 100) / (1 + (vat_percent / 100)),
            amt_no_vat = myval - vat_amount - vat2_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))
        mytr.find(".vat2_amount").val(public_round_number(vat2_amount))
        //            $(this).attr("MyVal", myval)
        is_td_total = 1;
        //            console.log((myval-vat_amount))
        mytr.find(".UnitPrice").val(myval - vat_amount - vat2_amount) //.trigger("keydown")
    }

    function fix_cloned_row(ClonedRow) {
        ClonedRow.find("input").val("")
        ClonedRow.attr("data-conv", "1")
        ClonedRow.removeAttr("data-id")
        ClonedRow.attr("data-expiry", "0")
        ClonedRow.attr("data-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-is-lot", "0")
        ClonedRow.attr("data-is-serial", "")
        ClonedRow.attr("data-ref", "")
        ClonedRow.attr("data-qty", "")
        ClonedRow.attr("data-depot-val", "")
        ClonedRow.attr("data-cost-arr", "")
        $(".option-tr,.option-main-td", $(ClonedRow)).addClass("hidden")
        //        ClonedRow.find(".Quantity").closest('tooltip').remove()
        EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
        EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
        EnableAutoComplete($(".AutoComplete.person_code", ClonedRow).removeClass("AutoAdded"));
        $(".Hint,.Total", ClonedRow).html("")
        ClonedRow.find(".mylabel").remove()
        ClonedRow.find('div.bootstrap-tagsinput').html('No Tags')
        //                $(".expiry_date", ClonedRow).removeClass('hidden').datepicker({autoclose: true});
        ClonedRow.removeAttr("data-prod-status")
        //                $(".Hint", ClonedRow).html("")
        $("input.ProductName,input.CODE,input.Quantity,select.UOM_ID,input[name=current_depot_id]", ClonedRow).removeAttr("disabled")
        $("input", ClonedRow).removeClass("wrong")
        $(".deleteRowRequest ", ClonedRow).removeClass("hidden")
        $(".select2-container", ClonedRow).empty().remove()
        $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2();
        $(".item_driver_id", ClonedRow).empty().html($("#select_item_driver").html()).show().select2()
        ClonedRow.find("input.expiry_date,input.lot_nb,input.serial_nb").addClass('hidden')
        build_select2($("input.item-class", ClonedRow), "xhr/PricingClassSearch?type=1")
        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('')
        build_select2($("input[name=current_depot_id]", ClonedRow), "xhr/depotSearch" + ('depot_options_ids' in invoice_type_details ? '?depots=' + invoice_type_details['depot_options_ids'] : ''))

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


        } else {
            $("input.expiry_date", ClonedRow).datepicker({
                autoclose: true
            });
            build_select2($("input[name=current_vehicle_id]"), "xhr/TruckSearch")

        }
        $(".select2-container", ClonedRow).show()
    }

    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-is-lot", "0")
        ClonedRow.attr("data-is-serial", "0")
        ClonedRow.attr("data-ref", "")
        ClonedRow.attr("data-depot-val", "")
        $(".option-tr,.option-main-td", $(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],input.lot_nb,input.serial_nb").attr('data-select-name', '').val('')
        $(".select2-container.UOM_ID", ClonedRow).show()
    }

    function trigger_proceed_extra_cost(is_main) {
        var total_extra_cost = 0,
            extra_validate = true,
            cost_arr = [];
        $(".extra_row").each(function() {
            var from_currency = $(this).find("select.extra_cost_currency").val(),
                amount = parseFloat($(this).find(".extra_cost_amount").val()) || 0,
                //                    type = parseFloat($(this).find("select.extra_cost_type").val()) || 0,
                rate = parseFloat($(this).find(".extra_cost_rate").val()) || 0,
                inv_amount = amount * rate;
            if (from_currency != '' && from_currency != '0' && amount > 0 && rate > 0) {
                total_extra_cost += inv_amount;
            } else {
                if ((from_currency == '0' || amount == 0 || rate == 0) &&
                    (from_currency != '0' || amount > 0 || rate > 0)) {
                    extra_validate = false;
                }

            }
            cost_arr.push({
                type: $("select.extra_cost_type", $(this)).val(),
                amount: $("input.extra_cost_amount ", $(this)).val(),
                currency_id: $("select.extra_cost_currency ", $(this)).val(),
                current_rate: $("input.extra_cost_rate", $(this)).val(),
                debit_acc_id: $("input.extra_cost_debit_acc", $(this)).val(),
                debit_acc_name: $("input.extra_cost_debit_acc", $(this)).select2("data") != null ? $("input.extra_cost_debit_acc", $(this)).select2("data").text : '',
                credit_acc_id: $("input.extra_cost_credit_acc", $(this)).val(),
                credit_acc_name: $("input.extra_cost_credit_acc", $(this)).select2("data") != null ? $("input.extra_cost_credit_acc", $(this)).select2("data").text : '',
                note: $("input.note", $(this)).val()
            })
        })


        //            console.log(total_extra_cost)
        if (extra_validate) {
            var current_rate = parseFloat($("#current_rate").val()) || 0;
            if (current_rate == 0)
                current_rate = ConvertCurrency2(1, $("#CurrencyDropDown button input").val(), local_currency)
            if (is_main == 1) {
                $("#extra_cost").val(public_round_number((total_extra_cost / current_rate), 3))
                global_cost_arr = cost_arr;
            } else {
                var cost = public_round_number((total_extra_cost / current_rate), 3);
                $("input.additional_cost", extra_cost_row).val(cost == 0 ? '' : cost)
                extra_cost_row.attr("data-cost-arr", JSON.stringify(cost_arr))
            }

            $("#extra_cost_modal").modal("hide")
        } else {
            $("#extra_cost_alert").attr("class", "alert alert-danger").html(RequiredField)
        }
    }

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

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

        $("#SupplierInfoContent").removeClass('hidden')
        if ($('#search_supplier').val() == '') {
            $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
            $("#ProdLoader").removeClass("hideme")
            $("#InventoryPurchaseTable").addClass("hideme")
            $("#choose_items").attr("disabled", "disabled")
        } 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")
            $("#choose_items").attr("disabled", "disabled")
        } else {
            $("#ProdLoader").addClass("hideme")
            $("#InventoryPurchaseTable").removeClass("hideme")
            $("#choose_items").removeAttr("disabled")
        }
        var Data = {
            id: $('#search_supplier').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-account-name='" + Data[0]['Account_Name'] + "' data-account-id='" + Data[0]['Account_ID'] + "' data-account-code='" + Data[0]['Account_Code'] + "' data-id='" + Data[0]['Customer_Name'] + "'>" + Data[0]['Customer_Name'] + "</span>" + (has_ledger_perm ? "<span class='fa fa-eye m-l-5 openFrame' data-src='ACC/ledger?is_pop=1/" + Data[0]['Account_Code'] + "' style='color:#8a7dbe;cursor:pointer'></span>" : "") + "</strong>";
                        Content += "<strong><span class='fa fa-solid fa-bars m-l-5 openFrame' data-src='Inventory/products_customers?is_pop=1/" + Data[0]['Customer_ID'] + "' style='color:#8a7dbe;cursor:pointer'></span>" + "</strong>";
                        Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Customer_Company'] + "</span></div>";
                        Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Customer_Email'] + "</span></div>";
                        Content += "<div><strong>" + 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>";
                        if (show_main_shipping_address == 1) {
                            Content += "<div class=''><strong>Main Shipping Address: </strong>" + Data['main_shipping_address'] + "</div>";
                        }
                        if (show_ret_cancel_alert_sales) {
                            if ('total_returns' in Data && Data['total_returns'] != 0) {
                                Content += "<div class='red-star'><strong>Returns: </strong>Total (" + Data['total_returns'] + "), last Return Date ( " + Data['last_return_date'] + ")</div>";
                            }
                            if ('total_cancelled' in Data && Data['total_cancelled'] != 0) {
                                Content += "<div class='red-star'><strong>Cancelled : </strong>Total (" + Data['total_cancelled'] + "), last Cancelled Date ( " + Data['last_cancelled_date'] + ")</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" + ('class_options_ids' in invoice_type_details ? '&classes=' + invoice_type_details['class_options_ids'] : ''))
                        $("#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'])
                        if (has_det_sales_rep_perm)
                            update_open_frame_sold_items();
                        if (sales_inv_fields_req.includes('0') && Data[0]['has_branch'] == 1) {
                            $("#customer_branch_label").removeClass("hidden")
                            $("#customer_branch_id").attr("required", "required")
                        } else {
                            $("#customer_branch_label").addClass("hidden")
                            $("#customer_branch_id").removeAttr("required")
                        }
                    } else {
                        $("#SupplierInfoContent").empty();
                        var Content = "";
                        Content += "<strong><span class='Name' id='Supplier_Name' data-account-name='" + Data[0]['Account_Name'] + "' data-account-id='" + Data[0]['Account_ID'] + "' data-account-code='" + Data[0]['Account_Code'] + "' data-id='" + Data[0]['Supplier_Name'] + "'>" + Data[0]['Supplier_Name'] + "</span>" + (has_ledger_perm ? "<span class='fa fa-eye m-l-5 openFrame' data-src='ACC/ledger?is_pop=1/" + Data[0]['Account_Code'] + "' style='color:#8a7dbe;cursor:pointer'></span>" : "") + "</strong>";
                        Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Supplier_Company'] + "</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>" + 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>" + 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>";
                        Content += "<div id='Class_Currency' style='display:none;'></div>";
                        $("#pricing_class").val('').attr("data-select-name", '')
                        build_select2($("#pricing_class"), "xhr/PricingClassSearch?type=1&supp_id=" + $("#search_supplier").val())

                        $("#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'])

                    }
                    if (Data[0]['other_pay_acc_id'] > 0) {
                        person_has_other_acc = 1;
                    }
                    $("#other_acc_id").val(Data[0]['other_pay_acc_id']).attr("data-select-name", Data[0]['other_pay_acc_name']).trigger("change")
                    fillShortcutFields()
                }
            }
        })
    }

    function build_optional_link(ref, cb, cb_param) {
        var tr = $("#InventoryPurchaseTable tbody tr[data-ref=" + ref + "]"),
            product_id = tr.attr("data-id"),
            tr_qty = (parseFloat(tr.find("input.Quantity").val()) || 0) * (parseFloat(tr.attr("data-conv")) || 0) / (parseFloat(tr.attr("recipe-qty")) || 1);
        $(".op-block:gt(0)").empty().remove()
        $(".op-block:eq(0) .op-block-det").empty()
        $("#product_options_modal").attr('data-ref', ref).modal("show");
        $("#product_options_modal #next_btn").prop("disabled", true)
        $("#product_options_modal .op-title").addClass("hidden")
        $.ajax({
            url: "POSAjax/get_prod_options",
            data: {
                product_id: product_id
            },
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {

                    var data = v1.responseJSON;
                    //                    console.log(data)
                    $.each(data, function(indx, row) {
                        var parent;
                        if (indx == 0) {
                            parent = $(".op-block:eq(0)");
                        } else {
                            parent = $(".op-block:eq(0)").clone();
                            $(".op-div", parent).remove()
                            parent.appendTo($("#op_main_div"))
                        }
                        var qty = public_round_number(tr_qty * row['quantity']);
                        $(".op-title", parent).html(block_title.replace('[[nb]]', qty) + (row['is_required'] == 1 ? '<span class="red-star" style="font-size:27px;">*</span>' : ''))
                        parent.attr('data-qty', qty)
                        parent.attr('data-required', row['is_required'])
                        $.each(row['details'], function(child_indx, child_row) {
                            var cloned = $('.temp-op-div').clone();
                            cloned.removeClass("hidden temp-op-div")
                            cloned.attr("data-id", child_row['sub_product_id'])
                            cloned.attr("data-option-id", row['option_id'])
                            cloned.attr("data-uom", child_row['UOM_ID'])
                            $(".op-prod-name", cloned).text(child_row['product_name'])
                            parent.find('.op-block-det').append(cloned)
                        });
                    });
                    if (typeof cb !== 'undefined')
                        cb.apply(null, (typeof cb_param === 'undefined' ? [] : cb_param));
                    $("#product_options_modal #next_btn").prop("disabled", false)
                    $("#product_options_modal .op-title").removeClass("hidden")



                }

            }
        })
    }

    function fill_cost_modal(arr) {
        $.each(arr, function(indx, row) {
            if (indx == 0) {
                $("select.extra_cost_type").val(row['type']).select2()
                $("input.extra_cost_amount ").val(row['amount'])
                $("select.extra_cost_currency").val(row['currency_id']).select2()
                $("input.extra_cost_rate").val(row['current_rate'])
                $("input.extra_cost_debit_acc").val(row['debit_acc_id']).attr("data-select-name", row['debit_acc_name']).trigger("change")
                $("input.extra_cost_credit_acc").val(row['credit_acc_id']).attr("data-select-name", row['credit_acc_name']).trigger("change")
                $("input.note").val(row['note'])
            } else {
                var Parent = $(".extra_row:eq(0)"),
                    NewItem = Parent.clone().insertAfter(Parent);
                NewItem.find(".select2-container").remove();
                $("select.extra_cost_type", NewItem).val(row['type']).select2()
                $("input.extra_cost_amount", NewItem).val(row['amount'])
                $("select.extra_cost_currency", NewItem).val(row['currency_id']).select2()
                $("input.extra_cost_rate", NewItem).val(row['current_rate'])
                $("input.extra_cost_debit_acc", NewItem).val(row['debit_acc_id']).attr("data-select-name", row['debit_acc_name']).trigger("change")
                $("input.extra_cost_credit_acc", NewItem).val(row['credit_acc_id']).attr("data-select-name", row['credit_acc_name']).trigger("change")
                $("input.note", NewItem).val(row['note'])
                build_select2($(".extra_cost_debit_acc,.extra_cost_credit_acc", NewItem), ("xhr/accIDSearch?type=Payment"))

                $(".select2-container", NewItem).show();
            }
        })
    }

    function trigger_proceed_extra_cost_currency() {
        var current_rate = parseFloat($("#current_rate").val()) || 0;

        $("#InventoryPurchaseTable tbody tr").each(function() {
            console.log($(this).attr("data-cost-arr"))
            if ($(this).attr("data-cost-arr") != '' && $(this).attr("data-cost-arr") != undefined) {


                var total_extra_cost = 0;
                $.each(JSON.parse($(this).attr("data-cost-arr")), function(indx, row) {
                    var amount = row['amount'],
                        rate = row['current_rate'],
                        inv_amount = amount * rate;
                    console.log(amount + '===' + rate + '====' + inv_amount)
                    total_extra_cost += inv_amount;

                })
                if (current_rate == 0)
                    current_rate = ConvertCurrency2(1, $("#CurrencyDropDown button input").val(), local_currency)
                var cost = public_round_number((total_extra_cost / current_rate), 3);
                $("input.additional_cost", $(this)).val(cost == 0 ? '' : cost)
            }
        })
        if (global_cost_arr != '' && global_cost_arr != undefined) {
            var total_extra_cost = 0;
            $.each(global_cost_arr, function(indx, row) {
                var amount = row['amount'],
                    rate = row['current_rate'],
                    inv_amount = amount * rate;
                total_extra_cost += inv_amount;

            })
            if (current_rate == 0)
                current_rate = ConvertCurrency2(1, $("#CurrencyDropDown button input").val(), local_currency)
            $("#extra_cost").val(public_round_number((total_extra_cost / current_rate), 3))

        }

    }

</script>
