/**
 * 
 * creating object for pos database add/edit/delete 
 */
var pos_db_obj = function() {
    var hxa_pos_db = null;

    //here create local variable inside this scope
    var init_db = function(callback_ft) {
        if (hxa_pos_db !== null)
            return callback_ft(true);
        //prefixes of implementation that we want to test
        window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
        //prefixes of window.IDB objects
        window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
        window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
        if (window.indexedDB) {
            var open_request = window.indexedDB.open('hxa_pos_db', 1);
            open_request.onupgradeneeded = function(event) {
                hxa_pos_db = event.target.result;
                //Create a new datastore.
                var object_store = hxa_pos_db.createObjectStore('pos_cat_prd', { keyPath: 'uniq_id' });
                //                //use transaction oncomplete to make sure the objectStore creation is finished if want to add data into it.
                //                object_store.transaction.oncomplete = function (event) {
                //                    // Store values in the newly created objectStore.
                //                    var object_store = db.transaction('pos_cat_prd', 'readwrite').objectStore('pos_cat_prd');
                //                    [{uniq_id: 1_1, data: "any data row 1"}, {uniq_id: 2_1, data: "any data row 3"}].forEach(function (row_data) {
                //                        object_store.add(row_data);
                //                    });
                //                };
            };
            //Handle successful datastore access.
            open_request.onsuccess = function(event) {
                hxa_pos_db = event.target.result; //open_request.result
                return callback_ft(true);
            };
            //Handle errors when opening the datastore.
            open_request.onerror = function(event) {
                return callback_ft(false);
                //console.log("indexed db open error! " + open_request.errorCode);
            };
        } else
            return callback_ft(false);
    };

    //here set a property for .this with function, and can be called outside
    this.get_cat = function(uniq_id, callback_ft) {
        if (pos_cache_time_min <= 0)
            return callback_ft(false);
        var prnt = this;
        init_db(function(is_init) {
            if (!is_init)
                return callback_ft(false); //init db. failed
            var transaction = hxa_pos_db.transaction(['pos_cat_prd']);
            var object_store = transaction.objectStore('pos_cat_prd');
            var read_request = object_store.get(uniq_id);
            read_request.onerror = function(event) {
                //console.log("Unable to retrieve daa from database!");
                callback_ft(false);
            };
            read_request.onsuccess = function(event) {
                //Do something with the request.result!
                if (read_request.result) {
                    if (read_request.result.expiry < Date.now()) {
                        //data already expired, so delete this old data
                        return prnt.remove_cat(uniq_id, function() {
                            callback_ft(false);
                        });
                    }
                    return callback_ft(read_request.result);
                }
                callback_ft(false); //data couldn't be found in your database!
            };
        });
    };

    //                //
    //                this.get_all_cat = function () {
    //                    init_db(function(){
    //                        var object_store = hxa_pos_db.transaction('pos_cat_prd').objectStore('pos_cat_prd');
    //                        object_store.openCursor().onsuccess = function (event) {
    //                            var cursor = event.target.result;
    //                            if (cursor) {
    //                                alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
    //                                cursor.continue();
    //                            } else {
    //                                alert("No more entries!");
    //                            }
    //                        };
    //                    });
    //                };

    //
    this.add_cat = function(new_uniq_id, cat_data) {
        //before add we try to delete previous one since mayb expired
        this.remove_cat(new_uniq_id, function() {
            init_db(function(is_init) {
                if (!is_init)
                    return false; //init db. failed
                var add_request = hxa_pos_db.transaction(['pos_cat_prd'], 'readwrite').objectStore("pos_cat_prd")
                    .add({ uniq_id: new_uniq_id, data: cat_data, expiry: (Date.now() /*in ms.*/ + (60000 * pos_cache_time_min)) });
                add_request.onsuccess = function(event) {
                    //data has been added to your database.
                };
                add_request.onerror = function(event) {
                    //Unable to add data, it is aready exist in your database!
                };
            });
        });
    };

    //
    this.remove_cat = function(uniq_id, callback_ft) {
        init_db(function(is_init) {
            if (!is_init)
                return callback_ft(false); //init db. failed
            var remove_request = hxa_pos_db.transaction(['pos_cat_prd'], "readwrite").objectStore('pos_cat_prd').delete(uniq_id);
            remove_request.onsuccess = function(event) {
                callback_ft(true); //entry has been removed from your database.
            };
            remove_request.onerror = function(event) {
                callback_ft(false); //entry not exist or error while removed
            };
        });
    };

    //
    this.remove_all_cat = function(callback_ft) {
        init_db(function(is_init) {
            if (!is_init)
                return callback_ft(false); //init db. failed
            var remove_request = hxa_pos_db.transaction(['pos_cat_prd'], "readwrite").objectStore('pos_cat_prd').clear(); //clear is for deleting all current records out of an object store.
            remove_request.onsuccess = function(event) {
                callback_ft(true); //all entries has been removed from your database.
            };
            remove_request.onerror = function(event) {
                callback_ft(false); //error while removed
            };
        });
    };
};
var pos_db = new pos_db_obj();
/**
 * 
 */

var update_total_timeout = false,
    Customer_ID,
    CurCats, SubC, CurPage, LastPage, CurPath, BestHeight = 0,
    Colors = [
        "Color1#rgb(16,207,189)",
        "Color2#rgb(72,176,247)",
        "Color3#rgb(109,92,174)",
        "Color4#rgb(245,78,83)",
        "Color5#rgb(10,124,113)"
    ],
    CategTemp = '<li class="pers" style="[pos_cell_style]" >' +
    '	<div class="$FROM$" style="min-width: 75px;">' +
    '		<a href="javascript:void()" data-id="$ID$" data-name="$NAME$" class="$CHILDCLASS$">' +
    '			<div class="$COLOR$ category-boxes" style="border:1px solid $STATUSBORDERCOLOR$;$STATUSSTYLE$;position:relative;"><table style="margin:0px 0 6px 0;" cellpadding="0" cellspacing="0" id="table_show_img"><tr><td>[thumb_img]</td></tr></table>' +
    '				<span class="IconCaption pers" style="font-size: 3vw;    margin-top: -10px;"><b style="text-shadow: 0 0 3px black;">$NAME$</b></span>' +
    '			</div>' +
    '		</a>' +
    '	</div>' +
    '</li>',
    ProductTemp = '<li class="pers" style="[pos_cell_style]" >' +
    '	<div class="$FROM$ Product" onselectstart="return false" ondragstart="return false">' +
    '	<a href="javascript:void()" data-disabled="$STATUS$" data-uom="$UOM$" data-id="$ID$" data-barcode="$BARCODE$" data-name="$NAME$" data-product-ref="$PRODUCTREF$" data-price="$PRICE$" data-discount="$DISCOUNT$" data-cost="$COST$" data-last-price="$LASTPRICE$" data-product-qty="$QTY$" data-vat="$VAT$" vat-percent="$VATPERCENT$" vat2-percent="$VAT2PERCENT$" data-is-option="$HASOPTIONAL$" recipe-qty="$RECIPEQTY$" ttc-price="$TTCPRICE$" data-max-discount="$MAXDISC$" item-units="$IUNITS$" data-tax="$TAX$" tax-amount="$TAXAMOUNT$" class="Product" expiry-active="$EXPIRYACTIVE$" data-lot="$ISLOT$" data-service="$ISSERVICE$" data-serial="$ISSERIAL$" data-conv="$UOMCONV$" reserve-active="$RESERVEACTIVE$" change-price="$CHANGEPRICE$" data-expiry-date="" data-category-id ="$CATEGORYID$">' +
    '			<div class="$COLOR$ product-boxes" style="border:1px solid $STATUSBORDERCOLOR$;$STATUSSTYLE$"><table style="margin:0px 0 6px 0;" cellpadding="0" cellspacing="0" id="table_show_img"><tr><td>[thumb_img]</td></tr></table>' +
    '				<span class="IconCaption pers" style="top:0%;"><div class="Price price_element $PRICECLASS$" style="position:relative;top:3px;">$QTY$</div><span style="white-space: pre-line !important ;text-overflow: ellipsis;overflow: hidden;text-shadow: 0 0 3px black;"">$NAME$</span></span>' +
    '			</div>' +
    '		</a>' +
    '	</div>' +
    '</li>',
    RowTemp = '';
