const optionsMenuWidth = 150;
const isWindows = navigator.appVersion.indexOf("Win") != -1;
var isMouseHold = false;
var clickTimer;

jOmnis.callbackObject = {
    tabBar: null,
    tabs: null,
    omnisOnLoad: function() {
        this.tabBar = document.getElementById("tab-bar");
        this.tabs = [];
    },
    omnisSetData: function(tabs) {
        const idColumn          = 1;
        const descriptionColumn = 2;
        const iconColumn        = 3;
        const selectedColumn    = 4;
        const disabledColumn    = 5;
        const explodedColumn    = 6;
        const hiddenColumn      = 7;

        this.tabBar.innerHTML = "";
        this.tabs = [];

        if (tabs instanceof omnis_list) {
            for (var i = 0; i < tabs.getRowCount(); i++) {
                if (!(tabs.getData(explodedColumn, i + 1)|tabs.getData(hiddenColumn, i + 1)|tabs.getData(disabledColumn, i + 1))) {
                    this.tabs.push({
                        id:          tabs.getData(idColumn, i + 1),
                        description: tabs.getData(descriptionColumn, i + 1),
                        icon:        tabs.getData(iconColumn, i + 1),
                        selected:    tabs.getData(selectedColumn, i + 1)
                    });
                }
            }

            this.loadTabBar();
        }
    },
    omnisGetCurrentLine: function() {
        return document.getElementById(this.tabs.find(x => x.selected)["id"]).omnisLine;
    },
    loadTabBar: function() {
        for (var i = 0; i < this.tabs.length; i++) {
            var tab = document.createElement("LI");
            tab.omnisLine = i + 1;
            tab.id = this.tabs[i]["id"];
            tab.className = "tab";
            tab.disabled = this.tabs[i]["disabled"];
            tab.onclick = function() {
                if (!this.disabled) jOmnis.callbackObject.openTab(this)
            };

            var description = '<div class="description">' 

            tab.innerHTML += "<div class='padding'>&nbsp;</div>"
            tab.innerHTML += this.tabs[i]["icon"].length > 0 ? `<img src='../../iconsets/suran/${this.tabs[i]["icon"]}'>` : "";
            tab.innerHTML += description +
            this.tabs[i]["description"] + `</div>
            <div class='options' onclick='jOmnis.callbackObject.optionsClicked(this.parentElement)'>⋮</div>`;

            this.tabBar.appendChild(tab);
            if (this.tabs[i]["selected"]) this.highlightSelectedTab(this.tabs[i]["id"]);
        }
    },
    openTab: function(tab) {
        var previousTab = this.tabs.find(x => x.selected);
        if (previousTab.id != tab.id) {
            previousTab["selected"] = false;

            document.getElementById(previousTab["id"]).style.background   = isWindows ? "#f0f0f0" : "#e2e2e2";
            document.getElementById(previousTab["id"]).style.borderBottom = isWindows ? "1px solid #f0f0f0" : "1px solid #cfcfcf";
            this.highlightSelectedTab(tab.id);

            jOmnis.sendClickEvent(this.omnisGetCurrentLine());
        }
    },
    highlightSelectedTab: function(tabID) {
        this.tabs.find(x => x.id == tabID)["selected"] = true;

        document.getElementById(tabID).style.backgroundColor = isWindows ? "#ffffff" : "#ececec";
        document.getElementById(tabID).style.borderBottom    = isWindows ? "1px solid #ffffff" : "1px solid #ececec";
    },
    optionsClicked: function(tab) {
        if (!tab.disabled) this.openTab(tab);

        jOmnis.sendControlEvent({
            "Description": "options",
            "Left": jOmnis.callbackObject.getLeft(tab),
            "Tab_ID": tab.id
        });
    },
    getLeft: function(tab) {
        if (tab.offsetLeft + tab.clientWidth - this.tabBar.scrollLeft - optionsMenuWidth < 0) {
            if (tab.getBoundingClientRect().left < 0) return optionsMenuWidth - (isWindows ? 8 : 0);
            return tab.offsetLeft + optionsMenuWidth - this.tabBar.scrollLeft - (isWindows ? 8 : 0);
        }
        return tab.offsetLeft + tab.clientWidth - this.tabBar.scrollLeft - (isWindows ? 7 : 0);
    },
    getSequence: function() {
        var tabsInOrder = [];
        var tabElements = this.tabBar.getElementsByTagName("li");
        for (var i = 0; i < tabElements.length; i++) {
            tabElements[i].omnisLine = i + 1;
            tabsInOrder.push(tabElements[i].id);
        }

        return tabsInOrder.toString();        
    },
    toggleNavButtons: function(windowWidth) {
        var tabBarWidth = 0;
        $(".tab").each(function(index) {
            tabBarWidth += parseInt($(this).outerWidth(), 10);
        });

        if(tabBarWidth > windowWidth) {
            this.tabBar.style.width = "calc(100% - 60px)";
            this.tabBar.style.marginLeft = "30px";
            document.getElementById("left").style.display = "inline-block";
            document.getElementById("right").style.display = "inline-block";
        } else {
            this.tabBar.style.width = "100%";
            this.tabBar.style.marginLeft = "0";
            document.getElementById("left").style.display = "none";
            document.getElementById("right").style.display = "none";
        }
    },
    findSelectedTab: function() {
        var selectedTabPosition = 0;
        var selectedTabIndex = this.tabs.findIndex(x => x.selected);

        for (var i = 0; i < selectedTabIndex; i++) selectedTabPosition += document.getElementById(this.tabs[i].id).offsetWidth;
        return selectedTabPosition;
    }
};

