<?php 
if ($IsEdit && empty($edit_arr['Main']['Auto_ID'])) { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this sales purchase! 
        <br>
        This sales purchase is not available.
    </div>
<?php die(); } ?>
<style type="text/css">
    #InventoryPurchaseTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #InventoryPurchaseTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #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 .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 18px;
        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;
    }
    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;

    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .hideme{

        display:none;
    }
    .select2-container > .select2-choice {

        width: 100% !important;

    }
    .supInv{
        display:inline-flex;
    }
    .invoice{
        padding-top:0 !important;
    }

    .current_supplier{
        width:100%;
    }
</style>

<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<div id="PurchaseDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
<form method="POST" action="" 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  sm-padding-10">
                    <div class = "container-sm-height">
                        <div class = "row-sm-height">
                            <div class = "col-md-9 col-sm-height sm-no-padding">
                                <div class = "row " style = "display:flex;">
                                    <div class = "col-md-8">
                                        <h2 class = "font-montserrat all-caps hint-text"><?php echo CommonLanguage::getMessage($is_return ? 'add_sales_purchase_return' : 'add_sales_purchase');?> </h2>
                                    </div>

                                </div>

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

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

                                    </div> 


                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="SupplierInfo">
                                    <input type="hidden" name="Supplier_ID" value="<?php echo $IsEdit ? ($edit_arr['Main']['Customer_ID'] ) : '' ?>" required id="Supplier_ID" />
                                    <div id="SupplierInfoContent" class="<?php echo $IsEdit ? '' : 'hidden' ?>">
                                        <strong><span class='Name' id='Customer_Name' data-id='<?php echo $IsEdit ? $edit_arr['Person']['Name'] : '' ?>'><?php echo $IsEdit ? $edit_arr['Person']['Name'] : '' ?></span></strong>
                                        <div><strong><?php echo CommonLanguage::getMessage('company'); ?>: </strong><span class='Company'><?php echo $IsEdit ? $edit_arr['Person']['Company'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('Email'); ?>: </strong><span class='Email'><?php echo $IsEdit ? $edit_arr['Person']['Email'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('Phone'); ?>: </strong><span class='Phone'><?php echo $IsEdit ? $edit_arr['Person']['Phone'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('address'); ?>: </strong><span class='Address'><?php echo $IsEdit ? $edit_arr['Person']['Address'] : '' ?></span></div>
                                        <div><strong><?php echo CommonLanguage::getMessage('country'); ?>: </strong><?php echo $IsEdit ? $edit_arr['Person']['Country_Name'] : '' ?></div>
                                        <div id='Finance_Account' data-id='<?php echo $IsEdit ? $edit_arr['Person']['Account_ID'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('financial_nb'); ?>: </strong><?php echo $IsEdit ? $edit_arr['Person']['Account_Code'] : '' ?></div>
                                        <div id='Class_ID' style='display:none;'><?php echo $IsEdit ? $edit_arr['Person']['Class_ID'] : '' ?></div>
                                        <div id='Class_Currency' style='display:none;'><?php echo $IsEdit ? $edit_arr['Person']['Class_Currency'] : '' ?></div>

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

                                </div>
                            </div>
                            <div class="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('invoice'); ?> #
                                        <?php
                                        echo $IsEdit ? $edit_arr['Main']['ID'] : '--';
                                        ?></h4>
                                </div>

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

                                <div  id="depot" class="form-group " >

                                    <div class="input-group m-b" >
                                        <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>
                                        <div class="input-group" style="    width: 311px;">
                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-primary"><i class="fa fa-certificate"></i> </button> </span>
                                            <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" data-old="<?php echo $IsEdit ? $edit_arr['Main']['Depot_ID'] : ''; ?>" value="<?= $IsEdit ? $edit_arr['Main']['Depot_ID'] : (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" data-select-name='<?= json_encode($IsEdit ? $all_depots[$edit_arr['Main']['Depot_ID']]['Depot_Name'] : (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name'])) ?>' />

                                        </div>
                                    </div>

                                </div>

                                <div id="CurrencyIDContainer" class=" m-t-10" >
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo $IsEdit ? $edit_arr['Main']['Currency_Symbol'] : ''; ?>">
                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><strong><?php echo $IsEdit ? ($edit_arr['Main']['Currency_Name'] . ' - ' . $edit_arr['Main']['Currency_Symbol']) : CommonLanguage::getMessage('select') ?></strong></span>
                                                <input type="hidden"  value="<?php echo $IsEdit ? $edit_arr['Main']['Currency_ID'] : $DefaultCurrencyID ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID"/>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <?php echo $CurList ?>
                                                <li class="divider"></li>
                                                <li><a class="LoadMore">More..</a></li>
                                            </ul>
                                        </div>

                                    </div>
                                </div>

                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <div id="ProdLoader" class="text-center alert <?php echo ($IsEdit) ? 'hideme' : '' ?>" style="height:100%;background-color:#E2DEEF"> <h3 ><?php print CommonLanguage::getMessage('choose_customer_first'); ?> </h3> </div>
                        <table class="table m-t-50 <?php echo ($IsEdit) ? '' : 'hideme' ?>" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"style="width:5%"></th>
                                    <th class="text-center"style="width:15%"><?php print CommonLanguage::getMessage('barcode'); ?></th>
                                    <th class="text-center" style="width:14%"><?php print CommonLanguage::getMessage('product_name'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center" style="width:8%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                    <th class="text-center" style="width:6%"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th class="text-center" style="width:9%"><?php print CommonLanguage::getMessage('unit_price'); ?></th>

                                    <th class="text-center" style="width:9%"><?php print CommonLanguage::getMessage('Description'); ?></th>
                                    <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('discount_percent'); ?></th>
                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('vat'); ?></th>
                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('vat_percent'); ?></th>
                                    <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('supplier'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/ViewVendorList?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center" style="width:9%"><?php print CommonLanguage::getMessage('Cost'); ?></th>
                                    <th class="text-center"style="width:10%"><?php print CommonLanguage::getMessage('total'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit) {
                                    $data_array = $edit_arr['Details'];
                                    foreach ($data_array as $item) {
                                        $uoms = explode('/', $item['Product_UOM']);
                                        //                                        die(print_r($uoms));
                                ?>

                                <tr data-conv="<?php echo $item['uom_con'] ?>" data-qty="<?php echo $item['Product_Quantity'] ?>" data-vat="<?php echo $item['VAT'] ?>" data-id="<?php echo $item['Product_ID'] ?>" data-prod-status="<?php echo $item['Status_ID'] ?>" unit_price="<?php echo $item['Product_Net_Price'] ?>">
                                    <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                    <td><input type="text" class="form-control AutoComplete CODE" value = "<?php echo $item['Code'] ?>"></td>
                                    <td><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item['Name'] ?>"></td>
                                    <td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber" value = "<?php echo $item['Item_Quantity_Current'] ?>"></td>
                                    <td>
                                        <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                            <?php for ($i = 0; $i < count($uoms); $i++) { ?>
                                            <option value="<?php echo $uoms[$i]; ?>" <?php echo $uoms[$i] == $item['UOM_ID'] ? 'selected' : '' ?>><?php echo $all_uom[$uoms[$i]]['UOM_Name']; ?></option>
                                            <?php } ?>
                                        </select>
                                    </td>
                                    <td><span class="Hint"></span><input type="text" class="form-control UnitPrice isnumber" value = "<?php echo $item['Product_Net_Price'] ?>" ></td>
                                    <td><span class=""></span><input type="text" class="form-control description" value = "<?php echo $item['product_description'] ?>" ></td>
                                    <!--
<td><span class="Hint"></span><input type="text" class="form-control" value = "" ></td>
<td><span class="Hint"></span><input type="text" class="form-control CostPrice isnumber" value = "" ></td>
<td><span class="Hint"></span><input type="text" class="form-control description isnumber" value = "" ></td>
-->
                                    <td><input type="text" class="form-control Disc" <?php echo!$permissions->hasPermission('sales_discount_on_item') ? 'disabled' : '' ?> value = "<?php echo $item['Product_Discount'] ?>"></td>
                                    <td><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission('sales_vat') && ($item['VAT'] == 1 || smc_session()['allow_purchase_vat_edit'] == 1)) ? '' : 'disabled' ?> value="<?php echo $item['vat_amount'] ?>"></td>
                                    <td><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission('sales_vat') && ($item['VAT'] == 1 || smc_session()['allow_purchase_vat_edit'] == 1)) ? '' : 'disabled' ?> value="<?php echo $item['vat_percent'] ?>"  ></td>
                                    <td><span class=""></span><input class="current_supplier" name="current_supplier" type="hidden" value = "<?php echo $item['Supplier_ID'] ?>" data-select-name="<?php echo $item['Supplier_Name'] ?>"></td>
                                    <td><span class=""></span><input type="text" class="form-control CostPrice " value = "<?php echo $item['cost_price'] ?>" ></td>
                                    <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                </tr>
                                <?php
                                    }
                                } else {
                                ?>
                                <tr data-conv="1">
                                    <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                    <td><input type="text" class="form-control AutoComplete CODE"></td>
                                    <td><input type="text" class="form-control AutoComplete ProductName"></td>
                                    <td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber"></td>
                                    <td>
                                        <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><span class="Hint"></span><input type="text" class="form-control UnitPrice isnumber"  ></td>

                                    <td><span class=""></span><input type="text" class="form-control description" value = "" ></td>
                                    <td><input type="text" class="form-control Disc" <?php echo!$permissions->hasPermission('sales_discount_on_item') ? 'disabled' : '' ?> value=""></td>
                                    <td><input type="text" class="form-control VATPerItem " <?php echo ($permissions->hasPermission('sales_vat') && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?> value=""></td>
                                    <td><input type="text" class="form-control vat_percent " <?php echo ($permissions->hasPermission('sales_vat') && smc_session()['allow_purchase_vat_edit'] == 1) ? '' : 'disabled' ?> ></td>
                                    <td><span class=""></span><input class="current_supplier" name="current_supplier" type="hidden" value = "" ></td>
                                    <td><span class=""></span><input type="text" class="form-control CostPrice " value = "" ></td>
                                    <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-6 col-sm-height col-middle  clearfix" style="border-left: 1px solid #eee;padding-left: 6px;border-right: 1px solid #eee;padding-right:0">
                                <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></h5>
                                <div id="InvoicePaymentSetup" class="no-print">
                                    <div class="Body">
                                        <div class="">
                                            <ul class="nav nav-tabs">
                                                <li class="active"><a data-toggle="tab" href="#SetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash'); ?></a></li>
                                                <li><a data-toggle="tab" href="#SetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check'); ?></a></li>
                                                <li><a data-toggle="tab" href="#SetPaidFormTab_3"><i class="fa fa-cc-visa"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('credit_card'); ?></a></li>
                                            </ul>
                                            <div class="tab-content" style="padding:0;overflow:visible">
                                                <div id="SetPaidFormTab_1" class="tab-pane fade in active">
                                                    <table class="table" cellpadding="0" cellspacing="0">
                                                        <tbody>
                                                            <tr>
                                                                <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                <td>
                                                                    <div class="input-group InputSpinner" style="width:120px">
                                                                        <input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['Transaction_Amount'] : '0' ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                        <div class="input-group-btn-vertical">
                                                                            <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                            <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                        </div>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
                                                                <td style="text-align:center">
                                                                    <input class="cash_account full-width" id="cash_account" name="cash_account" type="hidden"  value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['Account_ID'] : smc_session()['user_accounts']['cash_account_id'] ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['P_Name'] : smc_session()['user_accounts']['c_name'] ?>' />
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                                <div id="SetPaidFormTab_2" class="tab-pane fade in">
                                                    <table class="table" cellpadding="0" cellspacing="0">
                                                        <tbody>
                                                            <tr>
                                                                <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                <td>
                                                                    <div class="input-group InputSpinner" style="width:120px">
                                                                        <input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Transaction_Amount'] : "0" ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                        <div class="input-group-btn-vertical">
                                                                            <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                            <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                        </div>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
                                                                <td style="text-align:center">
                                                                    <!--                                                                    <div class="input-group-btn DropDownForForms Closable">-->
                                                                    <input class="check_account full-width" id="check_account" name="check_account" type="hidden" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Account_ID'] : smc_session()['user_accounts']['cheque_account_id'] ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['P_Name'] : "" ?>' />

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

                                                                    <!--                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span><?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" class="form-control" onkeyup="return false" onkeydown="return false"/>
</button>
<ul class="dropdown-menu">
<?php for ($x = 0; $x < count($CreditCards); $x++) { ?>
<li value="<?php echo $CreditCards[$x]["Account_Code"]; ?>"><a><?php echo $CreditCards[$x]["Payment_Type_Name"]; ?></a></li>
<?php } ?>
</ul>-->
                                                                    <!--                                                                    </div>-->
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check'); ?>#</span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control CheckNumValue" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['check_nb'] : '' ?>" /></td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check_due_date'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control check_due_date" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['due_date'] : '' ?>"/></td>
                                                                </tr>
                                                            <!--                                                            <tr>
<td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('approval_code'); ?></span></td>
<td style="text-align:center"><input type="text" class="form-control CardApproval" /></td>
</tr>-->
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3 col-sm-height col-middle clearfix sm-p-b-15" style="text-align:center">
                                <div  class="col-md-12" style="text-align: left;display: inline-block;">
                                    <h5 class="hidden font-montserrat all-caps small no-margin hint-text bold p-b-10" > <?php print CommonLanguage::getMessage('shipping_code'); ?>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>

                                        <input class=" full-width hidden" id="Shipping_Code" name="Shipping_Code" type="hidden" value=""  /></h5>


                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold p-b-10" > <?php print CommonLanguage::getMessage('shipping'); ?><input type="text" class="form-control ignore" id="Shipping" value="0"/> </h5>

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

                                    <!--<h3 class="no-margin"><span class="CurrencyIndicator"></span>&nbsp;<span id="InvoiceTotalAfterDiscount">0</span></h3>-->
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('item_discount'); ?></h5>
                                    <h3 class="no-margin"><span class="CurrencyIndicator"></span>&nbsp;<span id="DiscountVal">0</span></h3>
                                </div>
                            </div>
                            <div class="col-sm-3 text-right bg-menu col-sm-height padding-15" style="text-align:left !important">
                                <div style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseInvoiceTotalDetails">0</span></h1>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_paid'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseInvoiceTotalPaid">0</span></h1>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('taxable_amount'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PurchaseTaxableAmount">0</span></h1>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="container-sm-height" >

                        <button class=" btn btn-primary btn-cons m-b-10 pull-right " id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>

                        <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled <?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 class="pull-right form-group" style="margin-right: 42px;">
<div class="input-group"><label><?php print CommonLanguage::getMessage('pending'); ?></label></div>


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


<div class="modal fade bs-example-modal-md" data-backdrop="static" id="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>

<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')); ?>,
                                                                default_vat = <?php echo json_encode(smc_session()['vat_percent']); ?>,
                                                                    negative_sales = <?php echo json_encode(smc_session()['negative_sales']); ?>;
                                                                    var is_return = <?php echo $is_return ? "true" : "false"; ?>,
                                                                        IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>;
                                                                        var CurrencyRate = <?php echo json_encode($Extable); ?>,
                                                                            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
                                                                                max_discount = <?php echo json_encode(smc_session()['user_accounts']['max_discount']); ?>,
                                                                                local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
                                                                                uom_arr = <?php echo json_encode($all_uom); ?>;
                                                                            var inv_nb = <?php echo json_encode(CommonLanguage::getMessage('invoice_nb')); ?>;
                                                                            var TotalInvoice = 0,
                                                                                TotalDiscount = 0,
                                                                                TotalInvoiceDisounted = 0,
                                                                                TotalInvoiceWithoutDiscount = 0, vatVal = 0, totalvat = 0, taxAmount = 0, percent_flag = 0, global_round = <?php echo json_encode($currency_round); ?>;
                                                                            var CheckSubmit = true,
                                                                                has_vat_permission = <?php echo $permissions->hasPermission('sales_vat') ? 'true' : 'false'; ?>,
                                                                                allow_purchase_vat_edit = <?php echo json_encode(smc_session()['allow_purchase_vat_edit']); ?>;

                                                                            $(function () {
                                                                            if(IsEditMode){
                                                                            build_select2($(".search_supplier"), ("xhr/customerSearch?is_edited="+$(".search_supplier").val()))
    }else{
                                                                            build_select2($(".search_supplier"), ("xhr/customerSearch?Status_ID=1"))                                                                   
    }


                                                                            build_select2($("#Account_Code"), ("xhr/accIDSearch?type=sales"))
                                                                            build_select2($("#Shipping_Code"), ("xhr/accIDSearch?type=sales"))
                                                                            build_select2($(".Depot_Loc"), "xhr/depotSearch")
                                                                            build_select2($("#cash_account"), ("xhr/accIDSearch?type=cash"))
                                                                            build_select2($("#check_account"), ("xhr/accIDSearch?type=check"))
                                                                            build_select2($("#credit_account"), ("xhr/accIDSearch?type=credit_card"))
                                                                            build_select2($("#pricing_class"), "xhr/PricingClassSearch")
                                                                            apply_autocomplete($("#inv_truck"), 'xhr/searchInvTruck', function (event, ui, who) {
                                                                            who.val(ui.item.truck);
    });
                                                                            $("#InventoryPurchaseTable tr input[name=current_supplier]").each(function () {
                                                                            build_select2($(this), "xhr/supplierSearch?"+($(this).val() ? "is_edited="+$(this).val() : "Status_ID=1"))   
                                                                            
    })
                                                                            //        new Switchery($("#pending").get(0), {color: $.Pages.getColor("primary")})
                                                                            $(".CurrencyIndicator").html($("#CurrencyDropDown").attr("data-symbol"))

                                                                            $("#InventoryPurchaseTable ").on("click", ".deleteRowRequest", function () {//to delete a row
                                                                            var numItems = $('#InventoryPurchaseTable tr').length;//number of rows
                                                                            if (numItems > 2) {//only if number of rows is more than one row remove the deleted row
                                                                            $(this).parents("tr").remove()
                                                                            $(".Quantity").trigger('keyup')
    }
    })
                                                                            $("#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(), class_id: $("#pricing_class").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.UnitPrice").val(v1.responseJSON['Product_Price'])
                me.find("input.UnitPrice").val(parseFloat(ConvertCurrency2(v1.responseJSON['Product_Price'], v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val())).toFixed(3))

                me.find("input.Quantity").prev().text(AddCommas(parseFloat(v1.responseJSON['qty']).toFixed(3)) + " in stock")
                setTimeout('UpdateTable()', 100)
            }
        }
    })


    })




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

                    var data = v1.responseJSON;
                    $("#Class_Currency").html(data['Currency_ID']);

                }
            }
        })

    })
    $("#pricing_class").on("select2-selecting", function (e) {
        var flag = false;
        //            console.log(e.val)
        if (e.val == undefined)
            return false;
        if ($(this).val() != '' && e.val != $(this).val()) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                if ($(this).attr("data-id") != 0 && $(this).attr("data-id") != undefined) {
                    flag = true;
                }
            })
        }
        if (flag) {
            $("#CustomerProceedModal").modal("show")
        }
    })
    $(".yes-btn").on("click", function () {
        var item_arr = {items: [], class_id: $("#pricing_class").val()}
        $("#InventoryPurchaseTable tbody tr").each(function (e) {
            if ($(this).attr("data-id") > 0) {
                item_arr.items.push({pid: $(this).attr("data-id"), uid: $("select[name=UOM_ID]",$(this)).val()})
            }
        })
        $.ajax({
            url: "InventoryAjax/ReturnPriceByClass",
            data: item_arr,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    var Data = (v1.responseJSON);
                    for (var i = 0; i < Data.length; i++) {
                        var me = $("#InventoryPurchaseTable tbody tr[data-id='" + Data[i]['Product_ID'] + "']");
                        //                            me.find("input.UnitPrice").val(Data[i]['Product_Price'])
                        me.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? Data[i]['Product_Price'] : ConvertCurrency2(Data[i]['Product_Price'], $("#Class_Currency").text(), $("#CurrencyDropDown input").val()).toFixed(2))

                    }
                    UpdateTable()
                }
            }
        })
        $("#CustomerProceedModal").modal("hide")
    })
    $("#search_supplier").on("change", function () {
        $("#SupplierInfoContent").removeClass('hidden')
        if ($(this).val() == '') {
            $("#ProdLoader > h3").empty().html(customer_firstLang)
            $("#ProdLoader").removeClass("hideme")
            $("#InventoryPurchaseTable").addClass("hideme")
        } else
            if ($("#Account_Code").val() == '') {
                $("#ProdLoader > h3").empty().html(account_firstLang)
            } else if ($("#Depot_Loc").val() == '') {
                $("#ProdLoader > h3").empty().html(depot_firstLang)
                $("#ProdLoader").removeClass("hideme")
                $("#InventoryPurchaseTable").addClass("hideme")
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }
        var Data = {
            id: $(this).val(),
            mode: true
        }

        $.ajax({
            url: "InventoryAjax/addPurchaseAjax",
            data: Data,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    var Data = (v1.responseJSON);

                    $("#SupplierInfoContent").empty();
                    var Content = "";
                    Content += "<strong><span class='Name' id='Customer_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']);
                    $("#InvoiceDiscountInput").val(Data[0]['Customer_Discount']);
                    $("#pricing_class").val(Data[0]['Class_ID'])
                    $("#pricing_class").attr("data-select-name", Data[0]['Class_Name'])
                    build_select2($("#pricing_class"), "xhr/PricingClassSearch")
                    $("#pricing_class").trigger("change")
                    $("#pricing_class").trigger("select2-selecting")
                    //                            $("#CurrencyDropDown button span strong").html(Data[0]['Cur_Name'])
                    //                            $("#CurrencyDropDown button span strong").html(Data[0]['Cur_Name'] + ' - ' + Data[0]['Cur_Symbol'])
                    //                            $("#CurrencyDropDown button input").val(Data[0]['Class_Currency'])
                    //                            $(".CurrencyIndicator").html(Data[0]['Cur_Symbol'])


                }
            }
        })

    })
    $("#CurrencyDropDown .dropdown-menu > li").on("click", function () {
        setTimeout(function () {
            UpdateTable()
        }, 300)
    })

    $("#PrintBtn").on("click", function () {
        var myurl = "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val();
        printExternal(myurl, 'invoice_print_btn')
    })
    $("#PrintBtn1").on("click", function () {
        var myurl = "Inventory/ViewInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val();
        printExternal(myurl, 'delivery_print_btn')
    })
    $("#Account_Code,#Depot_Loc").on("change", function () {
        var accName = $.trim($("#s2id_Account_Code").text());
        //alert($(this).val())
        $('#Account_CodeDiv').remove()
        var Content = "";
        if ($("#Account_Code").val() != 0) {
            Content += "<div id='Account_CodeDiv' value='" + $("#Account_Code").val() + "'><strong>" + accountCodeLang + ": </strong>" + accName + "</div>";
            $("#SupplierAccInfo").append(Content).removeClass('hidden')
        }
        if ($("#Account_Code").val() == '') {

            $("#ProdLoader > h3").empty().html(account_firstLang)
            $("#ProdLoader").removeClass("hideme")
            $("#InventoryPurchaseTable").addClass("hideme")
        } else
            if ($("#search_supplier").val() == '') {

                $("#ProdLoader > h3").empty().html(customer_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'])
                        })
                    }
                }
            })
        }

    })


    if (!$("#InventoryPurchaseTable").hasClass('hideme')) {
        $("#InventoryPurchaseTable tbody tr").each(function () {
            EnableAutoComplete($(".AutoComplete.CODE", $(this)));
            EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
        });
    } else {
        EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.CODE"));
        EnableAutoComplete($("#InventoryPurchaseTable .AutoComplete.ProductName"));
    }

    $("#PurchaseInvoiceDueDate,#PurchaseInvoiceDate").datepicker({autoclose: true}).on("changeDate", function (e) {
        $(this).keyup();
    })
    $("#InventoryPurchaseTable tbody").on("keyup", ".vat_percent,.VATPerItem", function (e) {
        var cur_tr_vat = parseFloat($(this).val()) || 0,
            cur_tr_total = parseFloat($(this).parents("tr").find("span.Total").attr("myval")) || 0;
        if ($(this).hasClass("vat_percent")) {
            var cur_val = cur_tr_total * cur_tr_vat / 100;
            $(this).parents("tr").find(".VATPerItem").val(cur_val ? cur_val : '')
            setTimeout("UpdateTable()", 100);
        } else {
            var cur_val = cur_tr_vat / cur_tr_total * 100;
            $(this).parents("tr").find(".vat_percent").val(cur_val ? cur_val : '')
            $(this).parents("tr").find(".vat_percent").trigger("keyup")
        }

    })

    $("#InventoryPurchaseTable").delegate(".Quantity,.UnitPrice,.Disc", "blur keyup", function (e) {

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

        if (me.hasClass("Quantity")) {
            if (parseFloat(me.val()) > parseFloat(TR.attr('data-qty'))) {
                me.addClass("wrong")

            }

        }
        if (me.hasClass("Disc")) {
            if (parseFloat(me.val()) > parseFloat(max_discount)) {
                me.addClass("wrong")

            }

        }


        //            $("#InvoiceDiscountInput").trigger("keyup")
    });
    if (IsEditMode)
        $(".Quantity").trigger('keyup')
    $("#InvoiceDiscountInput").on(" keyup", function () {
        //            if (percent_flag != 2) {
        //            percent_flag = 1;
        $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($(this).val()) / 100) || 0)
        TotalInvoiceDisounted = TotalInvoice - parseFloat($("#TotalDiscAmount").val());
        setTimeout("checkTotals()", 100)
        //            }
    })
    $("#Shipping,#TotalDiscAmount").on("keyup", function () {
        if ($(this).attr("id") == 'TotalDiscAmount') {
            //                       console.log('percent_flag = '+percent_flag)   
            //
            //                if (percent_flag != 1) {
            //                      console.log(TotalInvoice)
            //                    console.log(parseFloat($(this).val())+' / '+TotalInvoice+' * 100 = '+(parseFloat($(this).val()) / TotalInvoice * 100))
            //                percent_flag = 2;
            $("#InvoiceDiscountInput").val((parseFloat($(this).val()) / TotalInvoice * 100) || 0)
            TotalInvoiceDisounted = TotalInvoice - parseFloat($(this).val());
            //                }
        }
        setTimeout("checkTotals()", 100)
    })
    $("#InventoryPurchaseTable tbody").delegate("> tr input", "keydown", function (e) {
        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) {
        var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
        $("tr", Parent).each(function (e) {
            if ($("tr", Parent).length > 1) {
                var IsEmpty = true;
                $(this).find("input").each(function () {
                    if ($(this).val() != "")
                        IsEmpty = false;
                })
                if (IsEmpty == true) {
                    if ($(this).index() <= $("#InventoryPurchaseTable tbody tr").length - 2) {
                        me.parents("tr").prev().find(".Disc").focus()
                        $(this).remove();
                    }
                }
            }
        })
        $("tr:last-child input", Parent).each(function (e) {
            if ($(this).val() != "")
                IsLastOneEmpty = false;
        })
        if (IsLastOneEmpty == false) {
            var ClonedRow = $("tr:first-child", Parent).clone()
            ClonedRow.find("input").val("")
            ClonedRow.attr("data-conv", "1")
            ClonedRow.attr("data-id", "0")
            Parent.append(ClonedRow);
            EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
            EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
            ClonedRow.removeAttr("data-prod-status")
            $(".Hint,.Total", ClonedRow).html("")
            $("input", ClonedRow).removeClass("wrong")
            $(".select2-container", ClonedRow).empty().remove()
            $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
            //                    $(".select2-container.current_supplier", ClonedRow).empty().remove()
            build_select2($("input[name=current_supplier]", ClonedRow), "xhr/supplierSearch?Status_ID=1")
            $(".select2-container.current_supplier", ClonedRow).css({display: 'block'})
            //                $(".deleteRowRequest").removeClass("hidden")
            //ClonedSelect.find('select.UOM_ID option:selected').removeAttr('selected');
            //ClonedSelect.find('select.UOM_ID option:first').attr('selected','selected');
            //ClonedSelect.find('select.UOM_ID').trigger('change');
            /* ClonedRow HERE | Reset The select tag here hahah */
            UpdateTable()
            //				setTimeout("openmodal()",800)
        }
    })
    $("#CurrencyDropDown li").click(function () {
        $(".CurrencyIndicator").html($(this).attr("MySymbol"))
        global_round = $(this).attr("data-round")
        setTimeout("UpdateSubmitButtonStatus()", 100)
    })
    var Def = $("#CurrencyDropDown li").filter(function () {
        return $(this).attr("value") == $("#CurrencyDropDown input").val()
    })
    if (Def.length > 0) {
        $(".CurrencyIndicator").html(Def.attr("MySymbol"))
        $("> button > span", $("#CurrencyDropDown")).html(Def.text())
    }
    $("#InvoiceForm").validate({
        ignore: ".ignore",
        rules: {
            PurchaseInvoiceDate: {required: true, date: true},
            //                PurchaseInvoiceDueDate: {date: true}
        }
    })
    $("#InvoiceSubmitButton").on("click", ApplyPostMethod);
    UpdateSubmitButtonStatus()
    })
    function UpdateTable() {
        //        var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        vatVal = 0, totalvat = 0, taxAmount = 0;
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0
        $("#InventoryPurchaseTable tbody tr").each(function () {
            UpdateTotalForRow($(this))
        })
        //        if (percent_flag == 1) {
        //            $("#InvoiceDiscountInput").trigger("keyup")
        //        } else {
        //            $("#TotalDiscAmount").trigger("keyup")
        //        }
        //        console.log(TotalInvoice)
        //        $("#TotalDiscAmount").val(TotalInvoice * (parseFloat($("#InvoiceDiscountInput").val()) / 100) || 0)
        //        $("#InvoiceDiscountInput").trigger("")
        //        $("#DiscountVal").html(AddCommas((TotalInvoiceWithoutDiscount - TotalInvoice).toFixed(3)))
        //        console.log(TotalInvoice)
        //        var totalDiscountValue = parseFloat($("#TotalDiscAmount").val()) || 0;
        //                var InvoiceDiscountInput = parseFloat($("#InvoiceDiscountInput").val()) || 0;
        //        var TotalInvoiceDisounted = TotalInvoice - totalDiscountValue

        setTimeout("UpdateSubmitButtonStatus()", 100)
        $("#InvoiceDiscountInput").trigger("keyup")
        checkTotals()
        //        var ftotal = TotalInvoiceDisounted + totalvat + shipping, finalTotal = 0;
        ////        console.log(global_round)
        //        if (global_round > 0) {
        //            var roundTo = global_round,
        //                    diff = ftotal % roundTo;
        //            var finalTotal = Math.floor(ftotal / roundTo);
        //            if (diff >= (roundTo / 2)) {
        //                finalTotal++;
        //            }
        //            finalTotal = finalTotal * roundTo;
        //        } else {
        //            finalTotal = ftotal;
        //        }
        //        $("#PurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted": TotalInvoice + shipping, "MyValueDiscounted": (TotalInvoiceDisounted + totalvat + shipping)}).text(AddCommas((finalTotal).toFixed(3)))

    }
    function checkTotals() {
        var shipping = parseFloat($("#Shipping").val() ? $("#Shipping").val() : 0);
        //     setTimeout("UpdateSubmitButtonStatus()", 100)
        var ftotal = TotalInvoiceDisounted + totalvat + shipping, finalTotal = 0;
        //        console.log(global_round)
        if (global_round > 0) {
            var roundTo = global_round,
                diff = ftotal % roundTo;
            var finalTotal = Math.floor(ftotal / roundTo);
            if (diff >= (roundTo / 2)) {
                finalTotal++;
            }
            finalTotal = finalTotal * roundTo;
        } else {
            finalTotal = ftotal;
        }
        $("#PurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted": TotalInvoice + shipping, "MyValueDiscounted": (TotalInvoiceDisounted + totalvat + shipping)}).text(AddCommas((finalTotal).toFixed(3)))

    }
    function EnableAutoComplete(who) {

        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: function (request, response) {
                    var classID = $("#pricing_class").val(),
                        depot_id = $("#Depot_Loc").val(),
                        product_id = who.parents('tr').attr('data-id'),
                        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") + "&ClassID=" + classID + '&depot_id=' + depot_id+status_cond, request, function (s, status, xhr) {
                        response(s);
                    });
                },
                minLength: 0,
                select: function (event, ui) {
                    var TR = $(this).parents("tr");
                    TR.attr("data-id", ui.item.ID)
                    TR.attr("data-vat", ui.item.VAT)
                    TR.attr("data-qty", ui.item.Quantity)
                    TR.attr("data-prod-status", ui.item.Status_ID)
                    TR.find("input.CODE").val(ui.item.Bar_Code)
                    TR.find("input.ProductName").val(ui.item.Name)
                    TR.find("input.vat_percent").val(ui.item.VAT == 1 ? ui.item.vat_percent : 0)
                    TR.find("input.VATPerItem").val('0')
                    if (ui.item.VAT == 0) {
                        TR.find("input.vat_percent,input.VATPerItem").attr("disabled", "disabled")
                    } else {
                        TR.find("input.vat_percent,input.VATPerItem").removeAttr("disabled")
                    }
                    TR.find("input.UnitPrice").val($("#Class_Currency").text() == $("#CurrencyDropDown input").val() ? ui.item.Price : ConvertCurrency2(ui.item.Price, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()).toFixed(2))
                    $("select[name=UOM_ID]", TR).empty()
                    TR.find("input.UnitPrice").prev().text("last cost: " + (!ui.item.LAST_COST ? "0" : AddCommas(parseFloat(ConvertCurrency2(ui.item.LAST_COST, local_currency, $("#CurrencyDropDown input").val())).toFixed(3))));

                    TR.find("input.Quantity")/*.focus()*/.prev().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();
                    UpdateTable()
                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width() * (this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = this.element.hasClass("CODE") ? (item.Bar_Code) : (item.Name + ' - ' + item.Code);
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }


        //        alert('hello')

        $(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 = {
                    Cash_Amount: $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
                    Cash_Account: $("#cash_account").val(),
                    Check_Amount: $("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
                    Check_Account: $("#check_account").val(),
                    Card_Amount: $("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
                    Card_Account: $("#credit_account").val(),
                    check_due_date: $(".check_due_date").val(),
                    Check_Num: $("#SetPaidFormTab_2 .CheckNumValue").eq(0).val(),
                    Card_Code: $("#SetPaidFormTab_3 .CardApproval").eq(0).val(),
                    Depot_ID: $("#Depot_Loc").val(),
                    Invoice_VAT: $("#InvoiceVAT").html().replace(/,/g, ""),
                    Account_Code: $('#Account_Code').val(),
                    CurrencySymbole: $(".CurrencyIndicator").html(),
                    IsSalesMode: 1,
                    //                        pending_status: $("#pending").is(":checked") ? 3 : 4,
                    shipping: $("#Shipping").val(),
                    shipping_account: $("#Shipping_Code").val(),
                    discount_amount: $("#TotalDiscAmount").val(),
                    is_return: is_return ? 1 : 0,
                    tax_amount:0,
                    Is_Actual: 0,
                    Invoice_Net_Total: $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted"),
                    Products: []

                };

            if (!is_return) {

                Data.Customer_ID = $("#Supplier_ID").val();
                Data.Customer_Account = $("#Finance_Account").attr("data-id")
                Data.Customer_Name = $("#Customer_Name").attr("data-id")
                Data.Invoice_Date = $("#PurchaseInvoiceDate").val();
                Data.Invoice_Due_Date = $("#PurchaseInvoiceDueDate").val() ? $("#PurchaseInvoiceDueDate").val() : $("#PurchaseInvoiceDate").val();
                Data.Invoice_Currency = $("#CurrencyDropDown input").val();
                Data.Invoice_Discount = $("#InvoiceDiscountInput").val();
                Data.Invoice_Sub_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
                Data.Invoice_Paid_Amount = $("#AdvanceValue").val();
                Data.truck = $("#inv_truck").val();
                Data.Class_ID = $("#pricing_class").val();
                Data.products = [];

            } else {
                Data.Person_ID = $("#Supplier_ID").val();
                Data.Person_Account = $("#Finance_Account").attr("data-id")
                Data.Return_Invoice_Date = $("#PurchaseInvoiceDate").val();
                Data.Currency_ID = $("#CurrencyDropDown input").val();
                Data.discount_percent = $("#InvoiceDiscountInput").val();
                Data.Return_Invoice_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
                Data.Class_ID = $("#pricing_class").val();
                Data.Is_Customer_Invoice = 1;
                Data.Return_Invoice_Note = '';
                Data.Products = [];
            }

            if (IsEditMode) {
                Data.Sales_Purchase_ID_Auto = ID_Edit;
                Data.Old_Depot_ID = $("#Depot_Loc").attr('data-old')
            }


            $("#InventoryPurchaseTable tbody tr").each(function (e) {
                var me = $(this);
                if (me.find(".Quantity").val() != '' && me.find(".ProductName").val() != '') {

                    Data.Products.push({
                        UOM_ID: me.find("select.UOM_ID").val(),
                        Product_ID: me.attr("data-id"),
                        Product_Code: me.find(".CODE").val(),
                        Product_Name: me.find(".ProductName").val(),
                        Item_Quantity: me.find(".Quantity").val(),
                        Return_Product_Quantity: me.find(".Quantity").val(),
                        Item_Price: me.find(".UnitPrice").val(),
                        Unit_Cost: me.find(".UnitPrice").val(),
                        current_supplier: me.find("input[name=current_supplier]").val(),
                        current_supplier_name: me.find(".current_supplier .select2-chosen").html(),
                        cost_price: me.find(".CostPrice").val(),
                        product_description: me.find(".description").val(),
                        Currency_ID: $("#CurrencyDropDown input").val(),
                        Item_Discount: me.find(".Disc").val(),
                        vat_percent: me.find("input.vat_percent").val(),
                        vat_val: me.find("input.VATPerItem ").val(),
                        Product_Total_Price: me.find(".TotalTD > .Total").attr("myval"),
                        Return_Product_Total: me.find(".TotalTD > .Total").attr("myval")
                    });

                    me.find(".CODE,.ProductName,.Quantity,.UnitPrice").each(function () {
                        if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                            $(this).addClass("wrong")
                            CheckSubmit = false;
                            IsValidated = false;
                        } else {
                            $(this).removeClass("wrong")
                        }

                    })
                    //                    console.log(me.find("input[name=current_supplier]").val() + '====' + me.find('.CostPrice').val())
                    if (me.find("input[name=current_supplier]").val() != '' && me.find('.CostPrice').val() == '') {
                        me.find('.CostPrice').addClass("wrong")
                        CheckSubmit = false;
                        IsValidated = false;
                    } else {
                        me.find('.CostPrice').removeClass("wrong")
                    }
                    //                    console.log(me)
                }
            })
            if (!IsValidated)
                return;
            $("#PurchaseDisabler").show();
            $.ajax({
                url: IsEditMode ? "InventoryAjax/editSalesPurchaseAjax" : "InventoryAjax/addSalesPurchaseAjax",
                method: "POST",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {

                    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 + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[2] + '</strong>')

                            $("#InvoiceSubmitButton").attr("disabled", "disabled")
                            CheckSubmit = true;
                        } else {
                            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseText)
                            CheckSubmit = false;
                        }
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        CheckSubmit = false;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#PurchaseDisabler").hide();
                }
            })
        } else {
            $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
            $(document.body).animate({scrollTop: 0}, 800)
        }
    }
    function UpdateTotalForRow(who) {
        //        alert(who.attr('data-vat'))
        var Single_Price = parseFloat(who.find(".UnitPrice").val()) || 0,
            Qty = parseFloat(who.find(".Quantity").val()) || 0,
            Total = Single_Price * Qty,
            Discount = parseFloat(who.find(".Disc").val()) || 0,
            Net_Total = (Total * (1 - Discount / 100)) || 0;

        TotalInvoiceWithoutDiscount += Total;
        TotalDiscount += Discount;
        TotalInvoice += Net_Total;
        who.find(".Total").attr("MyVal", Net_Total.toFixed(3)).text(AddCommas(Net_Total.toFixed(3)))
        who.attr('Unit_Price', Single_Price)
        var tr_vat_percent = (who.attr('data-vat') == 1) ? (parseFloat(who.find("input.vat_percent").val()) || 0) : 0,
            TRvalue = (who.attr('data-vat') == 1 && tr_vat_percent > 0) ? (parseFloat($(".TotalTD .Total", who).attr('myval'))) : 0;


        //        if ( Qty != 0) {
        vatVal = TRvalue * tr_vat_percent / 100;
        totalvat += vatVal;
        taxAmount += TRvalue;
        //alert(totalvat)
        who.find('.VATPerItem').val(vatVal ? vatVal : '')
        $('#PurchaseTaxableAmount').html(AddCommas(taxAmount))
        $("#InvoiceVAT").html(AddCommas(totalvat.toFixed(3)))
        //        }
        //        else{
        //            who.find('.VATPerItem').val('0')
        ////            $('#PurchaseTaxableAmount').html(AddCommas(taxAmount))
        ////            $("#InvoiceVAT").html(AddCommas(totalvat.toFixed(3)))
        //        }
    }
    function UpdateSubmitButtonStatus() {
        var Rows = $("#InventoryPurchaseTable tbody tr"), DoDisable = false
        if (Rows.length > 0) {
            if (Rows.length == 1) {
                if ($.trim($("input.CODE", Rows).val()) != "" && $.trim($("input.ProductName", Rows).val()) != "" && $.trim($("input.Quantity", Rows).val()) != "" && $.trim($("input.UnitPrice", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }
        if ($.trim($("#CurrencyDropDown > button > input").val()) == "")
            DoDisable = true;
        if (parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(/,/g, "")) > parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(/,/g, "")))
        {
            //            alert('Paid'+parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(",", ""))+' Total'+parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(",", "")))
            DoDisable = true;
        }

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

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

            }



        })

        // document.title = Rows.length
        if (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }
    function InputMustBeAtleastN(who, N) {
        if (parseInt(who.value) < N || !parseInt(who.value))
            who.value = N;
        UpdatePurchaseInvoiceTotalPaid();
    }
    function UpdatePurchaseInvoiceTotalPaid() {
        var A1 = parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val()) || 0,
            A2 = parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val()) || 0,
            A3 = parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val()) || 0;
        $("#PurchaseInvoiceTotalPaid").text(AddCommas(A1 + A2 + A3));
        UpdateSubmitButtonStatus();
        if (!is_return) {
            if ((A1 + A2 + A3) >= parseFloat($("#PurchaseInvoiceTotalDetails").attr("myvaluediscounted"))) {
                $("#PurchaseInvoiceDueDate").removeAttr("required")
            } else {
                $("#PurchaseInvoiceDueDate").attr("required", "required")
            }
        }


    }



    $(document).ready(function () {
        window.onbeforeunload = function (e) {
            if (!CheckSubmit) {
                var message = have_not_saved, e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }

    });
    function printExternal(url, btn_id) {
        $("#print_iframe").remove();
        $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:800px;height:800px;' src='" + url + "' onload='document.getElementById(\"print_iframe\").contentWindow.document.getElementById(\"" + btn_id + "\").click();'  ></iframe>").appendTo("body");


    }
</script>