$(function() {

    var uom_select = $("select[name=UOM_Select]").html();
    var pos_cell_style = 'display:inline-table;width: 15%;padding: 0px 0px;padding-left: 3px;';
    CategTemp = CategTemp.replace("[pos_cell_style]", pos_cell_style);
    CategTemp = CategTemp.replace('[thumb_img]', (show_category_image_pos == 1 ? '$THUMB$' : ''));
    ProductTemp = ProductTemp.replace("[pos_cell_style]", pos_cell_style);
    ProductTemp = ProductTemp.replace('[thumb_img]', (show_product_image_pos == 1 ? '$THUMB$' : ''));
    RowTemp = '	<td class="transfer_items_details entry_checkbox $CHECKBOX$"><input type="checkbox" name="entry_id"/> <input type="number" min="1" class="hidden" name="transfer_quantity" value="" onkeyup="ChangeQuantity(this)" onchange="ChangeQuantity(this)"/></td>' +
        '	<td class="Number">$ID$</td>' +
        '	<td class=" ' + (activate_pos_hold_fire == 1 && destination_type != 0 && is_smart_diner == 1 ? '' : 'hidden') + ' hold_td $holdclass$">$holdlevel$</td>' +
        '	<td class="Name">' + (view_barcode_in_pos == 1 ? '<span class="item-barcode">$BARCODE$<br></span>' : '') + '<span class="item-name" >$NAME$</span></td>' +
        '	<td class="qty-td">' +
        '		<div class="input-group InputSpinner">' +
        '<span class="qty_span max_qty_number">1</span>' +
        '		</div><span class="qty-hint Hint ' + ((view_stock_qty_in_pos == 1 && show_qty_stock_perm) ? '' : 'hidden') + '">$QTYHINT$</span>' +
        '	</td><td  class="' + (is_uom_active == 1 ? '' : 'hidden') + '"><select class="uom" name="uom">' +
        uom_select +
        '	</select></td>' +
        '	<td class="UPrice price_element ' + (show_all_prices ? '' : 'hidden') + '"><div class="input-group "><div style="display:flex"><span class="uprice-span max_price_number">$UNITPRICE$</span><span class="currency-sym">$CURRENCY$</span></div><span class="cost-hint ' + ((view_cost_in_pos == 1 && view_cost_permission == 1) ? '' : 'hidden') + '">$COSTHINT$</span><span class="price-hint ' + ((view_last_price_permission == 1) ? '' : 'hidden') + '">$PRICEHINT$</span></div></td>' +
        '	<td class=" disc-td ' + ((is_discount_active == 1 && show_all_prices) ? '' : 'hidden') + '"><span class="discount" data-disc="$DISCOUNT$">$DISCOUNT$ %</span></td>' +
        '	<td class="total-price-td price_element ' + ((show_all_prices) ? '' : 'hidden') + '"><span class="price" curprice="$PRICE$">$PRICE$</span> <span class="currency-sym">$CURRENCY$</span></td>';
    RowTemp += '<td class="product_description ' + (is_prod_desc_acive == 1 ? '' : 'hidden') + '"><i class="fa fa-sticky-note prod-desc-icon"></i></td>	<td class="tag-main-td ' + (is_tag_active == 1 ? '' : 'hidden') + '"><div class=" bootstrap-tagsinput"> ' + no_tags_lang + ' </div></td>';
    RowTemp += '<td class="reserve_date ' + (is_active_reserve_date == 1 ? '' : 'hidden') + '">$RESERVEICON$</td><td class="expiry_date ' + (is_active_expiry_date == 1 ? '' : 'hidden') + '">$EXPIRYICON$</td>	<td class="del-tr ' + (delete_row_pos ? '' : 'hidden') + '" ><span class="red-star "><i class="fa fa-trash" style="font-size:18px;"></i></span></td>';
    RowTemp += '	<td class="" ><span class="red-star "><i class="fa fa-th-list option-tr cursor hidden" style="font-size:18px;"></i></span></td>';
    //            '	<td class="hidden"><div class=" bootstrap-tagsinput"> ' + no_tags_lang + ' </div></td>';
    $("#OrderTable").on("change", "select.uom", function() {
        var me = $(this).parents("tr"),
            UOMData = {
                pid: $(this).parents("tr").attr("data-id"),
                uid: $(this).val(),
                depot_id: default_depot_id,
                class_id: $("#Customer_Class_ID").val(),
                customer_id: $("#CurCustomerInfo").attr('CurCustomerID') ? $("#CurCustomerInfo").attr('CurCustomerID') : 0
            };
        $.ajax({
            url: "InventoryAjax/ReturnProductUOMPriceCon",
            data: UOMData,
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {
                    //console.log(me.attr('data-cost'))
                    //console.log(v1.responseJSON['last_cost'])
                    is_ttc = v1.responseJSON['is_ttc']
                    me.attr('data-cost', v1.responseJSON['last_cost'])
                    me.attr('data-last-price', v1.responseJSON['last_price'])
                    me.attr('data-conv', v1.responseJSON['conversion_amount'])
                    me.attr("data-price-single", v1.responseJSON['Product_Price'])
                    me.attr("data-price-single-orginal", v1.responseJSON['Product_Price'])
                    me.attr("data-price-single-orginal-ttc", v1.responseJSON['ttc_price'])

                    me.attr("expiry-active", v1.responseJSON['is_expiry'])
                    me.attr("data-discount", v1.responseJSON['disc'])
                    me.attr("reserve-active", v1.responseJSON['duration_reservation'])
                    me.find('span.discount').attr("data-disc", v1.responseJSON['disc']).html(round_number(v1.responseJSON['disc']) + ' %')
                    if (v1.responseJSON['is_expiry'] == 1)
                        me.find('td.expiry_date').html('<i class="fa fa-calendar expiry-icon"></i>')
                    me.attr("ttc-price", v1.responseJSON['ttc_price'])
                    me.find(".UPrice span.uprice-span").html(AddCommas(public_round_number(parseFloat(v1.responseJSON['Product_Price']))))
                    me.find("span.price").attr("curprice", v1.responseJSON['Product_Price'])
                    me.find("span.qty-hint").html('(' + AddCommas(public_round_number(parseFloat(v1.responseJSON['qty']))) + ')')
                        //console.log('cost= '+me.attr('data-cost')+'=== conv'+v1.responseJSON['conversion_amount']+'=== total='+parseFloat(me.attr('data-cost'))/(parseFloat(v1.responseJSON['conversion_amount'])))
                    me.find("span.cost-hint").html('(' + AddCommas(parseFloat(parseFloat(me.attr('data-cost')) * (public_round_number(parseFloat(v1.responseJSON['conversion_amount']))))) + ')');
                    me.find("span.price-hint").html('(' + AddCommas(parseFloat(parseFloat(me.attr('data-last-price')) * (public_round_number(parseFloat(v1.responseJSON['conversion_amount']))))) + ')');
                    me.find("span.item-barcode").html((v1.responseJSON['Bar_Code'] === '' || v1.responseJSON['Bar_Code'] === null) ? '' : (v1.responseJSON['Bar_Code'] + '<br>'))
                    setTimeout(function() {
                        UpdateTable(me.parents("tbody"))
                    }, 100);
                }
            }
        });
    });
    //    $('.number_formatted_tooltip').tooltip({
    //        placement: "top",
    //        title: "",
    //    });
    //
    //    $(document).on("input",'.number_formatted',function(){
    ////        console.log('here')
    //        var current_value = $(this).val(),
    //            tooltip_id = $(this).attr('data-tooltip');
    //        $(this).parents('.'+tooltip_id).attr('data-original-title',AddCommas($(this).val()||0));
    //        $(this).parents('.'+tooltip_id).tooltip(!current_value ? "hide"  :"show");
    //        $(this).parents('.'+tooltip_id+'.block_tooltip').addClass("block");
    //    });
    //    $(document).on("blur", '.number_formatted',function(){
    //        var tooltip_id = $(this).attr('data-tooltip');
    //        $(this).parents('.'+tooltip_id).tooltip("hide");
    ////        $(this).parents('.'+tooltip_id).removeClass("block");
    //    });
    window.onbeforeunload = function() {
        if ($("#OrderTable tbody tr").length > 0) {
            return "You haven't finished your invoice yet. Do you want to leave without finishing?";
        }
    }
    $("#EditDiscount .modal-footer > .btn.btn-primary").on("click", EditTotalDiscountEvent)
    $("#DiscountInput").on("keyup", function(e) {
        //        if (e.which == 13)
        EditTotalDiscountEvent();
    });
    $('#TotalTable td.DiscountVal').on("change", function(e) {
        //        if (e.which == 13)
        EditDiscountEventByPrice();
    })

    $("input.TTCDiscountValue").on("blur", function() {
        //console.log(primary_total)
        $("#DiscountInput").val((parseFloat($(this).val()) / primary_total * 100) || 0)
        $("#EditDiscount").data("MyTarget", $("#TotalTable .TotalSpanInTable > .discount"))

        EditTotalDiscountEvent();
    })
    $("input.DiscountValue ").on("blur", function() {
        var subtotal = parseFloat($(".SubtotalVal").attr("data-subtotal")) || 0;
        //console.log(primary_total)
        $("#DiscountInput").val(public_round_number(parseFloat($(this).val()) / subtotal * 100) || 0)
        $("#EditDiscount").data("MyTarget", $("#TotalTable .TotalSpanInTable > .discount"))

        EditTotalDiscountEvent();
    })

    function EditDiscountEventByPrice() {
        var DIS = parseFloat($('#TotalTable .DiscountVal >.DiscountValue').val()) || 0;
        var Max = parseFloat($("#TotalTable td.SubtotalVal").attr("data-subtotal")) || 0;
        DIS = DIS < 0 ? 0 : DIS;
        if (Max > 0)
            DIS = DIS > Max ? Max : DIS;
        var Dis_percent = (Max == 0) ? 0 : ((DIS * 100) / Max);
        if (Dis_percent > parseFloat(user_max_discount))
            Dis_percent = parseFloat(user_max_discount);
        var it = $('#TotalTable td.DiscountVal');
        it.parents("tr").attr("data-discount", Dis_percent)
        $('#TotalTable .TotalSpanInTable .discount').html(public_round_number(Dis_percent) + " %");
        UpdateTable($("#OrderTable > tbody:last"));


    }

    $("#InvTypeMpdal").on("shown.bs.modal", function() {
        $("#cash_amount").focus().select()
            //        $("#cash_cat_amount").focus().select()
            //        if ($("#CurCustomerInfo").attr("CurCustomerID") != 0 && $('#invoice_unpaid_amount').val() != 0)
            //            $('#customer_id').attr("readonly", true)
            //
            //        else {
            //            $('#customer_id').removeAttr("readonly")
            //        }
    })

    $("#EditDiscount").on("shown.bs.modal", function() {
        if (checkPrintDisbaled())
            $('#SubmitDisc').prop('disabled', true)
        else
            $('#SubmitDisc').prop('disabled', false)

        var di = $("#DiscountInput").get(0);
        di.focus();
        di.setSelectionRange(0, di.value.length)

    });
    $("#EditDiscount .modal-body .InputSpinner .btn,#PaymentModal .modal-body .InputSpinner .btn,#InvoicePaymentSetup .InputSpinner .btn").on('click', function() {
        var Input = $("input", $(this).parent().parent()),
            V = parseInt(Input.val())
        Input.val($(this).hasClass("more") ? V + 1 : V == 0 ? 0 : V - 1)
    })
    $("#PaymentModal .modal-body .InputSpinner .btn,#InvoicePaymentSetup .InputSpinner .btn").on('click', function() {
        var Input = $("input", $(this).parent().parent()),
            V = parseInt(Input.val())
        Input.val($(this).hasClass("more") ? V + 1 : V == 0 ? 0 : V - 1)
    })
    $("#PageIndicatorHandler").delegate("li", "click", function() {
        GotoPage(parseInt($(this).attr("data-slide")));
        //UpdatePaginators(); //added for new pagination idea
    });
    $("#CurCategory_Crumbs").delegate("a", "click", function(e) {
        e.preventDefault()
        if ($("#Tab_1").hasClass("Busy"))
            return;
        var ID = parseInt($(this).attr("data-id"));
        if (ID == -1)
            GotoCateg(-1);
        else {
            CurPath = CurPath.slice(0, parseInt($(this).attr("CurPath")) + 1)
            AjaxLoadCateg(ID, Customer_ID);
        }
    })
    $("#CurAvailableItemsContainer")
        //        .delegate("> ul.Categories > li", "mouseenter", function (e) {
        //        var Prod = $(this).find("a.Product");
        //
        //        if (Prod.length > 0) {
        //            $(this).find(".ProductFullName").remove();
        //            var D = $("<div class='ProductFullName'><span class='Price'>" + Prod.attr("data-price") + " " + PrimaryCurrency[1] + "</span>" + Prod.attr("data-name") + "<br/></div>")
        //            D.css({"background": $(">div", Prod).css("background")})
        //            $(">div", Prod).append(D)
        //
        //            setTimeout(function () {
        //                D.addClass("Shown")
        //            }, 10)
        //        }
        //    }).delegate("> ul.Categories > li", "mouseleave", function (e) {
        //        var ProductFullName = $(this).find(".ProductFullName");
        //        ProductFullName.removeClass("Shown")
        //        setTimeout(function () {
        //            ProductFullName.remove()
        //        }, 300)
        //    })
        .delegate("> ul.Categories > li a[data-id]", "click", function(e) {

            e.preventDefault();
            if (checkPrintDisbaled())
                return;
            var me = $(this);
            /**
             @edited by: Smartclick
             @added: condition to the line below: && me.data("disabled") == false
             @reason: when product qty is 0, data-disabled will be set to false.
             when data-disbaled is flase, the item will not be added to
             table.
             */
            if (me.hasClass("Product") && me.data("disabled") == false) {
                AddItemToTable(me);
            } else {
                if (!me.hasClass("HasChild")) {
                    return;
                }
                if (me.hasClass("Disabled")) {
                    toastr.error(no_qty_lang)
                    return;
                }
                setTimeout(function() {
                    if ($("#Tab_1").attr("DidSwipe") == "true")
                        return;
                    var ID = me.attr("data-id");
                    CurPath.push([ID, me.attr("data-name")]);
                    $("#CurAvailableItems").find(".Shown").attr("class", $(this).parent().hasClass("FromRight") ? "FromRight" : "FromLeft");
                    AjaxLoadCateg(ID, Customer_ID)
                }, 10);
                me.addClass("Disabled");
            }
        });
    //    SwipeDetect(document.getElementById("Tab_1"), function (swipedir) {
    //        if (swipedir == "left") {
    //            GotoPage(++CurPage)
    //        } else if (swipedir == "right") {
    //            GotoPage(--CurPage)
    //        }
    //    })

    init_swipe_obj($('#RightBoxContents'), {
        margin_px: 70,
        scroll_ft: function(type, amount_px) {
            if (type == 'left')
                GotoPage(++CurPage);
            else if (type == 'right')
                GotoPage(--CurPage);
        }
    });

    GotoCateg(-1);
    //    if (IsTouchDevice())
    //        $("body").addClass("TouchDevice")
    $("body > .wrapper > .left-side").addClass("collapse-left")
    $("body > .wrapper > .right-side").addClass("strech")
    $("section.content-header").remove()
    UpdateTable($("#OrderTable > tbody:last"))
    var Style = "<style type='text/css'>"
    for (var x = 0; x < Colors.length; x++) {
        var CC1 = Colors[x].split("#")[1];
        var CurColor = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/.exec(CC1);
        CurColor[1] -= 40;
        CurColor[2] -= 40;
        CurColor[3] -= 40;
        var CC2 = "rgb(" + CurColor[1] + "," + CurColor[2] + "," + CurColor[3] + ")";
        Style += "ul.Categories > li > div > a > div." + Colors[x].split("#")[0] + ":before{background-color:" + CC1 + ";}"
        Style += "ul.Categories > li > div > a > div." + Colors[x].split("#")[0] + "{border:1px solid " + CC1 + ";background-color:" + CC1 + ";}"
        Style += "ul.Categories > li > div > a > div." + Colors[x].split("#")[0] + ":hover{background-color:" + CC2 + ";}"
        Style += "ul.Categories > li > div > a:not(.Product):not(.HasChild) > div." + Colors[x].split("#")[0] + "{opacity: 0.7;background-color:" + CC1 + " !important;}"
    }
    Style += "</style>"
    $("head").append(Style)
    $("#TotalTable .TotalSpanInTable > .discount").on("click", function() {
        if ($(this).hasClass('current_disable'))
            return false;
        $("#EditDiscount").data("MyTarget", $(this))
            .find(".modal-title").html("Discount").end().find(".modal-field-caption").html("Discount(%):")
        $("#DiscountInput").val(parseFloat($(this).parents("tr").attr('data-discount')) || 0)
        $("#EditDiscount").attr("data-max", user_max_discount)
        $("#EditDiscount").modal();
    })
    PrepareAutoComplete()
    $("#RightBoxContents *").each(function() {
        this.onselectstart = this.ondragstart = function() {
            return false
        }
    });

    //    PrepareDropDowns();
});

function enable_all_customers() {

    $("#customer_id").autocomplete({
            source: "POSAjax/getCustomerForAutoComplete",
            minLength: 1,
            position: { my: "left top", at: "left bottom", collision: "none" },
            select: function(event, ui) {
                Customer_ID = ui.item.Customer_ID;

                if (Customer_ID != 0) {
                    customerSelectAutocomplete(ui)

                } else {
                    $('#Loader').removeClass('hideme')
                }

                return false;
            }
        }).autocomplete("instance")._renderItem = function(ul, item) {
            var Content = "<table cellspacing='0' cellpadding='0'><tr><td class='Column1'><i class='fa fa-file-o'></i></td><td><strong >" + item.Customer_Name + " - " + item.Customer_Mobile + "</td></tr></table>"
            return $("<li class='" + (item.is_pos_customer == 1 ? 'primary-text' : '') + "'>").html(Content).appendTo(ul)

        }
        // This method is to resize the menu to same width as the input
    $("#customer_id").autocomplete("instance")._resizeMenu = function(ul, items) {
        this.menu.element.outerWidth($("#customer_id").parent().width());
    }


}

function AddLoader(Smoothly) {
    $("#CategLoader").parent().remove();
    var L = $("<div style='text-align:center;margin-bottom:20px'><img src='img/ajax-loader.gif' id='CategLoader'/></div>");
    if (Smoothly) {
        L.css({ opacity: 0 }).animate({ opacity: 1 })
    }
    L.css({ position: "absolute", left: 0, right: 0, top: "50%" })
    $("#Tab_1").append(L)
}

function GotoCateg(idx, DT) {
    AddLoader(false);
    LastPage = -1;
    CurC = CurPage = 0;
    if (idx == -1) {
        CurPath = [];
        if (default_cat_id > 0) { //different 0 & -1
            AjaxLoadCateg(default_cat_id, Customer_ID);
            $('#activate_cat_id').val(default_cat_id).select2();
            return;
        } else {
            CurCats = Categories;
            $("#CategLoader").parent().remove();
        }
    } else {
        $("#CurAvailableItems").empty().css({ visibility: "visible" });
        CurCats = DT ? DT : [];
    }
    UpdatePaginators();
    GotoPage(0);
    UpdateCrumbs();
}

function UpdatePaginators() {
    //$("#PageIndicatorHandler").css({display: "block", opacity: 0}).animate({opacity: 1}, 40).empty();
    $("#PageIndicatorHandler").hide().empty();
    var current_items = CurCats.length;
    if (current_items > ShowPerPage) {
        var X = Math.floor(current_items / ShowPerPage);
        if ((X * ShowPerPage) < current_items)
            X++;
        $.each(new Array(X), function(v1) {
            $("#PageIndicatorHandler").append($('<li  data-slide="' + v1 + '" class="' + (v1 == CurPage ? "active" : "") + '"></li>'));
        });
        //        //we stop above and display just a limited number of page since when it is too large number it display above the products
        //        var start = Math.max(0, CurPage - 5);
        //        var end = Math.min(X, start + 10);
        //        for (var v1 = start; v1 < end; v1++)
        //            $("#PageIndicatorHandler").append($('<li style="text-indent:0;" data-slide="' + v1 + '" class="' + (v1 == CurPage ? "active" : "") + '">' + v1 + '</li>'));
        $("#PageIndicatorHandler").show();
    }
    //    else
    //        $("#PageIndicatorHandler").hide();
}

function UpdateCrumbs() {
    var it = $("#CurCategory_Crumbs").empty().append($('<li><a href="javascript:void()" data-id="-1"><i class="fa fa-home"></i></a></li>'));
    for (var x = 0; x < CurPath.length; x++) {
        if (x == CurPath.length - 1) {
            it.append($('<li>' + CurPath[x][1] + '</li>'))
        } else {
            var C = $('<li><a href="javascript:void()" CurPath="' + x + '" data-id="' + CurPath[x][0] + '">' + CurPath[x][1] + '</a></li>');
            it.append(C)
        }
    }
}