$( function () {
    $( "#tab-bar" ).sortable({
        axis: "x",
        containment: "window",
        update: function(event, ui) {
            jOmnis.sendControlEvent({
                "Description": "rearrange",
                "Order": jOmnis.callbackObject.getSequence()
            });
        }
    });
    $( "#tab-bar" ).disableSelection();
} );

$("#left").on({
    "mousedown touchstart": function() {
        clickTimer = setTimeout(() => {
            isMouseHold = true;
        }, 200);

        var totalTabsWidth = 0;
        $(".tab").each(function(index) {
            totalTabsWidth -= parseInt($(this).outerWidth(), 10);
        });
        $("#tab-bar").animate({scrollLeft: totalTabsWidth/2}, 3000); // This setup has the most consistently matching speed
    },
    "mouseup touchend": function() {
        clearTimeout(clickTimer);
        $("#tab-bar").stop(true);
    },
    "click": function() {
        if (isMouseHold) {
            isMouseHold = false;
            return;
        }
        if (event.shiftKey){
            $("#tab-bar").animate({scrollLeft: jOmnis.callbackObject.findSelectedTab()}, 250);
        } else {
            $("#tab-bar").animate({scrollLeft: $("#tab-bar").scrollLeft() - 100}, 250);
        }
        isMouseHold = false;
    }
});

$("#right").on({
    "mousedown touchstart": function() {
        clickTimer = setTimeout(() => {
            isMouseHold = true;
        }, 200);

        var totalTabsWidth = 0;
        $(".tab").each(function(index) {
            totalTabsWidth += parseInt($(this).outerWidth(), 10);
        });
        $("#tab-bar").animate({scrollLeft: totalTabsWidth}, 3000);
    },
    "mouseup touchend": function() {
        clearTimeout(clickTimer);
        $("#tab-bar").stop(true);
    },
    "click": function(event) {
        if (isMouseHold) {
            isMouseHold = false;
            return;
        }
        if (event.shiftKey){
            $("#tab-bar").animate({scrollLeft: jOmnis.callbackObject.findSelectedTab()}, 250);
        } else {
            $("#tab-bar").animate({scrollLeft: $("#tab-bar").scrollLeft() + 100}, 250);
        }
        isMouseHold = false;
    }
});
