(function() {
    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;
    });
    
    var ns = MOA.ns('LM4.Monitor');
    
    var _originalPos = {
        x: 0,
        y: 0
    };
    var _browserPos = null;
    var _minWidth = 160;
    var _minHeight = 90;
    var _selectionBoxPos = {
        left: 0,
        top: 0,
        width: 0,
        height: 0 
    };
    var _notification = null;
    var _logger = jsm.utils.logger('LM4.monitor');
    var _isMoving = false;
    var _direction = null;
    var _isResizing = null;
    
    ns.init = function (ev ) {
        var mainWin = document.getElementById("appcontent");
        mainWin.addEventListener("DOMContentLoaded", this.injectPage, false);
        window.addEventListener("unload", function() {
            var mainWin = document.getElementById("appcontent"); 
            mainWin.removeEventListener("DOMContentLoaded", this.injectPage, false); 
            window.removeEventListener("unload", arguments.callee, false); 
        }, false);
        
        window.addEventListener("keydown", function() {
            var panel = document.getElementById("capture-panel");
            if (panel.state == "open"){
                panel.hidePopup();
            }
        }, false);
        
        window.addEventListener("click", function(event) {
            var panel = document.getElementById("capture-panel");
            var favButton = document.getElementById("favpart-button");
            var mainWin = document.getElementById("main-window");
            if (panel.state == "open" && event.target != favButton){
                var parNode = event.target;
                while (parNode != null){
                    if (parNode == panel) return;  // do nothing
                    parNode = parNode.parentNode;
                }
                panel.hidePopup();
            }
        }, false);

        //check whether user has manually removed the toolbar buttons
        var urlbar = document.getElementById("nav-bar");
        if (urlbar != null){
            urlbar.addEventListener("DOMAttrModified",function(event){
                if (event.type == "DOMAttrModified" && event.attrName == "currentset"){
                    if (event.newValue.indexOf("appcenter-button") == -1){
                        jsm.utils.setPref("manuallyRemovedAppcenterButton", true);
                    } else {
                        jsm.utils.setPref("manuallyRemovedAppcenterButton", false);
                    }
                    if (event.newValue.indexOf("favpart-button") == -1){
                        jsm.utils.setPref("manuallyRemovedFavpartButton", true);
                    } else {
                        jsm.utils.setPref("manuallyRemovedFavpartButton", false);
                    }
                }
            }, false);
        }
        //add LM3 toolbarbutton
        favpart_addToolbarButtons(false);
    };
        
    ns.showNotification = function (text) {
        try {
            var notificationBox = gBrowser.getNotificationBox();
            var priority = notificationBox.PRIORITY_INFO_HIGH;
            _notification = notificationBox.appendNotification(text, "livemargins-notification",
                                             "chrome://livemargins/skin/scissors.png",
                                             priority, []);
        } catch(e) {
            _logger.error("cpmanager: cpmanager_checkAddonUpdates: exception: " + e);
        }
    };
    
    ns.closeNotification = function (text) {
        if (_notification) {
            try {
                gBrowser.getNotificationBox().removeNotification(_notification);
            } catch(e) {
                _logger.info('the notification may have been manually dismissed')
            }
            _notification = null;
        }
    };
    
    ns.injectPage = function(ev) {
        try {
            if (! ev.originalTarget instanceof HTMLDocument) {
                return;
            }
            
            var view = ev.originalTarget.defaultView;
            if (view && view.top == view){
                // add for sina music
                var strDomains = jsm.utils.getPref("lminteractivesites","i.g-fox.cn,i.firefoxchina.cn");
                var domains = strDomains.split(",");
                var url = view.document.URL;
                for (var i = 0; i< domains.length; i++){
                    var domain = domains[i].replace(' ', '');
                    if (url.indexOf(domain) >= 0) {
                        view.wrappedJSObject.inlivemargin = true;
                        view.addEventListener("LM_PlayMusic", function(event) {
                            var songId = event.target.getAttribute("rel");
                            _logger.trace(songId);
                            jsm.AppCenter.dnd.playMusic(songId);
                            event.preventDefault();
                        }, true);
                        break;
                    }
                }
            }
        } catch (e){
            _logger.error(e);
        }
    };
    
    ns.printScreen = function() {
        var mainwin = document.getElementById("main-window");
        if (!mainwin.getAttribute("xmlns:html")) {
            mainwin.setAttribute("xmlns:html", "http://www.w3.org/1999/xhtml");
        }

        var content = window.content;
        var desth = content.innerHeight;
        var destw = content.innerWidth;

        // Unfortunately there is a limit:
        if (desth > 16384) {
            desth = 16384;
        }

        var canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "html:canvas");
        var ctx = canvas.getContext("2d");

        canvas.height = desth;
        canvas.width = destw;
        ctx.clearRect(0, 0, destw, desth);
        ctx.save();
        ctx.drawWindow(content, content.scrollX, content.scrollY, destw, desth, "rgb(255,255,255)");
    
        return canvas.toDataURL("image/png", "");
    };
    
    ns.capture = function (ev){
        _logger.trace('Start capturing.');
        var self = this;
        var panel = document.getElementById("capture-panel");
        
        if (panel.state == "open") {
            _logger.trace('Panel is already opened, hide it.');
            panel.hidePopup();
            return;
        }
        
        if (navigator.appVersion.indexOf("X11") != -1 || navigator.appVersion.indexOf("Linux")!= -1) {
            _logger.trace('In Linux, set interval to show background.');
            
            var bgImg = this.printScreen();
            panel.style.backgroundImage= "url('"+bgImg+"')";
            var scrollX = window.content.scrollX;
            var scrollY = window.content.scrollY;
            
            this.bkgndInterval = window.setInterval(function() {
                if (window.content.scrollX != scrollX || window.content.scrollY != scrollY){
                    scrollX = window.content.scrollX;
                    scrollY = window.content.scrollY;
                    var bgImg = self.printScreen();
                    panel.style.backgroundImage= "url('"+bgImg+"')";
                }
            }, 50);
            
            panel.addEventListener("popuphidden", function(){
                panel.removeEventListener("popuphidden",arguments.callee,true);
                window.clearInterval(this.bkgndInterval);
            }, true);
        }
        
        var browser = gBrowser.selectedBrowser;
        _logger.trace('box width: ' + browser.boxObject.width);
        _logger.trace('content width: ' + window.content.innerWidth);
        var doc = browser.contentDocument;
        _logger.trace('Doc with: ' + doc.width);

        _logger.trace('Check if error site.')
        var error_sites1 = jsm.utils.getPref("errorsitesone", "");
        var domains = error_sites1.split(",");
        
        if (!doc.URL) {
            _logger.trace("doc.URL is null.");
            return;
        }
        
        for (var i = 0; i < domains.length; i++){
            if (doc.URL.indexOf(domains[i]) >= 0){
                var strbundle = document.getElementById("livemarginsStrings");
                var errsite1 = strbundle.getString("notification.iframe1");
                this.showNotification(errsite1)
            }
        }
        var error_sites2 = jsm.utils.getPref("errorsitestwo","");
        domains = error_sites2.split(",");
        for (i = 0; i< domains.length; i++){
            if (doc.URL.indexOf(domains[i]) >= 0){
                strbundle = document.getElementById("livemarginsStrings");
                errsite2 = strbundle.getString("notification.iframe2");
                this.showNotification(errsite2)
            }
        }

        _logger.trace('Get capture-div and set with and height.')
        var div = document.getElementById("capture-div");
        var docWidth = doc.documentElement.clientWidth;
        if (docWidth > 0 && docWidth > browser.boxObject.width -50) {  //doc.width ==0 sometimes, and sometimes, doc.width does not equal to browser.width - scrollbar width
            div.width = browser.boxObject.width < docWidth?browser.boxObject.width : docWidth;
        } else {
            div.width = browser.boxObject.width;
        }
        div.height = browser.boxObject.height;
        
        _browserPos = {
            x: browser.boxObject.x,
            y: browser.boxObject.y,
            width: browser.boxObject.width,
            height: browser.boxObject.height
        };
        
        _logger.trace('Show web clipping panel.')
        panel.removeAttribute("hidden");
        var fullScreenLike = window.fullScreen || browser.boxObject.screenY + browser.boxObject.height + 2 >= window.screen.height;
        panel.setAttribute('level', fullScreenLike ? 'top' : '');
        panel.openPopup(browser, "overlap", 0, 0, false, true);
        
        _logger.trace('Show selection box.')
        var box = document.getElementById("selection-box");
        var control = document.getElementById("selectionbox-control-set");
        box.style.visibility = "visible";
        control.style.visibility = "hidden";
        
        _logger.trace('Add mouse related event to capture-div');
        //in case multiple handler is added
        div.removeEventListener("mousemove",resizingHandler,false);
        div.removeEventListener("mouseup",endResizeHandler,false);

        div.addEventListener("mousemove",guessSelectionHandler,false);
        div.addEventListener("mousedown",endDrawHandler,false);

        // deal with out of screen
        _logger.trace('Set interval to check if browser is out of screen.')
        panel.addEventListener("popuphidden", function(){
            panel.removeEventListener("popuphidden", arguments.callee, true);
            window.clearInterval(window.favpart_moveMonInterval);
            panel.setAttribute("hidden", true);
            _logger.trace('Clear out-of-screen checking interval.');
        }, true);
        
        window.favpart_moveMonInterval = window.setInterval(function() {
            if (browser.boxObject.screenX < 0 || 
                browser.boxObject.screenX + browser.boxObject.width > window.screen.width ||
                browser.boxObject.screenY < 0 || 
                browser.boxObject.screenY + browser.boxObject.height > window.screen.height) {
                _logger.trace('Browser is out of screen!');
                panel.hidePopup();
                var strbundle = document.getElementById("livemarginsStrings");
                var errstr = strbundle.getString("notification.keepbrowserinside");
                self.showNotification(errstr);
            }
        }, 300);
    };
    
    ns.endCapture = function(event) {
        var panel = document.getElementById("capture-panel");
        var box = document.getElementById("selection-box");
        var browser = window.getBrowser().selectedBrowser;
        var doc = browser.contentDocument;
        
        // -1 is for there is a +1 when show the box
        var boxTopInBrowser = box.boxObject.y - browser.boxObject.y - 1;
        var boxLeftInBrowser = box.boxObject.x - browser.boxObject.x - 1;
        var fullZoom = gBrowser.selectedBrowser.markupDocumentViewer.fullZoom;
        var pos = {
            x : boxLeftInBrowser / fullZoom + doc.defaultView.scrollX, 
            y : boxTopInBrowser / fullZoom + doc.defaultView.scrollY
        };
        
        // 1 and  5 are calculated
        var screenX = boxLeftInBrowser + window.screenX + 1;
        // var screenY = boxTopInBrowser + window.screenY + getBrowser().selectedBrowser.boxObject.y + 5;
        var screenY = event.screenY - (event.clientY - box.boxObject.y) - 29;
        
        // a scrollbar should not be more than 50px, document.documentElement.clientWidth could be 0 sometimes, so if it's 0 or wrong... use boxObject instead
        var browserWidth = (doc.documentElement.clientWidth == 0 || 
                                doc.documentElement.clientWidth > browser.boxObject.width || 
                                doc.documentElement.clientWidth < browser.boxObject.width -50) ? browser.boxObject.width : doc.documentElement.clientWidth;
        var browserHeight = (doc.documentElement.clientHeight == 0 || 
                                doc.documentElement.clientHeight > browser.boxObject.height || 
                                doc.documentElement.clientHeight < browser.boxObject.height -50) ? browser.boxObject.height : doc.documentElement.clientHeight;
        
        _logger.trace([browser.boxObject.width,document.documentElement.clientWidth,browserWidth,browserHeight]);
        
        var args = {
            name     : doc.title,
            location : doc.URL,
            docX     : pos.x,
            docY     : pos.y,
            screenX  : screenX,
            screenY  : screenY,
            width    : box.boxObject.width,
            height   : box.boxObject.height,
            browserWidth: browserWidth,
            browserHeight: browserHeight,
            zoom: fullZoom
        };
        _logger.trace(JSON.stringify(args));
        var appUID = jsm.AppCenter.addWebClipping(args);    
        _logger.trace(appUID + ' has been created, open it.');
        jsm.AppCenter.openApp(appUID);
        
        var box = document.getElementById("selection-box");
        //box.style.visibility = "hidden";
        this.closeNotification();
        panel.hidePopup();
    };
    
    ns.setSelectionBoxPos = function(left,top,width,height){
        var boxleft = document.getElementById("selection-box-left");
        var boxTop = document.getElementById("selection-box-top");
        var box = document.getElementById("selection-box");
        boxleft.width = left + 1;    //test shows that the left is 1px smaller than the real one
        boxTop.height = top;    //leave space for the box border
        box.width = width;
        box.height = height;
        _selectionBoxPos = {
            left : left,
            top : top,
            width : width,
            height : height
        };
    };
    
    ns.getSelectionFromPoint = function(x,y){
        var curDoc = getBrowser().selectedBrowser.contentDocument;
        var elem = curDoc.elementFromPoint(x,y);
        while (null != elem && elem.parentNode!= null && elem.parentNode != curDoc.documentElement){
            if (/*elem.tagName.match(/div|embed|iframe|img/i) && */elem.offsetWidth >= _minWidth && elem.offsetHeight >= _minHeight){
                return elem;
            }
            elem = elem.parentNode;
        }
        return null;
    };
        
    ns.guessSelection = function(ev){
        var mouseX = ev.clientX;
        var mouseY = ev.clientY;
        var x = mouseX - _browserPos.x;
        var y = mouseY - _browserPos.y;
        var fullZoom = gBrowser.selectedBrowser.markupDocumentViewer.fullZoom;

        var elem = this.getSelectionFromPoint(x/fullZoom,y/fullZoom);
        
        var box = document.getElementById("selection-box");
        if (elem == null){
            this.setSelectionBoxPos(x - _minWidth / 2, y-_minHeight / 2, _minWidth, _minHeight);
        } else {
            var browser = gBrowser.selectedBrowser;
            var pos = jsm.utils.getRectTRBLWH(elem,browser.contentWindow);
            var doc = getBrowser().selectedBrowser.contentDocument;
            var elemX = pos.left * fullZoom;
            var elemY = pos.top * fullZoom;
            var elemWidth = pos.width * fullZoom;
            var elemHeight = pos.height * fullZoom;
//            var elemX = (pos.x - doc.defaultView.scrollX)*fullZoom;
//            var elemY = (pos.y - doc.defaultView.scrollY)*fullZoom;
//            var elemWidth = elem.offsetWidth*fullZoom;
//            var elemHeight = elem.offsetHeight*fullZoom;
            
            if (elemX >= 0 && elemY >= 0 && 
                    elemX+elemWidth <= browser.boxObject.width + 1 && 
                    elemY+elemHeight <= browser.boxObject.height + 1){
                this.setSelectionBoxPos(elemX,elemY,elemWidth,elemHeight);
            } else {
                this.setSelectionBoxPos(x - _minWidth / 2, y - _minHeight / 2, _minWidth, _minHeight);
            }
        }
    }
    
    ns.startMove = function(ev){
        var mouseX = ev.clientX;
        var mouseY = ev.clientY;
        _originalPos.x = ev.clientX;
        _originalPos.y = ev.clientY;
        _isMoving = true;
        var div = document.getElementById("capture-div");
        div.addEventListener("mousemove",movingHandler,false);
        div.addEventListener("mouseup",endMoveHandler,false);
    };
    
    ns.moving = function(ev){
        var mouseX = ev.clientX;
        var mouseY = ev.clientY;
        var deltaX = mouseX - _originalPos.x;
        var deltaY = mouseY - _originalPos.y;
        _originalPos.x = ev.clientX;
        _originalPos.y = ev.clientY;
        this.setSelectionBoxPos(_selectionBoxPos.left + deltaX, _selectionBoxPos.top + deltaY,_selectionBoxPos.width,_selectionBoxPos.height);
    };
    
    ns.endMove = function(ev){
        var div = document.getElementById("capture-div");
        div.removeEventListener("mousemove",movingHandler,false);
        div.removeEventListener("mouseup",endMoveHandler,false);
    };

    ns.startResize = function(ev,direction){
        var mouseX = ev.clientX;
        var mouseY = ev.clientY;
        _originalPos.x = ev.clientX;
        _originalPos.y = ev.clientY;
        _direction = direction;
        _isResizing = true;
        var div = document.getElementById("capture-div");
        div.addEventListener("mousemove",resizingHandler,false);
        div.addEventListener("mouseup",endResizeHandler,false);
    };
    
    ns.resizing = function(ev){
        if (_direction == null) {
            return;
        }
        
        var mouseX = ev.clientX;
        var mouseY = ev.clientY;

        if (_direction.indexOf("left") != -1){
            var newLeft = _selectionBoxPos.left-_originalPos.x+mouseX;
            var newWidth = _selectionBoxPos.width+_originalPos.x-mouseX;
            if (newWidth > _minWidth){
                this.setSelectionBoxPos(newLeft,_selectionBoxPos.top,newWidth,_selectionBoxPos.height);
                _originalPos.x = ev.clientX;
            }
        } else if (_direction.indexOf("right") != -1){
            var newWidth = _selectionBoxPos.width-_originalPos.x+mouseX;
            if (newWidth > _minWidth){
                this.setSelectionBoxPos(_selectionBoxPos.left,_selectionBoxPos.top,newWidth,_selectionBoxPos.height);
                _originalPos.x = ev.clientX;
            }
        }

        if (_direction.indexOf("top") != -1){
            var newTop = _selectionBoxPos.top-_originalPos.y+mouseY;
            var newHeight = _selectionBoxPos.height+_originalPos.y-mouseY;
            if (newHeight > _minHeight){
                this.setSelectionBoxPos(_selectionBoxPos.left,newTop,_selectionBoxPos.width,newHeight);
                _originalPos.y = ev.clientY;
            }
        } else if (_direction.indexOf("bottom") != -1){
            var newHeight = _selectionBoxPos.height-_originalPos.y+mouseY;
            if (newHeight > _minHeight){
                this.setSelectionBoxPos(_selectionBoxPos.left,_selectionBoxPos.top,_selectionBoxPos.width,newHeight);
                _originalPos.y = ev.clientY;
            }
        }        
    };
    
    ns.endResize = function(ev){
        var div = document.getElementById("capture-div");
        div.removeEventListener("mousemove",resizingHandler,false);
        div.removeEventListener("mouseup",endResizeHandler,false);
    };
    
    ns.endDraw = function(ev){
        var div = document.getElementById("capture-div");
        var box = document.getElementById("selection-box");
        _logger.trace("endDraw");
        box.style.visibility = "visible";
        div.removeEventListener("mousemove",guessSelectionHandler,false);
        div.removeEventListener("mousedown",endDrawHandler,false);
        var controlSet = document.getElementById("selectionbox-control-set");
        controlSet.width = parseInt(box.style.width)+10;
        controlSet.height = parseInt(box.style.height)+10;
        controlSet.setAttribute("style","visibility:visible");
        controlSet.setAttribute("style","-moz-box-flex:1");
    };
    
    
    //import the history data from LM1 to LM2
    ns.importHistory = function(){
        // _logger.trace("importHistory");
        //read from the stocklist.lst
        var filepath = this.getHistoryFile();    
        filepath += "\\Chrome\\linkool\\juice\\stocklist.lst";    
        var stockstr = this.read(filepath);
        //wirte to the cookie
        if (stockstr != null){
            this.write(stockstr);
        }
    };
        
    ns.read = function(filepath){
        // _logger.trace("read");
        var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        file.initWithPath(filepath);
        if (file.exists() == false) {
                //alert("File does not exist");
            return;
        }
        var is = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
        is.init(file, 0x01, 00004, null);
        var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
        sis.init(is);
        var stocklist = sis.read(sis.available());
        return stocklist;
    };
    
    ns.getHistoryFile = function() {
        // _logger.trace("getHistoryFile");
        var file = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties).get('ProfD', Components.interfaces.nsIFile);
        return file.path;
    };
        
    ns.write = function(stockstr) {
        var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
        //var cookieUri = ios.newURI("http://fe1.g-fox.cn/", null, null);
        var cookieUri = ios.newURI("http://fe1.g-fox.cn:8000/WebContent/stock/stockC/", null, null);
        var cookieSvc = Components.classes["@mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
        cookieStr="lk_stockwidget="+stockstr;
        cookieSvc.setCookieString(cookieUri, null, cookieStr, null);
        //var cookie = cookieSvc.getCookieString(cookieUri, null);
        //alert(cookie);
    };
    
//    for (var attr in ns) {
//        if (typeof attr != 'function') {
//            return;
//        }
//        
//        ns[attr] = eval("try {    " +    ns[attr].toString() + " } catch (e) { alert(e); }");
//    }
    
    function movingHandler (event){
        ns.moving(event);
    }
    
    function endMoveHandler (event){
        ns.endMove(event);
    }
    
    function resizingHandler(event){
        ns.resizing(event);
    }
    
    function endResizeHandler (event){
        ns.endResize(event);
    }
    
    function drawHandler(event){
        ns.boxDrawing(event);
    }
    
    function guessSelectionHandler(event){
        ns.guessSelection(event);
    }
    
    function endDrawHandler(event){
        ns.endDraw(event);
    }
    
    function endCaptureHandler(event){
        ns.endCapture(event);
    }
    
    function showHideButtonClick(event){
        var button = document.getElementById("favpart-statusbar");
        if (button.image == "chrome://livemargins/skin/Folder-open.png"){
            favpart_hideAll();
            button.image = "chrome://livemargins/skin/Folder-hide.png";
            button.setAttribute("image","chrome://livemargins/skin/Folder-hide.png");
        } else{
            favpart_showAll();
            button.image = "chrome://livemargins/skin/Folder-open.png";
            button.setAttribute("image","chrome://livemargins/skin/Folder-open.png");
        }
    }
    
    function favpart_firstRun(){
        try {
            // _logger.trace("favpart_firstRun");
            favpart_addToolbarButtons(true);
            //import the history data from LM1 to LM2
            ns.importHistory();
        } catch (e) { 
            _logger.error(e);
        }
    }
    
    function favpart_addToolbarButtons(force){
        var firefoxnav = document.getElementById("nav-bar"); // use "nav-bar" in Firefox 2 and earlier
        var curSet = firefoxnav.currentSet;
        if (curSet.indexOf("favpart-button") == -1 || curSet.indexOf("appcenter-button") == -1)
        {
            var set = firefoxnav.currentSet + ""; // to build a new string , not sure and should make sure later.
            // Place the button before the urlbar
            var manuallyRemovedLM4Button = jsm.utils.getPref("manuallyRemovedAppcenterButton",false);
            var manuallyRemovedFavpartButton = jsm.utils.getPref("manuallyRemovedFavpartButton",false);
            
            // in case null || something case a exception, it happened before
            if (force == null)
                force = false; 
            
            if (set.indexOf("appcenter-button") == -1 && (force || manuallyRemovedLM4Button == false)){
                set = set + ",appcenter-button";
            }
            
            if (curSet.indexOf("favpart-button") == -1 && (force || manuallyRemovedFavpartButton == false)){
                if(curSet.indexOf("appcenter-button") != -1) {
                    set = curSet.replace(/appcenter-button/, "favpart-button,appcenter-button");
                } else if (curSet.indexOf("search-container") != -1) {
                    set = curSet.replace(/search-container/, "search-container,favpart-button");
                } else {
                    // at the end
                    set = firefoxnav.currentSet + ",favpart-button";
                }
            }
            firefoxnav.setAttribute("currentset", set);
            firefoxnav.currentSet = set;
            document.persist("nav-bar", "currentset");
            // If you don't do the following call, funny things happen
            try {
                BrowserToolboxCustomizeDone(true);
            } catch (e) { 
                _logger.error(e);
            }
        }
    }
    
    window.addEventListener("load", function() {
        window.setTimeout(function() {
            if (jsm.utils.isFFVersionGET4()) {
                Application.getExtensions(function(exts) {
                    if (exts.has("livemargins@mozillaonline.com")) {
                        if(exts.get("livemargins@mozillaonline.com").firstRun || jsm.utils.getPref("lastVerForUIChange","0.1.0") < "5.0"){
                            favpart_firstRun();
                            jsm.utils.setPref("lastVerForUIChange", "5.0");
                        }
                        
                        ns.init();
                    }
                });
            } else {
                if ( Application.extensions.get("livemargins@mozillaonline.com").firstRun ||  jsm.utils.getPref("lastVerForUIChange","0.1.0") < "2.9.0"){
                    favpart_firstRun();
                    jsm.utils.setPref("lastVerForUIChange","2.9.0");
                }
                
                ns.init();
            }
        }, 1000);
        window.removeEventListener("load", arguments.callee, false);
    }, false);
})();
