var undoClosedButt = {
  populateUndoSubmenu: function(aNode) {
    // remove existing menu items
    while (aNode.hasChildNodes())
      aNode.removeChild(aNode.firstChild);

    // get closed-tabs from nsSessionStore
    var ss = Cc["@mozilla.org/browser/sessionstore;1"].
              getService(Ci.nsISessionStore);

    // return if no restorable tabs
    var noHistory = document.getElementById("bundle_undoclosedtabsbutton")
                      .getString("noHistory");
    if (ss.getClosedTabCount(window) == 0) {
      aNode.appendChild(document.createElement("menuitem"));
      aNode.firstChild.setAttribute("label", noHistory);
      aNode.firstChild.setAttribute("disabled", "true");
      return;
    }

    // populate menu
    var undoItems = eval("(" + ss.getClosedTabData(window) + ")");
    for(var i = 0; i < undoItems.length; i++) {
      var m = aNode.appendChild(document.createElement("menuitem"));
      m.setAttribute("class", "menuitem-iconic bookmark-item");
      m.setAttribute("label", undoItems[i].title);
      m.setAttribute("value", i);
      m.setAttribute("oncommand", "undoCloseTab(" + i + ");");
      m.setAttribute("image", "moz-anno:favicon:" + undoItems[i].image);
    
	
	// Set the targetURI attribute so it will be shown in tooltip and statusbar.
    // SessionStore uses one-based indexes, so we need to normalize them.
    let tabData = undoItems[i].state;
    let activeIndex = (tabData.index || tabData.entries.length) - 1;
    if (activeIndex >= 0 && tabData.entries[activeIndex])
      m.setAttribute("targetURI", tabData.entries[activeIndex].url);
	}
	
	// add option to clear closed tabs list
    aNode.appendChild(document.createElement("menuseparator"));
    
    var clearHistoryLabel = document.getElementById("bundle_undoclosedtabsbutton")
                              .getString("clearHistory");
    var mItem = aNode.appendChild(document.createElement("menuitem"));
    mItem.setAttribute("oncommand", "undoClosedButt.clearClosedTabsHistory()");
    mItem.setAttribute("label", clearHistoryLabel);
    mItem.tooltipText = mItem.label;
	
	// "Restore All Tabs"
    var strings = gNavigatorBundle;
    m = aNode.appendChild(document.createElement("menuitem"));
    m.setAttribute("label", strings.getString("menuRestoreAllTabs.label"));
    m.setAttribute("accesskey", strings.getString("menuRestoreAllTabs.accesskey"));
    m.addEventListener("command", function() {
      for (var i = 0; i < undoItems.length; i++)
        undoCloseTab();
    }, false);
 
  },

  clearClosedTabsHistory: function() {
    try {
      var maxUndo = gPrefService.getIntPref("browser.sessionstore.max_tabs_undo");
    } catch(ex) {
      var maxUndo = 10;
      gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", maxUndo);
    }
    //clear close tabs history
    gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", 0);

    //restore maximum undo history pref
    gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", maxUndo);


    // update button disabled on TabOpen & TabClose
    gBrowser.addEventListener("TabOpen",undoClosedButt.tabOpenClose,false);
    gBrowser.addEventListener("TabClose",undoClosedButt.tabOpenClose,false);
    gBrowser.addEventListener("TabOpen",undoClosedButt.tabbarOpenClose,false);
    gBrowser.addEventListener("TabClose",undoClosedButt.tabbarOpenClose,false);
        gBrowser.addEventListener("TabOpen",undoClosedButt.contextEntryOpenClose,false);
    gBrowser.addEventListener("TabClose",undoClosedButt.contextEntryOpenClose,false);
    // 1 second after browser window load
    setTimeout("undoClosedButt.tabOpenClose()", 250);
    setTimeout("undoClosedButt.tabbarOpenClose()", 250); 
    setTimeout("undoClosedButt.contextEntryOpenClose()", 250);

  },

  rightClickMenu: function(aNode, aEvent) {
    if(aEvent.button == 2) {
      var popup = document.getElementById("undoclosedtabsbutton-menu");
      var x = aNode.boxObject.x;
      var y = aNode.boxObject.y + aNode.boxObject.height;
      document.popupNode = aNode;
      popup.showPopup(aNode, x, y, "popup", null, null);
    }
  },

  restartFX: function() {
    var appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"]
                               .getService(Components.interfaces.nsIAppStartup);
    appStartup.quit(appStartup.eForceQuit | appStartup.eRestart);  
  },

  //Disable the toolbar button when no tabs to unclose
  tabOpenClose: function() {
    var ss = Components.classes["@mozilla.org/browser/sessionstore;1"].
                                 getService(Components.interfaces.nsISessionStore);
    var button = document.getElementById("undoclosedtabsbutton-toolbar-button") ;
    var count = ss.getClosedTabCount(window);
    // has closed tabs
    if (button && count>0)
       button.removeAttribute('disabled');
    // no closed tabs
    else if (button && count<1)
       button.setAttribute("disabled", "true");
  },

  //Disable the tabbar button when no tabs to unclose
  tabbarOpenClose: function() {
    var ss = Components.classes["@mozilla.org/browser/sessionstore;1"].
                                 getService(Components.interfaces.nsISessionStore);
    var tabcontainer = document.getAnonymousElementByAttribute(gBrowser, "anonid", "tabcontainer");
    var tabbarbutton = document.getAnonymousElementByAttribute(tabcontainer, "class", "uctb-tab-button");
    var count = ss.getClosedTabCount(window);
    // has closed tabs
    if (tabcontainer, tabbarbutton && count>0)
       tabbarbutton.removeAttribute('disabled');
    // no closed tabs
    else if (tabcontainer, tabbarbutton && count<1)
       tabbarbutton.setAttribute("disabled", "true");
  },
  
    //Disable the context-menu entry when no tabs to unclose
  contextEntryOpenClose: function() {
    var ss = Components.classes["@mozilla.org/browser/sessionstore;1"].
                                 getService(Components.interfaces.nsISessionStore);
    var contextEntry = document.getElementById("uctb-contextentry") ;
    var count = ss.getClosedTabCount(window);
    // has closed tabs
    if (contextEntry && count>0)
       contextEntry.removeAttribute('disabled');
    // no closed tabs
    else if (contextEntry && count<1)
       contextEntry.setAttribute("disabled", "true");
  }

}

