
<style type="text/css">
    #InventoryPurchaseTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #InventoryPurchaseTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
        padding: 5px 9px 12px;
        /*font-size:12px;*/
        /*padding:0;*/
        /*padding-bottom:5px;*/
        height: 40px;
    }
    #InventoryPurchaseTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #InventoryPurchaseTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
    }
    #InvoiceVAT{
        display: inline-block;
        width: 92px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
        margin-left: 23px;
    }
    /*    #InventoryPurchaseTable .Hint{
    position: absolute;
    font-size: 10px;
    font-weight: bold;
    height: 20px;
    line-height: 20px;
    bottom: 2px;
    right: 4px;
    color: rgb(153, 153, 153);
    }*/
    #InventoryPurchaseTable .Hint{
        position: absolute;
        font-size: 10px;
        display: block;
        font-weight: bold;
        height: 12px;
        line-height: 11px;
        cursor: default;
        background: #ccc;
        padding: 0 2px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        bottom: 3px;
        right: 1px;
        left: 1px;
        color: #4c0870;
    }
    #InventoryPurchaseTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #InventoryPurchaseTable .Disc{
        width:70px;
    }
    #InventoryPurchaseTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    /*    .select2-container > .select2-choice{
    background-color: #e5e5e5;
    width: 150px;
    }*/
    #InventoryPurchaseTable .select2-container .select2-choice {
        background-image: none;
        border-radius: 2px;
        border: 1px solid rgba(0,0,0,0.07);
        padding: 5px 9px 16px;
        transition: border 0.2s linear 0s;
        height: 40px;
        background-color: #e5e5e5;
        width: 150px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    .hideme{
        display:none;
    }
    .select2-container > .select2-choice {
        width: 100% !important;
    }
    .supInv{
        display:inline-flex;
    }
    .invoice{
        padding-top:0 !important;
    }
    #Truck{
        width:48%;
        margin-right:2%
    }
    .right-div .form-group{
        margin-bottom:0px;
    }