function GotoPage(idx) {
    if ($("#PageIndicatorHandler").children().length == 0) {
        CurPage = 0;
        if (LastPage == 0)
            return;
    } else {
        if (LastPage == idx || $("#PageIndicatorHandler").children().length <= idx || idx < 0) {
            CurPage = LastPage;
            return;
        }
    }
    CurPage = idx;
    $(">li", "#PageIndicatorHandler").removeClass("active").eq(idx).addClass("active");
    var Handler = $("#CurAvailableItems");
    CurC = 0;
    if (Handler.children().length > 0) {
        var NewDiv = Handler.clone();
        var OldDiv = Handler.attr("id", "Old");
        var OldWidth = OldDiv.parent().parent().width() - 24
        var OldHeight = OldDiv.parent().height()
        OldDiv.css({ position: "absolute" })
            .width(OldWidth)
            .animate({ "x": 0 }, 20, function() {
                $(this).parent().css("height", "auto")
                $(this).remove()
            }).parent().height(OldHeight)
        $(OldDiv).find(".Shown").attr("class", LastPage > idx ? "FromRight" : "FromLeft")
        NewDiv.empty().appendTo(OldDiv.parent())
        Handler = NewDiv;
    }
    var color = '',
        current_color = '';
    var ToN = (idx * ShowPerPage) + ShowPerPage;
    for (var x = idx * ShowPerPage; x < ToN; x++) {
        if (x < CurCats.length) {
            var HT = CategTemp;
            color = Colors[CurC].split("#")[0];
            current_color = Colors[CurC].split("#")[1];
            if (CurCats[x][3] == "Product") {
                var CurPrice = parseFloat(ConvertCurrency(CurCats[x][4], CurCats[x][7], PrimaryCurrency));
                var TTCPrice = parseFloat(ConvertCurrency(CurCats[x][20], CurCats[x][7], PrimaryCurrency));
                HT = ProductTemp.replace(/\$PRICETEXT\$/g, AddCommas(public_round_number(TTCPrice)));
                if (!show_all_prices || !current_show_price) {
                    HT = HT.replace(/\$PRICECLASS\$/g, 'hidden');
                }

                HT = HT.replace(/\$PRICE\$/g, CurPrice);
                HT = HT.replace(/\$UOM\$/g, CurCats[x][11]);
                HT = HT.replace(/\$VAT\$/g, CurCats[x][10]);
                HT = HT.replace(/\$VATPERCENT\$/g, CurCats[x][13]);
                HT = HT.replace(/\$TTCPRICE\$/g, TTCPrice);
                HT = HT.replace(/\$EXPIRYACTIVE\$/g, CurCats[x][21]);
                HT = HT.replace(/\$ISLOT\$/g, CurCats[x][26]);
                HT = HT.replace(/\$ISSERVICE\$/g, CurCats[x][29]);
                HT = HT.replace(/\$ISSERIAL\$/g, CurCats[x][27]);
                HT = HT.replace(/\$UOMCONV\$/g, CurCats[x][28]);
                HT = HT.replace(/\$RESERVEACTIVE\$/g, CurCats[x][24]);
                HT = HT.replace(/\$CHANGEPRICE\$/g, CurCats[x][22]);
                HT = HT.replace(/\$IUNITS\$/g, CurCats[x][12]);
                HT = HT.replace(/\$PRODUCTREF\$/g, CurCats[x][8]);
                //first discount is for attr needed in calculations and second is for view
                HT = HT.replace("$DISCOUNT$", CurCats[x][5]);
                HT = HT.replace("$DISCOUNT$", round_number(CurCats[x][5]));
                //                replace("$TAXAMOUNT$", who.attr("tax-amount"))
                //                HT = HT.replace(/\$DISCOUNT\$/g, CurCats[x][5]);
                //                console.log(CurCats[x][5])
                HT = HT.replace(/\$CURRENCY\$/g, PrimaryCurrency[1]);
                /**
                 @reason: actual quantity for the product. The conditional statement will set
                 the data-disabled in product anchor true if the product quantity in stock
                 is less than or equal to zero, otherwise false.
                 */
                HT = HT.replace(/\$QTY\$/g, CurCats[x][9]);
                HT = HT.replace(/\$COST\$/g, CurCats[x][14]);
                HT = HT.replace(/\$LASTPRICE\$/g, CurCats[x][19]);
                HT = HT.replace(/\$BARCODE\$/g, CurCats[x][15]);
                HT = HT.replace(/\$MAXDISC\$/g, CurCats[x][16]);
                HT = HT.replace(/\$TAX\$/g, CurCats[x][17]);
                HT = HT.replace(/\$TAXAMOUNT\$/g, CurCats[x][25]);

                HT = HT.replace(/\$CATEGORYID\$/g, CurCats[x][23]);
                HT = HT.replace(/\$VAT2PERCENT\$/g, CurCats[x]['vat2_percent']);
                HT = HT.replace(/\$HASOPTIONAL\$/g, CurCats[x]['has_optional']);
                HT = HT.replace(/\$RECIPEQTY\$/g, CurCats[x]['recipe_qty']);
                //                HT = HT.replace(/\$RECIPEQTY\$/g, CurCats[x]['is_pos_disabled']);

                if (CurCats[x][22] == 1) {
                    $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                } else {
                    if (change_pos_price)
                        $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                    else
                        $(".key-price").addClass("not-allowed empty_key").removeAttr("data-role")

                }
                if (CurCats[x]['is_pos_disabled'] == 1) {
                    HT = HT.replace(/\$STATUS\$/g, true);
                    //                    HT = HT.replace(/\$STATUSSTYLE\$/g, "background: #F55753");
                    //                    HT = HT.replace(/\$STATUSBORDERCOLOR\$/g, "#F55753");
                } else {

                    HT = HT.replace(/\$STATUS\$/g, false);
                }
                current_color = CurCats[x][18] ? CurCats[x][18] : "#48B0F7";
                color = '';
                /*end edit*/

                HT = HT.replace("$THUMB$", CurCats[x][6] ? '<img style="position:absolute;left:0;top:0" src="' + site_link + 'uploads/products_photos/$ID$.jpg" />' : '');
                //                }
            }
            if (CurCats[x][3] == "Skip") {
                current_color = "#fff";
                color = '';
                HT = HT.replace(/\$STATUS\$/g, false);
            }
            //
            if (CurCats[x][3] != "Product" && CurCats[x][3] != "Skip") {
                HT = HT.replace("$THUMB$", CurCats[x][5] ? '<img style="position:absolute;left:0;top:0" src="' + site_link + 'uploads/category_photos/$ID$.jpg" />' : '');
                if (CurCats[x][4]) {
                    current_color = CurCats[x][4];
                    color = '';
                }
            }
            HT = HT.replace(/\$STATUSSTYLE\$/g, "background:" + current_color);
            HT = HT.replace(/\$STATUSBORDERCOLOR\$/g, current_color);
            HT = $(HT.replace(/\$NAME\$/g, CurCats[x][1])
                .replace(/\$ID\$/g, CurCats[x][0])
                .replace("$CHILDCLASS$", CurCats[x][2] ? "HasChild" : "")
                .replace("$COLOR$", color)
                .replace("$FROM$", LastPage < idx ? "FromRight" : "FromLeft"));

            Handler.append(HT);
            (function(v, v2) {
                setTimeout(function() {
                    $(">div", v).addClass("Shown");
                }, 10);
            })(HT, x);
            CurC = CurC < 4 ? ++CurC : 0;
        }
    }

    //    $("#RightBoxContents").css("height", $("#OrderTable").parents(".LeftTableContainer").height() + 199)
    //    $("#TotalTable").parent().height($("#CustomerInfo").height() - 25);
    LastPage = idx;
}

function AjaxLoadCateg(ID, Customer_ID) {
    AddLoader(true);
    $("#Tab_1").addClass("Busy")
    $("#PageIndicatorHandler").hide();
    setTimeout(function() {
        $("#CurAvailableItems").css({ visibility: "hidden" });
        var uniq_id = ID + '_' + $("#Customer_Class_ID").val();
        pos_db.get_cat(uniq_id, function(result) {
            //we only get saved/cached data if: cash customer or (if no last cost and no last price)
            //else we get always new live data since last cost, last price will be different for each customer
            if (is_production == 1 && result !== false && result.data !== undefined && (Customer_ID === undefined || Customer_ID <= 0 || (view_last_price_permission != 1 && (view_cost_in_pos != 1 || view_cost_permission != 1)))) {
                eval(result.data);
                $("#CategLoader").parent().remove();
                $("#Tab_1").removeClass("Busy");
                $("#product_search").blur().val("");
            } else {
                $.ajax({
                    url: "POSAjax/getCategory?id=" + ID + "&Customerid=" + Customer_ID + "&class_id=" + $("#Customer_Class_ID").val() + "&type=1",
                    dataType: "jsonp",
                    complete: function(e) {
                        //we only save data for cash customer else we don't get it since last cost, last price will be different
                        //below we add condition about response first 9 char. since for unknown reason sometimes it is undefined
                        if ((Customer_ID === undefined || Customer_ID <= 0) && e.responseText !== undefined && e.responseText.substring(0, 9) == 'GotoCateg')
                            pos_db.add_cat(uniq_id, e.responseText); //save it for next time use
                        $("#CategLoader").parent().remove();
                        $("#Tab_1").removeClass("Busy");
                        $("#product_search").blur().val("");
                    }
                });
            }
        });

    }, 31);
}

function AjaxLoadProd(ID, Customer_ID, uom) {
    AddLoader(true);
    $("#Tab_1").addClass("Busy")
    $("#PageIndicatorHandler").hide();
    setTimeout(function() {
        $("#CurAvailableItems").css({ visibility: "hidden" });
        $.ajax({
            url: "POSAjax/getProduct?id=" + ID + "&class_id=" + $("#Customer_Class_ID").val() + "&customer_id=" + Customer_ID + "&uom_id=" + uom,
            dataType: "jsonp",
            complete: function(e) {
                $("#CategLoader").parent().remove();
                $("#Tab_1").removeClass("Busy")
                $("#product_search").blur().val("");
                $("#CurAvailableItemsContainer > ul.Categories > li a[data-id=" + ID + "]").trigger("click")

            }
        });
    }, 31);
}













/**************** Table ****************/
function AddItemToTable(who) {
    //alert()
    //    console.log(who)
    if (!pos_return_postponed_change_item && is_return_postponed == 1) {
        return;
    }
    if (is_prod_desc_acive) {
        if ($(SelectedTR).attr('is_linked_note') == 1 && $(SelectedTR).attr('product-description') && $(SelectedTR).find('.prod-desc-icon').hasClass('red-star')) {
            var description = $(SelectedTR).attr('product-description');
            $(SelectedTR).attr('product-description', description + ' ' + who.attr('data-name'))
            $(SelectedTR).find('.prod-desc-icon').removeClass('red-star').addClass('note-filled')
            return;
        }
    }
    document.body.style.overflowX = "hidden"
    var T = $("#OrderTable > tbody:last");
    var SameID = T.find("tr[data-id='" + who.attr("data-id") + "']");
    var Item = who.closest("li");
    var Cloned = $("<ul class='Categories Adding' style='width:" + ($("#CurAvailableItems").width() + 54) + "px'></ul>").append(Item.clone(false, false).addClass("Transitioned"))
    var COORDS = {
        left: (T.offset().left - 27) + (T.parent().width() - Item.width()) / 2,
        top: (T.parent().parent().offset().top - 22) + (T.parent().parent().height() - Item.height()) / 2
    };
    var IsVisibleToEye = ($("#OrderTable").parent().prop('scrollHeight') - Item.position().top - $("#OrderTable").parent().scrollTop()) < T.parent().parent().height();
    //    if (SameID.length > 0 && IsVisibleToEye) {
    //        var Input = SameID.find(".InputSpinner > input")
    //        COORDS = {
    //            left: Input.offset().left - (Item.width() / 2),
    //            top: Input.offset().top - (Item.height() / 2) + 10
    //        };
    //    }
    Cloned.css({
        "position": "absolute",
        left: ($("#CurCategory_Crumbs").parent().offset().left - 18) + Item.position().left - 22,
        top: Item.offset().top,
        "z-index": 999
    }).animate(COORDS, 20, function() {
        //$("li",this).addClass("Hidden")
        document.body.style.overflowX = "visible"
    }).animate({ "x": 0 }, 30, function() {
        $(this).remove();
    });
    setTimeout(function() {
        $("li", Cloned).addClass("Hidden")
    }, 16);
    if ($("body").width() > 780)
        $("body").append(Cloned)
        //    if (SameID.length > 0) {
        //        var Input = SameID.find(".InputSpinner > span")
        ////        alert()
        //        /**
        //         @edited by: Smart
        //         */
        //        if (Input.text() < who.data("product-qty")) {
        //            Input.text(parseFloat(Input.text()) + 1)
        ////            Input.text(parseFloat(Input.text()) + 1)
        //        } else
        //            who.attr("data-disabled", true)
        //        /*end edit*/
        //        UpdateTable(T);
        //        return
        //    }
    var ref = Math.round(Date.now() + Math.random());
    var Row = $("<tr data-entry='0' price-change='0' data-conv='" + who.attr("data-conv") + "' data-product-ref='" + who.attr("data-product-ref") + "' data-ref='" + ref + "' data-cid='" + 0 + "'data-id='" + who.attr("data-id") + "' data-discount='" + who.attr("data-discount") + "' data-price-single='" + who.attr("data-price") + "' data-price-single-orginal='" + who.attr("data-price") + "' data-price-single-orginal-ttc='" + who.attr("ttc-price") + "' data-qty='" + who.attr("data-product-qty") + "' data-cost='" + who.attr("data-cost") + "' data-last-price='" + who.attr("data-last-price") + "' data-vat='" + who.attr("data-vat") + "' vat-percent='" + who.attr("vat-percent") + "' vat2-percent='" + who.attr("vat2-percent") + "' data-is-option='" + who.attr("data-is-option") + "' recipe-qty='" + who.attr("recipe-qty") + "' ttc-price='" + who.attr("ttc-price") + "' data-max-discount='" + who.attr("data-max-discount") + "' expiry-active = '" + who.attr("expiry-active") + "' data-lot = '" + who.attr("data-lot") + "' data-serial = '" + who.attr("data-serial") + "' reserve-active = '" + who.attr("reserve-active") + "'change-price='" + who.attr('change-price') + "' data-expiry-date = '' data-tax='" + who.attr("data-tax") + "' tax-amount='" + who.attr("tax-amount") + "' data-category-id='" + who.attr("data-category-id") + "' data-service='" + who.attr("data-service") + "' ></tr>"),
        T2 = RowTemp;

    T2 = T2.replace("$ID$", "1");
    T2 = T2.replace("$NAME$", who.attr("data-name"));
    T2 = T2.replace("$BARCODE$", who.attr("data-barcode"));
    T2 = T2.replace("$QTYHINT$", '(' + AddCommas(public_round_number(parseFloat(who.attr("data-product-qty")))) + ')');
    T2 = T2.replace("$COSTHINT$", '(' + AddCommas(public_round_number(parseFloat(who.attr("data-cost")))) + ')');
    T2 = T2.replace("$PRICEHINT$", '(' + AddCommas(public_round_number(parseFloat(who.attr("data-last-price")))) + ')');
    /**
     @edited by: Smart
     @added: T2 = T2.replace("$QTY$",who.attr("data-product-qty"))
     @reason: data-product-qty will hold the quantity of the product for validation
     */
    T2 = T2.replace("$QTY$", who.attr("data-product-qty"));
    /*end edit*/
    T2 = T2.replace("$VAT$", who.attr("data-vat"));
    T2 = T2.replace("$TAX$", who.attr("data-tax"));
    T2 = T2.replace("$TAXAMOUNT$", who.attr("tax-amount"));
    //first discount is for attr needed in calculations and second is for view
    T2 = T2.replace("$DISCOUNT$", who.attr("data-discount"));
    T2 = T2.replace("$DISCOUNT$", round_number(who.attr("data-discount")));
    //    T2 = T2.replace(/\$DISCOUNT\$/g, who.attr("data-discount"));
    //    console.log(who.attr("tax-amount")+'===')

    T2 = T2.replace("$VATPERCENT$", who.attr("vat-percent"));
    T2 = T2.replace("$VAT2PERCENT$", who.attr("vat2-percent"));
    T2 = T2.replace("$HASOPTIONAL$", who.attr("data-is-option"));
    T2 = T2.replace("$RECIPEQTY$", who.attr("recipe-qty"));
    T2 = T2.replace("$TTCPRICE$", who.attr("ttc-price"));
    T2 = T2.replace("$EXPIRYACTIVE$", who.attr("expiry-active"));
    T2 = T2.replace("$ISLOT$", who.attr("data-lot"));
    T2 = T2.replace("$ISSERVICE$", who.attr("data-service"));
    T2 = T2.replace("$ISSERIAL$", who.attr("data-serial"));
    T2 = T2.replace("$UOMCONV$", who.attr("data-conv"));
    T2 = T2.replace("$RESERVEACTIVE$", who.attr("reserve-active"));
    T2 = T2.replace("$CHANGEPRICE$", who.attr("change-price"));
    T2 = T2.replace("$MAXDISC$", who.attr("data-max-discount"));
    T2 = T2.replace("$UNITPRICE$", who.attr("data-price"));
    T2 = T2.replace("$PRICE$", who.attr("data-price"));
    T2 = T2.replace(/\$CATEGORYID\$/g, who.attr("data-category-id"));
    //    T2 = T2.replace("$CATEGORYID$", who.attr("data-category-id"));
    T2 = T2.replace("$PRICE$", "0");
    T2 = T2.replace(/\$CURRENCY\$/g, PrimaryCurrency[1]);
    var hold = 0;
    if ($(".selected_hold.hold").length > 0) {
        hold = $(".selected_hold").attr("data-role")
    }
    Row.attr("data-hold", hold)
    T2 = T2.replace("$holdclass$", "hold" + hold);
    T2 = T2.replace("$holdlevel$", hold);
    T.prepend(Row);


    //    return false;
    if ((who.attr("expiry-active") == 1 && is_active_expiry_date == 1) || (!pos_fields_to_hide.includes('0') && who.attr("data-lot") == 1) || (!pos_fields_to_hide.includes('1') && who.attr("data-serial") == 1)) {
        T2 = T2.replace("$EXPIRYICON$", '<i class="fa fa-calendar expiry-icon"></i>');
        if ($('#titleSpan').attr('data-type') == 1) {
            build_select2($('#expiry_date'), function() {
                var depot_id = $("#delivery_depot_id").val() != '' ? $("#delivery_depot_id").val() : user_depot_id;
                return 'xhr/get_product_expiry?product_id=' + who.attr("data-id") + '&depot=' + depot_id;
            });
        }
        if (who.attr("expiry-active") == 1 && is_active_expiry_date == 1) {
            $(".exp-modal-div").removeClass("hidden")
            $("#expiry_date").attr("required")
        } else {
            $("#expiry_date").removeAttr("required")
            $(".exp-modal-div").addClass("hidden")
        }
        if (!pos_fields_to_hide.includes('0') && who.attr("data-lot") == 1) {
            if ($('#titleSpan').attr('data-type') == 1) {
                build_select2($('#lot_nb'), function() {
                    var depot_id = $("#delivery_depot_id").val() != '' ? $("#delivery_depot_id").val() : user_depot_id;
                    return 'xhr/get_product_lot?product_id=' + who.attr("data-id") + '&depot=' + depot_id;
                });
            }
            $(".lot-modal-div").removeClass("hidden")

        } else {
            $(".lot-modal-div").addClass("hidden")
        }
        if (!pos_fields_to_hide.includes('1') && who.attr("data-serial") == 1) {
            if ($('#titleSpan').attr('data-type') == 1) {
                build_select2($('#serial_nb'), function() {
                    var depot_id = $("#delivery_depot_id").val() != '' ? $("#delivery_depot_id").val() : user_depot_id;
                    return 'xhr/get_product_serial?product_id=' + who.attr("data-id") + '&depot=' + depot_id;
                });
            }
            $(".serial-modal-div").removeClass("hidden")
        } else {
            $(".serial-modal-div").addClass("hidden")
        }
        $('#expiry-date-modal').modal('show')
    } else {
        T2 = T2.replace("$EXPIRYICON$", '');
    }
    if (who.attr("reserve-active") == 1 && is_active_reserve_date == 1) {
        T2 = T2.replace("$RESERVEICON$", '<i class="fa fa-calendar reserve-icon"></i>');

        $('#reservation-duration-modal').modal('show')
    } else {
        T2 = T2.replace("$RESERVEICON$", '');
    }

    if (who.attr("change-price") == 1) {
        $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
    } else {
        if (change_pos_price)
            $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
        else
            $(".key-price").addClass("not-allowed empty_key").removeAttr("data-role")

    }
    if ($('input[name=entry_id]').length > 0) {
        if (!$("#OrderTable .entry_checkbox ").hasClass('hidden')) {
            T2 = T2.replace("$CHECKBOX$", '');
        } else {
            T2 = T2.replace("$CHECKBOX$", 'hidden');
        }
    } else {
        T2 = T2.replace("$CHECKBOX$", 'hidden');
    }
    //    if (who.attr("data-is-option") == 1) {
    //        build_optional_link(ref)
    //        $(".option-tr", T2).removeClass("hidden")
    //    }

    Row.append(T2);
    if (who.attr("data-is-option") == 1) {
        build_optional_link(ref)
        $(".option-tr", $(Row)).removeClass("hidden")
    }
    //    return false;
    Row.find("select[name=uom] > option[value=" + who.attr("data-uom") + "]").attr("selected", true);
    var units_arr = who.attr("item-units").split("/");
    $("select[name=uom] > option", Row).each(function() {
        if ($.inArray($(this).attr("value"), units_arr) === -1) {
            $(this).remove();
        }
    });
    if (parseFloat($(SelectedTR).find("span.qty_span").html()) < 0) {
        $(SelectedTR).find("td").removeClass("tr-gray tr-white").addClass("tr-return")
    } else {
        $(SelectedTR).find("td").removeClass("tr-gray tr-return").addClass("tr-white")

    }
    if ($(SelectedTR).attr("is-promotion") == 1) {
        $(SelectedTR).find("td").removeClass("tr-gray tr-white").addClass("tr-prom")
    } else {
        $(SelectedTR).find("td").removeClass("tr-gray tr-prom").addClass("tr-white")
    }
    if (show_all_prices && current_show_price) {
        $(".price_element").removeClass("hidden")
    } else {
        $(".price_element").addClass("hidden")
    }
    //    $("#OrderTable").find("td").removeClass("tr-gray tr-return").addClass("tr-white")//.css("background-color", "white");
    $(Row).find("td").removeClass("tr-white tr-return").addClass("tr-gray") //css("background-color", "#e2e2e2");
    window.SelectedTR = $(Row);
    $(".key1[data-flag=2]").trigger("click"); //addClass("choosen");
    checkDisableCashGenerateBtn()
}

