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


    }

    #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: 20px;
        font-weight: bold;
    }
    #InventoryPurchaseTable .Disc{
        width:70px;
    }
    #InventoryPurchaseTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .select2-container > .select2-choice{
        background-color: #e5e5e5;
        width: 150px;
    }
    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
        /*
        -webkit-border-radius: 3px 0px 0px 3px !important;
        -moz-border-radius: 3px 0px 0px 3px !important;
        border-radius: 3px 0px 0px 3px !important;
        */
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .hideme{

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

        width: 100%;

    }
    .supInv{
        display:inline-flex;
    }
    .Account_Code{
        margin-left:10px;
    }

</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 padding-50 sm-padding-10">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <h2 class="font-montserrat all-caps hint-text"><?php echo CommonLanguage::getMessage($IsSales ? 'sales_invoice' : 'purchase_invoice'); ?> </h2>
                                <div class='row'>
                                    <div class="col-md-4"><label><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer' : 'choose_supplier'); ?></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo $IsSales ? "Inventory/CustomerList?is_pop=1":"Inventory/ViewVendorList?is_pop=1"?>" style="color:#8a7dbe;cursor:pointer"></span></div>
                                    <div class="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></div>
                                    <div class="col-md-3"><label><?php if($IsSales) { echo 'Pending';  } ?></label></div> 
                                </div>
                                <div class='row'>
                                    <div class="input-group  col-md-4 center-margin pull-left" >
                                        <input class="search_supplier full-width" id="search_supplier" name="search_supplier" type="hidden" value="<?=$IsEdit ? $edit_arr['Main'][$IsSales ? 'Customer_ID' : 'Supplier_ID'] :"";?>" data-select-name='<?=  json_encode($IsEdit ? $edit_arr['Person']['Name'] : "");?>' />
                                    </div>
                                    <div class="Account_Code col-md-4">
                                        <input class=" full-width" id="Account_Code" name="Account_Code" type="hidden" value="<?=$IsEdit ? $edit_arr['Main']['Transaction_Account']:"";?>" data-select-name='<?=  json_encode($IsEdit ? $edit_arr['Main']['Account_Name'] : "");?>' />
                                    </div>
                                    <?php if ($IsSales) { ?>
                                    <div class="pending_invoices col-md-3">
                                        <select  name="pending_invoices" id="pending_invoices"  onchange="location = this.value;" class="full-width pending_invoices " data-init-plugin="select2">
                                            <option value="0"> <?php print CommonLanguage::getMessage('pending_invoices'); ?></option> 

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

                                        </select>
                                        <!--                                        <input type = "text" id="Account_Code" class="form-control" placeholder="Account Code">-->
                                    </div>
                                    <?php } ?>
                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="SupplierInfo">
                                    <input type="hidden" name="Supplier_ID" value="<?php echo $IsEdit ? ($edit_arr['Main'][$IsSales ? 'Customer_ID' : 'Supplier_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 && $IsSales) ? $edit_arr['Person']['Class_ID'] : '' ?></div>
                                        <div id='Class_Currency' style='display:none;'><?php echo ($IsEdit && $IsSales) ? $edit_arr['Person']['Class_Currency'] : '' ?></div>

                                    </div>
                                    <div id="SupplierAccInfo" class="<?php echo $IsEdit ? '' : 'hidden' ?>">
                                        <div id='Account_CodeDiv' value='<?php echo $IsEdit ? $edit_arr['Main']['Transaction_Account'] : '' ?>'><strong><?php echo CommonLanguage::getMessage('account_code') ?>: </strong><?php echo $IsEdit ? $edit_arr['Main']['Account_Name'].' - '.$edit_arr['Main']['Transaction_Account'] : '' ?></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($IsSales ? 'invoice' : 'purchase_voucher'); ?> #
                                        <?php
