<?php if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
if ($IsEdit && empty($edit_arr['Main']['Auto_ID'])) { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this station purchase! 
        <br>
        This station purchase is not available.
    </div>
    <?php die();
} ?>
<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{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
    }
    #Shipping{
        display: inline-block;
        width: 70%;
        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,#service,#service_vat{
        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 input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
    }
    .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;
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .hideme{
        display:none;
    }
    .select2-container > .select2-choice {
        width: 100% !important;
    }
    .supInv{
        display:inline-flex;
    }
    .invoice{
        padding-top:0 !important;
    }
    #Truck{
        width:48%;
        margin-right:2%
    }
    .right-div .form-group{
        margin-bottom:0px;
    }
</style>
<!--<script src="< ?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.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="javascript:void(0);" onsubmit="return false" id="InvoiceForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id = "PurchaseSuccess" class = "hidden"></div>
                <div class = "invoice ">
                    <div class = "container-sm-height">
                        <div class = "row-sm-height">
                            <input type="hidden" name="due_date_period" id="due_date_period" value="<?php echo ($IsEdit) ? $edit_arr['Main']['due_date_period'] : ''; ?>" />
                            <div class = "col-md-9 col-sm-height sm-no-padding">
                                <div class = "row " style = "display:flex;">
                                    <div class = "col-md-6">
                                        <h2 class = "font-montserrat all-caps hint-text"><?php echo CommonLanguage::getMessage('station_purchase');