function UpdateTable(who) {
    //prevent on each character typing to update total
    if (update_total_timeout) {
        clearTimeout(update_total_timeout);
        update_total_timeout = false;
    }
    update_total_timeout = setTimeout(function() {
        //here we remove the timeout [which is the current] so we fill it false to work well "check_before_post_invoice" ft.
        clearTimeout(update_total_timeout);
        update_total_timeout = false;
        InternalUpdateTable();
    }, 200);
}

function InternalUpdateTable() {
    who = $("#OrderTable > tbody:last");
    var totalVAT = 0,
        vat1_total = 0,
        vat2_total = 0;
    var SubTotalVal = 0,
        card_tax = 0;
    primary_total = 0;
    var class_tax = parseFloat($("#CurCustomerInfo").attr("data-tax") || 0)

    who.find("tr[data-price-single]").each(function() {
        var tr_vat = 0,
            vat1_amount = 0,
            vat2_amount = 0;
        var P_single = parseFloat($(this).find('.price-input-span').val()) || parseFloat($(this).attr("data-price-single")),
            ttc_price = parseFloat($(this).find('.price-input-span').val()) || parseFloat($(this).attr("ttc-price")),
            is_expiry = $(this).attr('expiry-active'),
            N = parseFloat($(this).find(".InputSpinner > span.qty_span").text()) || parseFloat($(this).find('.qty-input-span').val()) || 0,
            con = parseFloat($(this).attr('data-conv')),
            P = (P_single * N),
            D = parseFloat($(this).find('.disc-input-span').val()) || parseFloat($(this).attr("data-discount")),
            T = P * (1 - D / 100),
            T_with_inv_disc = T * (1 - parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount")) / 100),
            basic_price = (P_single * N),
            basic_total = basic_price * (1 - D / 100);
        $(this).find('.UPrice span.uprice-span').html(AddCommas(public_round_number(is_ttc == 1 ? ttc_price : P_single)))
        $(this).find('span.currency-sym').html(PrimaryCurrency[1])
        qty = $(this).attr("data-qty");
        var mytotal = N * (is_ttc == 1 ? ttc_price : P_single) * (1 - D / 100) * parseFloat((1 - parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount")) / 100));
        //        console.log(mytotal+'==='+round_number(mytotal))
        SubTotalVal += T;
        primary_total += (parseFloat(ttc_price * N * (1 - D / 100)));
        //        if(N<0){
        //            $(this).find("td").removeClass("tr-gray tr-white").addClass("tr-return")
        //        }
        //        else{
        //            $(this).find("td").removeClass("tr-return tr-gray").addClass("tr-white")
        //        }
        //        SelectedTR.find("td").removeClass("tr-return tr-white").addClass("tr-gray")

        if ($(this).attr("data-vat") == 1) {
            tr_vat = parseFloat(T_with_inv_disc) * parseFloat($(this).attr("vat-percent") / 100);
            //            vat1_amount = tr_vat;
            totalVAT += tr_vat;
            vat1_total += tr_vat;
            //            console.log(tr_vat + '===' + totalVAT)

            if (activate_second_vat == 1) {
                vat2_amount = ((parseFloat(T_with_inv_disc) + tr_vat) * ((parseFloat($(this).attr("vat2-percent")) || 0) / 100));
                totalVAT += vat2_amount;
                vat2_total += vat2_amount;
            }
            //            console.log(tr_vat+'==='+vat2_amount)

            $(this).attr("vat-amount", tr_vat);
            $(this).attr("vat2-amount", vat2_amount);


        }
        //        console.log(totalVAT + '===' + tr_vat + '===' + vat2_amount)
        $(this).find("span.price").html(AddCommas(public_round_number(mytotal))).attr("CurPrice", (round_number(mytotal, 6)))
        if ($(this).attr("data-tax") == 1) {
            // console.log($(this).attr("tax-amount"))
            card_tax += (N * parseFloat($(this).attr("tax-amount") || 0));
            //console.log(card_tax)


        }
    })
    $(".tax_amount").html(public_round_number(card_tax) + " " + PrimaryCurrency[1])
    $(".tax_amount").attr("total-card-tax", card_tax)
        //console.log(card_tax + '===')
    $(".TVAVal").html(public_round_number(totalVAT)).attr("vat1-total", vat1_total).attr("vat2-total", vat2_total)
    var shipping_amount = parseFloat($("#shipping_id").val() || 0);
    $(".shipping_val").html(AddCommas(shipping_amount))
    var NetTotalPrice = SubTotalVal;
    $("#TotalTable .SubtotalVal").attr("data-subtotal", SubTotalVal).html(AddCommas(public_round_number(SubTotalVal)) + " " + PrimaryCurrency[1])
        // Discount
        //    var Dis = parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount"));
    var Dis = parseFloat($("#DiscountInput").val()) || 0;
    //    console.log(Dis+'===')
    SubTotalVal = SubTotalVal * (1 - Dis / 100);
    //    $("#TotalTable  .DiscountVal >.DiscountValue").val((NetTotalPrice - SubTotalVal).toXFixed(3))
    $("#TotalTable  .DiscountVal >.DiscountValue").val((public_round_number(NetTotalPrice - SubTotalVal)))
        //    console.log(primary_total+'=='+Dis)
    $("#TotalTable  .TTCDiscountVal >.TTCDiscountValue ").val(public_round_number(primary_total * Dis / 100))
        // T.V.A
        //var TVA = parseFloat($("#TotalTable .TVAVal").text());
    var TVA = 0;

    //    NetTotalPrice = SubTotalVal + parseFloat($("#shipping_id").val())
    NetTotalPrice = SubTotalVal + 0

    SubTotalVal = SubTotalVal * (1 + TVA / 100);
    //    SubTotalVal = SubTotalVal + parseFloat($("#shipping_id").val());
    //    SubTotalVal = SubTotalVal + 0;
    //  if ($("#credit_input_label").is(":checked") && pos_service_type==2) {
    var service_value = (SubTotalVal * parseFloat(($('#TotalTable .service').html() || 0))) / 100
    SubTotalVal = SubTotalVal + service_value
        //    NetTotalPrice = SubTotalVal + parseFloat($("#shipping_id").val())
    NetTotalPrice = SubTotalVal + 0
    $('#TotalTable .service').attr('data-value', service_value)
        //  }
        //


    console.log(SubTotalVal)

    // Total Items
    var TotalItems = 0;
    who.find("td.Number").each(function(e) {
        $(this).html(e + 1)
    })
    who.find(".InputSpinner > span").each(function() {
        TotalItems += parseFloat($(this).text())
    })

    var fTotal = round_number(SubTotalVal + totalVAT + card_tax);
    //        console.log(SubTotalVal+'=='+totalVAT)

    if (PrimaryCurrency[3] > 0) {
        var roundTo = PrimaryCurrency[3],
            diff = fTotal % roundTo;
        var finalTotal = Math.floor(fTotal / roundTo);

        if (diff > 0 && ((diff >= (roundTo / 2) && default_round_type == 0) || default_round_type == 1)) {
            finalTotal++;
        }
        finalTotal = round_number(finalTotal * roundTo);
    } else {
        finalTotal = fTotal;
    }
    // console.log(finalTotal)
    $("#TotalTable .TotalVal").attr("data-total", (finalTotal)).html(AddCommas(public_round_number(finalTotal + shipping_amount)) + " " + PrimaryCurrency[1]);
    $(".TotalVal1").html(AddCommas(public_round_number(finalTotal)) + " " + PrimaryCurrency[1]);
    // Total Price Second Currency
    $("#TotalTable .SecondCurrencyVal").html(AddCommas(public_round_number(ConvertCurrency((finalTotal + shipping_amount), PrimaryCurrency, SecondCurrency))) + " " + SecondCurrency[1]);
    $("#TotalTable .TotalItem").html(TotalLang)

    //$("#InvTypeMpdal input[name=main_total_value],#invoice_unpaid_amount").val($("#TotalTable tbody tr td.TotalVal").attr('data-total'));
    var tmp_unpaid_amount = (parseFloat($("#TotalTable tbody tr td.TotalVal").attr('data-total')) || 0) - (parseFloat($("#cash_amount").val()) || 0) - (parseFloat($("#other_amount").val()) || 0);
    $("#invoice_unpaid_amount").val(public_round_number(tmp_unpaid_amount));
    $("#InvTypeMpdal input[name=main_total_value]").val($("#TotalTable tbody tr td.TotalVal").attr('data-total'));

    who.find('.InputSpinner .btn:not(.EventAdded)').on('click', function() {
        var Input = $("input", $(this).parent().parent()),
            V = parseInt(Input.val())
            /**
             @edited by: Smart
             @added: sub condition to the statement: (V < qty ? V + 1 : V)
             @reason: checks if the entered qty is equal to the stock qty.
             blocks any edition if qty exceeds qty in stock
             */
        Input.val($(this).hasClass("more") ? (V < qty ? V + 1 : V) : V == 1 ? 1 : V - 1)
            /*end edit*/
        UpdateTable(who);
    }).addClass("EventAdded");
    who.find('.RowRemover:not(.EventAdded)').on('click', function() {
            $(this).closest("tr").remove();
            UpdateTable(who);
        }).addClass("EventAdded")
        //    UpdateButtons();s
        //    EnablePayButton();
}

function InputMustBeAtleastN(who, N) {
    if (parseFloat(who.value) < N || !parseFloat(who.value))
        who.value = N;
}
/**
 @edited by: Smart
 @added: validateQuantity(who, qty) function 
 @reason: validateQuantity checkes whether or not the entered qty is larger than the quantity available in stock
 if the qty is larger the function will set the qty in the textbox to the max qty available in stock
 */
function validateQuantity(who, qty) {
    if (parseInt(who.value) > qty || !parseInt(who.value)) {
        var enteredQty = parseInt(who.value);
        who.value = qty;
        alert('Warning: the quantity you entered ' + enteredQty + ' cannot be greater than the quantity in stock: ' + qty + '\nThe quantity was set to ' + qty);
    }
}
/*end edit*/
function AddCommas(val) {
    val = parseFloat(val.toString()).toString();
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val.replace(/\.0$|\.00$/, "") || "0";
}

function ConvertCurrency(Val, FromC, ToC) {
    if (FromC[0] == ToC[0]) {
        return Val
    } else {
        for (var x = 0; x < CurrencyRate.length; x++) {

            if (CurrencyRate[x]['from_currency'] == FromC[0] && CurrencyRate[x]['to_currency'] == ToC[0]) {

                return Val * CurrencyRate[x]['ExchRate'];
            } else if (CurrencyRate[x]['to_currency'] == FromC[0] && CurrencyRate[x]['from_currency'] == ToC[0]) {
                return Val / CurrencyRate[x]['ExchRate'];
            }
        }
    }
}

function EditTotalDiscountEvent() {
    var DIS = parseFloat($("#DiscountInput").val()) || 0;
    var Max = 100; //parseFloat($("#EditDiscount").attr("data-max"));
    DIS = DIS < 0 ? 0 : DIS;
    if (Max > 0)
        DIS = DIS > Max ? Max : DIS;
    var DIS_STR = $("#DiscountInput").val(); //we use this not the parse float var
    DIS_STR = DIS + (DIS_STR.length > 0 && DIS_STR.charAt(DIS_STR.length - 1) == '.' ? '.' : ''); //we keep it, if typeing decimal like '22.' 
    if (DIS > parseFloat(user_max_discount)) {
        DIS = parseFloat(user_max_discount);
        DIS_STR = user_max_discount;
        console.log(DIS == 0 ? '' : DIS_STR)
    }
    //    var it = $("#EditDiscount").data("MyTarget")
    //    console.log(DIS)

    //    if (it) {
    $("#TotalTable tr[data-discount]").attr("data-discount", DIS)
    $("#DiscountInput").val(DIS == 0 ? '' : DIS_STR)
        //        alert(DIS)
        //        it.html(DIS.toXFixed(3) + " %");
    UpdateTable($("#OrderTable > tbody:last"));
    //        $("#EditDiscount [data-dismiss='modal']").click()
    //    }
}








function EditDiscountEvent(SelectedTR) {
    //    var DIS = parseFloat($("#DiscountInput").val());
    var DIS = parseFloat($(".discount", SelectedTR).attr('data-disc'));
    var Max = 100;
    var max_disc = parseFloat(SelectedTR.attr("data-max-discount"));

    if (max_disc > 0 || ignore_zero_item_disc != 1) {
        if (DIS > Math.min(parseFloat(user_max_discount), max_disc))
            DIS = Math.min(parseFloat(user_max_discount), max_disc);
    } else if (DIS > parseFloat(user_max_discount))
        DIS = parseFloat(user_max_discount)
    $(".discount", SelectedTR).attr('data-disc', DIS)
    DIS = DIS < 0 ? 0 : DIS;
    if (Max > 0)
        DIS = DIS > Max ? Max : DIS;
    SelectedTR.attr("data-discount", DIS)
    SelectedTR.find("span.discount").html(round_number(DIS) + " %");
    UpdateTable($("#OrderTable > tbody:last"));

}

//function PrepareDropDowns() {
//    $(".DropDownForForms").on('hide.bs.dropdown', function (e) {
//        return false
//    });
//    $(".DropDownForForms").on('show.bs.dropdown', function (e) {
//        var me = this;
//        $(".DropDownForForms").each(function () {
//            if (this !== me)
//                $(this).removeClass("open")
//        })
//        return true
//    });
//    $(document).on("click", function (e) {
//        if ($(e.target).parents(".DropDownForForms").length == 0) {
//            $(".DropDownForForms").removeClass("open")
//        }
//    })
//    $(".DropDownForForms li > a.LoadMore").on("click", function (e) {
//        var it = $(this).parents(".dropdown-menu");
//        it.animate({height: 250}, 200).find("li").show()
//        setTimeout(function () {
//            it.find(".formore,.LoadMore").remove()
//        }, 100);
//        e.preventDefault();
//    })
//    $(".DropDownForForms li > a:not(.LoadMore)").on("click", function (e) {
//        var it = $(this).parents(".DropDownForForms");
//        $("> button > span", it).html($(this).text())
//        $("button > input", it).val($(this).parent().attr("value")).css("opacity", "0")
//        if (it.hasClass("Closable"))
//            it.removeClass("open")
//        e.preventDefault();
//    })
//}
//PrepareDropDowns();


function ucWords(str) {
    return str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

function PrepareAutoComplete() {
    //    $("#product_search").focus(function () {
    //        $(this).parent().stop().animate({width: "60%"}, 300)
    //    }).blur(function () {
    //        $(this).parent().stop().animate({width: "50%"}, 300)
    //    })

    var lang = $('html').attr('lang'),
        my_top = lang == 'en' ? "right top" : "left top",
        at_top = lang == 'en' ? "right bottom" : "left bottom";
    $("#product_search").autocomplete({
        source: "POSAjax/ajaxPOS",
        minLength: 1,
        //this position we put it here since we change the width of suggestion
        position: {
            my: my_top,
            at: at_top,
            collision: "none"
        },
        select: function(event, ui) {
            var ID = ui.item.category ? ui.item.category : ui.item.id;
            var value = ui.item.value;

            if ($("#Tab_1").attr("DidSwipe") == "true")
                return;
            CurPath = [
                [ID, "Search Result(" + value + ")"]
            ];
            $("#CurAvailableItems").find(".Shown").attr("class", "FromRight");
            //AjaxLoadProd(ui.item.id, Customer_ID)
            if (ui.item.category == undefined)
                AjaxLoadCateg(ui.item.id, Customer_ID)
            else {
                AjaxLoadProd(ui.item.id, Customer_ID, ui.item.uom)
                    //                searchProductforPOS(ui.item.id);
            }
        }
    }).autocomplete("instance")._renderItem = function(ul, item) {
        var Thumb = "<i class='fa fa-folder'></i>";
        if (item.category) {
            if (item.thumb) {
                Thumb = "<img src='" + site_link + "uploads/products_photos/" + item.id + ".jpg' />";
            } else {
                Thumb = "<i class='fa fa-file-o'></i>";
            }
        }
        var Content = "<table cellspacing='0' cellpadding='0'><tr><td class='Column1'>" + Thumb + "</td><td>" + item.value + "</td></tr></table>"
        return $("<li>").html(Content).appendTo(ul)
    }

    $("#product_search").autocomplete("instance")._resizeMenu = function(ul, items) {
        var extra_width = 200;
        this.menu.element.outerWidth((parseFloat($("#product_search").parent().width()) + extra_width) + 'px');
    };
    //    $("#Customer_Class_ID").on("change", function () {
    //        refreshPOS()
    //    })
    $("#CustomerSearch").autocomplete({
        source: "POSAjax/getCustomerForAutoComplete",
        minLength: 1,
        position: { my: "left top", at: "left bottom", collision: "none" },
        select: function(event, ui) {


            customerSelectAutocomplete(ui)

        }
    }).autocomplete("instance")._renderItem = function(ul, item) {
        //        if (item.thumb) {
        //            var Thumb = "<img src='"+site_link+"uploads/products_photos/" + item.Customer_ID + ".jpg' />";
        //        } else {
        //            var Thumb = "<i class='fa fa-file-o'></i>";
        //        }
        //        var Content = "<table cellspacing='0' cellpadding='0'><tr><td class='Column1'>" + Thumb + "</td><td><strong>" + item.Customer_Name + " - " + item.Customer_Mobile + "</td></tr></table>"
        var Content = item.Customer_Name + " - " + item.Customer_Mobile;
        return $("<li class='" + (item.is_pos_customer == 1 ? 'primary-text' : '') + "'>").html(Content).appendTo(ul)
    }

    // This method is to resize the menu to same width as the input
    $("#CustomerSearch").autocomplete("instance")._resizeMenu = function(ul, items) {
        this.menu.element.outerWidth($("#CustomerSearch").parent().width());
    }

}

function check_posponed_fields() {
    if ($("#posponted_status").val() != 0 && ($("#postponed_customer_id").val() == '' || $("#postponed_date_time").val() == '')) {
        toastr.error(posponed_alert);
        return false;

    }
    return true;
}

function time_convert_12_to_24(tmp_time) {
    var is_pm = tmp_time.toLowerCase().match('pm') ? true : false;
    tmp_time = tmp_time.split(' ')[0].split(':');
    //in case AM we can't just return substr(0,5) since maybe hours are one character like 7 and not 07
    var hour = parseFloat(tmp_time[0]);
    //12 am => 00, 12 pm => 12
    if (hour == 12)
        hour = 0;
    if (is_pm)
        hour = 12 + hour;
    return (hour + ':' + tmp_time[1]);
}

function time_convert_24_to_12(tmp_time) {
    // Check correct time format and split into components
    tmp_time = tmp_time.split(':');
    var time_12 = '';
    time_12 = (parseFloat(tmp_time[0]) % 12 || 12);
    time_12 += ':' + tmp_time[1];
    time_12 += ' ' + (parseFloat(tmp_time[0]) < 12 ? 'AM' : 'PM');
    return time_12;
}

function PostInvoice(inv_type, table_id, new_table_id, status_id, type_id, loader, with_print) {
    $("#OrderTable > tbody tr span.item-name").removeClass("red-border")
    if (is_nb_person_required == 1 && ($('#Persons_Count').val() == '' || $('#Persons_Count').val() == 0) && table_id != 0) {
        toastr.error(nb_person_required);
        return;
    }
    //    if ($(".transfer_items_details:not(.hidden)").length > 0) {
    //        toastr.error(cont_split_trans);
    //        return;
    //    }

    //any validation must be above before disable the buttons
    $("#GInvBtn,#submit_payment,#CashInvBtn,#CashWithoutPrintInvBtn,#generate_credit_card,#print_table_invoice,#kitchen_delivery_takeaway,#table_kitchen_btn").attr("disabled", "disabled");
    //console.log('AAAAAA');
    var vat_permation = $("#vat_permation").val() == 1 ? 1 : 0;

    var discount_first = parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount"));
    var type = (inv_type == 1 || inv_type == 3) ? 3 : 2,
        ship_val = $("#shipping_id").val() || 0,
        order_time = time_convert_12_to_24($("#timepicker").val());
    var is_return_value = $("#titleSpan").attr("data-type") ? $("#titleSpan").attr("data-type") : 1;
    var invoice_net_total = parseFloat($("#TotalTable td.TotalVal").attr("data-total")),
        currency_round_val = round_number((invoice_net_total - (parseFloat($("#TotalTable td.SubtotalVal").attr("data-subtotal")) - parseFloat($(".DiscountValue").val() || 0) + parseFloat($("#TotalTable td.TVAVal").text() || 0)) - parseFloat($(".tax_amount").attr("total-card-tax") || 0)), 7);
    var reservation_content = $("#reservation_id").val() ? $("#reservation_id").select2('data').text.split(" - ") : '';
    var data = {
        "is_return": is_return_value,
        "Customer_ID": $("#CurCustomerInfo").attr('CurCustomerID') ? $("#CurCustomerInfo").attr('CurCustomerID') : ($('#customer_id').attr('data-id') ? $('#customer_id').attr('data-id') : 0),
        pos_customer_id: $("#CurCustomerInfo").attr('customer-pos-id') ? $("#CurCustomerInfo").attr("customer-pos-id") : 0,
        customer_is_pos: $("#CurCustomerInfo").attr("data-is-pos") ? $("#CurCustomerInfo").attr("data-is-pos") : 0,
        "Sales_ID": $('#Depot_PIC_ID').val() ? $('#Depot_PIC_ID').val() : 0,
        "Logged_ID": SessionLoggedID,
        open_cash_table: (is_open_cash_table == 1 && table_id != 0 && type_id == 'generate_invoice' && is_smart_diner == 1 && inv_type == 2) ? 1 : 0,
        "table_id": table_id,
        "status_id": status_id,
        "new_table_id": new_table_id,
        "type_id": type_id ? type_id : '',
        "is_order": $("#titleSpan").attr('data-type') == 4 ? 1 : 0,
        "is_transfer": $("#titleSpan").attr('data-type') == 5 ? 1 : 0,
        "invoice_type": inv_type,
        "pending_status": pending_status,
        "Invoice_ID_Auto": $("#invoice_auto_id").val(),
        "ex_id": $("#invoice_auto_id").val(),
        "cust_address": $("#CurCustomerInfo span.Address").html(),
        "Persons_Count": $("#Persons_Count").val() ? $("#Persons_Count").val() : 0,
        //        "Account_Code": $("#CurCustomerInfo").attr('data-account') ? $("#CurCustomerInfo").attr('data-account') : $("#customer_id").attr('data-account'),
        "Invoice_Sub_Total": parseFloat($("#TotalTable td.SubtotalVal").attr("data-subtotal")) || 0,
        currency_round: currency_round_val || 0,
        "Invoice_Net_Total": invoice_net_total || 0,
        "Invoice_Shipping": ship_val || 0,
        service_value: $('#TotalTable .service').attr('data-value') || 0,
        "Invoice_VAT": parseFloat($("#TotalTable td.TVAVal").text()),
        vat1_total: $("#TotalTable td.TVAVal").attr('vat1-total') || 0,
        vat2_total: $("#TotalTable td.TVAVal").attr('vat2-total') || 0,
        "Invoice_Currency": PrimaryCurrency[0],
        Invoice_Description: $("#text_note").val(),
        order_delivery_date: $("#order_delivery_date").val(),
        Invoice_Discount: discount_first ? discount_first : 0,
        Discount_Amount: $(".DiscountValue").val() || 0,
        Invoice_Status: type,
        is_edited_invoice: is_edited_invoice,
        is_return_postponed: is_return_postponed,
        Paid_Amount: ((parseFloat($("#cash_amount").val()) || 0) + (parseFloat($("#other_amount").val()) || 0)), //(invoice_net_total - (isNaN(parseFloat($("#invoice_unpaid_amount").val())) ? invoice_net_total : parseFloat($("#invoice_unpaid_amount").val()))),
        Delivery_Time: order_time,
        Delivery_Date: $("#delivery_date").val(),
        is_delivery: is_delivery == 1 ? 1 : 0,
        is_takeaway: is_delivery == 2 ? 1 : 0,
        Class_ID: $("#Customer_Class_ID").val(),
        tax_amount: parseFloat($(".tax_amount").attr("total-card-tax")) || 0,
        cash_cat_amount: $("#cash_cat_amount").val() || 0,
        postponed_date_time: $("#postponed_date_time").val(),
        posponted_status: $("#posponted_status").val() ? $("#posponted_status").val() : 0,
        postponed_note: $("#postponed_note").val(),
        "products": [],
        void_items: JSON.parse(JSON.stringify(void_item_reason_array)),
        with_print: with_print,
        main_order_note: $('#order_note_description').val(),
        kitchen_takeaway_delivery: kitchen_takeaway_delivery,
        delivery_depot: $("#delivery_depot_id").val(),
        product_ids: [],
        is_actual: is_actual,
        Request_To: $("#transfer_depot_from").val(),
        Request_From: $("#transfer_depot_to").val(),
        reservation_id: $("#reservation_id").val(),
        Invoice_Note: $("#reservation_id").val() ? ($("#reservation_id").select2('data').id + '\n' + reservation_content[2]) : '',
        customer_name_alias: $("#reservation_id").val() ? reservation_content[1] : '',
        driver_id: $("#driver_id").val(),
        shipping_company_id: $("#shipping_company_id").val(),
        is_invoice_total_on_shipping: $("#is_invoice_total_on_shipping").is(":checked") ? 1 : 0,
        shipping_on_self: $("#shipping_on_self").is(":checked") ? 1 : 0,
        ship_acc_id: $('.ship_comp_div').attr('ship-acc-id'),
        sales_acc_id: $('.ship_comp_div').attr('sales-acc-id'),
        ship_comp_main_acc_id: $('.ship_comp_div').attr('data-main-shipping-account-id')

    };
    var validate = true,
        validate_option = true;
    $(".option-tr").removeClass("pulsate")
    $("#OrderTable tbody tr").each(function(e) {
        var me = $(this);
        var tags = [],
            tag_amount = 0,
            item_qty = parseFloat(me.find(".InputSpinner > span").text()) || 0,
            uom_conv = parseFloat(me.attr("data-conv")) || 0,
            default_qty = item_qty * uom_conv;
        //                console.log(item_qty + '=====' + me.attr("data-last-qty"))
        //                return;
        if (me.attr("data-is-option") == 1 && me.attr("data-last-qty") != item_qty) {
            validate_option = false;
            me.find('.option-tr').addClass("pulsate")
        }
        if (item_qty == 0)
            validate = false;
        $("td.tag-main-td .mylabel", $(this)).each(function() {
            var label_parent = $(this);
            tags.push({
                Quantity: item_qty,
                criteria_detail_id: $(this).attr("data-entry"),
                criteria_price: $(this).attr("data-price") || 0,
                criteria_note: $(this).attr("data-note") || ''
            });
            tag_amount += parseFloat(label_parent.attr('data-price'));
        });
        data.product_ids.push(me.attr("data-id"));
        var entry_checkbox = me.find('td:eq(0) > input[name=entry_id]').is(":checked");

        var vat_amount = parseFloat(me.attr("vat-amount")) || 0,
            vat2_amount = parseFloat(me.attr("vat2-amount")) || 0,
            //                prod_total_price = parseFloat(me.find("span.price").html().replace(/,/g, "")) || 0,
            total_price_without_vat = parseFloat(me.find("span.price").html().replace(/,/g, "")) || 0,
            total_price_with_vat = parseFloat(me.find("span.price").html().replace(/,/g, "")) || 0;
        //                cons
        if (vat_permation == 1) {
            total_price_without_vat -= (vat_amount + vat2_amount);
        } else {
            if (is_ttc == 1) {
                total_price_without_vat -= (vat_amount + vat2_amount);
            } else {
                total_price_with_vat += (vat_amount + vat2_amount);
            }
        }

        //        console.log(is_ttc+'====')
        //        console.log(prod_total_price+'==')
        data.products.unshift({
            prod_index: e,
            Product_ID: me.attr("data-id"),
            Product_Quantity: item_qty, //same as below
            Item_Quantity: item_qty, //same as above
            Request_Qty: item_qty, //same as above
            default_qty: default_qty, //same as above
            product_description: me.attr('product-description'),
            Product_Disc: parseFloat(me.find("span.discount").attr("data-disc")) || 0,
            //            Discount_Amount:  (parseFloat(me.find("span.discount").text()) * parseFloat(me.find("span.price").html().replace(/,/g, ""))) / 100,
            Discount_Amount: (parseFloat(me.find("span.discount").attr("data-disc") || 0) * parseFloat(me.find(".InputSpinner > span").text() || 0) * parseFloat(me.attr("data-price-single") || 0)) / 100,
            disc_amt_noqty: (parseFloat(me.find("span.discount").attr("data-disc") || 0) * parseFloat(me.attr("data-price-single") || 0)) / 100,
            Added_Amount: tag_amount || 0,
            is_transfer: entry_checkbox ? 1 : 0,
            transfered_quantity: entry_checkbox ? me.find('td:eq(0) > input[name=transfer_quantity]').val() : 0,
            Net_Price: me.attr("data-price-single") || 0, //same as below
            Item_Price: me.attr("data-price-single") || 0, //same as above
            Total_Price: total_price_with_vat || 0,
            Product_Total_Price: total_price_without_vat || 0,
            Entery_ID: $(this).attr("data-entry"),
            UOM_ID: me.find('select.uom').val(),
            vat_percent: me.attr("vat-percent") || 0,
            vat_amount: me.attr("vat-amount") || 0,
            vat2_percent: me.attr("vat2-percent") || 0,
            vat2_amount: me.attr("vat2-amount") || 0,
            expiry_date: (me.attr('data-expiry-date') == null || !me.attr('data-expiry-date')) ? "" : me.attr('data-expiry-date'),
            reserve_date_from: (me.attr('data-reserve-from') == null || !me.attr('data-reserve-from')) ? "" : me.attr('data-reserve-from'),
            reserve_date_to: (me.attr('data-reserve-to') == null || !me.attr('data-reserve-to')) ? "" : me.attr('data-reserve-to'),
            criteria_details: tags,
            total_tax: (parseFloat(me.attr("tax-amount") || 0) * parseFloat(me.find(".InputSpinner > span").text() || 0)),
            //used for edit return
            Return_Product_Quantity: item_qty,
            Return_Product_Total: total_price_without_vat || 0, //me.find("span.price").html().replace(/,/g, ""),
            vat_val: me.attr("vat-amount") || 0,
            Unit_Cost: me.attr("data-price-single") || 0,
            Item_Discount: parseFloat(me.find("span.discount").attr("data-disc")) || 0,
            purchase_detail_id: 0,
            lot_nb: me.attr("data-lot-nb"),
            serial_nb: me.attr("data-serial-nb"),
            is_service: me.attr("data-service"),
            options_arr: me.attr("data-option-arr"),
            //
            hold: me.attr("data-hold"),
            relate_entry_id: me.attr("relate-entry-id"),
            is_promotion: me.attr("is-promotion") || 0
        });

    });
    if (!validate_option) {
        toastr.error(check_prod_options)
        $("#GInvBtn,#submit_payment,#CashInvBtn,#CashWithoutPrintInvBtn,#generate_credit_card,#print_table_invoice,#kitchen_delivery_takeaway,#table_kitchen_btn").removeAttr("disabled", "disabled");
        return;
    }
    if (!validate) {
        toastr.error(check_qty_lang)
        $("#GInvBtn,#submit_payment,#CashInvBtn,#CashWithoutPrintInvBtn,#generate_credit_card,#print_table_invoice,#kitchen_delivery_takeaway,#table_kitchen_btn").removeAttr("disabled", "disabled");

        return;
    }
    //    if (not_valid_items != '') {
    //        alert('Item discount should not exceed user discount limit (' + user_max_discount + ' %)');
    //        $("#GInvBtn,#submit_payment,#CashInvBtn").removeAttr("disabled");
    //        return false;
    //    }
    //    if (discount_first > user_max_discount) {
    //        alert('Invoice discount should not exceed user discount limit (' + user_max_discount + ' %)')
    //        $("#GInvBtn,#submit_payment,#CashInvBtn").removeAttr("disabled");
    //        return false;
    //    }
    if (inv_type == 3 || inv_type == 1 || type_id == 'generate_invoice' || type_id == 4 || type == 2) {
        data.cash_amount = $("#cash_amount").val() || 0;
        data.other_amount = $("#other_amount").val() || 0;
        data.other_description = $("#other_description").val();
        data.invoice_unpaid_amount = public_round_number($("#invoice_unpaid_amount").val()) || 0;
        data.check_credit = $("#InvTypeMpdal input[name=check_credit]:checked").val() ? $("#InvTypeMpdal input[name=check_credit]:checked").val() : 0;
        //data.account_customer_id = $("#CurCustomerInfo").attr('data-account') ? $("#CurCustomerInfo").attr('data-account') : $("#customer_id").attr('data-account');
    }
    $("#SubmitPaymentInvoice").attr("disabled", "disabled").html(SubmittingLang)
    $(loader).removeClass('hidden')
    $('#main_pos_modal').removeClass('hidden');
    $.ajax({
        type: "POST",
        url: "POSAjax/ajaxInvoice",
        data: data,
        dataType: 'json',
        complete: function(v, v2) {
            if (v2 == 'success') {
                var response = v.responseJSON;
                if (response[3] !== undefined)
                    time_now = response[3];
                if (response[0] == 'OK') {

                    var myurl = '';
                    if (data.is_order == 0) {
                        if (pending_status != 3 && (inv_type != 1 || response[2] == 1) && type_id != 1 && type_id != 2 && type_id != 3) {
                            if ((inv_type != 1 || response[2] == 1) && data.is_edited_invoice == 1)
                                response[1] = $("#invoice_auto_id").val();
                            if ($("#titleSpan").attr("data-type") == 2) {
                                myurl = "Inventory/pos_view_return/" + response[1];
                            } else if ($("#titleSpan").attr("data-type") == 1) {
                                myurl = "Inventory/pos_view_invoice/" + response[1];
                            } else {
                                if (response[1][1] == 'exchange') {
                                    myurl = "Inventory/pos_view_exchange/" + response[1][0];
                                } else if (response[1][1] == 'return') {
                                    myurl = "Inventory/pos_view_return/" + response[1][0];

                                } else {
                                    myurl = "Inventory/pos_view_invoice/" + response[1][0];
                                }
                            }
                            if (!sumatra_print && with_print == 1)
                                printPOSExternal(myurl);
                            if ((is_return_value == 3 || is_return_value == 2) && sumatra_print == 1 && with_print == 1) //exchange and return case
                                printPOSExternal(myurl);
                        }
                    } else {
                        if (with_print == 1) {
                            myurl = "Inventory/pos_view_order/order/" + response[1];
                            printPOSExternal(myurl);
                        }
                    }
                    if (show_delivery_notification)
                        RebuildDataTable('Delivery List', [], "POSAjax/getRemindersInv", {}, "#RemindersTable");
                    if (is_shown_list_in_pos && destination_type == 0) {
                        RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {}, '#main_pos_invoice_list')
                        $('.main_pos_invoice_list_div .dataTables_filter,.main_pos_invoice_list_div .dataTables_length,.main_pos_invoice_list_div .dt-buttons,#main_pos_invoice_list thead tr.filter_columns_row').remove()
                    }
                    SuccessInvoice();
                    void_item_reason_array = [];
                    if (table_id != 0) {
                        if (type_id == 1) {
                            $('#ava_rese_tbl_modal').modal('hide');
                        }
                        setTimeout(function() {
                            window.location = site_link + 'main_page';
                        }, 160);
                    }
                    emptyPOSData()
                } else {
                    if (response[1][0] == 'expiry_error') {
                        $.each(response[1][1], function(indx, row) {
                            $("#OrderTable > tbody tr[data-id=" + row['Product_ID'] + "][data-expiry-date=" + row['expiry_date'] + "] span.item-name").addClass("red-border")
                        })
                        FailureInvoice(check_expiry_exist_lang)
                    } else
                    if (response[1][0] == 'serial_error') {
                        $.each(response[1][1], function(indx, row) {
                            $("#OrderTable > tbody tr[data-id=" + row['Product_ID'] + "][data-serial-nb=" + row['serial_nb'] + "] span.item-name").addClass("red-border")
                        })
                        FailureInvoice(check_serial_exist_lang)

                    } else
                    if (response[1][0] == 'lot_error') {
                        $.each(response[1][1], function(indx, row) {
                            $("#OrderTable > tbody tr[data-id=" + row['Product_ID'] + "][data-lot-nb=" + row['lot_nb'] + "] span.item-name").addClass("red-border")
                        })
                        FailureInvoice(check_lot_exist_lang)

                    } else
                    if (response[1][0] == 'qty_error') {
                        $.each(response[1][1], function(indx, row) {
                            $("#OrderTable > tbody tr[data-id=" + row['Product_ID'] + "] span.item-name").addClass("red-border")
                        })
                        FailureInvoice(check_qty_exist_lang)

                    } else
                    if ('overlapp' in response[1]) {
                        var overlap_indx = response[1]['overlapp'];
                        $.each(overlap_indx, function(index, value) {
                            $("#OrderTable > tbody tr:eq(" + value + ") span.item-name").addClass("red-border")
                        });
                        FailureInvoice(response[1][0]);
                    } else
                    if ('product_branches' in response[1]) {
                        var product_branches_indx = response[1]['product_branches'];
                        $.each(product_branches_indx, function(index, value) {
                            $("#OrderTable > tbody tr[data-id=" + value + "] span.item-name").addClass("red-border")
                        });
                        FailureInvoice(branch_prod_alert);
                    } else {
                        FailureInvoice(response[1][0]);
                    }

                }
                //                alert()
                $(loader).addClass('hidden')
                $('#main_pos_modal').addClass('hidden')
                $("#scan_cust_qr").modal("hide")
                $("#fill_scanned_customer").prop("disabled", false)
            }
            $("#GInvBtn,#submit_payment,#CashInvBtn,#CashWithoutPrintInvBtn,#generate_credit_card,#print_table_invoice,#kitchen_delivery_takeaway,#table_kitchen_btn").removeAttr("disabled");
        }
    });
}

function printOrderInvoiceNoSave() {
    if ($("#OrderTable tbody tr").length == 0)
        return;
    var invoice_net_total = parseFloat($("#TotalTable td.TotalVal").attr("data-total")),
        currency_round_val = round_number((invoice_net_total - (parseFloat($("#TotalTable td.SubtotalVal").attr("data-subtotal")) - parseFloat($(".DiscountValue").val() || 0) + parseFloat($("#TotalTable td.TVAVal").text() || 0)) - parseFloat($(".tax_amount").attr("total-card-tax") || 0)), 7),
        ship_val = $("#shipping_id").val() || 0,
        discount_first = parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount"));
    var data = {
        "Invoice_Sub_Total": parseFloat($("#TotalTable td.SubtotalVal").attr("data-subtotal")),
        "Invoice_Net_Total": invoice_net_total,
        "Invoice_Shipping": ship_val,
        service_value: $('#TotalTable .service').attr('data-value') || 0,
        "Invoice_VAT": parseFloat($("#TotalTable td.TVAVal").text()),
        vat1_total: $("#TotalTable td.TVAVal").attr('vat1-total'),
        vat2_total: $("#TotalTable td.TVAVal").attr('vat2-total'),
        "Invoice_Currency": PrimaryCurrency[0],
        Invoice_Description: $("#text_note").val(),
        Invoice_Note: $("#InvoiceNoteSpan").html(),
        Invoice_Discount: discount_first ? discount_first : 0,
        Discount_Amount: $(".DiscountValue").val(),
        Paid_Amount: ((parseFloat($("#cash_amount").val()) || 0) + (parseFloat($("#other_amount").val()) || 0)),
        tax_amount: parseFloat($(".tax_amount").attr("total-card-tax")) || 0,
        cash_cat_amount: $("#cash_cat_amount").val() || 0,
        "products": []
    };
    $("#OrderTable tbody tr").each(function(e) {
        var me = $(this);
        var tags = [],
            tag_amount = 0,
            tags_data = '';
        $("td.tag-main-td .mylabel", $(this)).each(function() {
            var label_parent = $(this);
            tags.push({
                Quantity: parseFloat(me.find(".InputSpinner > span").text()),
                Tag_ID: $(this).attr("data-entry"),
                tag_price: $(this).attr("data-price"),
                tag_note: $(this).attr("data-note") || ''
            });
            tag_amount += parseFloat(label_parent.attr('data-price'));
            tags_data += label_parent.attr('data-content') + ',';
        });
        data.products.push({
            Product_ID: me.attr("data-id"),
            Product_Quantity: parseFloat(me.find(".InputSpinner > span").text()),
            product_description: me.attr('product-description'),
            product_name: $('span.item-name', me).html(),
            Product_Disc: parseFloat(me.find("span.discount").attr("data-disc")),
            Discount_Amount: (parseFloat(me.find("span.discount").attr("data-disc") || 0) * parseFloat(me.find(".InputSpinner > span").text() || 0) * parseFloat(me.attr("data-price-single") || 0)) / 100,
            Added_Amount: tag_amount,
            Net_Price: me.attr("data-price-single"),
            //            Total_Price: me.find("span.price").html().replace(/,/g, ""),
            UOM_ID: me.find('select.uom').val(),
            vat_percent: me.attr("vat-percent") || 0,
            vat_amount: me.attr("vat-amount") || 0,
            vat2_percent: me.attr("vat2-percent") || 0,
            vat2_amount: me.attr("vat2-amount") || 0,
            tags: tags_data,
            total_tax: (parseFloat(me.attr("tax-amount") || 0) * parseFloat(me.find(".InputSpinner > span").text() || 0)),
            //used for edit return
            vat_val: me.attr("vat-amount") || 0,
            Unit_Cost: me.attr("data-price-single"),
            Item_Discount: parseFloat(me.find("span.discount").attr("data-disc")),
        });

    });
    $('#main_pos_modal').removeClass('hidden')
    $.ajax({
        type: "POST",
        url: "POSAjax/printInvoiceNoSave",
        data: data,
        complete: function(v, v2) {
            if (v2 == 'success') {
                var response = v.responseText;
                $("#OrderTable tbody").empty()
                emptyPOSData();
                if (!sumatra_print)
                    printPOSExternal('', response)
                $('#FunctionsModal').modal('hide');
                $('#main_pos_modal').addClass('hidden')
            }
        }
    });
}

function emptyPOSData() {
    $("#OrderTable > tbody:last,#CurCustomerInfo").empty();
    //    UpdateTable($("#OrderTable > tbody:last"));
    $(".initial_disable").addClass("current_disable").addClass("not-allowed")
    if ($(".DiscountValue").hasClass('initial_disable'))
        $(".DiscountValue").attr("disabled", "disabled")
    $("#scanned_cust_id").val('')
    $('.submit_main_div').removeClass('stop_submit_div');
    $("#CurCustomerInfo").attr("CurCustomerID", 0);
    $("#CurCustomerInfo").attr('customer-pos-id', 0);
    $("#CurCustomerInfo").attr("data-is-pos", 0);
    $("#CurCustomerInfo").attr("data-account-id", 0);
    $("#customer_id").val("").attr("data-id", 0);
    $('#cash_cat_amount,#cash_amount,#other_amount,#other_description,#invoice_unpaid_amount,#customer_id,#order_note_description,#order_delivery_date').val('');
    $("#timepicker").val(time_convert_24_to_12(time_now.split(" ")[1]));
    $("#delivery_date").val(time_now.split(" ")[0])
    $('#customer_id').attr('data-id', '')
    if (!$("#inv_with_print").is(":checked"))
        $("#inv_with_print").trigger('click')

    $("#postponed_pos_customer_id").val('').attr("data-select-name", "") //.trigger('change')
    build_select2($("#postponed_pos_customer_id"), "xhr/poscustomerSearch")
    $("#postponed_customer_id").val('').attr("data-select-name", "") //.trigger('change')
    build_select2($("#postponed_customer_id"), "xhr/customerSearch");

    kitchen_takeaway_delivery = 0;

    $('.payment-labels').removeClass('payment-color-labels')

    $('.cash-return-span').html(0);
    $('#postponed_date_time,#postponed_note').val('');
    $('#posponted_status').val('').select2();

    $("#TotalTable .tax_amount").html("0").attr("total-card-tax", 0)

    //
    $("#TotalTable .TotalSpanInTable.discount-span-input-per").parents("tr").attr("data-discount", 0)
    $("#TotalTable .TotalSpanInTable > .discount").html("0 %");
    $("#DiscountInput").val(0);
    $("#TotalTable input.DiscountValue, #TotalTable input.TTCDiscountValue").val(0);
    GotoCateg(-1);
    $("#NoteSpan").html("")
    pending_status = 0;
    is_edited_invoice = 0;
    is_return_postponed = 0;
    $("#FunctionsModal button").removeClass("disabled")
    if ($("#titleSpan").attr("data-type") == 4)
        $('#order_pos').trigger("click")
    else
        $("#invoicePOS").trigger('click')
        //                    $("#titleSpan").html('<b class="">Invoice</b>')
        //                    $("#titleSpan").attr("data-type", 1).removeClass("animateClass")
    $("#shipping_id").val('').attr("data-select-name", "").trigger('change')
    $("#delivery_depot_id").val('').attr("data-select-name", "").trigger('change')
    $('#delivery_date').datepicker("setDate", new Date());
    $("#text_note,#text_note_delivery").val("")
    $("#cash_amount").val(0);
    $(".TVAVal").html(0);
    $(".cash-return-span").html(0);
    PrimaryCurrency = LocalCurrency;
    $("#Customer_Class_ID").val(default_class_id).select2().trigger("change")
    UpdateTable($("#OrderTable > tbody:last"))
    is_delivery = 0;
    $("#driver_id").val("").attr("data-select-name", "").trigger("change")
    $("#shipping_company_id").val('').attr('data-select-name', '').trigger("change")
    $("#is_invoice_total_on_shipping").prop("checked", false)
    $("#shipping_on_self").prop("checked", false)
    $("#fill_scanned_customer").prop("disabled", false)
}

function SuccessInvoice() {
    AddAlert("#Payment_Alert", "Payment added successfully", "success");
    hideModalAlert('InvTypeMpdal', 'Payment_Alert');
    hideModalAlert('ava_rese_tbl_modal', '');
    hideModalAlert('request_transfer_modal', 'request_transfer_alert');

    global_counter += 1;
    if (global_counter >= 20) {
        $("#OrderTable > tbody").empty(); //we empty it to don't ask for confirm something like are you sure you want to continue without save? on unload
        if ($("#titleSpan").attr("data-type") == 4) {
            if (is_actual == 0)
                window.location = site_link + 'main_pos/order';
            else
                window.location = site_link + 'main_pos/act/order';
        } else
            location.reload();
    }

    //    setTimeout(function () {
    //      location.reload();
    //    }, 1600);
}

function FailureInvoice(response) {
    AddAlert("#Payment_Alert", response, "danger");
    toastr.error(response);
}
var ID;
$(window).ready(function(e) {
    $(window).scannerDetection({
        focusInputClass: 'input-save-on-barcodescan',
        minLength: default_barcode_length
    });
    $("#scan_cust_qr").scannerDetection({ minLength: 1 });

    $(window).bind('scannerDetectionComplete', function(e, data) {
            //         $("#OrderTable input").trigger("blur")
            //        console.log('complete ' + data.string);
            ID = data.string;
            //        $("#bCode").val(ID);
            if ($("#scan_cust_qr").data('bs.modal') == undefined || !$("#scan_cust_qr").data('bs.modal').isShown) {
                appendScannedItem(ID)
            } else {
                fill_scanned_customer(ID)
            }
            //        }
        })
        .bind('scannerDetectionError', function(e, data) {
            //        console.log('detection error ' + data.string);
        })
        .bind('scannerDetectionReceive', function(e, data) {
            //$("#OrderTable input").trigger("blur")
            //        console.log('Recieve');
            //        console.log(data.evt.which);
        });
});

function RebuildPOSDataTable(url, data, table) {
    var name = table === undefined ? "#tableWithSearch" : table;
    $(name).DataTable().destroy();
    $(name + " tbody").empty();
    var myurl = window.site_link + url;
    $(name).dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": myurl,
            "data": data
        },
        dom: 'Blfrtip',
        "pagingType": "simple_numbers",
        "bInfo": false,
        "aaSorting": [],
        "columnDefs": [
            { "className": "dt-center", "targets": "_all" }
        ],
        "bLengthChange": false,
        buttons: [],
        "pageLength": 10
    });
}

