<?php
if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
//echo '<pre>';
//print_r($edit_arr);
if ($IsEdit && empty($edit_arr['Main']['Return_Invoice_ID']) && !$is_exchange) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this retrun invoice! 
        <br>
        This return is not available.
    </div>
    <?php
    die();
}
$sales_inv_fields_hide = smc_session()['default_setting']['return_from_customer_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['return_from_customer_fields_to_hide']) : [];
$purchase_inv_fields_hide = smc_session()['default_setting']['return_purchase_invoice_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['return_purchase_invoice_fields_to_hide']) : [];
//echo"<pre>";die(print_r($sales_inv_fields_hide));
$has_sales_cost_perm = $permissions->hasPermission('view_return_customer_cost');
$has_purchase_cost_perm = $permissions->hasPermission('view_return_vendor_cost');
$has_sales_last_price = $permissions->hasPermission($is_actual ? 'actual_view_sales_last_price' : 'view_sales_last_price');
?>
<style type="text/css">
    #InventoryPurchaseTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #InventoryPurchaseTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
        padding: 5px 9px 12px;
        height: 40px;
    }
    #InventoryPurchaseTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #InventoryPurchaseTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput,#TTCInvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;


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

    }
    #InventoryPurchaseTable .Hint{
        position: absolute;
        font-size: 10px;
        display: block;
        font-weight: bold;
        height: 12px;
        line-height: 11px;
        cursor: default;
        background: #ccc;
        padding: 0 2px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        bottom: 3px;
        right: 1px;
        left: 1px;
        color: #4c0870;
    }
    #InventoryPurchaseTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #InventoryPurchaseTable .Disc{
        width:70px;
    }
    #InventoryPurchaseTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    #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;
        /*
        -webkit-border-radius: 3px 0px 0px 3px !important;
        -moz-border-radius: 3px 0px 0px 3px !important;
        border-radius: 3px 0px 0px 3px !important;
        */
    }
    .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;
    }

    .diff_class,.expiry_width{
        width:300px!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) {
                    ?>
                    <div class="alert alert-danger" role="alert">
                        <button class="close" data-dismiss="alert"></button>
                        <strong>Danger: </strong>you can not edit this return invoice! 
                        <br>
                        This return invoice is transfered to the main branch.
                    </div>
                    <?php
                    //    die();
                }
                ?>

                <div id="PurchaseSuccess" class="hidden"></div>
                <div class="invoice ">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <div class="inv_div row m-b-15 <?php echo ($IsEdit || $is_exchange) ? 'hidden' : '' ?>">

                                    <div class="input-group  col-md-6 center-margin pull-left">
                                        <span class="input-group-addon primary ">
                                            <?php print CommonLanguage::getMessage('invoice'); ?> #
                                        </span>
                                        <input type="text" id="Invoice_Purchase_ID" class="form-control ui-autocomplete-input AutoAdded" placeholder="search by number,customer,date" autocomplete="off" data-id="<?php echo $IsEdit ? $edit_arr['Main']['Invoice_Purchase_ID'] : '' ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <button class=" btn btn-primary btn-cons   " id="generate" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('generate_invoice'); ?></span></button>

                                    </div>
                                </div>

                                <div class='row'>
                                    <div class="input-group  col-md-4 center-margin pull-left" >
                                        <label><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer' : 'choose_supplier'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1" : "Inventory/ViewVendorList?is_pop=1" ?>" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="search_supplier full-width" id="search_supplier" name="search_supplier" type="hidden" value="<?= $IsEdit ? $edit_arr['Main']['Person_ID'] : ""; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Person']['Name'] : ""); ?>' />
                                    </div>
                                    <div class="Account_Code col-md-4">
                                        <label><?php print CommonLanguage::getMessage('accounts'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class=" full-width" id="Account_Code" name="Account_Code" type="hidden" value="<?= $IsEdit ? $edit_arr['Main']['Account_ID'] : smc_session()['user_accounts'][$IsSales ? 'sales_account_id' : 'purchase_account_id']; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Main']['Account_Name'] : smc_session()['user_accounts'][$IsSales ? 's_name' : 'p_name']); ?>' />
                                    </div>

                                    <div class="col-md-3 <?php echo ($IsSales && $permissions->hasPermission('change_class')) ? '' : 'hidden' ?>">
                                        <label><?php echo CommonLanguage::getMessage('pricing_class'); ?></label>
                                        <input type="text"   id="pricing_class" class=" full-width" value="<?php echo (($IsSales && $IsEdit) ? $edit_arr['Main']['Class_ID'] : smc_session()['pricing_class_id']) ?>" data-select-name="<?php echo ($IsSales && $IsEdit) ? $edit_arr['Main']['Class_Name'] : smc_session()['pricing_class_name'] ?>">

                                    </div> 


                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div class="row">


                                    <div id="SupplierInfo" class="col-md-4">
                                        <input type="hidden" name="Supplier_ID" value="<?php echo $IsEdit ? ($edit_arr['Person']['ID'] ) : '' ?>" <?php echo $IsEdit ? '' : 'required' ?>  id="Supplier_ID" />
                                        <div id="SupplierInfoContent" class="<?php echo $IsEdit ? '' : 'hidden' ?>">
                                            <strong><span class='Name hidden' id='Customer_Name' data-id='<?php echo $IsEdit ? $edit_arr['Person']['Name'] : '' ?>'><?php echo $IsEdit ? $edit_arr['Person']['Name'] : '' ?></span></strong>
                                            <!--<div><strong><?php echo CommonLanguage::getMessage('company'); ?>: </strong><span class='Company'><?php echo $IsEdit ? $edit_arr['Person']['Company'] : '' ?></span></div>-->
                                            <!--<div><strong><?php echo CommonLanguage::getMessage('Email'); ?>: </strong><span class='Email'><?php echo $IsEdit ? $edit_arr['Person']['Email'] : '' ?></span></div>-->
                                            <div><strong><?php echo CommonLanguage::getMessage('Phone'); ?>: </strong><span class='Phone'><?php echo $IsEdit ? $edit_arr['Person']['Phone'] : '' ?></span></div>
                                            <div><strong><?php echo CommonLanguage::getMessage('vat'); ?>: </strong><span class='vat'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['person_vat'] : '' ?></span></div>
                                            <div><strong><?php echo CommonLanguage::getMessage('cr'); ?>: </strong><span class='cr'><?php echo ($IsEdit || $IsOrder || $is_delivery || $is_note || $is_copy || $is_return) ? $edit_arr['Person']['person_cr']  : '' ?></span></div>
                                            <div><strong><?php echo CommonLanguage::getMessage('address'); ?>: </strong><span class='Address'><?php echo $IsEdit ? $edit_arr['Person']['Address'] : '' ?></span></div>
                                            <div><strong><?php echo CommonLanguage::getMessage('country'); ?>: </strong><?php echo $IsEdit ? $edit_arr['Person']['Country_Name'] : '' ?></div>
                                            <div id='Finance_Account' data-id='<?php echo $IsEdit ? $edit_arr['Person']['Account_ID'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('financial_nb'); ?>: </strong><?php echo $IsEdit ? $edit_arr['Person']['Account_Code'] : '' ?></div>
                                            <div id='Class_ID' style='display:none;'><?php echo ($IsEdit && $IsSales) ? $edit_arr['Person']['Class_ID'] : '' ?></div>
                                            <div id='Class_Currency' style='display:none;'><?php echo ($IsEdit && $IsSales) ? $edit_arr['Person']['Class_Currency'] : '' ?></div>

                                        </div>
                                        <div id="SupplierAccInfo" class="<?php echo $IsEdit ? '' : 'hidden' ?>">
                                            <div id='Account_CodeDiv' value='<?php echo $IsEdit ? $edit_arr['Main']['Account_ID'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('account_code') ?>: </strong><?php echo $IsEdit ? $edit_arr['Main']['Account_Name'] . ' - ' . $edit_arr['Main']['Account_Code'] : '' ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 <?php echo $IsSales ? '' : 'hidden'; ?>">
                                        <label><?php echo CommonLanguage::getMessage('customer_branch'); ?></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>
                            </div>
                            <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">

                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="PurchaseInvoiceDate" name="PurchaseInvoiceDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Date'] : $today); ?>" />
                                    <span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>
                                </div>


                                <div  id="depot" class="form-group <?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(17, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?> " style="display: flex" >

                                    <div style="width: 48%;margin-right:2%;" >
                                        <label><?php print CommonLanguage::getMessage('Depot'); ?></label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" data-old="<?php echo $IsEdit ? $edit_arr['Main']['Depot_ID'] : ''; ?>" value="<?= $IsEdit ? $edit_arr['Main']['Depot_ID'] : (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" data-select-name='<?= json_encode($IsEdit ? $all_depots[$edit_arr['Main']['Depot_ID']]['Depot_Name'] : (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name'])) ?>' />


                                    </div>
                                    <?php if ($IsSales) { ?>
                                        <div style="width: 50%;" >
                                            <label><?php print CommonLanguage::getMessage('salesman'); ?></label>
                                            <input  id="PIC_ID" name="PIC_ID" class="full-width PIC_ID" type="hidden"  value="<?= ($IsEdit && !empty($edit_arr['Main']['Sales_ID'])) ? $edit_arr['Main']['Sales_ID'] : '' ?>" data-select-name='<?= json_encode(($IsEdit && !empty($edit_arr['Main']['Employee_Name'])) ? $edit_arr['Main']['Employee_Name'] : '') ?>' />


                                        </div>
                                    <?php } ?>

                                </div>
                                <div  id="depot" class="form-group " style="display: flex" >

                                    <div style="width: 48%;margin-right:2%;" >
                                        <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" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>  value="<?php echo $IsEdit ? $edit_arr['Main']['current_rate'] : '' ?>" />


                                    </div>
                                    <div style="width: 50%;" >
                                        <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" id="second_currency_rate" name="second_currency_rate" class="form-control full-width second_currency_rate" <?php echo ($DefaultCurrencyID == smc_session()['default_setting']['second_currency']) ? 'disabled' : '' ?>  value="<?php echo $IsEdit && !empty($edit_arr['Main']['second_currency_rate']) ? $edit_arr['Main']['second_currency_rate'] : '' ?>" />
                                        </div>
                                    </div>

                                </div>


                                <div id="CurrencyIDContainer" class=" m-t-10" >
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms Closable  " id="CurrencyDropDown">
                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><?php echo $IsEdit ? ($edit_arr['Main']['Currency_Name'] . ' - ' . $edit_arr['Main']['Currency_Symbol']) : CommonLanguage::getMessage('select') ?></span>
                                                <input type="hidden" name="Currency_ID" value="<?php echo $IsEdit ? $edit_arr['Main']['Currency_ID'] : $DefaultCurrencyID ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false"/>
                                            </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="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 1 ? '' : 'hidden' ?>" style="width: 48%;margin-right:2%;" >
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" value="<?php echo $IsEdit ? $edit_arr['Main']['job_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_arr['Main']['job_name'] : '' ?>"/>
                                    </div>
                                    <div class="<?php echo smc_session()['default_setting']['activate_project'] == 1 ? '' : 'hidden' ?>" style="width: 50%;" >
                                        <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                        <input type="hidden" class="full-width" id="project_id" value="<?php echo ($IsEdit && !empty($edit_arr['Main']['project_id'])) ? $edit_arr['Main']['project_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_arr['Main']['project_name'] : '' ?>"/>
                                    </div>

                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <div id="ProdLoader" class="text-center alert <?php echo $IsEdit ? '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 ? '' : 'hideme' ?>" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center" style="width:3%"></th>
                                    <th class="text-center  <?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?> " style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center  <?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:20%"><?php print CommonLanguage::getMessage('product_name'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('Expiry_Date'); ?></th>
                                    <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('quantity'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('UOM'); ?></th>

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

                                    <th class="text-center <?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?> " style="width:20%"><?php print CommonLanguage::getMessage('Description'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width: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)) ? 'hidden' : ''; ?>" style="width:5%"><?php print CommonLanguage::getMessage('discount_percent'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(5, $sales_inv_fields_hide)) || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:10%"><?php print CommonLanguage::getMessage('vat'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(6, $sales_inv_fields_hide)) || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('vat_percent'); ?></th>
                                    <th class="text-center <?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !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(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !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(15, $sales_inv_fields_hide)) || !$IsSales || $is_noqty) ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('is_damaged'); ?></th>
                                    <th class="text-center"style="width:10%"><?php print CommonLanguage::getMessage('total'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit) {
                                    foreach ($edit_arr['Details'] as $item) {
                                        $uoms = explode('/', $item['Product_UOM']);
                                        //                                        die(print_r($uoms));
                                        ?>

                                        <tr  data-is-lot="<?php echo $item['is_lot'] ?>" data-is-serial="<?php echo $item['is_serial'] ?>" data-conv="<?php echo $item['uom_con'] ?>"
                                             data-qty="<?php echo $item['Product_Quantity'] ?>" data-vat="<?php echo $item['VAT'] ?>"
                                             data-id="<?php echo $item['Product_ID'] ?>" 
                                             unit_price="<?php echo $item['Product_Net_Price'] ?>" data-prod-status="<?php echo $item['Status_ID'] ?>" data-tax = "<?php echo $IsSales ? $item['is_tax'] : 0 ?>"
                                             data-expiry="<?php echo $item['is_expiry'] ?>"
                                             data-is-service="<?php echo $item['is_service'] ?>">
                                            <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td> 
                                            <td class=" <?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE  input-barcode-scan" value = "<?php echo $item['Bar_Code'] ?>"></td>
                                            <td class="<?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item['Name'] ?>"><span class="Hint"></span></td>
                                            <td 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 echo $IsSales ? 'text' : 'hidden'; ?>"/>
                                            </td>

                                            <td><input type="text" class="form-control Quantity isnumber" value = "<?php echo $item['Item_Quantity_Current'] ?>"><span class="Hint"></span></td>
                                            <td class="<?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                    <?php for ($i = 0; $i < count($uoms); $i++) { ?>
                                                        <option value="<?php echo $uoms[$i]; ?>" <?php echo $uoms[$i] == $item['UOM_ID'] ? 'selected' : '' ?>><?php echo $all_uom[$uoms[$i]]['UOM_Name']; ?></option>
                                                    <?php } ?>
                                                </select>
                                            </td>
                                            <td class="<?php echo ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                <input  data-select-name="<?php echo $item['is_lot'] == 1 ? $item['lot_nb'] : ''; ?>" type="<?php echo $IsSales ? 'text' : 'hidden'; ?>" class="<?php echo $IsSales ? 'form-control' : 'full-width'; ?> lot_nb hidden" value="<?php echo $item['lot_nb'] ?>"/>
                                            </td>
                                            <td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                                <input  data-select-name="<?php echo $item['is_serial'] == 1 ? $item['serial_nb'] : ''; ?>" type="<?php echo $IsSales ? 'text' : 'hidden'; ?>" class="<?php echo $IsSales ? 'form-control' : 'full-width'; ?> serial_nb hidden" value="<?php echo $item['serial_nb'] ?>"/>
                                            </td>

                                            <td class=" <?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?> <?php echo smc_session()['default_setting'][$IsSales ? 'item_note_in_sales' : 'item_note_in_purchase'] ? '' : 'hidden' ?>"><input type="text" class="form-control item_note" value = "<?php echo $item['product_description'] ?>"></td>
                                            <td class="<?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber" value = "<?php echo $item['Product_Net_Price'] ?>" ><span class="Hint"></span></td>
                                            <td class="<?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>"><input type="text" class="form-control ttc_price isnumber" <?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)) ? 'hidden' : ''; ?>"><input type="text" class="form-control Disc" value = "<?php echo $item['Product_Discount'] ?>"></td>
                                            <td class="<?php echo ($IsSales && in_array(5, $sales_inv_fields_hide)) || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && $item['VAT'] == 1) ? '' : 'disabled' ?> value="<?php echo $item['vat_amount'] ?>"></td>
                                            <td class="<?php echo ($IsSales && in_array(6, $sales_inv_fields_hide)) || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && $item['VAT'] == 1) ? '' : 'disabled' ?> value="<?php echo $item['vat_percent'] ?>"  ></td>
                                            <td class="<?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_amount isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && ($item['VAT'] == 1)) ? '' : 'disabled' ?> value="<?php echo $item['vat2_amount'] ?>"  ></td>
                                            <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_percent isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') && ($item['VAT'] == 1)) ? '' : 'disabled' ?> value="<?php echo $item['vat2_percent'] ?>"  ></td>

                                            <td class="<?php echo (($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales || $is_noqty) ? 'hidden' : ''; ?>"><input type="checkbox" name="is_damaged" <?php echo $item['is_damaged'] == 1 ? 'checked' : ''; ?> class="is_damaged"/></td>
                                            <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></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>
                                        <td class=" <?php echo ($IsSales && in_array(0, $sales_inv_fields_hide)) || (!$IsSales && in_array(0, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete CODE  input-barcode-scan"></td>
                                        <td class="<?php echo ($IsSales && in_array(1, $sales_inv_fields_hide)) || (!$IsSales && in_array(1, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td 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 ? 'text' : 'hidden'; ?>"/></td>
                                        <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                        <td class="<?php echo ($IsSales && in_array(2, $sales_inv_fields_hide)) || (!$IsSales && in_array(2, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                <?php foreach ($all_uom as $uom): ?>
                                                    <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>
                                        <td class="<?php echo ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input  type="<?php echo $IsSales ? 'text' : 'hidden'; ?>" class="<?php echo $IsSales ? 'form-control' : 'full-width'; ?> l lot_nb hidden" value=""/>
                                        </td>
                                        <td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                            <input  type="<?php echo $IsSales ? 'text' : 'hidden'; ?>" class="<?php echo $IsSales ? 'form-control' : 'full-width'; ?> serial_nb hidden" value=""/>
                                        </td>
                                        <td class=" <?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note"></td>

                                        <td class="<?php echo ($IsSales && in_array(3, $sales_inv_fields_hide)) || (!$IsSales && in_array(3, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control UnitPrice isnumber"  ><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>"><input type="text" class="form-control ttc_price isnumber" <?php echo ($IsSales && !$permissions->hasPermission('change_sales_unit_price')) ? 'disabled' : '' ?>  ></td>
                                        <td class="<?php echo ($IsSales && in_array(4, $sales_inv_fields_hide)) || (!$IsSales && in_array(4, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control Disc" value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(5, $sales_inv_fields_hide)) || (!$IsSales && in_array(5, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control VATPerItem " <?php echo $permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') ? '' : 'disabled' ?> value=""></td>
                                        <td class="<?php echo ($IsSales && in_array(6, $sales_inv_fields_hide)) || (!$IsSales && in_array(6, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control vat_percent " <?php echo $permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') ? '' : 'disabled' ?> ></td>
                                        <td class="<?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_amount isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat')) ? '' : 'disabled' ?>  ></td>
                                        <td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_percent isnumber" <?php echo ($permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') ) ? '' : 'disabled' ?>   ></td>

                                        <td class="<?php echo (($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales || $is_noqty) ? 'hidden' : ''; ?>"><input type="checkbox" name="is_damaged" class="is_damaged"/></td>
                                        <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-6 col-sm-height col-middle  clearfix" style="border-left: 1px solid #eee;padding-left: 6px;border-right: 1px solid #eee;padding-right:0">
                                <h5 class="font-montserrat all-caps small no-margin hint-text bold  <?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(16, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><?php print CommonLanguage::getMessage('payment'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></h5>
                                <div id="InvoicePaymentSetup" class="no-print  <?php echo ($IsSales && in_array(18, $sales_inv_fields_hide)) || (!$IsSales && in_array(16, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>">
                                    <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>
                                            </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" style="width:120px">
                                                                        <input type="text" class="form-control" value="<?php echo ($IsEdit && 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"  value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['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'] : smc_session()['user_accounts']['c_name'] ?>' />
                                                                </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" style="width:120px">
                                                                        <input type="text" class="form-control" value="<?php echo ($IsEdit && 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 && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Account_ID'] : "" ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['P_Name'] : "" ?>' />
                                                                </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 && 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 && 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 && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['value_date'] : '' ?>"/></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" style="width:120px">
                                                                        <input type="text" class="form-control" value="<?php echo ($IsEdit && 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">
                                                                    <input class="credit_account full-width" id="credit_account" name="credit_account" type="hidden"  value="<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['Account_ID'] : "" ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['P_Name'] : "" ?>' />
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3 col-sm-height col-middle clearfix sm-p-b-15">
                                <textarea id="Return_Invoice_Note" name="Return_Invoice_Note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>"><?php echo $IsEdit ? $edit_arr['Main'][$is_exchange ? 'Invoice_Description' : 'Return_Invoice_Note'] : '' ?></textarea>
                                <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 ? $edit_arr['Main']['tax_amount'] : 0 ?>" data-tax="<?php echo $IsEdit ? $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" id="InvoiceDiscountInput" value="<?php echo $IsEdit ? $edit_arr['Main']['Discount'] : 0 ?>"/> %</h5>

                                <div class="disc_div <?php echo $IsEdit ? ($edit_arr['Main']['is_ttc'] == 1 ? 'hidden' : '') : '' ?>">
                                    <h5 class="no-margin"><?php print CommonLanguage::getMessage('discount'); ?><input type="text" class="form-control ignore" id="TotalDiscAmount" value="<?php echo $IsEdit ? $edit_arr['Main']['discount_amount'] : 0 ?>"/></h5>
                                </div>
                                <div class="ttc_disc_div <?php echo $IsEdit ? ($edit_arr['Main']['is_ttc'] == 1 ? '' : 'hidden') : '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('sales_discount_on_invoice')) ? 'disabled' : '' ?> id="TTCInvoiceDiscountInput" value="<?php echo $IsEdit ? $edit_arr['Main']['Discount'] : 0 ?>"/> %</h5>-->
                                    <h5 class="no-margin"><?php print CommonLanguage::getMessage('ttc_discount'); ?><input type="text" class="form-control ignore" id="TTCTotalDiscAmount"  <?php echo ($IsSales && !$permissions->hasPermission('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 class="col-sm-3 text-right bg-menu col-sm-height padding-15" style="text-align:left !important">
                                <div style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseInvoiceTotalDetails">0</span></h1>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('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 class=""><?php echo smc_session()['local_currency_symbol'] ?></span>&nbsp;<span id="Local_Total">0</span></h1>
                                </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:253px;" 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'); ?></span></button>
                            <?php
                        } else {
                            foreach ($templates as $temp) {
                                ?>
                                <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled check_temp_key" data-id="<?php print $temp['template_id']; ?>"  style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print $temp['template_name']; ?></span></button>

                                <?php
                            }
                        }
                        ?>

<!--<button class=" btn btn-danger btn-cons m-b-10 pull-right disabled <?php echo $IsEdit ? 'hidden' : '' ?>" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>-->

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


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

                </div>
            </div>
        </div>
    </div>
</div>
<select required id="Select_UOM" name="Select_UOM"  class="full-width Select_UOM hidden" data-init-plugin="select2">
    <?php foreach ($all_uom as $uom): ?>
        <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
    <?php endforeach; ?>
</select>






<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
            EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email')); ?>,
            RequiredField = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
            customer_vatLang  = <?php echo json_encode(CommonLanguage::getMessage('vat')); ?>,
            Customer_CRLang  = <?php echo json_encode(CommonLanguage::getMessage('cr')); ?>,
            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']) ?>,

            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')); ?>,
            default_vat = <?php echo json_encode(smc_session()['vat_percent']); ?>;
           var disable_merge_same_prod_return=   <?php echo smc_session()['default_setting']['disable_merge_same_prod_return'] == 0 ? 0 : 1; ?>;
    var IsSalesMode = <?php echo $IsSales ? "true" : "false"; ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            is_actual = <?php echo $is_actual ? "true" : "false"; ?>;
            is_noqty = <?php echo json_encode($is_noqty);?>;
    var CurrencyRate = <?php echo json_encode($Extable); ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            is_exchange = <?php echo json_encode($is_exchange); ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            second_currency = <?php echo json_encode(smc_session()['default_setting']['second_currency']); ?>,
            has_sales_cost_perm = <?php echo $has_sales_cost_perm ? '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 ? 'detailed_sold_items' : 'act_detailed_sold_items')); ?>,
            has_edit_prod_perm = <?php echo json_encode($permissions->hasPermission('EditProduct')); ?>,
            display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
            active_expiry_date = <?php echo json_encode(smc_session()['default_setting']['activate_expiry_date']) ?>,
            uom_arr = <?php echo json_encode($all_uom); ?>,
            allow_purchase_vat_edit = <?php echo json_encode(smc_session()['allow_purchase_vat_edit']); ?>,
            has_vat_permission = <?php echo $permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') ? 'true' : 'false'; ?>,
            print_template_settings = <?php echo json_encode(smc_session()['default_setting']['print_template_settings']); ?>,
            activate_lot = <?php echo json_encode(($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 0 : 1); ?>,
            activate_second_vat = <?php echo json_encode(smc_session()['default_setting']['activate_second_vat']); ?>,
            activate_serial = <?php echo json_encode(($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 0 : 1); ?>;


    var TotalInvoice = 0, percent_flag = 0, from_inv = false,
            TotalDiscount = 0, primary_total = 0,
            TotalInvoiceWithoutDiscount = 0, vatVal = 0, totalvat = 0, vat1_total = 0, vat2_total = 0, taxAmount = 0, is_td_total = 0, is_ttc = <?php echo json_encode(smc_session()['class_is_ttc']); ?>;
    var CheckSubmit = true, checkClassFlag = true,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>,
            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' ?>;
    //    var is_actual = 0;
    //    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).closest('tr')
            searchScannedItem(ID, parent);
        }).bind('scannerDetectionError', function (e, data) {
        }).bind('scannerDetectionReceive', function (e, data) {
        });
    });
    $(function () {
        if (IsSalesMode)
            build_select2($("input[name=PIC_ID]"), "xhr/employeeSearch")
        build_select2($(".search_supplier"), (IsSalesMode ? "xhr/customerSearch?auto_salesman=1" : "xhr/supplierSearch") + (IsEditMode ? "?is_edited=" + $(".search_supplier").val() : "?Status_ID=1"))
        build_select2($("#Account_Code"), ("xhr/accIDSearch?type=" + (IsSalesMode ? 'sales' : 'purchase')))
        build_select2($("#Shipping_Code"), ("xhr/accIDSearch?type=" + (IsSalesMode ? 'sales' : 'purchase')))
        build_select2($(".Depot_Loc"), "xhr/depotSearch")
        build_select2($("#cash_account"), ("xhr/accIDSearch?type=cash"))
        build_select2($("#check_account"), ("xhr/accIDSearch?type=check"))
        build_select2($("#credit_account"), ("xhr/accIDSearch?type=credit_card"))
        build_select2($("#pricing_class"), "xhr/PricingClassSearch")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch");
        if (IsSalesMode)
            build_select2($("#customer_branch_id"), "xhr/searchCustomerBranch?customer_id=" + $("#search_supplier").val())
        //        build_select2($("#job_id"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs")

        if (IsEditMode && $("#Invoice_Purchase_ID").attr("data-id") != '' && $("#Invoice_Purchase_ID").attr("data-id") != '0' && $("#Invoice_Purchase_ID").attr("data-id") != undefined) {
            ChangeInvoice();
        }

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

            build_select2($("input[name=PIC_ID]"), "xhr/employeeSearch?customer_id=" + $("#search_supplier").val());
            if (IsSalesMode) {
                $("#customer_branch_id").val('');
                build_select2($("#customer_branch_id"), "xhr/searchCustomerBranch?customer_id=" + $("#search_supplier").val());
            }
        });
        apply_autocomplete($("#inv_truck"), 'xhr/searchInvTruck', function (event, ui, who) {
            who.val(ui.item.truck);
        });
        apply_autocomplete($("#Invoice_Purchase_ID"),
                'xhr/cutomerReturn?is_actual=' + (is_actual ? 1 : 0) + '&is_vendor=' + (!IsSalesMode ? 1 : 0),
                function (event, ui, who) {
                    $("#Invoice_Purchase_ID").val(ui.item.Invoice_ID)
                    $("#Invoice_Purchase_ID").attr("data-id", ui.item.Auto_ID)
                    return false;
                });
        $("#generate").on("click", function (e) {
            //            clearTimeout(UpdateTableTimeout);
            ChangeInvoice();

        });
        $("#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()
                $(".Quantity").trigger('keyup')
            }
            setTimeout("UpdateTable()", 100)
            if (percent_flag == 2) {
                if (is_ttc == 1) {
                    $("#TTCTotalDiscAmount").trigger("keyup")
                } else {
                    $("#TotalDiscAmount").trigger("keyup")
                }
            } else {
                $("#InvoiceDiscountInput").trigger("keyup")
            }
            //            if ($(this).attr("id") == 'TotalDiscAmount') {
            //                percent_flag = 2;
            //             UpdateTable()
        })
        //#public_round_number
        $("#InventoryPurchaseTable").on("change", "input.UnitPrice,input.VATPerItem,input.vat_percent,input.ttc_price,input.Disc", function() {        
            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(".Disc").val(public_round_number(mytr.find(".Disc").val()))

        })


        $("#InventoryPurchaseTable").on("change", "select.UOM_ID", function () {
            var me = $(this).parents("tr"), currency_id = $("#CurrencyDropDown input").val();

            var UOMData = {pid: $(this).parents("tr").attr("data-id"),
                uid: $(this).val(), depot_id: $("#Depot_Loc").val(), class_id: $("#pricing_class").val(), currency_id: currency_id};
            $.ajax({
                url: "InventoryAjax/ReturnProductUOMPriceCon",
                data: UOMData,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        me.attr('data-conv', v1.responseJSON['conversion_amount'])
                        if (IsSalesMode) {
                            me.find("input.UnitPrice").val(v1.responseJSON['Product_Price'])
                            me.find("input.UnitPrice").val(public_round_number(parseFloat(ConvertCurrency2(v1.responseJSON['Product_Price'], v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val()))))
                        }
                        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)));
                        me.find("input.Disc").val(v1.responseJSON['disc'])
                        var qty_hint = AddCommas(public_round_number(parseFloat(v1.responseJSON['qty']))) + " in stock";
                        me.find("input.Quantity").next().text(qty_hint).attr("title", qty_hint)
                        me.attr("data-qty", v1.responseJSON['qty'])
                        setTimeout('UpdateTable()', 100)
                    }
                }
            })


        })




        $("#InvoicePaymentSetup .InputSpinner .btn").on('click', function (e) {
            e.preventDefault();
            var Input = $("input", $(this).parent().parent()), V = parseInt(Input.val())
            Input.val($(this).hasClass("more") ? V + 1 : V == 0 ? 0 : V - 1)
            UpdatePurchaseInvoiceTotalPaid()
        })
        $("#InvoicePaymentSetup").find("input.form-control").on("keyup", function () {
            UpdatePurchaseInvoiceTotalPaid()
        })
        if (IsEditMode)
            $("#InvoicePaymentSetup").find("input.form-control").trigger('keyup')
        $("#pricing_class").on("change", function (e) {
            $.ajax({
                url: "POSAjax/ReturnClassCurrency",
                data: {class_id: $("#pricing_class").val()},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {

                        var data = v1.responseJSON;
                        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']);
                        $("#card_tax").attr("data-tax", (data['tax_amount'] || 0))


                    }
                }
            })

        })
        $("#pricing_class").on("select2-selecting", function (e) {
            var flag = false;

            if ($(this).val() != '' && e.val != $(this).val()) {
                $("#InventoryPurchaseTable tbody tr").each(function () {
                    if ($(this).attr("data-id") != 0 && $(this).attr("data-id") != undefined) {
                        flag = true;
                    }
                })
            }
            if (flag && checkClassFlag) {
                $("#CustomerProceedModal").modal("show")
                //                checkClassFlag = true;
            }
        })
        $(".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);
//                        console.log(Data)
                        for (var i = 0; i < Data.length; i++) {
                            var me = $("#InventoryPurchaseTable tbody tr:eq(" + Data[i]['index'] + ")");

                            //                                        TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ui.item.Price : ConvertCurrency2(ui.item.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()).toXFixed(2))

                            me.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data[i]['Product_Price'] : public_round_number(ConvertCurrency2(Data[i]['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))
                        }
                        UpdateTable()
                    }
                }
            })
            $("#CustomerProceedModal").modal("hide")
        })
        $("#search_supplier").on("change", function () {
            $("#SupplierInfoContent").removeClass('hidden')
            if ($(this).val() == '') {
                $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else
            if ($("#Account_Code").val() == '') {
                $("#ProdLoader > h3").empty().html(account_firstLang)
            } else if ($("#Depot_Loc").val() == '') {
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
            var Data = {
                id: $(this).val(),
                mode: IsSalesMode
            }

            $.ajax({
                url: "InventoryAjax/addPurchaseAjax",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        if (IsSalesMode) {
                            $("#SupplierInfoContent").empty();
                            var Content = "";
                            Content += "<strong><span class='Name hidden' id='Customer_Name' data-id='" + Data[0]['Customer_Name'] + "'>" + Data[0]['Customer_Name'] + "</span></strong>";
                            Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Customer_Phone'] + "</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>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Customer_Address'] + "</span></div>";
                            Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                            Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                            Content += "<div id='Class_ID' style='display:none;'>" + Data[0]['Class_ID'] + "</div>";
                            Content += "<div id='Class_Currency' style='display:none;'>" + Data[0]['Class_Currency'] + "</div>";
                            $("#SupplierInfoContent").append(Content)
                            $("#Supplier_ID-error").remove()
                            $("#Supplier_ID").removeClass("error").val(Data[0]['Customer_ID']);
                            $("#card_tax").attr("data-tax", Data[0]['tax_amount'])
                            percent_flag = 1;
                            if (checkClassFlag)
                                $("#InvoiceDiscountInput").val(Data[0]['Customer_Discount']);
                            $("#pricing_class").val(Data[0]['Class_ID'])
                            $("#pricing_class").attr("data-select-name", Data[0]['Class_Name'])
                            build_select2($("#pricing_class"), "xhr/PricingClassSearch")
                            $("#pricing_class").trigger("change")
                            $("#pricing_class").trigger("select2-selecting")
                            if (has_det_sales_rep_perm)
                                update_open_frame_sold_items();
                        } else {
                            $("#SupplierInfoContent").empty();
                            var Content = "";
                            Content += "<strong><span class='Name hidden' id='Supplier_Name' data-id='" + Data[0]['Supplier_Name'] + "'>" + Data[0]['Supplier_Name'] + "</span></strong>";
                            Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_Phone'] + "</span></div>";
                            Content += "<div><strong>" + customer_vatLang + ": </strong><span class='Phone'>" + Data[0]['supplier_vat'] + "</span></div>";
                            Content += "<div><strong>" + Customer_CRLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_CR'] + "</span></div>";
                            Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Supplier_Address'] + "</span></div>";
                            Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                            Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                            $("#SupplierInfoContent").html(Content)
                            $("#Supplier_ID-error").remove()
                            $("#Supplier_ID").removeClass("error").val(Data[0]['Supplier_ID']);

                        }
                    }
                }
            })

        })
        $("#CurrencyDropDown .dropdown-menu > li").on("click", function () {
            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")
            cur_id = $(this).attr("value");
            $("#InventoryPurchaseTable tbody tr").each(function () {
                if ($(this).attr("data-id") != '' && $(this).attr("data-id") != undefined) {

                    var last_cost = ConvertCurrency2(parseFloat($(this).attr("data-last-cost") || 0), local_currency, cur_id);
                    if (has_sales_cost_perm)
                        $(this).find("input.UnitPrice").next().text("last cost: " + (!last_cost ? "0" : public_round_number(AddCommas(parseFloat(last_cost)))));
                }
            })
            setTimeout(function () {
                UpdateTable()
            }, 300)
        })

        $("#PrintBtn").on("click", function () {
            if (print_template_settings == 0 || !IsSalesMode || is_exchange) {
                // var myurl = IsSalesMode ? "Inventory/ViewReturnDebit/" + Invoice_ID + "/" + $("#Supplier_ID").val() : "Inventory/ViewReturnDebit/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
                var myurl = is_exchange ? (inv_type == 'return' ? "Inventory/ViewReturnDebit/" + (IsSalesMode ? "" : "vendor/") + Invoice_ID : (inv_type == 'exchange' ? "Inventory/pos_view_exchange/" + Invoice_ID : "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val())) : "Inventory/ViewReturnDebit/" + (IsSalesMode ? "" : "vendor/") + Invoice_ID;
                printExternal(myurl)
            } else {
                $("#choose_template_modal").modal("show")
            }
        });

//        $("#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 = is_exchange ? (inv_type == 'return' ? "Inventory/ViewReturnDebit/" + (IsSalesMode ? "" : "vendor/") + Invoice_ID + '&template_id=' + $(this).attr("data-id") : (inv_type == 'exchange' ? "Inventory/pos_view_exchange/" + Invoice_ID : "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val())) + '&template_id=' + $(this).attr("data-id") : "Inventory/ViewReturnDebit/" + (IsSalesMode ? "" : "vendor/") + Invoice_ID + '&template_id=' + $(this).attr("data-id");
            printExternal(myurl)



//            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')
        })




        $("#Account_Code,#Depot_Loc").on("change", function () {
            var accName = $.trim($("#s2id_Account_Code").text());

            $('#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() == '') {
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }

            if ($(this).attr("id") == 'Depot_Loc') {
                var item_arr = {items: [], depot_id: $("#Depot_Loc").val()}
                $("#InventoryPurchaseTable tbody tr").each(function (e) {
                    if ($(this).attr("data-id") != 0) {
                        item_arr.items.push($(this).attr("data-id"))
                    }
                })
                $.ajax({
                    url: "InventoryAjax/ReturnQtyPerDepot",
                    data: item_arr,
                    dataType: 'json',
                    complete: function (v1, v2) {
                        if (v2 == "success") {
                            var Data = (v1.responseJSON);
                            $.each(Data, function (index, value) {
                                var me = $("#InventoryPurchaseTable tbody tr[data-id='" + value['Product_ID'] + "']"),
                                        tr_conv = parseFloat(me.attr("data-conv"));
                                var qty_hint = AddCommas(public_round_number(parseFloat(value['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", (value['qty'] / tr_conv))
                            })
                            UpdateSubmitButtonStatus()
                            //                            for (var i = 0; i < Data.length; i++) {
                            //                                var me = $("#InventoryPurchaseTable tbody tr[data-id='" + Data[i]['Product_ID'] + "']"),
                            //                                        tr_conv = parseFloat(me.attr("data-conv"));
                            //                                me.find(".Hint").text(AddCommas(parseFloat(Data[i]['qty'] / tr_conv).toXFixed(3)) + " in stock")
                            //                            }
                        }
                    }
                })
            }

        })


        if (!$("#InventoryPurchaseTable").hasClass('hideme')) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                EnableAutoComplete($(".AutoComplete.CODE", $(this)));
                EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
                if (IsSalesMode) {
                    if ($(this).attr('data-expiry') == 1) {
                        $("input.expiry_date", $(this)).datepicker({autoclose: true});
                    }
                } else {
                    if ($(this).attr('data-expiry') == 1)
                        build_select2($("input.expiry_date", $(this)), function () {
                            return 'xhr/get_product_expiry?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Loc").val();
                        }, '', 'expiry_width');
                    if ($(this).attr('data-is-lot') == 1 && activate_lot == 1)
                        build_select2($("input.lot_nb", $(this)), function () {
                            return 'xhr/get_product_lot?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Loc").val();
                        }, '', 'expiry_width');
                    if ($(this).attr('data-is-serial') == 1 && activate_serial == 1)
                        build_select2($("input.serial_nb", $(this)), function () {
                            return 'xhr/get_product_serial?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Loc").val();
                        }, '', 'expiry_width');
                }
                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");
                //            $(".expiry_date", $(this)).datepicker({autoclose: true});
            });
        } else {
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.CODE"));
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.ProductName"));
            //        $(".expiry_date").datepicker({autoclose: true});

        }

        $("#PurchaseInvoiceDueDate,#PurchaseInvoiceDate,.check_due_date,.value_date").datepicker({autoclose: true}).on("changeDate", function (e) {
            $(this).keyup();
        })
        $("#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("span.Total").attr("myval")) || 0;
            if ($(this).hasClass("vat_percent")) {
                var cur_val = public_round_number(cur_tr_total * cur_tr_vat / 100);
                $(this).parents("tr").find(".VATPerItem").val(cur_val ? cur_val : '')
                setTimeout("UpdateTable()", 100);
            } else {
                var cur_val = public_round_number(cur_tr_vat / cur_tr_total * 100);
                $(this).parents("tr").find(".vat_percent").val(cur_val ? cur_val : '')
                $(this).parents("tr").find(".vat_percent").trigger("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 = public_round_number((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 = public_round_number(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,.UnitPrice,.Disc", "blur keydown", function (e) {
            is_td_total = 0;
            var me = $(this), TR = me.parents("tr");
            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 (IsSalesMode) {
                if (me.hasClass("Quantity")) {
                    if (parseFloat(me.val()) > parseFloat(TR.attr('data-qty'))) {
                        me.addClass("wrong")

                    }

                }
            }
            $("#InvoiceDiscountInput").trigger("keyup")
        });
        if (IsEditMode)
            UpdateTable();  //$(".Quantity").trigger('keydown')
        $("#InvoiceDiscountInput").on("keyup", function () {
            percent_flag = 1;
            $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($(this).val()) / 100) || 0)
            $("#TTCTotalDiscAmount").val(primary_total * (parseFloat($(this).val()) / 100) || 0)
            setTimeout("UpdateTable()", 100)
        })
        //        $("#TTCInvoiceDiscountInput").on(" keyup", function () {
        ////             var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        ////            console.log(roundX_number(TotalInvoice+totalvat))
        //            var mytotal = primary_total;
        //            console.log(mytotal)
        //            check_discount($(this), max_discount)
        //            $("#TTCTotalDiscAmount").val(mytotal * (parseFloat($(this).val()) / 100) || 0)
        //            $("#InvoiceDiscountInput").val($(this).val()).trigger("keyup")
        ////            setTimeout("UpdateTable()", 100)
        //            //            }
        //        })
        $("#TTCTotalDiscAmount").on("keyup", function () {
            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("blur keyup", function () {
            if ($(this).attr("id") == 'TotalDiscAmount') {
                $("#InvoiceDiscountInput").val((parseFloat($(this).val()) / TotalInvoice * 100) || 0)
            }
            setTimeout("UpdateTable()", 100)
        })
        if (IsEditMode) {
            setTimeout(function () {
                $("#InvoiceDiscountInput").trigger("keyup")
            }, 500)

        }
        $("#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 && !from_inv) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                ClonedRow.find("input").val("")
                ClonedRow.attr("data-conv", "1")
                ClonedRow.attr("data-id", "0")
                ClonedRow.attr("data-expiry", "0")
                ClonedRow.attr("data-is-lot", "0")
                ClonedRow.attr("data-is-serial", "0")
                ClonedRow.attr("data-last-price", "0")
                ClonedRow.attr("data-last-cost", "0")
                ClonedRow.attr("data-is-service", "0")
                Parent.append(ClonedRow);
                EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
                $(".expiry_date,input.lot_nb,input.serial_nb", ClonedRow).addClass('hidden')
                $("input.is_damaged", ClonedRow).prop('checked', false)
                if (IsSalesMode) {
                    $("input.expiry_date", ClonedRow).datepicker({autoclose: true});
                } else {
                    $("input.expiry_date,input.lot_nb,input.serial_nb", ClonedRow).attr('data-select-name', '').val('')
                    build_select2(ClonedRow.find("input.expiry_date"), function () {
                        return 'xhr/get_product_expiry?product_id=' + $(".AutoComplete.ProductName", this.parents('tr')).attr('data-id') + '&depot=' + $("#Depot_Loc").val();
                    });
                    build_select2(ClonedRow.find("input.lot_nb"), function () {
                        return 'xhr/get_product_lot?product_id=' + $(".AutoComplete.ProductName", this.parents('tr')).attr('data-id') + '&depot=' + $("#Depot_Loc").val();
                    });
                    build_select2(ClonedRow.find("input.serial_nb"), function () {
                        return 'xhr/get_product_serial?product_id=' + $(".AutoComplete.ProductName", this.parents('tr')).attr('data-id') + '&depot=' + $("#Depot_Loc").val();
                    });
                }
                ClonedRow.removeAttr("data-prod-status")
                $(".Hint,.Total", ClonedRow).html("")
                $("input", ClonedRow).removeClass("wrong")
                $(".select2-container", ClonedRow).empty().remove()
                $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
                UpdateTable()
            }
        })
        $("#CurrencyDropDown li").click(function () {
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            cur_id = $(this).attr("value");

            $("#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);
                    var unit_price_hint_text = '';
                    if (has_sales_cost_perm)
                        unit_price_hint_text += (unit_price_hint_text == '' ? '' : ' | ') + "Cost: " + (!last_cost ? "0" : AddCommas(parseFloat(public_round_number(last_cost))));
                    $(this).find("input.UnitPrice").next().text(unit_price_hint_text).attr('title', unit_price_hint_text);
                }
            })
            setTimeout("UpdateSubmitButtonStatus()", 100)
        })
        var Def = $("#CurrencyDropDown li").filter(function () {
            return $(this).attr("value") == $("#CurrencyDropDown input").val()
        })
        if (Def.length > 0) {
            $(".CurrencyIndicator").html(Def.attr("MySymbol"))
            $("> button > span", $("#CurrencyDropDown")).html(Def.text())
        }
        $("#InvoiceForm").validate({
            ignore: ".ignore",
            rules: {
                PurchaseInvoiceDate: {required: true, date: true},
                PurchaseInvoiceDueDate: {date: true}
            }
        })
        $("#InvoiceSubmitButton").on("click", ApplyPostMethod);
        UpdateSubmitButtonStatus()
        $("#InventoryPurchaseTable").on("input", ".ttc_price ", function () {
            var myval = parseFloat($(this).val()) || 0,
                    mytr = $(this).parents("tr"),
                    //                    myqty = parseFloat(mytr.find(".Quantity").val()) || 0,
                    vat_percent = parseFloat(mytr.find(".vat_percent").val()) || 0,
                    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")
            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("input", ".ttc_price ", function () {
        //            var myval = parseFloat($(this).val()) || 0,
        //                    mytr = $(this).parents("tr"),
        //                    myqty = parseFloat(mytr.find(".Quantity").val()) || 0,
        //                    vat_percent = parseFloat(mytr.find(".vat_percent").val()) || 0,
        //                    vat_amount = myval * (vat_percent / 100) / (1 + (vat_percent / 100)),
        //                    amt_no_vat = myval - vat_amount,
        //                    disc_percent = parseFloat(mytr.find(".Disc").val()) || 0,
        //                    unit_amt = amt_no_vat * (1 + (disc_percent / 100));
        //            mytr.find(".VATPerItem").val(vat_amount.toXFixed(3))
        //            $(this).attr("MyVal", myval)
        //            is_td_total = 1;
        //            mytr.find(".UnitPrice").val(unit_amt)//.trigger("keydown")
        //            UpdateTable()
        //        })
    })
    function searchScannedItem(barcode, TR) {
        var get_parameters = 'Status_ID=1&barcode=' + barcode + '&depot_id=' + $('#Depot_Loc').val();
        if (IsSalesMode) {
            get_parameters += '&type=1&class_id=' + $("#pricing_class").val() + '&customer_id=' + $("#search_supplier").val();
        } else {
            get_parameters += '&type=2';
        }
        $.ajax({
            url: "POSAjax/searchBarcodeforPOS?" + get_parameters,
            method: 'GET',
            dataType: 'json',
            complete: function (v1, v2) {
                var Data = v1.responseJSON;
                if ($.type(Data) === "object") {
                    $("select[name=UOM_ID]", TR).empty();

                    TR.attr("data-id", Data.ID)
                    TR.attr("data-vat", (is_actual ? 0 : Data.VAT))
                    TR.attr("data-qty", Data.stock_qty)
                    TR.attr("data-expiry", Data.is_expiry)
                    TR.attr("data-last-cost", Data.LAST_COST)
                    TR.attr("data-is-service", Data.is_service)
                    TR.attr("data-is-lot", Data.is_lot)
                    TR.attr("data-is-serial", Data.is_serial)
                    TR.find("input.CODE").val(Data.Bar_Code)

                    TR.find("input.ProductName").val(Data.Name)
                    TR.find("input.vat_percent").val((Data.VAT == 1 && !is_actual) ? Data.vat_percent : 0)
                    TR.find("input.VATPerItem,input.vat2_amount").val('0')
                    TR.find("input.vat2_percent").val((Data.VAT == 1 && !is_actual && is_sec_vat) ? Data.vat2_percent : 0)

                    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)
                    if (display_shelf_locations == 1) {
                        TR.find("input.ProductName").next().text(Data.loc);
                    }

                    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();
                    if (IsSalesMode) {
                        TR.attr("data-tax", Data.is_tax)


                        TR.find("input.Disc").val(Data.disc)
                        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")
                        }
                        TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data.Price : public_round_number(ConvertCurrency2(Data.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val())))
                        if (true) {
                            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()))))));
                        }

                        if (Data.is_expiry == 0)
                            TR.find("input.expiry_date").addClass("hidden")
                        else {
                            TR.find("input.expiry_date").removeClass("hidden")
                            TR.find("input.expiry_date").datepicker({autoclose: true});
                        }

                    } else {
                        if (Data.VAT == 0 || is_actual) {
                            TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                        } else {
                            TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                        }
                        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()))))));
                        }
                        if (Data.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('')
                            build_select2(TR.find("input.expiry_date"), function () {
                                return 'xhr/get_product_expiry?product_id=' + Data.ID + '&depot=' + $("#Depot_Loc").val();
                            }, '', 'expiry_width');
                        }
                        if (Data.is_lot == 1)
                            build_select2(TR.find("input.lot_nb"), function () {
                                return 'xhr/get_product_lot?product_id=' + Data.ID + '&depot=' + $("#Depot_Loc").val();
                            }, '', 'expiry_width');
                        if (Data.is_serial == 1)
                            build_select2(TR.find("input.serial_nb"), function () {
                                return 'xhr/get_product_serial?product_id=' + Data.ID + '&depot=' + $("#Depot_Loc").val();
                            }, '', 'expiry_width');

                    }
                    UpdateTable()
                    return false;
                }
            }
        })
    }
    function UpdateTable() {
        var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        vatVal = 0, totalvat = 0, taxAmount = 0, vat1_total = 0, vat2_total = 0;
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0, card_tax = 0, primary_total = 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;
//                    console.log(Net_Total)
            var tr_vat_percent = (who.attr('data-vat') == 1) ? (parseFloat(who.find("input.vat_percent").val()) || 0) : 0,
                    tr_vat2_percent = ((who.attr('data-vat') == 1 && is_sec_vat)) ? (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;
//            console.log(TotalInvoice)
            primary_total += parseFloat(who.find('.ttc_price').val() || 0) * Qty * (1 - Discount / 100);
        });