//                                        echo $InvoiceNumber;
                                        echo'--';
                                        ?></h4>
                                </div>
                                <?php if (!$IsSales) { ?>
                                <div  class="form-group supInv" id="SupplierInv" style="">
                                    <h4> <?php print CommonLanguage::getMessage('supplier_invoice'); ?>#</h4>
                                    <input id="Supplier_Invoice" name="Supplier_Invoice" class="form-control" value="<?php echo (!$IsSales && $IsEdit) ? $edit_arr['Main']['Supplier_Invoice_ID'] : '' ?>" style="    width: 35%;
                                               margin-top: 11px;
                                               margin-left: 15px" />

                                </div>
                                <?php } ?>
                                <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  ">
                                    <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                    <input id="PurchaseInvoiceDueDate" name="PurchaseInvoiceDueDate" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Main']['Due_Date'] : $today); ?>" required>
                                    <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()['default_depot_id'] ?>" data-select-name='<?= json_encode( $IsEdit ? $all_depots[$edit_arr['Main']['Depot_ID']]['Depot_Name'] : smc_session()['default_depot_name'])?>' />

                                        </div>
                                    </div>

                                </div>
                                <?php if ($IsSales) { ?>
                                <div id="CurrencyIDContainer" class=" m-t-10" >
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms" 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>

                                        </div>

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

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

                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <div id="ProdLoader" class="text-center alert " style="height:100%;background-color:#E2DEEF"> <h3 ><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer_first' : 'choose_supplier_first'); ?> </h3> </div>
                        <table class="table m-t-50 hideme" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"style="width:15%"><?php print CommonLanguage::getMessage('Code'); ?></th>
                                    <th class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('product_name'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/listproduct?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></th>
                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('Quantity'); ?></th>
                                    <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('unit_price'); ?></th>
                                    <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('discount_percent'); ?></th>
                                    <th class="text-center"style="width:10%"><?php print CommonLanguage::getMessage('total'); ?></th>
                                </tr>
                            </thead>
                            <!--
<tbody>
<tr>
<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" <?php echo($IsSales ? 'disabled' : ''); ?> ></td>
<td><input type="text" class="form-control Disc" value=""></td>
<td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>

</tr>
</tbody>
-->



                            <tbody>
                                <?php
                                if ($IsEdit) {
                                    foreach ($edit_arr['Details'] 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'] ?>" unit_price="<?php echo $item['Product_Net_Price'] ?>">
                                    <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><input type="text" class="form-control Disc" value = "<?php echo $item['Product_Discount'] ?>"></td>

                                    <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                </tr>
                                <?php
                                    }
                                } else {
                                ?>
                                <tr data-conv="1">
                                    <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><input type="text" class="form-control Disc" value=""></td>

                                    <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                </tr>
                                <?php } ?>
                            </tbody>



































                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-6 col-sm-height 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="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">
                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                            <span><?php print CommonLanguage::getMessage('select'); ?></span>
                                                                            <input type="hidden" value="" class="form-control" onkeyup="return false" onkeydown="return false"/>
                                                                        </button>
                                                                        <ul class="dropdown-menu">
                                                                            <?php for ($x = 0; $x < count($Cashes); $x++) { ?>
                                                                            <li value="<?php echo $Cashes[$x]["Account_ID"]; ?>"><a><?php echo $Cashes[$x]["Account_Name"]; ?></a></li>
                                                                            <?php } ?>
                                                                        </ul>
                                                                    </div>
                                                                </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="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">
                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                            <span><?php print CommonLanguage::getMessage('select'); ?></span>
                                                                            <input type="hidden" value="" 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_ID"]; ?>"><a><?php echo $Checks[$x]["Account_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="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">
                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                            <span><?php print CommonLanguage::getMessage('select'); ?></span>
                                                                            <input type="hidden" value="" 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_ID"]; ?>"><a><?php echo $CreditCards[$x]["Account_Name"]; ?></a></li>
                                                                            <?php } ?>
                                                                        </ul>
                                                                    </div>
                                                                </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="font-montserrat all-caps small no-margin hint-text bold p-b-10" > <?php print CommonLanguage::getMessage('shipping_code'); ?>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>

                                        <input class=" full-width" id="Shipping_Code" name="Shipping_Code" type="hidden" value="<?=$IsEdit ? $edit_arr['Main']['shipping_account']:"";?>" data-select-name='<?=  json_encode($IsEdit ? $edit_arr['Main']['shipping_name'] : "");?>' /></h5>

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













                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" > <?php print CommonLanguage::getMessage('invoice_discount'); ?><input type="text" class="form-control ignore" id="InvoiceDiscountInput" /> %</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>
                                </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>
                    </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>
<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')); ?>,
                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')); ?>,
                                            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')); ?>;
                                                    var IsSalesMode = <?php echo $IsSales ? "true" : "false"; ?>,
                                                        IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>;
                                                        var CurrencyRate = <?php echo json_encode($Extable); ?>,
                                                            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
                                                                uom_arr = <?php echo json_encode($all_uom); ?>;

                                                            var TotalInvoice = 0,
                                                                TotalDiscount = 0,
                                                                TotalInvoiceWithoutDiscount = 0;
                                                            var CheckSubmit = true;

                                                            if (IsSalesMode) {
                                                            $("#SupplierInv").removeClass("supInv")
                                                            $("#SupplierInv").addClass("hideme")
    }

                                                            $(function () {
                                                            build_select2($(".search_supplier"),(IsSalesMode ? "xhr/customerSearch" : "xhr/supplierSearch"))
                                                            build_select2($("#Account_Code"),( "xhr/accIDSearch?type="+(IsSalesMode ? 'sales' :'purchase')))
    build_select2($("#Shipping_Code"),( "xhr/accIDSearch?type="+(IsSalesMode ? 'sales' :'purchase')))
    build_select2($(".Depot_Loc"),"xhr/depotSearch")
    build_select2($("#cash_account"),( "xhr/accIDSearch?type=cash"))
    build_select2($("#check_account"),( "xhr/accIDSearch?type=check"))
    build_select2($("#credit_account"),( "xhr/accIDSearch?type=credit_card"))



    $("#InventoryPurchaseTable").on("change", "select.UOM_ID", function () {
        var me = $(this).parents("tr");
        var UOMData = {pid: $(this).parents("tr").attr("data-id"),
                       uid: $(this).val()};
        $.ajax({
            url: "InventoryAjax/ReturnProductUOMCon",
            data: UOMData,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    me.attr('data-conv', v1.responseJSON)
                    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')
    $("#search_supplier").on("change", function () {
        $("#SupplierInfoContent").removeClass('hidden')
        if ($(this).val() == 0) {
            $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
            $("#ProdLoader").removeClass("hideme")
            $("#InventoryPurchaseTable").addClass("hideme")
        } else
            if ($("#Account_Code").val() == 0) {
                $("#ProdLoader > h3").empty().html(account_firstLang)
            }
        //            else
        //                    if($("#Supplier_Invoice").val() == 0 && !IsSalesMode){
        //                        $("#ProdLoader > h3").empty().html("Please enter supplier invoice number.")
        //                    }
        else {
            $("#ProdLoader").addClass("hideme")
            $("#InventoryPurchaseTable").removeClass("hideme")
        }
        var Data = {
            id: $(this).val(),
            mode: IsSalesMode
        }

        $.ajax({
            url: "InventoryAjax/addPurchaseAjax",
            data: Data,
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    var Data = (v1.responseJSON);
                    console.log(Data)
                    if (IsSalesMode) {
                        $("#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']);
                        $("#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'])
                    } else {
                        $("#SupplierInfoContent").empty();
                        var Content = "";
                        Content += "<strong><span class='Name' id='Supplier_Name' data-id='" + Data[0]['Supplier_Name'] + "'>" + Data[0]['Supplier_Name'] + "</span></strong>";
                        Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + Data[0]['Supplier_Company'] + "</span></div>";
                        Content += "<div><strong>" + EmailLang + ": </strong><span class='Email'>" + Data[0]['Supplier_Email'] + "</span></div>";
                        Content += "<div><strong>" + PhoneLang + ": </strong><span class='Phone'>" + Data[0]['Supplier_Phone'] + "</span></div>";
                        Content += "<div><strong>" + AddressLang + ": </strong><span class='Address'>" + Data[0]['Supplier_Address'] + "</span></div>";
                        Content += "<div><strong>" + CountryLang + ": </strong>" + Data[0]['Country_Name'] + "</div>";
                        Content += "<div id='Finance_Account' data-id='" + Data[0]['Account_ID'] + "'><strong>" + FinancialNbLang + ": </strong>" + Data[0]['Account_Code'] + "</div>";
                        $("#SupplierInfoContent").html(Content)
                        $("#Supplier_ID-error").remove()
                        $("#Supplier_ID").removeClass("error").val(Data[0]['Supplier_ID']);

                    }
                }
            }
        })

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

    })
    $("#PrintBtn").on("click", function () {
        var myurl = IsSalesMode ? "Inventory/viewActualInvoice/" + Invoice_ID + "/" + $("#Supplier_ID").val() : "Inventory/viewActualInvoice/vendor/" + Invoice_ID + "/" + $("#Supplier_ID").val();
        printExternal(myurl)
    })



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

        $('#Account_CodeDiv').remove()
        var Content = "";
        if ($(this).val() != 0) {
            Content += "<div id='Account_CodeDiv' value='" + $(this).val() + "'><strong>" + accountCodeLang + ": </strong>" + accName + "</div>";

            $("#SupplierAccInfo").append(Content).removeClass('hidden')
        }
        if ($(this).val() == 0) {
            $("#ProdLoader > h3").empty().html(account_firstLang)
            $("#ProdLoader").removeClass("hideme")
            $("#InventoryPurchaseTable").addClass("hideme")
        } else
            if ($("#search_supplier").val() == 0) {
                $("#ProdLoader > h3").empty().html(IsSalesMode ? customer_firstLang : supplier_firstLang)
            } else {
                $("#ProdLoader").addClass("hideme")
                $("#InventoryPurchaseTable").removeClass("hideme")
            }

    })

    //        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").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 (IsSalesMode) {
            if (me.hasClass("Quantity")) {
                if (parseFloat(me.val()) > parseFloat(TR.attr('data-qty'))) {
                    me.addClass("wrong")

                }

            }
        }
    });
    if (IsEditMode)
        $(".Quantity").trigger('keyup')
    $("#InvoiceDiscountInput,#Shipping").on("blur keyup", function () {
        setTimeout("UpdateTable()", 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", "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")
            Parent.append(ClonedRow);
            EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
            EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
            $(".Hint,.Total", ClonedRow).html("")
            $("input", ClonedRow).removeClass("wrong")
            $(".select2-container", ClonedRow).empty().remove()
            $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
            //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"))
        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);
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0
        $("#InventoryPurchaseTable tbody tr").each(function () {
            UpdateTotalForRow($(this))
        })
        var InvoiceDiscountInput = parseFloat($("#InvoiceDiscountInput").val()) || 0;
        var TotalInvoiceDisounted = TotalInvoice - (TotalInvoice * (InvoiceDiscountInput / 100))
        var SubTotalVal = TotalInvoiceWithoutDiscount * (1 - TotalDiscount / 100);
        $("#DiscountVal").html(AddCommas((parseFloat(TotalInvoiceWithoutDiscount - TotalInvoice)).toFixed(3)))
        $("#InvoiceTotalAfterDiscount").text(AddCommas((parseFloat(TotalInvoiceWithoutDiscount * (InvoiceDiscountInput / 100))).toFixed(3)))
        setTimeout("UpdateSubmitButtonStatus()", 100)
        $("#InventoryPurchaseTable tbody tr").each(function () {
            var TRvalue = parseFloat($(".TotalTD .Total", $(this)).attr('myval'));
            $("#PurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted": TotalInvoice, "MyValueDiscounted": parseFloat(TotalInvoiceDisounted + shipping )}).text(AddCommas(parseFloat((TotalInvoiceDisounted+ shipping)).toFixed(3)))
        })
    }

    function EnableAutoComplete(who) {
        if (IsSalesMode) {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function (request, response) {
                        //                        var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                        var classID = $("#Class_ID").text();
                        $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2") + "&ClassID=" + classID, request, function (s, status, xhr) {
                            response(s);
                        });
                    },
                    minLength: 0,
                    select: function (event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.ID)
                        TR.attr("data-qty", ui.item.Quantity)
                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.find("input.ProductName").val(ui.item.Name)
                        TR.find("input.UnitPrice").val(ui.item.Price)
                        $("select[name=UOM_ID]", TR).empty().html($("#Select_UOM").html()).select2()
                        TR.find("select[name=UOM_ID] > option[value=" + ui.item.UOM_ID + "]").attr("selected", true)
                        TR.find("select[name=UOM_ID]").select2()


                        //if(!IsSalesMode)TR.find("input.UnitPrice").prev().text("last cost: "+(!ui.item.LAST_COST ? "NAN" : ui.item.LAST_COST) + " " + (ui.item.Currency_ID ? ui.item.Currency_ID[1] : ""));
                        TR.find("input.Quantity").focus().prev().text((ui.item.Quantity) + " in stock")
                        var units_arr = ui.item.Product_UOM.split("/");
                        $("select[name=UOM_ID] > option", TR).each(function () {
                            if ($.inArray($(this).attr("value"), units_arr) === -1) {
                                $(this).remove()
                            }
                        })
                        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);
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }
            $(document).keydown(function (e) {
                if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
                    e.preventDefault()
                }
            })
        } else {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function (request, response) {
                        //                        var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                        $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2"), request, function (s, status, xhr) {
                            response(s);
                        });
                    },
                    minLength: 0,
                    select: function (event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.ID)
                        TR.attr("data-qty", ui.item.Quantity)
                        TR.find("input.CODE").val(ui.item.Bar_Code)
                        TR.find("input.ProductName").val(ui.item.Name)
                        $("select[name=UOM_ID]", TR).empty().html($("#Select_UOM").html()).select2()
                        TR.find("select[name=UOM_ID] > option[value=" + ui.item.UOM_ID + "]").attr("selected", true)
                        TR.find("select[name=UOM_ID]").select2()
                        //TR.find("input.UnitPrice").val(IsSalesMode ? (ui.item.Product_Price ? ui.item.Product_Price : ui.item.Material_Price ) : "")
                        TR.find("input.UnitPrice").prev().text("last cost: " + (!ui.item.LAST_COST ? "0" : ui.item.LAST_COST));
                        TR.find("input.Quantity").focus().prev().text((ui.item.Quantity) + " in stock")
                        var units_arr = ui.item.Product_UOM.split("/");
                        $("select[name=UOM_ID] > option", TR).each(function () {
                            if ($.inArray($(this).attr("value"), units_arr) === -1) {
                                $(this).remove()
                            }
                        })
                        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;
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }
            $(document).keydown(function (e) {
                if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
                    e.preventDefault()
                }
            })
        }
    }
    function ApplyPostMethod() {
        $("#PurchaseSuccess").attr("class", "hidden");
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                Data = {
                    Cash_Amount: $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
                    Cash_Account: $("#SetPaidFormTab_1 .DropDownForForms > button > input").eq(0).val(),
                    Check_Amount: $("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
                    Check_Account: $("#SetPaidFormTab_2 .DropDownForForms > button > input").eq(0).val(),
                    Check_Num: $("#SetPaidFormTab_2 .CheckNumValue").eq(0).val(),
                    Card_Amount: $("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
                    Card_Account: $("#SetPaidFormTab_3 .DropDownForForms > button > input").eq(0).val(),
                    Card_Code: $("#SetPaidFormTab_3 .CardApproval").eq(0).val(),

                 
                    shipping: $("#Shipping").val(),
                    CurrencySymbole: $(".CurrencyIndicator").html(),  
                    shipping_account: $("#Shipping_Code").val(),
                    Products: []


                };


            if (IsSalesMode) {
                Data.Depot_ID = $("#Depot_Loc").val();
                Data.Purchase_Invoice_ID = 0,
                    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.Currency_ID = $("#CurrencyDropDown input").val();
                Data.Invoice_Discount = $("#InvoiceDiscountInput").val();
                Data.Invoice_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
                Data.Invoice_Sub_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
                Data.Invoice_Paid_Amount = $("#AdvanceValue").val();
                Data.Currency_Symbol = $(".CurrencyIndicator").html();
                Data.Account_Code = $('#Account_CodeDiv').attr('value');
                Data.Old_Total = 0;
                Data.Paid_Old = 0;
                Data.Products = [];
                
                
            } else {
                Data.Purchase_Invoice_ID = 0,
                    Data.Depot_ID = $("#Depot_Loc").val();
                Data.Supplier_Invoice_ID = $("#Supplier_Invoice").val();
                Data.Supplier_ID = $("#Supplier_ID").val();
                Data.Supplier_Account = $("#Finance_Account").attr("data-id");
                Data.Supplier_Name = IsEditMode ? $("#Customer_Name").attr("data-id") :$("#Supplier_Name").attr("data-id");
                Data.Purchase_Date = $("#PurchaseInvoiceDate").val();
                Data.Purchase_Due_Date = $("#PurchaseInvoiceDueDate").val() ? $("#PurchaseInvoiceDueDate").val() : $("#PurchaseInvoiceDate").val();
                Data.Currency_ID = $("#CurrencyDropDown input").val();
                Data.Purchase_Discount = $("#InvoiceDiscountInput").val();
                Data.Purchase_Net_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
                Data.Purchase_Sub_Total = $("#PurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
                Data.Purchase_Paid_Amount = $("#AdvanceValue").val();
                Data.Currency_Symbol = $(".CurrencyIndicator").html();
                Data.Account_Code = $('#Account_CodeDiv').attr('value');
                Data.Old_Total = 0;
                Data.Paid_Old = 0;
                Data.Products = [];

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

            $("#InventoryPurchaseTable tbody tr").each(function (e) {
                var me = $(this);
                if (e < $(this).parent().children().length - 1) {

                    if (IsSalesMode) {
                        Data.Products.push({
                            Product_ID: me.attr("data-id"),
                            UOM_ID: me.find("select.UOM_ID").val(),
                            Product_Code: me.find(".CODE").val(),
                            Product_Name: me.find(".ProductName").val(),
                            Item_Quantity: me.find(".Quantity").val(),
                            Item_Price: me.find(".UnitPrice").val(),
                            Currency_ID: $("#CurrencyDropDown input").val(),
                            Item_Discount: me.find(".Disc").val(),
                            Product_Total_Price: me.find(".TotalTD > .Total").attr("myval")


                        });
                    } else {
                        Data.Products.push({
                            UOM_ID: me.find("select.UOM_ID").val(),
                            Product_ID: me.attr("data-id"),
                            Product_Code: me.find(".CODE").val(),
                            Product_Name: me.find(".ProductName").val(),
                            Item_Quantity: me.find(".Quantity").val(),
                            Item_Price: me.find(".UnitPrice").val(),
                            Currency_ID: $("#CurrencyDropDown input").val(),
                            Item_Discount: me.find(".Disc").val(),
                            Product_Total_Price: 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")
                            IsValidated = false;
                            CheckSubmit = false;
                        } else {
                            $(this).removeClass("wrong")
                        }
                    })
                }
            })
            if (!IsValidated)
                return;
            $("#PurchaseDisabler").show();
            //            $.ajax({
            //                url: "InventoryAjax/ActualNewInvoiceRequest",
            //                method: "POST",
            //                data: Data,
            //                complete: function (v1, v2) {
            //                    if (v2 == "success") {
            //                        if (v1.responseText == "OK") {
            //                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
            //                            $("#InvoiceSubmitButton").addClass("disabled", "disabled")
            //                        } else {
            //                            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseText)
            //                        }
            //                    } else {
            //                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
            //                    }
            //                    $(document.body).animate({scrollTop: 0}, 800)
            //                    $("#PurchaseDisabler").hide();
            //                }
            //            })
            //        } else {
            //            $(document.body).animate({scrollTop: 0}, 800)
            //        }


            $.ajax({
                url: IsEditMode ? "InventoryAjax/editInvoiceActual" : "InventoryAjax/ActualNewInvoiceRequest",
                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").removeClass("disabled")
                            }
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                            $("#InvoiceSubmitButton").addClass("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(Required_Fields)
            $(document.body).animate({scrollTop: 0}, 800)
        }




















    }
    function UpdateTotalForRow(who) {

        var Single_Price = parseFloat(who.find(".UnitPrice").val()) || 0,
            Qty = parseFloat(who.find(".Quantity").val()) || 0,
            uom_conv = parseFloat(who.attr('data-conv')),
            Total = IsSalesMode ? ConvertCurrency2(Single_Price * Qty * uom_conv, $("#Class_Currency").text(), $("#CurrencyDropDown input").val()) : Single_Price * Qty * uom_conv,
            //			final_Total           = Single_Price * Qty,
            Discount = parseFloat(who.find(".Disc").val()) || 0,
            Net_Total = (Total * (1 - Discount / 100)) || 0;
                 console.log(Single_Price+'*'+Qty+'*'+uom_conv)
        //                       var Net_Total = ConvertCurrency2(final_row_total,$("#Class_Currency").text(),$("#CurrencyDropDown input").val());
        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)
    }
    function UpdateSubmitButtonStatus() {
        var Rows = $("#InventoryPurchaseTable tbody tr"), DoDisable = false
        if (Rows.length > 0) {
            if (Rows.length == 1) {
                if ($.trim($("input.CODE", Rows).val()) != "" && $.trim($("input.ProductName", Rows).val()) != "" && $.trim($("input.Quantity", Rows).val()) != "" && $.trim($("input.UnitPrice", Rows).val()) != "") {
                    DoDisable = false;
                } else {
                    DoDisable = true;
                }
            } else {
                DoDisable = false;
            }
        } else {
            DoDisable = true;
        }
        if ($.trim($("#CurrencyDropDown > button > input").val()) == "")
            DoDisable = true;
        if (parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(",", "")) > parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(",", "")))
            DoDisable = true;
        if (IsSalesMode) {
            $("#InventoryPurchaseTable tbody tr").each(function () {
                if (parseFloat($(this).find(".Quantity").val()) > parseFloat($(this).attr('data-qty')))
                    DoDisable = true;

            })
        }
        // document.title = Rows.length
        if (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }
    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();
        console.log(A1 + A2 + A3)
        console.log(parseFloat($("#PurchaseInvoiceTotalDetails").attr("myvaluediscounted")))
        if ((A1 + A2 + A3) >= parseFloat($("#PurchaseInvoiceTotalDetails").attr("myvaluediscounted")))
            $("#PurchaseInvoiceDueDate").removeAttr("required")
        else
            $("#PurchaseInvoiceDueDate").attr("required", "required")

    }

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

    $(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;
            }
        }

    });




</script>