$(function() {
    $("#MainCat .catli").on("click", function(e) {
        //we add this condition so in touch screen if scroll don't fire click event
        if ($(this).closest('.dragscroll').hasClass('dragscroll-inprogress')) {
            e.preventDefault();
            return false;
        }
        //if cat disabled or parent is on scrololll progress then prevent click
        if (!$(this).hasClass('not-allowed')) {
            e.preventDefault();
            $("#MainCat .catli").removeClass('active');
            var ID = parseInt($(this).find('span').attr("data-id"));
            CurPath = [
                [ID, $(this).find('span').attr('data-name')]
            ];
            AjaxLoadCateg(ID, Customer_ID);
            $(this).addClass('active');
        }

    });
    //    $("#MainCat").on("click", ".catli > a", function (e) {
    //        e.preventDefault();
    //        $("#MainCat .catli").removeClass('active');
    //        var Customer_ID = $("#CurCustomerInfo").attr('CurCustomerID');
    //        // related to highlight and update breadcrumb
    //        var obj = $(this),
    //                main = obj.parent(),
    //                ID = obj.attr('data-id'),
    //                Name = obj.attr("data-name");
    //        CurPath = [];
    //        $.ajax({
    //            url: "POSAjax/getCategory?id=" + ID + "&Customerid=" + Customer_ID + "&class_id=" + $("#Customer_Class_ID").val() + "&type=1",
    //            dataType: "jsonp",
    //            complete: function (e) {
    //                main.addClass('active');
    //                $("#CategLoader")
    //                $("#CategLoader").parent().remove();
    //                $("#Tab_1").removeClass("Busy")
    //                $("#product_search").blur().val("");
    //                CurPath.push([ID, Name]);
    //                UpdateCrumbs();
    //            }
    //        });
    //    });
});

