(function() {
    var ns = MOA.ns('LM4');

    const Cu = Components.utils;
    const Ci = Components.interfaces;
    
    var jsm = { };
    if (typeof XPCOMUtils == "undefined") {    
        Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    }
    
    XPCOMUtils.defineLazyGetter(jsm, "utils", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/utils.jsm", obj);
        return obj.utils;
    });
    
    XPCOMUtils.defineLazyGetter(jsm, "AppCenter", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/appcenter.jsm", obj);
        return obj.AppCenter;
    });
    
    XPCOMUtils.defineLazyGetter(jsm, "AppCenterDAO", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/dao.jsm", obj);
        return obj.AppCenterDAO;
    });
    
    XPCOMUtils.defineLazyGetter(jsm, "Tracker", function() {
        let obj = { };
        Cu["import"]("resource://livemargins/track.jsm", obj);
        return obj.Tracker;
    });

    XPCOMUtils.defineLazyGetter(jsm, "windowMediator", function() {
        return Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
    });                        
    
    XPCOMUtils.defineLazyGetter(jsm, "logger", function() {
        return new jsm.utils.logger("LM4.Overlay");
    });

    function getPref(name, defValue) {
        return jsm.utils.getPref(name, defValue);
    }

    function setPref(name, value) {
        jsm.utils.setPref(name, value);
    }

    function closeAllAppWindow() {
        var appEnumerator = jsm.windowMediator.getEnumerator("mozilla:favpart_widget");
        while (appEnumerator.hasMoreElements()) {
            var appWindow = appEnumerator.getNext();
            // Mark app as auto_start
            jsm.AppCenterDAO.setAppAutoStart(appWindow.widget.args.id, true);
            appWindow.close();
        }
    }

    function checkQuit() {
        if (!getPref("closewithfirefox", false)) {
            jsm.logger.trace("Do not close all apps with firefox.");
            return;
        }

        var enumerator = jsm.windowMediator.getEnumerator("navigator:browser");
        if (enumerator.hasMoreElements()) {
            jsm.logger.trace("Still have browser windows.");
            return;
        }

        var appEnumerator = jsm.windowMediator.getEnumerator("mozilla:favpart_widget");
        if (appEnumerator.hasMoreElements()) {
            if (!getPref("nocloseconfirm", false)) {
                jsm.logger.trace("There are apps windows still open.");
                var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);

                var check = {
                    value: false
                };

                var stringBundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
                        .getService(Components.interfaces.nsIStringBundleService)
                        .createBundle("chrome://livemargins/locale/livemargins.properties");

                var button = prompts.confirmCheck(null,
                      stringBundle.GetStringFromName("confirm.title"),
                      stringBundle.GetStringFromName("confirm.content"),
                      stringBundle.GetStringFromName("confirm.check"),
                      check);

                if (check.value == true) {
                    setPref("nocloseconfirm", true);
                    setPref("closewithfirefox", button == 1);
                }

                //whether close the window or not
                if (button == 1){
                    closeAllAppWindow();
                }
            } else {
                closeAllAppWindow();
            }
        }
    };

    // Copy from Firefox4
    if (!window["switchToTabHavingURI"]) {
        window["isTabEmpty"] = function (aTab) {
            var browser = aTab.linkedBrowser;
            return  browser.sessionHistory.count < 2 &&
                    browser.currentURI.spec == "about:blank" &&
                    !browser.contentDocument.body.hasChildNodes() &&
                    !aTab.hasAttribute("busy");
        }

        window["switchToTabHavingURI"] = function(aURI, aOpenNew) {
            function switchIfURIInWindow(aWindow) {
                var browsers = aWindow.gBrowser.browsers;
                for (var i = 0; i < browsers.length; i++) {
                    var browser = browsers[i];
                    if (browser.currentURI.equals(aURI)) {
                        aWindow.focus();
                        aWindow.gBrowser.tabContainer.selectedIndex = i;
                        return true;
                    }
                }
                return false;
            }

            if (!(aURI instanceof Ci.nsIURI)) {
                var ioServices = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);
                aURI = ioServices.newURI(aURI, null, null);
            }

            var isBrowserWindow = !!window.gBrowser;
            if (isBrowserWindow && switchIfURIInWindow(window)) {
                return true;
            }

            var winEnum = jsm.windowMediator.getEnumerator("navigator:browser");
            while (winEnum.hasMoreElements()) {
                var browserWin = winEnum.getNext();
                if (browserWin.closed || browserWin == window) {
                    continue;
                }
                if (switchIfURIInWindow(browserWin)) {
                    return true;
                }
            }

            if (aOpenNew) {
                if (isBrowserWindow && isTabEmpty(gBrowser.selectedTab)) {
                    gBrowser.selectedBrowser.loadURI(aURI.spec);
                } else {
                    openUILinkIn(aURI.spec, "tab");
                }
            }

            return false;
        }
    }

    ns.onAppMenushowing = function(menu, event) {
        // Empty all menuitem.
        while (menu.childNodes.length > 0) {
            menu.removeChild(menu.childNodes[0]);
        }

        // Show the first 10 apps in bookmark.
        var apps = jsm.AppCenterDAO.getBookmarkedApps(0, 10);
        for (var i = 0; i < apps.length; i++ ) {
            var app = apps[i];
            var menuItem = document.createElement("menuitem");
            menuItem.appuid = app.uid;
            menuItem.setAttribute("label", app.name);
            menuItem.setAttribute("tooltiptext", app.name);
            menuItem.setAttribute("class", "menuitem-iconic menuitem-app");
            menuItem.setAttribute("image", jsm.AppCenter.getAppSmallIcon(app));
            menuItem.addEventListener("command", function(event) {
                jsm.AppCenter.openApp(this.appuid);
                event.stopPropagation();
            }, false);
            menu.appendChild(menuItem);
        }

        // add menu item to open app bookmarks
        var menuItem = document.createElement("menuitem");
        menuItem.setAttribute("class", "menuitem-iconic menuitem-app");
        // menuItem.setAttribute("image", "chrome://livemargins/skin/images/icons/bookmark.png");
        menuItem.setAttribute("label", document.getElementById("livemarginsStrings").getString("menuitem.showappbookmarks"));
        menuItem.setAttribute("style", "max-width: 160px;");
        menu.appendChild(menuItem);
        menuItem.addEventListener("command", function(event) {
            // switch view to apps bookmark
            jsm.utils.setPref("tabview", "tab-local");
            jsm.AppCenter.appPref.updatePref("showbookmarks", "");
        }, false);
    };

    function checkAppcenterFirstRun() {
        if (getPref("appcenter.firstRun", false)) {
            setPref("appcenter.firstRun", false);
            if (isTabEmpty(gBrowser.selectedTab)) {
                gBrowser.selectedBrowser.loadURI("about:appcenter");
            } else {
                gBrowser.loadOneTab("about:appcenter", {inBackground: true});
            }
        }
    }

    window.addEventListener('unload', function() {
        checkQuit();
        window.removeEventListener("load", arguments.callee, false);
    }, false);

    window.addEventListener("load", function() {
        window.setTimeout(function() {
            jsm.AppCenter.checkAutoStart();
            checkAppcenterFirstRun();
            document.addEventListener("click", function(event) {
                id = event.originalTarget.id;
                if (id == "favpart-button" || id == "appcenter-button") {
                    jsm.Tracker.track(jsm.Tracker.click.type, jsm.Tracker.click.actions.CLICK_XUL_BTN, id);
                }
            }, false);
        }, 1000);
        window.removeEventListener("load", arguments.callee, false);
    }, false)
})();
