var lookupBuilderGlobal =
{
    dictionary: {
        item: "مورد",
        search: "جستجو"
    }
}
jQuery.fn.extend({
    lookupBuilder: function (option) {
        var JsLookup = (function () {
            function jsLookup(target, parameters) {
                if (!parameters) {
                    parameters = {
                        isCheckComboBox: false
                    };
                }
                this.container = target;
                this.resetTime = null;
                this.changed = null;
                this.isCheckComboBox = this.container.hasClass("hasCheckbox");

                if (this.container.is("select")) {
                    var outerHtml = this.container[0].outerHTML.replace("<select", "<div").replace("</select>", "</div>");
                    var $element = $(outerHtml);
                    $element.append("<button class='lookup-button' data-toggle='dropdown' type='button'><span class='text'></span><span class='lookup-caret'></span></button>" +
                        "<div class='dropdown-menu' id='" + this.container.attr("id") + "_dropdown'>" +
                        "<input class='text-control' type='text' autocomplete='off' placeholder='" + lookupBuilderGlobal.dictionary.search + "...' />" +
                        "<ul></ul>" +
                        "<div class='lookup-status'><span class='record-count'></span>" + lookupBuilderGlobal.dictionary.item + "</div>" +
                        "</div>");
                    $("#" + this.container.attr("id"))[0].outerHTML = $element[0].outerHTML;
                    this.container = $("#" + this.container.attr("id"));
                }
                this.rebind();
            }

            jsLookup.prototype.rebind = function () {
                var that = this;
                this.container.off("keyup click shown.bs.dropdown");
                this.container.find("input[type='text']").off("click keyup");
                this.container.find(".text").off("change");
                this.container.on("keyup", function (event) {
                    if (event.keyCode === 13 || event.keyCode === 40)
                        $(this).find(".lookup-button").trigger("click");
                });
                this.container.on("show.bs.dropdown", async function () {
                    var input = $(this).find("input[type='text']");
                    const $dropdown = $(this).children(".dropdown-menu");
                    if ($(this).attr("data-online") === "true") {
                        if (eval("typeof getEventLookupCombo") === "function") {
                            $dropdown.find(".loading").show();
                            await getEventLookupCombo($(this), input.val(), that.getSelectedValue());
                        }
                    }
                    setTimeout(function () { input.focus(); }, 10);
                    const dropdownHeight = $dropdown.height() + 14;
                    const containerOffsetTop = $(this).offset().top;
                    const spaceUp = (containerOffsetTop - dropdownHeight) - $(window).scrollTop();
                    const spaceDown = $(window).scrollTop() + $(window).height() - (containerOffsetTop + $(this).height() + dropdownHeight);
                    if (spaceDown < 0 && (spaceUp >= 0 || spaceUp > spaceDown)) {
                        if (spaceUp < 0)
                            $dropdown.find("ul").css({ "max-height": (dropdownHeight + spaceUp - 68) + "px" });
                        $(this).addClass("dropup");
                    } else {
                        if (spaceDown < 0)
                            $dropdown.find("ul").css({ "max-height": (dropdownHeight + spaceDown - 68) + "px" });
                    }
                }).on("hidden.bs.dropdown", ".dropdown", function () {
                    $(this).removeClass("dropup");
                });
                this.container.find("input[type='text']").on("click", function (event) { event.stopPropagation(); }).on("keyup", function (event) {
                    var up = event.keyCode === 38;
                    var down = event.keyCode === 40;
                    var value = $(this).val();
                    var menuItems = that.container.find("li:not([hidden])");
                    var button = that.container.find(".lookup-button");
                    var isOnline = that.container.attr("data-online") === "true";


                    var $liActive = menuItems.filter(".active");
                    if (event.keyCode >= 37 && event.keyCode <= 40) {
                        if (menuItems.length === 0)
                            return;
                        if (down) {
                            if ($liActive.length === 0) {
                                $(menuItems[0]).addClass("active");
                                that.setScrollToActive();
                            } else if (menuItems.index($liActive) < menuItems.length - 1) {
                                $liActive.removeClass("active");
                                $liActive.next().addClass("active");
                                that.setScrollToActive();
                            }
                        } else if (up) {
                            if (menuItems.index($liActive) > 0 && !$liActive.prev().hasClass("loading")) {
                                $liActive.removeClass("active");
                                $liActive.prev().addClass("active");
                                that.setScrollToActive();
                            }
                        }
                    }
                    else if (event.keyCode === 13) {
                        if ($liActive.length === 1) {
                            $liActive.trigger("click");
                        }
                    }
                    else if (event.keyCode === 27) {
                        that.setSelectedValue(that.getSelectedValue());
                        button.trigger("click");
                        event.stopPropagation();
                        setTimeout(function () { that.container.focus(); }, 10);
                        return;
                    }
                    else if (isOnline) {
                        $liActive.removeClass("active");
                        if (that.resetTime) {
                            clearTimeout(that.resetTime);
                        }
                        that.resetTime = setTimeout(async function () {
                            if (eval("typeof getEventLookupCombo") === "function") {
                                that.container.find(".loading").show();
                                await getEventLookupCombo(that.container, value);
                            }
                        }, 1000);

                    }
                    else {

                        $liActive.removeClass("active");
                        that.container.find("ul li").each(function () {
                            if ($(this).html().includes(value)) {
                                $(this).removeAttr("hidden");
                            } else
                                $(this).attr("hidden", "hidden");
                        });

                        that.container.find(".lookup-count").text(that.container.find("li:not([hidden])").length);
                        //that.container.find(".text").text(that.container.find("li.active").text());
                    }
                    event.stopPropagation();
                });
                this.container.on("click", "li", function (event) {
                    if ($(this).find(".checkbox-control").length > 0) {
                        event.stopPropagation();
                        return;
                    }
                    that.setSelectedValue($(this).attr("data-code"));
                    setTimeout(function () { that.container.focus(); }, 10);

                });

                this.container.on("change", ".checkbox-control", async function () {
                    var resultCode = "";
                    var resultText = "";
                    that.container.find("ul li .checkbox-control:checked").each(function (index, item) {
                        resultCode += (resultCode !== "" ? "," : "") + $(item).closest("li").attr("data-code");
                        resultText += (resultText !== "" ? "," : "") + $(item).closest("li").text();
                    });
                    that.container.attr("data-value", resultCode);
                    that.container.find(".text").text(resultText);
                    if (that.changed)
                        await that.changed(that);
                    if (that.container.attr("onselected"))
                        eval("(async () => {" + that.container.attr("onselected") + "('" + that.container.attr("id") + "')" + "})()");
                });
            };
            jsLookup.prototype.bindData = function (dataSet) {
                var defaultValue = this.container.attr("data-value");
                var textWithCode = this.container.attr("data-lookup") === "true";
                var items = [];
                var texts = "";
                var codes = "";
                if (!this.isCheckComboBox && this.container.attr("data-required") !== "true")
                    items.push("<li data-code=''>" + window.top.noneSelected + "</li>");

                for (var i = 0; i < dataSet.length; i++) {
                    var code = dataSet[i]["Code"];
                    var name = convertArabicToPersian(dataSet[i]["Name"] || "");
                    var activeItem = false;
                    if (defaultValue) {
                        if (defaultValue.toString().toLowerCase().split(",").includes(code.toString().toLowerCase())) {
                            activeItem = true;
                            texts += (texts.length > 0 ? "," : "") + name;
                            codes += (codes.length > 0 ? "," : "") + code;
                        }
                    }
                    if (this.isCheckComboBox)
                        items.push("<li data-code='" + code + "' ><input type='checkbox' class='checkbox-control' " + (activeItem ? " checked='checked'" : "") + " />" + (textWithCode ? code + " " : "") + name + "</li>");
                    else
                        items.push("<li data-code='" + code + "' " + (activeItem ? "class='active'" : "") + ">" + (textWithCode ? code + " " : "") + name + "</li>");
                }
                if (this.container.find(".text").text() === "")
                    this.container.find(".text").text(texts);
                var $dropdown = $("#" + this.container.attr("id") + "_dropdown");
                if ($dropdown.length === 0) {
                    showMsgModal(0, "not found menu item :" + this.container.attr("id") + "_dropdown");
                    return;
                }
                $dropdown.find("ul li:not('.loading')").remove();
                $dropdown.find("ul").append(items.join(""));
                if (dataSet.length > 0)
                    $dropdown.find(".record-count").text(dataSet[0]["__RC"] ? dataSet[0]["__RC"] : dataSet.length);
                else
                    $dropdown.find(".record-count").text("0");
                $dropdown.find(".loading").hide();
            };
            jsLookup.prototype.getSelectedValue = function () {
                return this.container.attr("data-value");
            };
            jsLookup.prototype.getSelectedText = function () {
                return this.container.find(".text").text();
            };
            jsLookup.prototype.setSelectedValue = async function (selectedValue) {
                this.container.find("input[type='text']").val("");
                this.container.find("li.active").removeClass("active");
                this.container.find("li").removeAttr("hidden");

                this.container.find("li[data-code='" + selectedValue + "']").addClass("active");
                this.container.find(".text").text(this.container.find("li.active").text());
                this.setScrollToActive();

                var oldValue = this.container.attr("data-value") ? this.container.attr("data-value") : "";

                if (selectedValue === "") {
                    this.container.attr("data-value", "");
                    this.container.find(".text").text("");
                }
                else {
                    var result = this.getLookupText(selectedValue);
                    if (!result.text) {
                        await getEventLookupCombo(this.container, "", selectedValue);
                        result = this.getLookupText(selectedValue);
                    }
                    this.container.attr("data-value", result.value);
                    this.container.find(".text").text(result.text);
                    selectedValue = result.value;
                }
                if (oldValue !== selectedValue) {
                    if (this.changed)
                        await this.changed(this);
                    if (this.container.attr("onselected"))
                        eval("(async () => {" + this.container.attr("onselected") + "('" + this.container.attr("id") + "')" + "})()");
                }
            };
            jsLookup.prototype.setScrollToActive = function () {
                var $ul = this.container.find("ul");
                var $liActive = $ul.find("li.active");
                $ul.scrollTop(0);
                if ($liActive.length > 0)
                    $ul.scrollTop($liActive.offset().top - $ul.offset().top - $ul.height());
            };
            jsLookup.prototype.setEnabled = function (state) {
                this.container.find(".lookup-button").prop("disabled", !state);
            };
            jsLookup.prototype.clearItems = function () {
                this.container.attr("data-value", "");
                this.container.find(".text").text("");
                var $dropdown = $("#" + this.container.attr("id") + "_dropdown");
                $dropdown.find("ul li:not('.loading')").remove();
                $dropdown.find(".record-count").text("0");
            };
            jsLookup.prototype.addItem = function (name, code) {
                var $dropdown = $("#" + this.container.attr("id") + "_dropdown");
                $dropdown.push("<li data-code='" + code + "' >" + name + "</li>");
            };
            jsLookup.prototype.getLookupText = function (value) {
                var texts = "", values = "";
                if (!value)
                    value = "";
                var $lookup = this.container;
                var valueArr = [];
                if (value.toString().indexOf(",") > 0) {
                    valueArr = value.split(",");
                } else
                    valueArr.push(value.toString());
                valueArr.forEach(function (item) {
                    var $li = $lookup.find("li[data-code='" + item + "']");
                    if ($li.length === 0) {
                        $lookup.find("li:not('.loading')").each(function (index, li) {
                            if ($(li).attr("data-code").split("|")[0] === item)
                                $li = $(li);
                        });
                    }
                    if ($li.length === 1) {
                        texts += (texts !== "" ? "," : "") + $li.text();
                        values += (values !== "" ? "," : "") + $li.attr("data-code");
                        if ($li.find(".checkbox-control").length > 0)
                            $li.find(".checkbox-control").prop("checked", true);
                        else
                            $li.addClass("active");
                    }

                });
                return { value: values, text: texts };
            };
            jsLookup.prototype.onChanged = function (callback) {
                this.changed = callback;
            };
            return jsLookup;
        })();
        if (window[$(this).attr("id") + "Builder"])
            return window[$(this).attr("id") + "Builder"];
        window[$(this).attr("id") + "Builder"] = new JsLookup(this, option);
        return window[$(this).attr("id") + "Builder"];
    }
});