</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.js?v=<?php echo trusto_VERSION; ?>"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.compatibility.js"></script>
<div id="PurchaseDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
<form method="POST" action="" onsubmit="return false" id="InvoiceForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id = "PurchaseSuccess" class = "hidden"></div>
                <div class = "invoice ">
                    <div class = "container-sm-height">
                        <div class = "row-sm-height">
                            <div class = "col-md-9 col-sm-height sm-no-padding">
                                <div class = "row " style = "display:flex;">
                                    <div class = "col-md-12"><h2 class = "font-montserrat all-caps hint-text"><?php echo CommonLanguage::getMessage('purchase_orders'); ?></h2></div>
                                </div>

                                <br>

                            </div>
                            <div class="right-div col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">

                                <div  style="display: flex">
                                    <div  class="form-group " style="width: 48%;margin-right:2%;">
                                        <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                        <input id="PurchaseInvoiceDate" name="PurchaseInvoiceDate" class="form-control" value="<?php echo $today; ?>" />
                                    </div>
                                    <div  class="form-group  "  style="width: 50%;" >
                                        <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                        <input id="PurchaseInvoiceDueDate" name="PurchaseInvoiceDueDate" class="form-control" value="<?php echo $today; ?>" required>
                                    </div>
                                </div>
                                <div  id="depot" class="form-group " style="display: flex;">
                                    <div style="width: 48%;margin-right:2%;" >
                                        <label><?php print CommonLanguage::getMessage('Depot'); ?></label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" value="<?= (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" data-select-name='<?= json_encode((smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name'])) ?>' />
                                    </div>
                                    <!--                                    <div style="width: 50%;" >
                                                                            <div  class="form-group " >
                                                                                <label><?php print CommonLanguage::getMessage('exchange_rate'); ?></label>
                                                                                <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>   />
                                                                            </div>
                                                                        </div>-->
                                </div>
                                <!--                                <div id="CurrencyIDContainer" class=" m-t-10" >
                                                                    <div class="form-group form-material floating ">
                                                                        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="">
                                                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                                <span><strong><?php // echo CommonLanguage::getMessage('select')           ?></strong></span>
                                                                                <input type="hidden"  value="<?php // echo $DefaultCurrencyID           ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID"/>
                                                                            </button>
                                                                            <ul class="dropdown-menu">
                                <?php // echo $CurList ?>
                                                                                <li class="divider"></li>
                                                                                <li><a class="LoadMore">More..</a></li>
                                                                            </ul>
                                                                        </div>
                                                                    </div>
                                                                </div>-->
                                <div   class="form-group " style="display: flex;">
                                    <div   class="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 1 ? '' : 'hidden' ?>" style="width: 48%;margin-right:2%;" >
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" />
                                    </div>
                                    <div class="<?php echo smc_session()['default_setting']['activate_project'] == 1 ? '' : 'hidden' ?>" style="width: 50%;" >
                                        <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                        <input type="hidden" class="full-width" id="project_id" />
                                    </div>

                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <!--<div id="ProdLoader" class="text-center alert <?php // echo ($IsEdit ) ? 'hideme' : ''           ?>" style="height:100%;background-color:#E2DEEF"> <h3 ><?php print CommonLanguage::getMessage($IsSales ? 'choose_customer_first' : 'choose_supplier_first'); ?> </h3> </div>-->
                        <table class="table  " id='InventoryPurchaseTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"style="width:5%"></th>
                                    <th class="text-center"style="width:10%"><?php print CommonLanguage::getMessage('barcode'); ?></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:5%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                    <th class="text-center" style="width:7%"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th class="text-center" style="width:7%"><?php print CommonLanguage::getMessage('supplier'); ?></th>
                                    <th class="text-center" style="width:7%"><?php print CommonLanguage::getMessage('class'); ?></th>
                                    <th class="text-center" style="width:7%"><?php print CommonLanguage::getMessage('Currency'); ?></th>
                                    <th class="text-center" style="width:7%"><?php print CommonLanguage::getMessage('Cost'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                foreach ($data as $item) {
                                    $uoms = explode('/', $item['Product_UOM']);
                                    ?>
                                    <tr data-conv="1" data-id="<?php echo $item['Item_ID'] ?>" >
                                        <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                        <td><input type="text" class="form-control AutoComplete CODE input-barcode-scan" value="<?php echo $item['Bar_Code'] ?>"></td>
                                        <td><input type="text" class="form-control AutoComplete ProductName" value="<?php echo $item['Product_Name'] ?>"></td>
                                        <td><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><input type="hidden" class="full-width supplier_id" value="<?php echo $item['Supplier_ID'] ?>" data-select-name="<?php echo $item['Supplier_Name'] ?>"></td>
                                        <td><input type="hidden" class="full-width class_id" value="<?php echo $item['supp_class_id'] ?>" data-select-name="<?php echo $item['Class_Name'] ?>"></td>
                                        <td><select class="full-width Currency_ID" data-init-plugin="select2">
                                                <?php foreach ($currency_list as $currency): ?>
                                                    <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" value="<?php echo $currency['Currency_ID']; ?>" <?php echo $currency['Currency_ID'] == $item['Currency_ID'] ? 'selected' : ''; ?>><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                <?php endforeach; ?>
                                            </select></td>
                                        <td><input type="number" min="0" step="any" class="form-control item_cost" readonly value="<?php echo $item['Product_Price'] ?>"></td>

                                    </tr>
                                <?php } ?>
                                <tr data-conv="1"  >
                                    <td>  <span id = "deleteRowRequest" class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                    <td><input type="text" class="form-control AutoComplete CODE input-barcode-scan" ></td>
                                    <td><input type="text" class="form-control AutoComplete ProductName" ></td>
                                    <td><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><input type="hidden" class="full-width supplier_id" ></td>
                                    <td><input type="hidden" class="full-width class_id" ></td>
                                    <td><select class="full-width Currency_ID" data-init-plugin="select2">
                                            <option value="" selected disabled></option>
                                            <?php foreach ($currency_list as $currency): ?>
                                                <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" value="<?php echo $currency['Currency_ID']; ?>" ><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                            <?php endforeach; ?>
                                        </select></td>
                                    <td><input type="number" min="0" step="any" class="form-control item_cost" readonly ></td>

                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <br>

                    <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"><?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')); ?>,
            RequiredField = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
            AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
            CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country')); ?>,
            FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb')); ?>,
            accountCodeLang = <?php echo json_encode(CommonLanguage::getMessage('account_code')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            account_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_account_first')); ?>,
            depot_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_depot_first')); ?>,
            supplier_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_supplier_first')); ?>,
            customer_firstLang = <?php echo json_encode(CommonLanguage::getMessage('choose_customer_first')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
//            cost_percent_validate = <?php echo json_encode(CommonLanguage::getMessage('cost_percent_validate')); ?>,
            default_vat = <?php echo json_encode(smc_session()['vat_percent']); ?>,
            negative_sales = <?php echo json_encode(smc_session()['negative_sales']); ?>;
    var is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
//            CurrencyRate = <?php // echo json_encode($Extable);           ?>,
            sales_order_id = <?php echo json_encode($id); ?>,
//            max_discount = <?php // echo json_encode(smc_session()['user_accounts']['max_discount']);           ?>,
//            ignore_zero_item_disc = <?php // echo json_encode(smc_session()['default_setting']['ignore_zero_item_disc'])           ?>,
            display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            uom_arr = <?php echo json_encode($all_uom); ?>;
    var inv_nb = <?php echo json_encode(CommonLanguage::getMessage('order') . ' #'); ?>;
    var TotalInvoice = 0,
            TotalDiscount = 0,
            TotalInvoiceWithoutDiscount = 0, vatVal = 0, totalvat = 0, taxAmount = 0, is_td_total = 0,
            percent_flag = 0, total_qty = 0;
    var CheckSubmit = true;

    $(function () {

        build_select2($("input.supplier_id"), ("xhr/supplierSearch"));
        build_select2($(".Depot_Loc"), "xhr/depotSearch")
        $("input.class_id").each(function () {
            var tr = $(this).parents("tr");
            build_select2($(this), "xhr/PricingClassSearch?type=1&supp_id=" + $("input.supplier_id",tr).val())

        })
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        $("#InventoryPurchaseTable").on("change", "input.supplier_id", function () {
            var tr = $(this).parents("tr");
            $("input.class_id", tr).val("").attr("data-select-name", "")
            build_select2($("input.class_id", tr), "xhr/PricingClassSearch?type=1&supp_id=" + $(this).val())

        })
        $(".CurrencyIndicator").html($("#CurrencyDropDown").attr("data-symbol"))

        $("#InventoryPurchaseTable").on("change", "input.class_id", function () {
            var me = $(this).parents('tr');
            if ($(this).val() == '') {
                $("input.item_cost", me).val('')
                return false;
            }


            var item_arr = {items: [{pid: me.attr("data-id"), uid: $("select[name=UOM_ID]", me).val()}], class_id: $(this).val()}
            $.ajax({
                url: "InventoryAjax/ReturnPriceByClass",
                data: item_arr,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        $.each(Data, function (index, value) {
                            me.find("input.item_cost").val(value['Product_Price'])

                        })

                    }
                }
            })
        })
//

        $("#InventoryPurchaseTable ").on("click", ".deleteRowRequest", function () {//to delete a row
            var numItems = $('#InventoryPurchaseTable tr').length;//number of rows
            if (numItems > 2) {//only if number of rows is more than one row remove the deleted row
                $(this).parents("tr").remove()
            }
        })
        if (!$("#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});
        $("#InventoryPurchaseTable").delegate(".Quantity,.UnitPrice,.Disc", "blur keydown", function (e) {
            is_td_total = 0;
            var me = $(this), TR = me.parents("tr");
            if (e.which == 13 && e.type == "keydown") {
                if (me.hasClass("Quantity")) {
                    TR.find(".UnitPrice").focus()
                } else if (me.hasClass("UnitPrice")) {
                    TR.find(".Disc").focus()
                } else {
                    TR.next().find(".CODE").focus()
                }
            }
            if (TR.index() < $("#InventoryPurchaseTable tbody").children().length - 1) {
                if ($.trim(me.val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null) {
                    me.addClass("wrong")
                } else {
                    me.removeClass("wrong")
                }
            }
        });
        $("#InventoryPurchaseTable tbody").delegate("> tr input", "keydown", function (e) {
            is_td_total = 0;
            CheckSubmit = false;
            var me = $(this)
            if (e.which == 8) {
                if (me.val() == "" && !me.hasClass("CODE")) {
                    me.parents("td").prev().find("input").focus()
                } else if (me.val() == "" && me.hasClass("CODE")) {
                    if (me.parents("tr").prev()) {
                        me.parents("tr").prev().find(".Disc").focus()
                    }
                }
            }
        })
        $("#InventoryPurchaseTable tbody").delegate("> tr input:not(.AutoComplete,.ttc_price )", "keyup", function (e) {
            is_td_total = 0;
            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
            $("tr", Parent).each(function (e) {
                if ($("tr", Parent).length > 1) {
                    var IsEmpty = true;
                    $(this).find("input").each(function () {
                        if ($(this).val() != "")
                            IsEmpty = false;
                    })
                    if (IsEmpty == true) {
                        if ($(this).index() <= $("#InventoryPurchaseTable tbody tr").length - 2) {
                            me.parents("tr").prev().find(".Disc").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input", Parent).each(function (e) {
                if ($(this).val() != "")
                    IsLastOneEmpty = false;
            })
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                ClonedRow.find("input").val("")
                ClonedRow.attr("data-conv", "1")
                Parent.append(ClonedRow);
                EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
                $("input", ClonedRow).removeClass("wrong")
                $(".select2-container", ClonedRow).empty().remove()
                $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
                ClonedRow.removeAttr("data-id data-prod-status")
                $("input.supplier_id", ClonedRow).val("").attr("data-select-name", "")
                build_select2($("input.supplier_id"), ("xhr/supplierSearch"));
                $("input.class_id", ClonedRow).val("").attr("data-select-name", "")
                build_select2($("input.class_id", ClonedRow), "xhr/PricingClassSearch?type=1&supp_id=" + $("input.supplier_id", ClonedRow).val())
                $("select.Currency_ID", ClonedRow).val('').select2()
                $(".select2-container", ClonedRow).show()
            }
        })
        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);
    });
    function EnableAutoComplete(who) {

        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: function (request, response) {
                    var depot_id = $("#Depot_Loc").val();
                    $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2") + '&depot_id=' + depot_id + '&type=2', request, function (s, status, xhr) {
                        response(s);
                    });
                },
                minLength: 0,
                select: function (event, ui) {
                    var TR = $(this).parents("tr");
                    TR.attr("data-id", ui.item.ID)
                    TR.attr("data-qty", ui.item.Quantity)
                    TR.find("input.CODE").val(ui.item.Bar_Code)
                    TR.find("input.ProductName").val(ui.item.Name)
                    $("select[name=UOM_ID]", TR).empty();
                    if (event.which != 9)
                        TR.find("input.Quantity").focus().next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                    else
                        TR.find("input.Quantity").next().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                    //                        TR.find("input.Quantity")/*.focus()*/.prev().text((ui.item.Quantity) + " in stock");
                    var units_arr = ui.item.Product_UOM.split("/");
                    for (var i = 0; i < units_arr.length; i++) {
                        $("select[name=UOM_ID]", TR).append('<option value="' + units_arr[i] + '" ' + (units_arr[i] == ui.item.UOM_ID ? 'selected' : '') + '>' + uom_arr[units_arr[i]]['UOM_Name'] + '</option>')
                    }
                    $("select[name=UOM_ID]", TR).select2()
//                        UpdateTable()
                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width() * (this.element.hasClass("CODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = this.element.hasClass("CODE") ? (item.Bar_Code) : (item.Cat_Name + item.Name + ' - ' + item.Code);
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }

    }
    function ApplyPostMethod() {
        $("#PurchaseSuccess").attr("class", "hidden");
        if ($("#InvoiceForm").valid()) {
            var IsValidated = true,
                    Data = {
                        Products: []
                    };
            var total_cost = 0, is_negative_value = false, supp_class_check = false;
            console.log(supp_class_check)
            $("#InventoryPurchaseTable tbody tr").each(function (e) {
                var me = $(this);
                var qty = parseFloat(me.find(".Quantity").val() || 0);
                total_cost += (parseFloat(me.find("input.item-cost").val() || 0) * qty);
                total_cost += (parseFloat(me.find("input.item-other-cost").val() || 0) * qty);

                if (me.find(".Quantity").val() != '' && me.find(".ProductName").val() != '' && me.find('.UnitPrice').val() != '') {
                    if ($("input.supplier_id", me).val() == '' || $("input.class_id", me).val() == '') {
                        supp_class_check = true;

                    }
                    Data.Products.push({
                        UOM_ID: me.find("select.UOM_ID").val(),
                        Product_ID: me.attr("data-id"),
                        Item_Quantity: me.find(".Quantity").val(),
                        Currency_ID: me.find("select.Currency_ID").val(),
                        class_id: $("input.class_id", me).val(),
                        supplier_id: $("input.supplier_id", me).val(),
                        item_cost: $("input.item_cost", me).val() || 0,
                        Product_Total_Price: parseFloat($("input.item_cost", me).val() || 0) * parseFloat(me.find(".Quantity").val() || 0),
                        Depot_ID: $("#Depot_Loc").val(),
                        Invoice_VAT: 0,
                        discount_amount: 0,
                        is_actual: is_actual ? 1 : 0,
                        sales_order_id: sales_order_id,
                        job_id: $("#job_id").val(),
                        project_id: $("#project_id").val(),
                        Invoice_Date: $("#PurchaseInvoiceDate").val(),
                        Invoice_Due_Date: $("#PurchaseInvoiceDueDate").val() ? $("#PurchaseInvoiceDueDate").val() : $("#PurchaseInvoiceDate").val(),
                    });
                    //                    }
                    me.find(".ProductName,.Quantity,.UnitPrice").each(function () {
                        if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                            $(this).addClass("wrong")
                            CheckSubmit = false;
                            IsValidated = false;
                        } else {
                            $(this).removeClass("wrong")
                        }
                    })
                    if (me.attr("data-id") == '0' || me.attr("data-id") == '' || me.attr("data-id") == undefined || me.find("select.UOM_ID").val() == '') {
                        me.find(".CODE").addClass("wrong")
                        me.find(".ProductName").addClass("wrong")
                        IsValidated = false;
                        CheckSubmit = false;
                    }


                }
            })
            if (!IsValidated)
                return;
            if (supp_class_check) {
                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('class_supplier_required'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (Data.Products.length == 0) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_negative_value) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('negative_value'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if ($('#PurchaseInvoiceDueDate').val() < $('#PurchaseInvoiceDate').val()) {
                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('duedate_greater_currentdate'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }

            $("#PurchaseDisabler").show();
            $.ajax({
                url: "InventoryAjax/sales_to_purchase_ajax",
                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").attr("disabled", "disabled")
                            CheckSubmit = true;
                        } else {
                            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseText)
                            CheckSubmit = false;
                        }
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        CheckSubmit = false;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#PurchaseDisabler").hide();
                }
            })
        } else {
            $("#PurchaseSuccess").attr("class", "alert alert-warning").html(RequiredField)
            $(document.body).animate({scrollTop: 0}, 800)
        }
    }
    function 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 (DoDisable) {
            $("#InvoiceSubmitButton").addClass("disabled")
        } else {
            $("#InvoiceSubmitButton").removeClass("disabled")
        }
    }
    $(document).ready(function () {
        window.onbeforeunload = function (e) {
            if (!CheckSubmit) {
                var message = have_not_saved, e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }
    });
    function printExternalInv(url, btn_id) {
        $("#print_iframe").remove();
        $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:800px;height:800px;display:none;' src='" + url + "' onload='document.getElementById(\"print_iframe\").contentWindow.document.getElementById(\"" + btn_id + "\").click();'  ></iframe>").appendTo("body");
    }
    function updateDueDate(nb_days) {
        if (nb_days && nb_days != 0 && $('#PurchaseInvoiceDate').val()) {
            var date2 = $('#PurchaseInvoiceDate').datepicker('getDate');
            date2.setDate(date2.getDate() + parseInt(nb_days));
            $('#PurchaseInvoiceDueDate').datepicker('setDate', date2);
        }
    }
</script>