function appendScannedItem(barcode) {
    //     $("#OrderTable input").trigger("blur")
    var T = $("#OrderTable > tbody:last");
    $.ajax({
        url: "POSAjax/searchBarcodeforPOS",
        method: 'GET',
        data: {
            barcode: barcode,
            class_id: $("#Customer_Class_ID").val(),
            type: 1,
            customer_id: $("#CurCustomerInfo").attr('CurCustomerID') ? $("#CurCustomerInfo").attr('CurCustomerID') : 0
        },
        dataType: 'json',
        complete: function(v1, v2) {
            var Data = v1.responseJSON;
            if (Data['is_pos_disabled'] == 1) {
                toastr.error(no_qty_lang)
                return;
            }

            if ($.type(Data) === "object") {
                //            console.log(v1.responseJSON)
                //console.log(LocalCurrency[0]+' ==== '+PrimaryCurrency[0])
                var ref = Math.round(Date.now() + Math.random());
                var Row = $("<tr data-entry='0' price-change='0' data-conv='1' data-product-ref='" + Data['ID'] + "' data-ref='" + ref + "' data-cid='" + 0 + "'data-id='" + Data['ID'] + "' data-discount='" + Data['disc'] + "' data-price-single='" + Data['Price'] + "' data-price-single-orginal-ttc='" + Data['ttc_price'] + "' data-price-single-orginal='" + Data['Price'] + "' data-qty='" + Data['Quantity'] + "' data-cost ='" + Data['last_cost'] + "' data-last-price='" + Data['last_price'] + "' data-vat='" + Data['VAT'] + "' data-max-discount='" + Data["Product_Limit_Discount"] + "'  data-tax='" + Data['is_tax'] + "' tax-amount='" + Data['tax_amount'] + "' vat-percent='" + Data['vat_percent'] + "' vat2-percent='" + Data['vat2_percent'] + "' data-is-option='" + Data['has_optional'] + "' recipe-qty='" + Data['recipe_qty'] + "' ttc-price='" + Data['ttc_price'] + "' expiry-active='" + Data['is_expiry'] + "' data-lot='" + Data['is_lot'] + "' data-serial='" + Data['is_serial'] + "' reserve-active='" + Data['duration_reservation'] + "' change-price='" + Data['force_change_price'] + "' data-expiry-date ='' data-category-id='" + Data['Category_ID'] + "' data-service='" + Data['is_service'] + "'></tr>"),
                    T2 = RowTemp;

                T2 = T2.replace("$CHECKBOX$", "hidden")
                T2 = T2.replace("$ID$", "1")
                T2 = T2.replace("$NAME$", Data['Name'])
                T2 = T2.replace("$BARCODE$", Data['Bar_Code'])
                    //                        T2 = T2.replace("$QTY$",parseFloat(Data['Price']/Data['unit_price']));

                T2 = T2.replace("$QTY$", Data['unit_qty']);
                T2 = T2.replace("$QTYHINT$", '(' + AddCommas(public_round_number(parseFloat(Data['stock_qty']))) + ')');
                T2 = T2.replace("$COSTHINT$", '(' + AddCommas(public_round_number(parseFloat(ConvertCurrency2(Data['last_cost'], LocalCurrency[0], PrimaryCurrency[0])))) + ')');
                T2 = T2.replace("$PRICEHINT$", '(' + AddCommas(public_round_number(parseFloat(ConvertCurrency2(Data['last_price'], LocalCurrency[0], PrimaryCurrency[0])))) + ')');

                /*end edit*/
                T2 = T2.replace("$VAT$", Data['Product_VAT'])
                T2 = T2.replace("$TAX$", Data['is_tax'])

                T2 = T2.replace("$VATPERCENT$", Data['vat_percent'])
                T2 = T2.replace("$VAT2PERCENT$", Data['vat2_percent'])
                T2 = T2.replace("$HASOPTIONAL$", Data['has_optional'])
                T2 = T2.replace("$RECIPEQTY$", Data['recipe_qty'])
                T2 = T2.replace("$TTCPRICE$", Data['ttc_price'])
                T2 = T2.replace("$EXPIRYACTIVE$", Data['is_expiry'])
                T2 = T2.replace("$ISLOT$", Data['is_lot'])
                T2 = T2.replace("$ISSERVICE$", Data['is_service'])
                T2 = T2.replace("$ISSERIAL$", Data['is_serial'])
                T2 = T2.replace("$RESERVEACTIVE$", Data['duration_reservation'])
                T2 = T2.replace("$CHANGEPRICE$", Data['force_change_price'])
                T2 = T2.replace("$MAXDISC$", Data['Product_Limit_Discount'])
                T2 = T2.replace("$UNITPRICE$", Data['Price'])
                T2 = T2.replace("$PRICE$", Data['unit_price'])
                T2 = T2.replace(/\$CURRENCY\$/g, PrimaryCurrency[1]);
                //first discount is for attr needed in calculations and second is for view

                T2 = T2.replace("$DISCOUNT$", Data['disc']);
                T2 = T2.replace("$DISCOUNT$", round_number(Data['disc']));

                //                T2 = T2.replace(/\$DISCOUNT\$/g, Data['disc']);
                var hold = 0;
                if ($(".selected_hold.hold").length > 0) {
                    hold = $(".selected_hold").attr("data-role")
                }
                Row.attr("data-hold", hold)
                T2 = T2.replace("$holdclass$", "hold" + hold);
                T2 = T2.replace("$holdlevel$", hold);
                T.prepend(Row);
                if ((Data['is_expiry'] == 1 && is_active_expiry_date == 1) || (!pos_fields_to_hide.includes('0') && Data['is_lot'] == 1) || (!pos_fields_to_hide.includes('1') && Data['is_serial'] == 1)) {
                    T2 = T2.replace("$EXPIRYICON$", '<i class="fa fa-calendar expiry-icon"></i>');
                    $('#expiry-date-modal').modal('show');

                } else {
                    T2 = T2.replace("$EXPIRYICON$", '');
                }
                if ($('#titleSpan').attr('data-type') == 1) {
                    if (Data['is_expiry'] == 1 && is_active_expiry_date == 1) {
                        build_select2($('#expiry_date'), 'xhr/get_product_expiry?product_id=' + Data['ID']);
                    }
                    if (Data['is_lot'] == 1) {
                        build_select2($('#lot_nb'), 'xhr/get_product_lot?product_id=' + Data['ID']);
                    }
                    if (Data['is_serial'] == 1) {
                        build_select2($('#serial_nb'), 'xhr/get_product_serial?product_id=' + Data['ID']);
                    }
                }


                if (Data['duration_reservation'] == 1 && is_active_reserve_date == 1) {

                    $('#reservation-duration-modal').modal('show');
                    T2 = T2.replace("$RESERVEICON$", '<i class="fa fa-calendar reserve-icon"></i>');
                } else {
                    T2 = T2.replace("$RESERVEICON$", '');
                }
                if (Data['force_change_price'] == 1) {
                    $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                } else {
                    if (change_pos_price)
                        $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                    else
                        $(".key-price").addClass("not-allowed empty_key").removeAttr("data-role")

                }
                if (Data['has_optional'] == 1) {
                    build_optional_link(ref)
                    $(".option-tr", $(Row)).removeClass("hidden")
                }

                //                if (Data['has_optional'] == 1) {
                //                    build_optional_link(ref)
                //                }
                Row.append(T2);

                Row.find("span.qty_span").html(Data['unit_qty'])
                    //    Row.find('select.uom').show().select2()
                Row.find("select[name=uom] > option[value=" + Data['UOM_ID'] + "]").attr("selected", true)
                    //    Row.find("select[name=uom]").select2()
                var units_arr = Data['Product_UOM'].split("/");
                $("select[name=uom] > option", Row).each(function() {
                    if ($.inArray($(this).attr("value"), units_arr) === -1) {
                        $(this).remove()
                    }
                })
                if (parseFloat($(SelectedTR).find("span.qty_span").html()) < 0) {
                    $(SelectedTR).find("td").removeClass("tr-white tr-gray").addClass("tr-return") //css("background-color", "white");
                } else {
                    $(SelectedTR).find("td").removeClass("tr-return tr-gray").addClass("tr-white")
                }
                if ($(SelectedTR).attr("is-promotion") == 1) {
                    $(SelectedTR).find("td").removeClass("tr-gray tr-white").addClass("tr-prom")
                } else {
                    $(SelectedTR).find("td").removeClass("tr-gray tr-prom").addClass("tr-white")
                }
                $(Row).find("td").removeClass("tr-white tr-return").addClass("tr-gray") //css("background-color", "#e2e2e2");
                SelectedTR = $(Row);

                flag = 2
                $(".key1").removeClass("choosen");
                $(".key1[data-flag=2]").addClass("choosen").trigger("click");

                UpdateTable(T);
            } else {
                var audioElement = new Audio();
                audioElement.setAttribute('src', site_link + 'Views/files/success.wav');
                $("#scan_bar_code_bar").addClass('show').html("<b>" + bar_code_check + "</b>");
                setTimeout(function() {
                    $("#scan_bar_code_bar").removeClass('show')
                }, 2000);
                audioElement.play();
            }
        }
    })
}
//function searchProductforPOS(id) {
//    //    alert(Customer_ID)
//    //    return
//    var T = $("#OrderTable > tbody:last");
//    $.ajax({
//        url: "POSAjax/searchProductforPOS",
//        method: 'GET',
//        data: {id: id, class_id: $("#Customer_Class_ID").val(), customer_id: $("#CurCustomerInfo").attr('CurCustomerID') ? $("#CurCustomerInfo").attr('CurCustomerID') : 0},
//        dataType: 'json',
//        complete: function (v1, v2) {
//            var Data = v1.responseJSON;
//            var Row = $("<tr data-entry='0' price-change='0' data-conv='1' data-product-ref='" + Data['ID'] + "' data-cost ='" + Data['last_cost'] + "' data-last-price='" + Data['last_price'] + "' data-ref='" + Math.round(Date.now() + Math.random()) + "' data-cid='" + 0 + "'data-id='" + Data['ID'] + "' data-discount='0' data-price-single='" + Data['Price'] + "' data-qty='" + Data['Quantity'] + "' data-vat='" + Data['VAT'] + "' vat-percent='" + Data['vat_percent'] + "' ttc-price='" + Data['ttc_price'] + "' data-max-discount='" + Data["Product_Limit_Discount"] + "' data-tax='" + Data['is_tax'] + "'></tr>"), T2 = RowTemp;
//            var qty_changed = parseFloat($(this).find('span.price').attr("CurPrice")) / parseFloat($(this).attr("data-price-single"));
//
//            $(this).find('.InputSpinner > span.qty_span').html(qty_changed)
//
//            T2 = T2.replace("$CHECKBOX$", "hidden")
//            T2 = T2.replace("$ID$", "1")
//            T2 = T2.replace("$NAME$", Data['Name'])
//            T2 = T2.replace("$BARCODE$", Data['Bar_Code'])
//            T2 = T2.replace("$QTY$", Data['unit_qty']);
//            T2 = T2.replace("$QTYHINT$", '(' + AddCommas(parseFloat(Data['stock_qty']).toXFixed(1)) + ')');
//            T2 = T2.replace("$COSTHINT$", '(' + AddCommas(parseFloat(ConvertCurrency2(Data['last_cost'], LocalCurrency[0], PrimaryCurrency[0])).toXFixed(3)) + ')');
//
//            T2 = T2.replace("$PRICEHINT$", '(' + AddCommas(parseFloat(ConvertCurrency2(Data['last_price'], LocalCurrency[0], PrimaryCurrency[0])).toXFixed(3)) + ')');
//
//            /*end edit*/
//            T2 = T2.replace("$VAT$", Data['Product_VAT'])
//            T2 = T2.replace("$TAX$", Data['is_tax'])
//
//            T2 = T2.replace("$VATPERCENT$", Data['vat_percent'])
//            T2 = T2.replace("$TTCPRICE$", Data['ttc_price'])
//            T2 = T2.replace("$MAXDISC$", Data['Product_Limit_Discount'])
//            T2 = T2.replace("$UNITPRICE$", Data['Price'])
//            T2 = T2.replace("$PRICE$", Data['unit_price'])
//            T2 = T2.replace("$COST$", ConvertCurrency2(Data['last_cost'], LocalCurrency[0], PrimaryCurrency[0]))
//            T2 = T2.replace("$LASTPRICE$", ConvertCurrency2(Data['last_price'], LocalCurrency[0], PrimaryCurrency[0]))
//            T2 = T2.replace(/\$CURRENCY\$/g, PrimaryCurrency[1]);
//
//            T.prepend(Row);
//
//            Row.append(T2);
//            Row.find("span.qty_span").html(Data['unit_qty'])
//            //    Row.find('select.uom').show().select2()
//            Row.find("select[name=uom] > option[value=" + Data['UOM_ID'] + "]").attr("selected", true)
//            //    Row.find("select[name=uom]").select2()
//            var units_arr = Data['Product_UOM'].split("/");
//            $("select[name=uom] > option", Row).each(function () {
//                if ($.inArray($(this).attr("value"), units_arr) === -1) {
//                    $(this).remove()
//                }
//            })
//            $("#OrderTable").find("td").css("background-color", "white");
//            $(Row).find("td").css("background-color", "#e2e2e2");
//            window.SelectedTR = $(Row);
//
//            flag = 2
//            $(".key1").removeClass("choosen");
//            $(".key1[data-flag=2]").addClass("choosen").trigger("click");
//
//            UpdateTable(T);
//        }
//    })
//}
function printPOSExternal(url, data) {
    $("#print_iframe").remove();
    if (url == undefined || url == false || url == null || url == '')
        url = 'about::blank';
    $("<iframe id='print_iframe' style='position:absolute;top:0px;left:0;width:0px;height:0px;opacity:0;' src='" + url + "' ></iframe>").appendTo("body");
    if (data !== undefined) {
        $("#print_iframe")[0].contentWindow.document.write(data);
        $("#print_iframe")[0].contentWindow.document.close(); //important to make close or window load as example will not triggered
    }
}

