
<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: 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>
                                    <div class="input-group  col-md-4 center-margin pull-left">
                                        <span class="input-group-addon  primary">
                                            <i class="fa fa-search"></i>
                                        </span>
                                        <input type="text" id="search_invoice" class="form-control" placeholder="Enter Invoice ID" >
                                        <span id='Supplier_Customer_ID'style='display:none;'></span>
                                    </div>
                                    <div class="Account_Code col-md-4">
                                        <select  name="Account_Code" id="Account_Code"  class="full-width Account_Code " data-init-plugin="select2">
                                            <option value="0"> <?php print CommonLanguage::getMessage('choose_account'); ?></option> 
                                            <?php if (!$IsSales) { ?>
                                                <?php foreach ($purAcc as $pur): ?>
                                                    <option value="<?php echo $pur['Account_Code']; ?>"><?php echo $pur['Account_Name'] . ' - ' . $pur['Account_Code']; ?></option>
                                                <?php
                                                endforeach;
                                            } else {
                                                ?>
                                                <?php foreach ($salesAcc as $sal): ?>
                                                    <option value="<?php echo $sal['Account_Code']; ?>"><?php echo $sal['Account_Name'] . ' - ' . $sal['Account_Code']; ?></option>
                                                <?php
                                                endforeach;
                                            }
                                            ?>

                                        </select>
                                        <!--                                        <input type = "text" id="Account_Code" class="form-control" placeholder="Account Code">-->
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <br>
                                <div id="SupplierInfo">
                                    <input type="hidden" name="Supplier_ID" required id="Supplier_ID" />
                                    <input type="hidden"  id="Paid_Old" />
                                    <input type="hidden"  id="Person_Code" />
                                    <div id="SupplierInfoContent" class="hidden">
                                        <strong><?php print CommonLanguage::getMessage($IsSales ? 'customer_name' : 'vendor_name') ?>:&nbsp;</strong><span id="Supplier_Name"></span>
                                    </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 echo CommonLanguage::getMessage($IsSales ? 'invoice' : 'purchase_voucher'); ?>
                                        #
                                        <span id='purchase_ID'></span></h4>
                                </div>
                                <div  class="form-group supInv" id="SupplierInv" style="">
                                    <h4><?php print CommonLanguage::getMessage('supplier_invoice'); ?> #</h4>
                                    <input id="Supplier_Invoice" name="Supplier_Invoice" class="form-control" value="" style="    width: 35%;
                                           margin-top: 11px;
                                           margin-left: 15px" />

                                </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="" />
                                    <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="">
                                    <span class="input-group-addon primary"><i class="fa fa-calendar-o"></i></span>
                                </div>



                                <div Default-Currency="<?php echo $DefaultCurrencyID; ?>" 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><strong><?php print CommonLanguage::getMessage('Select_Currency'); ?></strong></span>
                                        <input type="hidden" value="<?php echo $DefaultCurrencyID; ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" required/>
                                    </button>
                                    <ul class="dropdown-menu">
