<?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>';
//echo $IsEdit;
//print_r($edit_arr);
if (empty($edit_arr['Main']['Auto_ID']) && $IsEdit) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php echo CommonLanguage::getMessage('delivery_not_available') ?> </strong>
    </div>
    <?php
    return;
}
//if ($check_invoice && $IsEdit) {
?>
<!--    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php echo CommonLanguage::getMessage('order_linked_invoice') ?> </strong>
    </div>-->
<?php
//    return;
//}
if ($is_order && count($edit_arr['Details']) == 0) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php echo CommonLanguage::getMessage('order_totally_delivered') ?></strong>
    </div>
    <?php
    return;
}
if ($is_purchase && $check_pur_converted == 1) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php echo CommonLanguage::getMessage('purchase_converted') ?></strong>
    </div>
    <?php
    return;
}
if ($is_purchase && $check_pur_is_from_delivery == 1) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php echo CommonLanguage::getMessage('purchase_is_from_delivery') ?></strong>
    </div>
    <?php
    return;
}
if (!empty($delivery_converted_nb)) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong><?php echo CommonLanguage::getMessage($IsSales ? 'delivery_converted_invoice' : 'delivery_converted_purchase' ) . ' #' . $delivery_converted_nb ?></strong>
    </div>
    <?php
    return;
}
$fields_to_hide = smc_session()['default_setting'][$IsSales ? 'delivery_customer_fields_to_hide' : 'delivery_supplier_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting'][$IsSales ? 'delivery_customer_fields_to_hide' : 'delivery_supplier_fields_to_hide']) : [];
$req_fields = smc_session()['default_setting'][$IsSales ? 'delivery_customer_required_fields' : 'delivery_supplier_required_fields'] != '' ? explode(",", smc_session()['default_setting'][$IsSales ? 'delivery_customer_required_fields' : 'delivery_supplier_required_fields']) : [];
?>
<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;
        /*font-size:12px;*/
        /*padding:0;*/
        /*padding-bottom:5px;*/
        height: 40px;
    }
    #InventoryPurchaseTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #InventoryPurchaseTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
    }
    #InvoiceVAT{
        display: inline-block;
        width: 92px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
        margin-left: 23px;
    }
    /*    #InventoryPurchaseTable .Hint{
    position: absolute;
    font-size: 10px;
    font-weight: bold;
    height: 20px;
    line-height: 20px;
    bottom: 2px;
    right: 4px;
    color: rgb(153, 153, 153);
    }*/
    #InventoryPurchaseTable .Hint{
        position: absolute;
        font-size: 10px;
        display: block;
        font-weight: bold;
        height: 12px;
        line-height: 11px;
        cursor: default;
        background: #ccc;
        padding: 0 2px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        bottom: 3px;
        right: 1px;
        left: 1px;
        color: #4c0870;
    }
    #InventoryPurchaseTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #InventoryPurchaseTable .Disc{
        width:70px;
    }
    #InventoryPurchaseTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    /*    .select2-container > .select2-choice{
    background-color: #e5e5e5;
    width: 150px;
    }*/
    #InventoryPurchaseTable .select2-container .select2-choice {
        background-image: none;
        border-radius: 2px;
        border: 1px solid rgba(0,0,0,0.07);
        padding: 5px 9px 16px;
        transition: border 0.2s linear 0s;
        height: 40px;
        background-color: #e5e5e5;
        width: 150px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    .hideme{
        display:none;
    }
    .select2-container > .select2-choice {
        width: 100% !important;
    }
    .supInv{
        display:inline-flex;
    }
    .invoice{
        padding-top:0 !important;
    }
    #Truck{
        width:48%;
        margin-right:2%
    }
    .right-div .form-group{
        margin-bottom:0px;
    }