//               console.log(TotalInvoice+'===='+shipping)

        $("#InventoryPurchaseTable tbody tr").each(function () {
            UpdateTotalForRow($(this))
        })
        if (IsSalesMode) {
            $("#card_tax").val(public_round_number(parseFloat(card_tax)))
        }
        console.log(percent_flag)
        if (percent_flag == 1) {
            $("#TotalDiscAmount").val(public_round_number(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val())) / 100) || 0)
            $("#TTCTotalDiscAmount").val(public_round_number(primary_total * (parseFloat($("#InvoiceDiscountInput").val())) / 100) || 0)
        }
        if (percent_flag == 2) {
            //            console.log(TotalInvoice)
            if (is_ttc == 1) {
                $("#InvoiceDiscountInput").val(public_round_number(parseFloat($("#TTCTotalDiscAmount").val()) / primary_total * 100) || 0)
                $("#TotalDiscAmount").val(public_round_number(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100)) || 0)

            } else {
                $("#InvoiceDiscountInput").val(public_round_number(parseFloat($("#TotalDiscAmount").val()) / TotalInvoice * 100) || 0)
                $("#TTCTotalDiscAmount").val(public_round_number(primary_total * (parseFloat($("#InvoiceDiscountInput").val()) / 100)) || 0)

            }
            if (parseFloat($("#InvoiceDiscountInput").val()) > 100) {
                $("#TotalDiscAmount").val('').trigger("keyup")
                $("#DiscountProceedModal").modal("show")
            }

        }

        ////            $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
        //            $("#InvoiceDiscountInput").trigger("keyup")
        //        } else {
        //            $("#TotalDiscAmount").trigger("keyup")
        //        }
        //        console.log(TotalInvoice)
        //        $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
        //        $("#InvoiceDiscountInput").trigger("")
        //        $("#DiscountVal").html(AddCommas((TotalInvoiceWithoutDiscount - TotalInvoice).toXFixed(3)))
        //        console.log(TotalInvoice)
        var totalDiscountValue = parseFloat($("#TotalDiscAmount").val()) || 0;
        var TTCtotalDiscountValue = parseFloat($("#TTCTotalDiscAmount").val()) || 0;
        //        var InvoiceDiscountInput = parseFloat($("#InvoiceDiscountInput").val()) || 0;
        var TotalInvoiceDisounted = TotalInvoice - totalDiscountValue;
        setTimeout("UpdateSubmitButtonStatus()", 100)
        var final_total = primary_total - (is_ttc ? TTCtotalDiscountValue : totalDiscountValue) + shipping + card_tax;
        console.log(final_total)
        $("#PurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted": public_round_number(TotalInvoice + shipping), "MyValueDiscounted": public_round_number(final_total)}).text(AddCommas(public_round_number(final_total)))
        if ($("#current_rate").val() != '')
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(final_total * $("#current_rate").val()))))
        else
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(ConvertCurrency2(final_total, $("#CurrencyDropDown input").val(), local_currency)))))

    }

    function EnableAutoComplete(who) {
        if (IsSalesMode) {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function (request, response) {
                        var classID = $("#pricing_class").val(),
                                depot_id = $("#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" : "2") + "&customer_id=" + (customer_id)+ "&is_sales=" + (IsSalesMode ? 1 : 0) + "&ClassID=" + classID + '&depot_id=' + depot_id + '&type=1' + 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-tax", ui.item.is_tax)
                        TR.attr("data-expiry", ui.item.is_expiry)
                        TR.attr("data-is-lot", ui.item.is_lot)
                        TR.attr("data-is-serial", ui.item.is_serial)
                        TR.attr("data-last-cost", ui.item.LAST_COST)
                        TR.attr("data-conv", ui.item.uom_conv)
                        TR.attr("data-qty", ui.item.Quantity)
                        TR.attr("data-is-service", ui.item.is_service)
                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.find("input.ProductName").val(ui.item.Name)
                        TR.find("input.vat_percent").val((ui.item.VAT == 1 && !is_actual) ? ui.item.vat_percent : 0)
                        TR.find("input.VATPerItem,input.vat2_amount").val('0')
                        TR.find("input.vat2_percent").val((ui.item.VAT == 1 && !is_actual && is_sec_vat) ? ui.item.vat2_percent : 0)

                        TR.find("input.Disc").val(ui.item.disc)
                        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")
                        }

                        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())))
                        //                        if (has_sales_cost_perm) {
                        //                            TR.find("input.UnitPrice").next().text("last cost: " + (!ui.item.LAST_COST ? "0" : AddCommas(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val())).toXFixed(3))));
                        //                        }

                        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)


                        $("select[name=UOM_ID]", TR).empty()
                        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)

                        if (display_shelf_locations == 1) {
                            TR.find("input.ProductName").next().text(ui.item.loc);
                        }
                        if (ui.item.is_expiry == 0) {
                            TR.find("input.expiry_date").val('').attr("data-select-name", "")
                            TR.find("input.expiry_date").addClass("hidden")
                        } else {
                            TR.find("input.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");
                        else {
                            TR.find(".lot_nb").val('').attr("data-select-name", "")
                            TR.find(".lot_nb").addClass("hidden");
                        }
                        if (ui.item.is_serial == 1 && activate_serial == 1)
                            TR.find(".serial_nb").removeClass("hidden");
                        else {
                            TR.find(".serial_nb").val('').attr("data-select-name", "")
                            TR.find(".serial_nb").addClass("hidden");
                        }

                        var units_arr = ui.item.Product_UOM.split("/");
                        for (var i = 0; i < units_arr.length; i++) {
                            $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                        }
                        TR.find("select[name=UOM_ID]").select2();
                        UpdateTable()
                        return false;
                    }
                }).focus(function () {
                    $(this).autocomplete("search", $(this).val());
                }).autocomplete("instance")._resizeMenu = function (ul, items) {
                    this.menu.element.outerWidth((who.width() * (this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
                }
                who.autocomplete("instance")._renderItem = function (ul, item) {
                    var MyType = this.element.hasClass("CODE") ? (item.Bar_Code) : (item.Cat_Name + item.Name + ' - ' + item.Bar_Code);
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }

        } else {

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

                who.autocomplete({
                    source: function (request, response) {
                        var depot_id = $("#Depot_Loc").val(),
                                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" : "2") + '&is_purchase=' + (IsSalesMode ? 0 : 1) + '&depot_id=' + depot_id + '&type=2' + 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-expiry", ui.item.is_expiry)
                        TR.attr("data-is-lot", ui.item.is_lot)
                        TR.attr("data-is-serial", ui.item.is_serial)
                        TR.attr("data-last-cost", ui.item.LAST_COST)
                        TR.attr("data-conv", ui.item.uom_conv)
                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.attr("data-is-service", ui.item.is_service)
                        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");
                        }
                        TR.find("input.ProductName").val(ui.item.Name)
                        $("select[name=UOM_ID]", TR).empty();
                        //                        if (has_purchase_cost_perm) {
                        //                            TR.find("input.UnitPrice").next().text("last cost: " + (!ui.item.LAST_COST ? "0" : AddCommas(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val())).toXFixed(3))));
                        //                        }

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

                        if (display_shelf_locations == 1) {
                            TR.find("input.ProductName").next().text(ui.item.loc);
                        }
                        TR.find("input.expiry_date,input.lot_nb,input.serial_nb").attr("data-select-name", "")

                        if (ui.item.is_expiry == 0) {
                            TR.find("input.expiry_date").val('').attr("data-select-name", "")
                            TR.find("input.expiry_date").addClass("hidden")
                        } else {
                            TR.find("input.expiry_date").removeClass("hidden")
                            build_select2(TR.find("input.expiry_date"), function () {
                                return 'xhr/get_product_expiry?product_id=' + ui.item.ID + '&depot=' + $("#Depot_Loc").val();
                            }, '', 'expiry_width');
                        }
                        if (ui.item.is_lot == 1 && activate_lot == 1) {
                            TR.find(".lot_nb").removeClass("hidden");
                            build_select2(TR.find("input.lot_nb"), function () {
                                return 'xhr/get_product_lot?product_id=' + ui.item.ID + '&depot=' + $("#Depot_Loc").val();
                            }, '', 'expiry_width');
                        } else {
                            TR.find("input.lot_nb").val('').attr("data-select-name", "")
                            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"), function () {
                                return 'xhr/get_product_serial?product_id=' + ui.item.ID + '&depot=' + $("#Depot_Loc").val();
                            }, '', 'expiry_width');
                        } else {
                            TR.find("input.serial_nb").val('').attr("data-select-name", "")
                            TR.find(".serial_nb").addClass("hidden");
                        }
                        //                        TR.find("input.Quantity")/*.focus()*/.prev().text((ui.item.Quantity) + " in stock");
                        var units_arr = ui.item.Product_UOM.split("/");
                        for (var i = 0; i < units_arr.length; i++) {
                            $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                        }
                        $("select[name=UOM_ID]", TR).select2()
                        UpdateTable()
                        return false;
                    }
                }).focus(function () {
                    $(this).autocomplete("search", $(this).val());
                }).autocomplete("instance")._resizeMenu = function (ul, items) {

                    this.menu.element.outerWidth((who.width() * (this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
                }
                who.autocomplete("instance")._renderItem = function (ul, item) {

                    var MyType = this.element.hasClass("CODE") ? (item.Bar_Code) : (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() {
//        console.log('hi guys')
        //        $("#InvoiceSubmitButton").attr("disabled", "disabled")
        $("#PurchaseSuccess").attr("class", "hidden");
        var validator = $("#InvoiceForm").validate(),
        errors = validator.errorList;
        console.log(validator);
 
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                    Data = {
                        Cash_Amount: $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
                        Cash_Account: $("#cash_account").val(),
                        Check_Amount: $("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
                        Check_Account: $("#check_account").val(),
                        Card_Amount: $("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
                        Card_Account: $("#credit_account").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(),
                        TotalTax: $("#PurchaseTaxableAmount").html().replace(/,/g, ""),
                        Account_Code: $('#Account_Code').val(),
                        Invoice_VAT: $("#InvoiceVAT").html().replace(/,/g, ""),
                        vat1_total: $("#InvoiceVAT").attr("vat1_total"),
                        vat2_total: $("#InvoiceVAT").attr("vat2_total"),
                        CurrencySymbole: $(".CurrencyIndicator").html(),
                        Is_Customer_Invoice: IsSalesMode ? 1 : 0,
                        Return_Invoice_Date: $("#PurchaseInvoiceDate").val(),
                        Return_Invoice_Total: $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted"),
                        Person_ID: $("#Supplier_ID").val(),
                        Person_Account: $("#Finance_Account").attr("data-id"),
                        Currency_ID: $("#CurrencyDropDown input").val(),
                        Return_Invoice_Note: $("#Return_Invoice_Note").val() ? $("#Return_Invoice_Note").val() : '',
                        discount_amount: $("#TotalDiscAmount").val(),
                        Discount_Amount: $("#TotalDiscAmount").val(), //for exchange
                        discount_percent: $("#InvoiceDiscountInput").val(),
                        Invoice_Discount: $("#InvoiceDiscountInput").val(), //for exchange
                        Invoice_Purchase_ID: $("#Invoice_Purchase_ID").attr('data-id'),
                        Is_Actual: is_actual ? 1 : 0,
                        Invoice_Currency_Rate: $("#current_rate").val(),
                        second_currency_rate: $("#second_currency_rate").val(),
                        job_id: $("#job_id").val(),
                        project_id: $("#project_id").val(),
                        tax_amount: $("#card_tax").val() || 0,
                        customer_branch_id: $("#customer_branch_id").val(),
                        customer_branch_name: $("#customer_branch_id").val() ? $("#customer_branch_id").select2('data').text : '',
                        unique_id: unique_id,
                        is_noqty: is_noqty,
                        Products: []

                    };


            if (IsSalesMode) {
                Data.Customer_ID = $("#Supplier_ID").val();
                Data.Customer_Account = $("#Finance_Account").attr("data-id")
                Data.Customer_Name = $("#Customer_Name").attr("data-id")
                Data.Invoice_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
                Data.Invoice_Paid_Amount = $("#AdvanceValue").val();
                Data.Class_ID = $("#pricing_class").val();
                Data.Sales_ID = $("input[name=PIC_ID]").val();
                Data.products = [];
            } else {
                Data.Supplier_ID = $("#Supplier_ID").val();
                Data.Supplier_Account = $("#Finance_Account").attr("data-id")
                Data.Supplier_Name = IsEditMode ? $("#Customer_Name").attr("data-id") : $("#Supplier_Name").attr("data-id")
                Data.Purchase_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
                Data.Purchase_Paid_Amount = $("#AdvanceValue").val();
            }
            if (IsEditMode) {
                Data.Return_ID = ID_Edit;
                Data.Old_Depot_ID = $("#Depot_Loc").attr('data-old')
                Data.ex_id = ID_Edit;
            }

            //            if(!CheckClassFlag)
            var is_negative_value, validate_multi = true;
            $("#InventoryPurchaseTable tbody tr").each(function (e) {
                var me = $(this);
                //                if (e < $(this).parent().children().length - 1) {
                if (me.find(".Quantity").val() != '' && me.find(".ProductName").val() != '' && me.find('.UnitPrice').val() != '') {
                    var tr_vat = (parseFloat(me.find("input.VATPerItem ").val()) || 0) + (parseFloat(me.find("input.vat2_amount").val()) || 0)
                    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(),
                        Return_Product_Quantity: me.find(".Quantity").val(),
                        Unit_Cost: me.find(".UnitPrice").val(),
                        Item_Discount: me.find(".Disc").val(),
                        vat_percent: me.find("input.vat_percent").val(),
                        vat_val: me.find("input.VATPerItem ").val(),
                        vat2_percent: me.find("input.vat2_percent ").val() || 0,
                        vat2_amount: me.find("input.vat2_amount").val() || 0,
                        Return_Product_Total: me.find(".TotalTD > .Total").attr("myval"),
                        product_description: me.find(".item_note").val(),
                        expiry_date: me.find("input.expiry_date").val(),
                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        is_damaged: $("input.is_damaged", me).is(":checked") ? 1 : 0,
                        // used for exchange 
                        Product_Quantity: me.find(".Quantity").val(),
                        vat_amount: me.find("input.VATPerItem ").val(),
                        Product_Disc: me.find(".Disc").val(),
                        Discount_Amount: ((parseFloat(me.find(".Disc").val()) || 0) / 100) * (parseFloat(me.find(".UnitPrice").val()) || 0) * (parseFloat(me.find(".Quantity").val()) || 0),
                        disc_amt_noqty: ((parseFloat(me.find(".Disc").val()) || 0) / 100) * (parseFloat(me.find(".UnitPrice").val())),
                        unit_price: me.find(".UnitPrice").val(),
                        Item_Price: (parseFloat(me.find(".UnitPrice").val()) || 0),
                        Total_Price: (parseFloat(me.find(".TotalTD > .Total").attr("myval")) || 0) + tr_vat,
                        Net_Price: me.find(".UnitPrice").val(),
                        total_tax: 0,
                        Added_Amount: 0,
                        is_transfer: 0,
                    });


                    me.find(".Quantity,.UnitPrice").each(function () {
                        var current_value = parseFloat($(this).val());
                        if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && ((current_value < 0 && !is_exchange && $(this).hasClass("Quantity")) || (current_value < 0 && $(this).hasClass("UnitPrice"))))) {
                            $(this).addClass("wrong")
                            CheckSubmit = false;
                            IsValidated = false;
                        } else {
                            $(this).removeClass("wrong")
                        }
                    })

                    if (active_expiry_date == 1 && me.attr("data-expiry") == 1 && me.find("input.expiry_date").val() == '') {
                        me.find(".expiry_date").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_lot == 1 && me.attr("data-is-lot") == 1 && me.find("input.lot_nb").val() == '') {
                        me.find(".lot_nb").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
                    if (activate_serial == 1 && me.attr("data-is-serial") == 1 && me.find("input.serial_nb").val() == '') {
                        me.find(".serial_nb").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }

                    if ((parseFloat($("input.Quantity ", me).val()) < 0 && !is_exchange) ||
                            parseFloat($("input.UnitPrice ", me).val()) < 0 ||
                            parseFloat($("input.Disc ", me).val()) < 0 ||
                            parseFloat($("input.vat_percent ", me).val()) < 0 ||
                            ($.trim($('input.Disc', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.Disc', me).val() != '' && $('input.Disc', me).val() != 0) ||
                            ($.trim($('input.vat_percent', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.vat_percent', me).val() != '' && $('input.vat_percent', me).val() != 0)) {
                        is_negative_value = true;
                    }
                    if(disable_merge_same_prod_return == 0){
                        if ($("#InventoryPurchaseTable tbody tr[data-id=" + me.attr("data-id") + "] select.UOM_ID option:selected[value=" + me.find("select.UOM_ID").val() + "]").length > 1)
                            validate_multi = false;
                    }


                }
            });
            if (!IsValidated) {
                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('Required_Fields'); ?>');
                $("#InvoiceSubmitButton").removeAttr("disabled")
                $(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'); ?>');
                $("#InvoiceSubmitButton").removeAttr("disabled")
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_negative_value) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('negative_value'); ?>');
                $("#InvoiceSubmitButton").removeAttr("disabled")
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (!validate_multi) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('merge_same_prod_uom'); ?>');
                $("#InvoiceSubmitButton").removeAttr("disabled")
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
//                        return false;
            $("#PurchaseDisabler").show();
            $.ajax({
                url: is_exchange ? (IsEditMode ? "InventoryAjax/edit_exchange" : "InventoryAjax/add_exchange") : (IsEditMode ? "InventoryAjax/editReturnNoInvoice" : "InventoryAjax/ReturnNoInvoice"),
                method: "POST",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    console.log(v1);
                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            console.log(v1.responseJSON);

                            Invoice_ID = v1.responseJSON[1];
                            if (is_exchange)
                                inv_type = v1.responseJSON[2];
                            else
                                inv_type = 'return';
                            $("#PrintBtn,.check_temp_key").removeClass("disabled")
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                            $(".inv_div").addClass("hidden")
                            //                            $("#InvoiceSubmitButton").attr("disabled", "disabled")
                            CheckSubmit = true;
                            $("#InvoiceSubmitButton").attr("disabled", "disabled")
                        } else {

                            if (v1.responseJSON[0] == 'expiry_error') {
                                $.each(v1.responseJSON[1], function (indx, row) {
                                    $("#InventoryPurchaseTable tbody tr[data-id=" + row['Product_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'] + "] 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'] + "] 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'] + "] 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])
                                $("#InvoiceSubmitButton").removeAttr("disabled")
                                CheckSubmit = false;
                            }
                        }
                    } else {
                        console.log(v1);

                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        $("#InvoiceSubmitButton").removeAttr("disabled")
                        CheckSubmit = false;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#PurchaseDisabler").hide();
                }
            })
        } else {
            $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
            $(document.body).animate({scrollTop: 0}, 800)
        }
    }
    function UpdateTotalForRow(who) {

        var Single_Price = parseFloat(who.find(".UnitPrice").val()) || 0,
                Qty = parseFloat(who.find(".Quantity").val()) || 0,
                uom_conv = parseFloat(who.attr('data-conv')),
                Total = Single_Price * Qty,
                //                Total = IsSalesMode ? ConvertCurrency2(Single_Price * Qty * uom_conv, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()) : Single_Price * Qty * uom_conv,
                Discount = parseFloat(who.find(".Disc").val()) || 0,
                Net_Total = (Total * (1 - Discount / 100)) || 0,
                net_total_with_invdisc = Net_Total * (1 - parseFloat($("#InvoiceDiscountInput").val() || 0) / 100);

        if (IsSalesMode) {
            var ctax = who.attr("data-tax") == 1 ? Qty * parseFloat($("#card_tax").attr("data-tax") || 0) : 0;
            card_tax += ctax
            //            console.log(Qty +'*'+ parseFloat($("#card_tax").attr("data-tax")))
        }
        TotalInvoiceWithoutDiscount += Total;
        TotalDiscount += Discount;
//        TotalInvoice += Net_Total;
        //        who.find(".Total").attr("MyVal", Net_Total.toXFixed(3)).text(AddCommas(Net_Total.toXFixed(3)))
        who.attr('Unit_Price', Single_Price)
        //        var TRvalue = who.attr('data-vat') == 1 ? (parseFloat($(".TotalTD .Total", who).attr('myval'))) : 0,
        //                tr_vat_percent = who.attr('data-vat') == 1 ? (parseFloat(who.find("input.vat_percent").val()) || 0) : 0;
        var tr_vat_percent = who.attr('data-vat') == 1 ? (parseFloat(who.find("input.vat_percent").val()) || 0) : 0,
                tr_vat2_percent = ((who.attr('data-vat') == 1 && is_sec_vat)) ? (parseFloat(who.find("input.vat2_percent").val()) || 0) : 0,
                TRvalue = ((who.attr('data-vat') == 1) && tr_vat_percent > 0) ? parseFloat(net_total_with_invdisc) : 0;

        vatVal = (TRvalue * tr_vat_percent / 100) || 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(mytdtotal)
        //alert(totalvat)
        who.find('.VATPerItem').val(public_round_number(vatVal) > 0 ? public_round_number(vatVal) : '')
        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)
        //        if (who.attr('data-vat') == 1 && Qty != 0) {
        //            vatVal = TRvalue * tr_vat_percent / 100;
        //            totalvat += vatVal;
        //            taxAmount += TRvalue;
        //            //alert(totalvat)
        //            who.find('.VATPerItem').val(vatVal ? vatVal : '')
        //            $('#PurchaseTaxableAmount').html(AddCommas(taxAmount))
        //            $("#InvoiceVAT").html(AddCommas(totalvat.toXFixed(3)))
        //        }
    }
    function UpdateSubmitButtonStatus() {
        var Rows = $("#InventoryPurchaseTable tbody tr"), DoDisable = false
        if (Rows.length > 0) {
            if (Rows.length == 1) {
                if ($.trim($("input.CODE", Rows).val()) != "" && $.trim($("input.ProductName", Rows).val()) != "" && $.trim($("input.Quantity", Rows).val()) != "" && $.trim($("input.UnitPrice", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }
        if ($.trim($("#CurrencyDropDown > button > input").val()) == "")
            DoDisable = true;
        if ((parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(",", "")) > parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(",", ""))) && !is_exchange)
        {
            DoDisable = true;
        }
        if (!checkClassFlag) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                if ((parseFloat($(this).find(".Quantity").val()) > parseFloat($(this).attr('data-qty'))) && !is_exchange) {
                    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 = 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;
        $("#PurchaseInvoiceTotalPaid").text(AddCommas(public_round_number(A1 + A2 + A3)));
            UpdateSubmitButtonStatus();

        if (public_round_number(A1 + A2 + A3) >= 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 ChangeInvoice() {
        var ID = parseInt($("#Invoice_Purchase_ID").val());
        var Auto_ID = parseInt($("#Invoice_Purchase_ID").attr("data-id"));
        //        if (ID == CurInvoiceID) {
        //            return
        //        }
        //        ReturnItemTableBody.empty();
        //        if (!isNaN(ID)) {
        //            CurInvoiceID = ID;
        //            $("#ReturnItemSuccess").addClass("hidden")
        //            $("#ReturnItemTableLoader").css({display: "block", opacity: 0}).animate({opacity: 1});
        //            $("#ReturnTotalDetails").text(CurrentCurrencySymbol + " 0");
        //            $("#ReturnSubmitButton").addClass("disabled")

        $.ajax({
            url: "InventoryAjax/ReturnCustomerAjax",
            data: {GetInvoiceData: ID, auto_id: Auto_ID, IsVendor: (IsSalesMode ? 0 : 1), is_actual: (is_actual ? 1 : 0), return_id: ID_Edit},
            dataType: "json",
            complete: function (v, vv) {
                from_inv = true;
                var Data = v.responseJSON;
                //                        PrLength = Object.keys(Products).length
//                console.log(Data)
                checkClassFlag = false;
                //                if(IsSalesMode){
                $("#search_supplier").val(Data['Main'][IsSalesMode ? 'Customer_ID' : 'Supplier_ID'])
                $("#search_supplier").attr("data-select-name", Data['Person']['Name'])
                build_select2($(".search_supplier"), (IsSalesMode ? "xhr/customerSearch" : "xhr/supplierSearch"))
                $("#search_supplier").attr("disabled", "disabled")
                $("#Account_Code").val(Data['Main']['Account_ID']).attr("disabled", "disabled")
                $("#Account_Code").attr("data-select-name", Data['Main']['Account_Name'])
                //                build_select2($("#Account_Code"), ("xhr/accIDSearch?type=" + (IsSalesMode ? 'sales' : 'purchase')))
                $("#search_supplier").trigger("change")
                $("#Depot_Loc").val(Data['Main']['Depot_ID'])
                $("#Depot_Loc").attr("data-select-name", Data['Main']['Depot_Name'])
                build_select2($(".Depot_Loc"), "xhr/depotSearch")
                $("#CurrencyDropDown button input").val(Data['Main']['Currency_ID'])
                $("#CurrencyDropDown button span").html(Data['Main']['Currency_Name'] + ' - ' + Data['Main']['Currency_Symbol'])
                $("#CurrencyDropDown button").attr("disabled", "disabled")
                 $(".CurrencyIndicator").html(Data['Main']['Currency_Symbol'])
                $("#InvoiceDiscountInput,#TotalDiscAmount").attr("disabled", "disabled")

                $("#InventoryPurchaseTable tbody").empty()
                for (var i = 0; i < Data['return'].length; i++) {
                    var TR = '<tr data-conv="' + Data['return'][i]['uom_conv'] + '" data-qty="' + Data['return'][i]['remaining_quantity'] + '" data-vat="' + (Data['return'][i]['invoice_vat_percent'] > 0 ? 1 : 0) + '" data-id="' + Data['return'][i]['invoice_product_id'] + '" unit_price="' + Data['return'][i]['invoice_unit_price'] + '" data-expiry="' + (Data['return'][i]['is_expiry']) + '" data-is-serial="' + (Data['return'][i]['is_serial']) + '" data-is-lot="' + (Data['return'][i]['is_lot']) + '">' +
                            '<td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>' +
                            '<td><input type="text" class="form-control AutoComplete CODE  input-barcode-scan" disabled value = "' + Data['return'][i]['Product_Code'] + '"></td>' +
                            '<td><input type="text" class="form-control AutoComplete ProductName" disabled value = "' + Data['return'][i]['Product_Name'] + '"></td>' +
                            '<td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 ? 'hidden' : ''; ?>"><input type="' + (IsSalesMode ? 'text' : 'hidden') + '" class="' + (IsSalesMode ? 'form-control' : 'full-width') + '  expiry_date " disabled  value = "' + (Data['return'][i]['expiry_date'] == null ? '' : Data['return'][i]['expiry_date']) + '" data-select-name = "' + (Data['return'][i]['expiry_date'] == null ? '' : Data['return'][i]['expiry_date']) + '"></td>' +
                            '<td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber" value = "' + Data['return'][i]['cur_qty'] + '"></td>' +
                            '<td><select required name="UOM_ID"  disabled class="full-width UOM_ID " data-init-plugin="select2"><option value="' + Data['return'][i]['invoice_uom_id'] + '">' + Data['return'][i]['UOM_Name'] + '</option></select></td>' +
                            '<td class="<?php echo ($IsSales && in_array(13, $sales_inv_fields_hide)) || (!$IsSales && in_array(8, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="' + (IsSalesMode ? 'text' : 'hidden') + '" disabled class="' + (IsSalesMode ? 'form-control' : 'full-width') + ' lot_nb " value="' + Data['return'][i]['lot_nb'] + '"  data-select-name = "' + (Data['return'][i]['lot_nb'] == '' ? '' : Data['return'][i]['lot_nb']) + '"/></td>' +
                            '<td class="<?php echo ($IsSales && in_array(14, $sales_inv_fields_hide)) || (!$IsSales && in_array(9, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="' + (IsSalesMode ? 'text' : 'hidden') + '" disabled class="' + (IsSalesMode ? 'form-control' : 'full-width') + ' serial_nb " value="' + Data['return'][i]['serial_nb'] + '"  data-select-name = "' + (Data['return'][i]['serial_nb'] == '' ? '' : Data['return'][i]['serial_nb']) + '"/></td>' +
                            '<td class="<?php echo ($IsSales && in_array(11, $sales_inv_fields_hide)) || (!$IsSales && in_array(7, $purchase_inv_fields_hide)) ? 'hidden' : ''; ?>"><input type="text" class="form-control item_note" value = "' + Data['return'][i]['invoice_item_desc'] + '"></td>' +
                            '<td><input type="text" class="form-control UnitPrice isnumber" disabled value = "' + Data['return'][i]['invoice_unit_price'] + '" ></td>' +
                            '<td <?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>><input type="text" class="form-control ttc_price isnumber" disabled value = "' + Data['return'][i]['ttc_price'] + '" ></td>' +
                            '<td><input type="text" class="form-control Disc" disabled value = "' + Data['return'][i]['invoice_product_discount'] + '"></td>' +
                            '<td><input type="text" class="form-control VATPerItem "  disabled value="' + Data['return'][i]['invoice_vat_amount'] + '"></td>' +
                            '<td><input type="text" class="form-control vat_percent " disabled value="' + Data['return'][i]['invoice_vat_percent'] + '"  ></td>' +
                            '<td class="<?php echo ($IsSales && in_array(17, $sales_inv_fields_hide)) || (!$IsSales && in_array(14, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_amount  " disabled value="' + Data['return'][i]['invoice_vat2_amount'] + '"  ></td>' +
                            '<td class="<?php echo ($IsSales && in_array(16, $sales_inv_fields_hide)) || (!$IsSales && in_array(15, $purchase_inv_fields_hide) || !smc_session()['default_setting']['activate_second_vat_purchase']) || !smc_session()['default_setting']['activate_second_vat'] ? 'hidden' : ''; ?>"><input type="text" class="form-control vat2_percent " disabled value="' + Data['return'][i]['invoice_vat2_percent'] + '"  ></td>' +
                            '<td class="<?php echo (($IsSales && in_array(15, $sales_inv_fields_hide)) || !$IsSales) ? 'hidden' : ''; ?>"><input type="checkbox" name="is_damaged" class="is_damaged"/></td>' +
                            '<td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td></tr>';
                    TR = $(TR)
                    $("#InventoryPurchaseTable tbody").append(TR)
                    if (!IsSalesMode) {
                        build_select2($("input.expiry_date", TR), function () {
                            return 'xhr/get_product_expiry?product_id=' + Data['return'][i]['invoice_product_id'] + $("#Depot_Loc").val();
                        }, '', 'expiry_width');
                        build_select2($("input.lot_nb", TR), function () {
                            return 'xhr/get_product_lot?product_id=' + Data['return'][i]['invoice_product_id'] + $("#Depot_Loc").val();
                        }, '', 'expiry_width');
                        build_select2($("input.serial_nb", TR), function () {
                            return 'xhr/get_product_serial?product_id=' + Data['return'][i]['invoice_product_id'] + $("#Depot_Loc").val();
                        }, '', 'expiry_width');
                    }
                    TR.find("select[name=UOM_ID]").select2()
                }
                $("#InvoiceDiscountInput").val(Data['Main']['Discount'])
                UpdateTable()
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")


            }
        })
    }
    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) : ''));
        });
    }
</script>