function customerSelectAutocomplete(ui) {
    var Content = "";
    Content += "<div class='row m-t-5'><span class='Name'><strong>" + NameLang + ": </strong> " + ui.item.Customer_Name + "</span>&nbsp/&nbsp<span class='Phone'> <strong>" + PhoneLang + ": </strong> " + ui.item.Customer_Mobile + "</span>&nbsp/&nbsp";
    Content += "<span class='Address'> <strong>" + AddressLang + ": </strong> " + ui.item.Customer_Address + "</span>";
    Content += "  <span id='search_customer_balance' class='bold'></span>";
    if ((ui.item.is_pos_customer == 1 && show_balance_search_road_cust) ||
        (ui.item.is_pos_customer == 0 && show_balance_search_cust)) {
        getAccBalance('#search_customer_balance', ui.item.account_id, ui.item.is_pos_customer == "0" ? '' : ui.item.pos_customer_id);
    }
    if (show_last_customer_order_perm) {
        Content += "&nbsp&nbsp<span class='fa fa-eye fa-2x view_customer_last_orders' style='color:#DDD;cursor:pointer'></span>";
    }
    Content += "&nbsp&nbsp<span class='fa fa-pencil fa-2x edit_road_customer " + (ui.item.is_pos_customer == 1 ? '' : 'openFrame') + "' " + (ui.item.is_pos_customer == 1 ? '' : 'data-src="Inventory/viewCustomerDetails/' + ui.item.Customer_ID + '?is_pop=1&modal=1"') + " style='color:#DDD;cursor:pointer'></span>";
    Content += "</div>";
    if (ui.item.allergy) {
        Content += "<span class='allergy'><strong>" + allergy + ": </strong> " + ui.item.allergy + "</span></div>";
    }
    if (ui.item.intolerance) {
        Content += "&nbsp/&nbsp<span class='intolerance'><strong>" + intolerance + ": </strong> " + ui.item.intolerance + "</span></div>";
    }
    $("#CurCustomerInfo").html(Content).attr("CurCustomerID", ui.item.Customer_ID);
    $("#CurCustomerInfo").attr("data-is-pos", ui.item.is_pos_customer);
    $("#CurCustomerInfo").attr("data-account-id", ui.item.account_id);
    $("#CurCustomerInfo").attr("customer-pos-id", ui.item.pos_customer_id)
    Customer_ID = ui.item.Customer_ID;
    $("#InvTypeMpdal input[name=customer_id],#customer_id").val(ui.item.Customer_Name + " - " + ui.item.Customer_Mobile);
    $('#customer_id').attr('data-id', Customer_ID)
        //    alert()
    if (ui.item.is_pos_customer == 1) {
        $("#postponed_pos_customer_id").val(ui.item.pos_customer_id).attr("data-select-name", (ui.item.Customer_Name + " - " + ui.item.Customer_Mobile))
    } else {
        $("#postponed_pos_customer_id").val('').attr("data-select-name", '')
    }
    build_select2($("#inv_pos_cust,#post_pos_cust,#postponed_pos_customer_id"), "xhr/poscustomerSearch")

    var old_class_val = $("#Customer_Class_ID").val();
    //
    if (old_class_val != ui.item.Class_ID) {
        $("#Customer_Class_ID").val(ui.item.Class_ID).select2()
        $("#Customer_Class_ID").trigger('select2-selecting')
        ChangePOSCurrency()
    }
    if (Customer_ID != 0) {
        $('#Loader').addClass('hideme')
    } else {
        $('#Loader').removeClass('hideme')
    }
    var CurDiscount = $("#TotalTable .DiscountVal").parent();
    CurDiscount.attr("data-discount", parseFloat(ui.item.Customer_Discount));
    $("#DiscountInput").val(parseFloat(ui.item.Customer_Discount))
        //    $("#TotalTable .TotalSpanInTable > .discount").text(parseFloat(CurDiscount.attr("data-discount")).toXFixed(3) + " %");//.click();
    UpdateTable($("#OrderTable > tbody:last"));
}