<?php echo($currencyList); ?>
                                        <li class="divider"></li>
                                        <li><a class="LoadMore"><?php print CommonLanguage::getMessage('More'); ?>..</a></li>
                                    </ul>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50" id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Code'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('product_name'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Quantity'); ?></th>
                                    <!--<th class="text-center"><?php // print CommonLanguage::getMessage('UOM');   ?></th>-->
                                    <th class="text-center"><?php print CommonLanguage::getMessage('unit_price'); ?></th>
                                    <th class="text-center" ><?php print CommonLanguage::getMessage('discount_percent'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('total'); ?></th>
                                </tr>
                            </thead>
                            <tbody>

                                <tr>
                                    <td><input type="text" class="form-control AutoComplete CODE" value=''></td>
                                    <td><input type="text" class="form-control AutoComplete ProductName" value=''></td>
                                    <td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber" value=''></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"></span></td>
                                </tr>

                            </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'); ?></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 style="text-align: left;display: inline-block;">
                                        <!--                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" >VAT 10%<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" id="InvoiceDiscountInput" value='' /> %</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>
                    </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">Phone: <?php echo $org_details[0]['Organization_Phone']; ?></span>
                        <span class="m-l-40 text-black sm-pull-right">Email: <?php echo $org_details[0]['Organization_Email']; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<script>
    var Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            account_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_account_first')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    var IsSalesMode = <?php echo $IsSales ? "true" : "false"; ?>;

    var TotalInvoice = 0,
            TotalDiscount = 0,
            TotalInvoiceWithoutDiscount = 0,
            UpdateTableTimeout, ReturnItemTableBody = $("#InventoryPurchaseTable tbody");
    if (IsSalesMode) {

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

    $(function () {
        $("#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 (!$("#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")
                }
            }
        });
        $("#InvoiceDiscountInput").on("blur keyup", function () {
            setTimeout("UpdateTable()", 100)
        })
        $("#InventoryPurchaseTable tbody").delegate("> tr input", "keydown", function (e) {
            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("")
                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).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()
            }
        })
        $("#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: {required: true, date: true}
            }
        })
        $("#InvoiceSubmitButton").on("click", ApplyPostMethod);
        UpdateSubmitButtonStatus()

        $("#search_invoice").on("keyup", function (e) {
            clearTimeout(UpdateTableTimeout);
            if (e.which == 13) {
                ChangeInvoice();
                return;
            }
            UpdateTableTimeout = setTimeout(function () {
                ChangeInvoice();
            }, 1000)
        });

    })
    })
    function ChangeInvoice() {
        var id = $('#search_invoice').val(),
                type = IsSalesMode ? 1 : 0,
                Data = {id: id,
                    invoiceType: type}
        $('#InventoryPurchaseTable').DataTable().destroy();
        $("#InventoryPurchaseTable tbody").empty();
        $.ajax({
            url: "InventoryAjax/ActualSalesInvoice",
            data: Data,
            dataType: "json",
            complete: function (v, vv) {
                if (vv == "success") {

                    var Data = (v.responseJSON),
                            DataTotal = Data[0],
                            DataDetail = Data[1];
                    console.log(Data)
                    $('#InventoryPurchaseTable').attr('data-net-total', IsSalesMode ? DataTotal[0]['Invoice_Net_Total'] : DataTotal[0]['Purchase_Net_Total'])
                    $('#purchase_ID').html(IsSalesMode ? DataTotal[0]['Invoice_ID'] : DataTotal[0]['Purchase_ID'])
                    if (!IsSalesMode)
                        $('#Supplier_Invoice').val(DataTotal[0]['Supplier_Invoice_ID'])
                    $('#Paid_Old').val(IsSalesMode ? DataTotal[0]['Invoice_Paid_Amount'] : DataTotal[0]['Purchase_Paid_Amount'])
                    $('#PurchaseInvoiceTotalPaid').html(IsSalesMode ? DataTotal[0]['Invoice_Paid_Amount'] : DataTotal[0]['Purchase_Paid_Amount'])
                    $('#Person_Code').val(DataTotal[0]['Account_Code'])
                    $('#Supplier_Name').html(IsSalesMode ? DataTotal[0]['Customer_Name'] : DataTotal[0]['Supplier_Name'])
                    $('#SupplierInfoContent').removeClass('hidden')
                    $('#PurchaseInvoiceDate').val(IsSalesMode ? DataTotal[0]['Invoice_Date'] : DataTotal[0]['Purchase_Date'])
                    $('#PurchaseInvoiceDueDate').val(IsSalesMode ? DataTotal[0]['Invoice_Due_Date'] : DataTotal[0]['Purchase_Due_Date'])
                    $('#Supplier_Customer_ID').html(IsSalesMode ? DataTotal[0]['Customer_ID'] : DataTotal[0]['Supplier_ID'])
                    $('#PurchaseInvoiceTotalDetails').html(IsSalesMode ? DataTotal[0]['Invoice_Net_Total'] : DataTotal[0]['Purchase_Net_Total'])
                    $('#InvoiceDiscountInput').val(IsSalesMode ? DataTotal[0]['Invoice_Discount'] : DataTotal[0]['Purchase_Discount'])
                    $('#CurrencyDropDown input').val(DataTotal[0]['Currency_ID'])
                    $('#CurrencyDropDown button span').html(DataTotal[0]['Currency_Name'])
                    $(".CurrencyIndicator").html(DataTotal[0]['Currency_Symbol'])
                    $("#Supplier_ID").val(IsSalesMode ? DataTotal[0]['Customer_ID'] : DataTotal[0]['Supplier_ID'])



                    var DetailLen = Object.keys(DataDetail).length
                    for (var i = 0; i < DetailLen - 2; i++) {

                        var TR = "<tr data-qty='" + DataDetail[i]['Item_Quantity_Current'] + "' data-uom='" + DataDetail[i]['UOM_ID'] + "' data-id='" + DataDetail[i]['Product_ID'] + "'>"
                        TR += " <td><input type='text' class='form-control AutoComplete CODE' value='" + DataDetail[i]['Code'] + "'></td>"
                        TR += " <td><input type='text' class='form-control AutoComplete ProductName' value='" + DataDetail[i]['Name'] + "'></td>"
                        TR += " <td><span class='Hint'></span><input type='text' class='form-control Quantity isnumber' value='" + (IsSalesMode ? DataDetail[i]['Product_Quantity'] : DataDetail[i]['Item_Quantity']) + "' disabled></td>"
                        TR += " <td><span class='Hint'></span><input type='text' class='form-control UnitPrice isnumber' value='" + (IsSalesMode ? DataDetail[i]['Product_Net_Price'] : DataDetail[i]['Item_Price']) + "'></td>"
                        TR += "<td><input type='text' class='form-control Disc' value='" + (IsSalesMode ? DataDetail[i]['Product_Discount'] : DataDetail[i]['Item_Discount']) + "'></td>"
                        TR += "<td class='TotalTD'><span class='CurrencyIndicator'>" + DataDetail[i]['Currency_Symbol'] + "</span>&nbsp;<span class='Total'>" + DataDetail[i]['Product_Total_Price'] + "</span></td></tr>"

                        TR = $(TR)
                        $("#InventoryPurchaseTable").append(TR)
                    }

                }
            }//end of ajax complete
        })
    }











    function UpdateTable() {
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0
        $("#InventoryPurchaseTable tr").each(function () {
            UpdateTotalForRow($(this))
        })
        var InvoiceDiscountInput = parseFloat($("#InvoiceDiscountInput").val()) || 0;
        var TotalInvoiceDisounted = TotalInvoice - (TotalInvoice * (InvoiceDiscountInput / 100))
        $("#PurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted": TotalInvoice, "MyValueDiscounted": TotalInvoiceDisounted}).text(AddCommas(TotalInvoiceDisounted.toFixed(3)))
        var SubTotalVal = TotalInvoiceWithoutDiscount * (1 - TotalDiscount / 100);
        $("#DiscountVal").html(AddCommas((TotalInvoiceWithoutDiscount - TotalInvoice).toFixed(3)))
        $("#InvoiceTotalAfterDiscount").text(AddCommas((TotalInvoiceWithoutDiscount * (InvoiceDiscountInput / 100)).toFixed(3)))
        setTimeout("UpdateSubmitButtonStatus()", 100)
        //        var vatVal=0,totalvat=0
        //        $("#InventoryPurchaseTable tbody tr").each(function(){
        //            var TRvalue = parseFloat($(".TotalTD .Total",$(this)).attr('myval'));
        //        if(TRvalue !=0){
        //            //alert(TRvalue)
        //            if($(this).attr('data-vat') == 1){
        //            vatVal = TRvalue * 0.1;
        //            totalvat += vatVal
        //            //alert(totalvat)
        //            $("#InvoiceVAT").html(totalvat.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.php?cmd=' + (who.hasClass("CODE") ? "1" : "2") + "&ClassID=" + classID, request, function (s, status, xhr) {
                            response(s);
                        });
                    },
                    minLength: 2,
                    select: function (event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.ID)
                        TR.attr("data-vat", ui.item.VAT)
                        TR.find("input.CODE").val(ui.item.Code)
                        TR.find("input.ProductName").val(ui.item.Name)
                        TR.find("input.UnitPrice").val(ui.item.Price)
                        //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")
                        return false;
                    }
                }).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.Code) : (item.Name);
                    return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
                }
                who.addClass("AutoAdded")
            }
        } else {
            if (!who.hasClass("AutoAdded")) {
                who.autocomplete({
                    source: function (request, response) {
//                        var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                        $.getJSON('xhr/getProducts.php?cmd=' + (who.hasClass("CODE") ? "1" : "2"), request, function (s, status, xhr) {
                            response(s);
                        });
                    },
                    minLength: 2,
                    select: function (event, ui) {
                        var TR = $(this).parents("tr");
                        TR.attr("data-id", ui.item.Product_ID ? ui.item.Product_ID : ui.item.Material_ID)
                        TR.attr("data-vat", ui.item.Product_VAT ? ui.item.Product_VAT : ui.item.Material_VAT)
                        TR.find("input.CODE").val(ui.item.Product_Code ? ui.item.Product_Code : ui.item.Material_Code)
                        TR.find("input.ProductName").val(ui.item.Product_Name ? ui.item.Product_Name : ui.item.Material_Name)
                        //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) + " " + (ui.item.Currency_ID ? ui.item.Currency_ID[1] : ""));
                        TR.find("input.Quantity").focus().prev().text((ui.item.Product_Quantity ? ui.item.Product_Quantity : ui.item.Material_Quantity) + " in stock")
                        return false;
                    }
                }).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.Product_Code ? item.Product_Code : item.Material_Code) : (item.Product_Name ? item.Product_Name : item.Material_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() {
        if ($("#Account_Code").val() == 0) {
            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(account_firstLang)
            $(document.body).animate({scrollTop: 0}, 800)

            return

        }
        $("#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(),
                        Products: []

                    };


            if (IsSalesMode) {
                Data.Customer_ID = $("#Supplier_Customer_ID").html();
                Data.Customer_Name = $("#Supplier_Name").html();
                Data.Customer_Account = $("#Person_Code").val();
                Data.Account_Code = $("#Account_Code").val();
                Data.Invoice_Date = $("#PurchaseInvoiceDate").val();
                Data.Invoice_Due_Date = $("#PurchaseInvoiceDueDate").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.Purchase_Invoice_ID = $('#search_invoice').val()
                Data.Paid_Old = $('#Paid_Old').val()
                Data.Old_Total = $('#InventoryPurchaseTable').attr('data-net-total')
                Data.Currency_Symbol = $('.CurrencyIndicator').html()
                Data.Products = [];
            } else {
                Data.Depot_ID = 0;
                Data.Account_Code = $("#Account_Code").val();

                Data.Supplier_Invoice_ID = $("#Supplier_Invoice").val();
                Data.Supplier_ID = $("#Supplier_Customer_ID").html();
                Data.Supplier_Name = $("#Supplier_Name").html();
                Data.Supplier_Account = $("#Person_Code").val();
                Data.Purchase_Date = $("#PurchaseInvoiceDate").val();
                Data.Purchase_Due_Date = $("#PurchaseInvoiceDueDate").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.Purchase_Invoice_ID = $('#search_invoice').val()
                Data.Paid_Old = $('#Paid_Old').val()
                Data.Old_Total = $('#InventoryPurchaseTable').attr('data-net-total')
                Data.Currency_Symbol = $('.CurrencyIndicator').html()
                //                Data.Invoice_VAT = $("#InvoiceVAT").html();
            }


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

                    if (IsSalesMode) {
                        Data.Products.push({
                            UOM_ID: me.attr("data-uom"),
                            Product_ID: me.attr("data-id"),
                            Product_Code: me.find(".CODE").val(),
                            Product_Name: me.find(".ProductName").val(),
                            Item_Quantity: me.attr("data-qty"),
                            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.attr("data-uom"),
                            Product_ID: me.attr("data-id"),
                            Product_Code: me.find(".CODE").val(),
                            Product_Name: me.find(".ProductName").val(),
                            Item_Quantity: me.attr("data-qty"),
                            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,.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;
                        } else {
                            $(this).removeClass("wrong")
                        }
                    })
                }
            })
            if (!IsValidated)
                return;
            $("#PurchaseDisabler").show();
            $.ajax({
                url: "InventoryAjax/ActualSalesInvoice",
                method: "POST",
                data: Data,
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        console.log(v1.responseText)
                        if (v1.responseText === 'OK') {
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                        } 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)
        }
    }
    function UpdateTotalForRow(who) {
        var Single_Price = parseFloat(who.find(".UnitPrice").val()) || 0,
                Qty = parseFloat(who.find(".Quantity").val()) || 0,
                Total = Single_Price * Qty,
                Discount = parseFloat(who.find(".Disc").val()) || 0,
                Net_Total = (Total * (1 - Discount / 100)) || 0;
        TotalInvoiceWithoutDiscount += Total;
        TotalDiscount += Discount
        TotalInvoice += Net_Total
        who.find(".Total").attr("MyVal", Net_Total.toFixed(3)).text(AddCommas(Net_Total.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;
        // 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 old = parseFloat($("#Paid_Old").val());
        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(old + A1 + A2 + A3);
    }
</script>