?> </h2>
                                    </div>
                                </div>
                                <div class='row form-group'>
                                    <div class="input-group  col-md-4 center-margin pull-left " >
                                        <label><?php print CommonLanguage::getMessage('choose_supplier'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="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']['Supplier_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']['purchase_account_id']; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Main']['Account_Name'] : smc_session()['user_accounts']['p_name']); ?>' required />
                                    </div>
                                    <div class="bone_type_id col-md-4">
                                        <label><?php print CommonLanguage::getMessage('bone_type'); ?></label>
                                        <input class=" full-width" id="bone_type_id" name="bone_type_id" type="hidden" value="<?= $IsEdit ? $edit_arr['Main']['bone_type_id'] : ''; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['Main']['bone_type_name'] : ''); ?>'  />
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="SupplierInfo">
                                    <input type="hidden" name="Supplier_ID" value="<?php echo $IsEdit ? ($edit_arr['Main']['Supplier_ID'] ) : '' ?>" required id="Supplier_ID" />
                                    <div id="SupplierInfoContent" class="<?php echo $IsEdit ? '' : 'hidden' ?>">
                                        <strong><span class='Name' id='Supplier_Name' data-id='<?php echo $IsEdit ? $edit_arr['Person']['Name'] : '' ?>'><?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('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>
                                    <div id="SupplierAccInfo" class="<?php echo $IsEdit ? '' : 'hidden' ?>">
                                        <div id='Account_CodeDiv' value='<?php echo $IsEdit ? $edit_arr['Main']['Account_Code'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('account_code') ?>: </strong><?php echo $IsEdit ? $edit_arr['Main']['Account_Name'] . ' - ' . $edit_arr['Main']['Account_Code'] : '' ?></div>
                                    </div>
                                </div>
                            </div>
                            <div class="right-div col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                <div class="sm-m-t-20">
                                    <h4><?php print CommonLanguage::getMessage('purchase_voucher'); ?> #
                                        <?php
                                        echo $IsEdit ? $edit_arr['Main']['ID'] : '--';
                                        ?></h4>
                                </div>
                                <div  class="form-group supInv" id="SupplierInv" style="">
                                    <h4> <?php print CommonLanguage::getMessage('supplier_invoice'); ?>#</h4>
                                    <input id="Supplier_Invoice" name="Supplier_Invoice" class="form-control" value="<?php echo $IsEdit ? $edit_arr['Main']['Supplier_Invoice_ID'] : '' ?>" style="    width: 35%;
                                           margin-top: 11px;
                                           margin-left: 15px" />
                                </div>
                                <div  style="display: flex">
                                    <div  class="form-group " style="width: 48%;margin-right:2%;">
                                        <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                        <input id="PurchaseInvoiceDate" name="PurchaseInvoiceDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Date'] : $today); ?>" required />
                                    </div>
                                    <div  class="form-group  "  style="width: 50%;" >
                                        <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                        <input id="PurchaseInvoiceDueDate" name="PurchaseInvoiceDueDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Due_Date'] : $today); ?>" required>
                                    </div>
                                </div>
                                <div  id="depot" class="form-group " 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" <?php echo $permissions->hasPermission('change_depot') ? '' : 'disabled' ?> data-old="<?php echo $IsEdit ? $edit_arr['Main']['Depot_ID'] : ''; ?>" value="<?= $IsEdit ? $edit_arr['Main']['Depot_ID'] : (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" data-select-name='<?= json_encode($IsEdit ? $all_depots[$edit_arr['Main']['Depot_ID']]['Depot_Name'] : (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name'])) ?>' />
                                    </div>
                                    <div style="width: 50%;" >
                                        <div  class="form-group " >
                                            <label><?php print CommonLanguage::getMessage('exchange_rate'); ?></label>
                                            <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>  value="<?php echo ($IsEdit ) ? $edit_arr['Main']['current_rate'] : '' ?>" />
                                        </div>
                                    </div>
                                </div>
                                <div style="display: flex">
                                    <div  id="Truck" class="form-group " >
                                        <label><?php print CommonLanguage::getMessage('truck'); ?>
                                        <span class="red-star">*</span>
                                        </label>
                                        <input  id="inv_truck" name="inv_truck" class="form-control full-width inv_truck"  value="<?php echo $IsEdit ? $edit_arr['Main']['truck'] : '' ?>" required />
                                    </div>
                                    <div  class="form-group " >
                                        <label><?php print CommonLanguage::getMessage('loading_number'); ?>
                                        <span class="red-star">*</span>
                                        </label>
                                        <input  id="loading_number" name="loading_number" class="form-control full-width loading_number"  value="<?php echo $IsEdit ? $edit_arr['Main']['loading_number'] : '' ?>" required />
                                    </div>
                                </div>
                                <div id="CurrencyIDContainer" class=" m-t-10" >
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo $IsEdit ? $edit_arr['Main']['Currency_Symbol'] : ''; ?>">
                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><strong><?php echo $IsEdit ? ($edit_arr['Main']['Currency_Name'] . ' - ' . $edit_arr['Main']['Currency_Symbol']) : CommonLanguage::getMessage('select') ?></strong></span>
                                                <input type="hidden"  value="<?php echo $IsEdit ? $edit_arr['Main']['Currency_ID'] : $DefaultCurrencyID ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID"/>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <?php echo $CurList ?>
                                                <li class="divider"></li>
                                                <li><a class="LoadMore">More..</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div   class="form-group " style="display: flex;">
                                    <!--<div class="col-md-12">-->
                                    <div class="<?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('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"style="width:18%"><?php echo CommonLanguage::getMessage('compts'); ?><span class="red-star">*</span></th>
                                    <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('product_name'); ?> <span class="red-star">*</span><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('lits_obs'); ?> <span class="red-star">*</span></th>
                                    <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('abrv_temperature'); ?> <span class="red-star">*</span></th>
                                    <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('abrv_coefficient'); ?> <span class="red-star">*</span></th>
                                    <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('litres_15_degree'); ?><span class="red-star">*</span></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['item_note_in_purchase'] ? '' : 'hidden' ?> " style="width:20%"><?php print CommonLanguage::getMessage('Description'); ?></th>
                                    <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('unit_price'); ?> <span class="red-star">*</span></th>
                                    <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('discount_percent'); ?></th>
                                    <th class="text-center"style="width:10%"><?php print CommonLanguage::getMessage('total'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit) {
                                    $data_array = $IsEdit ? $edit_arr['Details'] : $edit_arr['Details'];
                                    if (!empty($data_array)) {
                                        foreach ($data_array as $item) {
                                            $comp_arr = !empty($item['compts']) ? explode(',', $item['compts']) : array();
                                            ?>
                                            <tr data-conv="<?php echo $item['uom_con'] ?>" data-qty="<?php echo $item['Product_Quantity'] ?>"
                                                data-id="<?php echo $item['Product_ID'] ?>"
                                                unit_price="<?php echo $item['Product_Net_Price'] ?>"
                                                data-item-disc="<?php echo $item['Product_Limit_Discount'] ?>"
                                                data-prod-status ="<?php echo $item['Status_ID'] ?>" >
                                                <td>  <span class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                                <td>
                                                    <select name="compts_id"  class="full-width compts_id " data-init-plugin="select2" multiple>
                                                        <?php foreach ($all_compts as $compts): ?>
                                                            <option value="<?php echo $compts['compts_id']; ?>" <?php echo (in_array($compts['compts_id'], $comp_arr) ? 'selected' : '' ) ?>><?php echo $compts['compts_name']; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </td>
                                                <td><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item['Name'] ?>">
                                                </td>
                                                <td><input type="number" class="form-control lits_Obs isnumber" value = "<?php echo $item['liter_abs'] ?>"></td>
                                                <td><input type="number" class="form-control Temperature isnumber" value = "<?php echo $item['temp'] ?>"></td>
                                                <td><input type="number" class="form-control Coefficient isnumber" value = "<?php echo $item['coeff'] ?>"></td>
                                                <td><input type="number" class="form-control Quantity isnumber" value = "<?php echo $item['Item_Quantity_Current'] ?>"><span class="Hint"></span></td>
                                                <td class="<?php echo smc_session()['default_setting']['item_note_in_purchase'] ? '' : 'hidden' ?>"><input type="text" class="form-control item_note" value = "<?php echo $item['product_description'] ?>"></td>
                                                <td><input type="number" class="form-control UnitPrice isnumber"  value = "<?php echo $item['Product_Net_Price'] ?>" ><span class="Hint"></span></td>
                                                <td><input type="text" class="form-control Disc"  value = "<?php echo $item['Product_Discount'] ?>"></td>
                                                <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>
                                    <tr data-conv="1">
                                        <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                        <td>
                                            <select name="compts_id"  class="full-width compts_id " data-init-plugin="select2" multiple>
                                                <?php foreach ($all_compts as $compts): ?>
                                                    <option value="<?php echo $compts['compts_id']; ?>"><?php echo $compts['compts_name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>
                                        <td><input type="text" class="form-control AutoComplete ProductName"></td>
                                        <td><input type="number" class="form-control lits_Obs isnumber"></td>
                                        <td><input type="number" class="form-control Temperature isnumber"></td>
                                        <td><input type="number" class="form-control Coefficient isnumber"></td>
                                        <td><input type="number" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['item_note_in_purchase'] ? '' : 'hidden' ?>"><input type="text" class="form-control item_note" ></td>
                                        <td><input type="number" class="form-control UnitPrice isnumber"  ><span class="Hint"></span></td>
                                        <td><input type="text" class="form-control Disc"  value=""></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>
                                            <select  name="compts_id"  class="full-width compts_id " data-init-plugin="select2" multiple>
                                                <?php foreach ($all_compts as $compts): ?>
                                                    <option value="<?php echo $compts['compts_id']; ?>"><?php echo $compts['compts_name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>
                                        <td><input type="text" class="form-control AutoComplete ProductName"></td>
                                        <td><input type="number" class="form-control lits_Obs isnumber"></td>
                                        <td><input type="number" class="form-control Temperature isnumber"></td>
                                        <td><input type="number" class="form-control Coefficient isnumber"></td>
                                        <td><input type="number" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                        <td class="<?php echo smc_session()['default_setting']['item_note_in_purchase'] ? '' : 'hidden' ?>"><input type="text" class="form-control item_note"></td>
                                        <td><input type="number" class="form-control UnitPrice isnumber"  ><span class="Hint"></span></td>
                                        <td><input type="text" class="form-control Disc"  value=""></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   clearfix" style="border-left: 1px solid #eee;border-right: 1px solid #eee;padding-right:0">
                                <div class="col-sm-12  " style="padding-right:0">
                                    <textarea id="invoice_note" name="invoice_note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?> ...." aria-invalid="false"><?php echo $IsEdit ? $edit_arr['Main']['Invoice_Description'] : '' ?></textarea>
                                </div>
                                <div class="col-sm-12  " style="padding-right:0">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></h5>
                                    <div id="InvoicePaymentSetup" class="no-print">
                                        <div class="Body">
                                            <div class="">
                                                <ul class="nav nav-tabs">
                                                    <li class="active"><a data-toggle="tab" href="#SetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#SetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#SetPaidFormTab_3"><i class="fa fa-cc-visa"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('credit_card'); ?></a></li>
                                                </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">
                                                                        <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'] : smc_session()['user_accounts']['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">
                                                                        <!--                                                                    <div class="input-group-btn DropDownForForms Closable">-->
                                                                        <input class="credit_account full-width" id="credit_account" name="credit_account" type="hidden"  value="<?php echo ($IsEdit && 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>
                            <div class="col-sm-3 col-sm-height col-middle clearfix sm-p-b-15" style="text-align:center">
                                <div  class="col-md-12" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10" > <?php print CommonLanguage::getMessage('shipping_code'); ?>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class=" full-width" id="Shipping_Code" name="Shipping_Code" type="hidden" value="<?= $IsEdit ? $edit_arr['Main']['shipping_id'] : smc_session()['user_accounts']['pur_ship_account_id']; ?>" data-select-name='<?= json_encode(($IsEdit && array_key_exists('shipping_name', $edit_arr['Main'])) ? $edit_arr['Main']['shipping_name'] : smc_session()['user_accounts']['ps_name']); ?>' /></h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10" > <?php print CommonLanguage::getMessage('shipping'); ?><input type="text" class="form-control ignore" id="Shipping" value="<?php echo $IsEdit ? $edit_arr['Main']['shipping'] : 0 ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('vat_ten'); ?><input class="form-control ignore" id="InvoiceVAT" value="<?php echo $IsEdit ? $edit_arr['Main']['VAT'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('service'); ?><input class="form-control ignore" id="service" value="<?php echo $IsEdit ? $edit_arr['Main']['service_amount'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('service_vat') . ' (' . (smc_session()['vat_percent']) . ' %)'; ?><input class="form-control ignore" id="service_vat" value="<?php echo $IsEdit ? $edit_arr['Main']['service_vat'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" > <?php print CommonLanguage::getMessage('invoice_discount'); ?><input type="text" class="form-control ignore "  id="InvoiceDiscountInput" value="<?php echo $IsEdit ? $edit_arr['Main']['Discount'] : 0 ?>"/> %</h5>
                                    <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>
                            <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('local_amount'); ?></h5>
                                    <h1 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" >
                        <button class=" btn btn-primary btn-cons m-b-10 pull-right " id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button">
                            <i class="pg-form"></i>
                            <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span>
                        </button>
                        <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button">
                            <i class="fa fa-print"></i>
                            <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span>
                        </button>
                        <button class=" btn btn-success-darker btn-cons m-b-10 pull-right disabled <?php echo $IsEdit ? 'hidden' : '' ?>" id="PrintBtn1" style="padding-top: 10px;top: 20px;min-width:253px;" type="button">
                            <i class="fa fa-print"></i> 
                            <span class="bold"><?php print CommonLanguage::getMessage('print_delv'); ?></span>
                        </button>
                        <div class="pull-right form-group" style="margin-right: 42px;">
                            <div class="input-group"><label><?php print CommonLanguage::getMessage('pending'); ?></label></div>
                            <div class="input-group"><input type="checkbox" id="pending" name="pending"/></div>
                        </div>
                    </div>
                    <hr>
                    <div>
                        <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Legal_Name']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Province']; ?> <?php echo $org_details[0]['Organization_Country']; ?> - <?php echo $org_details[0]['Organization_City']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right">CR: <?php echo $org_details[0]['Organization_Commercial_Registry']; ?></span>
                        <span class="m-l-20 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Phone'); ?>: <?php echo $org_details[0]['Organization_Phone']; ?></span>
                        <span class="m-l-40 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Email'); ?>: <?php echo $org_details[0]['Organization_Email']; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<div class="modal fade bs-example-modal-md" data-backdrop="static" id="DiscountProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('discount_alert') ?></p>
                        <p><?php print CommonLanguage::getMessage('enter_new_disc') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary "  data-dismiss="modal" style="width:auto"><?php echo CommonLanguage::getMessage('proceed') ?></button>
            </div>
        </div>
    </div>
</div>
<select id="select_compts" name="select_compts"  class="full-width select_compts hidden" data-init-plugin="select2" multiple>
    <?php foreach ($all_compts as $compts): ?>
        <option value="<?php echo $compts['compts_id']; ?>"><?php echo $compts['compts_name']; ?></option>
    <?php endforeach; ?>
</select>
<script>
    var CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
            EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email')); ?>,
            RequiredField = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            discount_alert = <?php echo json_encode(CommonLanguage::getMessage('discount_alert')); ?>,
            PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
            AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
            CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country')); ?>,
            FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb')); ?>,
            accountCodeLang = <?php echo json_encode(CommonLanguage::getMessage('account_code')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            account_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_account_first')); ?>,
            depot_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_depot_first')); ?>,
            supplier_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_supplier_first')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            default_vat = <?php echo json_encode(smc_session()['vat_percent']); ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            max_discount = <?php echo json_encode(smc_session()['user_accounts']['max_discount']); ?>,
            ignore_zero_item_disc = <?php echo json_encode(smc_session()['default_setting']['ignore_zero_item_disc']) ?>,
            display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            inv_nb = <?php echo json_encode(CommonLanguage::getMessage('purchase') . ' #'); ?>;
    TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = vatVal = totalvat = taxAmount = is_td_total = 0,
            percent_flag = total_qty = 0,
            global_round = <?php echo json_encode($currency_round); ?>,
            CheckSubmit = true,
            CurrencyRate = <?php echo json_encode($Extable); ?>,
            has_purchase_cost_perm = <?php echo $permissions->hasPermission('view_purchase_last_cost') ? 'true' : 'false'; ?>;
    $(function () {
        build_select2($(".search_supplier"), ("xhr/supplierSearch") + (IsEditMode ? "?is_edited=" + $(".search_supplier").val() : "?Status_ID=1"))
//        build_select2($("#bone_type_id"), ("xhr/accIDSearch"))
        build_select2($("#bone_type_id"), "xhr/CommonSearch?col_id=bone_type_id&col_name=bone_type_name&table=tbl_bone_type")

        build_select2($("#Account_Code"), ("xhr/accIDSearch?type=" + ('purchase')))
        build_select2($("#Shipping_Code"), ("xhr/accIDSearch?type=" + ('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($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        apply_autocomplete($("#inv_truck"), 'xhr/searchInvTruck', function (event, ui, who) {
            who.val(ui.item.truck);
        });
        new Switchery($("#pending").get(0), {color: $.Pages.getColor("primary")})
        $(".CurrencyIndicator").html($("#CurrencyDropDown").attr("data-symbol"))
        $("#current_rate").on("keyup", function () {
            UpdateTable()
        })

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

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


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

        })

        $("#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()
            }
            if (percent_flag == 2) {
                $("#TotalDiscAmount").trigger("keyup")
            } else {
                $("#InvoiceDiscountInput").trigger("keyup")
            }
        })
        $("#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')



        $("#search_supplier").on("change", function () {
            $("#SupplierInfoContent").removeClass('hidden')
            if ($(this).val() == '') {
                $("#ProdLoader > h3").empty().html(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(),
            }
            $.ajax({
                url: "InventoryAjax/addPurchaseAjax",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        $("#SupplierInfoContent").empty();
                        var Content = "";
                        Content += "<strong><span class='Name' id='Supplier_Name' data-id='" + Data[0]['Supplier_Name'] + "'>" + Data[0]['Supplier_Name'] + "</span></strong>";
                        Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Supplier_Company'] + "</span></div>";
                        Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Supplier_Email'] + "</span></div>";
                        Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_Phone'] + "</span></div>";
                        Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Supplier_Address'] + "</span></div>";
                        Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                        Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                        $("#SupplierInfoContent").html(Content)
                        $("#Supplier_ID-error").remove()
                        $("#Supplier_ID").removeClass("error").val(Data[0]['Supplier_ID']);
                        $("#due_date_period").val(Data[0]['supplier_due_date_period']);
                        updateDueDate(Data[0]['supplier_due_date_period'])
                    }
                }
            })
        })
        $("#CurrencyDropDown .dropdown-menu > li").on("click", function () {
            setTimeout(function () {
                UpdateTable()
            }, 300)
        })
        $("#PrintBtn").on("click", function () {
            var myurl = "Inventory/ViewInvoice/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
            printExternalInv(myurl, 'invoice_print_btn')
        })
        $("#PrintBtn1").on("click", function () {
            var myurl = "Inventory/ViewInvoice/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
            printExternalInv(myurl, 'delivery_print_btn')
        })
        $("#Account_Code,#Depot_Loc").on("change", function () {
            var accName = $.trim($("#s2id_Account_Code").text());
            //alert($(this).val())
            $('#Account_CodeDiv').remove()
            var Content = "";
            if ($("#Account_Code").val() != 0) {
                Content += "<div id='Account_CodeDiv' value='" + $("#Account_Code").val() + "'><strong>" + accountCodeLang + ": </strong>" + accName + "</div>";
                $("#SupplierAccInfo").append(Content).removeClass('hidden')
            }
            if ($("#Account_Code").val() == '') {
                $("#ProdLoader > h3").empty().html(account_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else
            if ($("#search_supplier").val() == '') {
                $("#ProdLoader > h3").empty().html(supplier_firstLang)
            } else if ($("#Depot_Loc").val() == '') {
                //                alert()
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
            if ($(this).attr("id") == 'Depot_Loc') {
                var item_arr = {items: [], depot_id: $("#Depot_Loc").val()}
                $("#InventoryPurchaseTable tbody tr").each(function (e) {
                    if ($(this).attr("data-id") != 0) {
                        item_arr.items.push($(this).attr("data-id"))
                    }
                })
                $.ajax({
                    url: "InventoryAjax/ReturnQtyPerDepot",
                    data: item_arr,
                    dataType: 'json',
                    complete: function (v1, v2) {
                        if (v2 == "success") {
                            var Data = (v1.responseJSON);
                            $.each(Data, function (index, value) {
                                var me = $("#InventoryPurchaseTable tbody tr[data-id='" + value['Product_ID'] + "']"),
                                        tr_conv = parseFloat(me.attr("data-conv"));
                                me.find(".Quantity").next().text(AddCommas(public_round_number(parseFloat(value['qty'] / tr_conv))) + " in stock")
                                me.find("input.ProductName").next().text(value['loc'])
                            })
                        }
                    }
                })
            }
        })
        if (!$("#InventoryPurchaseTable").hasClass('hideme')) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
            });
        } else {
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.ProductName"));
        }
        $("#PurchaseInvoiceDueDate,#PurchaseInvoiceDate,.check_due_date,.value_date").datepicker({autoclose: true});
        $('#PurchaseInvoiceDate').on("changeDate", function (e) {
            updateDueDate($('#due_date_period').val());
        });

        $("#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 (IsEditMode)
            $(".Quantity").trigger('keydown')
        $("#InvoiceDiscountInput").on(" keyup", function () {
            percent_flag = 1;
            check_discount($(this), max_discount)
            $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($(this).val()) / 100) || 0)
            setTimeout("UpdateTable()", 100)
        })
        $("#Shipping,#TotalDiscAmount").on("keyup", function () {
            if ($(this).attr("id") == 'TotalDiscAmount') {
                percent_flag = 2;
                //                check_discount($("#InvoiceDiscountInput"), max_discount)
                if (parseFloat($(this).val()) > (TotalInvoice * max_discount / 100))
                    $(this).val((TotalInvoice * max_discount / 100))
                $("#InvoiceDiscountInput").val((parseFloat($(this).val()) / TotalInvoice * 100) || 0)
                //                }
            }
            setTimeout("UpdateTable()", 100)
        })
        $("#InventoryPurchaseTable tbody").delegate("> tr input", "keydown", function (e) {
            is_td_total = 0;
            CheckSubmit = false;
            var me = $(this)
            if (e.which == 8) {
                if (me.val() == "" && !me.hasClass("CODE")) {
                    me.parents("td").prev().find("input").focus()
                } else if (me.val() == "" && me.hasClass("CODE")) {
                    if (me.parents("tr").prev()) {
                        me.parents("tr").prev().find(".Disc").focus()
                    }
                }
            }
        })
        $("#InventoryPurchaseTable tbody").delegate("> tr input:not(.AutoComplete)", "keyup", function (e) {
            is_td_total = 0;
            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
            $("tr", Parent).each(function (e) {
                if ($("tr", Parent).length > 1) {
                    var IsEmpty = true;
                    $(this).find("input").each(function () {
                        if ($(this).val() != "")
                            IsEmpty = false;
                    })
                    if (IsEmpty == true) {
                        if ($(this).index() <= $("#InventoryPurchaseTable tbody tr").length - 2) {
                            me.parents("tr").prev().find(".Disc").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input", Parent).each(function (e) {
                if ($(this).val() != "")
                    IsLastOneEmpty = false;
            });
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                ClonedRow.find("input").val("")
                ClonedRow.attr("data-conv", "1")
                ClonedRow.removeAttr("data-id")
                Parent.append(ClonedRow);
                EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
                $(".Hint,.Total", ClonedRow).html("")
                ClonedRow.removeAttr("data-prod-status")
                $("input", ClonedRow).removeClass("wrong")
                $(".select2-container", ClonedRow).empty().remove()
                $(".compts_id", ClonedRow).empty().html($("#select_compts").html()).show().select2()
                UpdateTable()
            }
        })
        $("#CurrencyDropDown li").click(function () {
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            global_round = $(this).attr("data-round")
            if ($(this).attr("value") == local_currency) {
                $("#current_rate").val(1).attr("disabled", "disabled")
            } else
                $("#current_rate").val("").removeAttr("disabled")
            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}
            }
        })
        $("#InvoiceVAT").on("keyup", function () {
            UpdateTable()
        })
        $("#service").on("keyup", function () {
            var service_val = parseFloat($(this).val() ? $(this).val() : 0);

            if (isNaN(service_val))
                service_val = 0;
            $("#service_vat").val(service_val * default_vat / 100)
            UpdateTable();
        })
        $("#InvoiceSubmitButton").on("click", ApplyPostMethod);
        UpdateSubmitButtonStatus()

    })
    function UpdateTable() {

        var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        var service = parseFloat($("#service").val() ? $("#service").val() : 0);
        if (isNaN(service))
            service = 0;
        var service_vat = parseFloat($("#service_vat").val() ? $("#service_vat").val() : 0);

        vatVal = 0, totalvat = parseFloat($("#InvoiceVAT").val() || 0), taxAmount = 0, total_qty = 0;
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0
        $("#InventoryPurchaseTable tbody tr").each(function () {
            UpdateTotalForRow($(this))
        });
        if (percent_flag == 1)
            $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
        if (percent_flag == 2) {
            $("#InvoiceDiscountInput").val((parseFloat($("#TotalDiscAmount").val()) / TotalInvoice * 100) || 0)
            if (parseFloat($("#InvoiceDiscountInput").val()) > 100) {
                $("#TotalDiscAmount").val('').trigger("keyup")
                $("#DiscountProceedModal").modal("show")
            }
        }
        var totalDiscountValue = parseFloat($("#TotalDiscAmount").val()) || 0;
        var TotalInvoiceDisounted = TotalInvoice - totalDiscountValue;
        setTimeout("UpdateSubmitButtonStatus()", 100)
        var ftotal = TotalInvoiceDisounted + totalvat + shipping + service + service_vat, finalTotal = 0;
//        console.log(totalvat)
        if (global_round > 0) {
            var roundTo = global_round,
                    diff = ftotal % roundTo;
            var finalTotal = Math.floor(ftotal / roundTo);
            if (diff >= (roundTo / 2)) {
                finalTotal++;
            }
            finalTotal = finalTotal * roundTo;
        } else {
            finalTotal = ftotal;
        }
        $("#PurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted": round_number(TotalInvoice + shipping), "MyValueDiscounted": round_number(TotalInvoiceDisounted + totalvat + shipping)}).text(AddCommas(public_round_number(finalTotal)))
        if ($("#current_rate").val() != '')
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(finalTotal * $("#current_rate").val()))))
        else
            $("#Local_Total").html(AddCommas(public_round_number(parseFloat(ConvertCurrency2(finalTotal, $("#CurrencyDropDown input").val(), local_currency)))))
    }
    function EnableAutoComplete(who) {
        if (!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=2&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-qty", ui.item.Quantity);


                    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(public_round_number(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val()))))));
                    }
                    TR.find("input.Quantity").next().text(AddCommas(public_round_number(parseFloat(ui.item.Quantity))) + " in stock")

                    if (event.which != 9)
                        TR.find("input.lits_Obs").focus()