</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.js?v=<?php echo trusto_VERSION; ?>"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.compatibility.js"></script>
<div id="PurchaseDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
<form method="POST" action="" onsubmit="return false" id="InvoiceForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id = "PurchaseSuccess" class = "hidden"></div>
                <div class = "invoice ">
                    <div class = "container-sm-height">
                        <div class = "row-sm-height">
                            <input type="hidden" name="current_invoice_type" id="current_invoice_type" value="<?php echo $current_invoice_type; ?>" />

                            <div class = "col-md-9 col-sm-height sm-no-padding">
                                <div class = "row " style = "display:flex;">
                                    <div class = "col-md-12"><h2 class = "font-montserrat all-caps hint-text"><?php echo $title; ?></h2></div>
                                </div>
                                <div class='row form-group'>
                                    <div class="input-group  col-md-4 center-margin pull-left " >
                                        <label><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer' : 'choose_supplier'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1" : "Inventory/ViewVendorList?is_pop=1" ?>" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="search_supplier full-width" id="search_supplier" name="search_supplier" type="hidden" value="<?= ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Main']['Person_ID'] : ( ''); ?>" data-select-name='<?= json_encode(($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Name'] : ""); ?>' />
                                    </div>
                                    <div class="input-group  col-md-3   pull-left <?php echo in_array('16', $fields_to_hide) ? 'hidden' : '' ?>" >
                                        <label><?php print CommonLanguage::getMessage('debit_account'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1" : "ACC/viewlibrary/1?is_pop=1" ?>" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="debit_acc_id full-width" id="debit_acc_id" name="debit_acc_id" type="hidden"  <?php echo in_array('1', $req_fields) ? 'required' : '' ?> value="<?= ($IsEdit) ? $edit_arr['Main']['debit_acc_id'] : ( ''); ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['Main']['debit_acc_name'] : ""); ?>' />
                                    </div>
                                    <div class="input-group  col-md-3    pull-left <?php echo in_array('15', $fields_to_hide) ? 'hidden' : '' ?>" >
                                        <label><?php print CommonLanguage::getMessage('credit_account'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1" : "ACC/viewlibrary/1?is_pop=1" ?>" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="credit_acc_id full-width" id="credit_acc_id" name="credit_acc_id" type="hidden"  <?php echo in_array('0', $req_fields) ? 'required' : '' ?> value="<?= ($IsEdit) ? $edit_arr['Main']['credit_acc_id'] : ( ''); ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['Main']['credit_acc_name'] : ""); ?>' />
                                    </div>

                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="SupplierInfo">
                                    <input type="hidden" name="Supplier_ID" value="<?php echo ($IsEdit || $is_order || $is_purchase) ? ($edit_arr['Main']['Person_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 || $is_order || $is_purchase) ? $edit_arr['Person']['Name'] : '' ?>'><?php echo ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Name'] : '' ?></span></strong>
                                        <div><strong><?php echo CommonLanguage::getMessage('company'); ?>: </strong><span class='Company'><?php echo ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Company'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('Email'); ?>: </strong><span class='Email'><?php echo ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Email'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('Phone'); ?>: </strong><span class='Phone'><?php echo ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Phone'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('address'); ?>: </strong><span class='Address'><?php echo ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Address'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('country'); ?>: </strong><?php echo ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Person']['Country_Name'] : '' ?></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($IsSales ? 'invoice' : 'purchase_voucher'); ?> #
                                <?php
                                echo $IsEdit ? $edit_arr['Main']['ID'] : '--';
                                ?></h4>
</div>-->
                                <!--<div  style="display: flex">-->
                                <div  class="form-group " >
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="PurchaseInvoiceDate" name="PurchaseInvoiceDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Date'] : $today); ?>" />
                                    <!--<span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>-->
                                </div>
                                <!--</div>-->
                                <div  id="depot" class="form-group " style="display: flex;">
                                    <div style="width: 48%;margin-right:2%;" class=" <?php echo $permissions->hasPermission('Depots') ? '':'hidden'; ?>" >

                                        <label><?php print CommonLanguage::getMessage('Depot'); ?></label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" <?php echo $permissions->hasPermission($IsSales ? 'change_invoice_depot' : 'change_depot') ? '' : 'disabled' ?> data-old="<?php echo $IsEdit ? $edit_arr['Main']['Depot_ID'] : ''; ?>" value="<?= ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Main']['Depot_ID'] : (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" data-select-name='<?= json_encode(($IsEdit || $is_order || $is_purchase) ? $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  <?php echo in_array('7', $fields_to_hide) ? 'hidden' : '' ?>" >
                                            <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 ($IsEdit || $is_purchase) ? ($edit_arr['Main']['Currency_ID'] == smc_session()['local_currency'] ? 'disabled' : '') : ($DefaultCurrencyID == smc_session()['local_currency'] ? 'disabled' : '') ?>  value="<?php echo ($IsEdit || $is_purchase) ? $edit_arr['Main']['current_rate'] : '' ?>" />
                                        </div>
                                    </div>
                                </div>
                                <div id="CurrencyIDContainer" class=" m-t-10 <?php echo $permissions->hasPermission($IsSales ? 'change_sales_delivery_cost' : 'change_pur_delivery_cost') ? '' : 'hidden' ?>" >
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo ($IsEdit || $is_purchase || $is_order) ? $edit_arr['Main']['Currency_Symbol'] : ''; ?>">
                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><strong><?php echo ($IsEdit || $is_purchase || $is_order) ? ($edit_arr['Main']['Currency_Name'] . ' - ' . $edit_arr['Main']['Currency_Symbol']) : smc_session()['local_currency_name'] .' - '.smc_session()['local_currency_code']  ?></strong></span>
                                                <input type="hidden"  value="<?php echo ($IsEdit || $is_purchase || $is_order) ? $edit_arr['Main']['Currency_ID'] : smc_session()['local_currency'] ?>" class="form-control " onkeyup="return false" onkeydown="return false" name="Currency_ID" required/>
                                            </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 && !in_array('10', $fields_to_hide) ? '' : 'hidden' ?>" style="width: 48%;margin-right:2%;" >
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" value="<?php echo ($IsEdit || $is_order || $is_purchase) ? (!empty($edit_arr['Main']['job_id']) ? $edit_arr['Main']['job_id'] : '') : '' ?>" data-select-name="<?= ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Main']['job_name'] : '' ?>"/>
                                    </div>
                                    <div class="<?php echo smc_session()['default_setting']['activate_project'] == 1 && !in_array('11', $fields_to_hide) ? '' : 'hidden' ?>" style="width: 50%;" >
                                        <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                        <input type="hidden" class="full-width" id="project_id" value="<?php echo (($IsEdit || $is_order || $is_purchase ) && !empty($edit_arr['Main']['project_id'])) ? $edit_arr['Main']['project_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_order || $is_purchase) ? $edit_arr['Main']['project_name'] : '' ?>"/>
                                    </div>

                                </div>
                                <div   class="form-group <?php echo in_array('12', $fields_to_hide) ? 'hidden' : '' ?>" style="display: flex;" >
                                    <div   class="form-group "  style="width: 48%;margin-right:2%;" >
                                        <label><?php echo CommonLanguage::getMessage('ref') ?></label>
                                        <input type="text" class="full-width form-control" id="delivery_ref" value="<?php echo ($IsEdit) ? $edit_arr['Main']['delivery_ref'] : '' ?>" />
                                    </div>
                                    <?php if (!$IsSales && $permissions->hasPermission('change_pur_delivery_cost')) { ?>
                                        <div   class="form-group <?php echo in_array('17', $fields_to_hide) ? 'hidden' : '' ?>"  style="width: 50%;">
                                            <label><?php print CommonLanguage::getMessage('cost_dist_method'); ?></label>
                                            <select id="cost_dist_method" class="full-width" data-init-plugin="select2">
                                                <option value="0" <?php echo ($IsEdit || $is_purchase) ? ($edit_arr['Main']['cost_dist_method'] == 0 ? 'selected' : '') : (smc_session()['default_setting']['cost_dist_method'] == 0 ? 'selected' : '') ?>><?php echo CommonLanguage::getMessage('Quantity') ?></option>
                                                <option value="1" <?php echo ($IsEdit || $is_purchase) ? ($edit_arr['Main']['cost_dist_method'] == 1 ? 'selected' : '') : (smc_session()['default_setting']['cost_dist_method'] == 1 ? 'selected' : '') ?>><?php echo CommonLanguage::getMessage('Price') ?></option>
                                                <option value="2" <?php echo ($IsEdit || $is_purchase) ? ($edit_arr['Main']['cost_dist_method'] == 2 ? 'selected' : '') : (smc_session()['default_setting']['cost_dist_method'] == 2 ? 'selected' : '') ?>><?php echo CommonLanguage::getMessage('maunual_percent') ?></option>
                                            </select>
                                        </div>
                                    <?php } ?>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <div id="ProdLoader" class="text-center alert <?php echo ($IsEdit || $is_order || $is_purchase) ? 'hideme' : '' ?>" style="height:100%;background-color:#E2DEEF"> <h3 ><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer_first' : 'choose_supplier_first'); ?> </h3> </div>
                        <table class="table  <?php echo ($IsEdit || $is_order || $is_purchase) ? '' : 'hideme' ?>" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center" style="width:5%"></th>
                                    <th class="text-center  <?php echo in_array('0', $fields_to_hide) ? 'hidden' : '' ?>" style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center  <?php echo in_array('1', $fields_to_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 || in_array('13', $fields_to_hide) ? 'hidden' : ''; ?>" style="width:6%"><?php print CommonLanguage::getMessage('Expiry_Date'); ?></th>
                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                    <th class="text-center  <?php echo in_array('2', $fields_to_hide) ? 'hidden' : '' ?>" style="width:7%"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th class="text-center <?php echo $permissions->hasPermission($IsSales ? 'change_sales_delivery_cost' : 'change_pur_delivery_cost') && !in_array('3', $fields_to_hide) ? '' : 'hidden' ?>" style="width:7%"><?php print CommonLanguage::getMessage('cost'); ?></th>
                                    <th class="text-center <?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>" style="width:12%"><?php print CommonLanguage::getMessage('additional_cost'); ?></th>
                                    <th class="text-center <?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>" style="width:12%"></th>
                                    <th class="text-center cost-cell <?php echo ($IsEdit || $is_purchase || $is_order) ? ((!empty($edit_arr['Main']['cost_dist_method']) && $edit_arr['Main']['cost_dist_method'] == 2 && !$IsSales && $permissions->hasPermission('change_pur_delivery_cost')) ? '' : 'hidden') : ((smc_session()['default_setting']['cost_dist_method'] == 2 && !$IsSales && $permissions->hasPermission('change_pur_delivery_cost')) ? '' : 'hidden') ?>" style="width:12%" ><?php print CommonLanguage::getMessage('cost_percent'); ?></th>

                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 0 || in_array('5', $fields_to_hide) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('lot'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 0 || in_array('6', $fields_to_hide) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('serial'); ?></th>
                                    <th class="text-center <?php echo in_array('4', $fields_to_hide) ?> " style="width:15%"><?php print CommonLanguage::getMessage('description'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit || $is_order || $is_purchase) {
                                    $data_array = $edit_arr['Details'];
                                    if (!empty($data_array)) {
                                        foreach ($data_array as $item) {
                                            $uoms = explode('/', $item['Product_UOM']);
//                                                                                    die(print_r($uoms));
                                            ?>
                                            <tr data-is-lot="<?php echo $item['is_lot'] ?>" data-is-serial="<?php echo $item['is_serial'] ?>" data-conv="<?php echo $item['uom_con'] ?>" data-qty="<?php echo $item['Product_Quantity'] ?>"
                                                data-id="<?php echo $item['Product_ID'] ?>"
                                                data-prod-status="<?php echo $item['Status_ID']; ?>"
                                                data-delivered="<?php echo ($is_order && !empty($item['total_delivered'])) ? $item['total_delivered'] : 0 ?>" data-order="<?php echo $is_order ? $item['Item_Quantity_Current'] : 0 ?>"
                                                data-order-entry="<?php echo $is_order ? $item['Entry_ID'] : ($IsEdit ? $item['order_detail_id'] : '') ?>"
                                                data-is-service="<?php echo $item['is_service'] ?>"
                                                data-cost-arr='<?php echo json_encode(($item['cost_arr']) ? $item['cost_arr'] : []) ?>'
                                                >
                                                <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest <?php echo ($is_order || $is_purchase) ? 'hidden' : '' ?>" style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                                <td class="  <?php echo in_array('0', $fields_to_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan" value = "<?php echo $item['Bar_Code'] ?>" <?php echo ($is_order || $is_purchase) ? 'disabled' : '' ?>></td>
                                                <td class=" <?php echo in_array('1', $fields_to_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item['Name'] ?>" <?php echo ($is_order || $is_purchase) ? 'disabled' : '' ?>><span class="Hint"></span></td>
                                                <td class="<?php echo smc_session()['default_setting']['activate_expiry_date'] == 0 || in_array('13', $fields_to_hide) ? 'hidden' : ''; ?> "><input  name="expiry_date"  class="full-width expiry_date <?php echo $item['is_expiry'] == 1 ? '' : 'hidden'; ?>" <?php echo ($is_purchase) ? 'disabled' : '' ?> value="<?php echo $item['is_expiry'] == 1 ? $item['expiry_date'] : ''; ?>" data-select-name="<?php echo $item['is_expiry'] == 1 ? $item['expiry_date'] : ''; ?>" type="<?php $IsSales ? 'hidden' : 'text'; ?>"/></td>
                                                <td><input type="text" class="form-control Quantity isnumber"  value = "<?php echo ($is_order && !empty($item['remaining'])) ? ($item['remaining']) : $item['Item_Quantity_Current'] ?>"  ><span class="Hint"><?php echo $is_order ? ('Del: ' . $item['total_delivered'] . ' / Rem: ' . ($item['remaining'])) : '' ?></span></td>
                                                <td class=" <?php echo in_array('2', $fields_to_hide) ? 'hidden' : '' ?>">
                                                    <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2"  <?php echo ($is_order || $is_purchase) ? 'disabled' : '' ?>>
                                                        <?php for ($i = 0; $i < count($uoms); $i++) { ?>

                                                            <option value="<?php echo $uoms[$i]; ?>" <?php echo $uoms[$i] == $item['UOM_ID'] ? 'selected' : '' ?>><?php echo $all_uom[$uoms[$i]]['UOM_Name']; ?></option>
                                                        <?php } ?>
                                                    </select>
                                                </td>
                                                <td class="<?php echo $permissions->hasPermission($IsSales ? 'change_sales_delivery_cost' : 'change_pur_delivery_cost') && !in_array('3', $fields_to_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control current_cost isnumber" value = "<?php echo $IsEdit ? $item['current_cost'] : $item['unit_cost'] ?>"   <?php echo ($is_order || $is_purchase) ? 'disabled' : '' ?> ></td>
                                                <td class="<?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>"><input type="text" class="form-control additional_cost isnumber"  value="<?php echo!empty($item['additional_cost']) ? $item['additional_cost'] : '' ?>"  ></td>
                                                <td class="<?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>"><span class="fa fa-pencil extra_icon"></span></td>

                                                <td class=" cost-cell <?php echo (!$IsSales && $edit_arr['Main']['cost_dist_method'] == 2 && $permissions->hasPermission('change_pur_delivery_cost')) ? '' : 'hidden' ?>"><input type="text" class="form-control cost_percent isnumber"  value="<?php echo!empty($item['cost_percent']) ? $item['cost_percent'] : '' ?>" <?php echo ($is_order || $is_purchase) ? 'disabled' : '' ?> ></td>

                                                <td class="<?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 0 || in_array('5', $fields_to_hide) ? 'hidden' : ''; ?>">
                                                    <input type="text" class="form-control lot_nb " value = "<?php echo $item['lot_nb'] ?>" <?php echo ( $is_purchase) ? 'disabled' : '' ?>>
                                                </td>
                                                <td class="<?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 0 || in_array('6', $fields_to_hide) ? 'hidden' : ''; ?>">
                                                    <input type="text" class="form-control serial_nb " value = "<?php echo $item['serial_nb'] ?>" <?php echo ($is_purchase) ? 'disabled' : '' ?>>
                                                </td>
                                                <td class=""><input type="text" class="form-control item_note <?php echo in_array('4', $fields_to_hide) ? 'hidden' : '' ?>" value = "<?php echo $item['product_description'] ?>"></td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    if (!$is_order && !$is_purchase) {
                                        ?>

                                        <tr data-conv="1">
                                            <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                            <td class="  <?php echo in_array('0', $fields_to_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan"></td>
                                            <td class=" <?php echo in_array('1', $fields_to_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 || in_array('13', $fields_to_hide) ? 'hidden' : ''; ?> "><input  name="expiry_date"  class="full-width expiry_date hidden" type="<?php $IsSales ? 'hidden' : 'text'; ?>"/></td>
                                            <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                            <td class=" <?php echo in_array('2', $fields_to_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 $permissions->hasPermission($IsSales ? 'change_sales_delivery_cost' : 'change_pur_delivery_cost') && !in_array('3', $fields_to_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control current_cost isnumber"   ></td>
                                            <td class="<?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>"><input type="text" class="form-control additional_cost isnumber"    ></td>
                                            <td class="<?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>"><span class="fa fa-pencil extra_icon"></span></td>

                                            <td class="cost-cell <?php echo (($IsEdit || $is_purchase) && !$IsSales && $edit_arr['Main']['cost_dist_method'] == 2 && $permissions->hasPermission('change_pur_delivery_cost')) ? '' : ( (!$IsEdit && !$is_purchase && !$IsSales && smc_session()['default_setting']['cost_dist_method'] == 2 && $permissions->hasPermission('change_pur_delivery_cost')) ? '' : 'hidden') ?>"><input type="text" class="form-control cost_percent "    ></td>

                                            <td class="<?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 0 || in_array('5', $fields_to_hide) ? 'hidden' : ''; ?>">
                                                <input type="text" class="form-control lot_nb  " value = "">
                                            </td>
                                            <td class="<?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 0 || in_array('6', $fields_to_hide) ? 'hidden' : ''; ?>">
                                                <input type="text" class="form-control serial_nb  " value = "">
                                            </td>
                                            <td class=""><input type="text" class="form-control item_note <?php echo in_array('4', $fields_to_hide) ? 'hidden' : '' ?>" ></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 in_array('0', $fields_to_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control AutoComplete CODE input-barcode-scan"></td>
                                        <td class=" <?php echo in_array('1', $fields_to_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 || in_array('13', $fields_to_hide) ? 'hidden' : ''; ?> "><input  name="expiry_date"  class="full-width expiry_date hidden" type="<?php $IsSales ? 'hidden' : 'text'; ?>"/></td>
                                        <td><input type="text" class="form-control Quantity isnumber"><span class="Hint"></span></td>
                                        <td class=" <?php echo in_array('2', $fields_to_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 $permissions->hasPermission($IsSales ? 'change_sales_delivery_cost' : 'change_pur_delivery_cost') && !in_array('3', $fields_to_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control current_cost isnumber"   ></td>
                                        <td class="<?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>"><input type="text" class="form-control additional_cost isnumber"    ></td>
                                        <td class="<?php echo ((!$IsSales && in_array(19, $fields_to_hide))) ? 'hidden' : ''; ?>"><span class="fa fa-pencil extra_icon"></span></td>
                                        <td class="cost-cell <?php echo (!$IsSales && smc_session()['default_setting']['cost_dist_method'] == 2 && $permissions->hasPermission('change_pur_delivery_cost')) ? '' : 'hidden' ?>"><input type="text" class="form-control cost_percent "    ></td>

                                        <td class="<?php echo smc_session()['default_setting']['activate_product_lot_nb'] == 0 || in_array('5', $fields_to_hide) ? 'hidden' : ''; ?>">
                                            <input type="text" class="form-control lot_nb  " value = "">
                                        </td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_product_serial_nb'] == 0 || in_array('6', $fields_to_hide) ? 'hidden' : ''; ?>">
                                            <input type="text" class="form-control serial_nb  " value = "">
                                        </td>
                                        <td class=""><input type="text" class="form-control item_note <?php echo in_array('4', $fields_to_hide) ? 'hidden' : '' ?>" ></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-8 col-sm-height   clearfix" style="border-left: 1px solid #eee;border-right: 1px solid #eee;padding-right:0">
                                <div class="col-sm-12  <?php echo in_array('14', $fields_to_hide) ? 'hidden' : ''; ?>" style="padding-right:0">
                                    <textarea id="invoice_note" name="invoice_note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>  ..." ><?php echo ($IsEdit || $is_order) ? $edit_arr['Main']['delivery_note'] : '' ?></textarea>
                                </div>
                            </div>
                            <div class="col-sm-4 col-sm-height  clearfix sm-p-b-15" style="text-align:center">
                                <div  class="col-md-6" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold  <?php echo (!$IsSales && $permissions->hasPermission('change_pur_delivery_cost') && !in_array('17', $fields_to_hide) ? '' : 'hidden') ?>"> <span id="main_extra_icon" class="fa fa-plus-circle <?php echo smc_session()['default_setting']['extra_cost_type'] == 1 ? '' : 'hidden' ?>" style="color: #8a7dbe;cursor: pointer;"></span>&nbsp;<?php print CommonLanguage::getMessage('extra_cost'); ?><input type="text" class="form-control ignore " id="extra_cost" value="<?php echo ($IsEdit || $is_purchase) ? (!$IsSales ? $edit_arr['Main']['extra_cost'] : 0 ) : 0 ?>" data-extra-cost="<?php echo ($is_purchase) ? (!$IsSales ? $edit_arr['Main']['extra_cost'] : 0 ) : 0 ?>" data-net="<?php echo ($is_purchase) ? (!$IsSales ? $edit_arr['Main']['Purchase_Net_Total'] : 0 ) : 0 ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('stock_delivery_nb'); ?><input type="text" class="form-control ignore " id="stock_delivery_nb" value="<?php echo ($IsEdit) ? $edit_arr['Main']['stock_delivery_nb'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('idf_nb'); ?><input type="text" class="form-control ignore " id="idf_nb" value="<?php echo ($IsEdit) ? $edit_arr['Main']['idf_nb'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('clearing_agent_name'); ?><input type="text" class="form-control ignore " id="clearing_agent_name" value="<?php echo ($IsEdit) ? $edit_arr['Main']['clearing_agent_name'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('clearing_inv_date'); ?><input type="text" class="form-control ignore " id="clearing_inv_date" value="<?php echo ($IsEdit) ? $edit_arr['Main']['clearing_inv_date'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('ceps_nb'); ?><input type="text" class="form-control ignore " id="ceps_nb" value="<?php echo ($IsEdit && !empty($edit_arr['Main']['ceps_nb'])) ? $edit_arr['Main']['ceps_nb'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('ccvr_nb'); ?><input type="text" class="form-control ignore " id="ccvr_nb" value="<?php echo ($IsEdit && !empty($edit_arr['Main']['ccvr_nb'])) ? $edit_arr['Main']['ccvr_nb'] : '' ?>"/> </h5>

                                </div>
                                <div  class="col-md-6" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold <?php echo in_array('9', $fields_to_hide) ? 'hidden' : '' ?>" > <?php print CommonLanguage::getMessage('shipping'); ?><input type="text" class="form-control ignore " id="Shipping" value="<?php echo ($IsEdit || $is_purchase) ? $edit_arr['Main']['shipping'] : 0 ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('stock_delivery_date'); ?><input type="text" class="form-control ignore " id="stock_delivery_date" value="<?php echo ($IsEdit) ? $edit_arr['Main']['stock_delivery_date'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('idf_date'); ?><input type="text" class="form-control ignore " id="idf_date" value="<?php echo ($IsEdit) ? $edit_arr['Main']['idf_date'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('clearing_inv_nb'); ?><input type="text" class="form-control ignore " id="clearing_inv_nb" value="<?php echo ($IsEdit) ? $edit_arr['Main']['clearing_inv_nb'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('container_deposit'); ?><input type="text" class="form-control ignore " id="container_deposit" value="<?php echo ($IsEdit) ? $edit_arr['Main']['container_deposit'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('ceps_date'); ?><input type="text" class="form-control ignore " id="ceps_date" value="<?php echo ($IsEdit && !empty($edit_arr['Main']['ceps_date'])) ? $edit_arr['Main']['ceps_date'] : '' ?>"/> </h5>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold   <?php echo!empty($invoice_type_details['show_fields']) ? '' : 'hidden' ?>" > <?php print CommonLanguage::getMessage('ccvr_date'); ?><input type="text" class="form-control ignore " id="ccvr_date" value="<?php echo ($IsEdit && !empty($edit_arr['Main']['ccvr_date'])) ? $edit_arr['Main']['ccvr_date'] : '' ?>"/> </h5>

                                </div>
                            </div>

                        </div>

                    </div>
                    <div class="container-sm-height" >
                    <button class=" btn btn-success-darker btn-cons m-b-10 pull-right disabled " id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="submit"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('submit'); ?></span></button>

                    <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled <?php // echo $IsEdit ? 'hidden' : '' ?>" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>
                   <!-- <button class=" btn btn-success-darker btn-cons m-b-10 pull-right disabled <?php echo $IsEdit ? 'hidden' : '' ?>" id="PrintBtn1" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print_delv'); ?></span></button>-->
                    </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="CustomerProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('confirm_customer_change') ?></p>
                        <p><?php print CommonLanguage::getMessage('proceed_change_price') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary yes-btn"  style="width:auto"><?php echo CommonLanguage::getMessage('yes') ?></button>
                <button type="button" class="btn btn-danger  pull-left no-btn"  data-dismiss="modal"><?php echo CommonLanguage::getMessage('no') ?> </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade bs-example-modal-md" data-backdrop="static" id="SupplierProceedModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"> </h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="confirm_change_customer_alert"></div>
                    <div class="col-md-12 ">
                        <p><?php print CommonLanguage::getMessage('confirm_supplier_change') ?></p>
                        <p><?php print CommonLanguage::getMessage('proceed_change_cost') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary supp-yes-btn"  style="width:auto"><?php echo CommonLanguage::getMessage('yes') ?></button>
                <button type="button" class="btn btn-danger  pull-left "  data-dismiss="modal"><?php echo CommonLanguage::getMessage('no') ?> </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade bs-example-modal-md" 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('dicount_inv_alert') ?></p>
                        <p><?php print CommonLanguage::getMessage('enter_new_disc') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary "  data-dismiss="modal" style="width:auto"><?php echo CommonLanguage::getMessage('proceed') ?></button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade " id="extra_cost_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content-wrapper">
            <div class="modal-content">
                <div class="modal-header clearfix text-left">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                    </button>
                    <h5 class="add-label bold"><?php echo CommonLanguage::getMessage('extra_cost') ?></h5>
                </div>
                <div class="modal-body">
                    <div id="extra_cost_alert"></div>
                    <div class="row ">

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

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

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

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

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

                </div>
            </div>
        </div>
    </div>
</div>
<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')); ?>,
            AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
            CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country')); ?>,
            FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb')); ?>,
            accountCodeLang = <?php echo json_encode(CommonLanguage::getMessage('account_code')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            account_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_account_first')); ?>,
            depot_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_depot_first')); ?>,
            supplier_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_supplier_first')); ?>,
            customer_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_customer_first')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            cost_percent_validate = <?php echo json_encode(CommonLanguage::getMessage('cost_percent_validate')); ?>,
            negative_sales = <?php echo json_encode(smc_session()['negative_sales']); ?>;
    var IsSalesMode = <?php echo $IsSales ? "true" : "false"; ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            is_order = <?php echo $is_order ? "true" : "false"; ?>,
            is_purchase = <?php echo $is_purchase ? "true" : "false"; ?>,
            is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
            ID_Edit = (IsEditMode) ? <?php echo json_encode($id); ?> : '',
            order_id = (is_order) ? <?php echo json_encode($id); ?> : '',
            purchase_id = (is_purchase) ? <?php echo json_encode($id); ?> : '',
            display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            second_currency = <?php echo json_encode(smc_session()['default_setting']['second_currency']); ?>,
            CurrencyRate = <?php echo json_encode($Extable); ?>,
            uom_arr = <?php echo json_encode($all_uom); ?>;
    var inv_nb = <?php echo json_encode(CommonLanguage::getMessage('order') . ' #'); ?>;
    var TotalInvoice = 0,
            TotalDiscount = 0,
            TotalInvoiceWithoutDiscount = 0, vatVal = 0, totalvat = 0, taxAmount = 0, is_td_total = 0,
            percent_flag = 0, total_qty = 0;
    var CheckSubmit = true,
            has_vat_permission = <?php echo $permissions->hasPermission($IsSales ? 'sales_vat' : 'purchase_vat') ? 'true' : 'false'; ?>,
            has_sales_cost_perm = <?php echo $permissions->hasPermission('view_sales_last_cost') ? 'true' : 'false'; ?>,
            has_purchase_cost_perm = <?php echo $permissions->hasPermission('view_purchase_last_cost') ? 'true' : 'false'; ?>,
            has_sales_last_price = <?php echo json_encode($permissions->hasPermission('view_sales_last_price')); ?>,
            allow_purchase_vat_edit = <?php echo json_encode(smc_session()['allow_purchase_vat_edit']); ?>,
            activate_lot = <?php echo json_encode(smc_session()['default_setting']['activate_product_lot_nb'] ? 0 : 1); ?>,
            activate_serial = <?php echo json_encode(smc_session()['default_setting']['activate_product_serial_nb'] ? 0 : 1); ?>,
            global_cost_arr = <?php echo json_encode(!$IsSales && ($IsEdit || $is_purchase) && !empty($edit_arr['extra_cost']) ? $edit_arr['extra_cost'] : array()) ?>, extra_cost_row = '';
    //    var CCustID = 0, CCustName = '';
    if (IsSalesMode) {
        $("#SupplierInv").removeClass("supInv")
        $("#SupplierInv").addClass("hideme")
    }

    $(window).ready(function (e) {
        $(window).scannerDetection({focusInputClass: 'input-barcode-scan', minLength: default_barcode_length});
        $(window).bind('scannerDetectionComplete', 'input.CODE', function (e, data) {
            ID = data.string;
            var parent = $(data.my_event.target).parents('tr')
            searchScannedItem(ID, parent);
        }).bind('scannerDetectionError', function (e, data) {
        }).bind('scannerDetectionReceive', function (e, data) {
        });
        //
    })
    $(function () {

        build_select2($(".search_supplier"), (IsSalesMode ? "xhr/customerSearch" : "xhr/supplierSearch") + (IsEditMode ? "?is_edited=" + $(".search_supplier").val() : "?Status_ID=1"));
        build_select2($(".Depot_Loc"), "xhr/depotSearch")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        build_select2($("#debit_acc_id,#credit_acc_id"), ("xhr/accIDSearch?type=Payment"))

        $("#cost_dist_method").on("change", function () {
            if ($(this).val() == 2) {
                $(".cost-cell").removeClass("hidden")
            } else {
                $(".cost-cell").addClass("hidden")
                $(".cost_percent").val(0)
            }
        })
        $("#extra_main_div").on("click", " .fa-plus-circle", function (e) {
            $("#extra_main_div  .fa-minus-circle").css("display", "inline-block")
            var Parent = $(this).parents(".extra_row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".select2-container").remove();
            NewItem.find('input').val('')
            NewItem.find("select.extra_cost_currency").val(0).select2()
            NewItem.find("select.extra_cost_type").val(0).select2()
            build_select2($(".extra_cost_debit_acc,.extra_cost_credit_acc", NewItem), ("xhr/accIDSearch?type=Payment"))

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

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

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

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

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

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

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

        $("#extra_cost_modal").on("modal.bs.modal", function () {
            $("#extra_cost_alert").addClass("hidden")
        })
        $("#CurrencyDropDown .dropdown-menu > li").on("click", function () {
            setTimeout(function () {
                trigger_proceed_extra_cost_currency();
//                $("#proceed_extra_cost").trigger("click")

                UpdateTable()
            }, 300)
            UpdateSubmitButtonStatus()
        })
        $("#InventoryPurchaseTable ").on("click", ".deleteRowRequest", function () {//to delete a row
            var numItems = $('#InventoryPurchaseTable tr').length;//number of rows
            if (numItems > 2) {//only if number of rows is more than one row remove the deleted row
                $(this).parents("tr").remove()
            }
        })
        $("#InventoryPurchaseTable").on("input", "input.current_cost,input.Quantity", function () {
            update_extra_cost()
        })
        $("#InventoryPurchaseTable").on("change", "select.UOM_ID", function () {
            var me = $(this).parents("tr");

            var UOMData = {pid: $(this).parents("tr").attr("data-id"),
                uid: $(this).val(), depot_id: $("#Depot_Loc").val()};
            $.ajax({
                url: "InventoryAjax/ReturnProductUOMPriceCon",
                data: UOMData,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        me.attr('data-conv', v1.responseJSON['conversion_amount'])

                        me.find("input.Quantity").next().text(AddCommas(parseFloat(v1.responseJSON['qty']).toFixed(3)) + " in stock")
                        UpdateSubmitButtonStatus()
                    }
                }
            })
        })



        $("#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 ($("#Depot_Loc").val() == '') {
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
            var Data = {
                id: $(this).val(),
                mode: IsSalesMode
            }
            $.ajax({
                url: "InventoryAjax/addPurchaseAjax",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        if (IsSalesMode) {
                            $("#SupplierInfoContent").empty();
                            var Content = "";
                            Content += "<strong><span class='Name' id='Supplier_Name' data-id='" + Data[0]['Customer_Name'] + "'>" + Data[0]['Customer_Name'] + "</span></strong>";
                            Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Customer_Company'] + "</span></div>";
                            Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Customer_Email'] + "</span></div>";
                            Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Customer_Phone'] + "</span></div>";
                            Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Customer_Address'] + "</span></div>";
                            Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                            Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                            Content += "<div id='Class_ID' style='display:none;'>" + Data[0]['Class_ID'] + "</div>";
                            Content += "<div id='Class_Currency' style='display:none;'>" + Data[0]['Class_Currency'] + "</div>";
                            $("#SupplierInfoContent").append(Content)
                            $("#Supplier_ID-error").remove()
                            $("#Supplier_ID").removeClass("error").val(Data[0]['Customer_ID']);

                        } else {
                            $("#SupplierInfoContent").empty();
                            var Content = "";
                            Content += "<strong><span class='Name' id='Supplier_Name' data-id='" + Data[0]['Supplier_Name'] + "'>" + Data[0]['Supplier_Name'] + "</span></strong>";
                            Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Supplier_Company'] + "</span></div>";
                            Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Supplier_Email'] + "</span></div>";
                            Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_Phone'] + "</span></div>";
                            Content += "<div><strong>" + 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']);
                        }
                    }
                }
            })
        })

        $("#PrintBtn").on("click", function () {
            var myurl = IsSalesMode ? "Inventory/ViewDeliveryNote/" + Invoice_ID + "/" + $("#Supplier_ID").val() : "Inventory/ViewDeliveryNote/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
            console.log(myurl);
            window.location.href = myurl;

            //printExternalInv(myurl, 'invoice_print_btn')
        })
        $("#PrintBtn1").on("click", function () {
            var myurl = IsSalesMode ? "Inventory/ViewDeliveryNote/" + Invoice_ID + "/" + $("#Supplier_ID").val() : "Inventory/ViewDeliveryNote/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
            //printExternalInv(myurl, 'delivery_print_btn')
        })
        $("#Depot_Loc").on("change", function () {
            var accName = $.trim($("#s2id_Account_Code").text());
            //alert($(this).val())
            $('#Account_CodeDiv').remove()

            if ($("#search_supplier").val() == '') {
                $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
            } else if ($("#Depot_Loc").val() == '') {
                //                alert()
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
            if ($(this).attr("id") == 'Depot_Loc') {
                var item_arr = {items: [], depot_id: $("#Depot_Loc").val()}
                $("#InventoryPurchaseTable tbody tr").each(function (e) {
                    if ($(this).attr("data-id") != 0) {
                        item_arr.items.push($(this).attr("data-id"))
                    }
                })
                $.ajax({
                    url: "InventoryAjax/ReturnQtyPerDepot",
                    data: item_arr,
                    dataType: 'json',
                    complete: function (v1, v2) {
                        if (v2 == "success") {
                            var Data = (v1.responseJSON);
                            $.each(Data, function (index, value) {
                                var me = $("#InventoryPurchaseTable tbody tr[data-id='" + value['Product_ID'] + "']"),
                                        tr_conv = parseFloat(me.attr("data-conv"));
                                me.find(".Quantity").next().text(AddCommas(parseFloat(value['qty'] / tr_conv).toFixed(3)) + " in stock")
                                me.find("input.ProductName").next().text(value['loc'])
                            })
                            UpdateSubmitButtonStatus()
                        }
                    }
                })
            }
        })
        if (!$("#InventoryPurchaseTable").hasClass('hideme')) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                EnableAutoComplete($(".AutoComplete.CODE", $(this)));
                EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
                if ($(this).attr('data-is-lot') == 1 && activate_lot == 1)
                    $("input.lot_nb", $(this)).removeClass("hidden");
                else
                    $("input.lot_nb", $(this)).addClass("hidden");

                if ($(this).attr('data-is-serial') == 1 && activate_serial == 1)
                    $("input.serial_nb", $(this)).removeClass("hidden");
                else
                    $("input.serial_nb", $(this)).addClass("hidden");

            });
        } else {
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.CODE"));
            EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.ProductName"));
        }
        $("#PurchaseInvoiceDate,#idf_date,#clearing_inv_date,#stock_delivery_date,#ceps_date,#ccvr_date").datepicker({autoclose: true});

        $("#InventoryPurchaseTable").delegate(".Quantity", "blur keydown", function (e) {
            var me = $(this), TR = me.parents("tr");
            if (e.which == 13 && e.type == "keydown") {
                if (me.hasClass("Quantity")) {
                    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")
                    }
                }
                //                else
                //                if (me.hasClass("Disc")) {
                //                    if (parseFloat($(this).val()) > parseFloat(me.parents("tr").attr("data-disc"))) {
                //                        $(this).val(me.parents("tr").attr("data-disc"))
                //                    }
                //                }

            }
            //            $("#InvoiceDiscountInput").trigger("keyup")
        });



        $("#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;
            //        if($(this).hasClass("total-td"))
            //            return;
            //        console.log('here')
            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
            $("tr", Parent).each(function (e) {
                if ($("tr", Parent).length > 1) {
                    var IsEmpty = true;
                    $(this).find("input").each(function () {
                        if ($(this).val() != "")
                            IsEmpty = false;
                    })
                    if (IsEmpty == true) {
                        if ($(this).index() <= $("#InventoryPurchaseTable tbody tr").length - 2) {
                            me.parents("tr").prev().find(".Disc").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input", Parent).each(function (e) {
                if ($(this).val() != "")
                    IsLastOneEmpty = false;
            })
            //            console.log(IsLastOneEmpty)
            if (IsLastOneEmpty == false && !is_order) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                ClonedRow.find("input").val("")
                ClonedRow.attr("data-conv", "1")
                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"));
                $(".Hint", ClonedRow).html("")
                //                $(".Hint", ClonedRow).html("")
                $("input", ClonedRow).removeClass("wrong")
                $("input.lot_nb,input.serial_nb", ClonedRow).addClass("hidden")
                $(".select2-container", ClonedRow).empty().remove()
                $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
                ClonedRow.removeAttr("data-id data-prod-status")
                $(".select2-container", ClonedRow).show()
            }
        })


        $("#InvoiceForm").validate({
            ignore: ".ignore",
            rules: {
                PurchaseInvoiceDate: {required: true, date: true},
                PurchaseInvoiceDueDate: {date: true},
                Currency_ID: {required: true}
            }
        })
        $("#InvoiceSubmitButton").on("click", ApplyPostMethod);
        UpdateSubmitButtonStatus()
        $("#CurrencyDropDown li").click(function () {
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            global_round = $(this).attr("data-round")
            cur_id = $(this).attr("value");
            if ($(this).attr("value") == local_currency) {
                $("#current_rate").val(1).attr("disabled", "disabled")
            } else
                $("#current_rate").val("").removeAttr("disabled")
        })
    });
    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.find("input.CODE").val(Data.Bar_Code)
                    TR.attr("data-prod-status", Data.Status_ID)
                    TR.find("input.ProductName").val(Data.Name)

                    var units_arr = Data.Product_UOM.split("/");
                    for (var i = 0; i < units_arr.length; i++) {
                        $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == Data.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                    }
                    $("select[name=UOM_ID]", TR).select2();
                    if (display_shelf_locations == 1) {
                        TR.find("input.ProductName").next().text(Data.loc);
                    }
                    if (event.which != 9)
                        TR.find("input.Quantity").focus().next().text(AddCommas(parseFloat(Data.stock_qty).toFixed(3)) + " in stock")
                    else
                        TR.find("input.Quantity").next().text(AddCommas(parseFloat(Data.stock_qty).toFixed(3)) + " in stock")
                    if (IsSalesMode) {
                        TR.find("input.Quantity").next().text(AddCommas(parseFloat(Data.stock_qty).toFixed(3)) + " in stock")
                    }
                    return false;
                }
            }
        })
    }

    function EnableAutoComplete(who) {
        if (IsSalesMode) {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function (request, response) {
                        //                        var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                        var depot_id = $("#Depot_Loc").val(),
                                customer_id = $("#search_supplier").val(),
                                product_id = who.parents('tr').attr('data-id'),
                                product_status_id = who.parents('tr').attr('data-prod-status'),
                                status_cond = !IsEditMode ? '&Status_ID=1' : (product_status_id == 0 ? ('&is_edited=' + product_id) : '&Status_ID=1');
                        $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2") + '&depot_id=' + depot_id + '&type=1&customer_id=' + customer_id + status_cond, request, function (s, status, xhr) {
                            response(s);
                            //                            getProducts
                        });
                    },
                    minLength: 0,
                    select: function (event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.ID)
                        TR.attr("data-qty", ui.item.Quantity)
                        TR.attr("data-prod-status", ui.item.Status_ID)
                        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)
                        $("select[name=UOM_ID]", TR).empty()

                        if (display_shelf_locations == 1) {
                            TR.find("input.ProductName").next().text(ui.item.loc);
                        }
                        if (ui.item.is_lot == 1 && activate_lot == 1)
                            TR.find(".lot_nb").removeClass("hidden");
                        else
                            TR.find(".lot_nb").addClass("hidden");

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

                        if (event.which != 9)
                            TR.find("input.Quantity").focus().next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                        else
                            TR.find("input.Quantity").next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                        TR.find("input.Quantity").next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                        var units_arr = ui.item.Product_UOM.split("/");
                        for (var i = 0; i < units_arr.length; i++) {
                            $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                        }
                        TR.find("select[name=UOM_ID]").select2();
                        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")
            }
        } else {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function (request, response) {
                        var depot_id = $("#Depot_Loc").val();
                        $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2") + '&depot_id=' + depot_id + '&type=2', 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.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)
                        $("select[name=UOM_ID]", TR).empty();

                        if (event.which != 9)
                            TR.find("input.Quantity").focus().next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                        else
                            TR.find("input.Quantity").next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                        if (display_shelf_locations == 1) {
                            TR.find("input.ProductName").next().text(ui.item.loc);
                        }
                        if (ui.item.is_lot == 1 && activate_lot == 1)
                            TR.find(".lot_nb").removeClass("hidden");
                        else
                            TR.find(".lot_nb").addClass("hidden");

                        if (ui.item.is_serial == 1 && activate_serial == 1)
                            TR.find(".serial_nb").removeClass("hidden");
                        else
                            TR.find(".serial_nb").addClass("hidden");
                        //                        TR.find("input.Quantity")/*.focus()*/.prev().text((ui.item.Quantity) + " in stock");
                        var units_arr = ui.item.Product_UOM.split("/");
                        for (var i = 0; i < units_arr.length; i++) {
                            $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                        }
                        $("select[name=UOM_ID]", TR).select2()
                        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")
            }
        }
        //        textarea can't remove character when used backspace
        //        $(document).keydown(function (e) {
        //            if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
        //                e.preventDefault()
        //            }
        //        })
    }
    function ApplyPostMethod() {
        $("#PurchaseSuccess").attr("class", "hidden");
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                    Data = {
                        Depot_ID: $("#Depot_Loc").val(),
                        IsSales: IsSalesMode ? 1 : 0,
                        is_actual: is_actual ? 1 : 0,
                        delivery_note: $("#invoice_note").val(),
                        job_id: $("#job_id").val(),
                        project_id: $("#project_id").val(),
                        Person_ID: $("#search_supplier").val(),
                        Delivery_Report_Date: $("#PurchaseInvoiceDate").val(),
                        delivery_ref: $("#delivery_ref").val(),
                        extra_cost: $("#extra_cost").val(),
                        shipping: $("#Shipping").val(),
                        stock_delivery_nb: $("#stock_delivery_nb").val(),
                        stock_delivery_date: $("#stock_delivery_date").val(),
                        idf_date: $("#idf_date").val(),
                        idf_nb: $("#idf_nb").val(),
                        clearing_agent_name: $("#clearing_agent_name").val(),
                        clearing_inv_nb: $("#clearing_inv_nb").val(),
                        clearing_inv_date: $("#clearing_inv_date").val(),
                        container_deposit: $("#container_deposit").val(),
                        cost_dist_method: $("#cost_dist_method").val(),
                        Currency_ID: $("#CurrencyDropDown input").val(),
                        current_rate: $("#current_rate").val(),
                        current_invoice_type: $("#current_invoice_type").val(),
                        ceps_date: $("#ceps_date").val(),
                        ceps_nb: $("#ceps_nb").val(),
                        ccvr_nb: $("#ccvr_nb").val(),
                        ccvr_date: $("#ccvr_date").val(),
                        debit_acc_id: $("#debit_acc_id").val(),
                        credit_acc_id: $("#credit_acc_id").val(),
                        extra_cost_arr: global_cost_arr,
                        Products: []
                    };
            if (IsEditMode) {
                Data.Delivery_Report_ID = ID_Edit;
            }
            if (is_order) {
                Data.order_id = order_id;
            }
            if (is_purchase) {
                Data.purchase_id = purchase_id;
            }
            var check_totals = false, total_cost_percent = 0, total_cost = 0;
            $("#InventoryPurchaseTable tbody tr").each(function (e) {
                var me = $(this);
                total_cost_percent += parseFloat(me.find(".cost_percent").val()) || 0;
                total_qty += parseFloat(me.find(".Quantity").val()) || 0;
                var item_cost = parseFloat(me.find(".current_cost").val()) || 0,
                        qty = parseFloat(me.find(".Quantity").val()) || 0,
                        total_tr_cost = (item_cost * qty);
                total_cost += total_tr_cost;
                if (me.find(".Quantity").val() != '' && me.find(".Quantity").val() != 0 && me.find(".ProductName").val() != '') {
                    Data.Products.push({
                        UOM_ID: me.find("select.UOM_ID").val(),
                        Product_ID: me.attr("data-id"),
                        Item_Quantity: qty,
                        product_description: me.find(".item_note").val(),
                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        item_cost: item_cost,
                        order_detail_id: me.attr("data-order-entry") || 0,
                        is_service: me.attr("data-is-service") || 0,
                        cost_percent: me.find(".cost_percent").val(),
                        total_cost: total_tr_cost,
                        cost_arr: me.attr("data-cost-arr"),
                        additional_cost: me.find("input.additional_cost").val(),
                    });
                    var delivered = parseFloat(me.attr("data-delivered") || 0),
                            ordered = parseFloat(me.attr("data-order") || 0),
                            cur_qty = parseFloat(me.find(".Quantity").val() || 0);
//                            console.log(delivered+'==='+cur_qty+'==='+(delivered + cur_qty)+'==='+ordered)
                    if ((delivered + cur_qty) > ordered && !IsEditMode && is_order)
                        check_totals = true;
//                    console.log(check_totals)
                    //                    }
                    me.find(".ProductName,.Quantity").each(function () {
                        if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                            $(this).addClass("wrong")
                            CheckSubmit = false;
                            IsValidated = false;
                        } else {
                            $(this).removeClass("wrong")
                        }
                    })
                    //                    console.log('data-id:'+me.attr("data-id")+'==uom'+me.find("select.UOM_ID").val())
                    if (me.attr("data-id") == '0' || me.attr("data-id") == '' || me.attr("data-id") == undefined || me.find("select.UOM_ID").val() == '') {
                        me.find(".CODE").addClass("wrong")
                        me.find(".ProductName").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }
//                    if (qty > parseFloat(me.find(".Quantity").attr("data-qty"))) {
//                        $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('delivered_exceed_purchased'); ?>');
//                        me.find(".Quantity").addClass("wrong")
//                        IsValidated = false;
//                        $(document.body).animate({scrollTop: 0}, 800)
//
//                    }

                }
            })
            Data.total_qty = total_qty;
            Data.total_cost = total_cost;

            if (!IsValidated)
                return;
            if (Data.Products.length == 0) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (check_totals) {
//                console.log('here')
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('delivered_exceeded_ordered'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if ($("#extra_cost").val() != '' && parseFloat($("#extra_cost").val()) > 0 && $("#cost_dist_method").val() == 2) {
                if (total_cost_percent != 100) {
                    $("#PurchaseSuccess").attr("class", "alert alert-danger").html(cost_percent_validate)
                    $(document.body).animate({scrollTop: 0}, 800)
                    return false;
                }

            }


            $("#PurchaseDisabler").show();
            $.ajax({
                url: IsEditMode ? "InventoryAjax/EditDeliveryNoteRequest" : "InventoryAjax/DeliveryNoteRequest",
                method: "POST",
                data: Data,
                dataType: 'json',

                complete: function (v1, v2) {
                   console.log(v1)
                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            //                            if (!IsEditMode) {
                            Invoice_ID = v1.responseJSON[1];
                            $("#PrintBtn,#PrintBtn1").removeClass("disabled")
                            //                            }
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                            $("#InvoiceSubmitButton").attr("disabled", "disabled")
                            CheckSubmit = true;
                        } else {
                            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseJSON)
                            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 UpdateSubmitButtonStatus() {
        var Rows = $("#InventoryPurchaseTable tbody tr"), DoDisable = false
        if (Rows.length > 0) {
            if (Rows.length == 1) {
                if ($.trim($("input.CODE", Rows).val()) != "" && $.trim($("input.ProductName", Rows).val()) != "" && $.trim($("input.Quantity", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }

        if (IsSalesMode) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                if (negative_sales == 0) {
                    if (parseFloat($(this).find(".Quantity").val()) > parseFloat($(this).attr('data-qty'))) {
                        DoDisable = true;
                    }
                }

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

    $(document).ready(function () {
        window.onbeforeunload = function (e) {
            if (!CheckSubmit) {
                var message = have_not_saved, e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }
    });
    function 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 update_extra_cost() {
        var total = 0,
                extra_cost_old = parseFloat($("#extra_cost").attr("data-extra-cost")) || 0,
                old_net = parseFloat($("#extra_cost").attr("data-net")) || 0,
                extra_cost = 0;

        $("#InventoryPurchaseTable tbody tr").each(function () {
            var qty = parseFloat($(this).find("input.Quantity").val()) || 0,
                    cost = parseFloat($(this).find("input.current_cost").val()) || 0;
            total += (qty * cost);
        })
        if (old_net < total)
            extra_cost = extra_cost_old;
        else
            extra_cost = (old_net - total) + extra_cost_old;

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

                $(".select2-container", NewItem).show();
            }
        })
    }
    function trigger_proceed_extra_cost_currency() {
        var current_rate = parseFloat($("#current_rate").val()) || 0;

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


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

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

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

        }

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

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


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

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