window.addEventListener("load", UCT_init, false);
function UCT_init() {
   document.getElementById("contentAreaContextMenu").addEventListener("popupshowing", onUCTBPopup, false);

   // Add attribute to nsSessionStore persistTabAttribute after delay
   // we call this after nsSessionStore.init
   window.setTimeout(UCT_ss_persist, 2000, false);

   // add tab image and url in statustext to closed tab list
   // add menu entry to clear the closed tabs list
   eval("HistoryMenu.populateUndoSubmenu ="+HistoryMenu.populateUndoSubmenu.toString().replace(
      'var m = undoPopup.appendChild(document.createElement("menuitem"));',
      '$& \ m.setAttribute("class", "menuitem-iconic bookmark-item"); \
       var tabData = undoItems[i].state; \
       var activeIndex = (tabData.index || tabData.entries.length) - 1; \
       m.setAttribute("statustext", tabData.entries[activeIndex].url); \
       m.setAttribute("image", "moz-anno:favicon:" + undoItems[i].image);'
   ).replace(
      'undoPopup.appendChild(document.createElement("menuseparator"));',
      '$& \ var clearHistoryLabel = document.getElementById("bundle_undoclosedtabsbutton").getString("clearHistory");\
       var mItem = undoPopup.appendChild(document.createElement("menuitem")); \
       mItem.setAttribute("oncommand", "undoClosedButt.clearClosedTabsHistory()"); \
       mItem.setAttribute("label", clearHistoryLabel);'
   ));

    // update button disabled on TabOpen & TabClose
    gBrowser.addEventListener("TabOpen",undoClosedButt.tabOpenClose,false);
    gBrowser.addEventListener("TabClose",undoClosedButt.tabOpenClose,false);
    gBrowser.addEventListener("TabOpen",undoClosedButt.tabbarOpenClose,false);
    gBrowser.addEventListener("TabClose",undoClosedButt.tabbarOpenClose,false);
    gBrowser.addEventListener("TabOpen",undoClosedButt.contextEntryOpenClose,false);
    gBrowser.addEventListener("TabClose",undoClosedButt.contextEntryOpenClose,false);
    // 1 second after browser window load
    setTimeout("undoClosedButt.tabOpenClose()", 250);
    setTimeout("undoClosedButt.tabbarOpenClose()", 250); 
    setTimeout("undoClosedButt.contextEntryOpenClose()", 250);

}

function UCT_ss_persist() {
   if (!window.__SSi) // nsISessionStore not initialized
     return;

   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
         getService(Ci.nsISessionStore);
   ss.persistTabAttribute("image");
}

function onUCTBPopup() {
  var someConditions = !(gContextMenu.isContentSelected ||
                          gContextMenu.onLink ||
                          gContextMenu.onImage ||
                          gContextMenu.onTextInput);

  gContextMenu.showItem("uctb-contextentry", someConditions);
  gContextMenu.showItem("uctb-separator", someConditions);
}

function canQuitApplication() {
  var os=Components.classes["@mozilla.org/observer-service;1"]
   .getService(Components.interfaces.nsIObserverService)
 if(!os)return true
   try{
  var cancelQuit=Components.classes["@mozilla.org/supports-PRBool;1"]
   .createInstance(Components.interfaces.nsISupportsPRBool)
   os.notifyObservers(cancelQuit,"quit-application-requested",null)
 if(cancelQuit.data)
   return false}
     catch(ex){}
     os.notifyObservers(null,"quit-application-granted",null)
   return true
}