//                    else
//                        TR.find("input.Quantity").next().text(AddCommas(parseFloat(ui.item.Quantity).toXFixed(3)) + " in stock")
                    if (display_shelf_locations == 1) {
                        TR.find("input.ProductName").next().text(ui.item.loc);
                    }
                    //                    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() * 2.3) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = 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() {
        $("#PurchaseSuccess").attr("class", "hidden");
        if (!$("#InvoiceForm").valid()) {
            var validator = $("#InvoiceForm").validate(),
    errors = validator.errorList;
    console.log(errors);
            $(document.body).animate({scrollTop: 0}, 800)
            return;
        }
        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(),
                    loading_number: $("#loading_number").val(),
                    Invoice_VAT: $("#InvoiceVAT").val(),
                    Account_Code: $('#Account_Code').val(),
                    bone_type_id: $("#bone_type_id").val(),
                    CurrencySymbole: $(".CurrencyIndicator").html(),
                    pending_status: $("#pending").is(":checked") ? 3 : 4,
                    shipping: $("#Shipping").val(),
                    shipping_account: $("#Shipping_Code").val(),
                    discount_amount: $("#TotalDiscAmount").val(),
                    is_actual: is_actual ? 1 : 0,
                    Invoice_Currency_Rate: $("#current_rate").val(),
                    Invoice_Description: $("#invoice_note").val(),
                    job_id: $("#job_id").val(),
                    project_id: $("#project_id").val(),
                    service: $("#service").val(),
                    service_vat: $("#service_vat").val(),
                    Products: []
                };
        Data.Supplier_Invoice_ID = $("#Supplier_Invoice").val();
        Data.Supplier_ID = $("#Supplier_ID").val();
        Data.truck = $("#inv_truck").val();
        Data.Supplier_Account = $("#Finance_Account").attr("data-id")
        Data.Supplier_Name = $("#Supplier_Name").attr("data-id")
        Data.Purchase_Date = $("#PurchaseInvoiceDate").val();
        Data.Purchase_Due_Date = $("#PurchaseInvoiceDueDate").val() ? $("#PurchaseInvoiceDueDate").val() : $("#PurchaseInvoiceDate").val();
        Data.Currency_ID = $("#CurrencyDropDown input").val();
        Data.Purchase_Discount = $("#InvoiceDiscountInput").val();
        Data.Purchase_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
        Data.Purchase_Sub_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
        Data.Purchase_Paid_Amount = $("#AdvanceValue").val();
        if (IsEditMode) {
            Data.Invoice_ID_Auto = ID_Edit;
            Data.Old_Depot_ID = $("#Depot_Loc").attr('data-old')
        }
        $("#InventoryPurchaseTable tbody tr").each(function (e) {
            var me = $(this);
            if (me.find(".Quantity").val() != '' && me.find(".ProductName").val() != '') {
                Data.Products.push({
                    compts: me.find("select.compts_id").val(),
                    Product_ID: me.attr("data-id"),
                    Product_Name: me.find(".ProductName").val(),
                    Item_Quantity: me.find(".Quantity").val(),
                    liter_abs: me.find(".lits_Obs").val(),
                    coeff: me.find(".Coefficient").val(),
                    temp: me.find(".Temperature").val(),
                    Item_Price: me.find(".UnitPrice").val(),
                    Currency_ID: $("#CurrencyDropDown input").val(),
                    Item_Discount: me.find(".Disc").val(),
                    Product_Total_Price: me.find(".Total").attr("myval"),
                    product_description: me.find(".item_note").val()
                });
                me.find(".Quantity,.UnitPrice,.lits_Obs,.Temperature,.Coefficient").each(function () {
                    if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                        $(this).addClass("wrong")
                        CheckSubmit = false;
                        IsValidated = false;
                    } else {
                        $(this).removeClass("wrong")
                    }
                })
                if (me.attr("data-id") == '0' || me.attr("data-id") == '' || me.attr("data-id") == undefined) {
                    me.find(".ProductName").addClass("wrong")
                    IsValidated = false;
                    CheckSubmit = false;
                }
            }
        })
        if (!IsValidated)
            return;
        if ($('#PurchaseInvoiceDueDate').val() < $('#PurchaseInvoiceDate').val()) {
            $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('duedate_greater_currentdate'); ?>');
            $(document.body).animate({scrollTop: 0}, 800)
            return;
        }
        $("#PurchaseDisabler").show();
        $.ajax({
            url: IsEditMode ? "InventoryAjax/edit_station_purchase" : "InventoryAjax/add_station_purchase",
            method: "POST",
            data: Data,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    if (v1.responseJSON[0] == 'OK') {
                        Invoice_ID = v1.responseJSON[1];
                        $("#PrintBtn,#PrintBtn1").removeClass("disabled")
                        $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[2] + '</strong>')
                        $("#InvoiceSubmitButton").attr("disabled", "disabled")
                        CheckSubmit = true;
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])
                        CheckSubmit = false;
                    }
                } else {
                    $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                    CheckSubmit = false;
                }
                $(document.body).animate({scrollTop: 0}, 800)
                $("#PurchaseDisabler").hide();
            }
        })
        //        } else {
        //            $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
        //            $(document.body).animate({scrollTop: 0}, 800)
        //        }
    }
    function UpdateTotalForRow(who) {
        var Single_Price = parseFloat(who.find(".UnitPrice").val()) || 0,
                Qty = parseFloat(who.find(".Quantity").val()) || 0,
                Total = Single_Price * Qty,
                Discount = parseFloat(who.find(".Disc").val()) || 0,
                Net_Total = (Total * (1 - Discount / 100)) || 0,
                net_total_with_invdisc = Net_Total * (1 - parseFloat($("#InvoiceDiscountInput").val() || 0) / 100);
        TotalInvoiceWithoutDiscount += Total;
        TotalDiscount += Discount;
        TotalInvoice += Net_Total;
        total_qty += Qty;

        who.attr('Unit_Price', Single_Price)


        var mytdtotal = (Math.round((net_total_with_invdisc) * 100) / 100);
        who.find(".Total").attr("MyVal", public_round_number(net_total_with_invdisc)).html(mytdtotal)
//        $("#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.ProductName", Rows).val()) != "" && $.trim($("input.Quantity", Rows).val()) != "" && $.trim($("input.UnitPrice", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }
        if ($.trim($("#CurrencyDropDown > button > input").val()) == "")
            DoDisable = true;
        if (parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(/,/g, "")) > parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(/,/g, ""))) {
            DoDisable = true;
        }
        if (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }
    function InputMustBeAtleastN(who, N) {
        if (parseInt(who.value) < N || !parseInt(who.value))
            who.value = N;
        UpdatePurchaseInvoiceTotalPaid();
    }
    function UpdatePurchaseInvoiceTotalPaid() {
        var A1 = public_round_number(parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val())) || 0,
                A2 = public_round_number(parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val())) || 0,
                A3 = public_round_number(parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val())) || 0;
        $("#PurchaseInvoiceTotalPaid").text(AddCommas(A1 + A2 + A3));
        UpdateSubmitButtonStatus();
        if ((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 printExternalInv(url, btn_id) {
        $("#print_iframe").remove();
        $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:800px;height:800px;display:none;' src='" + url + "' onload='document.getElementById(\"print_iframe\").contentWindow.document.getElementById(\"" + btn_id + "\").click();'  ></iframe>").appendTo("body");
    }
    function check_discount(me, item_disc) {
        if (item_disc > 0 || ignore_zero_item_disc != 1) {
            if (parseFloat(me.val()) > Math.min(parseFloat(max_discount), item_disc))
                me.val(Math.min(parseFloat(max_discount), item_disc))
        } else if (parseFloat(me.val()) > parseFloat(max_discount))
            me.val(parseFloat(max_discount))
    }
    function updateDueDate(nb_days) {
        if (nb_days && nb_days != 0 && $('#PurchaseInvoiceDate').val()) {
            var date2 = $('#PurchaseInvoiceDate').datepicker('getDate');
            date2.setDate(date2.getDate() + parseInt(nb_days));
            $('#PurchaseInvoiceDueDate').datepicker('setDate', date2);
        }
    }
</script>
