// Не редактировать!
var vertical_top_bottom_bar = {
    get Serv() {
        delete this.Serv;
        if ("Services" in window)
            return this.Serv = window.Services;
        return this.Serv = Components.utils.import("resource://gre/modules/Services.jsm", {}).Services;
    },
    get Prefs() {
        delete this.Prefs;
        return this.Prefs = this.Serv.prefs.getBranch("extensions.user_chrome_files.");
    },
    navtoolbox: null,
    verticalbox: null,
    verticalbar: null,
    browserNode: null,
    sidebarbox: null,
    topbar: null,
    bottombar: null,
    timer: null,
    timerImg: null,
    observerthemeenable: false,
    panelcontainer: null,
    showTimer: null,
    hideTimer: null,
    _visible: false,
    isPopupOpen: false,
    isMouseOver: false,
    options: {
        t_enable: true,
        b_enable: true,
        v_enable: true,
        t_collapsed: false,
        b_collapsed: false,
        v_collapsed: false,
        v_bar_start: true,
        v_autohide: false,
        v_fullscreen: true,
        v_showdelay: 300,
        v_hidedelay: 2000
    },
    observe: function(aEngine, aTopic, aVerb) {
        if (aTopic == "lightweight-theme-styling-update")
            this._setImagebar();
    },
    constructor: function() {
        var navtoolbox = this.navtoolbox = (window.gNavToolbox || document.querySelector("#navigator-toolbox"));
        if (!navtoolbox) return;
        var options = this.options;
        var knsxul = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

        if (options.t_enable) {
            var topbar = document.createElementNS(knsxul, "toolbar");
            var navbar = navtoolbox.querySelector("#nav-bar");
            topbar.id = "add-additional-top-bar";
            topbar.className = "toolbar-primary chromeclass-toolbar customization-target browser-toolbar";
            topbar.setAttribute("toolbarname", "Дополнительная панель");
            topbar.setAttribute("context", "toolbar-context-menu");
            topbar.setAttribute("mode", "icons");
            topbar.setAttribute("iconsize", "small");
            topbar.setAttribute("fullscreentoolbar", true);
            topbar.setAttribute("customizable", true);
            topbar.setAttribute("collapsed", options.t_collapsed);
            navtoolbox.insertBefore(topbar, navbar.nextSibling);
            this.topbar = topbar;
        }

        if (!options.v_enable && !options.b_enable) return;

        if (options.v_enable) {
            var vcontainer = document.createElementNS(knsxul, "vbox");
            vcontainer.id = "add-additional-vertical-container";
            vcontainer.setAttribute("vertautohide", options.v_autohide);
            vcontainer.setAttribute("verticalbarstart", options.v_bar_start);
            var verticalbox = document.createElementNS(knsxul, "vbox");
            verticalbox.id = "add-additional-vertical-box";
            verticalbox.setAttribute("vertautohide", options.v_autohide);
            verticalbox.setAttribute("verticalbarstart", options.v_bar_start);
            verticalbox.setAttribute("flex", "1");
            var verticalbar = document.createElementNS(knsxul, "toolbar");
            var v_startend, v_startendnext;
            if (options.v_bar_start) {
                v_startend = document.querySelector("#browser-border-start");
                v_startendnext = v_startend.nextSibling;
            } else {
                v_startend = document.querySelector("#browser-border-end");
                v_startendnext = v_startend;
            }
            verticalbar.id = "add-additional-vertical-bar";
            verticalbar.className = "toolbar-primary chromeclass-toolbar customization-target browser-toolbar";
            verticalbar.setAttribute("toolbarname", "Вертикальная панель");
            verticalbar.setAttribute("toolboxid", "navigator-toolbox");
            verticalbar.setAttribute("context", "toolbar-context-menu");
            verticalbar.setAttribute("mode", "icons");
            verticalbar.setAttribute("iconsize", "small");
            verticalbar.setAttribute("orient", "vertical");
            verticalbar.setAttribute("flex", "1");
            verticalbar.setAttribute("fullscreentoolbar", options.v_fullscreen);
            verticalbar.setAttribute("customizable", true);
            verticalbar.setAttribute("collapsed", options.v_collapsed);
            verticalbox.appendChild(verticalbar);
            vcontainer.appendChild(verticalbox);
            var browserNode = this.browserNode = v_startend.parentNode;
            browserNode.insertBefore(vcontainer, v_startendnext);
            this.verticalbar = verticalbar;
            this.verticalbox = verticalbox;

            if (options.v_autohide) {
                window.addEventListener("load", this, false);
                try {
                    this.Serv.obs.addObserver(this, "lightweight-theme-styling-update", false);
                    this.observerthemeenable = true;
                    this.setImagebar();
                } catch(e) {}
            }
            navtoolbox.addEventListener("beforecustomization", this, false);
        }

        if (options.b_enable) {
            var bottombar = document.createElementNS(knsxul, "toolbar");
            bottombar.id = "add-additional-bottom-bar";
            bottombar.className = "toolbar-primary chromeclass-toolbar customization-target browser-toolbar";
            bottombar.setAttribute("toolbarname", "Нижняя панель");
            bottombar.setAttribute("toolboxid", "navigator-toolbox");
            bottombar.setAttribute("context", "toolbar-context-menu");
            bottombar.setAttribute("mode", "icons");
            bottombar.setAttribute("iconsize", "small");
            bottombar.setAttribute("customizable", true);
            bottombar.setAttribute("collapsed", options.b_collapsed);
            var closebutton = document.createElementNS(knsxul, "toolbarbutton");
            closebutton.id = "add-additional-bottom-closebutton";
            closebutton.className = "close-icon closebutton";
            closebutton.setAttribute("tooltiptext", "Скрыть панель");
            closebutton.setAttribute("removable", false);
            closebutton.setAttribute("oncommand", "var bar = this.parentNode; setToolbarVisibility(bar, bar.collapsed);");
            bottombar.appendChild(closebutton);
            document.querySelector("#browser-bottombox").appendChild(bottombar);
            this.bottombar = bottombar;
        }
        window.addEventListener("toolbarvisibilitychange", this, false);

        var toolbarsid = [];
        if (options.v_enable)
            toolbarsid.push("add-additional-vertical-bar");
        if (options.b_enable)
            toolbarsid.push("add-additional-bottom-bar");
        if (!toolbarsid.length)
            return;
        setTimeout(function() {
            if ("getTogglableToolbars" in window) return;
            var ViewToolbarsPopup = window.onViewToolbarsPopupShowing;
            if (typeof ViewToolbarsPopup != "function") return;
            var StringFn = ViewToolbarsPopup.toString();
            var RegRep = /toolbarNodes\s*=\s*gNavToolbox\s*\.\s*(childNodes|children|querySelectorAll\s*\(\s*(\"|\')\s*toolbar\s*(\"|\')\s*\))/g;
            if (!RegRep.test(StringFn)) return;
            StringFn = "window.onViewToolbarsPopupShowing = " + StringFn.replace(RegRep, `toolbarNodes = Array.from(gNavToolbox.querySelectorAll("toolbar:not(#add-additional-vertical-bar)")).concat(${toolbarsid.toSource()}.map(id => document.querySelector("#" + id)).filter(id => id !== null))`);
            eval(StringFn);
        }, 200);
    },
    destructor: function() {
        window.removeEventListener("toolbarvisibilitychange", this, false);
        var options = this.options;
        if (options.v_enable) {
            this.navtoolbox.removeEventListener("beforecustomization", this, false);
            if (options.v_autohide) {
                if (this.observerthemeenable) {
                    try {
                        this.Serv.obs.removeObserver(this, "lightweight-theme-styling-update");
                    } catch(e) {}
                }
                var verticalbox = this.verticalbox;
                verticalbox.removeEventListener("mouseenter", this, false);
                verticalbox.removeEventListener("mouseleave", this, false);
                verticalbox.removeEventListener("dragenter", this, false);
            }
        }
    },
    handleEvent: function(event) {
        this[event.type](event);
    },
    load: function() {
        window.removeEventListener("load", this, false);
        window.addEventListener("MozAfterPaint", this, false);
        this.setImagebar();
        var panelcontainer = this.panelcontainer = gBrowser.mPanelContainer || gBrowser.tabpanels;
        var sidebarbox = this.sidebarbox = this.browserNode.querySelector("#sidebar-box");
        if (!panelcontainer || !sidebarbox) return;
        var verticalbox = this.verticalbox;
        verticalbox.addEventListener("mouseenter", this, false);
        verticalbox.addEventListener("mouseleave", this, false);
        verticalbox.addEventListener("dragenter", this, false);
    },
    MozAfterPaint: function() {
        window.removeEventListener("MozAfterPaint", this, false);
        this.setImagebar();
    },
    toolbarvisibilitychange: function(event) {
        if (event.target == this.verticalbar) {
            try {
                this.Prefs.setBoolPref("vertical_collapsed", this.verticalbar.collapsed);
            } catch(e) {}
        } else if (event.target == this.topbar) {
            try {
                this.Prefs.setBoolPref("top_collapsed", this.topbar.collapsed);
            } catch(e) {}
        } else if (event.target == this.bottombar) {
            try {
                this.Prefs.setBoolPref("bottom_collapsed", this.bottombar.collapsed);
            } catch(e) {}
        }
    },
    beforecustomization: function() {
        var toolbar = this.verticalbar;
        toolbar.removeAttribute("orient");
        this.verticalbar = this.navtoolbox.appendChild(toolbar);
        this.navtoolbox.addEventListener("aftercustomization", this, false);
    },
    aftercustomization: function() {
        var toolbar = this.verticalbar;
        toolbar.setAttribute("orient", "vertical");
        this.verticalbar = this.verticalbox.appendChild(toolbar);
        this.navtoolbox.removeEventListener("aftercustomization", this, false);
        this.setImagebar();
    },
    _setImagebar: function() {
        clearTimeout(this.timerImg);
        this.timerImg = setTimeout(() => {
            this.setImagebar();
        }, 500);
    },
    setImagebar: function() {
        if (!this.observerthemeenable) return;
        var docElm = document.documentElement;
        docElm.style.setProperty("--v-lwt-header-image", window.getComputedStyle(docElm).getPropertyValue("background-image"));
    },
    mouseenter: function(event) {
        if (!this._visible && event.currentTarget == this.verticalbox)
            this.showToolbar();
        else if (event.currentTarget == this.verticalbar)
            this.isMouseOver = true;
        else {
            this.isMouseOver = false;
            this.hideToolbar();
        }
    },
    dragenter: function() {
        if (!this._visible)
            this.showToolbar();
    },
    mouseleave: function() {
        clearTimeout(this.showTimer);
    },
    popupshown: function(event) {
        if (event.target.localName != "tooltip" && event.target.localName != "window")
            this.isPopupOpen = true;
    },
    popuphidden: function(event) {
        if (event.target.localName != "tooltip" && event.target.localName != "window") {
            this.isPopupOpen = false;
            this.hideToolbar();
        }
    },
    showToolbar: function() {
        clearTimeout(this.showTimer);
        this.showTimer = setTimeout(() => {
            this.verticalbox.setAttribute("auto-hide-toolbar-visible", true);
            this._visible = true;
            this.panelcontainer.addEventListener("mouseenter", this, false);
            this.sidebarbox.addEventListener("mouseenter", this, false);
            var verticalbar = this.verticalbar;
            verticalbar.addEventListener("mouseenter", this, false);
            verticalbar.addEventListener("popupshown", this, false);
            verticalbar.addEventListener("popuphidden", this, false);
            var navtoolbox = this.navtoolbox;
            navtoolbox.addEventListener("popupshown", this, false);
            navtoolbox.addEventListener("popuphidden", this, false);
        }, this.options.v_showdelay);
    },
    hideToolbar: function() {
        clearTimeout(this.hideTimer);
        this.hideTimer = setTimeout(() => {
            if (this.isPopupOpen || this.isMouseOver) return;
            this.panelcontainer.removeEventListener("mouseenter", this, false);
            this.sidebarbox.removeEventListener("mouseenter", this, false);
            var verticalbar = this.verticalbar;
            verticalbar.removeEventListener("mouseenter", this, false);
            verticalbar.removeEventListener("popupshown", this, false);
            verticalbar.removeEventListener("popuphidden", this, false);
            var navtoolbox = this.navtoolbox;
            navtoolbox.removeEventListener("popupshown", this, false);
            navtoolbox.removeEventListener("popuphidden", this, false);
            this.verticalbox.removeAttribute("auto-hide-toolbar-visible");
            this._visible = false;
        }, this.options.v_hidedelay);
    }
};
window.addEventListener("unload", function unload() {
    window.removeEventListener("unload", unload, false);
    vertical_top_bottom_bar.destructor();
}, false);