function chck_manager_disc_pass(seed, pass) {
    var myseed = parseFloat(seed.substr(1, 3)) + 10,
        user_seed = parseFloat(pass.charAt(4) + pass.charAt(2) + pass.charAt(0));
    if (myseed == user_seed)
        return true;
    return false;

}

function ChangeQuantity(input) {
    var min = parseInt($(input).attr('min')),
        max = parseInt($(input).parents('tr').find('td:eq(3) span.qty_span').html()),
        value = parseInt($(input).val());
    if (value >= min && value <= max) {
        $(input).val(value)
    } else {
        if (value < min) {
            $(input).val(min)
        }
        if (value > max) {
            $(input).val(max)
        }
    }
}

function check_before_post_invoice() {
    //console.log('BBBBB')
    //if waiting to update total then stop waiting and direct call it here
    //ex: if fill discount amount and then direct click cash it will insert total amount without discount
    if (update_total_timeout) {
        clearTimeout(update_total_timeout);
        update_total_timeout = false;
        InternalUpdateTable();
    }
}

//function round_number(number, digits) {
//    if (digits === undefined)
//        digits = 7;
//    
//    digits = parseFloat(1+'0'.repeat(digits));
//    return total = Math.round(number * digits) / digits;
//}
function fill_scanned_customer(ID, cb_ft) {
    //    alert(ID)
    $.ajax({
        url: "POSAjax/get_scanned_customer",
        method: 'GET',
        data: { customer_code: ID },
        dataType: 'json',
        complete: function(v1, v2) {
            var customer_txt = '';
            var is_new_cust = false;
            if (v1.responseJSON['item'] != '') {
                customerSelectAutocomplete(v1.responseJSON)
                    //customer_txt = $("#CurCustomerInfo span.Name").html();
                is_new_cust = true;
            } else {
                //customer_txt = no_data_available;
            }
            //$("#scan_cust_qr").modal("hide")
            if ($("#CurCustomerInfo").attr('CurCustomerID') == '' || $("#CurCustomerInfo").attr('CurCustomerID') == 0) {
                $('#generate_scan').addClass("style_btn");
                $('#fill_scanned_customer').removeClass("style_btn");
                customer_txt = no_data_available;
            } else {
                $('#generate_scan').removeClass("style_btn");
                $('#fill_scanned_customer').addClass("style_btn");
                customer_txt = $("#CurCustomerInfo span.Name").html();
                if (is_new_cust == false)
                    alert(no_data_available);
            }
            $("#scanned_cust_id").val('');
            $("#scanned_cust_name").removeClass("hidden").html(customer_txt);
        }
    })
}

function fill_customer_by_id(ID) {
    $.ajax({
        url: "POSAjax/get_customer_by_id",
        method: 'GET',
        data: { id: ID },
        dataType: 'json',
        complete: function(v1, v2) {
            if (v1.responseJSON.item != '')
                customerSelectAutocomplete(v1.responseJSON)
        }
    })
}

function show_prices() {
    $(".price_element").removeClass("hidden")
        //    $('#keypad').addClass('show_all_price_keypad_height')
    current_show_price = true;
}

function hide_prices() {
    $(".price_element").addClass("hidden")
        //    $("#keypad").removeClass("show_all_price_keypad_height")
    current_show_price = false;
}

function build_optional_link(ref, cb, cb_param, is_force_open) {
    var tr = $("#OrderTable tbody tr[data-ref=" + ref + "]"),
        product_id = tr.attr("data-id"),
        tr_main_qty = (parseFloat(tr.find(".InputSpinner > span").text()) || 0),
        tr_qty = (parseFloat(tr.find(".InputSpinner > span").text()) || 0) * (parseFloat(tr.attr("data-conv")) || 0) / (parseFloat(tr.attr("recipe-qty")) || 1);
    $(".op-block:gt(0)").empty().remove()
    $(".op-block:eq(0) .op-block-det").empty()
    $("#op_main_qty").val(tr_main_qty)
    $("#product_options_modal").attr('data-ref', ref) //.modal("show");
    $("#product_options_modal #next_btn").prop("disabled", true)
    $("#product_options_modal .op-title").addClass("hidden")
    $.ajax({
        url: "POSAjax/get_prod_options",
        data: { product_id: product_id },
        dataType: 'json',
        complete: function(v1, v2) {
            if (v2 == "success") {

                var data = v1.responseJSON,
                    is_req = false;
                $.each(data, function(indx, row) {
                    var parent;
                    if (indx == 0) {
                        parent = $(".op-block:eq(0)");
                    } else {
                        parent = $(".op-block:eq(0)").clone();
                        $(".op-div", parent).remove()
                        parent.appendTo($("#op_main_div"))
                    }
                    //                    var qty = round_number(row['quantity']);
                    var qty = round_number(tr_qty * row['quantity']);
                    //                    console.log(tr_qty+'===='+row['quantity']+'==='+qty)
                    $(".op-title", parent).html(block_title.replace('[[nb]]', qty) + (row['is_required'] == 1 ? '<span class="red-star" style="font-size:27px;">*</span>' : ''))
                    parent.attr('data-qty', row['quantity'])
                    parent.attr('data-required', row['is_required'])
                    if (row['is_required'] == 1)
                        is_req = true;
                    $.each(row['details'], function(child_indx, child_row) {
                        var cloned = $('.temp-op-div').clone();
                        cloned.removeClass("hidden temp-op-div")
                        cloned.attr("data-id", child_row['sub_product_id'])
                        cloned.attr("data-option-id", row['option_id'])
                        cloned.attr("data-uom", child_row['UOM_ID'])
                        $(".op-prod-name", cloned).text(child_row['product_name'])
                        parent.find('.op-block-det').append(cloned)
                    });
                });
                if (is_req || is_force_open == true)
                    $("#product_options_modal").modal("show");

                if (typeof cb !== 'undefined')
                    cb.apply(null, (typeof cb_param === 'undefined' ? [] : cb_param));
                $("#product_options_modal #next_btn").prop("disabled", false)
                $("#product_options_modal .op-title").removeClass("hidden")



            }

        }
    })
}
