home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 July & August / PCWorld_2005-07-08_cd.bin / komunikace / netscape / nsb-install-8-0.exe / chrome / browser.jar / content / browser / browser.js < prev    next >
Text File  |  2005-05-08  |  286KB  |  8,986 lines

  1.  
  2. const NS_ERROR_MODULE_NETWORK = 2152398848;
  3. const NS_NET_STATUS_READ_FROM = NS_ERROR_MODULE_NETWORK + 8;
  4. const NS_NET_STATUS_WROTE_TO  = NS_ERROR_MODULE_NETWORK + 9;
  5. const kXULNS = 
  6.     "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  7. const XHTML_NS = "http://www.w3.org/1999/xhtml";  
  8.  
  9. const nsCI               = Components.interfaces;
  10. const nsIWebNavigation   = nsCI.nsIWebNavigation;
  11. const nsIHTMLPluginDocument = Components.interfaces.nsIHTMLPluginDocument;
  12. const PRINT_PREVIEW_REQ_WHILE_TRIDENT_LOADING_ERROR = 0;
  13. const PRINT_REQ_WHILE_TRIDENT_LOADING_ERROR = 1;
  14.  
  15. const MAX_HISTORY_MENU_ITEMS = 15;
  16.  
  17. var gRDF = null;
  18. var gGlobalHistory = null;
  19. var gURIFixup = null;
  20. var gPageStyleButton = null;
  21. var gLivemarksButton = null;
  22. var gCharsetMenu = null;
  23. var gLastBrowserCharset = null;
  24. var gPrevCharset = null;
  25. var gURLBar = null;
  26. var gProxyButton = null;
  27. var gProxyFavIcon = null;
  28. var gProxyDeck = null;
  29. var gNavigatorBundle = null;
  30. var gIsLoadingBlank = false;
  31. var gLastValidURLStr = "";
  32. var gLastValidURL = null;
  33. var gHaveUpdatedToolbarState = false;
  34. var gClickSelectsAll = false;
  35. var gIgnoreFocus = false;
  36. var gIgnoreClick = false;
  37. var gMustLoadSidebar = false;
  38. var gProgressMeterPanel = null;
  39. var gProgressCollapseTimer = null;
  40. var gPrefService = null;
  41. var appCore = null;
  42. var gBrowser = null;
  43. var gSidebarCommand = "";
  44. var gReportButton = null;
  45.  
  46. // Global variable that holds the nsContextMenu instance.
  47. var gContextMenu = null;
  48.  
  49. var gChromeState = null; // chrome state before we went into print preview
  50.  
  51. var gFormFillPrefListener = null;
  52. var gFormHistory = null;
  53. var gFormFillEnabled = true;
  54.  
  55. var gURLBarAutoFillPrefListener = null;
  56.  
  57. var afDataMgr = null;
  58. var gOptout = null;
  59.  
  60. var isButtonToggle = true;
  61.  
  62.  
  63. function showStack() {
  64.     dump("\n STACK DUMP: \n");
  65.     try {
  66.         var borkbork = 1 / 0;
  67.         var biteme;
  68.         biteme.Cannibal;
  69.         throw "biteme";
  70.     } catch (e){
  71.         dump(e.stack);
  72.     }
  73. }
  74.  
  75.  
  76. /**
  77. * We can avoid adding multiple load event listeners and save some time by adding
  78. * one listener that calls all real handlers.
  79. */
  80.  
  81. function loadEventHandlers(event)
  82. {
  83.     // Filter out events that are not about the document load we are interested in
  84.     if (event.originalTarget == _content.document) {
  85.         try {
  86.             UpdateInternetSearchResults(event); // MERC JA migration ff5->vulpine
  87.         } catch (ex) { }
  88.         checkForDirectoryListing();
  89.         charsetLoadListener(event);
  90.         updatePageLivemarks();
  91.     }
  92.  
  93.     // some event handlers want to be told what the original browser/listener is
  94.     var targetBrowser = null;
  95.     var targetListener = null;
  96.     if (gBrowser.mTabbedMode) {
  97.         var targetBrowserIndex = gBrowser.getBrowserIndexForDocument(event.originalTarget);
  98.         if (targetBrowserIndex == -1)
  99.             return;
  100.  
  101.         targetBrowser = gBrowser.getBrowserAtIndex(targetBrowserIndex);
  102.         targetListener = gBrowser.mTabListeners[targetBrowserIndex];
  103.     } else {
  104.         targetBrowser = gBrowser.mCurrentBrowser;
  105.         targetListener = null;      // no listener for non-tabbed-mode
  106.     }
  107.  
  108.     updatePageFavIcon(targetBrowser, targetListener);
  109.  
  110.     // update the last visited date
  111.     if (targetBrowser.currentURI.spec)
  112.         BMSVC.updateLastVisitedDate(targetBrowser.currentURI.spec,
  113.                                     targetBrowser.contentDocument.characterSet);
  114. }
  115.  
  116. /**
  117. * Determine whether or not the content area is displaying a page with frames,
  118. * and if so, toggle the display of the 'save frame as' menu item.
  119. **/
  120. function getContentAreaFrameCount()
  121. {
  122.     var iDF = false;
  123.     try
  124.     {
  125.         iDF = isDocumentFrame(document.commandDispatcher.focusedWindow);
  126.     }
  127.     catch(e) { dump ("Caught Exception: " + e + "\n");}
  128.  
  129.     var saveFrameItem = document.getElementById("menu_saveFrame");
  130.     if (!content || !_content.frames.length || !iDF)
  131.     saveFrameItem.setAttribute("hidden", "true");
  132. else
  133.     saveFrameItem.removeAttribute("hidden");
  134. }
  135.  
  136. //////////////////////////////// BOOKMARKS ////////////////////////////////////
  137.  
  138. function UpdateBookmarksLastVisitedDate(event)
  139. {
  140.     var url = getWebNavigation().currentURI.spec;
  141.     if (url) {
  142.         // if the URL is bookmarked, update its "Last Visited" date
  143.         BMSVC.updateLastVisitedDate(url, _content.document.characterSet);
  144.     }
  145. }
  146.  
  147. function HandleBookmarkIcon(iconURL, addFlag)
  148. {
  149.     var url = getWebNavigation().currentURI.spec
  150.     if (url) {
  151.         // update URL with new icon reference
  152.         if (addFlag) {
  153.             // MERC: TODO: ccampbell: This function call should not use nulls.
  154.             // Unfortunately the function spec changed between foxforce5 and vulpine
  155.             // so we will need to do more here in order for this to work properly...
  156.             // See bookmarks.js for example usage.
  157.             if (BMSVC) BMSVC.updateBookmarkIcon(url, null, null, 0);
  158.         } else {
  159.             if (BMSVC) BMSVC.removeBookmarkIcon(url);
  160.         }
  161.     }
  162. }
  163.  
  164. function UpdateBackForwardButtons()
  165. {
  166.     var backBroadcaster = document.getElementById("Browser:Back");
  167.     var forwardBroadcaster = document.getElementById("Browser:Forward");
  168.  
  169.     var webNavigation = gBrowser.webNavigation;
  170.  
  171.     // Avoid setting attributes on broadcasters if the value hasn't changed!
  172.     // Remember, guys, setting attributes on elements is expensive!  They
  173.     // get inherited into anonymous content, broadcast to other widgets, etc.!
  174.     // Don't do it if the value hasn't changed! - dwh
  175.  
  176.     var backDisabled = backBroadcaster.hasAttribute("disabled");
  177.     var forwardDisabled = forwardBroadcaster.hasAttribute("disabled");
  178.     if (backDisabled == webNavigation.canGoBack) {
  179.         if (backDisabled)
  180.         backBroadcaster.removeAttribute("disabled");
  181.     else
  182.         backBroadcaster.setAttribute("disabled", true);
  183.     }
  184.  
  185.     if (forwardDisabled == webNavigation.canGoForward) {
  186.         if (forwardDisabled)
  187.         forwardBroadcaster.removeAttribute("disabled");
  188.     else
  189.         forwardBroadcaster.setAttribute("disabled", true);
  190.     }
  191. }
  192.  
  193. // MERC - JCH : changed pageReport to removePRIcon to check for icon display
  194. function UpdatePageReport(event)
  195. {
  196.     if (!gReportButton)
  197.         gReportButton = document.getElementById("page-report-button");
  198.  
  199.  
  200.     if (gBrowser.selectedBrowser.showPageReportIcon) {
  201.  
  202.         gReportButton.setAttribute("blocked", "true");
  203.  
  204.         if (gPrefService && gPrefService.getBoolPref("privacy.popups.firstTime")) {
  205.             displayPageReportFirstTime();
  206.  
  207.             // Now set the pref.
  208.             gPrefService.setBoolPref("privacy.popups.firstTime", "false");
  209.         }
  210.  
  211.         if (gPrefService && gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
  212.             displayNotificationBar("popup");
  213.         }
  214.     } else {
  215.         gReportButton.removeAttribute("blocked");
  216.     }
  217. }
  218.  
  219.  
  220.  
  221. const gSessionHistoryObserver = {
  222.     observe: function(subject, topic, data)
  223.     {
  224.         if (topic != "browser:purge-session-history")
  225.             return;
  226.  
  227.         var backCommand = document.getElementById("Browser:Back");
  228.         backCommand.setAttribute("disabled", "true");
  229.         var fwdCommand = document.getElementById("Browser:Forward");
  230.         fwdCommand.setAttribute("disabled", "true");
  231.     }
  232. };
  233.  
  234. const gPopupBlockerObserver = {
  235.     _reportButton: null,
  236.     _kIPM: Components.interfaces.nsIPermissionManager,
  237.  
  238.     onUpdatePageReport: function ()
  239.     {
  240.         if (!this._reportButton)
  241.             this._reportButton = document.getElementById("page-report-button");
  242.  
  243.         if (gBrowser.selectedBrowser.pageReport) {
  244.             this._reportButton.setAttribute("blocked", "true");
  245.             if (gPrefService && gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
  246.                 displayNotificationBar("popup");
  247.             }
  248.         }
  249.         else
  250.             this._reportButton.removeAttribute("blocked");
  251.     },
  252.  
  253.     toggleAllowPopupsForSite: function (aEvent)
  254.     {
  255.         var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  256.         var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  257.                            .getService(this._kIPM);
  258.         var shouldBlock = aEvent.target.getAttribute("block") == "true";
  259.         var perm = shouldBlock ? this._kIPM.DENY_ACTION : this._kIPM.ALLOW_ACTION;
  260.         pm.add(currentURI, "popup", perm);
  261.  
  262.         hideNotificationBar("popup", gBrowser);
  263.         // gBrowser.hideMessage(gBrowser.selectedBrowser, "top");
  264.     },
  265.  
  266.     fillPopupList: function (aEvent)
  267.     {
  268.         var bundle_browser = document.getElementById("bundle_browser");
  269.         // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites
  270.         //          we should really walk the pageReport and create a list of "allow for <host>"
  271.         //          menuitems for the common subset of hosts present in the report, this will
  272.         //          make us frame-safe.
  273.         var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  274.         var blockedPopupAllowSite = document.getElementById("blockedPopupAllowSite");
  275.         try {
  276.             blockedPopupAllowSite.removeAttribute("hidden");
  277.  
  278.             var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  279.                                .getService(this._kIPM);
  280.             if (pm.testPermission(uri, "popup") == this._kIPM.ALLOW_ACTION) {
  281.                 // Offer an item to block popups for this site, if a whitelist entry exists
  282.                 // already for it.
  283.                 var blockString = bundle_browser.getFormattedString("popupBlock", [uri.host]);
  284.                 blockedPopupAllowSite.setAttribute("label", blockString);
  285.                 blockedPopupAllowSite.setAttribute("block", "true");
  286.             }
  287.         else {
  288.             // Offer an item to allow popups for this site
  289.             var allowString = bundle_browser.getFormattedString("popupAllow", [uri.host]);
  290.             blockedPopupAllowSite.setAttribute("label", allowString);
  291.             blockedPopupAllowSite.removeAttribute("block");
  292.         }
  293.     }
  294.     catch (e) {
  295.         blockedPopupAllowSite.setAttribute("hidden", "true");
  296.     }
  297.  
  298.     var item = aEvent.target.lastChild;
  299.     while (item && item.getAttribute("observes") != "blockedPopupsSeparator") {
  300.         var next = item.previousSibling;
  301.         item.parentNode.removeChild(item);
  302.         item = next;
  303.     }
  304.     var pageReport = gBrowser.selectedBrowser.pageReport;
  305.     if (pageReport && pageReport.length > 0) {
  306.         var blockedPopupsSeparator = document.getElementById("blockedPopupsSeparator");
  307.         blockedPopupsSeparator.removeAttribute("hidden");
  308.         for (var i = 0; i < pageReport.length; ++i) {
  309.             var popupURIspec = pageReport[i].popupWindowURI.spec;
  310.             if (popupURIspec == "" || popupURIspec == "about:blank" ||
  311.                 popupURIspec == uri.spec)
  312.             {
  313.                 continue;
  314.             }
  315.  
  316.             var menuitem = document.createElement("menuitem");
  317.             var label = bundle_browser.getFormattedString("popupShowPopupPrefix",
  318.                                                           [popupURIspec]);
  319.             menuitem.setAttribute("label", label);
  320.             menuitem.setAttribute("requestingWindowURI", pageReport[i].requestingWindowURI.spec);
  321.             menuitem.setAttribute("popupWindowURI", popupURIspec);
  322.             menuitem.setAttribute("popupWindowFeatures", pageReport[i].popupWindowFeatures);
  323.             menuitem.setAttribute("oncommand", "gPopupBlockerObserver.showBlockedPopup(event);");
  324.             aEvent.target.appendChild(menuitem);
  325.         }
  326.     }
  327.     else {
  328.         var blockedPopupsSeparator = document.getElementById("blockedPopupsSeparator");
  329.         blockedPopupsSeparator.setAttribute("hidden", "true");
  330.     }
  331.  
  332.     var blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage");
  333.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  334.     blockedPopupDontShowMessage.setAttribute("checked", !showMessage);
  335.     if (aEvent.target.localName == "popup")
  336.         blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromMessage"));
  337.     else
  338.         blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromStatusbar"));
  339. },
  340.  
  341. _findChildShell: function (aDocShell, aSoughtURI)
  342. {
  343.     var webNav = aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation);
  344.     if (webNav.currentURI.spec == aSoughtURI.spec)
  345.     return aDocShell;
  346.  
  347.     var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  348.     for (var i = 0; i < node.childCount; ++i) {
  349.         var docShell = node.getChildAt(i);
  350.         docShell = this._findChildShell(docShell, aSoughtURI);
  351.         if (docShell)
  352.             return docShell;
  353.     }
  354.     return null;
  355. },
  356.  
  357. showBlockedPopup: function (aEvent)
  358. {
  359.     var requestingWindowURI = Components.classes["@mozilla.org/network/standard-url;1"]
  360.                                         .createInstance(Components.interfaces.nsIURI);
  361.     requestingWindowURI.spec = aEvent.target.getAttribute("requestingWindowURI");
  362.     var popupWindowURI = aEvent.target.getAttribute("popupWindowURI");
  363.     var features = aEvent.target.getAttribute("popupWindowFeatures");
  364.  
  365.     var shell = this._findChildShell(gBrowser.selectedBrowser.docShell,
  366.                                      requestingWindowURI);
  367.     if (shell) {
  368.         var ifr = shell.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  369.         var dwi = ifr.getInterface(Components.interfaces.nsIDOMWindowInternal);
  370.         // XXXben - nsIDOMPopupBlockedEvent needs to store target, too!
  371.         dwi.open(popupWindowURI, "", features);
  372.     }
  373. },
  374.  
  375. editPopupSettings: function ()
  376. {
  377.     var host = "";
  378.     try {
  379.         var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  380.         host = uri.host;
  381.     }
  382.     catch (e) { }
  383.  
  384.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  385.                        .getService(Components.interfaces.nsIWindowMediator);
  386.     var existingWindow = wm.getMostRecentWindow("exceptions");
  387.     if (existingWindow) {
  388.         existingWindow.setHost(host);
  389.         existingWindow.focus();
  390.     }
  391.     else {
  392.         var params = { blockVisible: false,
  393.                        allowVisible: true,
  394.                        prefilledHost: host,
  395.                        permissionType: "popup" };
  396.         window.openDialog("chrome://browser/content/cookieviewer/CookieExceptions.xul?permission=popup",
  397.                           "_blank", "chrome,modal,resizable=yes", params);
  398.     }
  399. },
  400.  
  401. dontShowMessage: function ()
  402. {
  403.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  404.     var firstTime = gPrefService.getBoolPref("privacy.popups.firstTime");
  405.  
  406.     // If the info message is showing at the top of the window, and the user has never
  407.     // hidden the message before, show an info box telling the user where the info
  408.     // will be displayed.
  409.     if (showMessage && firstTime)
  410.         this._displayPageReportFirstTime();
  411.  
  412.     gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
  413.  
  414.     hideNotificationBar("popup", gBrowser);
  415. },
  416.  
  417. _displayPageReportFirstTime: function ()
  418. {
  419.     window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank",
  420.     "dependent");
  421. }
  422. };
  423.  
  424. const gXPInstallObserver = {
  425.     _findChildShell: function (aDocShell, aSoughtShell)
  426.     {
  427.         if (aDocShell == aSoughtShell)
  428.             return aDocShell;
  429.  
  430.         var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  431.         for (var i = 0; i < node.childCount; ++i) {
  432.             var docShell = node.getChildAt(i);
  433.             docShell = this._findChildShell(docShell, aSoughtShell);
  434.             if (docShell == aSoughtShell)
  435.                 return docShell;
  436.         }
  437.         return null;
  438.     },
  439.  
  440.     _getBrowser: function (aDocShell)
  441.     {
  442.         var tabbrowser = getBrowser();
  443.         for (var i = 0; i < tabbrowser.browsers.length; ++i) {
  444.             var browser = tabbrowser.getBrowserAtIndex(i);
  445.             var soughtShell = aDocShell;
  446.             var shell = this._findChildShell(browser.docShell, soughtShell);
  447.             if (shell)
  448.                 return browser;
  449.         }
  450.         return null;
  451.     },
  452.  
  453.     observe: function (aSubject, aTopic, aData)
  454.     {
  455.         var brandBundle = document.getElementById("bundle_brand");
  456.         var browserBundle = document.getElementById("bundle_browser");
  457.         switch (aTopic) {
  458.         case "xpinstall-install-blocked":
  459.             var shell = aSubject.QueryInterface(Components.interfaces.nsIDocShell);
  460.             browser = this._getBrowser(shell);
  461.             if (browser) {
  462.                 var extraData = new Array();
  463.                 extraData.push(shell);
  464.                 displayNotificationBar("xpi", extraData);
  465.             }
  466.             break;
  467.  
  468.         case "xpinstall-install-edit-prefs":
  469.             var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  470.                                .getService(Components.interfaces.nsIWindowMediator);
  471.             var optionsWindow = wm.getMostRecentWindow("Browser:Options");
  472.             if (optionsWindow) {
  473.                 optionsWindow.focus();
  474.                 optionsWindow.switchPage("catFeaturesbutton");
  475.             }
  476.             else
  477.                 openDialog("chrome://browser/content/pref/pref.xul", "PrefWindow",
  478.                            "chrome,titlebar,resizable,modal", "catFeaturesbutton");
  479.             var tabbrowser = getBrowser();
  480.             // tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top");
  481.             hideNotificationBar("xpi", tabbrowser);
  482.             break;
  483.  
  484.         case "xpinstall-install-edit-permissions":
  485.             var browser = this._getBrowser(aSubject.QueryInterface(Components.interfaces.nsIDocShell));
  486.             if (browser) {
  487.                 var webNav = aSubject.QueryInterface(Components.interfaces.nsIWebNavigation);
  488.                 var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  489.                                    .getService(Components.interfaces.nsIWindowMediator);
  490.                 var existingWindow = wm.getMostRecentWindow("exceptions");
  491.                 if (existingWindow) {
  492.                     existingWindow.setHost(webNav.currentURI.host);
  493.                     existingWindow.focus();
  494.                 }
  495.                 else {
  496.                     var params = { blockVisible:    false,
  497.                     allowVisible:    true,
  498.                     prefilledHost:   webNav.currentURI.host,
  499.                     permissionType:  "install" };
  500.                     window.openDialog("chrome://browser/content/cookieviewer/CookieExceptions.xul?permission=install",
  501.                                       "_blank", "chrome,modal,resizable=yes", params);
  502.                 }
  503.                 var tabbrowser = getBrowser();
  504.                 // tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top");
  505.                 hideNotificationBar("xpi", tabbrowser);
  506.             }
  507.             break;
  508.         }
  509.     }
  510. };
  511.  
  512. function Startup()
  513. {
  514.     dump("Startup()\n");
  515.     gBrowser = document.getElementById("content");
  516.  
  517.     // Allows Trident to update security (SSL) state; see nsHTMLPluginDocument.cpp.
  518.     // We can easily get fields from the window, but not from the browser object.
  519.     window.securityUI = gBrowser.securityUI;
  520.  
  521.     gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  522.                              .getService(Components.interfaces.nsIPrefBranch);
  523.     
  524.     titlebar.init();
  525.     moveMenubar();
  526.     
  527.     // Mercurial START
  528.     sitecontrols.initServices();
  529.     perfmon.initServices();
  530.     search.Init();
  531.  
  532.     passcardUtilsInit();
  533.  
  534.     // need to set up this observer early to deal with field highlighting in Passcards/Datacards
  535.     var docIsFillable=new docEndObserver();
  536.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  537.     os.addObserver(docIsFillable, "EndDocumentLoad", false);
  538.  
  539.     // Mercurial END
  540.  
  541.     var uriToLoad = null;
  542.     // Check for window.arguments[0]. If present, use that for uriToLoad.
  543.     if ("arguments" in window && window.arguments.length >= 1 && window.arguments[0])
  544.         uriToLoad = window.arguments[0];
  545.  
  546.     // MERC (DP): on first startup of browser, we show the Netscape welcome page
  547.     pref = Components.classes["@mozilla.org/preferences-service;1"]
  548.                      .getService(Components.interfaces.nsIPrefBranch);
  549.     // JMC: Fix this, it causes no pages on startup bug
  550.     var firstTime = pref.getBoolPref("browser.startup.firsttime");
  551.     if (firstTime) {
  552.         uriToLoad = uriToLoad + '|' + pref.getCharPref("browser.startup.welcomepage");
  553.         pref.setBoolPref("browser.startup.firsttime", false);
  554.     }
  555.  
  556.     // MERC (rpaul) if window shaping is define, move the menu to the left and move 
  557.     // the throbber to the right
  558.     
  559.     // read the property from the properties file
  560.     // N.B. for future themers this file should be placed in the theme jar
  561.     var windowShapingBundle = document.getElementById("drawOsBorder");
  562.     var drawOsWindowBorder = windowShapingBundle.getString("ShowOSTitleBar");
  563.     
  564.     if (drawOsWindowBorder) {
  565.         if (drawOsWindowBorder == 1) {
  566.             gPrefService.setBoolPref("browser.menu_in_titlebar", false);
  567.             moveMenubar();
  568.                                                         
  569.             // remove toggle menu bar position from context menu
  570.             var toggleMenuItem = document.getElementById('menuitem_toggleMenuBar');
  571.             if (toggleMenuItem) {
  572.                 document.getElementById('toolbar-context-menu').removeChild(toggleMenuItem);
  573.             }                                        
  574.                                                         
  575.             // remove the throbber from the top-box
  576.             var throbber = document.getElementById('throbber-box');
  577.             if (throbber) {
  578.                 document.getElementById('topstack').removeChild(throbber);
  579.             }
  580.             
  581.         } else {
  582.             // not window shaping, so remove throbber as a toolbar item
  583.             var navBar = document.getElementById('nav-bar');
  584.             if (navBar) {
  585.                     var throbberToolbarItem = document.getElementById('throbber-button');
  586.                     if (throbberToolbarItem) {
  587.                         navBar.removeChild(throbberToolbarItem);
  588.                     
  589.                         // remove from default toolbar set
  590.                         var defaultSet = navBar.getAttribute('defaultset');
  591.                         var strPos;
  592.                         strPos = defaultSet.indexOf('throbber-button');
  593.                         if (strPos != -1) {
  594.                                 navBar.setAttribute('defaultset', defaultSet.substring(0, strPos-1)); 
  595.                         }
  596.                                                             
  597.                     }
  598.             }    
  599.         }    
  600.     } 
  601.     
  602.     gIsLoadingBlank = uriToLoad == "about:blank";
  603.  
  604.     if (!gIsLoadingBlank)
  605.         prepareForStartup();
  606.  
  607.  
  608.     // only load url passed in when we're not page cycling
  609.     if (uriToLoad && !gIsLoadingBlank) {
  610.         if ("arguments" in window && window.arguments.length >= 3)
  611.             loadURI(uriToLoad, window.arguments[2], null);
  612.         else
  613.         {
  614.             loadOneOrMoreURIs(uriToLoad);
  615.             // MERC (DP): select the about tab browsing tab on first time
  616.             if (firstTime)
  617.             {
  618.                 var browserTabs = gBrowser.mTabContainer.childNodes;
  619.                 gBrowser.selectedTab = browserTabs[browserTabs.length - 1];
  620.             }
  621.         }
  622.     }
  623.  
  624.  
  625.         // Determine whether to show the sidebar
  626.         var sidebarBox = document.getElementById("sidebar-box");
  627.         var sidebarSplitter = document.getElementById("sidebar-splitter");
  628.         var sidebarCmd = null;
  629.  
  630.         if (window.opener && !window.opener.closed) {
  631.             if (window.opener.gFindMode == FIND_NORMAL) {
  632.                 var openerFindBar = window.opener.document.getElementById("FindToolbar");
  633.                 if (openerFindBar && !openerFindBar.hidden)
  634.                 openFindBar();
  635.             }
  636.  
  637.             var openerSidebarBox = window.opener.document.getElementById("sidebar-box");
  638.             // The opener can be the hidden window too, if we're coming from the state
  639.             // where no windows are open, and the hidden window has no sidebar box.
  640.             if (openerSidebarBox && !openerSidebarBox.hidden) {
  641.                 sidebarBox.setAttribute("width", openerSidebarBox.boxObject.width);
  642.                 if (openerSidebarBox.hasAttribute("sidebarcommand")) {
  643.                     sidebarCmd = openerSidebarBox.getAttribute("sidebarcommand");
  644.                     sidebarBox.setAttribute("sidebarcommand", sidebarCmd);
  645.                 }
  646.             } else {
  647.                 // The opener sidebar-box is either hidden or non-existent
  648.                 sidebarBox.hidden = true;
  649.                 sidebarSplitter.hidden = true;
  650.             }
  651.         } else {
  652.             // There is no opener
  653.             if (sidebarBox.hasAttribute("sidebarcommand"))
  654.             sidebarCmd = sidebarBox.getAttribute("sidebarcommand");
  655.         }
  656.         if (sidebarCmd) {
  657.             gMustLoadSidebar = true;
  658.             sidebarBox.hidden = false;
  659.             sidebarSplitter.hidden = false;
  660.             document.getElementById(sidebarCmd).setAttribute("checked", "true");
  661.         }
  662.  
  663.         // Certain kinds of automigration rely on this notification to complete their
  664.         // tasks BEFORE the browser window is shown.
  665.         var obs = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  666.         obs.notifyObservers(null, "browser-window-before-show", "");
  667.  
  668.         // Set a sane starting width/height for all resolutions on new profiles.
  669.         if (!document.documentElement.hasAttribute("width")) {
  670.             var defaultWidth = 994, defaultHeight;
  671.             if (screen.availHeight <= 600) {
  672.                 document.documentElement.setAttribute("sizemode", "maximized");
  673.                 defaultWidth = 610;
  674.                 defaultHeight = 450;
  675.             }
  676.         else {
  677.             // Create a narrower window for large or wide-aspect displays, to suggest
  678.             // side-by-side page view.
  679.             if ((screen.availWidth / 2) >= 800)
  680.                 defaultWidth = (screen.availWidth / 2) - 20;
  681.             defaultHeight = screen.availHeight - 10;
  682.         }
  683.         document.documentElement.setAttribute("width", defaultWidth);
  684.         document.documentElement.setAttribute("height", defaultHeight);
  685.     }
  686.  
  687.     // Initialize optout list
  688.     if (!gOptout)
  689.     {
  690.         var optoutInstance = Components.classes['@mozilla.org/optout;1'].getService();
  691.         gOptout = optoutInstance.QueryInterface(Components.interfaces.nsIOptOutService);
  692.         if (!gOptout)
  693.             dump('\nbrowser.js: gOptout has NOT been initialized!\n\n\n');
  694.     }
  695.  
  696.     if (gOptout)
  697.         gOptout.RefreshSiteList();
  698.  
  699.     // update tab chrome
  700.     gBrowser.updateChromeWhenLastTab();
  701.     setTimeout(delayedStartup, 0);
  702. }
  703.  
  704. function prepareForStartup()
  705. {
  706.     dump ("prepareForStartup()\n");
  707.     gURLBar = document.getElementById("urlbar");
  708.     gNavigatorBundle = document.getElementById("bundle_browser");
  709.     gProgressMeterPanel = document.getElementById("statusbar-progresspanel");
  710.     //gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver.onUpdatePageReport, false);
  711.     gBrowser.addEventListener("DOMUpdatePageReport", UpdatePageReport, false);
  712.     gBrowser.addEventListener("DOMLinkAdded", livemarkOnLinkAdded, false);
  713.     gBrowser.addEventListener("PluginNotFound", gMissingPluginInstaller.newMissingPlugin, false);
  714.  
  715.     var webNavigation;
  716.     try {
  717.         // Create the browser instance component.
  718.         appCore = Components.classes["@mozilla.org/appshell/component/browser/instance;1"]
  719.         .createInstance(Components.interfaces.nsIBrowserInstance);
  720.         if (!appCore)
  721.         throw "couldn't create a browser instance";
  722.  
  723.         webNavigation = getWebNavigation();
  724.         if (!webNavigation)
  725.         throw "no XBL binding for browser";
  726.     } catch (e) {
  727.         alert("Error launching browser window:" + e);
  728.         window.close(); // Give up.
  729.         return;
  730.     }
  731.  
  732.     // initialize observers and listeners
  733.     // and give C++ access to gBrowser
  734.     window.XULBrowserWindow = new nsBrowserStatusHandler();
  735.     window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  736.     .getInterface(Components.interfaces.nsIWebNavigation)
  737.     .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
  738.     .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  739.     .getInterface(Components.interfaces.nsIXULWindow)
  740.     .XULBrowserWindow = window.XULBrowserWindow;
  741.     gBrowser.docShell
  742.     .QueryInterface(nsCI.nsIDocShellTreeItem)
  743.     .rootTreeItem
  744.     .QueryInterface(nsCI.nsIInterfaceRequestor)
  745.     .getInterface(nsCI.nsIDOMWindow)
  746.     .QueryInterface(nsCI.nsIInterfaceRequestor)
  747.     .getInterface(nsCI.nsIDOMWindowUtils)
  748.     .browserDOMWindow = new nsBrowserAccess();
  749.  
  750.     window.browserContentListener =
  751.     new nsBrowserContentListener(window, gBrowser);
  752.  
  753.     // set default character set if provided
  754.     if ("arguments" in window && window.arguments.length > 1 && window.arguments[1]) {
  755.         if (window.arguments[1].indexOf("charset=") != -1) {
  756.             var arrayArgComponents = window.arguments[1].split("=");
  757.             if (arrayArgComponents) {
  758.                 //we should "inherit" the charset menu setting in a new window
  759.                 getMarkupDocumentViewer().defaultCharacterSet = arrayArgComponents[1];
  760.             }
  761.         }
  762.     }
  763.  
  764.     // Initialize browser instance..
  765.     appCore.setWebShellWindow(window);
  766.  
  767.     // Wire up session and global history before any possible
  768.     // progress notifications for back/forward button updating
  769.     webNavigation.sessionHistory = Components.classes["@mozilla.org/browser/shistory;1"]
  770.     .createInstance(Components.interfaces.nsISHistory);
  771.  
  772.     // enable global history
  773.     gBrowser.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = true;
  774.  
  775.     const selectedBrowser = gBrowser.selectedBrowser;
  776.     if (selectedBrowser.securityUI)
  777.     selectedBrowser.securityUI.init(selectedBrowser.contentWindow);
  778.  
  779.     // hook up UI through progress listener
  780.     gBrowser.addProgressListener(window.XULBrowserWindow, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
  781.  
  782. }
  783.  
  784. //Added by SLiu, for customize bookmarks toolbar
  785. function populateBookmarks()
  786. {
  787.     var bt = document.getElementById("bookmarks-ptf");
  788.     if (bt)
  789.     {
  790.         var btf = BMSVC.getBookmarksToolbarFolder().Value;
  791.         bt.ref = btf;
  792.         document.getElementById("bookmarks-chevron").ref = btf;
  793.         bt.database.AddObserver(BookmarksToolbarRDFObserver);
  794.         bt.controllers.appendController(BookmarksMenuController);
  795.         bt.builder.rebuild();
  796.     }
  797.     var bm = document.getElementById("bookmarks-menu");
  798.     bm.controllers.appendController(BookmarksMenuController);
  799. }
  800.  
  801. function ShowPhishingSiteWarning() {
  802.     displayNotificationBar("phishing");
  803. }
  804. function ShowSpywareSiteWarning() {
  805.     displayNotificationBar("spyware");
  806. }
  807.  
  808. function docEndObserver()
  809. {
  810. }
  811.  
  812. docEndObserver.prototype =
  813. {
  814.     // Data is a URL
  815.     // Subject is ?
  816.     observe: function (subject, topic, data)
  817.     {
  818.         if (topic == "EndDocumentLoad") {
  819.             // dump ("EndDocumentLoad... \n");
  820.             // JMC: Check to attach formfill controller, if required.
  821.             gBrowser.attachFormFill();
  822.             
  823.             if (this.checkRoll(subject, data))
  824.                 return;
  825.             var docType = String(gBrowser.contentDocument.contentType);
  826.             if (docType.indexOf("/xml") > 0)
  827.             {
  828.                 var isRss = true;
  829.                 if (getWebNavigation().currentURI.spec.indexOf(".rdf") > -1) ;
  830.                 else if(getWebNavigation().currentURI.spec.indexOf(".rss") > -1) ;
  831.                 else if(gBrowser.contentDocument.getElementsByTagName('rss').length) ;
  832.                 else if (gBrowser.contentDocument.getElementsByTagNameNS('http://my.netscape.com/rdf/simple/0.9/','channel')) ; // version 0.9
  833.                 else if (gBrowser.contentDocument.getElementsByTagNameNS('http://purl.org/rss/1.0/','channel')) ; // version 1.0
  834.                 else if (gBrowser.contentDocument.getElementsByTagNameNS('http://purl.org/atom/ns#draft-ietf-atompub-format-08', 'entry')) ; // atom version
  835.                 else {
  836.                     isRss = false;
  837.                 }
  838.                 
  839.                 if(isRss) {
  840.                     displayNotificationBar('rss');
  841.                 }
  842.             }
  843.             this.endDocLoad(subject);
  844.         }
  845.     },
  846.  
  847.     checkRoll : function (aWindow, aURL)
  848.     {
  849.             if (aWindow)
  850.             {
  851.                 var titleNodes = gBrowser.contentDocument.getElementsByTagName('title');
  852.                 for (var i=0; i < titleNodes.length; i++)
  853.                 {
  854.                     for (j=0; j < titleNodes.item(i).childNodes.length; j++)
  855.                     {
  856.                         if (titleNodes.item(i).childNodes[j].nodeValue.indexOf("404") > -1)
  857.                         {
  858.             
  859.                             // Find an h2 node with the text 'Error 404'
  860.                             var h2Nodes = gBrowser.contentDocument.getElementsByTagName('h2');
  861.                             dump ("ROLL: Found " + h2Nodes.length + " h2 nodes\n");
  862.                             for (var i=0; i < h2Nodes.length; i++)
  863.                             {
  864.                                 for (j=0; j < h2Nodes.item(i).childNodes.length; j++)
  865.                                 {
  866.                                         if (h2Nodes.item(i).childNodes[j].nodeValue.indexOf("Error 404") > -1)
  867.                                         {
  868.                                             var newURL = gPrefService.getCharPref('browser.redirect404.URL');
  869.                                             newURL += aURL;
  870.                                             // alert("Found a perfect 404 - roll this sucka");
  871.                                             loadURI(newURL, null, null);
  872.                                             return true;
  873.                                         }
  874.                                 }
  875.                             }
  876.                             
  877.                             var h1Nodes = gBrowser.contentDocument.getElementsByTagName('h1');
  878.                             for (var i=0; i < h1Nodes.length; i++)
  879.                             {
  880.                                 for (j=0; j < h1Nodes.item(i).childNodes.length; j++)
  881.                                 {
  882.                                     if ((h1Nodes.item(i).childNodes[j].nodeValue.indexOf("Error 404") > -1) ||
  883.                                     (h1Nodes.item(i).childNodes[j].nodeValue == "Not Found"))
  884.                                         {
  885.                                             var newURL = gPrefService.getCharPref('browser.redirect404.URL');
  886.                                             newURL += aURL;
  887.                                             // alert("Found a perfect 404 - roll this sucka");
  888.                                             loadURI(newURL, null, null);
  889.                                             return true;
  890.                                         }
  891.                                 }
  892.                             }
  893.                         }
  894.                     }
  895.                 }
  896.             }            
  897.             return false;
  898.         },
  899.  
  900.     endDocLoad : function (aWindow)
  901.     {
  902.         // dump('***** EndDocLoad: gCurrentNotificationBar: ' + gCurrentNotificationBar + '\n');
  903.         // MERC JVL: should not set to null before the message bar can clean itself up
  904.         //gCurrentNotificationBar = null;
  905.  
  906.         if (blacklistUtils.IsSiteInPhishList(gBrowser.currentURI)) {
  907.             displayNotificationBar("phishing",[gBrowser.currentURI]);
  908.             // ShowPhishingSiteWarning();
  909.         } else if (blacklistUtils.IsSiteInSpywareList(gBrowser.currentURI)) {
  910.             displayNotificationBar("spyware",[gBrowser.currentURI]);
  911.         }
  912.  
  913.         // MERC - JCH: When page has finished loading, check for password fields
  914.         // If we invoke the passcard notification bar, don't do the form fill check
  915.         var bIsPasscardable = CheckForPasscardField();
  916.  
  917.         var hpDoc = getTridentDocument();
  918.         if (!hpDoc)
  919.         {
  920.             // TODO JVL : see note in isPasscardHighlight()
  921.             if (bIsPasscardable && isPasscardHighlight() &&
  922.                 !PasscardIsSiteBlacklisted(gBrowser.currentURI))
  923.             {
  924.                 passcardDebug('highlighting in GECKO\n');
  925.                 // highlight passcard fields in the root document,
  926.                 // then the ones in each frame
  927.                 this.highlightPasscardFields(gBrowser.contentDocument);
  928.             }
  929.         }
  930.  
  931.         // Check if page datacard fillable
  932.         if (!bIsPasscardable)
  933.             datacardUtils.DoPageLoadedCheck();
  934.     }, // observe
  935.  
  936.     // highlight passcard fields in the current document
  937.     highlightPasscardFields : function (doc)        // JMC/JVL
  938.     {
  939.         if (!doc)
  940.             return;
  941.  
  942.         // highlight if we have a Passcard for the site
  943.         var domain = new Object();
  944.         gPasscardMgr.getDomain(gBrowser.currentURI, domain);
  945.         passcardDebug('HighlightPasscardFields() - host: ' + gBrowser.currentURI.host + ', domain: ' + domain.value + '\n');
  946.         if (!GetFirstPasscardForSite(domain.value))
  947.         {
  948.             var defaultPasscard = GetDefaultPasscard();
  949.             if (!defaultPasscard)
  950.                 return;
  951.  
  952.             // do not highlight if the Default Passcard's
  953.             // username and password fields are blank
  954.             if (defaultPasscard.user.length < 1 ||
  955.                 defaultPasscard.password.length < 1)
  956.             {
  957.                 return;
  958.             }
  959.         }
  960.  
  961.         var kBackgroundColor = "#ffff66";
  962.         var usernameField;
  963.         var tagList = doc.getElementsByTagName('input');
  964.         for (var i = 0; i < tagList.length; i++)
  965.         {
  966.             var tag = tagList.item(i);
  967.             if (tag)
  968.             {
  969.                 if (tag.getAttribute('type') == 'text' ||
  970.                 tag.getAttribute('type') == null)
  971.                 {
  972.                     usernameField = tag;
  973.                 }
  974.  
  975.                 if (tag.getAttribute('type') == 'password')
  976.                 {
  977.                     tag.style.backgroundColor = kBackgroundColor;
  978.  
  979.                     if (usernameField)
  980.                     {
  981.                         usernameField.style.backgroundColor = kBackgroundColor;
  982.                         usernameField = null;
  983.                     }
  984.                 }
  985.             }
  986.         }
  987.  
  988.         this.highlightPasscardFieldsInFrames(doc, 'iframe');
  989.         this.highlightPasscardFieldsInFrames(doc, 'frame');
  990.         this.highlightPasscardFieldsInFrames(doc, 'object');
  991.     },
  992.  
  993.     // highlight passcard fields in each 'frame' ('iframe' and 'object' as well) document
  994.     highlightPasscardFieldsInFrames : function(doc, elementName)
  995.     {
  996.         var iframeElements = doc.getElementsByTagName(elementName);
  997.         for (var i = 0; i < iframeElements.length; i++)
  998.         {
  999.             var iframeElement = iframeElements.item(i);
  1000.             if (iframeElement)
  1001.             {
  1002.                 this.highlightPasscardFields(iframeElement.contentDocument);
  1003.             }
  1004.         }
  1005.     }
  1006. }; // end docEndObserver
  1007.  
  1008.  
  1009. function toggleMenubar()
  1010. {
  1011.     // True = Right, False = Left
  1012.     gPrefService.setBoolPref("browser.menu_in_titlebar", gPrefService.getBoolPref("browser.menu_in_titlebar") != true);
  1013.     moveMenubar();
  1014. }
  1015.  
  1016. function moveMenubar()
  1017. {
  1018.     var mainMenu = document.getElementById('titlebar-menu-stack');
  1019.     var menuSpacer = document.getElementById('titlebar-menu-replacement');
  1020.  
  1021.     if (!gPrefService.getPrefType("browser.menu_in_titlebar")) return;
  1022.  
  1023.     if (gPrefService.getBoolPref("browser.menu_in_titlebar")
  1024.         != (mainMenu.parentNode.localName == 'toolbox')) return;
  1025.  
  1026.     var menuWidth=mainMenu.boxObject.width;
  1027.     mainMenu.parentNode.removeChild(mainMenu);
  1028.     var titlebarContainer = document.getElementById('titlebar-container');
  1029.     if (gPrefService.getBoolPref("browser.menu_in_titlebar")) {
  1030.         // dump(' Moving from toolbox to titlebar\n');
  1031.         if (menuSpacer) menuSpacer.parentNode.removeChild(menuSpacer);
  1032.         titlebarContainer.appendChild(mainMenu);
  1033.         //    document.getElementById('mainMenuPopupBroadcaster').setAttribute('position', 'after_end');
  1034.     } else {
  1035.         // dump(' Moving from titlebar to toolbox\n');
  1036.         var toolbox = document.getElementById('navigator-toolbox');
  1037.         toolbox.insertBefore(mainMenu, toolbox.firstChild);
  1038.         menuSpacer=document.createElement("spacer");
  1039.         menuSpacer.setAttribute("width",menuWidth + "");
  1040.         menuSpacer.setAttribute("id","titlebar-menu-replacement");
  1041.         menuSpacer.setAttribute("class",'titlebar-menu-stack');
  1042.         titlebarContainer.appendChild(menuSpacer);
  1043.         //document.getElementById('mainMenuPopupBroadcaster').setAttribute('position', 'after_start');
  1044.     }
  1045. }
  1046.  
  1047.  
  1048. function delayedStartup()
  1049. {
  1050.     dump ("delayedStartup()\n");
  1051.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  1052.     os.addObserver(gSessionHistoryObserver, "browser:purge-session-history", false);
  1053.  
  1054.     // We have to do this because we manually hook up history for the first browser in prepareForStartup
  1055.     os.addObserver(gBrowser.browsers[0], "browser:purge-session-history", false);
  1056.     os.addObserver(gXPInstallObserver, "xpinstall-install-blocked", false);
  1057.     os.addObserver(gXPInstallObserver, "xpinstall-install-edit-prefs", false);
  1058.     os.addObserver(gXPInstallObserver, "xpinstall-install-edit-permissions", false);
  1059.     os.addObserver(gMissingPluginInstaller, "missing-plugin", false);
  1060.  
  1061.     // MERC - JCH : To check if history is cleared
  1062.     if (!gGlobalHistory)
  1063.     gGlobalHistory = Components.classes["@mozilla.org/browser/global-history;2"]
  1064.                                .getService(Components.interfaces.nsIBrowserHistory);
  1065.     SetHistoryButton(); // JMC: Set anonymous mode button state
  1066.     BrowserOffline.init();
  1067.  
  1068.     if (gURLBar && document.documentElement.getAttribute("chromehidden").indexOf("toolbar") != -1) {
  1069.         gURLBar.setAttribute("readonly", "true");
  1070.         gURLBar.setAttribute("enablehistory", "false");
  1071.     }
  1072.  
  1073.     if (gIsLoadingBlank)
  1074.         prepareForStartup();
  1075.  
  1076.     if (gURLBar)
  1077.         gURLBar.addEventListener("dragdrop", URLBarOnDrop, true);
  1078.  
  1079. //    resizeSearchBar(); // JMC Disabled for beta
  1080.     // loads the services
  1081.     initServices();
  1082.  
  1083.     // Initialize SPUI
  1084.     if (spui) {
  1085.         // spui.RefreshComponentList();
  1086.         setTimeout( "spui.RefreshComponentList()", 0);  // this was causing crashes!
  1087.     } else dump('\nbrowser.js: SPUI has NOT been initialized!\n\n\n');
  1088.  
  1089.     initBMService();
  1090.     gBrowser.addEventListener("load", function(evt) { setTimeout(loadEventHandlers, 0, evt); }, true);
  1091.     
  1092.     // JMC - Do this earlier
  1093.     if (window.windowState == window.STATE_MAXIMIZED) {
  1094.         // call it, as we deal with the foxy theme in nsWindow
  1095.         window.maximize();        // MERC - Stevo (removed to fix bug with missing title bar on foxy
  1096.                                 //  theme when closed in maximized state and restarted.
  1097.         document.getElementById('main-window').setAttribute('sizemode', 'maximized');
  1098.         document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down';
  1099.         isButtonToggle = false;
  1100.     }
  1101.     
  1102.     window.addEventListener("keypress", ctrlNumberTabSelection, false);
  1103.     
  1104.     //if (gMustLoadSidebar) {
  1105.     //  var sidebar = document.getElementById("sidebar");
  1106.     //  var sidebarBox = document.getElementById("sidebar-box");
  1107.     //  sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
  1108.     //}
  1109.     
  1110.     initFindBar();
  1111.     
  1112.     // now load bookmarks
  1113.     BMSVC.readBookmarks();
  1114.     var bt = document.getElementById("bookmarks-ptf");
  1115.     if (bt) {
  1116.         var btf = BMSVC.getBookmarksToolbarFolder().Value;
  1117.         bt.ref = btf;
  1118.         document.getElementById("bookmarks-chevron").ref = btf;
  1119.         bt.database.AddObserver(BookmarksToolbarRDFObserver);
  1120.         bt.controllers.appendController(BookmarksMenuController);
  1121.     }
  1122.     var bm = document.getElementById("bookmarks-menu");
  1123.     bm.controllers.appendController(BookmarksMenuController);
  1124.     
  1125.     //JA ff5->vulp //<Modified by SLiu
  1126.     populateBookmarks();
  1127.     //SLiu>
  1128.     
  1129.     window.addEventListener("resize", onWindowResize, false);
  1130.     
  1131.     // called when we go into full screen, even if it is
  1132.     // initiated by a web page script
  1133.     window.addEventListener("fullscreen", onFullScreen, false);
  1134.     
  1135.     var element;
  1136.     if (gIsLoadingBlank && gURLBar && !gURLBar.hidden && !gURLBar.parentNode.parentNode.collapsed)
  1137.         element = gURLBar;
  1138.     else
  1139.         element = _content;
  1140.  
  1141.     // This is a redo of the fix for jag bug 91884
  1142.     var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  1143.                        .getService(Components.interfaces.nsIWindowWatcher);
  1144.     if (window == ww.activeWindow) {
  1145.         // JMC - URLBar Focus issue debugging
  1146.         dump ("delayed Startup, setting focus to " + element.id + "\n");
  1147.         element.focus();
  1148.     } else {
  1149.         // set the element in command dispatcher so focus will restore properly
  1150.         // when the window does become active
  1151.         if (element instanceof Components.interfaces.nsIDOMWindow) {
  1152.             document.commandDispatcher.focusedWindow = element;
  1153.             document.commandDispatcher.focusedElement = null;
  1154.         } else if (element instanceof Components.interfaces.nsIDOMElement) {
  1155.             document.commandDispatcher.focusedWindow = element.ownerDocument.defaultView;
  1156.             document.commandDispatcher.focusedElement = element;
  1157.         }
  1158.     }
  1159.  
  1160.     // This trashes the urlbar favicon so carefully set up in tabbrowser.xml...
  1161.     //SetPageProxyState("invalid", null);
  1162.  
  1163.     var toolbox = document.getElementById("navigator-toolbox");
  1164.     toolbox.customizeDone = BrowserToolboxCustomizeDone;
  1165.  
  1166.     // Enable/Disable Form Fill
  1167.     gFormFillPrefListener = new FormFillPrefListener();
  1168.     var pbi = gPrefService.QueryInterface(Components.interfaces.nsIPrefBranchInternal);
  1169.     pbi.addObserver(gFormFillPrefListener.domain, gFormFillPrefListener, false);
  1170.     gFormFillPrefListener.toggleFormFill();
  1171.  
  1172.     // Enable/Disable URL Bar Auto Fill
  1173.     gURLBarAutoFillPrefListener = new URLBarAutoFillPrefListener();
  1174.     pbi.addObserver(gURLBarAutoFillPrefListener.domain, gURLBarAutoFillPrefListener, false);
  1175.  
  1176.     pbi.addObserver(gHomeButton.prefDomain, gHomeButton, false);
  1177.     //gHomeButton.updateTooltip(); DO NOT USE..this is set in the browser.xul file
  1178.  
  1179.     // Initialize Plugin Overrides
  1180.     const kOverridePref = "browser.download.pluginOverrideTypes";
  1181.     if (gPrefService.prefHasUserValue(kOverridePref)) {
  1182.         var types = gPrefService.getCharPref(kOverridePref);
  1183.         types = types.split(",");
  1184.  
  1185.         const kPluginOverrideTypesNotHandled = "browser.download.pluginOverrideTypesNotHandled";
  1186.  
  1187.         var catman = Components.classes["@mozilla.org/categorymanager;1"].getService(Components.interfaces.nsICategoryManager);
  1188.         var typesNotHandled = "";
  1189.         for (var i = 0; i < types.length; ++i) {
  1190.             // Keep track of all overrides for plugins that aren't actually installed,
  1191.             // so we know not to show them in the plugin configuration dialog BUT
  1192.             // don't delete the overrides such that when the user actually installs the
  1193.             // plugin in this build their preferences are remembered.
  1194.             try {
  1195.                 var catEntry = catman.getCategoryEntry("Gecko-Content-Viewers", types[i]);
  1196.             }
  1197.             catch (e) {
  1198.                 catEntry = "";
  1199.             }
  1200.             if (catEntry == "")
  1201.             typesNotHandled += types[i] + ",";
  1202.  
  1203.             catman.deleteCategoryEntry("Gecko-Content-Viewers", types[i], false);
  1204.         }
  1205.  
  1206.         if (typesNotHandled) {
  1207.             typesNotHandled = typesNotHandled.substr(0, typesNotHandled.length - 1);
  1208.             gPrefService.setCharPref(kPluginOverrideTypesNotHandled, typesNotHandled);
  1209.         }
  1210.         else if (gPrefService.prefHasUserValue(kPluginOverrideTypesNotHandled))
  1211.             gPrefService.clearUserPref(kPluginOverrideTypesNotHandled);
  1212.     }
  1213.  
  1214.     gClickSelectsAll = gPrefService.getBoolPref("browser.urlbar.clickSelectsAll");
  1215.     
  1216.     clearObsoletePrefs();
  1217.  
  1218.     // Perform default browser checking (after window opens).
  1219.     var shell = getShellService();
  1220.     if (shell) {
  1221.         var shouldCheck = shell.shouldCheckDefaultBrowser;
  1222.         if (shouldCheck && !shell.isDefaultBrowser(true)) {
  1223.             var brandBundle = document.getElementById("bundle_brand");
  1224.             var shellBundle = document.getElementById("bundle_shell");
  1225.     
  1226.             var brandShortName = brandBundle.getString("brandShortName");
  1227.             var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
  1228.             var promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage",
  1229.                 [brandShortName]);
  1230.             var checkboxLabel = shellBundle.getFormattedString("setDefaultBrowserDontAsk",
  1231.                 [brandShortName]);
  1232.             const IPS = Components.interfaces.nsIPromptService;
  1233.             var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  1234.                                .getService(IPS);
  1235.             var checkEveryTime = { value: shouldCheck };
  1236.             var rv = ps.confirmEx(window, promptTitle, promptMessage,
  1237.                                   (IPS.BUTTON_TITLE_YES * IPS.BUTTON_POS_0) +
  1238.                                  (IPS.BUTTON_TITLE_NO * IPS.BUTTON_POS_1),
  1239.                                  null, null, null, checkboxLabel, checkEveryTime);
  1240.             if (rv == 0)
  1241.                 shell.setDefaultBrowser(true, false);
  1242.             shell.shouldCheckDefaultBrowser = checkEveryTime.value;
  1243.         }
  1244.     } else {
  1245.         // We couldn't get the shell service; go hide the mail toolbar button.
  1246.         var mailbutton = document.getElementById("mail-button");
  1247.         if (mailbutton)
  1248.         mailbutton.hidden = true;
  1249.     }
  1250.  
  1251.     // START Mercurial
  1252.     
  1253.     // Initialize Webmail
  1254.     webmail.Init();
  1255.     // For toolbar overflow
  1256.     var nb = document.getElementById('nav-bar');
  1257.     nb.enableOverflowMenu = true;
  1258.     var pt = document.getElementById('PersonalToolbar');
  1259.     if (pt) { pt.enableOverflowMenu = true; }
  1260.     // TODO: This form submission observer should really be singleton
  1261.     // (ie., one-per-application, not one-per-browser-window)
  1262.     datacardUtils.InitSubmitObserver();
  1263.  
  1264.     // END Mercurial
  1265.  
  1266.     var updatePanel = document.getElementById("softwareupdate");
  1267.     try {
  1268.         updatePanel.init();
  1269.     }
  1270.     catch (e) { dump("updatePanel failed with " + e + "\n"); }
  1271.     
  1272.     // BiDi UI
  1273.     if (isBidiEnabled()) {
  1274.         document.getElementById("documentDirection-separator").hidden = false;
  1275.         document.getElementById("documentDirection-swap").hidden = false;
  1276.         document.getElementById("textfieldDirection-separator").hidden = false;
  1277.         document.getElementById("textfieldDirection-swap").hidden = false;
  1278.     }
  1279. }
  1280.  
  1281. function resizeSearchBar()
  1282. {
  1283.     var searchBar = document.getElementById("searchbar");
  1284.     if(searchBar) {
  1285.         searchBar.addEventListener("dragdrop", SearchBarOnDrop, true);
  1286.         if (gPrefService.getPrefType("browser.search.size")) {
  1287.             var searchSize = gPrefService.getCharPref("browser.search.size");
  1288.             // this.parentNode.style.width = searchSize;
  1289.             // dump("SEARCH: Setting the checked attribute for search size\n");
  1290.             var sizeMenuItem = document.getAnonymousElementByAttribute(searchBar, "value", searchSize);
  1291.             if (sizeMenuItem) {
  1292.                 // dump("SEARCH: Calling doCommand on the sizeMenuItem\n");
  1293.                 sizeMenuItem.doCommand();
  1294.                 // sizeMenuItem.setAttribute('checked', 'true');
  1295.             }
  1296.         }
  1297.     }
  1298. }
  1299.  
  1300. function Shutdown()
  1301. {
  1302.     var os = Components.classes["@mozilla.org/observer-service;1"]
  1303.                        .getService(Components.interfaces.nsIObserverService);
  1304.     os.removeObserver(gSessionHistoryObserver, "browser:purge-session-history");
  1305.     os.removeObserver(gBrowser.browsers[0], "browser:purge-session-history");
  1306.     os.removeObserver(gXPInstallObserver, "xpinstall-install-blocked");
  1307.     os.removeObserver(gXPInstallObserver, "xpinstall-install-edit-permissions");
  1308.     os.removeObserver(gXPInstallObserver, "xpinstall-install-edit-prefs");
  1309.     os.removeObserver(gMissingPluginInstaller, "missing-plugin");
  1310.  
  1311.     try {
  1312.         gBrowser.removeProgressListener(window.XULBrowserWindow);
  1313.     } catch (ex) {
  1314.     }
  1315.  
  1316.     var bt = document.getElementById("bookmarks-ptf");
  1317.     if (bt) {
  1318.         try {
  1319.             bt.database.RemoveObserver(BookmarksToolbarRDFObserver);
  1320.             bt.controllers.removeController(BookmarksMenuController);
  1321.         } catch (ex) {
  1322.         }
  1323.     }
  1324.  
  1325.     try {
  1326.         var bm = document.getElementById("bookmarks-menu");
  1327.         bm.controllers.removeController(BookmarksMenuController);
  1328.     } catch (ex) {
  1329.     }
  1330.  
  1331.     try {
  1332.         var pbi = gPrefService.QueryInterface(Components.interfaces.nsIPrefBranchInternal);
  1333.         pbi.removeObserver(gFormFillPrefListener.domain, gFormFillPrefListener);
  1334.         pbi.removeObserver(gURLBarAutoFillPrefListener.domain, gURLBarAutoFillPrefListener);
  1335.         pbi.removeObserver(gHomeButton.prefDomain, gHomeButton);
  1336.     } catch (ex) {
  1337.     }
  1338.  
  1339.     BrowserOffline.uninit();
  1340.  
  1341.     uninitFindBar();
  1342.  
  1343.     var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  1344.     var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  1345.     var enumerator = windowManagerInterface.getEnumerator(null);
  1346.     enumerator.getNext();
  1347.     if (!enumerator.hasMoreElements()) {
  1348.         document.persist("sidebar-box", "sidebarcommand");
  1349.         document.persist("sidebar-box", "width");
  1350.         document.persist("sidebar-box", "src");
  1351.         document.persist("sidebar-title", "value");
  1352.     }
  1353.  
  1354.     window.XULBrowserWindow.destroy();
  1355.     window.XULBrowserWindow = null;
  1356.     window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1357.     .getInterface(Components.interfaces.nsIWebNavigation)
  1358.     .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
  1359.     .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1360.     .getInterface(Components.interfaces.nsIXULWindow)
  1361.     .XULBrowserWindow = null;
  1362.     gBrowser.docShell
  1363.     .QueryInterface(nsCI.nsIDocShellTreeItem)
  1364.     .rootTreeItem
  1365.     .QueryInterface(nsCI.nsIInterfaceRequestor)
  1366.     .getInterface(nsCI.nsIDOMWindow)
  1367.     .QueryInterface(nsCI.nsIInterfaceRequestor)
  1368.     .getInterface(nsCI.nsIDOMWindowUtils)
  1369.     .browserDOMWindow = null;
  1370.  
  1371.     window.browserContentListener.close();
  1372.     // Close the app core.
  1373.     if (appCore)
  1374.     appCore.close();
  1375. }
  1376.  
  1377. function FormFillPrefListener()
  1378. {
  1379.     gBrowser.attachFormFill();
  1380. }
  1381.  
  1382. FormFillPrefListener.prototype =
  1383. {
  1384.     domain: "browser.formfill.enable",
  1385.     observe: function (aSubject, aTopic, aPrefName)
  1386.     {
  1387.         if (aTopic != "nsPref:changed" || aPrefName != this.domain)
  1388.         return;
  1389.  
  1390.         this.toggleFormFill();
  1391.     },
  1392.  
  1393.     toggleFormFill: function ()
  1394.     {
  1395.         try {
  1396.             gFormFillEnabled = gPrefService.getBoolPref(this.domain);
  1397.         }
  1398.         catch (e) {
  1399.         }
  1400.         var formController = Components.classes["@mozilla.org/satchel/form-fill-controller;1"].getService(Components.interfaces.nsIAutoCompleteInput);
  1401.         formController.disableAutoComplete = !gFormFillEnabled;
  1402.  
  1403.         var searchBar = document.getElementsByTagName("searchbar");
  1404.         for (var i=0; i<searchBar.length;i++) {
  1405.             if (gFormFillEnabled)
  1406.             searchBar[i].removeAttribute("disableautocomplete");
  1407.         else
  1408.             searchBar[i].setAttribute("disableautocomplete", "true");
  1409.         }
  1410.     }
  1411. }
  1412.  
  1413. function URLBarAutoFillPrefListener()
  1414. {
  1415.     this.toggleAutoFillInURLBar();
  1416. }
  1417.  
  1418. URLBarAutoFillPrefListener.prototype =
  1419. {
  1420.     domain: "browser.urlbar.autoFill",
  1421.     observe: function (aSubject, aTopic, aPrefName)
  1422.     {
  1423.         if (aTopic != "nsPref:changed" || aPrefName != this.domain)
  1424.         return;
  1425.  
  1426.         this.toggleAutoFillInURLBar();
  1427.     },
  1428.  
  1429.     toggleAutoFillInURLBar: function ()
  1430.     {
  1431.         if (!gURLBar)
  1432.         return;
  1433.  
  1434.         var prefValue = false;
  1435.         try {
  1436.             prefValue = gPrefService.getBoolPref(this.domain);
  1437.         }
  1438.         catch (e) {
  1439.         }
  1440.  
  1441.         if (prefValue)
  1442.         gURLBar.setAttribute("completedefaultindex", "true");
  1443.     else
  1444.         gURLBar.removeAttribute("completedefaultindex");
  1445.     }
  1446. }
  1447.  
  1448. function ctrlNumberTabSelection(event)
  1449. {
  1450.     if (event.altKey && event.keyCode == KeyEvent.DOM_VK_RETURN) {
  1451.         // XXXblake Proper fix is to just check whether focus is in the urlbar. However, focus with the autocomplete widget is all
  1452.         // hacky and broken and there's no way to do that right now. So this just patches it to ensure that alt+enter works when focus
  1453.         // is on a link.
  1454.         if (!document.commandDispatcher.focusedElement || document.commandDispatcher.focusedElement.localName.toLowerCase() != "a") {
  1455.             // Don't let winxp beep on ALT+ENTER, since the URL bar uses it.
  1456.             event.preventDefault();
  1457.             return;
  1458.         }
  1459.     }
  1460.  
  1461.         if (!event.ctrlKey)
  1462.         return;
  1463.         //JA
  1464.         const MAX_TABS = 80;//defined in nsGUIEvent.h
  1465.         var index = event.charCode - 49;//49 == '0'
  1466.         if (index < 0 || (index > 8 && (index<0x0700 || index>0x0700+MAX_TABS)) )
  1467.         return;
  1468.         if(index>=0x0700)
  1469.         index = index-0x0700;
  1470.         //JA end
  1471.         if (index >= gBrowser.tabContainer.childNodes.length)
  1472.         return;
  1473.  
  1474.         var oldTab = gBrowser.selectedTab;
  1475.         var newTab = gBrowser.tabContainer.childNodes[index];
  1476.         if (newTab != oldTab) {
  1477.             oldTab.selected = false;
  1478.             gBrowser.selectedTab = newTab;
  1479.         }
  1480.  
  1481.         event.preventDefault();
  1482.         event.preventBubble();
  1483.         event.preventCapture();
  1484.         event.stopPropagation();
  1485.     }
  1486.  
  1487.     function gotoHistoryIndex(aEvent)
  1488.     {
  1489.         var index = aEvent.target.getAttribute("index");
  1490.         if (!index)
  1491.         return false;
  1492.         /*Mercurial Start */
  1493.         //JA check if HTML plugin
  1494.         var hpDoc = getTridentDocument();
  1495.         if(hpDoc)
  1496.         {
  1497.             var docshell=getWebNavigation();;
  1498.             var sessionHistory = docshell.sessionHistory;
  1499.             sessionHistory.setCurrentIndex(index);
  1500.  
  1501.             var loadedByGecko = false;
  1502.             try
  1503.             {
  1504.                 var currURI = new Object();
  1505.                 hpDoc.getURIAtIndex(index, currURI);
  1506.                 if(currURI)
  1507.                 {
  1508.                     var site = currURI.value.host;
  1509.                     var bControlled=sitecontrols.SCSVC.isControlledSite(site);
  1510.                     if(bControlled)
  1511.                     {
  1512.                         var displayEngine=sitecontrols.SCSVC.readSiteControl(site, "displayEngine");
  1513.                         if(displayEngine=="Gecko")
  1514.                         {
  1515.                             loadedByGecko=true;
  1516.                             hpDoc.geckoLoadURI(uri, Components.interfaces.nsIDocShellLoadInfo.loadBypassHistory);
  1517.                             //hpDoc.geckoLoadURI(currURI.value, 10);
  1518.                         }
  1519.                     }
  1520.                 }
  1521.             }
  1522.             catch(ex){dump("GoForward check sitecontrols engine failed!!!\n");}
  1523.  
  1524.             if(!loadedByGecko)
  1525.             hpDoc.goCmd(-index);
  1526.             UpdateBackForwardButtons();
  1527.         }/*Mercurial Finish*/
  1528.     else {
  1529.         var where = whereToOpenLink(aEvent);
  1530.         if (where == "current") {
  1531.             // Normal click.  Go there in the current tab and update session history.
  1532.             try {
  1533.                 getWebNavigation().gotoIndex(index);
  1534.             }
  1535.             catch(ex) {
  1536.                 return false;
  1537.             }
  1538.             return true;
  1539.         }
  1540.     else {
  1541.         // Modified click.  Go there in a new tab/window.
  1542.         // This code doesn't copy history or work well with framed pages.
  1543.  
  1544.         var sessionHistory = getWebNavigation().sessionHistory;
  1545.         var entry = sessionHistory.getEntryAtIndex(index, false);
  1546.         var url = entry.URI.spec;
  1547.         openUILinkIn(url, where);
  1548.         return true;
  1549.     }
  1550. }
  1551. }
  1552.  
  1553. function BrowserForward(aEvent, aIgnoreAlt)
  1554. {
  1555.     var docshell = getWebNavigation();
  1556.     var sessionHistory = docshell.sessionHistory;
  1557.     var count = sessionHistory.count;
  1558.     var index = sessionHistory.index;
  1559.  
  1560.     //JA ff5->vulp + modif
  1561.     if (index >= count-1)
  1562.     return;//error call
  1563.  
  1564.     // Try to get handle on Trident
  1565.     var hpDoc = getTridentDocument();
  1566.     var fromEngine = 'Gecko';
  1567.     if (hpDoc)
  1568.     fromEngine = 'Trident';
  1569.  
  1570.  
  1571.     index++;
  1572.     var uri = sessionHistory.getEntryAtIndex(index, false).URI;
  1573.     // dump('  To page is ==> '+uri.spec+'\n');
  1574.     var site = sitecontrols.SCSVC.getResourceForURI(uri.spec);
  1575.     var toEngine = sitecontrols.SCSVC.readSiteControlResource(site, 'displayEngine');
  1576.     docshell.browserEngine = toEngine;
  1577.  
  1578.     if (fromEngine == 'Trident')
  1579.     {
  1580.         sessionHistory.setCurrentIndex(index);
  1581.         if (toEngine == 'Gecko'){
  1582.             // dump('BrowserForward: Trident=>Gecko\n');
  1583.             hpDoc.geckoLoadURI(uri, Components.interfaces.nsIDocShellLoadInfo.loadNormalReplace);
  1584.             //hpDoc.geckoLoadURI(uri, 1);
  1585.         } else {
  1586.             // dump('BrowserForward: Trident ==> Trident\n');
  1587.             hpDoc.goCmd(2);
  1588.         }
  1589.     }
  1590. else//original code
  1591.     {
  1592.         var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
  1593.  
  1594.         if (where == "current") {
  1595.             try {
  1596.                 docshell.goForward();
  1597.             }
  1598.             catch(ex) { dump ("Caught Exception: " + ex + "\n");}
  1599.         }
  1600.     else {
  1601.         //JA var sessionHistory = getWebNavigation().sessionHistory;
  1602.         //JA var currentIndex = sessionHistory.index;
  1603.         //JA var entry = sessionHistory.getEntryAtIndex(currentIndex + 1, false);
  1604.         //JA var uri = entry.URI.spec;
  1605.         openUILinkIn(uri, where);
  1606.     }
  1607. }
  1608. }
  1609.  
  1610. function BrowserBack(aEvent, aIgnoreAlt)
  1611. {
  1612.     var docshell = getWebNavigation();
  1613.     var sessionHistory = docshell.sessionHistory;
  1614.     var index = sessionHistory.index;
  1615.     if (index <= 0)
  1616.     return;//error!
  1617.     // Try to get handle on Trident
  1618.     var hpDoc = getTridentDocument();
  1619.     var fromEngine = 'Gecko';
  1620.     if (hpDoc)
  1621.     fromEngine = 'Trident';
  1622.  
  1623.     index--;
  1624.     var uri = sessionHistory.getEntryAtIndex(index, false).URI;
  1625.     // dump('  To page is ==> '+uri.spec+'\n');
  1626.     var site = sitecontrols.SCSVC.getResourceForURI(uri.spec);
  1627.     var toEngine = sitecontrols.SCSVC.readSiteControlResource(site, 'displayEngine');
  1628.     getWebNavigation().browserEngine = toEngine;
  1629.     if (fromEngine == 'Trident')
  1630.     {
  1631.         sessionHistory.setCurrentIndex(index);
  1632.         if (toEngine == 'Gecko')
  1633.         {
  1634.             // dump('BrowserBack: Trident ==> Gecko\n');
  1635.             hpDoc.geckoLoadURI(uri, Components.interfaces.nsIDocShellLoadInfo.loadBypassHistory);
  1636.             //hpDoc.geckoLoadURI(uri, 10);
  1637.         } else {
  1638.             // dump('BrowserBack: Trident ==> Trident\n');
  1639.             hpDoc.goCmd(1);
  1640.         }
  1641.     }
  1642. else//Gecko, original code
  1643.     {
  1644.  
  1645.         var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
  1646.  
  1647.         if (where == "current") {
  1648.             try {
  1649.                 getWebNavigation().goBack();
  1650.             }
  1651.             catch(ex) { dump ("Caught Exception: " + ex + "\n");     }
  1652.         }
  1653.     else {
  1654.         //JA var sessionHistory = getWebNavigation().sessionHistory;
  1655.         //JA var currentIndex = sessionHistory.index;
  1656.         //JA var entry = sessionHistory.getEntryAtIndex(currentIndex - 1, false);
  1657.         //JA var uri = entry.URI.spec;
  1658.         openUILinkIn(uri, where);
  1659.     }
  1660. }
  1661. }
  1662.  
  1663. function BrowserHandleBackspace()
  1664. {
  1665.     BrowserBack();
  1666. }
  1667.  
  1668. function BrowserBackMenu(event)
  1669. {
  1670.     return FillHistoryMenu(event.target, "back");
  1671. }
  1672.  
  1673. function BrowserForwardMenu(event)
  1674. {
  1675.     return FillHistoryMenu(event.target, "forward");
  1676. }
  1677.  
  1678. // MERC (DP): fill in the home button dropdown with a each home page item
  1679. function BrowserHomeMenu(menu) {
  1680.     var homePage = gHomeButton.getHomePage();
  1681.     var urls = homePage.split("|");
  1682.     var separator;
  1683.     var referenceNodeList = menu.getElementsByTagName("menuseparator");
  1684.     var referenceNode = null;
  1685.  
  1686.     var children = menu.childNodes;
  1687.  
  1688.     for (var j = 0; j < children.length; j++) {
  1689.         // clear old menuitems
  1690.         try {
  1691.             var tmpElement = children[j].QueryInterface(Components.interfaces.nsIDOMElement);
  1692.             if(!tmpElement.hasAttribute("nodelete")) { //avoid deleting separators
  1693.                 menu.removeChild(children[j]);
  1694.             }
  1695.         }
  1696.         catch(e){
  1697.             dump ("Caught Exception : "+e+"\n");
  1698.             //we may still want to delete this node?
  1699.         }
  1700.  
  1701.     }
  1702.  
  1703.     //find the first separator to insert the page links before
  1704.     if (referenceNodeList.length > 0){
  1705.         referenceNode = referenceNodeList[0];
  1706.     }
  1707.  
  1708.     for (var i = 0; i < urls.length; i++) {
  1709.         var menuitem = document.createElement( "menuitem" );
  1710.         menuitem.setAttribute("label", urls[i]);
  1711.         //var tmpStr = "gBrowser.addTab('" +  urls[i] + "')";
  1712.         var tmpStr = "loadURIWithOpenPref('" +  urls[i] + "', 'browser.tabs.homepage.open');";
  1713.         menuitem.setAttribute("oncommand", tmpStr);
  1714.         menuitem.setAttribute("tooltiptext", "Go to this page");
  1715.         if (referenceNodeList.length > 0){
  1716.             menu.insertBefore( menuitem, referenceNode );
  1717.         } else  {
  1718.             menu.appendChild( menuitem );
  1719.         }
  1720.     }
  1721. }
  1722. // <MERC
  1723.  
  1724. function BrowserStop()
  1725. {
  1726.     var hpDoc = getTridentDocument();
  1727.  
  1728.     if(hpDoc)
  1729.     {
  1730.         //var stopbutton = document.getElementById("stop-button");
  1731.         //stopbutton.setAttribute("disabled", "true");
  1732. /*        var stopReloadBtn = document.getElementById("stop-reload-button");
  1733.         if (stopReloadBtn) {
  1734.             // JCH: Need to set label according to state
  1735.             stopReloadBtn.setAttribute("label","Reload");
  1736.             stopReloadBtn.setAttribute("state","reload");
  1737.             stopReloadBtn.removeAttribute("command");
  1738.             stopReloadBtn.setAttribute("oncommand","BrowserStopReload(event);");
  1739.         }*/
  1740.         hpDoc.cancelNavigation();
  1741.     } else  {
  1742.         try
  1743.         {
  1744.             const stopFlags = nsIWebNavigation.STOP_ALL;
  1745.             getWebNavigation().stop(stopFlags);
  1746.         }
  1747.         catch(ex) { dump ("Caught Exception: " + ex + "\n");}
  1748.     }
  1749. }
  1750. //MERC/>
  1751.  
  1752.  
  1753. /**
  1754. * MERC: ccampbell
  1755. * Added this function to differentiate between the way Find works in
  1756. * Gecko (a.k.a Find Bar) and Trident (old fashioned dialog)
  1757. **/
  1758. function findCommand(again) {
  1759.     var hpDoc = getTridentDocument();
  1760.     if (hpDoc) {
  1761.         // The current tab is in Trident
  1762.         gBrowser.find();
  1763.     } else {
  1764.         try {
  1765.             // The current tab is in Gecko
  1766.             if (again)
  1767.                 onFindAgainCmd();
  1768.             else
  1769.                 onFindCmd();
  1770.         } catch(ex) { dump ("Caught Exception: " + ex + "\n"); }
  1771.     }
  1772. }
  1773.  
  1774.  
  1775. ///////////////////////////////////////////////////////////////////////////////////////
  1776. //                       POPUPBLOCK BUTTON GENERAL FUNCTIONALITY                     //
  1777. ///////////////////////////////////////////////////////////////////////////////////////
  1778.  
  1779. // MERC - JCH
  1780. // Increment the global popup blocked count
  1781. function IncrementPopupsBlocked(windowDoc)
  1782. {
  1783.     if (!gBrowser)
  1784.         return;
  1785.  
  1786.     // Get the index of the relevant tab document object
  1787.     var foundIndex = gBrowser.getBrowserIndexForDocument(windowDoc);
  1788.  
  1789.     if (foundIndex < 0)
  1790.         return;
  1791.  
  1792.     // Get ref to target tab
  1793.     var browserTabs = gBrowser.mTabContainer.childNodes;
  1794.     var targetTab = browserTabs[foundIndex];
  1795.  
  1796.     // Modify the global count
  1797.     ++gBrowser.numberBlocked;
  1798.  
  1799.     // Get the browser object of the current tab
  1800.     var browserForCurrentTab = gBrowser.getBrowserForTab(gBrowser.mCurrentTab);
  1801.  
  1802.     // Get the browser object of the target tab
  1803.     var browserForTargetTab = gBrowser.getBrowserForTab(targetTab);
  1804.  
  1805.     // Compare browser that has popup with the current browser
  1806.     // If they are not the same don't update the UI
  1807.     if (browserForTargetTab != browserForCurrentTab)
  1808.     {
  1809.         return;
  1810.     }
  1811.  
  1812.     // Update UI
  1813.     SetPopupBlockToggle();
  1814.  
  1815.     // Get a handle to the button element
  1816.     var button = document.getElementById("popupblocker-button");
  1817.  
  1818.     // JMC added sanity check for when button is removed from toolbar
  1819.     if (button) {
  1820.         // Change icon for two seconds when popups are blocked
  1821.         button.setAttribute("popupDetected","true");
  1822.         // Show popup block icon for two seconds
  1823.         setTimeout("RestorePBB()", 2000);
  1824.     }
  1825. }
  1826.  
  1827.  
  1828. // MERC - JCH : Restore the look of the button
  1829. function RestorePBB()
  1830. {
  1831.     // dump("\nIn RestorePBB -> Show image\n");
  1832.  
  1833.     // Get a handle to the button element
  1834.     var button = document.getElementById("popupblocker-button");
  1835.     if (button) {
  1836.         button.setAttribute("popupDetected","false");
  1837.         SetPopupBlockToggle();
  1838.     }
  1839. }
  1840.  
  1841.  
  1842. // MERC - JCH : Determine whether blocking is on
  1843. // Called from nsGlobalWindow.cpp and nsHTMLPluginDocument.cpp
  1844. function PopupBlockingOn(windowDoc)
  1845. {
  1846.     // Get the index of the relevant tab document object
  1847.     var foundIndex = gBrowser.getBrowserIndexForDocument(windowDoc);
  1848.  
  1849.     // dump(">>>>>>  In PopupBlockingOn() foundIndex is: " + foundIndex + "\n");
  1850.     if (foundIndex < 0)
  1851.     return;
  1852.  
  1853.     // Get controlling site resource
  1854.     var site = GetSiteControlResource(gBrowser.getBrowserAtIndex(foundIndex));
  1855.  
  1856.     // If site is illegitimate and uncontrollable then block pop-ups
  1857.     if (!site)
  1858.     return false;
  1859.  
  1860.     // Get the value of the setting associated with popup blocking
  1861.     var popupsAllowed = sitecontrols.SCSVC.readSiteControlResource(site,"allowPopups");
  1862.  
  1863.     // Return whether to block popups or not
  1864.     // Assume no blocking
  1865.     var blockPopups = false;
  1866.     if (popupsAllowed.indexOf("false") > -1)
  1867.     blockPopups = true;
  1868.  
  1869.     return blockPopups;
  1870. }
  1871.  
  1872.  
  1873. // MERC - JCH : determine whether blocking sound is on
  1874. // Called from nsGlobalWindow.cpp and nsHTMLPluginDocument.cpp
  1875. function BlockingSoundOn(windowDoc)
  1876. {
  1877.     if (!gBrowser)
  1878.     return;
  1879.  
  1880.     // Get the index of the relevant tab browser object
  1881.     var foundIndex = gBrowser.getBrowserIndexForDocument(windowDoc);
  1882.  
  1883.     // dump("@@@@@ in BlockingSoundOn with index: " + foundIndex + "\n");
  1884.  
  1885.     if (foundIndex < 0)
  1886.         return false;
  1887.  
  1888.     // Get the browser object of the current tab
  1889.     var browserForTab = gBrowser.getBrowserForTab(gBrowser.mCurrentTab);
  1890.  
  1891.     // Compare browser that has popup with the current browser
  1892.     // If they are not the same don't play sound
  1893.     if (gBrowser.getBrowserAtIndex(foundIndex) != browserForTab)
  1894.         return false;
  1895.  
  1896.     if (!gPrefService)
  1897.         return false;
  1898.  
  1899.     return gPrefService.getBoolPref("privacy.popups.sound_enabled");
  1900. }
  1901.  
  1902. /**
  1903. * Returns the RDF resource for the site control applicable to the
  1904. * given browser object, or else to the current tab's if no object
  1905. * is specified
  1906. **/
  1907. function GetSiteControlResource(browser) {
  1908.     // dump('enter >> GetSiteControlResource()\n');
  1909.  
  1910.     // Grab the right browser object
  1911.     if (!browser)
  1912.         browser = gBrowser.getBrowserForTab(gBrowser.mCurrentTab);
  1913.  
  1914.     // Pull out the URI for that tab/browser
  1915.     var uri;
  1916.     if (!browser.currentURI) uri = '';
  1917.     else uri = browser.currentURI.spec;
  1918.     //dump('         uri: '+uri+'\n');
  1919.  
  1920.     // The URI must either be for a controllable site (including local files)
  1921.     // or else 'about:blank'.  Otherwise, exit without doing anything.
  1922.     if ((uri != 'about:blank') && (!sitecontrols.SCSVC.isControllableURI(uri)))
  1923.     {
  1924.         // if the site is controlled, it's rendered with Gecko, so update statusbar
  1925.         UpdateStatusBarEngineIcon();
  1926.         // dump('         '+uri+' is not a controllable uri\n');
  1927.         return null;
  1928.     }
  1929.  
  1930.     // Site 'about:blank' is treated as if it's a DEFAULT site.
  1931.     // This should be SiteControls:Default resource.
  1932.     if (uri == 'about:blank')
  1933.     {
  1934.         UpdateStatusBarEngineIcon();
  1935.         // dump('         '+uri+' will use default settings\n');
  1936.         uri = '';
  1937.     }
  1938.  
  1939.     // Return the RDF resource
  1940.     // Note that if site is not explicitly controlled
  1941.     // the default resource is returned
  1942.     return sitecontrols.SCSVC.getResourceForURI(uri);
  1943. }
  1944.  
  1945.  
  1946. // MERC - JCH : Updates XUL related to the popupblock button
  1947. function SetPopupBlockToggle()
  1948. {
  1949.     //dump('SetPopupBlockToggle()\n');
  1950.  
  1951.     // Get current url in proper format
  1952.     var site = GetSiteControlResource();
  1953.  
  1954.     // If site is not controllable we will use default settings for xul
  1955.     if (!site)
  1956.     site = sitecontrols.SCSVC.getResourceForURI('');
  1957.  
  1958.     // dump(">>>>>>  In SetPopupBlockToggle() site is: " + site + "\n");
  1959.  
  1960.     // Get the value of the site controls associated with popup blocking
  1961.     var popupsAllowed = sitecontrols.SCSVC.readSiteControlResource(site,"allowPopups");
  1962.  
  1963.     // Get a handle to the button element
  1964.     var button = document.getElementById("popupblocker-button");
  1965.     if (!button) return; // JMC Sanity check when button is removed from toolbar
  1966.     var popupDetected = button.getAttribute("popupDetected");
  1967.  
  1968.     // Get handles to menu checkboxes
  1969.     // Don't need sanity checks for these since they are tied to the button
  1970.     // and that's been checked above
  1971.     var menuItemBlock = document.getElementById("popupblocker-onoff");
  1972.     var menuItemCount = document.getElementById("popupblocker-showcount");
  1973.     var menuItemSound = document.getElementById("popupblocker-playsound");
  1974.  
  1975.     // Don't change icon if the blocked popup icon has not finished showing
  1976.     if (popupDetected.indexOf("false") > -1) {
  1977.         // Check if the value is true, in which case popups are allowed
  1978.         if (popupsAllowed.indexOf("true") > -1) {
  1979.             button.setAttribute("popupblocking","off");
  1980.             button.setAttribute("tooltiptext", "Turn pop-up blocking on");
  1981.             menuItemBlock.setAttribute("label", "Enable pop-up blocker");
  1982.             // DisableSoundCountDisplay
  1983.             // Disable sound/count checkboxes
  1984.         } else {
  1985.             button.setAttribute("popupblocking","on");
  1986.             menuItemBlock.setAttribute("label", "Disable pop-up blocker");
  1987.             button.setAttribute("tooltiptext", "Turn pop-up blocking off");
  1988.             menuItemCount.setAttribute('disabled','false');                // Enable count item
  1989.             menuItemSound.setAttribute('disabled','false');                // Enable sound item
  1990.         }
  1991.     }
  1992.  
  1993.     if (!gPrefService)
  1994.         return;
  1995.  
  1996.     // Pop-up count is a global pref
  1997.     var showCount = gPrefService.getBoolPref("privacy.popups.show_count");
  1998.  
  1999.     // Check if we show count of popups blocked
  2000.     if (showCount) {
  2001.         // Get number of popups blocked
  2002.         var numBlocked = gBrowser.numberBlocked;
  2003.         button.setAttribute("label", " Blocked: "+numBlocked);
  2004.         // Need to set this property so that in browser.css can override
  2005.         // no text in icons mode
  2006.         button.setAttribute("showCount", "true");
  2007.         menuItemCount.setAttribute("checked", "true");
  2008.     } else {
  2009.         // If we don't show count we show a default text if in full or text modes
  2010.         button.setAttribute("showCount", "false");
  2011.         // Get the navbar and check what mode it's in
  2012.  
  2013.         if (popupsAllowed.indexOf("true") > -1) {
  2014.             button.setAttribute("label", " Allowed");
  2015.         }
  2016.         // If popups are not allowed
  2017.         else {
  2018.             button.setAttribute("label", " Blocked");
  2019.         }
  2020.  
  2021.         // Uncheck the show count menu item
  2022.         menuItemCount.setAttribute("checked", "false");
  2023.     }
  2024.  
  2025.     // Pop-up sound is a global pref
  2026.     var playSound = gPrefService.getBoolPref("privacy.popups.sound_enabled");
  2027.  
  2028.     // Update sound menu checkbox
  2029.     if (playSound)
  2030.         menuItemSound.setAttribute("checked", "true");
  2031.     else
  2032.         menuItemSound.setAttribute("checked", "false");
  2033. }
  2034.  
  2035.  
  2036. // MERC - JCH : Handle updating site controls.
  2037. // When the button is clicked or the sound or count menu item is checked the
  2038. // update proceeds as follows: If the site is uncontrollable and not about:blank,
  2039. // then do nothing; if the site is about:blank, update default settings; if the
  2040. // site is either explicitly controlled or a local-file type uri, then update the
  2041. // corresponding SC settings; if the site is controlled by the default settings,
  2042. // then add the site to SCs and update the newly added settings.
  2043. function PBBUpdateSiteControls(controlName)
  2044. {
  2045.     if (!gBrowser)
  2046.         return;
  2047.  
  2048.     // Get current url in proper format
  2049.     var uri = gBrowser.currentURI.spec;
  2050.  
  2051.     if (!sitecontrols)
  2052.         return;
  2053.  
  2054.     // If the site is an illegitimate uncontrollable site, do nothing but return.
  2055.     if ((uri != 'about:blank') && (!sitecontrols.SCSVC.isControllableURI(uri)))
  2056.         return;
  2057.  
  2058.     // Get resource related to uri
  2059.     var siteResource = sitecontrols.SCSVC.getResourceForURI(uri);
  2060.  
  2061.     // If the site is about:blank, modify default settings.
  2062.     if (uri == 'about:blank') {
  2063.         siteResource = sitecontrols.SCSVC.getResourceForURI('');
  2064.     }
  2065.  
  2066.     // Remaining cases are local file, explicitly controlled site,
  2067.     // and the various default site types. If site is controlled by a default setting
  2068.     // it must be added as an explicitly controlled site.
  2069.     if ((uri != 'about:blank') && (siteResource.Value == sitecontrols.SC_VERIFIED_DEFAULT ||
  2070.                                    siteResource.Value == sitecontrols.SC_NOT_VERIFIED_DEFAULT ||
  2071.                                    siteResource.Value == sitecontrols.SC_WARNING_DEFAULT))
  2072.     {
  2073.         var host = sitecontrols.getStrippedHostFromURL(uri);
  2074.         sitecontrols.SCSVC.addControlledSite(host);
  2075.         siteResource = sitecontrols.SCSVC.getResourceForURI(host);
  2076.     }
  2077.  
  2078.     // Get current site control setting
  2079.     var controlValue =  sitecontrols.SCSVC.readSiteControlResource(siteResource, controlName);
  2080.  
  2081.  
  2082.     var invVal;
  2083.     if (controlValue.indexOf("true") > -1) invVal = "false";
  2084.     else invVal = "true";
  2085.  
  2086.     // Assign negation of current control value
  2087.     sitecontrols.SCSVC.updateSiteControlResource(siteResource, controlName, invVal);
  2088. }
  2089.  
  2090. /////////////////////////////////////////////////////////////////////////////////
  2091. //                POPUPBLOCK BUTTON MENU ITEMS FUNCTIONALITY                   //
  2092. /////////////////////////////////////////////////////////////////////////////////
  2093.  
  2094. // MERC - JCH: Popups are about to be allowed so disable showing count and sound
  2095. // in both the pbb drop-down menu and in the options-advanced-browsing
  2096. function DisableSoundCountDisplay() {
  2097.     //dump('DisableSoundCountDisplay()\n');
  2098.  
  2099.     // Get current url in proper format
  2100.     var ctrlSite = GetSiteControlResource();
  2101.  
  2102.     // If site is not controllable we will use default settings for xul
  2103.     if (!ctrlSite)
  2104.     ctrlSite = sitecontrols.SCSVC.getResourceForURI('');
  2105.  
  2106.     // Notation: "rg = range = array"
  2107.     var rgMenuSoundAndCount = new Array('popupblocker-showcount','popupblocker-playsound');
  2108.  
  2109.     // dump("\n####### Well here we are in the zone ######\n");
  2110.     for (var i=0; i<2; i++)
  2111.     {
  2112.         // Disable the menu item
  2113.         menuItem = document.getElementById(rgMenuSoundAndCount[i]);
  2114.         if (menuItem)
  2115.         menuItem.setAttribute('disabled','true');
  2116.     }
  2117. }
  2118.  
  2119.  
  2120. // MERC - JCH : When you click on the pop-up blocking button or the sound or
  2121. // count menu items, you first check if the dialog is supposed to show. It will
  2122. // retrieve the user's decision to change site controls. If the dialog has been
  2123. // disabled, then site controls are changed without prompting.
  2124. function DoPBBAction(event, controlName)
  2125. {
  2126.  
  2127.     //dump('DoPBBAction()\n');
  2128.  
  2129.     // Assume we are going to update site control settings
  2130.     var updateSite = true;
  2131.  
  2132.     if (!gPrefService) {
  2133.         event.preventBubble();
  2134.         return;
  2135.     }
  2136.  
  2137.     // Pop-up count is now a global pref
  2138.     if (controlName == "showBlockedCount") {
  2139.         var showCount = gPrefService.getBoolPref("privacy.popups.show_count");
  2140.         gPrefService.setBoolPref("privacy.popups.show_count", !showCount);
  2141.         SetPopupBlockToggle();
  2142.         event.preventBubble();
  2143.         return;
  2144.     }
  2145.  
  2146.     // Pop-up sound is now a global pref
  2147.     if (controlName == "playBlockedSound") {
  2148.         var playSound = gPrefService.getBoolPref("privacy.popups.sound_enabled");
  2149.         gPrefService.setBoolPref("privacy.popups.sound_enabled", !playSound);
  2150.         SetPopupBlockToggle();
  2151.         event.preventBubble();
  2152.         return;
  2153.     }
  2154.  
  2155.     // Check if we show site controls info dialog and get user's choice if we do
  2156.     if (gPrefService.getBoolPref("show.popupblockbutton.dialog"))
  2157.     {
  2158.         // Get current raw url
  2159.         if (!gBrowser) {
  2160.             event.preventBubble();
  2161.             return;
  2162.         }
  2163.  
  2164.         var uri = gBrowser.currentURI.spec;
  2165.  
  2166.         if (!sitecontrols) {
  2167.             event.preventBubble();
  2168.             return;
  2169.         }
  2170.  
  2171.         var siteString;
  2172.  
  2173.         // Get resource related to uri
  2174.         var site = sitecontrols.SCSVC.getResourceForURI(uri);
  2175.  
  2176.         // Check for about:blank URI
  2177.         if (uri == 'about:blank')
  2178.         {
  2179.             siteString = "Default Settings";
  2180.         }
  2181.         else if (site.Value == sitecontrols.SC_LOCAL)
  2182.         {
  2183.             siteString = "Local File Settings";
  2184.         }
  2185.         // If the site value is null then the site in not controllable
  2186.         else if (!site)
  2187.         {
  2188.             event.preventBubble();
  2189.             return;
  2190.         }
  2191.         // The site is controllable and not a local file, so, since we
  2192.         // are going to add it to SC, show it's stripped domain on the dialog
  2193.         else
  2194.         {
  2195.             siteString = sitecontrols.getStrippedHostFromURL(uri);
  2196.         }
  2197.  
  2198.         // Pass in the site string and the boolean set to update SC.
  2199.         // The boolean may be modified by the user depending on how
  2200.         // they respond to dialog prompt
  2201.         var args = new Object();
  2202.         args.doupdate = updateSite;
  2203.         args.site = siteString;
  2204.  
  2205.         updateSite = ShowPBBInfoDialog(args);
  2206.     }
  2207.  
  2208.     // User wants to change site control settings
  2209.     if (updateSite)
  2210.     {
  2211.         PBBUpdateSiteControls(controlName);
  2212.         SetPopupBlockToggle();
  2213.     }
  2214.  
  2215.     event.preventBubble();
  2216.     return;
  2217. }
  2218.  
  2219.  
  2220. // MERC - JCH: Invoke dialog explaining how to properly change SCs. The user can
  2221. // cancel the action as well as deactivate the dialog.
  2222. function ShowPBBInfoDialog(args)
  2223. {
  2224.  
  2225.     window.openDialog("chrome://browser/content/pbbDecisionDialog.xul",
  2226.     "Decision",
  2227.     "modal,centerscreen,chrome,resizable=no",
  2228.     args);
  2229.  
  2230.     return args.doupdate;
  2231. }
  2232.  
  2233. // MERC - JCH: open list of blocked domains with option to make a controlled site
  2234. function BlockerShowList(event)
  2235. {
  2236.     try {
  2237.         window.openDialog("chrome://browser/content/pageReport.xul", "_blank",
  2238.         "modal,resizable,centerscreen");
  2239.  
  2240.         event.preventBubble();
  2241.         return;
  2242.     } catch(ex) { dump("Exception in browser.js: BlockerShowList\n" + ex + "\n"); }
  2243. }
  2244.  
  2245. // MERC - JCH: open site controls dialog with pertinent site selected
  2246. function BlockerShowSCDialog(event)
  2247. {
  2248.     // not in tabbed mode, ignore this action
  2249.     if (gPrefService.getBoolPref("browser.tabs.autoHide") &&  gBrowser.mTabContainer.childNodes.length < 2)
  2250.         return;
  2251.  
  2252.     // MERC(rpaul) for BLT bug #147538 the scdialog from the popup toolbar menu opens
  2253.     // the sitecontrols the advanced tab of the popup from the tab
  2254.         
  2255.     var myTab = gBrowser.mCurrentTab;
  2256.     
  2257.     // if we're not in tabbed mode, then do nothing
  2258.     if (!myTab) return;
  2259.     
  2260.     var siteControlPopup = document.getElementById('SiteControlsPopup');
  2261.     
  2262.     // set the popup to open the advanced tab when it opens
  2263.     var trustTab = document.getElementById('scp_trustTab');
  2264.     if (trustTab) trustTab.setAttribute('selected', 'false');
  2265.     var advancedTab = document.getElementById('scp_advancedTab');
  2266.     if (advancedTab) advancedTab.setAttribute('selected', 'true');
  2267.     
  2268.     // wrap around a timeout function to avoid conflicting popup focuses
  2269.     if (siteControlPopup) {
  2270.         setTimeout("document.getElementById('SiteControlsPopup').showPopup(gBrowser.mCurrentTab, -1, -1, 'popup', 'bottomleft', 'topleft');",100);
  2271.     }
  2272.     event.preventBubble();
  2273. }
  2274.  
  2275. // MERC - JCH: Zero the popups blocked count
  2276. function ClearPopupCount(event)
  2277. {
  2278.     if (!gBrowser)
  2279.     return;
  2280.     gBrowser.numberBlocked = 0;
  2281.  
  2282.     SetPopupBlockToggle();
  2283.     event.preventBubble();
  2284.     return;
  2285. }
  2286.  
  2287. ////////////////////////////////////////////////////////////////////////////////////
  2288. ////////////////////////////////////////////////////////////////////////////////////
  2289.  
  2290. // MERC (DP): Fired when clear histories button clicked. Will warn the user
  2291. // via a dialog that they are clearing histories.
  2292. function ClearHistoriesButtonClick(event, historyLabel)
  2293. {
  2294.     // Assume we are going to update site control settings
  2295.     var flagval = "true";
  2296.  
  2297.     // Check if we show site controls info dialog
  2298.     if (!gPrefService.getBoolPref("clearhistories.button.dialog"))
  2299.     flagval = ShowClearHistoriesInfoDialog(historyLabel);
  2300.  
  2301.     // User wants to clear histories
  2302.     if (flagval.indexOf("true") > -1) {
  2303.         PrivacyPanel.clearData['history'](false);
  2304.         SetHistoryButton();
  2305.     }
  2306.  
  2307.     event.preventBubble();
  2308.     return;
  2309. }
  2310.  
  2311. // MERC (DP): Invoke dialog explaining that user about to clear histories
  2312. function ShowClearHistoriesInfoDialog(historyLabel)
  2313. {
  2314.     // Pass "doUpdate" into dialog. If it returns 'true' then clear
  2315.     var doUpdate = new String();
  2316.     doUpdate.value = "false";
  2317.  
  2318.     window.openDialog("chrome://browser/content/clearHistoriesDecisionDialog.xul",
  2319.     "Decision",
  2320.     "modal,centerscreen,chrome,resizable=no",
  2321.     doUpdate,
  2322.     historyLabel);
  2323.  
  2324.     return doUpdate.value;
  2325. }
  2326.  
  2327. // MERC - JCH : Update the history button.
  2328. function SetHistoryButton()
  2329. {
  2330.     try {
  2331.         var button = document.getElementById("clearhistories-button");
  2332.         if (!button)
  2333.         return;
  2334.  
  2335.         if (gGlobalHistory == null)
  2336.         return;
  2337.  
  2338.         if (gPrefService == null)
  2339.         return;
  2340.  
  2341.         var isAnonymous = gPrefService.getBoolPref("privacy.anonMode.enabled");
  2342.  
  2343.         var anonMenuItem = document.getElementById("clearHistoryAnonymousMode");
  2344.         anonMenuItem.setAttribute('checked', isAnonymous);
  2345.         if (isAnonymous) {
  2346.             // dump("browser.js SetHistoryButton(): isAnonymous is " +isAnonymous+ "\n");
  2347.             button.setAttribute("historyEmpty", "anon");
  2348.             return;
  2349.         }
  2350.  
  2351.         //dump("browser.js SetHistoryButton(): gGlobalHistory.count is " +gGlobalHistory.count+ "\n");
  2352.  
  2353.         if (gGlobalHistory != null && gGlobalHistory.count == 0) {
  2354.             button.setAttribute("historyEmpty", "true");
  2355.         } else {
  2356.             button.setAttribute("historyEmpty", "false");
  2357.         }
  2358.     } catch(ex) { dump("Exception in browser.js: SetHistoryButton\n" + ex + "\n"); }
  2359. }
  2360.  
  2361. ////////////////////////////////////////////////////////////////////////////////////////////
  2362.  
  2363. //JA ff5->vulp
  2364. function BrowserReload(actionType)
  2365. {
  2366.     const reloadFlags = nsIWebNavigation.LOAD_FLAGS_NONE;
  2367.  
  2368.     // When switching to Gecko, avoid making a new history entry.
  2369.     if (actionType)
  2370.     {
  2371.         switch (actionType)
  2372.         {
  2373.         case "ToTrident":
  2374.             // Not needed yet.
  2375.             break;
  2376.         case "ToGecko":
  2377.             // Rip this out when certain it is not needed.
  2378.             // Also, rip out corresponding code in nsDocShell.cpp.
  2379.             // gPrefService.setBoolPref("navigate.suppresshistory", true);
  2380.             break;
  2381.         }
  2382.     }
  2383.  
  2384.     // MERC (DP): we really only need to call this when the engine is Trident.
  2385.     // if Gecko, it is taken care of in the onLocationChange handler in
  2386.     // tabbrowser.xml
  2387.     try {
  2388.         UpdateSiteControlIcon();
  2389.     } catch (ex) {}
  2390.  
  2391.     return BrowserReloadWithFlags(reloadFlags);
  2392. }
  2393. //JA/>
  2394.  
  2395. // MERC (ccampbell) - command for merged stop-reload-button
  2396. function BrowserStopReload(evt) {
  2397.     var btn = document.getElementById('stop-reload-button');
  2398.     if (!btn)
  2399.     return;
  2400.  
  2401.     if (btn.getAttribute('state') == 'stop')
  2402.     {
  2403.     } // JMC- hackish fix for coming back from customize dialog, loses state
  2404. // Else if (btn.getAttribute('state') == 'reload')
  2405. else // if (btn.getAttribute('state') == 'reload')
  2406. {
  2407.     if (evt.shiftKey) BrowserReloadSkipCache();
  2408. else BrowserReload();
  2409. }
  2410. }
  2411.  
  2412. // MERC (ccampbell) - execute command for overflow toolbar item
  2413. function OverflowMenuCommand(btnId) {
  2414.     var btn = document.getElementById(btnId);
  2415.     if (!btn) return;
  2416.     if (btn.hasAttribute('overflowcommand')) {
  2417.         setTimeout(btn.getAttribute('overflowcommand'), 1);
  2418.     } else if (btn.hasAttribute('oncommand')) {
  2419.         btn.doCommand();
  2420.     } else if (btn.hasAttribute('command')) {
  2421.         var cmd = document.getElementById(btn.getAttribute('command'));
  2422.         cmd.doCommand();
  2423.     } else {
  2424.         dump('NOTHING TO DO FOR OVERFLOW MENU ITEM: '+btnId+'\n');
  2425.     }
  2426. }
  2427.  
  2428. // MERC (rpaul) - update the statusbar icon to reflect which engine we're currently in
  2429. function UpdateStatusBarEngineIcon(tab) {
  2430.     var engineBroadcaster = document.getElementById("currentEngineBroadcaster");
  2431.     var currentEngine;
  2432.  
  2433.     // browser isn't in tabbed mode        
  2434.     if (!gBrowser.mTabbedMode) {
  2435.         var currentTab = gBrowser.mCurrentTab;
  2436.         currentEngine = gBrowser.getBrowserForTab(gBrowser.mCurrentTab).docShell.browserEngine;
  2437.         dump("*** not in tabbed mode: " +  currentEngine + "\n");
  2438.     }
  2439.     
  2440.     // hide the engine icon if the pref isn't set
  2441.     if (!gPrefService.getBoolPref("browser.show_engine_icon")) {
  2442.         engineBroadcaster.setAttribute("collapsed", "true");
  2443.     } else {
  2444.         engineBroadcaster.removeAttribute("collapsed");
  2445.     }
  2446.     
  2447.     // MERC (rpaul)if we have a handle on a tab and we're in tabbed mode, get the current engine
  2448.     // from the tab
  2449.     if (tab && gBrowser.mTabbedMode) {
  2450.         currentEngine = gBrowser.getBrowserForTab(tab).docShell.browserEngine;
  2451.     } else if(gBrowser.mTabbedMode){
  2452.         // uncontrolled site, so disable all UI engine toggling
  2453.         currentEngine = "Gecko";
  2454.         engineBroadcaster.setAttribute("src", "chrome://browser/skin/firefox-dropmarker-16px.png");
  2455.         engineBroadcaster.setAttribute("value", "Gecko");
  2456.     
  2457.         //uncheck "Display Like Internet Explorer" in status bar engine menu
  2458.         document.getElementById('displayLikeIE').removeAttribute('checked');
  2459.         document.getElementById('displayLikeIE').setAttribute('disabled', 'true');
  2460.         
  2461.         // check "Display Like Firefox" in status bar engine menu
  2462.         document.getElementById('displayLikeFirefox').setAttribute('checked', 'true');    
  2463.         document.getElementById('displayLikeFirefox').setAttribute('disabled', 'true');
  2464.         
  2465.         //disable display like firefox and display like IE in View menu
  2466.         // disable "Display like IE in view->rendering engines menu
  2467.         document.getElementById('engineIsIEBroadcaster').setAttribute('disabled', 'true');
  2468.         document.getElementById('engineIsFirefoxBroadcaster').setAttribute('disabled', 'true');
  2469.         //disable "Toggle Rendering enginers in View menu"
  2470.         document.getElementById('viewMenuToggleRenderingEngine').setAttribute('disabled', 'true');
  2471.         
  2472.         return;
  2473.     }
  2474.             
  2475.     if (currentEngine == "Gecko") {
  2476.         engineBroadcaster.setAttribute("src", "chrome://browser/skin/firefox-dropmarker-16px.png");
  2477.         engineBroadcaster.setAttribute("value", "Gecko");
  2478.                 
  2479.         //enable "Toggle Rendering engines in View menu"
  2480.       document.getElementById('viewMenuToggleRenderingEngine').removeAttribute('disabled');    
  2481.                 
  2482.         //uncheck "Display Like Internet Explorer" in status bar engine menu
  2483.         document.getElementById('displayLikeIE').removeAttribute('checked');
  2484.         document.getElementById('displayLikeIE').removeAttribute('disabled');
  2485.                 
  2486.         // check "Display Like Firefox" in status bar engine menu
  2487.         document.getElementById('displayLikeFirefox').setAttribute('checked', 'true');    
  2488.         document.getElementById('displayLikeFirefox').setAttribute('disabled', 'true');
  2489.         
  2490.         // disable "Display like firefox in view->rendering engines menu
  2491.         document.getElementById('engineIsFirefoxBroadcaster').setAttribute('disabled', 'true');
  2492.         document.getElementById('engineIsIEBroadcaster').removeAttribute('disabled');
  2493.                         
  2494.     } else if (currentEngine == "Trident") {    
  2495.         engineBroadcaster.setAttribute("src", "chrome://browser/skin/ie_icon-dropmarker.gif");
  2496.         engineBroadcaster.setAttribute("value", "IE");
  2497.         
  2498.         //enable "Toggle Rendering engines in View menu"
  2499.       document.getElementById('viewMenuToggleRenderingEngine').removeAttribute('disabled');    
  2500.                 
  2501.         //uncheck "Display Like Firefox" in status bar engine menu
  2502.         document.getElementById('displayLikeFirefox').removeAttribute('checked');
  2503.         document.getElementById('displayLikeFirefox').removeAttribute('disabled');
  2504.         
  2505.         // check "Display Like Internet Explorer" in status bar engine menu
  2506.         document.getElementById('displayLikeIE').setAttribute('checked', 'true');
  2507.         document.getElementById('displayLikeIE').setAttribute('disabled', 'true');
  2508.         
  2509.         // disable "Display like IE in view->rendering engines menu
  2510.         document.getElementById('engineIsIEBroadcaster').setAttribute('disabled', 'true');
  2511.         document.getElementById('engineIsFirefoxBroadcaster').removeAttribute('disabled');
  2512.         
  2513.     } else {
  2514.         dump("Unknown engine name: " + currentEngine + "\n");
  2515.     }
  2516. }
  2517.  
  2518. function UpdateStatusbarEngineIconTrident() {
  2519.     var engineBroadcaster = document.getElementById("currentEngineBroadcaster");
  2520.     
  2521.     engineBroadcaster.setAttribute("src", "chrome://browser/skin/ie_icon-dropmarker.gif");
  2522.     engineBroadcaster.setAttribute("value", "IE");
  2523.     
  2524.     //enable "Toggle Rendering engines in View menu"
  2525.   document.getElementById('viewMenuToggleRenderingEngine').removeAttribute('disabled');    
  2526.             
  2527.     //uncheck "Display Like Firefox" in status bar engine menu
  2528.     document.getElementById('displayLikeFirefox').removeAttribute('checked');
  2529.     document.getElementById('displayLikeFirefox').removeAttribute('disabled');
  2530.     
  2531.     // check "Display Like Internet Explorer" in status bar engine menu
  2532.     document.getElementById('displayLikeIE').setAttribute('checked', 'true');
  2533.     document.getElementById('displayLikeIE').setAttribute('disabled', 'true');
  2534.     
  2535.     // disable "Display like IE in view->rendering engines menu
  2536.     document.getElementById('engineIsIEBroadcaster').setAttribute('disabled', 'true');
  2537.     document.getElementById('engineIsFirefoxBroadcaster').removeAttribute('disabled');
  2538. }
  2539.  
  2540. // MERC (DP): populates partner icons (if any) into the status bar
  2541. function UpdateStatusbarPartnerIcons() {
  2542.     var iconContainer = document.getElementById('partner-icons-container');
  2543.  
  2544.     // clear the partner icons
  2545.     while(iconContainer.firstChild) {
  2546.         iconContainer.removeChild(iconContainer.firstChild);
  2547.     }
  2548.     
  2549.     var sc = sitecontrols.SCSVC;
  2550.     var url = gBrowser.getBrowserForTab(gBrowser.mCurrentTab).currentURI.spec;
  2551.     
  2552.     var urlArray;
  2553.     var iconArray;
  2554.     switch(sc.getSiteTrustLevel(url)) {
  2555.         case 0:
  2556.             // whitelisted
  2557.             var whiteListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_WHITELIST_IDX);
  2558.             var urlStr = sc.getSiteTrustProviderURL(whiteListCode);
  2559.             urlArray = urlStr.split('|');
  2560.             var iconStr = sc.getSiteTrustProviderIcon(whiteListCode);
  2561.             iconArray = iconStr.split('|');
  2562.             break;
  2563.         case 2:
  2564.             // phish
  2565.             var phishListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_PHISHLIST_IDX);
  2566.             var urlStr = sc.getSiteTrustProviderURL(phishListCode);
  2567.             urlArray = urlStr.split('|');
  2568.             var iconStr = sc.getSiteTrustProviderIcon(phishListCode);
  2569.             iconArray = iconStr.split('|');
  2570.             break;
  2571.         case 4:
  2572.             // spy
  2573.             var spyListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_SPYLIST_IDX);
  2574.             var urlStr = sc.getSiteTrustProviderURL(spyListCode);
  2575.             urlArray = urlStr.split('|');
  2576.             var iconStr = sc.getSiteTrustProviderIcon(spyListCode);
  2577.             iconArray = iconStr.split('|');
  2578.             break;
  2579.         case 6:
  2580.             var phishListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_PHISHLIST_IDX);
  2581.             var plistStr = sc.getSiteTrustProviderName(phishListCode);
  2582.             var plistArray = plistStr.split('|');
  2583.             var purlStr = sc.getSiteTrustProviderURL(phishListCode);
  2584.             var purlArray = purlStr.split('|');
  2585.             var piconStr = sc.getSiteTrustProviderIcon(phishListCode);
  2586.             var piconArray = piconStr.split('|');
  2587.  
  2588.             var spyListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_SPYLIST_IDX);
  2589.             var slistStr = sc.getSiteTrustProviderName(spyListCode);
  2590.             var slistArray = slistStr.split('|');
  2591.             var surlStr = sc.getSiteTrustProviderURL(spyListCode);
  2592.             var surlArray = surlStr.split('|');
  2593.             var siconStr = sc.getSiteTrustProviderIcon(spyListCode);
  2594.             var siconArray = siconStr.split('|');
  2595.  
  2596.             var combinedURLArray = purlArray;
  2597.             var combinedIconArray = piconArray;
  2598.             var found;
  2599.  
  2600.             for(var arrayItem in slistArray) {
  2601.                 found = false;
  2602.                 for(var k = 0; k < plistArray.length; k++) {
  2603.                     if(slistArray[arrayItem] == plistArray[k]) {
  2604.                         found = true;
  2605.                         break;
  2606.                     }
  2607.                 }
  2608.                 if(!found) {
  2609.                     combinedURLArray.push(surlArray[arrayItem]);
  2610.                     combinedIconArray.push(siconArray[arrayItem]);
  2611.                 }
  2612.             }
  2613.             urlArray = combinedURLArray;
  2614.             iconArray = combinedIconArray;
  2615.             break;
  2616.         case 1:
  2617.         default:
  2618.             // unknown
  2619.     }
  2620.  
  2621.     if(!iconArray || !iconArray.length) {
  2622.         iconContainer.setAttribute('hidden', 'true');
  2623.     } else {
  2624.         iconContainer.removeAttribute('hidden');
  2625.         
  2626.         var iconElem;
  2627.         for(var i = 0; i < iconArray.length; i++) {
  2628.             if(iconArray[i]) {
  2629.                 iconElem = document.createElement("image");
  2630.                 iconElem.setAttribute("src", iconArray[i]);
  2631.                 iconElem.setAttribute("onclick", "loadPartnerPageFromStatusBar('" + urlArray[i] + "');");
  2632.                 iconElem.setAttribute("style", "padding-left: 4px;");
  2633.                 iconContainer.appendChild(iconElem);
  2634.             }
  2635.         }
  2636.     }
  2637. }
  2638.  
  2639. function loadPartnerPageFromStatusBar(url) {
  2640.     var trustTab = gBrowser.addTabAt(url);
  2641.     if (!gPrefService.getBoolPref("browser.tabs.loadInBackground"))
  2642.         gBrowser.selectedTab = trustTab;
  2643. }
  2644.  
  2645.  
  2646. // MERC (DP) - update the icon to match security level AND browser engine
  2647. function UpdateSiteControlIcon(tab)
  2648. {
  2649.     //dump('UpdateSiteControlIcon()\n');
  2650.  
  2651.     // if no tab specified, use the current tab
  2652.     if (!tab) {
  2653.         tab = gBrowser.mCurrentTab;
  2654.     }
  2655.     var tabWindow = gBrowser.getBrowserForTab(tab);
  2656.     var url = tabWindow.currentURI.spec;
  2657.     var menubutton = document.getAnonymousElementByAttribute(tab, 'anonid', 'menubutton');
  2658.  
  2659.     // MERC - JCH: Sanity check
  2660.     if (!menubutton)
  2661.         return;
  2662.  
  2663.     if (!sitecontrols.SCSVC.isControllableURI(url)) {
  2664.         menubutton.setAttribute('hidden', 'true');
  2665.     } else {
  2666.         menubutton.removeAttribute('hidden');
  2667.  
  2668.         var site;
  2669.         if(url == 'about:blank') {
  2670.             site = sitecontrols.SCSVC.getResourceForURI('');
  2671.         } else {
  2672.             site = sitecontrols.SCSVC.getResourceForURI(url);
  2673.         }
  2674.         // MERC - JCH: 'site' is already a resource
  2675.         // site = site.QueryInterface(Components.interfaces.nsIRDFResource);
  2676.  
  2677.         // if host is not controlled (default), change icon accordingly
  2678.         //  MERC - JCH: Three possible default settings now
  2679.         // if (site.Value == sitecontrols.DEFAULT_SITE)
  2680.         if ((site.Value == sitecontrols.SC_VERIFIED_DEFAULT) ||
  2681.             (site.Value == sitecontrols.SC_NOT_VERIFIED_DEFAULT) ||
  2682.             (site.Value == sitecontrols.SC_WARNING_DEFAULT))
  2683.         {
  2684.             menubutton.setAttribute("defaultSC", "true");
  2685.         }
  2686.         else
  2687.             menubutton.removeAttribute("defaultSC");
  2688.  
  2689.         var trustLevel = 1;
  2690.         try {
  2691.               // MERC - JCH: Pass host string to getSiteTrustLevel()
  2692.             if (tabWindow.currentURI.spec) {
  2693.                 trustLevel = sitecontrols.SCSVC.getSiteTrustLevel(tabWindow.currentURI.spec);
  2694.             }
  2695.         } catch (ex) {
  2696.             dump("Caught exception : " + ex + "\n\n");
  2697.         }
  2698.         menubutton.setAttribute("trustLevel", trustLevel);
  2699.  
  2700.         // if trust settings is disabled
  2701.         var securityLevel;
  2702.         if(trustLevel == -1 && !sitecontrols.SCSVC.isControlledSite(tabWindow.currentURI.host)) {
  2703.             securityLevel = gPrefService.getCharPref("trustsettings.default");
  2704.         } else {
  2705.             securityLevel = sitecontrols.SCSVC.readSiteControlResource(site, 'securityLevel');
  2706.         }
  2707.         menubutton.setAttribute("browserSetting", securityLevel);
  2708.  
  2709.         // update the down menubutton icon according to what browser engine is set
  2710.         var currentEngine = gBrowser.getBrowserForTab(tab).docShell.browserEngine;
  2711.  
  2712.         /*
  2713.         dump('********** SECURITY LEVEL ***************\n');
  2714.         dump('Host: ' + site.Value + ' - Level: ' + securityLevel + '\n');
  2715.         dump('********** Current Engine ***************\n');
  2716.         dump('engine: ' + currentEngine + '\n');
  2717.         dump('*****************************************\n');
  2718.         */
  2719.         
  2720.         // MERC (rpaul) update the statusbar engine icon
  2721.         UpdateStatusBarEngineIcon(tab);
  2722.  
  2723.         if (currentEngine == "Gecko") {
  2724.             menubutton.setAttribute("engine", "Gecko");
  2725.         } else if (currentEngine == "Trident") {
  2726.             menubutton.setAttribute("engine", "Trident");
  2727.         } else {
  2728.             dump("Unknown engine name: " + currentEngine + "\n");
  2729.         }
  2730.     }
  2731. }
  2732.  
  2733. /*
  2734. engine    ActiveX     Javascript     Java        securityLevel
  2735. weight  8         4           2              1
  2736. Gecko     false       false          false       High
  2737. Gecko     false       false          true        Medium
  2738. Gecko     false       true           false       Medium
  2739. Gecko     false       true           true        Medium
  2740. Gecko     true        false          false       High
  2741. Gecko     true        false          true        Medium
  2742. Gecko     true        true           false       Medium
  2743. Gecko     true        true           true        Medium
  2744. Trident   false       false          false       High
  2745. Trident   false       false          true        Medium
  2746. Trident   false       true           false       Medium
  2747. Trident   false       true           true        Medium
  2748. Trident   true        false          false       Low
  2749. Trident   true        false          true        Low
  2750. Trident   true        true           false       Low
  2751. Trident   true        true           true        Low
  2752.  
  2753.  
  2754. */
  2755.  
  2756. // ********* if you change this var, you need to change in pref-sitecontrols.js as well
  2757. var gSecurityLevels= new Array('High','Medium','Medium','Medium','High','Medium','Medium','Medium', 'High','Medium', 'Medium', 'Medium', 'Low', 'Low', 'Low', 'Low');
  2758. function updateSCSecurityLevel()
  2759. {
  2760.     var wtEngine, wtActiveX, wtJS, wtJava;
  2761.  
  2762.     // Get RDF resource for the controlled site
  2763.     // *** at this point host should always be controlled since it gets added when
  2764.     // you select activex, java, js from the dropdown menu
  2765.     var site = GetSiteControlResource();
  2766.  
  2767.     var displayEngine = getWebNavigation().browserEngine;
  2768.     var enableActiveX = sitecontrols.SCSVC.readSiteControlResource(site, 'enableActiveX');
  2769.     var enableJava = sitecontrols.SCSVC.readSiteControlResource(site, 'enableJava');
  2770.     var enableJavaScript = sitecontrols.SCSVC.readSiteControlResource(site, 'enableJavaScript');
  2771.  
  2772.     var sec;
  2773.     if (displayEngine == 'Trident')
  2774.     wtEngine=8;
  2775. else
  2776.     wtEngine=0;
  2777.  
  2778.     if(enableActiveX == 'true')
  2779.     wtActiveX=4;
  2780. else
  2781.     wtActiveX=0;
  2782.  
  2783.     if(enableJavaScript == 'true')
  2784.     wtJS=2;
  2785. else
  2786.     wtJS=0;
  2787.  
  2788.     if(enableJava == 'true')
  2789.     wtJava=1;
  2790. else
  2791.     wtJava=0;
  2792.  
  2793.     var idx = wtEngine + wtActiveX + wtJS + wtJava;
  2794.     var securityLevel = gSecurityLevels[idx];
  2795.  
  2796.     /*
  2797.     dump('************** updateSCSecurityLevel() *******************\n');
  2798.     dump('host: ' + host + '\n');
  2799.     dump('displayEngine: ' + displayEngine + '\n');
  2800.     dump('enableActiveX: ' + enableActiveX + '\n');
  2801.     dump('enableJava: ' + enableJava + '\n');
  2802.     dump('enableJavaScript: ' + enableJavaScript + '\n');
  2803.     dump('securityLevel: ' + securityLevel + '\n');
  2804.     dump('idx: ' + idx + '\n');
  2805.     dump('**********************************************************\n');
  2806.     */
  2807.  
  2808.     sitecontrols.SCSVC.updateSiteControlResource(site, 'securityLevel', securityLevel);
  2809.     // sitecontrols.SCSVC.writeSiteControls();
  2810. }
  2811.  
  2812. function BrowserReloadSkipCache()
  2813. {
  2814.     // Bypass proxy and cache.
  2815.     const reloadFlags = nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  2816.     return BrowserReloadWithFlags(reloadFlags);
  2817. }
  2818.  
  2819. function BrowserHome(forceNewTab)
  2820. {
  2821.     var homePage = gHomeButton.getHomePage();
  2822.     //JA ff5->vulp loadOneOrMoreURIs(homePage);
  2823.     // if overwrite: load tabs left to right - add tabs as needed
  2824.     // if new: add tabs starting at position specified browser.tabs.newTabLocation
  2825.     if(!forceNewTab && gPrefService.getCharPref("browser.tabs.homepage.open") == 'overwrite') {
  2826.         loadOneOrMoreURIsOnHomePageClick(homePage);
  2827.     } else { // else == 'new'
  2828.         addOneOrMoreURIs(homePage);
  2829.     }//JA/>
  2830. }
  2831.  
  2832. function loadOneOrMoreURIsOnHomePageClick(aURIString)
  2833. {
  2834.     if (aURIString.indexOf("|") != -1) {
  2835.         var i;
  2836.  
  2837.         // get browser tabs
  2838.         var browserTabs = gBrowser.mTabContainer.childNodes;
  2839.  
  2840.         // get URLs
  2841.         var urls = aURIString.split("|");
  2842.  
  2843.         // 3 cases:
  2844.         if (browserTabs.length < urls.length) {
  2845.             // a) if # tabs < # URLs
  2846.             for (i = 0; i < browserTabs.length; i++) {
  2847.                 gBrowser.getBrowserForTab(browserTabs[i]).loadURI(urls[i]);
  2848.             }
  2849.             for (i = browserTabs.length; i < urls.length; i++) {
  2850.                 gBrowser.addTab(urls[i]);
  2851.             }
  2852.         } else if (browserTabs.length > urls.length) {
  2853.             // b) if # tabs > # URLs
  2854.             for (i = 0; i < urls.length; i++) {
  2855.                 gBrowser.getBrowserForTab(browserTabs[i]).loadURI(urls[i]);
  2856.             }
  2857.         } else {
  2858.             // c) if # tabs == # URLs
  2859.             for (i = 0; i < urls.length; i++) {
  2860.                 gBrowser.getBrowserForTab(browserTabs[i]).loadURI(urls[i]);
  2861.             }
  2862.         }
  2863.  
  2864.         // set focus to the first tab
  2865.         gBrowser.selectedTab = browserTabs[0];
  2866.  
  2867.     } else {
  2868.         // only one URL specifed
  2869.         loadURI(aURIString, null, null);
  2870.     }
  2871.  
  2872.     // update the tab chrome
  2873.     gBrowser.updateChromeWhenLastTab();
  2874. }
  2875.  
  2876. function closeAllTabsFromSameSite() {
  2877.     var browserPanels = gBrowser.mPanelContainer.childNodes;
  2878.  
  2879.     for(var i = 0; i < browserPanels.length; i++) {
  2880.         // dump("*** URL: " + browserPanels[i].getCurrentURI() + "\n");
  2881.     }
  2882. }
  2883.  
  2884. // MERC (DP): adds tabs starting at browser.tabs.newTabLocation and subsequently
  2885. // to the right. select the first tab added after.
  2886. function addOneOrMoreURIs(aURIString)
  2887. {
  2888.     var savedSelectedTab = gBrowser.selectedTab;
  2889.     var firstAdded;
  2890.  
  2891.     if (aURIString.indexOf("|") != -1) {
  2892.         var urls = aURIString.split("|");
  2893.         gBrowser.selectedTab = gBrowser.addTabAt(urls[0]);
  2894.  
  2895.         // save the first tab add, so that we can focus it at the end
  2896.         firstAdded = gBrowser.selectedTab;
  2897.  
  2898.         for (var i = 1; i < urls.length; ++i)
  2899.         gBrowser.selectedTab = gBrowser.addTabAt(urls[i], 'right');
  2900.     }
  2901. else {
  2902.     firstAdded = gBrowser.addTabAt(aURIString);
  2903. }
  2904.  
  2905. /* comment this out because we always want to focus the first tab
  2906. if(gPrefService.getBoolPref("browser.tabs.loadInBackground")) {
  2907. // focus the tab active before addition
  2908. gBrowser.selectedTab = savedSelectedTab;
  2909. } else {
  2910. // focus the first added tab
  2911. gBrowser.selectedTab = firstAdded;
  2912. }
  2913. */
  2914.  
  2915. // focus the first added tab
  2916. gBrowser.selectedTab = firstAdded;
  2917. }
  2918.  
  2919.  
  2920. function BrowserHomeClick(aEvent)
  2921. {
  2922.     if (aEvent.button == 2) // right-click: do nothing
  2923.         return;
  2924.  
  2925.     var homePage = gHomeButton.getHomePage();
  2926.     var where = whereToOpenLink(aEvent);
  2927.     var urls;
  2928.  
  2929.     // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages
  2930.     switch (where) {
  2931.     case "save":
  2932.         urls = homePage.split("|");
  2933.         saveURL(urls[0], null, null, true);  // only save the first page
  2934.         break;
  2935.     case "current":
  2936.         loadOneOrMoreURIs(homePage);
  2937.         break;
  2938.     case "tabshifted":
  2939.     case "tab":
  2940.         urls = homePage.split("|");
  2941.         var firstTabAdded = gBrowser.addTab(urls[0]);
  2942.         for (var i = 1; i < urls.length; ++i)
  2943.             gBrowser.addTab(urls[i]);
  2944.         if ((where == "tab") ^ getBoolPref("browser.tabs.loadBookmarksInBackground", false)) {
  2945.             gBrowser.selectedTab = firstTabAdded;
  2946.             _content.focus();
  2947.             // JMC - URLBar focus bug, workin on it
  2948.             dump ("Just focused the _content, which is " + _content + "\n");
  2949.         }
  2950.         break;
  2951.     case "window":
  2952.         OpenBrowserWindow();
  2953.         break;
  2954.     }
  2955. }
  2956.  
  2957. function loadOneOrMoreURIs(aURIString)
  2958. {
  2959.     var urls = aURIString.split("|");
  2960.     loadURI(urls[0]);
  2961.     for (var i = 1; i < urls.length; ++i)
  2962.         gBrowser.addTab(urls[i]);
  2963. }
  2964.  
  2965. function constructGoMenuItem(goMenu, beforeItem, url, title)
  2966. {
  2967.     var menuitem = document.createElementNS(kXULNS, "menuitem");
  2968.     menuitem.setAttribute("statustext", url);
  2969.     menuitem.setAttribute("label", title);
  2970.     goMenu.insertBefore(menuitem, beforeItem);
  2971.     return menuitem;
  2972. }
  2973.  
  2974. function onGoMenuHidden()
  2975. {
  2976.     setTimeout(destroyGoMenuItems, 0, document.getElementById('goPopup'));
  2977. }
  2978.  
  2979. function destroyGoMenuItems(goMenu) {
  2980.     var startSeparator = document.getElementById("startHistorySeparator");
  2981.     var endSeparator = document.getElementById("endHistorySeparator");
  2982.     endSeparator.hidden = true;
  2983.  
  2984.     // Destroy the items.
  2985.     var destroy = false;
  2986.     for (var i = 0; i < goMenu.childNodes.length; i++) {
  2987.         var item = goMenu.childNodes[i];
  2988.         if (item == endSeparator)
  2989.             break;
  2990.  
  2991.         if (destroy) {
  2992.             i--;
  2993.             goMenu.removeChild(item);
  2994.         }
  2995.  
  2996.         if (item == startSeparator)
  2997.             destroy = true;
  2998.     }
  2999. }
  3000.  
  3001. function updateGoMenu(goMenu)
  3002. {
  3003.     // In case the timer didn't fire.
  3004.     destroyGoMenuItems(goMenu);
  3005.  
  3006.     var history = document.getElementById("hiddenHistoryTree");
  3007.  
  3008.     if (history.hidden) {
  3009.         history.hidden = false;
  3010.         var globalHistory = Components.classes["@mozilla.org/browser/global-history;2"]
  3011.                                       .getService(Components.interfaces.nsIRDFDataSource);
  3012.         history.database.AddDataSource(globalHistory);
  3013.     }
  3014.  
  3015.     if (!history.ref)
  3016.         history.ref = "NC:HistoryRoot";
  3017.  
  3018.     var count = history.treeBoxObject.view.rowCount;
  3019.     if (count > 10)
  3020.         count = 10;
  3021.  
  3022.     if (count == 0)
  3023.         return;
  3024.  
  3025.     const NC_NS     = "http://home.netscape.com/NC-rdf#";
  3026.  
  3027.     if (!gRDF)
  3028.         gRDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]
  3029.                          .getService(Components.interfaces.nsIRDFService);
  3030.  
  3031.     var builder = history.builder.QueryInterface(Components.interfaces.nsIXULTreeBuilder);
  3032.  
  3033.     var beforeItem = document.getElementById("endHistorySeparator");
  3034.  
  3035.     var nameResource = gRDF.GetResource(NC_NS + "Name");
  3036.  
  3037.     var endSep = beforeItem;
  3038.     var showSep = false;
  3039.  
  3040.     for (var i = count-1; i >= 0; i--) {
  3041.         var res = builder.getResourceAtIndex(i);
  3042.         var url = res.Value;
  3043.         var titleRes = history.database.GetTarget(res, nameResource, true);
  3044.         if (!titleRes)
  3045.             continue;
  3046.  
  3047.         showSep = true;
  3048.         var titleLiteral = titleRes.QueryInterface(Components.interfaces.nsIRDFLiteral);
  3049.         beforeItem = constructGoMenuItem(goMenu, beforeItem, url, titleLiteral.Value);
  3050.     }
  3051.  
  3052.     if (showSep)
  3053.         endSep.hidden = false;
  3054. }
  3055.  
  3056. // MERC - JCH : Add one site to bookmarks. Referred to in browser-context.inc,
  3057. // browser-sets.inc, browser.xul, tabbox.xml, and tabbrowser.xml.
  3058. function bookmarkPage(aBrowser, aIsWebPanel)
  3059. {
  3060.     addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel, false);
  3061. }
  3062.  
  3063. function bookmarkPageFromMultibar(aBrowser, aIsWebPanel)
  3064. {
  3065.     addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel, true);
  3066. }
  3067.  
  3068. // MERC - JCH: Add all the current tabs to bookmarks.
  3069. function bookmarkAllTabs(aBrowser, isMultibarButton, aIsWebPanel)
  3070. {
  3071.     const browsers = aBrowser.browsers;
  3072.     if (browsers && browsers.length > 1)
  3073.         addBookmarkForTabBrowser(aBrowser, isMultibarButton);
  3074.     else addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel, isMultibarButton);
  3075. }
  3076.  
  3077.  
  3078. function addBookmarkAs(aBrowser, aIsWebPanel, bTabGroup)
  3079. {
  3080.     const browsers = aBrowser.browsers;
  3081.     if (browsers && browsers.length > 1)
  3082.     {
  3083.         if (bTabGroup)
  3084.         {
  3085.             bookmarkAllTabs(aBrowser, true, aIsWebPanel);
  3086.         } else {
  3087.             addBookmarkForTabBrowser(aBrowser);
  3088.         }
  3089.     } else {
  3090.         addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel);
  3091.     }
  3092. }
  3093.  
  3094. function addBookmarkForTabBrowser(aTabBrowser, aSelect)
  3095. {
  3096.     var tabsInfo = [];
  3097.     var currentTabInfo = { name: "", url: "", charset: null };
  3098.  
  3099.     const activeBrowser = aTabBrowser.selectedBrowser;
  3100.     const browsers = aTabBrowser.browsers;
  3101.     for (var i = 0; i < browsers.length; ++i) {
  3102.         var webNav = browsers[i].webNavigation;
  3103.         var url = webNav.currentURI.spec;
  3104.         var name = "";
  3105.         var charSet;
  3106.         try {
  3107.             var doc = webNav.document;
  3108.             name = doc.title || url;
  3109.             charSet = doc.characterSet;
  3110.         } catch (e) {
  3111.             name = url;
  3112.         }
  3113.         tabsInfo[i] = { name: name, url: url, charset: charSet };
  3114.         if (browsers[i] == activeBrowser)
  3115.             currentTabInfo = tabsInfo[i];
  3116.     }
  3117.  
  3118.     openDialog( "chrome://browser/content/bookmarks/addBookmark2.xul",
  3119.                 "",
  3120.                 "centerscreen,chrome,dialog,resizable,dependent",
  3121.                 currentTabInfo.name,
  3122.                 currentTabInfo.url,
  3123.                 null,
  3124.                 currentTabInfo.charset,
  3125.                 "addGroup" + (aSelect ? ",group" : ""),
  3126.                 tabsInfo,
  3127.                 null, null, null, null, null, aSelect);
  3128. }
  3129.  
  3130. function addBookmarkForBrowser(aDocShell, aIsWebPanel, cmdFromMultibar)
  3131. {
  3132.     // Bug 52536: We obtain the URL and title from the nsIWebNavigation
  3133.     // associated with a <browser/> rather than from a DOMWindow.
  3134.     // This is because when a full page plugin is loaded, there is
  3135.     // no DOMWindow (?) but information about the loaded document
  3136.     // may still be obtained from the webNavigation.
  3137.  
  3138.     var url = aDocShell.currentURI.spec;
  3139.     var title, charSet = null;
  3140.     try {
  3141.         title = aDocShell.document.title || url;
  3142.         charSet = aDocShell.document.characterSet;
  3143.     }
  3144.     catch (e) {
  3145.         title = url;
  3146.     }
  3147.     if (cmdFromMultibar) BookmarksUtils.addBookmarkFromMultibar(url, title, charSet, aIsWebPanel);
  3148.     else BookmarksUtils.addBookmark(url, title, charSet, aIsWebPanel);
  3149. }
  3150.  
  3151. // MERC (DP): this function is only called from inside tabbrowser.  It is needed
  3152. // for the case when you add a bookmark using the tab context menu from a
  3153. // non-active tab.
  3154. function bookmarkPageFromTabRightClick()
  3155. {
  3156.     var uri = gBrowser.getBrowserForTab(gBrowser.mContextTab).currentURI.spec;
  3157.     var title = gBrowser.mContextTab.label;
  3158.     
  3159.     BookmarksUtils.addBookmark(uri, title);
  3160. }
  3161.  
  3162. function openLocation()
  3163. {
  3164.     if (gURLBar && !gURLBar.parentNode.parentNode.collapsed) {
  3165.         gURLBar.focus();
  3166.         gURLBar.select();
  3167.     }
  3168. else {
  3169.     openDialog("chrome://browser/content/openLocation.xul", "_blank", "chrome,modal,titlebar", window);
  3170. }
  3171. }
  3172.  
  3173. function BrowserOpenTab()
  3174. {
  3175.     gBrowser.selectedTab = gBrowser.addTabAt('about:blank');
  3176.         
  3177.     // MERC (rpaul) update the current engine broadcaster for the statusbar
  3178.     // blank tabs are by default Gecko
  3179.     UpdateStatusBarEngineIcon();    
  3180.     
  3181.     if (gURLBar)
  3182.         setTimeout(function() { gURLBar.focus(); }, 0);
  3183. }
  3184.  
  3185. function BrowserNetscapeTab()
  3186. {
  3187.     var url;
  3188.     var pref = Components.classes["@mozilla.org/preferences-service;1"]
  3189.                          .getService(Components.interfaces.nsIPrefBranch);
  3190.     try {
  3191.         url = gPrefService.getComplexValue("browser.netscape.homepage",
  3192.                                            Components.interfaces.nsIPrefLocalizedString).data;
  3193.     } catch(e) {dump ("Caught Exception: " + e + "\n"); }
  3194.  
  3195.     gBrowser.selectedTab = gBrowser.addTabAt(url);
  3196. }
  3197.  
  3198. //<JA ff5->vulp
  3199. var gCurrentDocCharset = null;
  3200.  
  3201. function BrowserStoreTabCharset()
  3202. {
  3203.     gCurrentDocCharset = window._content.document.characterSet;
  3204. }
  3205.  
  3206. function BrowserOpenPrefTab()
  3207. {
  3208.     gBrowser.selectedTab = gBrowser.addPrefTab();
  3209. }
  3210.  
  3211. // MERC (DP)
  3212. function BrowserOpenNewCurrentTab() {
  3213.     currentTab = gBrowser.mCurrentTab;
  3214.     var curTabBrowser=gBrowser.getBrowserForTab(currentTab);
  3215.     var sHistory=curTabBrowser.sessionHistory;
  3216.     gBrowser.selectedTab = gBrowser.addTabAtWithFlag(0,gBrowser.getBrowserForTab(currentTab).currentURI.spec);
  3217.     var newTabBrowser=gBrowser.getBrowserForTab(gBrowser.selectedTab);
  3218.     newTabBrowser.sessionHistory.appendFrom(sHistory);
  3219. }//JA/>
  3220.  
  3221. /* Called from the openLocation dialog. This allows that dialog to instruct
  3222. its opener to open a new window and then step completely out of the way.
  3223. Anything less byzantine is causing horrible crashes, rather believably,
  3224. though oddly only on Linux. */
  3225. function delayedOpenWindow(chrome,flags,url)
  3226. {
  3227.     // The other way to use setTimeout,
  3228.     // setTimeout(openDialog, 10, chrome, "_blank", flags, url),
  3229.     // doesn't work here.  The extra "magic" extra argument setTimeout adds to
  3230.     // the callback function would confuse prepareForStartup() by making
  3231.     // window.arguments[1] be an integer instead of null.
  3232.     setTimeout(function() { openDialog(chrome, "_blank", flags, url); }, 10);
  3233. }
  3234.  
  3235. /* Required because the tab needs time to set up its content viewers and get the load of
  3236. the URI kicked off before becoming the active content area. */
  3237. function delayedOpenTab(url)
  3238. {
  3239.     setTimeout(function(aTabElt) { gBrowser.selectedTab = aTabElt; }, 0, gBrowser.addTabAt(url));
  3240. }
  3241.  
  3242. function BrowserOpenFileWindow()
  3243. {
  3244.     // Get filepicker component.
  3245.     try {
  3246.         const nsIFilePicker = Components.interfaces.nsIFilePicker;
  3247.         var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  3248.         fp.init(window, gNavigatorBundle.getString("openFile"), nsIFilePicker.modeOpen);
  3249.         fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText | nsIFilePicker.filterImages |
  3250.         nsIFilePicker.filterXML | nsIFilePicker.filterHTML);
  3251.  
  3252.         if (fp.show() == nsIFilePicker.returnOK) {
  3253.             // MERC (DP): respect local file open pref
  3254.             var openPref = gPrefService.getCharPref("browser.tabs.localfile.open");
  3255.             if (openPref == 'overwrite') {
  3256.                 openTopWin(fp.fileURL.spec);
  3257.             } else {
  3258.                 // dump("Opening file: " + fp.fileURL.spec + " with addTabAt()\n");
  3259.                 var t = gBrowser.addTabAt(fp.fileURL.spec);
  3260.                 if(!gPrefService.getBoolPref("browser.tabs.loadInBackground")) {
  3261.                     gBrowser.selectedTab = t;
  3262.                 }    
  3263.             }
  3264.             // END MERC
  3265.  
  3266.         }
  3267.     } catch (ex) {
  3268.     }
  3269. }
  3270.  
  3271. function BrowserCloseCurrentTab()
  3272. {
  3273.     setTimeout("gBrowser.removeCurrentTab();", 10);
  3274. }
  3275.  
  3276. function BrowserDelayRemoveAllTabsBut()
  3277. {
  3278.     setTimeout("gBrowser.removeAllTabsBut(gBrowser.mCurrentTab);", 10 );
  3279. }
  3280.  
  3281. function BrowserDelayCloseAllTabsToLeft()
  3282. {
  3283.     setTimeout("gBrowser.closeAllTabsToLeft(gBrowser.mContextTab);", 10 );
  3284. }
  3285.  
  3286. function BrowserDelayCloseAllTabsToRight()
  3287. {
  3288.     setTimeout("gBrowser.closeAllTabsToRight(gBrowser.mContextTab);", 10 );
  3289. }
  3290.  
  3291. function BrowserDelayCloseAllBlankTabs()
  3292. {
  3293.     setTimeout("gBrowser.closeAllBlankTabs();", 10 );
  3294. }
  3295.  
  3296. function DelayCloseAllTabsFromSameSite()
  3297. {
  3298.     setTimeout("gBrowser.closeAllTabsFromSameSite(gBrowser.mContextTab);", 10 );
  3299. }
  3300.  
  3301. function DelayCloseAllTabsExceptFromSameSite()
  3302. {
  3303.     setTimeout("gBrowser.closeAllTabsExceptFromSameSite(gBrowser.mContextTab);", 10 );
  3304. }
  3305.  
  3306. function BrowserCloseTabOrWindow()
  3307. {
  3308.     //dump("\nJA~~~~~~~~~~~~~:BrowserCloseThisTabOrWindow: hpSomeDoc\n");
  3309.     if (gBrowser.localName == 'tabbrowser' && gBrowser.tabContainer.childNodes.length > 1)
  3310.     { // Just close up a tab.
  3311.         gBrowser.removeCurrentTab();
  3312.         return;
  3313.     }
  3314.  
  3315.     BrowserCloseWindow();
  3316. }
  3317.  
  3318. //JA
  3319. function BrowserGetTabsCount()
  3320. {
  3321.     return gBrowser.tabContainer.childNodes.length;
  3322. }
  3323.  
  3324. function BrowserCloseThisTabOrWindow(hpSomeDoc)
  3325. {
  3326.     //dump("\nJA~~~~~~~~~~~~~:BrowserCloseThisTabOrWindow: hpSomeDoc ="+hpSomeDoc+"\n");
  3327.     if(!hpSomeDoc)
  3328.         return false;//err
  3329.     var cnTabs = gBrowser.tabContainer.childNodes;
  3330.     var numtabs = cnTabs.length;
  3331.     if (numtabs>1)
  3332.     {
  3333.         for (var i = 0; i < numtabs; ++i)
  3334.         {
  3335.             var doc = gBrowser.getBrowserForTab(cnTabs[i]).contentDocument;
  3336.             if (doc == hpSomeDoc)
  3337.             {    //dump("!!!!!~~~~~~~~~~~~~~Found in tab# "+i+"\n");
  3338.                 cnTabs[i].isClosing = true;
  3339.                 setTimeout(function(n){ gBrowser.removeTab(gBrowser.tabContainer.childNodes[n]); }, 0, i);
  3340.                 //gBrowser.removeTab(cnTabs[i]);crashes plugin!
  3341.                 return true;
  3342.             }
  3343.         }
  3344.     }
  3345.     else if(numtabs ==1 && hpSomeDoc == gBrowser.getBrowserForTab(cnTabs[0]).contentDocument)
  3346.     {
  3347.         //dump("~~~~~~~~~~~~~~~~Found in the only tab!\n\n");
  3348.         setTimeout("BrowserCloseWindow()");
  3349.         return true;
  3350.     }
  3351.  
  3352.     //dump("~~~~~~~~~~Couldn't find hpSomeDoc!\n\n");
  3353.     return false;
  3354. }
  3355. //end JA
  3356.  
  3357. function BrowserTryToCloseWindow()
  3358. {
  3359.     //give tryToClose a chance to veto if it is defined
  3360.     if (typeof(window.tryToClose) != "function" || window.tryToClose())
  3361.     BrowserCloseWindow();
  3362. }
  3363.  
  3364. function BrowserCloseWindow()
  3365. {
  3366.     // This code replicates stuff in Shutdown().  It is here because
  3367.     // window.screenX and window.screenY have real values.  We need
  3368.     // to fix this eventually but by replicating the code here, we
  3369.     // provide a means of saving position (it just requires that the
  3370.     // user close the window via File->Close (vs. close box).
  3371.  
  3372.     // Get the current window position/size.
  3373.     var x = window.screenX;
  3374.     var y = window.screenY;
  3375.     var h = window.outerHeight;
  3376.     var w = window.outerWidth;
  3377.  
  3378.     // Store these into the window attributes (for persistence).
  3379.     var win = document.getElementById( "main-window" );
  3380.     win.setAttribute( "x", x );
  3381.     win.setAttribute( "y", y );
  3382.     win.setAttribute( "height", h );
  3383.     win.setAttribute( "width", w );
  3384.  
  3385.     closeWindow(true);
  3386. }
  3387.  
  3388.  
  3389. function loadURI(uri, referrer, postData)
  3390. {
  3391.  
  3392.     // dump('************ loadURI('+uri+') *******************\n');
  3393.     var docshell = getWebNavigation();
  3394.     var hpDoc;
  3395.  
  3396.     if (docshell.browserEngine == 'Trident')
  3397.     hpDoc = getTridentDocument();
  3398.  
  3399.     //JA if we have Trident running, check if we have to switch to Gecko, otherwise
  3400.     //JA decision about engine is made in nsContenDLF.cpp!
  3401.     if (hpDoc)
  3402.     {
  3403.         var sc = sitecontrols.SCSVC;
  3404.         // this will put a http:// in front of the uri if needed
  3405.         if (!gURIFixup)
  3406.             gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
  3407.                                   .getService(Components.interfaces.nsIURIFixup);
  3408.         
  3409.         var urispec;
  3410.         if (!uri || (uri == '')) urispec = 'about:blank';
  3411.         else urispec = gURIFixup.createFixupURI(uri, 0).spec;
  3412.  
  3413.         if ((urispec != 'about:blank') && (!sc.isControllableURI(urispec))) {
  3414.             // Generally speaking, for non-controllable URIs we want to force
  3415.             // the engine into Gecko...
  3416.             docshell.browserEngine = 'Gecko';
  3417.         } else {
  3418.             // At this point we know that the URI is either controllable or else
  3419.             // is 'about:blank', so the engine to use will be dictated by
  3420.             // Site Controls
  3421.             var site;
  3422.             if (uri == 'about:blank') {
  3423.                 // We will treat this as if it's a DEFAULT site
  3424.                 // This should be SiteControls:Default resource
  3425.                 site = sc.getResourceForURI('');
  3426.             }
  3427.             else
  3428.                 site = sc.getResourceForURI(uri);
  3429.  
  3430.             docshell.browserEngine = sc.readSiteControlResource(site, "displayEngine");
  3431.         
  3432.         }
  3433.     } 
  3434.     
  3435.     // Check current engine
  3436.     try {
  3437.         if (docshell.browserEngine == 'Trident' && hpDoc) {
  3438.             hpDoc.navigateToURL(uri,null);
  3439.         } else {
  3440.             if (postData === undefined)
  3441.                 postData = null;
  3442.             //var webnav = getWebNavigation();
  3443.             docshell.loadURI(uri, nsIWebNavigation.LOAD_FLAGS_NONE, referrer, postData, null);
  3444.         }
  3445.     } catch(e) {dump ("Caught Exception: " + e + "\n");    }
  3446.     // dump('************ END loadURI('+uri+') *******************\n');
  3447. UpdateStatusBarEngineIcon();
  3448. }
  3449.  
  3450.  
  3451. // MERC (DP):
  3452. // uses openPref to determine whether to open URI in current tab or new tab.
  3453. // set focus according to 'browser.tabs.loadInBackground'
  3454. function loadURIWithOpenPref(uri, openPref, referrer, postData) {
  3455.     if (gPrefService.getCharPref(openPref) == 'overwrite') {
  3456.         loadURI(uri, referrer, postData);
  3457.     } else { // == 'new'
  3458.         var theTab = gBrowser.addTabAt(uri, undefined, referrer, null, postData);
  3459.         if (!gPrefService.getBoolPref("browser.tabs.loadInBackground"))
  3460.             gBrowser.selectedTab = theTab;
  3461.     }
  3462. }
  3463.  
  3464.  
  3465. /* trim leading and trailing whitespace from a string */
  3466. function trim(str)
  3467. {
  3468.     str=str.replace(/^\s*/,"");
  3469.     str=str.replace(/\s*$/,"");
  3470.     return str;
  3471. }
  3472.  
  3473.  
  3474. /**
  3475. * Given keywords in uri variable, simulate typing
  3476. * stuff into search-bar
  3477. **/
  3478. function BrowserSearchURL(uri, referrer, postData)
  3479. {
  3480.     dump('browser.js: BrowserSearchURL('+uri+')\n');
  3481.  
  3482.     // trim whitespace from either end of the uri
  3483.     var trimuri = trim(uri);
  3484.     if (trimuri)
  3485.         search.AddToHistory(trimuri);
  3486.  
  3487.     var searchURL = gPrefService.getCharPref('keyword.URL')
  3488.                     + encodeURIComponent(trimuri);
  3489.     loadURIWithOpenPref(searchURL,
  3490.                         "browser.tabs.searchbarresult.open",
  3491.                         referrer, postData);
  3492.     var searchSvc =
  3493.         Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"]
  3494.                   .getService(Components.interfaces.nsIInternetSearchService);
  3495.     searchSvc.FindInternetSearchResults(searchURL);
  3496. }
  3497.  
  3498.  
  3499. // MERC (DP):
  3500. // added the param bOpenWithPref. this determines whether to open the URL
  3501. // in current OR new tab
  3502. function BrowserLoadURL(aTriggeringEvent, aPostData, aOpenWithPref)
  3503. {
  3504.     if (!gURLBar)
  3505.         gURLBar = document.getElementById("urlbar");    
  3506.     var url = gURLBar.value;
  3507.     
  3508.     dump('browser.js: BrowserLoadURL(): '+url+'\n');
  3509.     // MERC (DP): save the current URL
  3510.     var currURL = getWebNavigation().currentURI.spec;
  3511.  
  3512.     if (url.match(/^view-source:/)) {
  3513.         BrowserViewSourceOfURL(url.replace(/^view-source:/, ""), null, null);
  3514.     } else if (url.match(/^search:/)) {
  3515.         BrowserSearchURL(url.replace(/^search:/, ""), null, aPostData);
  3516.     } else {
  3517.         if (gBrowser.localName == "tabbrowser" &&
  3518.             aTriggeringEvent && 'altKey' in aTriggeringEvent &&
  3519.             aTriggeringEvent.altKey)
  3520.         {
  3521.             _content.focus();
  3522.             // JMC - only happens on an altKey load
  3523.             
  3524.             // MERC (DP): add tab and focus according to prefs
  3525.             var t = gBrowser.addTabAt(url, undefined, null, null, aPostData); // open link in new tab
  3526.             if (!gPrefService.getBoolPref("browser.tabs.loadInBackground")) {
  3527.                 gBrowser.selectedTab = t;
  3528.                 gURLBar.value = url;
  3529.             } else {
  3530.                 gURLBar.value = currURL;
  3531.             }
  3532.             //dump('browser.js: gURLbar.value = '+gURLBar.value+'\n\n');
  3533.             // END MERC
  3534.             event.preventDefault();
  3535.             event.preventBubble();
  3536.             event.preventCapture();
  3537.             event.stopPropagation();
  3538.         } else {
  3539.             // if no pref passed in, load in current tab.
  3540.             // otherwise open url according to pref
  3541.             if (aOpenWithPref) {
  3542.                 loadURIWithOpenPref(url, aOpenWithPref, null, aPostData);
  3543.             } else {
  3544.                 loadURI(url, null, aPostData);
  3545.             }
  3546.         }
  3547.         dump ("BrowserLoadURL: Currently focused element is : " + document.commandDispatcher.focusedElement.getAttribute('anonid') + ", at least that's what commandDispatcher thinks.\n");
  3548.         
  3549.         if (document.commandDispatcher.focusedElement.getAttribute('anonid') != 'input')
  3550.         {
  3551.             _content.focus();
  3552.             dump ("Now the _content is focused, which is : " + _content + "\n");
  3553.         } else {
  3554.             gBrowser.userTypedValue = null;
  3555.             gBrowser.userTypedClear = true;
  3556.             SetPageProxyState("valid", null); // XXX Build a URI and pass it in here.
  3557.         } // JMC - Note that this hack doesn't work in trident navigation
  3558.         // JMC - Is this URLBar defocusing?
  3559.         
  3560.     }
  3561. }
  3562.  
  3563. function SearchLoadURL(aURL, aTriggeringEvent)
  3564. {
  3565.    dump ("SearchLoadURL : " + aURL + "\t");
  3566. //    showStack();
  3567.     if (gBrowser.localName == "tabbrowser" &&
  3568.     aTriggeringEvent && 'altKey' in aTriggeringEvent &&
  3569.     aTriggeringEvent.altKey) {
  3570.         _content.focus();
  3571.         var t = gBrowser.addTab(aURL, null); // open link in new tab
  3572.         gBrowser.selectedTab = t;
  3573.         if (gURLBar)
  3574.            gURLBar.value = aURL;
  3575.     }
  3576.     else {
  3577.         loadURIWithOpenPref(aURL, "browser.tabs.searchbarresult.open", null, null);
  3578.     }
  3579.     _content.focus();
  3580.       
  3581.     var internetSearch =
  3582.         Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"]
  3583.                   .getService(nsIInternetSearchService);
  3584.     internetSearch.FindInternetSearchResults(aURL);
  3585. }
  3586.  
  3587. function getShortcutOrURI(aURL, aPostDataRef)
  3588. {
  3589.     // rjc: added support for URL shortcuts (3/30/1999)
  3590.     try {
  3591.         var shortcutURL = BMSVC.resolveKeyword(aURL, aPostDataRef);
  3592.         if (!shortcutURL) {
  3593.             // rjc: add support for string substitution with shortcuts (4/4/2000)
  3594.             //      (see bug # 29871 for details)
  3595.             var aOffset = aURL.indexOf(" ");
  3596.             if (aOffset > 0) {
  3597.                 var cmd = aURL.substr(0, aOffset);
  3598.                 var text = aURL.substr(aOffset+1);
  3599.                 shortcutURL = BMSVC.resolveKeyword(cmd, aPostDataRef);
  3600.                 if (shortcutURL && text) {
  3601.                     if (aPostDataRef && aPostDataRef.value) {
  3602.                         // XXXben - currently we only support "application/x-www-form-urlencoded"
  3603.                         //          enctypes.
  3604.                         aPostDataRef.value = unescape(aPostDataRef.value);
  3605.                         if (aPostDataRef.value.match(/%s/)) {
  3606.                             aPostDataRef.value = getPostDataStream(aPostDataRef.value, text,
  3607.                                                                    "application/x-www-form-urlencoded");
  3608.                         } else {
  3609.                             shortcutURL = null;
  3610.                             aPostDataRef.value = null;
  3611.                         }
  3612.                     }
  3613.                 else
  3614.                     shortcutURL = shortcutURL.match(/%s/) ? shortcutURL.replace(/%s/g, encodeURIComponent(text)) : null;
  3615.                 }
  3616.             }
  3617.         }
  3618.     
  3619.         if (shortcutURL)
  3620.             aURL = shortcutURL;
  3621.     
  3622.     } catch (ex) { }
  3623.     return aURL;
  3624. }
  3625.  
  3626.  
  3627. function getPostDataStream(aStringData, aKeyword, aType)
  3628. {
  3629.     var dataStream = Components.classes["@mozilla.org/io/string-input-stream;1"]
  3630.                                .createInstance(Components.interfaces.nsIStringInputStream);
  3631.     aStringData = aStringData.replace(/%s/g, encodeURIComponent(aKeyword));
  3632.     dataStream.setData(aStringData, aStringData.length);
  3633.  
  3634.     var mimeStream = Components.classes["@mozilla.org/network/mime-input-stream;1"]
  3635.                                .createInstance(Components.interfaces.nsIMIMEInputStream);
  3636.     mimeStream.addHeader("Content-Type", aType);
  3637.     mimeStream.addContentLength = true;
  3638.     mimeStream.setData(dataStream);
  3639.     return mimeStream.QueryInterface(Components.interfaces.nsIInputStream);
  3640. }
  3641.  
  3642.  
  3643. function readFromClipboard()
  3644. {
  3645.     var url;
  3646.  
  3647.     try {
  3648.         // Get clipboard.
  3649.         var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
  3650.         .getService(Components.interfaces.nsIClipboard);
  3651.  
  3652.         // Create tranferable that will transfer the text.
  3653.         var trans = Components.classes["@mozilla.org/widget/transferable;1"]
  3654.         .createInstance(Components.interfaces.nsITransferable);
  3655.  
  3656.         trans.addDataFlavor("text/unicode");
  3657.  
  3658.         // If available, use selection clipboard, otherwise global one
  3659.         if (clipboard.supportsSelectionClipboard())
  3660.             clipboard.getData(trans, clipboard.kSelectionClipboard);
  3661.         else
  3662.             clipboard.getData(trans, clipboard.kGlobalClipboard);
  3663.  
  3664.         var data = {};
  3665.         var dataLen = {};
  3666.         trans.getTransferData("text/unicode", data, dataLen);
  3667.  
  3668.         if (data) {
  3669.             data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
  3670.             url = data.data.substring(0, dataLen.value / 2);
  3671.         }
  3672.     } catch (ex) {
  3673.     }
  3674.  
  3675.     return url;
  3676. }
  3677.  
  3678. function BrowserViewSourceOfDocument(aDocument)
  3679. {
  3680.     var docCharset;
  3681.     var pageCookie;
  3682.     var webNav;
  3683.  
  3684.     // Get the document charset
  3685.     docCharset = "charset=" + aDocument.characterSet;
  3686.  
  3687.     // Get the nsIWebNavigation associated with the document
  3688.     try {
  3689.         var win;
  3690.         var ifRequestor;
  3691.  
  3692.         // Get the DOMWindow for the requested document.  If the DOMWindow
  3693.         // cannot be found, then just use the _content window...
  3694.         //
  3695.         // XXX:  This is a bit of a hack...
  3696.         win = aDocument.defaultView;
  3697.         if (win == window) {
  3698.             win = _content;
  3699.         }
  3700.         ifRequestor = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  3701.  
  3702.         webNav = ifRequestor.getInterface(nsIWebNavigation);
  3703.     } catch(err) {
  3704.         // If nsIWebNavigation cannot be found, just get the one for the whole
  3705.         // window...
  3706.         webNav = getWebNavigation();
  3707.     }
  3708.     //
  3709.     // Get the 'PageDescriptor' for the current document. This allows the
  3710.     // view-source to access the cached copy of the content rather than
  3711.     // refetching it from the network...
  3712.     //
  3713.     try {
  3714.         var PageLoader = webNav.QueryInterface(Components.interfaces.nsIWebPageDescriptor);
  3715.         pageCookie = PageLoader.currentDescriptor;
  3716.     } catch(err) {
  3717.         // If no page descriptor is available, just use the view-source URL...
  3718.     }
  3719.  
  3720.     BrowserViewSourceOfURL(webNav.currentURI.spec, docCharset, pageCookie);
  3721. }
  3722.  
  3723. function BrowserViewSourceOfURL(url, charset, pageCookie)
  3724. {
  3725.     // try to open a view-source window while inheriting the charset (if any)
  3726.     openDialog("chrome://global/content/viewSource.xul",
  3727.                "_blank",
  3728.                "scrollbars,resizable,chrome,dialog=no",
  3729.                url, charset, pageCookie);
  3730. }
  3731.  
  3732. // doc=null for regular page info, doc=owner document for frame info.
  3733. function BrowserPageInfo(doc)
  3734. {
  3735.     var hpDoc = getTridentDocument();
  3736.     if (hpDoc) {
  3737.         hpDoc.showPageInfo();
  3738.     } else {
  3739.         window.openDialog("chrome://browser/content/pageInfo.xul",
  3740.         "_blank",
  3741.         "chrome,dialog=no",
  3742.         doc);
  3743.     }
  3744. }
  3745.  
  3746.  
  3747. function checkForDirectoryListing()
  3748. {
  3749.     if ( "HTTPIndex" in _content &&
  3750.     _content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
  3751.         _content.defaultCharacterset = getMarkupDocumentViewer().defaultCharacterSet;
  3752.     }
  3753. }
  3754.  
  3755. function URLBarFocusHandler(aEvent, aElt)
  3756. {
  3757.     if (gIgnoreFocus)
  3758.         gIgnoreFocus = false;
  3759.     else if (gClickSelectsAll)
  3760.         aElt.select();
  3761. }
  3762.  
  3763. function URLBarMouseDownHandler(aEvent, aElt)
  3764. {
  3765.     if (aElt.hasAttribute("focused")) {
  3766.         gIgnoreClick = true;
  3767.     } else {
  3768.         gIgnoreFocus = true;
  3769.         gIgnoreClick = false;
  3770.         aElt.setSelectionRange(0, 0);
  3771.     }
  3772. }
  3773.  
  3774. function URLBarClickHandler(aEvent, aElt)
  3775. {
  3776.     if (!gIgnoreClick && gClickSelectsAll && aElt.selectionStart == aElt.selectionEnd)
  3777.     aElt.select();
  3778. }
  3779.  
  3780. // If "ESC" is pressed in the url bar, we replace the urlbar's value with the url of the page
  3781. // and highlight it, unless it is about:blank, where we reset it to "".
  3782. function handleURLBarRevert()
  3783. {
  3784.     dump ("handleURLBarRevent()\n");
  3785.     var url = getWebNavigation().currentURI.spec;
  3786.     var throbberElement = document.getElementById("throbberBroadcaster");
  3787.  
  3788.     var isScrolling = gURLBar.popupOpen;
  3789.  
  3790.     // don't revert to last valid url unless page is NOT loading
  3791.     // and user is NOT key-scrolling through autocomplete list
  3792.     if ((!throbberElement || !throbberElement.hasAttribute("busy")) && !isScrolling) {
  3793.         if (url != "about:blank") {
  3794.             gURLBar.value = url;
  3795.             gURLBar.select();
  3796.             SetPageProxyState("valid", null); // XXX Build a URI and pass it in here.
  3797.         } else { //if about:blank, urlbar becomes ""
  3798.             gURLBar.value = "";
  3799.         }
  3800.     }
  3801.  
  3802.     gBrowser.userTypedValue = null;
  3803.  
  3804.     // tell widget to revert to last typed text only if the user
  3805.     // was scrolling when they hit escape
  3806.     return !isScrolling;
  3807. }
  3808.  
  3809. function TextIsURI(selectedText)
  3810. {
  3811.     return selectedText && /^http:\/\/|^https:\/\/|^file:\/\/|\
  3812.     ^ftp:\/\/|^about:|^mailto:|^news:|^snews:|^telnet:|^ldap:|\
  3813.     ^ldaps:|^gopher:|^finger:|^javascript:/i.test(selectedText);
  3814. }
  3815.  
  3816. function shouldPrependSearch(url)
  3817. {
  3818.     // if search: is already at the beginning, don't add it again
  3819.     if (/^search:/.test(url)) {
  3820.         return false;
  3821.     }
  3822.  
  3823.     // trim leading/trailing whitespace
  3824.     trimmedURL = url.replace(/^\s*/, '').replace(/\s*$/, '');
  3825.  
  3826.     // if string is empty do not prepend
  3827.     if (!trimmedURL) return false;
  3828.  
  3829.     // if string has protocol, do not prepend
  3830.     if( /^http:\/\/|^https:\/\/|^file:\/\/|\
  3831.     ^ftp:\/\/|^about:|^mailto:|^news:|^snews:|^telnet:|^ldap:|\
  3832.     ^ldaps:|^gopher:|^finger:|^javascript:/i.test(trimmedURL) )
  3833.     {
  3834.         return false;
  3835.     }
  3836.  
  3837.     // if the string looks like a path to a local file, do not prepend
  3838.     if (/^[a-z]:\\/.test(trimmedURL)) {
  3839.         return false;
  3840.     }
  3841.  
  3842.     // if whitespace occurs in the url, treat it as a search
  3843.     if (/\s+/.test(trimmedURL)) {
  3844.         return true;
  3845.     }
  3846.  
  3847.     // if any dots occur in the url, DO NOT treat as search
  3848.     if (/\./.test(url)) {
  3849.         return false;
  3850.     }
  3851.  
  3852.     return false;
  3853. }
  3854.  
  3855. function handleURLBarCommand(aTriggeringEvent)
  3856. {
  3857.     var postData = { };
  3858.     canonizeUrl(aTriggeringEvent, postData);
  3859.  
  3860.     try {
  3861.         addToUrlbarHistory();
  3862.     } catch (ex) {
  3863.         // Things may go wrong when adding url to session history,
  3864.         // but don't let that interfere with the loading of the url.
  3865.     }
  3866.  
  3867.     BrowserLoadURL(aTriggeringEvent, postData.value);
  3868.     // BrowserLoadURL(aTriggeringEvent, postData.value, "browser.tabs.history.open");
  3869. }
  3870.  
  3871. function canonizeUrl(aTriggeringEvent, aPostDataRef)
  3872. {
  3873.     if (!gURLBar || gURLBar.value == '')
  3874.         return;
  3875.  
  3876.     var url = gURLBar.value;
  3877.  
  3878.     if (shouldPrependSearch(url)) {
  3879.         url = 'search:'+url;
  3880.     }
  3881.     // Prevent suffix when already exists www , http , /
  3882.     else if (!/^(www|http)|\/\s*$/i.test(url)) {
  3883.         var suffix = null;
  3884.  
  3885.         if (aTriggeringEvent && 'ctrlKey' in aTriggeringEvent &&
  3886.             aTriggeringEvent.ctrlKey && 'shiftKey' in aTriggeringEvent &&
  3887.             aTriggeringEvent.shiftKey)
  3888.         {
  3889.             suffix = ".org/";
  3890.         }
  3891.         else if (aTriggeringEvent && 'ctrlKey' in aTriggeringEvent &&
  3892.                  aTriggeringEvent.ctrlKey)
  3893.         {
  3894.             suffix = ".com/";
  3895.         }
  3896.         else if (aTriggeringEvent && 'shiftKey' in aTriggeringEvent &&
  3897.                  aTriggeringEvent.shiftKey)
  3898.         {
  3899.             suffix = ".net/";
  3900.         }
  3901.         
  3902.         if (suffix != null) {
  3903.             // trim leading/trailing spaces (bug 233205)
  3904.             url = url.replace(/^\s+/, "");
  3905.             url = url.replace(/\s+$/, "");
  3906.             // Tack www. and suffix on.
  3907.             url = "http://www." + url + suffix;
  3908.         }
  3909.     }
  3910.     gURLBar.value = getShortcutOrURI(url, aPostDataRef);
  3911. }
  3912.  
  3913. function UpdatePageProxyState()
  3914. {
  3915.     if (gURLBar && gURLBar.value != gLastValidURLStr)
  3916.     SetPageProxyState("invalid", null);
  3917. }
  3918.  
  3919.  
  3920. // MERC - JCH: Called in nsHTMLPluginDocument.cpp to update favicons
  3921. //function UpdateFavIcons(windowDoc)
  3922. // MRR - This function signature will change when nsHTMLPluginDocument is rationalized.
  3923. //       Will become: function UpdateFavIcons(windowDoc, aHref)
  3924. function UpdateFavIcons( aHref, dummy1, dummy2, dummy3, windowDoc)
  3925. {
  3926.     if (windowDoc == null) return false;
  3927.  
  3928.     var tabIndex = gBrowser.getBrowserIndexForDocument(windowDoc);
  3929.     if (tabIndex < 0) return false;
  3930.  
  3931.     var aTab = gBrowser.tabContainer.childNodes[tabIndex];
  3932.     if (aTab == null) return false;
  3933.  
  3934.     var tabUri = gBrowser.getBrowserForTab(aTab).currentURI;
  3935.  
  3936. //    dump( "))      WMWMWMWMWMW===> UpdateFavIcons(\""+tabUri.spec+"\")  from TRIDENT\n" );
  3937. //    dump( "))      WMWMWMWMWMW===> UpdateFavIcons - Trident passed \""+aHref+"\"\n" );
  3938.  
  3939.     if (gBrowser.shouldLoadFavIcon(tabUri))
  3940.     {
  3941.         var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  3942.         var favIconURI = ios.newURI(aHref, null, tabUri);
  3943.         var favIconURIstr = "";
  3944.         if ( aHref == "" ) {
  3945.             favIconURIstr = gBrowser.buildFavIconString(tabUri);
  3946.             favIconURI.spec = favIconURIstr;
  3947.         } else {
  3948.             favIconURIstr = favIconURI.spec;
  3949.         }
  3950. //        dump( "))      WMWMWMWMWMW===> UpdateFavIcons - Yay; Built \""+favIconURI.spec+"\"\n" );
  3951.  
  3952.         // This sets the icon on the tab.
  3953.         gBrowser.mCurrentBrowser.mFavIconURL = favIconURIstr;
  3954.         aTab.setAttribute('image', favIconURIstr);
  3955.  
  3956.         // This sets the icon on the listener, so switch tabs synchs the icon in URL bar.
  3957.         if (gBrowser.mTabbedMode)
  3958.             gBrowser.mTabListeners[tabIndex].mIcon = gBrowser.mCurrentBrowser.mFavIconURL;
  3959.         // This sets the icon on the URL bar.
  3960.         PageProxySetIcon(gBrowser.mCurrentBrowser.mFavIconURL);
  3961.     } else {
  3962.         //dump( "---------- UpdateFavIcons: Clearing icon\n");
  3963.         aTab.removeAttribute("image");
  3964.         gBrowser.mCurrentBrowser.mFavIconURL = null;
  3965.         if (gBrowser.mTabListeners[tabIndex])
  3966.         {
  3967.             gBrowser.mTabListeners[tabIndex].mIcon = null;
  3968.             PageProxyClearIcon();
  3969.         }
  3970.     }
  3971.     return true;
  3972. }
  3973.  
  3974. function StartTabProgress(hpSomeDoc)
  3975. {
  3976.     //dump("\nJA~~~~~~~~~~~~~:StartTabProgress(): hpSomeDoc ="+hpSomeDoc+"\n");
  3977.     if(!hpSomeDoc)
  3978.         return false;//err
  3979.     
  3980.     // loop through all the tabs and match which trident document this event has originated from
  3981.     var cnTabs = gBrowser.tabContainer.childNodes;
  3982.     var numtabs = cnTabs.length;
  3983.     var tabBrowser = getBrowser();
  3984.     if (numtabs>1)
  3985.     {
  3986.         for (var i = 0; i < numtabs; ++i)
  3987.         {
  3988.             var doc = gBrowser.getBrowserForTab(cnTabs[i]).contentDocument;
  3989.             if (doc && doc == hpSomeDoc)
  3990.             {    
  3991.                 //dump("!!!!!~~~~~~~~~~~~~~Found in tab# "+i+"\n");
  3992.                 cnTabs[i].setAttribute("busy", "true");
  3993.                 cnTabs[i].label = tabBrowser.mStringBundle.getString("tabs.loading");
  3994.                 cnTabs[i].removeAttribute("image"); 
  3995.                 cnTabs[i].mIcon = null;
  3996.                 return true;
  3997.             }
  3998.         }
  3999.     }
  4000.     //dump("~~~~~~~~~~Couldn't find hpSomeDoc!\n\n");
  4001.     return false;
  4002. }
  4003.  
  4004. function EndTabProgress(hpSomeDoc) {
  4005.     
  4006.     // loop through all the tabs and match which trident document this event has originated from
  4007.     if(!hpSomeDoc)
  4008.         return false;//err
  4009.     var cnTabs = gBrowser.tabContainer.childNodes;
  4010.     var numtabs = cnTabs.length;
  4011.     var tabBrowser = getBrowser();
  4012.     if (numtabs>1)
  4013.     {
  4014.         for (var i = 0; i < numtabs; ++i)
  4015.         {
  4016.             var doc = gBrowser.getBrowserForTab(cnTabs[i]).contentDocument;
  4017.             if (doc && doc == hpSomeDoc)
  4018.             {    
  4019.                 //dump("!!!!!~~~~~~~~~~~~~~Found in tab# "+i+"\n");
  4020.                 cnTabs[i].removeAttribute("busy")
  4021.                 tabBrowser.setTabTitle(cnTabs[i]);
  4022.                 return true;
  4023.             }
  4024.         }
  4025.     }
  4026.     //dump("~~~~~~~~~~Couldn't find hpSomeDoc!\n\n");
  4027.     return false;
  4028. }
  4029.  
  4030.  
  4031. function SetPageProxyState(aState, aURI)
  4032. {
  4033.     if (!gURLBar)
  4034.         return;
  4035.  
  4036.     if (!gProxyButton)
  4037.         gProxyButton = document.getElementById("page-proxy-button");
  4038.     if (!gProxyFavIcon)
  4039.         gProxyFavIcon = document.getElementById("page-proxy-favicon");
  4040.     if (!gProxyDeck)
  4041.         gProxyDeck = document.getElementById("page-proxy-deck");
  4042.  
  4043.     gProxyButton.setAttribute("pageproxystate", aState);
  4044.  
  4045. //    if ( aURI )
  4046. //        dump( "))      WMWMWMWMWMW===> SetPageProxyState(\""+aURI.spec+"\") - gProxyFavIcon is: \""+gProxyFavIcon.getAttribute("src")+"\"\n" );
  4047. //    else
  4048. //        dump( "))      WMWMWMWMWMW===> SetPageProxyState(null) - gProxyFavIcon is: \""+gProxyFavIcon.getAttribute("src")+"\"\n" );
  4049.  
  4050.     // the page proxy state is set to valid via OnLocationChange, which
  4051.     // gets called when we switch tabs.  We'll let updatePageFavIcon
  4052.     // take care of updating the mFavIconURL because it knows exactly
  4053.     // for which tab to update things, instead of confusing the issue
  4054.     // here.
  4055.     if (aState == "valid") {
  4056.         gLastValidURLStr = gURLBar.value;
  4057.         gURLBar.addEventListener("input", UpdatePageProxyState, false);
  4058.  
  4059.         if (gBrowser.mCurrentBrowser.mFavIconURL != null) {
  4060.             if (gBrowser.isFavIconKnownMissing(gBrowser.mCurrentBrowser.mFavIconURL)) {
  4061.                 gBrowser.mFavIconURL = null;
  4062. //                dump( "))      WMWMWMWMWMW===> SetPageProxyState() - clearing icon (#1)\n" );
  4063.                 PageProxyClearIcon();
  4064.             } else {
  4065.                 PageProxySetIcon(gBrowser.mCurrentBrowser.mFavIconURL);
  4066.             }
  4067.         } else {
  4068. //            dump( "))      WMWMWMWMWMW===> SetPageProxyState() - clearing icon (#2)\n" );
  4069.             PageProxyClearIcon();
  4070.         }
  4071.     } else if (aState == "invalid") {
  4072.         gURLBar.removeEventListener("input", UpdatePageProxyState, false);
  4073.         PageProxyClearIcon();
  4074.     }
  4075. }
  4076.  
  4077. function PageProxySetIcon (aURL)
  4078. {
  4079.     if (!gProxyFavIcon)
  4080.         return;
  4081.     if (gProxyFavIcon.getAttribute("src") != aURL)
  4082.         gProxyFavIcon.setAttribute("src", aURL);
  4083.  
  4084.     if (gProxyDeck && gProxyDeck.selectedIndex != 1 && gProxyFavIcon.getAttribute("src"))
  4085.         gProxyDeck.selectedIndex = 1;
  4086.     else if (gProxyDeck && gProxyDeck.selectedIndex != 0 && !gProxyFavIcon.getAttribute("src"))
  4087.         gProxyDeck.selectedIndex = 0;
  4088.  
  4089. //    dump( "))      WMWMWMWMWMW===> PageProxySetIcon(\""+aURL+"\"); index="+gProxyDeck.selectedIndex+"\n" );
  4090. }
  4091.  
  4092. function PageProxyClearIcon ()
  4093. {
  4094. //    dump( "))      WMWMWMWMWMW===> PageProxyClearIcon()\n" );
  4095.     if (gProxyDeck && gProxyDeck.selectedIndex != 0)
  4096.         gProxyDeck.selectedIndex = 0;
  4097.     if (gProxyFavIcon && gProxyFavIcon.hasAttribute("src"))
  4098.         gProxyFavIcon.removeAttribute("src");
  4099. }
  4100.  
  4101. function PageProxyDragGesture(aEvent)
  4102. {
  4103.     if (gProxyButton.getAttribute("pageproxystate") == "valid") {
  4104.         nsDragAndDrop.startDrag(aEvent, proxyIconDNDObserver);
  4105.         return true;
  4106.     }
  4107.     return false;
  4108. }
  4109.  
  4110.  
  4111. function URLBarOnDrop(evt)
  4112. {
  4113.     nsDragAndDrop.drop(evt, urlbarObserver);
  4114. }
  4115.  
  4116. var urlbarObserver = {
  4117.     onDrop: function (aEvent, aXferData, aDragSession)
  4118.     {
  4119.         var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  4120.  
  4121.         // The URL bar automatically handles inputs with newline characters,
  4122.         // so we can get away with treating text/x-moz-url flavours as text/unicode.
  4123.         if (url) {
  4124.             getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
  4125.  
  4126.             // XXXBlake Workaround caret crash when you try to set the textbox's value on dropping
  4127.             setTimeout(function(u) { gURLBar.value = u; handleURLBarCommand(); }, 0, url);
  4128.         }
  4129.     },
  4130.     getSupportedFlavours: function ()
  4131.     {
  4132.         var flavourSet = new FlavourSet();
  4133.  
  4134.         // Plain text drops are often misidentified as "text/x-moz-url", so favor plain text.
  4135.         flavourSet.appendFlavour("text/unicode");
  4136.         flavourSet.appendFlavour("text/x-moz-url");
  4137.         flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4138.         return flavourSet;
  4139.     }
  4140. }
  4141.  
  4142. function SearchBarOnDrop(evt)
  4143. {
  4144.     nsDragAndDrop.drop(evt, searchbarObserver);
  4145. }
  4146.  
  4147. var searchbarObserver = {
  4148.     onDrop: function (aEvent, aXferData, aDragSession)
  4149.     {
  4150.         var data = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  4151.         if (data) {
  4152.             // XXXBlake Workaround caret crash when you try to set the textbox's value on dropping
  4153.             var field = document.getElementById("search-bar");
  4154.             setTimeout(function(field, data, evt) { field.value = data; field.onTextEntered(evt); }, 0, field, data, aEvent);
  4155.         }
  4156.     },
  4157.     getSupportedFlavours: function ()
  4158.     {
  4159.         var flavourSet = new FlavourSet();
  4160.  
  4161.         flavourSet.appendFlavour("text/unicode");
  4162.         flavourSet.appendFlavour("text/x-moz-url");
  4163.         flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4164.         return flavourSet;
  4165.     }
  4166. }
  4167.  
  4168. function SearchBarPopupShowing(aEvent)
  4169. {
  4170. }
  4171.  
  4172. function SearchBarPopupCommand(aEvent)
  4173. {
  4174.  
  4175.     if (!aEvent.target.id)
  4176.         return;
  4177.  
  4178.     if (aEvent.target.id == "miAddEngines") {
  4179.         var regionBundle = document.getElementById("bundle_browser_region");
  4180.         loadURI(regionBundle.getString("searchEnginesURL"), null, null);
  4181.         return;
  4182.     }
  4183.  
  4184.     document.getElementById("search-bar").currentEngine = aEvent.target.id;
  4185. }
  4186.  
  4187. function showSearchEnginePopup()
  4188. {
  4189.     var searchEnginePopup = document.getElementById("SearchBarPopup");
  4190.     var searchEngineButton = document.getElementById("search-proxy-button");
  4191.     searchEnginePopup.showPopup(searchEngineButton);
  4192. }
  4193.  
  4194. function updateToolbarStates(toolbarMenuElt)
  4195. {
  4196.     if (!gHaveUpdatedToolbarState) {
  4197.         var mainWindow = document.getElementById("main-window");
  4198.         if (mainWindow.hasAttribute("chromehidden")) {
  4199.             gHaveUpdatedToolbarState = true;
  4200.             var i;
  4201.             for (i = 0; i < toolbarMenuElt.childNodes.length; ++i)
  4202.             document.getElementById(toolbarMenuElt.childNodes[i].getAttribute("observes")).removeAttribute("checked");
  4203.             var toolbars = document.getElementsByTagName("toolbar");
  4204.  
  4205.             // Start i at 1, since we skip the menubar.
  4206.             for (i = 1; i < toolbars.length; ++i) {
  4207.                 if (toolbars[i].getAttribute("class").indexOf("chromeclass") != -1)
  4208.                 toolbars[i].setAttribute("collapsed", "true");
  4209.             }
  4210.  
  4211.             toolbars = document.getElementsByTagName("multibar");
  4212.             for (i = 0; i < toolbars.length; ++i) {
  4213.                 if (toolbars[i].getAttribute("class").indexOf("chromeclass") != -1)
  4214.                 toolbars[i].setAttribute("collapsed", "true");
  4215.             }
  4216.  
  4217.             var statusbars = document.getElementsByTagName("statusbar");
  4218.             for (i = 1; i < statusbars.length; ++i) {
  4219.                 if (statusbars[i].getAttribute("class").indexOf("chromeclass") != -1)
  4220.                 statusbars[i].setAttribute("collapsed", "true");
  4221.             }
  4222.             
  4223.             var toolbox = document.getElementById("navigator-toolbox");    
  4224.             toolbox.reorderToolbars();        
  4225.             
  4226.             mainWindow.removeAttribute("chromehidden");
  4227.         }
  4228.     }
  4229. }
  4230.  
  4231. function BrowserImport()
  4232. {
  4233.         var features = "modal,centerscreen,chrome,resizable=no";
  4234.         window.openDialog("chrome://browser/content/migration/migration.xul", "migration", features);
  4235.     }
  4236.     
  4237.     function BrowserFullScreen()
  4238.     {
  4239.         window.fullScreen = !window.fullScreen;
  4240.     }
  4241.  
  4242.     function BrowserToggleMaximize()
  4243.     {
  4244.         if (window.windowState == window.STATE_MAXIMIZED) {
  4245.             window.restore();
  4246.             document.getElementById('main-window').setAttribute('sizemode', 'normal');
  4247.             document.getElementById('restoreButtonBroadcaster').tooltipText = 'Maximize';
  4248.             isButtonToggle = true;
  4249.         } else {
  4250.             window.maximize();
  4251.             document.getElementById('main-window').setAttribute('sizemode', 'maximized');
  4252.             document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down';
  4253.             isButtonToggle = false;    
  4254.         }
  4255.         reshuffleToolbars();
  4256.     }
  4257.     function onWindowResize()
  4258.     {
  4259.             if (window.windowState == window.STATE_MAXIMIZED)
  4260.                 document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down';
  4261.             else if (window.windowState == window.STATE_NORMAL)
  4262.                 document.getElementById('restoreButtonBroadcaster').tooltipText = 'Maximize';
  4263.             BookmarksToolbar.resizeFunc();
  4264.     }
  4265.     function onFullScreen()
  4266.     {
  4267.         if(isButtonToggle) {
  4268.             if (window.windowState == window.STATE_MAXIMIZED) {
  4269.                 document.getElementById('main-window').setAttribute('sizemode', 'normal');
  4270.                 document.getElementById('restoreButtonBroadcaster').tooltipText = 'Maximize';
  4271.             } else {
  4272.                 document.getElementById('main-window').setAttribute('sizemode', 'maximized');
  4273.                 document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down';
  4274.             }
  4275.         }
  4276.         else {
  4277.             document.getElementById('main-window').setAttribute('sizemode', 'maximized');
  4278.             document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down';
  4279.         }
  4280.         
  4281.         FullScreen.toggle();
  4282.     }
  4283.  
  4284.     function getWebNavigation()
  4285.     {
  4286.         try {
  4287.             return gBrowser.webNavigation;
  4288.         } catch (e) {
  4289.             return null;
  4290.         }
  4291.     }
  4292.  
  4293.     function BrowserReloadWithFlags(reloadFlags)
  4294.     {
  4295.         // MERC JVL
  4296.         // stop the browser first (within the context) before proceeding with the reload
  4297.         BrowserStop();
  4298.  
  4299.         //JA
  4300.         var hpDoc;
  4301.         var webNav = getWebNavigation();
  4302.         if(webNav.browserEngine=="Trident")
  4303.             hpDoc=getTridentDocument();
  4304.         if(hpDoc)
  4305.             hpDoc.reloadDocument();//end JA
  4306.         else //default
  4307.         {
  4308.             /* First, we'll try to use the session history object to reload so
  4309.             * that framesets are handled properly. If we're in a special
  4310.             * window (such as view-source) that has no session history, fall
  4311.             * back on using the web navigation's reload method.
  4312.             */
  4313.             // check site control to try to switch engine
  4314.             var needSwitchEngine=false;
  4315.             var bRedirected;
  4316.             try
  4317.             {
  4318.                 var site = webNav.currentURI.host;
  4319.                 var bControlled=sitecontrols.SCSVC.isControlledSite(site);
  4320.                 var displayEngine;
  4321.                 if(bControlled)
  4322.                     displayEngine=sitecontrols.SCSVC.readSiteControl(site, "displayEngine");
  4323.                 else
  4324.                     displayEngine=sitecontrols.SCSVC.readSiteControl(sitecontrols.DEFAULT_SITE, "displayEngine");
  4325.                 if (displayEngine=="Trident")
  4326.                 {
  4327.                     needSwitchEngine=true;
  4328.                     webNav.browserEngine='Trident';
  4329.                 }
  4330.                 if (needSwitchEngine)
  4331.                 {
  4332.                     var filePath=webNav.currentURI.path;
  4333.                     //SLiu, if it is a image url, and reload will cause switch engine from Gecko to Trident
  4334.                     //we let browser load a Trident blank page first then navigate to the image url
  4335.                     var len=filePath.length;
  4336.                     var isImgURL=false;
  4337.                     if (len > 4) //".jpg"
  4338.                     {
  4339.                         var fileType=filePath.substr(len-3, 3);
  4340.                         fileType.toLowerCase();
  4341.                         var imgExtList= new Array('gif','jpg','bmp','png');
  4342.                         var i;
  4343.                         for (i=0;i<imgExtList.length;i++)
  4344.                         {
  4345.                             if (fileType==imgExtList[i])
  4346.                             {
  4347.                                 isImgURL=true;
  4348.                                 break;
  4349.                             }
  4350.                         }
  4351.                     }
  4352.                     if(isImgURL)
  4353.                     {
  4354.                         bRedirected=true;
  4355.                         var urlStr = Components.classes["@mozilla.org/supports-string;1"]
  4356.                             .createInstance(Components.interfaces.nsISupportsString);
  4357.                         urlStr.data = webNav.currentURI.spec;
  4358.                         gPrefService.setComplexValue("browser.navigation.nexturl",
  4359.                             Components.interfaces.nsISupportsString,
  4360.                             urlStr);
  4361.                         var blankPage="about:blank";
  4362.                         webNav.loadURI(blankPage, nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
  4363.                     }
  4364.                 }
  4365.             }//end default
  4366.             catch(ex){ dump ("Caught Exception: " + ex + "\n");}
  4367.  
  4368.             try
  4369.             {
  4370.                 if(!bRedirected)
  4371.                 {
  4372.                     // dump ("~~~~~~~~browser.js: webNav.reload(...)\n");
  4373.                     webNav.reload(reloadFlags);
  4374.                 }
  4375.             }
  4376.             catch(ex){ dump ("Caught Exception: " + ex + "\n");}
  4377.         }
  4378.     }
  4379.  
  4380.     function toggleAffectedChrome(aHide)
  4381.     {
  4382.         // chrome to toggle includes:
  4383.         //   (*) menubar
  4384.         //   (*) navigation bar
  4385.         //   (*) bookmarks toolbar
  4386.         //   (*) sidebar
  4387.         //   (*) find bar
  4388.         //   (*) statusbar
  4389.  
  4390.         var menuBar = document.getElementById("menubar-items");
  4391.         if (menuBar) menuBar.hidden = aHide;
  4392.         var navToolbox = document.getElementById("navigator-toolbox");
  4393.         navToolbox.hidden = aHide;
  4394.         var statusbar = document.getElementById("status-bar");
  4395.         statusbar.hidden = aHide;
  4396.         var throbber = document.getElementById("throbber-box");
  4397.         if (throbber) {
  4398.             throbber.hidden = aHide;
  4399.         }
  4400.         if (aHide)
  4401.         {
  4402.             gChromeState = {};
  4403.             var sidebar = document.getElementById("sidebar-box");
  4404.             gChromeState.sidebarOpen = !sidebar.hidden;
  4405.             gSidebarCommand = sidebar.getAttribute("sidebarcommand");
  4406.  
  4407.             var findBar = document.getElementById("FindToolbar");
  4408.             gChromeState.findOpen = !findBar.hidden;
  4409.             closeFindBar();
  4410.         }
  4411.     else {
  4412.         if (gChromeState.findOpen)
  4413.             openFindBar();
  4414.     }
  4415.  
  4416.     if (gChromeState.sidebarOpen)
  4417.         toggleSidebar(gSidebarCommand);
  4418. }
  4419.  
  4420. function onEnterPrintPreview()
  4421. {
  4422.     toggleAffectedChrome(true);
  4423. }
  4424.  
  4425. function onExitPrintPreview()
  4426. {
  4427.     // restore chrome to original state
  4428.     toggleAffectedChrome(false);
  4429.     if (spui) spui.RedrawComponents();
  4430. }
  4431.  
  4432. function browserDoOLECmd(iCmd)
  4433. {
  4434.     //Mercurial start
  4435.     var hpDoc = getTridentDocument();
  4436.  
  4437.     try
  4438.     {
  4439.         switch(iCmd)
  4440.         {
  4441.         case 0://Page Setup
  4442.             if(hpDoc)
  4443.                 hpDoc.doOLECmd(0);
  4444.             else
  4445.                 PrintUtils.showPageSetup();
  4446.             break;
  4447.         case 1://Print Preview
  4448.             // dump("Customize printpreview!\n");
  4449.             if (hpDoc)
  4450.             {
  4451.                 if (hpDoc.loadingState==nsIHTMLPluginDocument.LOADING)
  4452.                 {
  4453.                     ShowPrintErrorDialogForTrident(PRINT_PREVIEW_REQ_WHILE_TRIDENT_LOADING_ERROR);
  4454.                     //alert("Page loading not finished, please wait!");
  4455.                 }
  4456.                 else
  4457.                     hpDoc.doOLECmd(1);
  4458.             }
  4459.             else
  4460.                 PrintUtils.printPreview(onEnterPrintPreview, onExitPrintPreview);
  4461.             break;
  4462.         case 2:
  4463.             if (hpDoc)
  4464.             {
  4465.                 if (hpDoc.loadingState==nsIHTMLPluginDocument.LOADING)
  4466.                 {
  4467.                     ShowPrintErrorDialogForTrident(PRINT_REQ_WHILE_TRIDENT_LOADING_ERROR);
  4468.                     //alert("Page loading not finished, please wait!");
  4469.                 }
  4470.                 else
  4471.                     hpDoc.doOLECmd(2);
  4472.             }
  4473.             else
  4474.                 PrintUtils.print();
  4475.             break;
  4476.         case 4:
  4477.             if (hpDoc) hpDoc.doOLECmd(4);
  4478.             else ZoomManager.prototype.getInstance().reduce();
  4479.             break;
  4480.         case 5:
  4481.             if (hpDoc) hpDoc.doOLECmd(5);
  4482.             else ZoomManager.prototype.getInstance().enlarge();
  4483.             break;
  4484.         }
  4485.     }
  4486.     catch(e){ dump ("Caught Exception: " + e + "\n");}
  4487. }
  4488.  
  4489.  
  4490. function getMarkupDocumentViewer()
  4491. {
  4492.     return gBrowser.markupDocumentViewer;
  4493. }
  4494.  
  4495. /**
  4496. * Content area tooltip.
  4497. * XXX - this must move into XBL binding/equiv! Do not want to pollute
  4498. *       browser.js with functionality that can be encapsulated into
  4499. *       browser widget. TEMPORARY!
  4500. *
  4501. * NOTE: Any changes to this routine need to be mirrored in ChromeListener::FindTitleText()
  4502. *       (located in mozilla/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp)
  4503. *       which performs the same function, but for embedded clients that
  4504. *       don't use a XUL/JS layer. It is important that the logic of
  4505. *       these two routines be kept more or less in sync.
  4506. *       (pinkerton)
  4507. **/
  4508. function FillInHTMLTooltip(tipElement)
  4509. {
  4510.     var retVal = false;
  4511.     if (tipElement.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")
  4512.     return retVal;
  4513.  
  4514.     const XLinkNS = "http://www.w3.org/1999/xlink";
  4515.  
  4516.     var titleText = null;
  4517.     var XLinkTitleText = null;
  4518.  
  4519.     while (!titleText && !XLinkTitleText && tipElement) {
  4520.         if (tipElement.nodeType == Node.ELEMENT_NODE) {
  4521.             titleText = tipElement.getAttribute("title");
  4522.             XLinkTitleText = tipElement.getAttributeNS(XLinkNS, "title");
  4523.         }
  4524.         tipElement = tipElement.parentNode;
  4525.     }
  4526.  
  4527.     var texts = [titleText, XLinkTitleText];
  4528.     var tipNode = document.getElementById("aHTMLTooltip");
  4529.  
  4530.     for (var i = 0; i < texts.length; ++i) {
  4531.         var t = texts[i];
  4532.         if (t && t.search(/\S/) >= 0) {
  4533.             tipNode.setAttribute("label", t);
  4534.             retVal = true;
  4535.         }
  4536.     }
  4537.  
  4538.     return retVal;
  4539. }
  4540.  
  4541. var proxyIconDNDObserver = {
  4542.     onDragStart: function (aEvent, aXferData, aDragAction)
  4543.     {
  4544.         var value = gURLBar.value;
  4545.         // XXX - do we want to allow the user to set a blank page to their homepage?
  4546.         //       if so then we want to modify this a little to set about:blank as
  4547.         //       the homepage in the event of an empty urlbar.
  4548.         if (!value) return;
  4549.  
  4550.         var urlString = value + "\n" + window._content.document.title;
  4551.         var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
  4552.  
  4553.         aXferData.data = new TransferData();
  4554.         aXferData.data.addDataForFlavour("text/x-moz-url", urlString);
  4555.         aXferData.data.addDataForFlavour("text/unicode", value);
  4556.         aXferData.data.addDataForFlavour("text/html", htmlString);
  4557.  
  4558.         // we're copying the URL from the proxy icon, not moving
  4559.         // we specify all of them though, because d&d sucks and OS's
  4560.         // get confused if they don't get the one they want
  4561.         aDragAction.action =
  4562.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_COPY |
  4563.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_MOVE |
  4564.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  4565.     }
  4566. }
  4567.  
  4568. var homeButtonObserver = {
  4569.     onDrop: function (aEvent, aXferData, aDragSession)
  4570.     {
  4571.         var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  4572.         setTimeout(openHomeDialog, 0, url);
  4573.     },
  4574.  
  4575.     onDragOver: function (aEvent, aFlavour, aDragSession)
  4576.     {
  4577.         var statusTextFld = document.getElementById("statusbar-display");
  4578.         statusTextFld.label = gNavigatorBundle.getString("droponhomebutton");
  4579.         aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  4580.     },
  4581.  
  4582.     onDragExit: function (aEvent, aDragSession)
  4583.     {
  4584.         var statusTextFld = document.getElementById("statusbar-display");
  4585.         statusTextFld.label = "";
  4586.     },
  4587.  
  4588.     getSupportedFlavours: function ()
  4589.     {
  4590.         var flavourSet = new FlavourSet();
  4591.         flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4592.         flavourSet.appendFlavour("text/x-moz-url");
  4593.         flavourSet.appendFlavour("text/unicode");
  4594.         return flavourSet;
  4595.     }
  4596. }
  4597.  
  4598. function openHomeDialog(aURL)
  4599. {
  4600.     var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  4601.     var promptTitle = gNavigatorBundle.getString("droponhometitle");
  4602.     var promptMsg   = gNavigatorBundle.getString("droponhomemsg");
  4603.     var pressedVal  = promptService.confirmEx(window, promptTitle, promptMsg,
  4604.         (promptService.BUTTON_TITLE_YES * promptService.BUTTON_POS_0) +
  4605.         (promptService.BUTTON_TITLE_NO * promptService.BUTTON_POS_1),
  4606.         null, null, null, null, {value:0});
  4607.  
  4608.     if (pressedVal == 0) {
  4609.         try {
  4610.             var str = Components.classes["@mozilla.org/supports-string;1"]
  4611.                                 .createInstance(Components.interfaces.nsISupportsString);
  4612.             str.data = aURL;
  4613.             gPrefService.setComplexValue("browser.startup.homepage",
  4614.                                          Components.interfaces.nsISupportsString, str);
  4615.             var homeButton = document.getElementById("home-button");
  4616.             //homeButton.setAttribute("tooltiptext", aURL); //replaced as this is reported as a bug..JC
  4617.         } catch (ex) {
  4618.             dump("Failed to set the home page.\n"+ex+"\n");
  4619.         }
  4620.     }
  4621. }
  4622.  
  4623. var bookmarksButtonObserver = {
  4624.     onDrop: function (aEvent, aXferData, aDragSession)
  4625.     {
  4626.         var split = aXferData.data.split("\n");
  4627.         var url = split[0];
  4628.         if (url != aXferData.data) {  //do nothing if it's not a valid URL
  4629.             var name = split[1];
  4630.             openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "",
  4631.                        "centerscreen,chrome,dialog,resizable,dependent", name, url);
  4632.         }
  4633.     },
  4634.  
  4635.     onDragOver: function (aEvent, aFlavour, aDragSession)
  4636.     {
  4637.         var statusTextFld = document.getElementById("statusbar-display");
  4638.         statusTextFld.label = gNavigatorBundle.getString("droponbookmarksbutton");
  4639.         aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  4640.     },
  4641.  
  4642.     onDragExit: function (aEvent, aDragSession)
  4643.     {
  4644.         var statusTextFld = document.getElementById("statusbar-display");
  4645.         statusTextFld.label = "";
  4646.     },
  4647.  
  4648.     getSupportedFlavours: function ()
  4649.     {
  4650.         var flavourSet = new FlavourSet();
  4651.         flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4652.         flavourSet.appendFlavour("text/x-moz-url");
  4653.         flavourSet.appendFlavour("text/unicode");
  4654.         return flavourSet;
  4655.     }
  4656. }
  4657.  
  4658. var goButtonObserver = {
  4659.     onDragOver: function(aEvent, aFlavour, aDragSession)
  4660.     {
  4661.         var statusTextFld = document.getElementById("statusbar-display");
  4662.         statusTextFld.label = gNavigatorBundle.getString("dropongobutton");
  4663.         aEvent.target.setAttribute("dragover", "true");
  4664.         return true;
  4665.     },
  4666.     onDragExit: function (aEvent, aDragSession)
  4667.     {
  4668.         var statusTextFld = document.getElementById("statusbar-display");
  4669.         statusTextFld.label = "";
  4670.         aEvent.target.removeAttribute("dragover");
  4671.     },
  4672.     onDrop: function (aEvent, aXferData, aDragSession)
  4673.     {
  4674.         var xferData = aXferData.data.split("\n");
  4675.         var uri = xferData[0] ? xferData[0] : xferData[1];
  4676.         if (uri) {
  4677.             getBrowser().dragDropSecurityCheck(aEvent, aDragSession, uri);
  4678.             loadURI(uri, null, null);
  4679.         }
  4680.     },
  4681.     getSupportedFlavours: function ()
  4682.     {
  4683.         var flavourSet = new FlavourSet();
  4684.         flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4685.         flavourSet.appendFlavour("text/x-moz-url");
  4686.         flavourSet.appendFlavour("text/unicode");
  4687.         return flavourSet;
  4688.     }
  4689. }
  4690.  
  4691. var DownloadsButtonDNDObserver = {
  4692.     /////////////////////////////////////////////////////////////////////////////
  4693.     // nsDragAndDrop
  4694.     onDragOver: function (aEvent, aFlavour, aDragSession)
  4695.     {
  4696.         var statusTextFld = document.getElementById("statusbar-display");
  4697.         statusTextFld.label = gNavigatorBundle.getString("dropondownloadsbutton");
  4698.         aDragSession.canDrop = (aFlavour.contentType == "text/x-moz-url" ||
  4699.         aFlavour.contentType == "text/unicode");
  4700.     },
  4701.  
  4702.     onDragExit: function (aEvent, aDragSession)
  4703.     {
  4704.         var statusTextFld = document.getElementById("statusbar-display");
  4705.         statusTextFld.label = "";
  4706.     },
  4707.  
  4708.     onDrop: function (aEvent, aXferData, aDragSession)
  4709.     {
  4710.         var split = aXferData.data.split("\n");
  4711.         var url = split[0];
  4712.         if (url != aXferData.data) {  //do nothing, not a valid URL
  4713.             getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
  4714.  
  4715.             var name = split[1];
  4716.             saveURL(url, name, null, true, true);
  4717.         }
  4718.     },
  4719.     getSupportedFlavours: function ()
  4720.     {
  4721.         var flavourSet = new FlavourSet();
  4722.         flavourSet.appendFlavour("text/x-moz-url");
  4723.         flavourSet.appendFlavour("text/unicode");
  4724.         return flavourSet;
  4725.     }
  4726. }
  4727.  
  4728. function focusSearchBar()
  4729. {
  4730.    dump ("focusSearchBar()");
  4731.     var searchBar = document.getElementsByTagName("searchbar");
  4732.     if (searchBar.length > 0) {
  4733.         searchBar[0].select();
  4734.         searchBar[0].focus();
  4735.     }
  4736. }
  4737.  
  4738.  
  4739. // MERC - JCH: Wrapper for OpenSearch, called from nsHTMLPluginDocument.cpp
  4740. function WrapperOpenSearch(searchStr)
  4741. {
  4742.     OpenSearch("internet", searchStr);
  4743. }
  4744.  
  4745.  
  4746. // MERC - JCH: Slightly modified version of onTextEntered() from search.xml
  4747. function OpenSearch(tabName, searchStr, newTabFlag)
  4748. {
  4749.     dump("OpenSearch called. tabName : " + tabName + ", searchStr : " + searchStr + ", newTabFlag : " + newTabFlag);
  4750.     // dump("\nINPUT SEARCH STRING: " +searchStr+ "\n");
  4751.  
  4752.     var searchURL = null;
  4753.  
  4754.     var PREF = Components.classes["@mozilla.org/preferences-service;1"]
  4755.                          .getService(Components.interfaces.nsIPrefService)
  4756.                          .getBranch(null);
  4757.  
  4758.     var ISEARCHSVC = Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"]
  4759.                                .getService(Components.interfaces.nsIInternetSearchService);
  4760.  
  4761.  
  4762.     // GET THE SEARCH ENGINE AS SET IN SIDEBAR SEARCH OR NAV BAR SEARCH DROPDOWN MENUS
  4763.     var broadcaster = document.getElementById('searchEngineBroadcaster');
  4764.     var currentEngine = broadcaster.getAttribute("searchengine");
  4765.  
  4766.     // JMC : If it's netscape, use the context menu link, not the default from the .src file
  4767.     // dump("JMC: currentEngine is " + currentEngine + "\n");
  4768.  
  4769.     if (currentEngine.indexOf('NetscapeSearch') > -1)
  4770.     {
  4771.         searchURL = gPrefService.getCharPref('browser.contextSearch.URL') +(searchStr? encodeURIComponent(searchStr):"");
  4772.         // searchURL = gPrefService.getCharPref('browser.contextSearch.URL') + (searchStr? searchStr:"");
  4773.     } else {
  4774.         // NOW GET THE WHOLE SEARCH URI
  4775.         searchURL = ISEARCHSVC.GetInternetSearchURL(
  4776.             currentEngine, searchStr? encodeURIComponent(searchStr):"",
  4777.             0, 0, {value:0});
  4778.     }
  4779.     
  4780.     // dump("\nOUTPUT SEARCH STRING: " +searchURL+ "\n");
  4781.  
  4782.     // if the search box is empty, let's go to netscape search
  4783.     if (!searchURL) {
  4784.         // GO TO FALLBACK POSITION, WHICH IS NETSCAPE SEARCH PAGE
  4785.         // This gets chrome URL from browser\base\content\browser-sets.inc
  4786.         var navigatorRegionBundle = document.getElementById("bundle_browser_region");
  4787.         searchURL = navigatorRegionBundle.getString("fallbackDefaultSearchURL");
  4788.     }
  4789.     SearchLoadURL(searchURL, null);
  4790. }
  4791.  
  4792.  
  4793. // MERC - JCH: Made changes to regular expression which selects a valid URI.
  4794. // There is no internetsearch.rdf file so I commented out a bunch of
  4795. // code that tries to access it. The URIs associated with 'fallbackDefaultSearchURL'
  4796. // and 'browser.search.defaulturl' were changed to ones that work. See region.properties file.
  4797. function OpenSearchBAK(tabName, searchStr, newTabFlag)
  4798. {
  4799.     //This function needs to be split up someday.
  4800.     //XXXnoririty I don't want any prefs switching open by tabs to window
  4801.     //XXXpch: this routine needs to be cleaned up.
  4802.  
  4803.     // GET FALLBACK SEARCH ENGINE: jch set it to google.
  4804.     var defaultSearchURL = null;
  4805.     // This gets chrome URL from browser\base\content\browser-sets.inc
  4806.     var navigatorRegionBundle = document.getElementById("bundle_browser_region");
  4807.     var fallbackDefaultSearchURL = navigatorRegionBundle.getString("fallbackDefaultSearchURL");
  4808.  
  4809.     dump("#$#$#$  OpenSearch(): Search String : " +searchStr+ "\n");
  4810.  
  4811.     //Check to see if search string contains "://" or "ftp." or white space.
  4812.     //If it does treat as url and match for pattern
  4813.     //var urlmatch= /(:\/\/|^ftp\.)[^ \S]+$/
  4814.     var urlmatch = /^(http|https|ftp|chrome|file):\/\/.+|^www\..+/;
  4815.     var forceAsURL = urlmatch.test(searchStr);
  4816.  
  4817.     dump("#$#$#$  OpenSearch() FORCE TO A URL : " +forceAsURL+ "\n");
  4818.  
  4819.     // TRY TO GET PREFERRED SEARCH ENGINE
  4820.     try {
  4821.         defaultSearchURL = gPrefService.getComplexValue("browser.search.defaulturl",
  4822.         Components.interfaces.nsIPrefLocalizedString).data;
  4823.     } catch (ex) {}
  4824.  
  4825.     // Fallback to a default url (one that we can get sidebar search results for)
  4826.     if (!defaultSearchURL)
  4827.     defaultSearchURL = fallbackDefaultSearchURL;
  4828.  
  4829.     if (!defaultSearchURL) return;
  4830.  
  4831.     dump("#$#$#$  OpenSearch(): Default String : " +defaultSearchURL+ "\n");
  4832.  
  4833.     if (!searchStr) {
  4834.         return;
  4835.         // BrowserSearchInternet();
  4836.     } else {
  4837.  
  4838.         //Check to see if location bar field is a url
  4839.         //If it is a url go to URL.  A Url is "://" or "." as commented above
  4840.         //Otherwise search on entry
  4841.         if (forceAsURL) {
  4842.             if (!newTabFlag) {
  4843.                 loadURI(searchStr, null, null);
  4844.             }
  4845.         else {
  4846.             var newTab = getBrowser().addTab(searchStr);
  4847.             if (!pref.getBoolPref("browser.tabs.loadInBackground"))
  4848.             getBrowser().selectedTab = newTab;
  4849.         }
  4850.  
  4851.         return;
  4852.         // BrowserLoadURL(null, null)
  4853.     } else {
  4854.         if (searchStr) {
  4855.             var escapedSearchStr = encodeURIComponent(searchStr);
  4856.             defaultSearchURL += escapedSearchStr;
  4857.  
  4858.  
  4859.             /*
  4860.             var searchDS = Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"]
  4861.             .getService(Components.interfaces.nsIInternetSearchService);
  4862.  
  4863.  
  4864.             searchDS.RememberLastSearchText(escapedSearchStr);
  4865.             try {
  4866.             var searchEngineURI = gPrefService.getCharPref("browser.search.defaultengine");
  4867.             if (searchEngineURI) {
  4868.             var searchURL = getSearchUrl("actionButton");
  4869.  
  4870.             if (searchURL) {
  4871.             defaultSearchURL = searchURL + escapedSearchStr;
  4872.             } else {
  4873.             searchURL = searchDS.GetInternetSearchURL(searchEngineURI, escapedSearchStr, 0, 0, {value:0});
  4874.             if (searchURL)
  4875.             defaultSearchURL = searchURL;
  4876.             }
  4877.             }
  4878.             } catch (ex) {
  4879.             }
  4880.             */
  4881.  
  4882.             dump("#$#$#$ Complete string : " +defaultSearchURL+ "\n");
  4883.  
  4884.             if (!newTabFlag) {
  4885.                 loadURI(defaultSearchURL, null, null);
  4886.             }
  4887.         else {
  4888.             var newTab = getBrowser().addTab(defaultSearchURL);
  4889.             if (!pref.getBoolPref("browser.tabs.loadInBackground"))
  4890.             getBrowser().selectedTab = newTab;
  4891.         }
  4892.     }
  4893. }
  4894. }
  4895. }
  4896.  
  4897. function FillHistoryMenu(aParent, aMenu)
  4898. {
  4899.     // Remove old entries if any
  4900.     deleteHistoryItems(aParent);
  4901.  
  4902.     var sessionHistory = getWebNavigation().sessionHistory;
  4903.  
  4904.     var count = sessionHistory.count;
  4905.     var index = sessionHistory.index;
  4906.     var end;
  4907.     var j;
  4908.     var entry;
  4909.  
  4910.     switch (aMenu)
  4911.     {
  4912.         case "back":
  4913.         end = (index > MAX_HISTORY_MENU_ITEMS) ? index - MAX_HISTORY_MENU_ITEMS : 0;
  4914.         if ((index - 1) < end) return false;
  4915.         for (j = index - 1; j >= end; j--)
  4916.         {
  4917.             entry = sessionHistory.getEntryAtIndex(j, false);
  4918.             if (entry)
  4919.             createMenuItem(aParent, j, entry.title);
  4920.         }
  4921.         break;
  4922.         case "forward":
  4923.         end  = ((count-index) > MAX_HISTORY_MENU_ITEMS) ? index + MAX_HISTORY_MENU_ITEMS : count;
  4924.         if ((index + 1) >= end) return false;
  4925.         for (j = index + 1; j < end; j++)
  4926.         {
  4927.             entry = sessionHistory.getEntryAtIndex(j, false);
  4928.             if (entry)
  4929.             createMenuItem(aParent, j, entry.title);
  4930.         }
  4931.         break;
  4932.         case "go":
  4933.         aParent.lastChild.hidden = (count == 0);
  4934.         end = count > MAX_HISTORY_MENU_ITEMS ? count - MAX_HISTORY_MENU_ITEMS : 0;
  4935.         for (j = count - 1; j >= end; j--)
  4936.         {
  4937.             entry = sessionHistory.getEntryAtIndex(j, false);
  4938.             if (entry)
  4939.             createRadioMenuItem(aParent, j, entry.title, j==index);
  4940.         }
  4941.         break;
  4942.     }
  4943.     return true;
  4944. }
  4945.  
  4946. function addToUrlbarHistory()
  4947. {
  4948.     var urlToAdd = gURLBar.value;
  4949.     if (!urlToAdd)
  4950.     return;
  4951.     if (urlToAdd.search(/[\x00-\x1F]/) != -1) // don't store bad URLs
  4952.     return;
  4953.  
  4954.     if (!gGlobalHistory)
  4955.     gGlobalHistory = Components.classes["@mozilla.org/browser/global-history;2"]
  4956.     .getService(Components.interfaces.nsIBrowserHistory);
  4957.  
  4958.     if (!gURIFixup)
  4959.     gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
  4960.     .getService(Components.interfaces.nsIURIFixup);
  4961.     try {
  4962.         if (urlToAdd.indexOf(" ") == -1) {
  4963.             var fixedUpURI = gURIFixup.createFixupURI(urlToAdd, 0);
  4964.             if(fixedUpURI.spec=="about:blank")
  4965.             return;
  4966.             // MERC (DP): history debug
  4967.  
  4968.             gGlobalHistory.markPageAsTyped(fixedUpURI);
  4969.         }
  4970.     }
  4971.     catch(ex) { dump ("Caught Exception: " + ex + "\n");   }
  4972. }
  4973.  
  4974. function createMenuItem( aParent, aIndex, aLabel)
  4975. {
  4976.     var menuitem = document.createElement( "menuitem" );
  4977.     menuitem.setAttribute( "label", aLabel );
  4978.     menuitem.setAttribute( "index", aIndex );
  4979.     aParent.appendChild( menuitem );
  4980. }
  4981.  
  4982. function createRadioMenuItem( aParent, aIndex, aLabel, aChecked)
  4983. {
  4984.     var menuitem = document.createElement( "menuitem" );
  4985.     menuitem.setAttribute( "type", "radio" );
  4986.     menuitem.setAttribute( "label", aLabel );
  4987.     menuitem.setAttribute( "index", aIndex );
  4988.     if (aChecked==true)
  4989.     menuitem.setAttribute( "checked", "true" );
  4990.     aParent.appendChild( menuitem );
  4991. }
  4992.  
  4993. function deleteHistoryItems(aParent)
  4994. {
  4995.     var children = aParent.childNodes;
  4996.     for (var i = 0; i < children.length; i++)
  4997.     {
  4998.         var index = children[i].getAttribute("index");
  4999.         if (index)
  5000.         aParent.removeChild(children[i]);
  5001.     }
  5002. }
  5003.  
  5004. function toJavaScriptConsole()
  5005. {
  5006.     toOpenWindowByType("global:console", "chrome://global/content/console.xul");
  5007. }
  5008.  
  5009. function toOpenWindowByType(inType, uri, features)
  5010. {
  5011.     var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  5012.     var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  5013.     var topWindow = windowManagerInterface.getMostRecentWindow(inType);
  5014.  
  5015.     if (topWindow)
  5016.         topWindow.focus();
  5017.     else if (features)
  5018.         window.open(uri, "_blank", features);
  5019.     else
  5020.         window.open(uri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
  5021. }
  5022.  
  5023. // MERC (DP): when the user presses CTRL-N we look at the pref
  5024. // browser.tabs.newtabinsteadofwindow to determine whether to open
  5025. // a new window or a new tab.  effectively if the pref is on,
  5026. // pressing CTRL-N is equiv to pressing CTRL-T
  5027. function OpenBrowserWindowWithPref()
  5028. {
  5029.     if (gPrefService.getBoolPref("browser.tabs.newtabinsteadofwindow"))
  5030.     {
  5031.         BrowserHome(true);
  5032.     } else {
  5033.         OpenBrowserWindow();
  5034.     }
  5035. }
  5036.  
  5037. function tridentStartNav(urlStr)
  5038. {
  5039.     // dump ("\nStarting trident navigation to url " + urlStr);    
  5040.     getBrowser().userTypedClear = true;
  5041.     // JMC - Ought to call observer service notify for startDocumentLoad
  5042.     // But need to haul out the trident-hacked code there first
  5043.     UpdateStatusbarEngineIconTrident();
  5044. }
  5045.  
  5046. function tridentStartSubFrameNav(urlStr)
  5047. {
  5048.     // dump ("\nStarting trident subframe navigation to url " + urlStr);    
  5049. }
  5050.  
  5051. function tridentEndNav(urlStr)
  5052. {
  5053.     // dump ("\nStopping trident navigation to : " + urlStr);    
  5054.     // JMC - Ought to call observer service notify for endDocumentLoad
  5055.     // But need to haul out the trident-hacked code there first
  5056. }
  5057.  
  5058. function tridentEndSubFrameNav(urlStr)
  5059. {
  5060.     // dump ("\nStopping trident subframe navigation to : " + urlStr);    
  5061.     // JMC - Ought to call observer service notify for endDocumentLoad
  5062.     // But need to haul out the trident-hacked code there first
  5063. }
  5064.  
  5065.  
  5066.  
  5067. function OpenBrowserWindow()
  5068. {
  5069.     var charsetArg = new String();
  5070.     var handler = Components.classes['@mozilla.org/commandlinehandler/general-startup;1?type=browser'];
  5071.     handler = handler.getService();
  5072.     handler = handler.QueryInterface(Components.interfaces.nsICmdLineHandler);
  5073.     var startpage = handler.defaultArgs;
  5074.     var url = handler.chromeUrlForTask;
  5075.     var wintype = document.firstChild.getAttribute('windowtype');
  5076.  
  5077.     // if and only if the current window is a browser window and it has a document with a character
  5078.     // set, then extract the current charset menu setting from the current document and use it to
  5079.     // initialize the new browser window...
  5080.     if (window && (wintype == "navigator:browser") && window._content && window._content.document)
  5081.     {
  5082.         var DocCharset = window._content.document.characterSet;
  5083.         charsetArg = "charset="+DocCharset;
  5084.  
  5085.         //we should "inherit" the charset menu setting in a new window
  5086.         window.openDialog(url, "_blank", "chrome,all,dialog=no", startpage, charsetArg);
  5087.     }
  5088. else // forget about the charset information.
  5089.     {
  5090.         window.openDialog(url, "_blank", "chrome,all,dialog=no", startpage);
  5091.     }
  5092. }
  5093.  
  5094. function openAboutDialog()
  5095. {
  5096.     window.openDialog("chrome://browser/content/aboutDialog.xul", "About", "modal,centerscreen,chrome,resizable=no");
  5097. }
  5098.  
  5099. function BrowserCustomizeToolbar()
  5100. {
  5101.     // Disable the toolbar context menu items
  5102.     var menubar = document.getElementById("main-menubar");
  5103.     for (var i = 0; i < menubar.childNodes.length; ++i)
  5104.     menubar.childNodes[i].setAttribute("disabled", true);
  5105.  
  5106.     var cmd = document.getElementById("cmd_CustomizeToolbars");
  5107.     cmd.setAttribute("disabled", "true");
  5108.  
  5109.     window.openDialog("chrome://global/content/customizeToolbar.xul", "CustomizeToolbar",
  5110.     "chrome,dependent,dialog", document.getElementById("navigator-toolbox"));
  5111. }
  5112.  
  5113. function BrowserToolboxCustomizeDone(aToolboxChanged)
  5114. {
  5115.     // Update global UI elements that may have been added or removed
  5116.     if (aToolboxChanged) {
  5117.         gURLBar = document.getElementById("urlbar");
  5118.         gProxyButton = document.getElementById("page-proxy-button");
  5119.         gProxyFavIcon = document.getElementById("page-proxy-favicon");
  5120.         gProxyDeck = document.getElementById("page-proxy-deck");
  5121.         //gHomeButton.updateTooltip();  DO NOT USE..this is set in the browser.xul file
  5122.         //<added by SLiu , fixing customize personal bookmarks toolbar
  5123.         var ptf = document.getElementById("personal-bookmarks");
  5124.         if (ptf) populateBookmarks();
  5125.  
  5126.         //<added by MSD , fixing webmail button
  5127.         webmail.fixMenus();
  5128.  
  5129.         window.XULBrowserWindow.init();
  5130.     }
  5131.  
  5132.     // Update the urlbar
  5133.     var url = getWebNavigation().currentURI.spec;
  5134.     if (gURLBar) {
  5135.         gURLBar.value = url;
  5136.         var uri = Components.classes["@mozilla.org/network/standard-url;1"]
  5137.                             .createInstance(Components.interfaces.nsIURI);
  5138.         uri.spec = url;
  5139.         SetPageProxyState("valid", uri);
  5140.     }
  5141.  
  5142.     // Re-enable parts of the UI we disabled during the dialog
  5143.     var menubar = document.getElementById("main-menubar");
  5144.     for (var i = 0; i < menubar.childNodes.length; ++i)
  5145.         menubar.childNodes[i].setAttribute("disabled", false);
  5146.     var cmd = document.getElementById("cmd_CustomizeToolbars");
  5147.     cmd.removeAttribute("disabled");
  5148.  
  5149.     // fix up the personal toolbar folder
  5150.     var bt = document.getElementById("bookmarks-ptf");
  5151.     if (bt) {
  5152.         var btf = BMSVC.getBookmarksToolbarFolder().Value;
  5153.         var btchevron = document.getElementById("bookmarks-chevron");
  5154.         bt.ref = btf;
  5155.         btchevron.ref = btf;
  5156.         // no uniqueness is guaranteed, so we have to remove first
  5157.         try {
  5158.             bt.database.RemoveObserver(BookmarksToolbarRDFObserver);
  5159.             bt.controllers.removeController(BookmarksMenuController);
  5160.         } catch (ex) {
  5161.             // ignore
  5162.         }
  5163.         bt.database.AddObserver(BookmarksToolbarRDFObserver);
  5164.         bt.controllers.appendController(BookmarksMenuController);
  5165.         bt.builder.rebuild();
  5166.         btchevron.builder.rebuild();
  5167.  
  5168.         // fake a resize; this function takes care of flowing bookmarks
  5169.         // from the bar to the overflow item
  5170.         BookmarksToolbar.resizeFunc(null);
  5171.     }
  5172.  
  5173.     // Initialize SPUI
  5174.     // JMC - NEEDS to refresh spui components here, but this is not quite right
  5175.     // if (spui) spui.RefreshComponentList();
  5176.     if (spui) spui.RedrawComponents();
  5177.     reshuffleToolbars(true);
  5178.     // XXX Shouldn't have to do this, but I do
  5179.     
  5180.     // JMC - Don't like this...
  5181.     dump("Focusing the window\n");
  5182.     window.focus();
  5183. }
  5184.  
  5185. function reshuffleToolbars(aForce)
  5186. {
  5187.     var toolbox = document.getElementById("navigator-toolbox");
  5188.     var toolbars = toolbox.getElementsByTagName('toolbar');
  5189.     for (var i = 0; i < toolbars.length; i++) {
  5190.         var toolbar = toolbars.item(i);
  5191.           try {
  5192.               toolbar.allocateItems(aForce);
  5193.           } catch (ex) {
  5194.               // not a overflow toolbar
  5195.           }
  5196.     }
  5197.     toolbars = toolbox.getElementsByTagName('multibartray');
  5198.     for (var i = 0; i < toolbars.length; i++) {
  5199.         var toolbar = toolbars.item(i);
  5200.           try {
  5201.               toolbar.allocateItems(aForce);
  5202.           } catch (ex) {
  5203.               // not a overflow toolbar
  5204.           }
  5205.     }
  5206. }
  5207.  
  5208. var FullScreen =
  5209. {
  5210.     toggle: function()
  5211.     {
  5212.         // show/hide all menubars, toolbars, and statusbars (except the full screen toolbar)
  5213.         this.showXULChrome("toolbar", window.fullScreen);
  5214.         this.showXULChrome("multibar", window.fullScreen);
  5215.         this.showXULChrome("statusbar", window.fullScreen);
  5216.         var throbberBox = document.getElementById('throbber-box');
  5217.         if (throbberBox) {
  5218.             throbberBox.setAttribute('hidden', !window.fullScreen); //JMC : hide throbber in fullscreen
  5219.         }
  5220.         var popupBlockerButton = document.getElementById("popupblocker-button");
  5221.         if (popupBlockerButton)
  5222.             popupBlockerButton.setAttribute('hideLabel', !window.fullScreen);
  5223.     },
  5224.  
  5225.     showXULChrome: function(aTag, aShow)
  5226.     {
  5227.         var XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  5228.         var els = document.getElementsByTagNameNS(XULNS, aTag);
  5229.  
  5230.         var i;
  5231.         for (i = 0; i < els.length; ++i) {
  5232.             // XXX don't interfere with previously collapsed toolbars
  5233.             if (els[i].getAttribute("fullscreentoolbar") == "true") {
  5234.                 if (!aShow) {
  5235.                     var toolbarMode = els[i].getAttribute("mode");
  5236.                     var iconSize = els[i].getAttribute("iconsize");
  5237.                     var contextMenu = els[i].getAttribute("context");
  5238.  
  5239.                     if (toolbarMode != "text") {
  5240.                         els[i].setAttribute("saved-mode", toolbarMode);
  5241.                         els[i].setAttribute("saved-iconsize", iconSize);
  5242.                         els[i].setAttribute("mode", "icons");
  5243.                         els[i].setAttribute("iconsize", "small");
  5244.                     }
  5245.  
  5246.                     // XXX See bug 202978: we disable the context menu
  5247.                     // to prevent customization while in fullscreen, which
  5248.                     // causes menu breakage.
  5249.                     els[i].setAttribute("saved-context", contextMenu);
  5250.                     els[i].removeAttribute("context");
  5251.                 }
  5252.             else {
  5253.                 if (els[i].hasAttribute("saved-mode")) {
  5254.                     var savedMode = els[i].getAttribute("saved-mode");
  5255.                     els[i].setAttribute("mode", savedMode);
  5256.                     els[i].removeAttribute("saved-mode");
  5257.                 }
  5258.  
  5259.                 if (els[i].hasAttribute("saved-iconsize")) {
  5260.                     var savedIconSize = els[i].getAttribute("saved-iconsize");
  5261.                     els[i].setAttribute("iconsize", savedIconSize);
  5262.                     els[i].removeAttribute("saved-iconsize");
  5263.                 }
  5264.  
  5265.                 // XXX see above.
  5266.                 if (els[i].hasAttribute("saved-context")) {
  5267.                     var savedContext = els[i].getAttribute("saved-context");
  5268.                     els[i].setAttribute("context", savedContext);
  5269.                     els[i].removeAttribute("saved-context");
  5270.                 }
  5271.             }
  5272.         } else {
  5273.             // use moz-collapsed so it doesn't persist hidden/collapsed,
  5274.             // so that new windows don't have missing toolbars
  5275.             if (aShow)
  5276.             els[i].removeAttribute("moz-collapsed");
  5277.         else
  5278.             els[i].setAttribute("moz-collapsed", "true");
  5279.         }
  5280.     }
  5281.     var controls = document.getElementsByAttribute("fullscreencontrol", "true");
  5282.     for (i = 0; i < controls.length; ++i)
  5283.     controls[i].hidden = aShow;
  5284.  
  5285. }
  5286. };
  5287.  
  5288. function nsBrowserStatusHandler()
  5289. {
  5290.     this.init();
  5291. }
  5292.  
  5293. nsBrowserStatusHandler.prototype =
  5294. {
  5295.     // Stored Status, Link and Loading values
  5296.     status : "",
  5297.     defaultStatus : "",
  5298.     jsStatus : "",
  5299.     jsDefaultStatus : "",
  5300.     overLink : "",
  5301.     startTime : 0,
  5302.     statusText: "",
  5303.     lastURI: null,
  5304.  
  5305.     statusTimeoutInEffect : false,
  5306.  
  5307.     QueryInterface : function(aIID)
  5308.     {
  5309.         if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
  5310.         aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
  5311.         aIID.equals(Components.interfaces.nsIXULBrowserWindow) ||
  5312.         aIID.equals(Components.interfaces.nsISupports))
  5313.         return this;
  5314.         throw Components.results.NS_NOINTERFACE;
  5315.     },
  5316.  
  5317.     init : function()
  5318.     {
  5319.         this.throbberElement = document.getElementById("throbberBroadcaster");
  5320.         this.statusMeter     = document.getElementById("statusbar-icon");
  5321.         this.stopCommand     = document.getElementById("Browser:Stop");
  5322.         this.stopReloadBtn   = document.getElementById("stop-reload-button");
  5323.         this.statusTextField = document.getElementById("statusbar-display");
  5324.         this.securityButton  = document.getElementById("security-button");
  5325.         this.urlBar          = document.getElementById("urlbar");
  5326.  
  5327.         // Initialize the security button's state and tooltip text
  5328.         const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  5329.         this.onSecurityChange(null, null, nsIWebProgressListener.STATE_IS_INSECURE);
  5330.     },
  5331.  
  5332.     destroy : function()
  5333.     {
  5334.         // XXXjag to avoid leaks :-/, see bug 60729
  5335.         this.throbberElement = null;
  5336.         this.statusMeter     = null;
  5337.         this.stopCommand     = null;
  5338.         this.stopReloadBtn   = null;
  5339.         this.statusTextField = null;
  5340.         this.securityButton  = null;
  5341.         this.urlBar          = null;
  5342.         this.statusText      = null;
  5343.         this.lastURI         = null;
  5344.     },
  5345.  
  5346.     setJSStatus : function(status)
  5347.     {
  5348.         this.jsStatus = status;
  5349.         this.updateStatusField();
  5350.     },
  5351.  
  5352.     setJSDefaultStatus : function(status)
  5353.     {
  5354.         this.jsDefaultStatus = status;
  5355.         this.updateStatusField();
  5356.     },
  5357.  
  5358.     setDefaultStatus : function(status)
  5359.     {
  5360.         this.defaultStatus = status;
  5361.         this.updateStatusField();
  5362.     },
  5363.  
  5364.     setOverLink : function(link, b)
  5365.     {
  5366.         this.overLink = link;
  5367.         this.updateStatusField();
  5368.     },
  5369.  
  5370.     updateStatusField : function()
  5371.     {
  5372.         var text = this.overLink || this.status || this.jsStatus || this.jsDefaultStatus || this.defaultStatus;
  5373.  
  5374.         // check the current value so we don't trigger an attribute change
  5375.         // and cause needless (slow!) UI updates
  5376.         if (this.statusText != text) {
  5377.             this.statusTextField.label = text;
  5378.             this.statusText = text;
  5379.         }
  5380.     },
  5381.  
  5382.     onLinkIconAvailable : function(aBrowser, aHref)
  5383.     {
  5384. //        dump( "))      WMWMWMWMWMW===> onLinkIconAvailable(aBowser, \""+aHref+"\")\n" );
  5385.         if (gProxyFavIcon &&
  5386.         gBrowser.mCurrentBrowser == aBrowser &&
  5387.         gBrowser.userTypedValue === null)
  5388.         {
  5389.             PageProxySetIcon(aHref);
  5390.         }
  5391.  
  5392.         aBrowser.mFavIconURL = aHref;
  5393.     },
  5394.  
  5395.     onProgressChange : function (aWebProgress, aRequest,
  5396.     aCurSelfProgress, aMaxSelfProgress,
  5397.     aCurTotalProgress, aMaxTotalProgress)
  5398.     {
  5399.         if (aMaxTotalProgress > 0) {
  5400.             // This is highly optimized.  Don't touch this code unless
  5401.             // you are intimately familiar with the cost of setting
  5402.             // attrs on XUL elements. -- hyatt
  5403.             var percentage = (aCurTotalProgress * 100) / aMaxTotalProgress;
  5404.             this.statusMeter.value = percentage;
  5405.         }
  5406.     },
  5407.  
  5408.     onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus)
  5409.     {
  5410.         if (aRequest) {
  5411.             blacklistUtils.debug('\nonStateChange('+aRequest.name+')\n');
  5412.             if (blacklistUtils.IsSiteInPhishList(aRequest.originalURI)) {
  5413.                 // ShowPhishingSiteWarning();
  5414.                 displayNotificationBar("phishing",[aRequest.originalURI]);
  5415.                 //aRequest.suspend();
  5416.                 //aRequest.cancel(Components.results.NS_BINDING_ABORTED);
  5417.             } else if (blacklistUtils.IsSiteInSpywareList(aRequest.originalURI)) {
  5418.                 //ShowSpywareSiteWarning();
  5419.                 displayNotificationBar("spyware",[aRequest.originalURI]);
  5420.             }
  5421.         }
  5422.         /*
  5423.         if (aRequest) {
  5424.         for (var p in aRequest) {
  5425.         dump(' aRequest.'+p+': '+aRequest[p]+'\n');
  5426.         }
  5427.         }
  5428.         */
  5429.  
  5430.         const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  5431.         const nsIChannel = Components.interfaces.nsIChannel;
  5432.         if (aStateFlags & nsIWebProgressListener.STATE_START) {
  5433.             // This (thanks to the filter) is a network start or the first
  5434.             // stray request (the first request outside of the document load),
  5435.             // initialize the throbber and his friends.
  5436.  
  5437.             // always reset the favicon
  5438.             if (gBrowser.mTabbedMode) {
  5439.                 var browserIndex = gBrowser.getBrowserIndexForDocument(aWebProgress.DOMWindow);
  5440.                 if (browserIndex != -1)
  5441.                 gBrowser.getBrowserAtIndex(browserIndex).mFavIconURL = null;
  5442.             }
  5443.         else
  5444.             gBrowser.mCurrentBrowser.mFavIconURL = null;
  5445.  
  5446.             // Call start document load listeners (only if this is a network load)
  5447.             if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK &&
  5448.             aRequest && aWebProgress.DOMWindow == content)
  5449.             this.startDocumentLoad(aRequest);
  5450.  
  5451.             if (this.throbberElement) {
  5452.                 // Turn the throbber on.
  5453.                 this.throbberElement.setAttribute("busy", "true");
  5454.             }
  5455.  
  5456.             // Turn the status meter on.
  5457.             this.statusMeter.value = 0;  // be sure to clear the progress bar
  5458.             if (gProgressCollapseTimer) {
  5459.                 window.clearTimeout(gProgressCollapseTimer);
  5460.                 gProgressCollapseTimer = null;
  5461.             }
  5462.         else
  5463.             this.statusMeter.parentNode.collapsed = false;
  5464.  
  5465.             // XXX: This needs to be based on window activity...
  5466.             this.stopCommand.removeAttribute("disabled");
  5467.             if (this.stopReloadBtn) {
  5468.                 // JCH: Need to set label according to state
  5469.                 this.stopReloadBtn.setAttribute("label","Stop");
  5470.                 this.stopReloadBtn.setAttribute("state","stop");
  5471.                 this.stopReloadBtn.removeAttribute("oncommand");
  5472.                 this.stopReloadBtn.setAttribute("command","Browser:Stop");
  5473.             }
  5474.         }
  5475.     else if (aStateFlags & nsIWebProgressListener.STATE_STOP) {
  5476.         if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
  5477.             if (aRequest) {
  5478.                 if (aWebProgress.DOMWindow == content)
  5479.                 this.endDocumentLoad(aRequest, aStatus);
  5480.             }
  5481.         }
  5482.  
  5483.         // This (thanks to the filter) is a network stop or the last
  5484.         // request stop outside of loading the document, stop throbbers
  5485.         // and progress bars and such
  5486.         if (aRequest) {
  5487.             var msg = "";
  5488.             // Get the channel if the request is a channel
  5489.             var channel;
  5490.             try {
  5491.                 channel = aRequest.QueryInterface(nsIChannel);
  5492.             }
  5493.             catch(e) { };
  5494.             if (channel) {
  5495.                 var location = channel.URI;
  5496.  
  5497.                 // For keyword URIs clear the user typed value since they will be changed into real URIs
  5498.                 if (location.scheme == "keyword" && aWebProgress.DOMWindow == content)
  5499.                     getBrowser().userTypedValue = null;
  5500.  
  5501.                 if (location.spec != "about:blank") {
  5502.                     const kErrorBindingAborted = 0x804B0002;
  5503.                     const kErrorNetTimeout = 0x804B000E;
  5504.                     switch (aStatus) {
  5505.                         case kErrorBindingAborted:
  5506.                         msg = gNavigatorBundle.getString("nv_stopped");
  5507.                         break;
  5508.                         case kErrorNetTimeout:
  5509.                         msg = gNavigatorBundle.getString("nv_timeout");
  5510.                         break;
  5511.                     }
  5512.                 }
  5513.             }
  5514.             // If msg is false then we did not have an error (channel may have
  5515.             // been null, in the case of a stray image load).
  5516.             if (!msg) {
  5517.                 msg = gNavigatorBundle.getString("nv_done");
  5518.             }
  5519.             this.status = "";
  5520.             this.setDefaultStatus(msg);
  5521.         }
  5522.  
  5523.         // Turn the progress meter and throbber off.
  5524.         gProgressCollapseTimer = window.setTimeout(
  5525.         function() {
  5526.             gProgressMeterPanel.collapsed = true;
  5527.             gProgressCollapseTimer = null;
  5528.         }, 100);
  5529.  
  5530.         if (this.throbberElement)
  5531.         this.throbberElement.removeAttribute("busy");
  5532.  
  5533.         this.stopCommand.setAttribute("disabled", "true");
  5534.         if (this.stopReloadBtn) {
  5535.             // JCH: Need to set label according to state
  5536.             this.stopReloadBtn.setAttribute("label","Reload");
  5537.             this.stopReloadBtn.setAttribute("state","reload");
  5538.             this.stopReloadBtn.removeAttribute("command");
  5539.             this.stopReloadBtn.setAttribute("oncommand","BrowserStopReload(event);");
  5540.         }
  5541.     }
  5542. },
  5543.  
  5544. onLocationChange : function(aWebProgress, aRequest, aLocation)
  5545. {
  5546.     var location = aLocation.spec;
  5547.     if (location == "about:blank") location = "";
  5548.     // dump("browser.js: onLocationChange: location = "+location+"\n");
  5549.  
  5550.     if (blacklistUtils.IsSiteInPhishList(aLocation)) {
  5551.         // Get partners who think it's bad
  5552.         displayNotificationBar("phishing", [aLocation]);
  5553.     } else if (blacklistUtils.IsSiteInSpywareList(aLocation)) {
  5554.         // ShowSpywareSiteWarning();
  5555.         displayNotificationBar("spyware", [aLocation]);
  5556.     }
  5557.  
  5558.     // This code here does not compare uris exactly when determining
  5559.     // whether or not the message should be hidden since the message
  5560.     // may be prematurely hidden when an install is invoked by a click
  5561.     // on a link that looks like this:
  5562.     //
  5563.     // <a href="#" onclick="return install();">Install Foo</a>
  5564.     //
  5565.     // - which fires a onLocationChange message to uri + '#'...
  5566.     var selectedBrowser = getBrowser().selectedBrowser;
  5567.     if (selectedBrowser.lastURI) {
  5568.         var oldSpec = selectedBrowser.lastURI.spec;
  5569.         var oldIndexOfHash = oldSpec.indexOf("#");
  5570.         if (oldIndexOfHash != -1)
  5571.         oldSpec = oldSpec.substr(0, oldIndexOfHash);
  5572.         var newSpec = aLocation.spec;
  5573.         var newIndexOfHash = newSpec.indexOf("#");
  5574.         if (newIndexOfHash != -1)
  5575.         newSpec = newSpec.substr(0, newSpec.indexOf("#"));
  5576.         
  5577.         if (newSpec != oldSpec) {
  5578.             var tabbrowser = getBrowser();
  5579.             tabbrowser.hideMessage(tabbrowser.selectedBrowser, "both");
  5580.             gCurrentNotificationBar = null;
  5581.         } else {
  5582.             // MERC (DP): added this ELSE branch to fix BLT # 129362 - popup message bar doesn't
  5583.             // disappear when you turn off blocking and reload page.
  5584.             var site = sitecontrols.SCSVC.getResourceForURI(gBrowser.currentURI.spec);
  5585.             var blockState = sitecontrols.SCSVC.readSiteControlResource(site, 'allowPopups');
  5586.             if (blockState == 'true' && gCurrentNotificationBar == 'popup') {
  5587.                 var tabbrowser = getBrowser();
  5588.                 tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top");
  5589.                 gCurrentNotificationBar = null;
  5590.             }
  5591.         }
  5592.     }
  5593.     selectedBrowser.lastURI = aLocation;
  5594.  
  5595.     this.setOverLink("", null);
  5596.  
  5597.     // MERC - JCH : update popup block button
  5598.     SetPopupBlockToggle();
  5599.  
  5600.     // We should probably not do this if the value has changed since the user
  5601.     // searched
  5602.     // Update urlbar only if a new page was loaded on the primary content area
  5603.     // Do not update urlbar if there was a subframe navigation
  5604.  
  5605.     var browser = getBrowser().selectedBrowser;
  5606.     var findField = document.getElementById("find-field");
  5607.  
  5608.     // MERC: set up for Trident
  5609.     var hpDoc = getTridentDocument();
  5610.  
  5611.     if (aWebProgress.DOMWindow == content) {
  5612.         // The document loaded correctly, clear the value if we should
  5613.         if (browser.userTypedClear)
  5614.         {
  5615.             // dump("Going to clear user's typed values\n");
  5616.             browser.userTypedValue = null;
  5617.         }
  5618.         
  5619.         if (findField)
  5620.             setTimeout(function() { findField.value = browser.findString; }, 0, findField, browser);
  5621.  
  5622.         //XXXBlake don't we have to reinit this.urlBar, etc.
  5623.         //         when the toolbar changes?
  5624.  
  5625.         if (hpDoc) {
  5626.             //clean it here as we are not using startDocumentLoad
  5627.             // JMC - trying to fix clobbering of urlbar
  5628.             // If the typedValue is the same as where we are, clear it
  5629.             // dump ("/nJMC Trying to clear userTypedValue when appropriate");
  5630.             // dump ("Location is : " + location + ", userTypedValue : " + browser.userTypedValue);
  5631.             
  5632.             if (browser.userTypedClear || browser.userTypedValue == location)
  5633.             {
  5634.                 // dump("Going to clear user's typed values because we're hpDoc?\n");
  5635.                 browser.userTypedValue = null;
  5636.             }
  5637.             if (findField)
  5638.                 closeFindBar();
  5639.         }
  5640.         if (gURLBar) {
  5641.             var userTypedValue = browser.userTypedValue;
  5642.             if (!userTypedValue) {
  5643.                 // If the url has "wyciwyg://" as the protocol, strip it off.
  5644.                 // Nobody wants to see it on the urlbar for dynamically generated
  5645.                 // pages.
  5646.                 if (!gURIFixup) {
  5647.                     gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
  5648.                                           .getService(Components.interfaces.nsIURIFixup);
  5649.                 }
  5650.                 if (location && gURIFixup) {
  5651.                     try {
  5652.                         var locationURI = gURIFixup.createExposableURI(aLocation);
  5653.                         location = locationURI.spec;
  5654.                     } catch (exception) {}
  5655.                 }
  5656.  
  5657.                 if (getBrowser().forceSyncURLBarUpdate) {
  5658.                     gURLBar.value = ""; // hack for bug 249322
  5659.                     gURLBar.value = location;
  5660.                     SetPageProxyState("valid", aLocation);
  5661.                 } else {
  5662.                     setTimeout(function(loc, aloc) {
  5663.                         gURLBar.value = ""; // hack for bug 249322
  5664.                         gURLBar.value = loc;
  5665.                         SetPageProxyState("valid", aloc);
  5666.                     }, 0, location, aLocation);
  5667.                 }
  5668.  
  5669.                 // Setting the urlBar value in some cases causes userTypedValue to
  5670.                 // become set because of oninput, so reset it to its old value.
  5671.                 browser.userTypedValue = userTypedValue;
  5672.             } else {
  5673.                 // JMC - introduced bug with urlBarValue
  5674.                 dump ("userTYpedValue is non-null, setting invalid proxy state\n");
  5675.                 gURLBar.value = userTypedValue;
  5676.                 SetPageProxyState("invalid", null);
  5677.             }
  5678.         }
  5679.     }
  5680.     //MERC - Durga : display default passcard on toolbar in text mode
  5681.     // TODO (DP): this should be in the onClick handler of tabbrowser as well
  5682.     SetPasscard();
  5683.  
  5684.     UpdateBackForwardButtons();
  5685.  
  5686.     if (findField && gFindMode != FIND_NORMAL) {
  5687.         // Close the Find toolbar if we're in old-style TAF mode
  5688.         closeFindBar();
  5689.         gBackProtectBuffer = 0;
  5690.     }
  5691.  
  5692.     //fix bug 253793 - turn off highlight when page changes
  5693.     if (document.getElementById("highlight").checked)
  5694.         document.getElementById("highlight").removeAttribute("checked");
  5695.  
  5696.     // clear missing plugins
  5697.     gMissingPluginInstaller.clearMissingPlugins(getBrowser().selectedTab);
  5698.  
  5699.     setTimeout(function () { updatePageLivemarks(); }, 0);
  5700. },
  5701.  
  5702. onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
  5703. {
  5704.     this.status = aMessage;
  5705.     this.updateStatusField();
  5706. },
  5707.  
  5708. onSecurityChange : function(aWebProgress, aRequest, aState)
  5709. {
  5710.     const wpl = Components.interfaces.nsIWebProgressListener;
  5711.     this.securityButton.removeAttribute("label");
  5712.  
  5713.     switch (aState) {
  5714.     case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
  5715.         this.securityButton.setAttribute("level", "high");
  5716.         if (this.urlBar)
  5717.         this.urlBar.setAttribute("level", "high");
  5718.         try {
  5719.             this.securityButton.setAttribute("label",
  5720.             gBrowser.contentWindow.location.host);
  5721.         } catch(exception) {}
  5722.         break;
  5723.     case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
  5724.         this.securityButton.setAttribute("level", "low");
  5725.         if (this.urlBar)
  5726.         this.urlBar.setAttribute("level", "low");
  5727.         try {
  5728.             this.securityButton.setAttribute("label",
  5729.             gBrowser.contentWindow.location.host);
  5730.         } catch(exception) {}
  5731.         break;
  5732.     case wpl.STATE_IS_BROKEN:
  5733.         this.securityButton.setAttribute("level", "broken");
  5734.         if (this.urlBar)
  5735.         this.urlBar.setAttribute("level", "broken");
  5736.         break;
  5737.     case wpl.STATE_IS_INSECURE:
  5738.     default:
  5739.         this.securityButton.removeAttribute("level");
  5740.         if (this.urlBar)
  5741.         this.urlBar.removeAttribute("level");
  5742.         break;
  5743.     }
  5744.  
  5745.     var securityUI = gBrowser.securityUI;
  5746.     if (securityUI) {
  5747.         this.securityButton.setAttribute("tooltiptext", securityUI.tooltipText);
  5748.         if (this.urlBar)
  5749.         this.urlBar.setAttribute("infotext", securityUI.tooltipText);
  5750.     }
  5751. else {
  5752.     this.securityButton.setAttribute("tooltiptext", securityUI.tooltipText);
  5753.     if (this.urlBar)
  5754.     this.urlBar.removeAttribute("infotext");
  5755. }
  5756. },
  5757.  
  5758. startDocumentLoad : function(aRequest)
  5759. {
  5760.     dump ("StartDocumentLoad\n");
  5761.     
  5762.     // It's okay to clear what the user typed when we start
  5763.     // loading a document. If the user types, this flag gets
  5764.     // set to false, if the document load ends without an
  5765.     // onLocationChange, this flag also gets set to false
  5766.     // (so we keep it while switching tabs after failed load
  5767.     getBrowser().userTypedClear = true;
  5768.  
  5769.     // clear out livemark data
  5770.     gBrowser.mCurrentBrowser.livemarkLinks = null;
  5771.     
  5772.     // hide all message bars on reload
  5773.     gBrowser.hideMessage(gBrowser.mCurrentBrowser, "both");
  5774.     gCurrentNotificationBar = null;
  5775.  
  5776.     const nsIChannel = Components.interfaces.nsIChannel;
  5777.     var urlStr = aRequest.QueryInterface(nsIChannel).URI.spec;
  5778.     var observerService = Components.classes["@mozilla.org/observer-service;1"]
  5779.     .getService(Components.interfaces.nsIObserverService);
  5780.     try {
  5781.         observerService.notifyObservers(_content, "StartDocumentLoad", urlStr);
  5782.     } catch (e) {
  5783.     }
  5784. },
  5785.  
  5786. endDocumentLoad : function(aRequest, aStatus)
  5787. {
  5788.     dump ("endDocumentLoad\n");
  5789.     // The document is done loading, it's okay to clear
  5790.     // the value again.
  5791.     getBrowser().userTypedClear = false;
  5792.  
  5793.     const nsIChannel = Components.interfaces.nsIChannel;
  5794.     var urlStr = aRequest.QueryInterface(nsIChannel).originalURI.spec;
  5795.  
  5796.     var observerService = Components.classes["@mozilla.org/observer-service;1"]
  5797.     .getService(Components.interfaces.nsIObserverService);
  5798.  
  5799.     var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad";
  5800.     try {
  5801.         observerService.notifyObservers(_content, notification, urlStr);
  5802.     } catch (e) {
  5803.     }
  5804.     setTimeout(function() { if (document.getElementById("highlight").checked) toggleHighlight(true); }, 0);
  5805.     
  5806.     UpdateStatusbarPartnerIcons();
  5807. }
  5808. }
  5809.  
  5810. function nsBrowserAccess()
  5811. {
  5812. }
  5813.  
  5814. nsBrowserAccess.prototype =
  5815. {
  5816.     QueryInterface : function(aIID)
  5817.     {
  5818.         if (aIID.equals(nsCI.nsIBrowserDOMWindow) ||
  5819.         aIID.equals(nsCI.nsISupports))
  5820.         return this;
  5821.         throw Components.results.NS_NOINTERFACE;
  5822.     },
  5823.  
  5824.     openURI : function(aURI, aOpener, aWhere, aContext)
  5825.     {
  5826.         var newWindow = null;
  5827.         var referrer = null;
  5828.         if (aWhere == nsCI.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW) {
  5829.             switch (aContext) {
  5830.                 case nsCI.nsIBrowserDOMWindow.OPEN_EXTERNAL :
  5831.                 aWhere = gPrefService.getIntPref("browser.link.open_external");
  5832.                 break;
  5833.                 default : // OPEN_NEW or an illegal value
  5834.                 aWhere = gPrefService.getIntPref("browser.link.open_newwindow");
  5835.             }
  5836.         }
  5837.         var url = aURI ? aURI.spec : "about:blank";
  5838.         switch(aWhere) {
  5839.             case nsCI.nsIBrowserDOMWindow.OPEN_NEWWINDOW :
  5840.             newWindow = openDialog(getBrowserURL(), "_blank", "all,dialog=no", url);
  5841.             break;
  5842.             case nsCI.nsIBrowserDOMWindow.OPEN_NEWTAB :
  5843.             var newTab = gBrowser.addTab("about:blank");
  5844.             if (!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
  5845.             gBrowser.selectedTab = newTab;
  5846.             newWindow = gBrowser.getBrowserForTab(newTab).docShell
  5847.             .QueryInterface(nsCI.nsIInterfaceRequestor)
  5848.             .getInterface(nsCI.nsIDOMWindow);
  5849.             try {
  5850.                 if (aOpener) {
  5851.                     referrer = Components.classes["@mozilla.org/network/standard-url;1"]
  5852.                     .createInstance(nsCI.nsIURI);
  5853.                     referrer.spec = Components.lookupMethod(aOpener,"location")
  5854.                     .call(aOpener);
  5855.                 }
  5856.                 newWindow.QueryInterface(nsCI.nsIInterfaceRequestor)
  5857.                 .getInterface(nsCI.nsIWebNavigation)
  5858.                 .loadURI(url, nsCI.nsIWebNavigation.LOAD_FLAGS_NONE,
  5859.                 referrer, null, null);
  5860.             } catch(e) {
  5861.             }
  5862.             break;
  5863.             default : // OPEN_CURRENTWINDOW or an illegal value
  5864.             try {
  5865.                 if (aOpener) {
  5866.                     newWindow = Components.lookupMethod(aOpener,"top")
  5867.                     .call(aOpener);
  5868.                     referrer = Components.classes["@mozilla.org/network/standard-url;1"]
  5869.                     .createInstance(nsCI.nsIURI);
  5870.                     referrer.spec = Components.lookupMethod(aOpener,"location")
  5871.                     .call(aOpener);
  5872.                     newWindow.QueryInterface(nsCI.nsIInterfaceRequestor)
  5873.                     .getInterface(nsIWebNavigation)
  5874.                     .loadURI(url, nsIWebNavigation.LOAD_FLAGS_NONE, referrer,
  5875.                     null, null);
  5876.                 } else {
  5877.                     newWindow = gBrowser.selectedBrowser.docShell
  5878.                     .QueryInterface(nsCI.nsIInterfaceRequestor)
  5879.                     .getInterface(nsCI.nsIDOMWindow);
  5880.                     loadURI(url, null);
  5881.                 }
  5882.             } catch(e) {
  5883.             }
  5884.         }
  5885.         return newWindow;
  5886.     }
  5887. }
  5888.  
  5889. function onViewToolbarsPopupShowing(aEvent)
  5890. {
  5891.     var popup = aEvent.target;
  5892.     var i;
  5893.  
  5894.     // Empty the menu
  5895.     for (i = popup.childNodes.length-1; i >= 0; --i) {
  5896.         var deadItem = popup.childNodes[i];
  5897.         if (deadItem.hasAttribute("toolbarindex"))
  5898.         popup.removeChild(deadItem);
  5899.     }
  5900.  
  5901.     var firstMenuItem = popup.firstChild;
  5902.     var highestOrdinal = 0;
  5903.     
  5904.     var toolbox = document.getElementById("navigator-toolbox");
  5905.     for (i = 0; i < toolbox.childNodes.length; ++i) {
  5906.         var toolbar = toolbox.childNodes[i];
  5907.         var toolbarName = toolbar.getAttribute("toolbarname");
  5908.         var type = toolbar.getAttribute("type");
  5909.         if (toolbarName && type != "menubar") {
  5910.             var menuItem = document.createElement("menuitem");
  5911.             menuItem.setAttribute("toolbarindex", i);
  5912.             menuItem.setAttribute("type", "checkbox");
  5913.             menuItem.setAttribute("label", toolbarName);
  5914.             menuItem.setAttribute("accesskey", toolbar.getAttribute("accesskey"));
  5915.             menuItem.setAttribute("checked", toolbar.getAttribute("collapsed") != "true");
  5916.             // JMC- Hack to order the items to match the toolbar orders
  5917.             var toolbarordinal = toolbar.getAttribute("ordinal");
  5918.             menuItem.setAttribute('ordinal',toolbarordinal);
  5919.             if (toolbarordinal > highestOrdinal)
  5920.                 highestOrdinal = toolbarordinal;
  5921.             popup.insertBefore(menuItem, firstMenuItem);
  5922.  
  5923.             menuItem.addEventListener("command", onViewToolbarCommand, false);
  5924.         }
  5925.         // JMC: Iterate through all multibartrays, too
  5926.         // toolbar = toolbar.nextSibling;
  5927.         if (toolbar.localName == 'multibar')
  5928.         toolbar = toolbar.firstChild;
  5929.     else if (toolbar.localName == 'multibartray' && (!toolbar.nextSibling)) {
  5930.         toolbar = toolbar.parentNode.nextSibling;
  5931.     } else {
  5932.         toolbar = toolbar.nextSibling;
  5933.     }
  5934. }
  5935. firstMenuItem.setAttribute('ordinal',highestOrdinal + 1);
  5936. firstMenuItem.nextSibling.setAttribute('ordinal',highestOrdinal + 2);
  5937. if (firstMenuItem.nextSibling.nextSibling)
  5938.     firstMenuItem.nextSibling.nextSibling.setAttribute('ordinal',highestOrdinal + 3);
  5939. // JMC :  HACK HACK HACK
  5940. }
  5941.  
  5942. function onViewToolbarCommand(aEvent)
  5943. {
  5944.     var toolbox = document.getElementById("navigator-toolbox");
  5945.     var index = aEvent.originalTarget.getAttribute("toolbarindex");
  5946.     var toolbar = toolbox.childNodes[index];
  5947.  
  5948.     toolbar.collapsed = aEvent.originalTarget.getAttribute("checked") != "true";
  5949.     document.persist(toolbar.id, "collapsed");
  5950.     toolbox.reorderToolbars();
  5951. }
  5952.  
  5953. function displaySecurityInfo()
  5954. {
  5955.     // MERC - JCH: Temporary fix to show a Properties dialog
  5956.     // when lock icon is clicked and Trident is the engine. This code triggers
  5957.     // a Trident Properties dialog when Trident is the engine. It would be better
  5958.     // to show Gecko pageInfo dialog that has appropriate info.
  5959.  
  5960.     var docshell = getWebNavigation();
  5961.  
  5962.     if (docshell.browserEngine=="Trident")
  5963.     {
  5964.         var hpDoc = getTridentDocument();
  5965.         if(hpDoc)
  5966.         {
  5967.             hpDoc.showPageInfo();
  5968.         }
  5969.     } else {
  5970.         window.openDialog("chrome://browser/content/pageInfo.xul", "_blank",
  5971.         "dialog=no", null, "securityTab");
  5972.     }
  5973. }
  5974.  
  5975.  
  5976. function displayPageReportFirstTime()
  5977. {
  5978.     window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank",
  5979.     "dependent");
  5980. }
  5981.  
  5982. function displayPageReport()
  5983. {
  5984.     window.openDialog("chrome://browser/content/pageReport.xul", "_blank",
  5985.     "dialog,modal,resizable");
  5986. }
  5987. function nsBrowserContentListener(toplevelWindow, contentWindow)
  5988. {
  5989.     // this one is not as easy as you would hope.
  5990.     // need to convert toplevelWindow to an XPConnected object, instead
  5991.     // of a DOM-based object, to be able to QI() it to nsIXULWindow
  5992.  
  5993.     this.init(toplevelWindow, contentWindow);
  5994. }
  5995.  
  5996. /* implements nsIURIContentListener */
  5997.  
  5998. nsBrowserContentListener.prototype =
  5999. {
  6000.     init: function(toplevelWindow, contentWindow)
  6001.     {
  6002.         const nsIWebBrowserChrome = Components.interfaces.nsIWebBrowserChrome;
  6003.         this.toplevelWindow = toplevelWindow;
  6004.         this.contentWindow = contentWindow;
  6005.  
  6006.         // hook up the whole parent chain thing
  6007.         var windowDocShell = this.convertWindowToDocShell(toplevelWindow);
  6008.         if (windowDocShell)
  6009.         windowDocshell.parentURIContentListener = this;
  6010.  
  6011.         var registerWindow = false;
  6012.         try {
  6013.             var treeItem = contentWindow.docShell.QueryInterface(Components.interfaces.nsIDocShellTreeItem);
  6014.             var treeOwner = treeItem.treeOwner;
  6015.             var interfaceRequestor = treeOwner.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  6016.             var webBrowserChrome = interfaceRequestor.getInterface(nsIWebBrowserChrome);
  6017.             if (webBrowserChrome)
  6018.             {
  6019.                 var chromeFlags = webBrowserChrome.chromeFlags;
  6020.                 var res = chromeFlags & nsIWebBrowserChrome.CHROME_ALL;
  6021.                 var res2 = chromeFlags & nsIWebBrowserChrome.CHROME_DEFAULT;
  6022.                 if ( res == nsIWebBrowserChrome.CHROME_ALL || res2 == nsIWebBrowserChrome.CHROME_DEFAULT)
  6023.                 {
  6024.                     registerWindow = true;
  6025.                 }
  6026.             }
  6027.         } catch (ex) {}
  6028.  
  6029.         // register ourselves
  6030.         if (registerWindow)
  6031.         {
  6032.             var uriLoader = Components.classes["@mozilla.org/uriloader;1"].getService(Components.interfaces.nsIURILoader);
  6033.             uriLoader.registerContentListener(this);
  6034.         }
  6035.     },
  6036.     close: function()
  6037.     {
  6038.         this.contentWindow = null;
  6039.         var uriLoader = Components.classes["@mozilla.org/uriloader;1"].getService(Components.interfaces.nsIURILoader);
  6040.  
  6041.         uriLoader.unRegisterContentListener(this);
  6042.     },
  6043.     QueryInterface: function(iid)
  6044.     {
  6045.         if (iid.equals(Components.interfaces.nsIURIContentListener) ||
  6046.         iid.equals(Components.interfaces.nsISupportsWeakReference) ||
  6047.         iid.equals(Components.interfaces.nsISupports))
  6048.         return this;
  6049.         throw Components.results.NS_NOINTERFACE;
  6050.     },
  6051.     onStartURIOpen: function(uri)
  6052.     {
  6053.         // ignore and don't abort
  6054.         return false;
  6055.     },
  6056.  
  6057.     doContent: function(contentType, isContentPreferred, request, contentHandler)
  6058.     {
  6059.         // forward the doContent to our content area webshell
  6060.         var docShell = this.contentWindow.docShell;
  6061.         var contentListener;
  6062.         try {
  6063.             contentListener =
  6064.             docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  6065.             .getInterface(Components.interfaces.nsIURIContentListener);
  6066.         } catch (ex) {
  6067.             dump(ex);
  6068.         }
  6069.  
  6070.         if (!contentListener) return false;
  6071.  
  6072.         return contentListener.doContent(contentType, isContentPreferred, request, contentHandler);
  6073.  
  6074.     },
  6075.  
  6076.     isPreferred: function(contentType, desiredContentType)
  6077.     {
  6078.         // seems like we should be getting this from helper apps or something
  6079.         switch(contentType) {
  6080.             case "text/html":
  6081.             case "text/xul":
  6082.             case "text/rdf":
  6083.             case "text/xml":
  6084.             case "text/css":
  6085.             case "image/gif":
  6086.             case "image/jpeg":
  6087.             case "image/png":
  6088.             case "text/plain":
  6089.             case "application/http-index-format":
  6090.             return true;
  6091.         }
  6092.         return false;
  6093.     },
  6094.     canHandleContent: function(contentType, isContentPreferred, desiredContentType)
  6095.     {
  6096.         var docShell = this.contentWindow.docShell;
  6097.         var contentListener;
  6098.         try {
  6099.             contentListener =
  6100.             docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIURIContentListener);
  6101.         } catch (ex) {
  6102.             dump(ex);
  6103.         }
  6104.         if (!contentListener) return false;
  6105.  
  6106.         return contentListener.canHandleContent(contentType, isContentPreferred, desiredContentType);
  6107.     },
  6108.     convertWindowToDocShell: function(win) {
  6109.         // don't know how to do this
  6110.         return null;
  6111.     },
  6112.     loadCookie: null,
  6113.     parentContentListener: null
  6114. }
  6115.  
  6116. // |forceOpen| is a bool that indicates that the sidebar should be forced open.  In other words
  6117. // the toggle won't be allowed to close the sidebar.
  6118. function toggleSidebar(aCommandID, forceOpen) {
  6119.  
  6120.     var sidebarBox = document.getElementById("sidebar-box");
  6121.     if (!aCommandID)
  6122.     aCommandID = sidebarBox.getAttribute("sidebarcommand");
  6123.  
  6124.     var elt = document.getElementById(aCommandID);
  6125.     if (!elt) return;
  6126.  
  6127.     var sidebar = document.getElementById("sidebar");
  6128.     var sidebarSplitter = document.getElementById("sidebar-splitter");
  6129.  
  6130.     if (!forceOpen && elt.getAttribute("checked") == "true") {
  6131.         elt.removeAttribute("checked");
  6132.         sidebarBox.setAttribute("sidebarcommand", "");
  6133.         sidebarBox.hidden = true;
  6134.         sidebarSplitter.hidden = true;
  6135.         _content.focus();
  6136.         return;
  6137.     }
  6138.  
  6139.     var elts = document.getElementsByAttribute("group", "sidebar");
  6140.     for (var i = 0; i < elts.length; ++i)
  6141.     elts[i].removeAttribute("checked");
  6142.  
  6143.     elt.setAttribute("checked", "true");;
  6144.  
  6145.     if (sidebarBox.hidden) {
  6146.         sidebarBox.hidden = false;
  6147.         sidebarSplitter.hidden = false;
  6148.     }
  6149.  
  6150.     var url = elt.getAttribute("sidebarurl");
  6151.     var title = elt.getAttribute("sidebartitle");
  6152.     if (!title)
  6153.     title = elt.getAttribute("label");
  6154.     sidebar.setAttribute("src", url);
  6155.     sidebarBox.setAttribute("src", url);
  6156.     sidebarBox.setAttribute("sidebarcommand", elt.id);
  6157.     if (aCommandID != "viewWebPanelsSidebar") { // no searchbox there
  6158.         // if the sidebar we want is already constructed, focus the searchbox
  6159.         if ((aCommandID == "viewBookmarksSidebar" && sidebar.contentDocument.getElementById("bookmarksPanel"))
  6160.         || (aCommandID == "viewHistorySidebar" && sidebar.contentDocument.getElementById("history-panel")))
  6161.         sidebar.contentDocument.getElementById("search-box").focus();
  6162.         // otherwiese, attach an onload handler
  6163.     else
  6164.         sidebar.addEventListener("load", asyncFocusSearchBox, true);
  6165.     }
  6166. }
  6167.  
  6168. function asyncFocusSearchBox(event)
  6169. {
  6170.     var sidebar = document.getElementById("sidebar");
  6171.     var searchBox = sidebar.contentDocument.getElementById("search-box");
  6172.     searchBox.focus();
  6173.     sidebar.removeEventListener("load", asyncFocusSearchBox, true);
  6174. }
  6175.  
  6176. function openPreferences()
  6177. {
  6178.     // dump ("The parent browser window is : " + window);
  6179.     /*JA ff5->vulp gPrefWindow =*/ 
  6180.     openDialog("chrome://browser/content/pref/pref.xul","PrefWindow",
  6181.                "chrome,titlebar,resizable,modal");
  6182. }
  6183.  
  6184. var gHomeButton = {
  6185.     prefDomain: "browser.startup.homepage",
  6186.     observe: function (aSubject, aTopic, aPrefName)
  6187.     {
  6188.         if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain)
  6189.         return;
  6190.  
  6191.         this.updateTooltip();
  6192.     },
  6193.  
  6194.     updateTooltip: function ()
  6195.     {
  6196.         var homeButton = document.getElementById("home-button");
  6197.         if (homeButton) {
  6198.             var homePage = this.getHomePage();
  6199.             homePage = homePage.replace(/\|/g,', ');
  6200.             homeButton.setAttribute("tooltiptext", homePage);
  6201.         }
  6202.     },
  6203.  
  6204.     getHomePage: function ()
  6205.     {
  6206.         var url;
  6207.         try {
  6208.             url = gPrefService.getComplexValue(this.prefDomain,
  6209.             Components.interfaces.nsIPrefLocalizedString).data;
  6210.         } catch (e) {
  6211.         }
  6212.  
  6213.         // use this if we can't find the pref
  6214.         if (!url) {
  6215.             var navigatorRegionBundle = document.getElementById("bundle_browser_region");
  6216.             url = navigatorRegionBundle.getString("homePageDefault");
  6217.         }
  6218.  
  6219.         return url;
  6220.     }
  6221. };
  6222.  
  6223. function nsContextMenu( xulMenu ) {
  6224.     this.target         = null;
  6225.     this.menu           = null;
  6226.     this.onTextInput    = false;
  6227.     this.onKeywordField = false;
  6228.     this.onImage        = false;
  6229.     this.onLink         = false;
  6230.     this.onMailtoLink   = false;
  6231.     this.onSaveableLink = false;
  6232.     this.onMetaDataItem = false;
  6233.     this.onMathML       = false;
  6234.     this.link           = false;
  6235.     this.inFrame        = false;
  6236.     this.hasBGImage     = false;
  6237.     this.isTextSelected = false;
  6238.     this.inDirList      = false;
  6239.     this.shouldDisplay  = true;
  6240.  
  6241.     // Initialize new menu.
  6242.     this.initMenu( xulMenu );
  6243. }
  6244.  
  6245. // Prototype for nsContextMenu "class."
  6246. nsContextMenu.prototype = {
  6247.     // onDestroy is a no-op at this point.
  6248.     onDestroy : function () {
  6249.     },
  6250.     // Initialize context menu.
  6251.     initMenu : function ( popup ) {
  6252.         // Save menu.
  6253.         this.menu = popup;
  6254.  
  6255.         // Get contextual info.
  6256.         this.setTarget( document.popupNode );
  6257.  
  6258.         this.isTextSelected = this.isTextSelection();
  6259.  
  6260.         // Initialize (disable/remove) menu items.
  6261.         this.initItems();
  6262.     },
  6263.     initItems : function () {
  6264.         this.initTridentSwitchItem();  // MERC (DP): disable/enable Trident switch
  6265.         this.initOpenItems();
  6266.         this.initNavigationItems();
  6267.         this.initViewItems();
  6268.         this.initMiscItems();
  6269.         this.initSaveItems();
  6270.         this.initClipboardItems();
  6271.         this.initMetadataItems();
  6272.         this.initPrintItems();
  6273.     },
  6274.     // MERC (DP): this function will disable the Trident switch menu item.
  6275.     // for all 'about:*' we disable, except for 'about:blank' - allow engine switch on blank page
  6276.     initTridentSwitchItem : function () {
  6277.         //dump('*** target: ' + this.target.localName + '\n');
  6278.  
  6279.         var engineMenuItem = document.getElementById('switchToTrident');
  6280.         //dump('*** switch to trident menu item: ' + engineMenuItem.getAttribute('label') + '\n');
  6281.  
  6282.         var url = gBrowser.getBrowserForTab(gBrowser.mCurrentTab).currentURI.spec;
  6283.  
  6284.         var regex = /^about:/;
  6285.         if(regex.test(url) && url != 'about:blank') {
  6286.             engineMenuItem.setAttribute('disabled', 'true');
  6287.         } else {
  6288.             engineMenuItem.removeAttribute('disabled');
  6289.         }
  6290.  
  6291.         this.showItem( "switchToTrident", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6292.     },
  6293.     initOpenItems : function () {
  6294.         this.showItem( "context-openlink", this.onSaveableLink || ( this.inDirList && this.onLink ) );
  6295.         this.showItem( "context-openlinkintab", this.onSaveableLink || ( this.inDirList && this.onLink ) );
  6296.  
  6297.         //this.showItem( "context-sep-open", this.onSaveableLink || ( this.inDirList && this.onLink ) );
  6298.         this.showItem( "context-sep-open", false );
  6299.     },
  6300.     initNavigationItems : function () {
  6301.         // Back determined by canGoBack broadcaster.
  6302.         this.setItemAttrFromNode( "context-back", "disabled", "canGoBack" );
  6303.  
  6304.         // Forward determined by canGoForward broadcaster.
  6305.         this.setItemAttrFromNode( "context-forward", "disabled", "canGoForward" );
  6306.  
  6307.         this.showItem( "context-back", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6308.         this.showItem( "context-forward", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6309.  
  6310.         this.showItem( "context-reload", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6311.  
  6312.         this.showItem( "context-stop", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6313.         this.showItem( "context-sep-stop", !( this.isTextSelected || this.onTextInput || this.onImage ) );
  6314.  
  6315.         // XXX: Stop is determined in navigator.js; the canStop broadcaster is broken
  6316.         //this.setItemAttrFromNode( "context-stop", "disabled", "canStop" );
  6317.     },
  6318.     initSaveItems : function () {
  6319.         this.showItem( "context-savepage", !( this.inDirList || this.isTextSelected || this.onTextInput || this.onLink || this.onImage ));
  6320.         this.showItem( "context-sendpage", !( this.inDirList || this.isTextSelected || this.onTextInput || this.onLink || this.onImage ));
  6321.  
  6322.         // Save link depends on whether we're in a link.
  6323.         this.showItem( "context-savelink", this.onSaveableLink );
  6324.  
  6325.         // Save image depends on whether there is one.
  6326.         this.showItem( "context-saveimage", this.onImage );
  6327.  
  6328.         this.showItem( "context-sendimage", this.onImage );
  6329.  
  6330.         // Send link depends on whether we're in a link.
  6331.         //this.showItem( "context-sendlink", this.onSaveableLink );
  6332.         this.showItem( "context-sendlink", false );
  6333.     },
  6334.     initViewItems : function () {
  6335.         // View source is always OK, unless in directory listing.
  6336.         this.showItem( "context-viewpartialsource-selection", this.isTextSelected );
  6337.         this.showItem( "context-viewpartialsource-mathml", this.onMathML && !this.isTextSelected );
  6338.         this.showItem( "context-viewsource", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) );
  6339.         this.showItem( "context-viewinfo", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) );
  6340.  
  6341.         this.showItem( "context-sep-properties", !( this.inDirList || this.isTextSelected || this.onTextInput ) );
  6342.         // Set As Wallpaper depends on whether an image was clicked on, and only works if we have a shell service.
  6343.         var haveSetWallpaper = false;
  6344.         // Only enable set as wallpaper if we can get the shell service.
  6345.         var shell = getShellService();
  6346.         if (shell)
  6347.         haveSetWallpaper = true;
  6348.         this.showItem( "context-setWallpaper", haveSetWallpaper && this.onImage );
  6349.  
  6350.         if( haveSetWallpaper && this.onImage )
  6351.         // Disable the Set As Wallpaper menu item if we're still trying to load the image
  6352.         this.setItemAttr( "context-setWallpaper", "disabled", (("complete" in this.target) && !this.target.complete) ? "true" : null );
  6353.  
  6354.         // View Image depends on whether an image was clicked on.
  6355.         this.showItem( "context-viewimage", this.onImage );
  6356.  
  6357.         // View background image depends on whether there is one.
  6358.         this.showItem( "context-viewbgimage", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) );
  6359.         this.showItem( "context-sep-viewbgimage", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) );
  6360.         this.setItemAttr( "context-viewbgimage", "disabled", this.hasBGImage ? null : "true");
  6361.     },
  6362.     initMiscItems : function () {
  6363.         // Use "Bookmark This Link" if on a link.
  6364.         this.showItem( "context-bookmarkpage", !( this.isTextSelected || this.onTextInput || this.onLink || this.onImage ) );
  6365.         //this.showItem( "context-bookmarklink", this.onLink && !this.onMailtoLink );
  6366.         this.showItem( "context-bookmarklink", false );
  6367.         this.showItem( "context-addBookmarkAsTabGrp", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6368.         //this.showItem( "context-addBookmarkAsTabGrp", false);
  6369.         this.showItem( "context-searchselect", this.isTextSelected );
  6370.         //this.showItem( "context-keywordfield", this.onTextInput && this.onKeywordField );
  6371.         this.showItem( "context-keywordfield", false );
  6372.         this.showItem( "frame", this.inFrame );
  6373.         this.showItem( "frame-sep", this.inFrame );
  6374.         /* MERC: ccampbell: commented this out because it needs to be updated to use Site Controls instead
  6375.         this.showItem( "context-blockimage", this.onImage);
  6376.  
  6377.         // BiDi UI
  6378.         var showBIDI = isBidiEnabled();
  6379.         this.showItem( "context-sep-bidi", showBIDI);
  6380.         this.showItem( "context-bidi-text-direction-toggle", this.onTextInput && showBIDI);
  6381.         this.showItem( "context-bidi-page-direction-toggle", !this.onTextInput && showBIDI);
  6382.  
  6383.         if (this.onImage) {
  6384.         var blockImage = document.getElementById("context-blockimage");
  6385.  
  6386.         var uri = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI);
  6387.         uri.spec = this.imageURL;
  6388.  
  6389.         var shortenedUriHost = uri.host.replace(/^www\./i,"");
  6390.         if (shortenedUriHost.length > 15)
  6391.         shortenedUriHost = shortenedUriHost.substr(0,15) + "...";
  6392.         blockImage.label = gNavigatorBundle.getFormattedString ("blockImages", [shortenedUriHost]);
  6393.  
  6394.         if (this.isImageBlocked()) {
  6395.         blockImage.setAttribute("checked", "true");
  6396.         }
  6397.         else
  6398.         blockImage.removeAttribute("checked");
  6399.         }
  6400.         */
  6401.     },
  6402.     initClipboardItems : function () {
  6403.  
  6404.         // Copy depends on whether there is selected text.
  6405.         // Enabling this context menu item is now done through the global
  6406.         // command updating system
  6407.         // this.setItemAttr( "context-copy", "disabled", !this.isTextSelected() );
  6408.  
  6409.         goUpdateGlobalEditMenuItems();
  6410.  
  6411.         this.showItem( "context-undo", this.onTextInput );
  6412.         this.showItem( "context-sep-undo", this.onTextInput );
  6413.         this.showItem( "context-cut", this.onTextInput );
  6414.         this.showItem( "context-copy", this.isTextSelected || this.onTextInput );
  6415.         this.showItem( "context-paste", this.onTextInput );
  6416.         this.showItem( "context-delete", this.onTextInput );
  6417.         this.showItem( "context-sep-paste", this.onTextInput );
  6418.         this.showItem( "context-selectall", !( this.onLink || this.onImage ) );
  6419.         //this.showItem( "context-sep-selectall", this.isTextSelected );
  6420.         //this.showItem( "context-sep-selectall", true );
  6421.         this.showItem( "context-sep-selectall", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) );
  6422.  
  6423.         // XXX dr
  6424.         // ------
  6425.         // nsDocumentViewer.cpp has code to determine whether we're
  6426.         // on a link or an image. we really ought to be using that...
  6427.  
  6428.         // Copy email link depends on whether we're on an email link.
  6429.         this.showItem( "context-copyemail", this.onMailtoLink );
  6430.  
  6431.         // Copy link location depends on whether we're on a link.
  6432.         this.showItem( "context-copylink", this.onLink );
  6433.         //this.showItem( "context-copylink", false );
  6434.         this.showItem( "context-sep-copylink", this.onLink && this.onImage);
  6435.         //this.showItem( "context-sep-copylink", false );
  6436.  
  6437.         // Copy image contents depends on whether we're on an image.
  6438.         //this.showItem( "context-copyimage-contents", this.onImage );
  6439.         this.showItem( "context-copyimage-contents", false );
  6440.         // Copy image location depends on whether we're on an image.
  6441.         //this.showItem( "context-copyimage", this.onImage );
  6442.         this.showItem( "context-copyimage", false );
  6443.         this.showItem( "context-sep-copyimage", this.onImage && this.onLink );
  6444.         this.showItem( "context-sep-copyimage", false );
  6445.     },
  6446.     initMetadataItems : function () {
  6447.         // Show if user clicked on something which has metadata.
  6448.         this.showItem( "context-metadata", this.onMetaDataItem );
  6449.     },
  6450.     // MERC (DP): control the print menu items
  6451.     initPrintItems : function () {
  6452.         this.showItem( "context-sep-print", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) );
  6453.         this.showItem( "context-print", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) );
  6454.     },
  6455.     // Set various context menu attributes based on the state of the world.
  6456.     setTarget : function ( node ) {
  6457.         const xulNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  6458.         if ( node.namespaceURI == xulNS ) {
  6459.             this.shouldDisplay = false;
  6460.             return;
  6461.         }
  6462.         // Initialize contextual info.
  6463.         this.onImage    = false;
  6464.         this.onMetaDataItem = false;
  6465.         this.onTextInput = false;
  6466.         this.onKeywordField = false;
  6467.         this.imageURL   = "";
  6468.         this.onLink     = false;
  6469.         this.onMathML   = false;
  6470.         this.inFrame    = false;
  6471.         this.hasBGImage = false;
  6472.         this.bgImageURL = "";
  6473.  
  6474.         // Remember the node that was clicked.
  6475.         this.target = node;
  6476.  
  6477.         // See if the user clicked on an image.
  6478.         if ( this.target.nodeType == Node.ELEMENT_NODE ) {
  6479.             if ( this.target.localName.toUpperCase() == "IMG" ) {
  6480.                 this.onImage = true;
  6481.                 this.imageURL = this.target.src;
  6482.                 // Look for image map.
  6483.                 var mapName = this.target.getAttribute( "usemap" );
  6484.                 if ( mapName ) {
  6485.                     // Find map.
  6486.                     var map = this.target.ownerDocument.getElementById( mapName.substr(1) );
  6487.                     if ( map ) {
  6488.                         // Search child <area>s for a match.
  6489.                         var areas = map.childNodes;
  6490.                         //XXX Client side image maps are too hard for now!
  6491.                         areas.length = 0;
  6492.                         for ( var i = 0; i < areas.length && !this.onLink; i++ ) {
  6493.                             var area = areas[i];
  6494.                             if ( area.nodeType == Node.ELEMENT_NODE
  6495.                             &&
  6496.                             area.localName.toUpperCase() == "AREA" ) {
  6497.                                 // Get type (rect/circle/polygon/default).
  6498.                                 var type = area.getAttribute( "type" );
  6499.                                 var coords = this.parseCoords( area );
  6500.                                 switch ( type.toUpperCase() ) {
  6501.                                     case "RECT":
  6502.                                     case "RECTANGLE":
  6503.                                     break;
  6504.                                     case "CIRC":
  6505.                                     case "CIRCLE":
  6506.                                     break;
  6507.                                     case "POLY":
  6508.                                     case "POLYGON":
  6509.                                     break;
  6510.                                     case "DEFAULT":
  6511.                                     // Default matches entire image.
  6512.                                     this.onLink = true;
  6513.                                     this.link = area;
  6514.                                     this.onSaveableLink = this.isLinkSaveable( this.link );
  6515.                                     break;
  6516.                                 }
  6517.                             }
  6518.                         }
  6519.                     }
  6520.                 }
  6521.             } else if ( this.target.localName.toUpperCase() == "OBJECT"
  6522.             &&
  6523.             // See if object tag is for an image.
  6524.             this.objectIsImage( this.target ) ) {
  6525.                 // This is an image.
  6526.                 this.onImage = true;
  6527.                 // URL must be constructed.
  6528.                 this.imageURL = this.objectImageURL( this.target );
  6529.             } else if ( this.target.localName.toUpperCase() == "INPUT") {
  6530.                 type = this.target.getAttribute("type");
  6531.                 if(type && type.toUpperCase() == "IMAGE") {
  6532.                     this.onImage = true;
  6533.                     // Convert src attribute to absolute URL.
  6534.                     this.imageURL = makeURLAbsolute( this.target.baseURI,
  6535.                     this.target.src );
  6536.                 } else /* if (this.target.getAttribute( "type" ).toUpperCase() == "TEXT") */ {
  6537.                     this.onTextInput = this.isTargetATextBox(this.target);
  6538.                     this.onKeywordField = this.isTargetAKeywordField(this.target);
  6539.                 }
  6540.             } else if ( this.target.localName.toUpperCase() == "TEXTAREA" ) {
  6541.                 this.onTextInput = true;
  6542.             } else if ( this.target.localName.toUpperCase() == "HTML" ) {
  6543.                 // pages with multiple <body>s are lame. we'll teach them a lesson.
  6544.                 var bodyElt = this.target.ownerDocument.getElementsByTagName("body")[0];
  6545.                 if ( bodyElt ) {
  6546.                     var computedURL = this.getComputedURL( bodyElt, "background-image" );
  6547.                     if ( computedURL ) {
  6548.                         this.hasBGImage = true;
  6549.                         this.bgImageURL = makeURLAbsolute( bodyElt.baseURI,
  6550.                         computedURL );
  6551.                     }
  6552.                 }
  6553.             } else if ( "HTTPIndex" in _content &&
  6554.             _content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
  6555.                 this.inDirList = true;
  6556.                 // Bubble outward till we get to an element with URL attribute
  6557.                 // (which should be the href).
  6558.                 var root = this.target;
  6559.                 while ( root && !this.link ) {
  6560.                     if ( root.tagName == "tree" ) {
  6561.                         // Hit root of tree; must have clicked in empty space;
  6562.                         // thus, no link.
  6563.                         break;
  6564.                     }
  6565.                     if ( root.getAttribute( "URL" ) ) {
  6566.                         // Build pseudo link object so link-related functions work.
  6567.                         this.onLink = true;
  6568.                         this.link = { href : root.getAttribute("URL"),
  6569.                         getAttribute: function (attr) {
  6570.                             if (attr == "title") {
  6571.                                 return root.firstChild.firstChild.getAttribute("label");
  6572.                             } else {
  6573.                                 return "";
  6574.                             }
  6575.                         }
  6576.                     };
  6577.                     // If element is a directory, then you can't save it.
  6578.                     if ( root.getAttribute( "container" ) == "true" ) {
  6579.                         this.onSaveableLink = false;
  6580.                     } else {
  6581.                         this.onSaveableLink = true;
  6582.                     }
  6583.                 } else {
  6584.                     root = root.parentNode;
  6585.                 }
  6586.             }
  6587.         }
  6588.     }
  6589.  
  6590.     // We have meta data on images.
  6591.     this.onMetaDataItem = this.onImage;
  6592.  
  6593.     // See if the user clicked on MathML
  6594.     const NS_MathML = "http://www.w3.org/1998/Math/MathML";
  6595.     if ((this.target.nodeType == Node.TEXT_NODE &&
  6596.     this.target.parentNode.namespaceURI == NS_MathML)
  6597.     || (this.target.namespaceURI == NS_MathML))
  6598.     this.onMathML = true;
  6599.  
  6600.     // See if the user clicked in a frame.
  6601.     if ( this.target.ownerDocument != window._content.document ) {
  6602.         this.inFrame = true;
  6603.     }
  6604.  
  6605.     // Bubble out, looking for items of interest
  6606.     var elem = this.target;
  6607.     while ( elem ) {
  6608.         if ( elem.nodeType == Node.ELEMENT_NODE ) {
  6609.             var localname = elem.localName.toUpperCase();
  6610.  
  6611.             // Link?
  6612.             if ( !this.onLink &&
  6613.             ( (localname === "A" && elem.href) ||
  6614.             localname === "AREA" ||
  6615.             localname === "LINK" ||
  6616.             elem.getAttributeNS( "http://www.w3.org/1999/xlink", "type") == "simple" ) ) {
  6617.                 // Clicked on a link.
  6618.                 this.onLink = true;
  6619.                 this.onMetaDataItem = true;
  6620.                 // Remember corresponding element.
  6621.                 this.link = elem;
  6622.                 this.onMailtoLink = this.isLinkType( "mailto:", this.link );
  6623.                 // Remember if it is saveable.
  6624.                 this.onSaveableLink = this.isLinkSaveable( this.link );
  6625.             }
  6626.  
  6627.             // Text input?
  6628.             if ( !this.onTextInput ) {
  6629.                 // Clicked on a link.
  6630.                 this.onTextInput = this.isTargetATextBox(elem);
  6631.             }
  6632.  
  6633.             // Metadata item?
  6634.             if ( !this.onMetaDataItem ) {
  6635.                 // We currently display metadata on anything which fits
  6636.                 // the below test.
  6637.                 if ( ( localname === "BLOCKQUOTE" && 'cite' in elem && elem.cite)  ||
  6638.                 ( localname === "Q" && 'cite' in elem && elem.cite)           ||
  6639.                 ( localname === "TABLE" && 'summary' in elem && elem.summary) ||
  6640.                 ( ( localname === "INS" || localname === "DEL" ) &&
  6641.                 ( ( 'cite' in elem && elem.cite ) ||
  6642.                 ( 'dateTime' in elem && elem.dateTime ) ) )               ||
  6643.                 ( 'title' in elem && elem.title )                             ||
  6644.                 ( 'lang' in elem && elem.lang ) ) {
  6645.                     this.onMetaDataItem = true;
  6646.                 }
  6647.             }
  6648.  
  6649.             // Background image?  Don't bother if we've already found a
  6650.             // background image further down the hierarchy.  Otherwise,
  6651.             // we look for the computed background-image style.
  6652.             if ( !this.hasBGImage ) {
  6653.                 var bgImgUrl = this.getComputedURL( elem, "background-image" );
  6654.                 if ( bgImgUrl ) {
  6655.                     this.hasBGImage = true;
  6656.                     this.bgImageURL = makeURLAbsolute( elem.baseURI,
  6657.                     bgImgUrl );
  6658.                 }
  6659.             }
  6660.         }
  6661.         elem = elem.parentNode;
  6662.     }
  6663. },
  6664. // Returns the computed style attribute for the given element.
  6665. getComputedStyle: function( elem, prop ) {
  6666.     return elem.ownerDocument.defaultView.getComputedStyle( elem, '' ).getPropertyValue( prop );
  6667. },
  6668. // Returns a "url"-type computed style attribute value, with the url() stripped.
  6669. getComputedURL: function( elem, prop ) {
  6670.     var url = elem.ownerDocument.defaultView.getComputedStyle( elem, '' ).getPropertyCSSValue( prop );
  6671.     return ( url.primitiveType == CSSPrimitiveValue.CSS_URI ) ? url.getStringValue() : null;
  6672. },
  6673. // Returns true iff clicked on link is saveable.
  6674. isLinkSaveable : function ( link ) {
  6675.     // We don't do the Right Thing for news/snews yet, so turn them off
  6676.     // until we do.
  6677.     return !(this.isLinkType( "mailto:" , link )     ||
  6678.     this.isLinkType( "javascript:" , link ) ||
  6679.     this.isLinkType( "news:", link )        ||
  6680.     this.isLinkType( "snews:", link ) );
  6681. },
  6682. // Returns true iff clicked on link is of type given.
  6683. isLinkType : function ( linktype, link ) {
  6684.     try {
  6685.         // Test for missing protocol property.
  6686.         if ( !link.protocol ) {
  6687.             // We must resort to testing the URL string :-(.
  6688.             var protocol;
  6689.             var wrapper = new XPCNativeWrapper(link, "href",
  6690.             "getAttributeNS()");
  6691.             if (wrapper.href) {
  6692.                 protocol = wrapper.href.substr(0, linktype.length);
  6693.             } else {
  6694.                 protocol = wrapper.getAttributeNS("http://www.w3.org/1999/xlink","href");
  6695.                 if (protocol) {
  6696.                     protocol = protocol.substr(0, linktype.length);
  6697.                 }
  6698.             }
  6699.             return protocol.toLowerCase() === linktype;
  6700.         } else {
  6701.             // Presume all but javascript: urls are saveable.
  6702.             return link.protocol.toLowerCase() === linktype;
  6703.         }
  6704.     } catch (e) {
  6705.         // something was wrong with the link,
  6706.         // so we won't be able to save it anyway
  6707.         return false;
  6708.     }
  6709. },
  6710. // Open linked-to URL in a new window.
  6711. openLink : function () {
  6712.     // Determine linked-to URL.
  6713.     openNewWindowWith(this.linkURL(), this.link, true);
  6714. },
  6715. // Open linked-to URL in a new tab.
  6716. openLinkInTab : function () {
  6717.     // Determine linked-to URL.
  6718.     openNewTabWith(this.linkURL(), this.link, null, true);
  6719. },
  6720. // Open frame in a new tab.
  6721. openFrameInTab : function () {
  6722.     // Determine linked-to URL.
  6723.     openNewTabWith(this.target.ownerDocument.location.href, null, null, true);
  6724. },
  6725. // Reload clicked-in frame.
  6726. reloadFrame : function () {
  6727.     this.target.ownerDocument.location.reload();
  6728. },
  6729. // Open clicked-in frame in its own window.
  6730. openFrame : function () {
  6731.     openNewWindowWith(this.target.ownerDocument.location.href, null, true);
  6732. },
  6733. // Open clicked-in frame in the same window
  6734. showOnlyThisFrame : function () {
  6735.     window.loadURI(this.target.ownerDocument.location.href, null, null);
  6736. },
  6737. // View Partial Source
  6738. viewPartialSource : function ( context ) {
  6739.     var focusedWindow = document.commandDispatcher.focusedWindow;
  6740.     if (focusedWindow == window)
  6741.     focusedWindow = _content;
  6742.     var docCharset = null;
  6743.     if (focusedWindow)
  6744.     docCharset = "charset=" + focusedWindow.document.characterSet;
  6745.  
  6746.         // "View Selection Source" and others such as "View MathML Source"
  6747.         // are mutually exclusive, with the precedence given to the selection
  6748.         // when there is one
  6749.         var reference = null;
  6750.         if (context == "selection")
  6751.           reference = focusedWindow.getSelection();
  6752.         else if (context == "mathml")
  6753.           reference = this.target;
  6754.         else
  6755.           throw "not reached";
  6756.  
  6757.     var docUrl = null; // unused (and play nice for fragments generated via XSLT too)
  6758.     window.openDialog("chrome://global/content/viewPartialSource.xul",
  6759.     "_blank", "scrollbars,resizable,chrome,dialog=no",
  6760.     docUrl, docCharset, reference, context);
  6761. },
  6762. // Open new "view source" window with the frame's URL.
  6763. viewFrameSource : function () {
  6764.     BrowserViewSourceOfDocument(this.target.ownerDocument);
  6765. },
  6766. viewInfo : function () {
  6767.     BrowserPageInfo();
  6768. },
  6769. viewFrameInfo : function () {
  6770.     BrowserPageInfo(this.target.ownerDocument);
  6771. },
  6772. // Change current window to the URL of the image.
  6773. viewImage : function (e) {
  6774.     openUILink( this.imageURL, e );
  6775. },
  6776. // Change current window to the URL of the background image.
  6777. viewBGImage : function (e) {
  6778.     openUILink( this.bgImageURL, e );
  6779. },
  6780. setWallpaper: function() {
  6781.     // Confirm since it's annoying if you hit this accidentally.
  6782.     openDialog("chrome://browser/content/setWallpaper.xul", "",
  6783.     "centerscreen,chrome,dialog,modal,dependent",
  6784.     this.target);
  6785. },
  6786. // Save URL of clicked-on frame.
  6787. saveFrame : function () {
  6788.     saveDocument( this.target.ownerDocument );
  6789. },
  6790. // Save URL of clicked-on link.
  6791. saveLink : function () {
  6792.     saveURL( this.linkURL(), this.linkText(), null, true, false );
  6793. },
  6794. sendLink : function () {
  6795.     MailIntegration.sendMessage( this.linkURL(), "" ); // we don't know the title of the link so pass in an empty string
  6796. },
  6797. // Save URL of clicked-on image.
  6798. saveImage : function () {
  6799.     saveURL( this.imageURL, null, "SaveImageTitle", false );
  6800. },
  6801. sendImage : function () {
  6802.     MailIntegration.sendMessage(this.imageURL, "");
  6803. },
  6804. toggleImageBlocking : function (aBlock) {
  6805.     var nsIPermissionManager = Components.interfaces.nsIPermissionManager;
  6806.     var permissionmanager =
  6807.     Components.classes["@mozilla.org/permissionmanager;1"]
  6808.     .getService(nsIPermissionManager);
  6809.     var uri = Components.classes["@mozilla.org/network/standard-url;1"]
  6810.     .createInstance(Components.interfaces.nsIURI);
  6811.     uri.spec = this.imageURL;
  6812.     permissionmanager.add(uri, "image",
  6813.     aBlock ? nsIPermissionManager.DENY_ACTION : nsIPermissionManager.ALLOW_ACTION);
  6814. },
  6815. isImageBlocked : function() {
  6816.     var nsIPermissionManager = Components.interfaces.nsIPermissionManager;
  6817.     var permissionmanager =
  6818.     Components.classes["@mozilla.org/permissionmanager;1"]
  6819.     .getService(Components.interfaces.nsIPermissionManager);
  6820.     var uri = Components.classes["@mozilla.org/network/standard-url;1"]
  6821.     .createInstance(Components.interfaces.nsIURI);
  6822.     uri.spec = this.imageURL;
  6823.     return permissionmanager.testPermission(uri, "image") == nsIPermissionManager.DENY_ACTION;
  6824. },
  6825. // Generate email address and put it on clipboard.
  6826. copyEmail : function () {
  6827.     // Copy the comma-separated list of email addresses only.
  6828.     // There are other ways of embedding email addresses in a mailto:
  6829.     // link, but such complex parsing is beyond us.
  6830.     var url = this.linkURL();
  6831.     var qmark = url.indexOf( "?" );
  6832.     var addresses;
  6833.  
  6834.     if ( qmark > 7 ) {                   // 7 == length of "mailto:"
  6835.         addresses = url.substring( 7, qmark );
  6836.     } else {
  6837.         addresses = url.substr( 7 );
  6838.     }
  6839.  
  6840.     // Let's try to unescape it using a character set
  6841.     // in case the address is not ASCII.
  6842.     try {
  6843.         var characterSet = Components.lookupMethod(this.target.ownerDocument, "characterSet")
  6844.         .call(this.target.ownerDocument);
  6845.         const textToSubURI = Components.classes["@mozilla.org/intl/texttosuburi;1"]
  6846.         .getService(Components.interfaces.nsITextToSubURI);
  6847.         addresses = textToSubURI.unEscapeNonAsciiURI(characterSet, addresses);
  6848.     }
  6849.     catch(ex) {
  6850.         // Do nothing.
  6851.     }
  6852.  
  6853.     var clipboard = this.getService( "@mozilla.org/widget/clipboardhelper;1",
  6854.     Components.interfaces.nsIClipboardHelper );
  6855.     clipboard.copyString(addresses);
  6856. },
  6857. addBookmark : function() {
  6858.     var docshell = document.getElementById( "content" ).webNavigation;
  6859.     BookmarksUtils.addBookmark( docshell.currentURI.spec,
  6860.     docshell.document.title,
  6861.     docshell.document.charset);
  6862. },
  6863. addBookmarkForFrame : function() {
  6864.     var doc = this.target.ownerDocument;
  6865.     var uri = doc.location.href;
  6866.     var title = doc.title;
  6867.     if ( !title )
  6868.     title = uri;
  6869.     BookmarksUtils.addBookmark(uri, title, doc.charset);
  6870. },
  6871. // Open Metadata window for node
  6872. showMetadata : function () {
  6873.     window.openDialog(  "chrome://browser/content/metaData.xul",
  6874.     "_blank",
  6875.     "scrollbars,resizable,chrome,dialog=no",
  6876.     this.target);
  6877. },
  6878.  
  6879. ///////////////
  6880. // Utilities //
  6881. ///////////////
  6882.  
  6883. // Create instance of component given contractId and iid (as string).
  6884. createInstance : function ( contractId, iidName ) {
  6885.     var iid = Components.interfaces[ iidName ];
  6886.     return Components.classes[ contractId ].createInstance( iid );
  6887. },
  6888. // Get service given contractId and iid (as string).
  6889. getService : function ( contractId, iidName ) {
  6890.     var iid = Components.interfaces[ iidName ];
  6891.     return Components.classes[ contractId ].getService( iid );
  6892. },
  6893. // Show/hide one item (specified via name or the item element itself).
  6894. showItem : function ( itemOrId, show ) {
  6895.     var item = itemOrId.constructor == String ? document.getElementById(itemOrId) : itemOrId;
  6896.     if (item)
  6897.     item.hidden = !show;
  6898. },
  6899. // Set given attribute of specified context-menu item.  If the
  6900. // value is null, then it removes the attribute (which works
  6901. // nicely for the disabled attribute).
  6902. setItemAttr : function ( id, attr, val ) {
  6903.     var elem = document.getElementById( id );
  6904.     if ( elem ) {
  6905.         if ( val == null ) {
  6906.             // null indicates attr should be removed.
  6907.             elem.removeAttribute( attr );
  6908.         } else {
  6909.             // Set attr=val.
  6910.             elem.setAttribute( attr, val );
  6911.         }
  6912.     }
  6913. },
  6914. // Set context menu attribute according to like attribute of another node
  6915. // (such as a broadcaster).
  6916. setItemAttrFromNode : function ( item_id, attr, other_id ) {
  6917.     var elem = document.getElementById( other_id );
  6918.     if ( elem && elem.getAttribute( attr ) == "true" ) {
  6919.         this.setItemAttr( item_id, attr, "true" );
  6920.     } else {
  6921.         this.setItemAttr( item_id, attr, null );
  6922.     }
  6923. },
  6924. // Temporary workaround for DOM api not yet implemented by XUL nodes.
  6925. cloneNode : function ( item ) {
  6926.     // Create another element like the one we're cloning.
  6927.     var node = document.createElement( item.tagName );
  6928.  
  6929.     // Copy attributes from argument item to the new one.
  6930.     var attrs = item.attributes;
  6931.     for ( var i = 0; i < attrs.length; i++ ) {
  6932.         var attr = attrs.item( i );
  6933.         node.setAttribute( attr.nodeName, attr.nodeValue );
  6934.     }
  6935.  
  6936.     // Voila!
  6937.     return node;
  6938. },
  6939. // Generate fully-qualified URL for clicked-on link.
  6940. linkURL : function () {
  6941.     var wrapper = new XPCNativeWrapper(this.link, "href", "baseURI",
  6942.     "getAttributeNS()");
  6943.     if (wrapper.href) {
  6944.         return wrapper.href;
  6945.     }
  6946.     var href = wrapper.getAttributeNS("http://www.w3.org/1999/xlink",
  6947.     "href");
  6948.     if (!href || !href.match(/\S/)) {
  6949.         throw "Empty href"; // Without this we try to save as the current doc, for example, HTML case also throws if empty
  6950.     }
  6951.     href = makeURLAbsolute(wrapper.baseURI, href);
  6952.     return href;
  6953. },
  6954. // Get text of link.
  6955. linkText : function () {
  6956.     var text = gatherTextUnder( this.link );
  6957.     if (!text || !text.match(/\S/)) {
  6958.         text = this.link.getAttribute("title");
  6959.         if (!text || !text.match(/\S/)) {
  6960.             text = this.link.getAttribute("alt");
  6961.             if (!text || !text.match(/\S/)) {
  6962.                 var wrapper = new XPCNativeWrapper(this.link, "href", "baseURI",
  6963.                 "getAttributeNS()");
  6964.  
  6965.                 if (wrapper.href) {
  6966.                     text = wrapper.href;
  6967.                 } else {
  6968.                     text = wrapper.getAttributeNS("http://www.w3.org/1999/xlink",
  6969.                     "href");
  6970.                     if (text && text.match(/\S/)) {
  6971.                         text = makeURLAbsolute(wrapper.baseURI, text);
  6972.                     }
  6973.                 }
  6974.             }
  6975.         }
  6976.     }
  6977.  
  6978.     return text;
  6979. },
  6980.  
  6981. //Get selected object and convert it to a string to get
  6982. //selected text.   Only use the first 15 chars.
  6983. isTextSelection : function() {
  6984.     var result = false;
  6985.     var selection = this.searchSelected(16);
  6986.  
  6987.     var searchSelectText;
  6988.     if (selection) {
  6989.         searchSelectText = selection.toString();
  6990.  
  6991.         dump("1: In isTextSelection(): " +searchSelectText+ "\n");
  6992.  
  6993.  
  6994.         if (searchSelectText.length > 15)
  6995.         searchSelectText = searchSelectText.substr(0,15) + "...";
  6996.         result = true;
  6997.  
  6998.         // format "Search for <selection>" string to show in menu
  6999.         searchSelectText = gNavigatorBundle.getFormattedString("searchText", [searchSelectText]);
  7000.  
  7001.         dump("2: In isTextSelection(): " +searchSelectText+ "\n");
  7002.  
  7003.         this.setItemAttr("context-searchselect", "label", searchSelectText);
  7004.     }
  7005.     return result;
  7006. },
  7007.  
  7008. searchSelected : function( charlen ) {
  7009.     var focusedWindow = document.commandDispatcher.focusedWindow;
  7010.         var searchStr = focusedWindow.getSelection();
  7011.     searchStr = searchStr.toString();
  7012.  
  7013.     dump("In searchSelected(): " +searchStr+ "\n");
  7014.  
  7015.     // searching for more than 150 chars makes no sense
  7016.     if (!charlen)
  7017.     charlen = 150;
  7018.     if (charlen < searchStr.length) {
  7019.         // only use the first charlen important chars. see bug 221361
  7020.         var pattern = new RegExp("^(?:\\s*.){0," + charlen + "}");
  7021.         pattern.test(searchStr);
  7022.         searchStr = RegExp.lastMatch;
  7023.     }
  7024.     searchStr = searchStr.replace(/\s*(.*?)\s*$/, "$1");
  7025.     searchStr = searchStr.replace(/\s+/g, " ");
  7026.     return searchStr;
  7027. },
  7028.  
  7029. // Determine if target <object> is an image.
  7030. objectIsImage : function ( objElem ) {
  7031.     var result = false;
  7032.     // Get type and data attributes.
  7033.     var type = objElem.getAttribute( "type" );
  7034.     var data = objElem.getAttribute( "data" );
  7035.     // Presume any mime type of the form "image/..." is an image.
  7036.     // There must be a data= attribute with an URL, also.
  7037.     if ( type.substring( 0, 6 ) == "image/" && data) {
  7038.         result = true;
  7039.     }
  7040.     return result;
  7041. },
  7042. // Extract image URL from <object> tag.
  7043. objectImageURL : function ( objElem ) {
  7044.     // Extract url from data= attribute.
  7045.     var data = objElem.getAttribute( "data" );
  7046.     // Make it absolute.
  7047.     return makeURLAbsolute( objElem.baseURI, data );
  7048. },
  7049. // Parse coords= attribute and return array.
  7050. parseCoords : function ( area ) {
  7051.     return [];
  7052. },
  7053. toString : function () {
  7054.     return "contextMenu.target     = " + this.target + "\n" +
  7055.     "contextMenu.onImage    = " + this.onImage + "\n" +
  7056.     "contextMenu.onLink     = " + this.onLink + "\n" +
  7057.     "contextMenu.link       = " + this.link + "\n" +
  7058.     "contextMenu.inFrame    = " + this.inFrame + "\n" +
  7059.     "contextMenu.hasBGImage = " + this.hasBGImage + "\n";
  7060. },
  7061. isTargetATextBox : function ( node )
  7062. {
  7063.     if (node.nodeType != Node.ELEMENT_NODE)
  7064.     return false;
  7065.  
  7066.     if (node.localName.toUpperCase() == "INPUT") {
  7067.         var attrib = "";
  7068.         var type = node.getAttribute("type");
  7069.  
  7070.         if (type)
  7071.         attrib = type.toUpperCase();
  7072.  
  7073.         return( (attrib != "IMAGE") &&
  7074.         (attrib != "CHECKBOX") &&
  7075.         (attrib != "RADIO") &&
  7076.         (attrib != "SUBMIT") &&
  7077.         (attrib != "RESET") &&
  7078.         (attrib != "FILE") &&
  7079.         (attrib != "HIDDEN") &&
  7080.         (attrib != "RESET") &&
  7081.         (attrib != "BUTTON") );
  7082.     } else  {
  7083.         return(node.localName.toUpperCase() == "TEXTAREA");
  7084.     }
  7085. },
  7086. isTargetAKeywordField : function ( node )
  7087. {
  7088.     var form = node.form;
  7089.     if (!form)
  7090.     return false;
  7091.     var method = form.method.toUpperCase();
  7092.  
  7093.     // These are the following types of forms we can create keywords for:
  7094.     //
  7095.     // method   encoding type       can create keyword
  7096.     // GET      *                                 YES
  7097.     //          *                                 YES
  7098.     // POST                                       YES
  7099.     // POST     application/x-www-form-urlencoded YES
  7100.     // POST     text/plain                        NO (a little tricky to do)
  7101.     // POST     multipart/form-data               NO
  7102.     // POST     everything else                   YES
  7103.     return (method == "GET" || method == "") ||
  7104.     (form.enctype != "text/plain") && (form.enctype != "multipart/form-data");
  7105. },
  7106.  
  7107. // Determines whether or not the separator with the specified ID should be
  7108. // shown or not by determining if there are any non-hidden items between it
  7109. // and the previous separator.
  7110. shouldShowSeparator : function ( aSeparatorID )
  7111. {
  7112.     var separator = document.getElementById(aSeparatorID);
  7113.     if (separator) {
  7114.         var sibling = separator.previousSibling;
  7115.         while (sibling && sibling.localName != "menuseparator") {
  7116.             if (sibling.getAttribute("hidden") != "true")
  7117.             return true;
  7118.             sibling = sibling.previousSibling;
  7119.         }
  7120.     }
  7121.     return false;
  7122. }
  7123. }
  7124.  
  7125. var gWebPanelURI;
  7126. function openWebPanel(aTitle, aURI)
  7127. {
  7128.     // Ensure that the web panels sidebar is open.
  7129.     toggleSidebar('viewWebPanelsSidebar', true);
  7130.  
  7131.     // Set the title of the panel.
  7132.     document.getElementById("sidebar-title").value = aTitle;
  7133.  
  7134.     // Tell the Web Panels sidebar to load the bookmark.
  7135.     var sidebar = document.getElementById("sidebar");
  7136.     if (sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser')) {
  7137.         sidebar.contentWindow.loadWebPanel(aURI);
  7138.         if (gWebPanelURI) {
  7139.             gWebPanelURI = "";
  7140.             sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  7141.         }
  7142.     }
  7143. else {
  7144.     // The panel is still being constructed.  Attach an onload handler.
  7145.     if (!gWebPanelURI)
  7146.     sidebar.addEventListener("load", asyncOpenWebPanel, true);
  7147.     gWebPanelURI = aURI;
  7148. }
  7149. }
  7150.  
  7151. function asyncOpenWebPanel(event)
  7152. {
  7153.     var sidebar = document.getElementById("sidebar");
  7154.     if (gWebPanelURI && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser'))
  7155.     sidebar.contentWindow.loadWebPanel(gWebPanelURI);
  7156.     gWebPanelURI = "";
  7157.     sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  7158. }
  7159.  
  7160. /*
  7161. * - [ Dependencies ] ---------------------------------------------------------
  7162. *  utilityOverlay.js:
  7163. *    - gatherTextUnder
  7164. */
  7165.  
  7166. // Called whenever the user clicks in the content area,
  7167. // except when left-clicking on links (special case)
  7168. // should always return true for click to go through
  7169. function contentAreaClick(event, fieldNormalClicks)
  7170. {
  7171.     if (!event.isTrusted) {
  7172.         return true;
  7173.     }
  7174.  
  7175.     var target = event.target;
  7176.     var linkNode;
  7177.  
  7178.     var local_name = target.localName;
  7179.  
  7180.     if (local_name) {
  7181.         local_name = local_name.toLowerCase();
  7182.     }
  7183.  
  7184.     switch (local_name) {
  7185.         case "a":
  7186.         case "area":
  7187.         case "link":
  7188.         if (target.hasAttribute("href"))
  7189.         linkNode = target;
  7190.         break;
  7191.         default:
  7192.         linkNode = findParentNode(event.originalTarget, "a");
  7193.         // <a> cannot be nested.  So if we find an anchor without an
  7194.         // href, there is no useful <a> around the target
  7195.         if (linkNode && !linkNode.hasAttribute("href"))
  7196.         linkNode = null;
  7197.         break;
  7198.     }
  7199.     if (linkNode) {
  7200.              var wrapper = new XPCNativeWrapper(linkNode, "href", "getAttribute()", "ownerDocument");
  7201.         if (event.button == 0 && !event.ctrlKey && !event.shiftKey &&
  7202.         !event.altKey && !event.metaKey) {
  7203.             // A Web panel's links should target the main content area.  Do this
  7204.             // if no modifier keys are down and if there's no target or the target equals
  7205.             // _main (the IE convention) or _content (the Mozilla convention).
  7206.             // The only reason we field _main and _content here is for the markLinkVisited
  7207.             // hack.
  7208.                target = wrapper.getAttribute("target");
  7209.                var docWrapper = new XPCNativeWrapper(wrapper.ownerDocument, "location");
  7210.                var locWrapper = new XPCNativeWrapper(docWrapper.location, "href");
  7211.             if (fieldNormalClicks &&
  7212.             (!target || target == "_content" || target  == "_main"))
  7213.             // IE uses _main, SeaMonkey uses _content, we support both
  7214.                {
  7215.                  if (!wrapper.href) 
  7216.                    return true;
  7217.                  if (wrapper.getAttribute("onclick")) 
  7218.                    return true;
  7219.                  // javascript links should be executed in the current browser
  7220.                  if (wrapper.href.substr(0, 11) === "javascript:")
  7221.                    return true;
  7222.  
  7223.                  if (!webPanelSecurityCheck(locWrapper.href, wrapper.href))
  7224.                    return false;
  7225.  
  7226.                 var postData = { };
  7227.                 var url = getShortcutOrURI(wrapper.href, postData);
  7228.                 if (!url)
  7229.                 return true;
  7230.                 markLinkVisited(wrapper.href, linkNode);
  7231.                 loadURI(url, null, postData.value);
  7232.                 event.preventDefault();
  7233.                 return false;
  7234.             }
  7235.         else if (linkNode.getAttribute("rel") == "sidebar") {
  7236.             // This is the Opera convention for a special link that - when clicked - allows
  7237.             // you to add a sidebar panel.  We support the Opera convention here.  The link's
  7238.             // title attribute contains the title that should be used for the sidebar panel.
  7239.             openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "",
  7240.             "centerscreen,chrome,dialog,resizable,dependent",
  7241.             wrapper.getAttribute("title"),
  7242.             wrapper.href, null, null, null, null, true);
  7243.             event.preventDefault();
  7244.             return false;
  7245.         }
  7246.     else if (target == "_search") {
  7247.         // Used in WinIE as a way of transiently loading pages in a sidebar.  We
  7248.         // mimic that WinIE functionality here and also load the page transiently.
  7249.  
  7250.              // javascript links targeting the sidebar shouldn't be allowed
  7251.              // we copied this from IE, and IE blocks this completely
  7252.              if (wrapper.href.substr(0, 11) === "javascript:")
  7253.                return false;
  7254.  
  7255.              // data: URIs are just as dangerous
  7256.              if (wrapper.href.substr(0, 5) === "data:")
  7257.                return false;
  7258.  
  7259.              if (!webPanelSecurityCheck(locWrapper.href, wrapper.href))
  7260.                return false;
  7261.  
  7262.         openWebPanel(gNavigatorBundle.getString("webPanels"), wrapper.href);
  7263.         event.preventDefault();
  7264.         return false;
  7265.     }
  7266. }
  7267. else {
  7268.     handleLinkClick(event, wrapper.href, linkNode);
  7269. }
  7270.  
  7271. return true;
  7272. } else {
  7273.     // Try simple XLink
  7274.     var href;
  7275.     linkNode = target;
  7276.     while (linkNode) {
  7277.         if (linkNode.nodeType == Node.ELEMENT_NODE) {
  7278.             var wrapper = new XPCNativeWrapper(linkNode, "getAttributeNS()");
  7279.  
  7280.             href = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href");
  7281.             break;
  7282.         }
  7283.         linkNode = linkNode.parentNode;
  7284.     }
  7285.     if (href) {
  7286.         var baseURI = new XPCNativeWrapper(linkNode, "baseURI").baseURI;
  7287.         href = makeURLAbsolute(baseURI, href);
  7288.         handleLinkClick(event, href, null);
  7289.         return true;
  7290.     }
  7291. }
  7292. if (event.button == 1 &&
  7293. !findParentNode(event.originalTarget, "scrollbar") &&
  7294. gPrefService.getBoolPref("middlemouse.contentLoadURL")) {
  7295.     middleMousePaste(event);
  7296. }
  7297. return true;
  7298. }
  7299.  
  7300. function handleLinkClick(event, href, linkNode)
  7301. {
  7302.     switch (event.button) {
  7303.         case 0:
  7304.                 if (event.ctrlKey) {
  7305.                     openNewTabWith(href, linkNode, event, true);
  7306.                     event.preventBubble();
  7307.                     return true;
  7308.                 }
  7309.                 // if left button clicked
  7310.                 if (event.shiftKey) {
  7311.                     openNewWindowWith(href, linkNode, true);
  7312.                     event.preventBubble();
  7313.                     return true;
  7314.                 }
  7315.  
  7316.                 if (event.altKey) {
  7317.                     saveURL(href, linkNode ? gatherTextUnder(linkNode) : "", null, true, true);
  7318.                     return true;
  7319.                 }
  7320.  
  7321.                 return false;
  7322.                 case 1:                                                         // if middle button clicked
  7323.                 var tab;
  7324.                 try {
  7325.                     tab = gPrefService.getBoolPref("browser.tabs.opentabfor.middleclick")
  7326.                 }
  7327.                 catch(ex) {
  7328.                     tab = true;
  7329.                 }
  7330.                 if (tab)
  7331.                 openNewTabWith(href, linkNode, event, true);
  7332.             else
  7333.                 openNewWindowWith(href, linkNode, true);
  7334.                 event.preventBubble();
  7335.                 return true;
  7336.             }
  7337.             return false;
  7338.         }
  7339.  
  7340.         function middleMousePaste(event)
  7341.         {
  7342.             var url = readFromClipboard();
  7343.             if (!url)
  7344.             return false;
  7345.             var postData = { };
  7346.             url = getShortcutOrURI(url, postData);
  7347.             if (!url)
  7348.             return false;
  7349.  
  7350.             // On ctrl-middleclick, open in new tab.
  7351.             var openNewTab;
  7352.                 openNewTab = event.ctrlKey;
  7353.  
  7354.                 if (!openNewTab) {
  7355.                     // If ctrl wasn't down, then just load the url in the current win/tab.
  7356.                     openUILink(url,event,true /* ignore the fact this is a middle click */);
  7357.                 } else {
  7358.                     const nsIURIFixup = Components.interfaces.nsIURIFixup;
  7359.                     if (!gURIFixup)
  7360.                     gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
  7361.                     .getService(nsIURIFixup);
  7362.  
  7363.                     url = gURIFixup.createFixupURI(url, nsIURIFixup.FIXUP_FLAGS_MAKE_ALTERNATE_URI).spec;
  7364.  
  7365.                     openNewTabWith(url, null, event, true, postData.value);
  7366.                 }
  7367.  
  7368.                 event.preventBubble();
  7369.                 return true;
  7370.             }
  7371.  
  7372.             function makeURLAbsolute( base, url )
  7373.             {
  7374.                 // Construct nsIURL.
  7375.                 var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  7376.                 .getService(Components.interfaces.nsIIOService);
  7377.                 var baseURI  = ioService.newURI(base, null, null);
  7378.  
  7379.                 return ioService.newURI(baseURI.resolve(url), null, null).spec;
  7380.             }
  7381.  
  7382.             function findParentNode(node, parentNode)
  7383.             {
  7384.                 if (node && node.nodeType == Node.TEXT_NODE) {
  7385.                     node = node.parentNode;
  7386.                 }
  7387.                 while (node) {
  7388.                     var nodeName = node.localName;
  7389.                     if (!nodeName)
  7390.                     return null;
  7391.                     nodeName = nodeName.toLowerCase();
  7392.                     if (nodeName == "body" || nodeName == "html" ||
  7393.                     nodeName == "#document") {
  7394.                         return null;
  7395.                     }
  7396.                     if (nodeName == parentNode)
  7397.                     return node;
  7398.                     node = node.parentNode;
  7399.                 }
  7400.                 return null;
  7401.             }
  7402.  
  7403.             function saveFrameDocument()
  7404.             {
  7405.                 var focusedWindow = document.commandDispatcher.focusedWindow;
  7406.                 if (isContentFrame(focusedWindow))
  7407.                 saveDocument(focusedWindow.document);
  7408.             }
  7409.  
  7410.             /*
  7411.             * Note that most of this routine has been moved into C++ in order to
  7412.             * be available for all <browser> tags as well as gecko embedding. See
  7413.             * mozilla/content/base/src/nsContentAreaDragDrop.cpp.
  7414.             *
  7415.             * Do not add any new fuctionality here other than what is needed for
  7416.             * a standalone product.
  7417.             */
  7418.  
  7419.             var contentAreaDNDObserver = {
  7420.                 onDrop: function (aEvent, aXferData, aDragSession)
  7421.                 {
  7422.                     var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  7423.  
  7424.                     // valid urls don't contain spaces ' '; if we have a space it
  7425.                     // isn't a valid url, or if it's a javascript: or data: url,
  7426.                     // bail out
  7427.                     if (!url || !url.length || url.indexOf(" ", 0) != -1 ||
  7428.                     /^\s*(javascript|data):/.test(url)) 
  7429.                         return;
  7430.  
  7431.                     getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
  7432.  
  7433.                     switch (document.firstChild.getAttribute('windowtype')) {
  7434.                         case "navigator:browser":
  7435.                         var postData = { };
  7436.                         var uri = getShortcutOrURI(url, postData);
  7437.                         loadURI(uri, null, postData.value);
  7438.                         break;
  7439.                         case "navigator:view-source":
  7440.                         viewSource(url);
  7441.                         break;
  7442.                     }
  7443.  
  7444.                     // keep the event from being handled by the dragDrop listeners
  7445.                     // built-in to gecko if they happen to be above us.
  7446.                     aEvent.preventDefault();
  7447.                 },
  7448.  
  7449.                 getSupportedFlavours: function ()
  7450.                 {
  7451.                     var flavourSet = new FlavourSet();
  7452.                     flavourSet.appendFlavour("text/x-moz-url");
  7453.                     flavourSet.appendFlavour("text/unicode");
  7454.                     flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  7455.                     return flavourSet;
  7456.                 }
  7457.  
  7458.             };
  7459.  
  7460.             // For extensions
  7461.             function getBrowser()
  7462.             {
  7463.                 if (!gBrowser)
  7464.                 gBrowser = document.getElementById("content");
  7465.                 return gBrowser;
  7466.             }
  7467.  
  7468.             function MultiplexHandler(event)
  7469.             { try {
  7470.                 var node = event.target;
  7471.                 var name = node.getAttribute('name');
  7472.  
  7473.                 if (name == 'detectorGroup') {
  7474.                     SetForcedDetector(true);
  7475.                     SelectDetector(event, false);
  7476.                 } else if (name == 'charsetGroup') {
  7477.                     var charset = node.getAttribute('id');
  7478.                     charset = charset.substring('charset.'.length, charset.length)
  7479.                     SetForcedCharset(charset);
  7480.                     SetDefaultCharacterSet(charset);
  7481.                 } else if (name == 'charsetCustomize') {
  7482.                     //do nothing - please remove this else statement, once the charset prefs moves to the pref window
  7483.                 } else {
  7484.                     SetForcedCharset(node.getAttribute('id'));
  7485.                     SetDefaultCharacterSet(node.getAttribute('id'));
  7486.                 }
  7487.             } catch(ex) { dump ("Caught Exception: " + ex + "\n"); }
  7488.         }
  7489.  
  7490.         function SetDefaultCharacterSet(charset)
  7491.         {
  7492.             BrowserSetDefaultCharacterSet(charset);
  7493.         }
  7494.  
  7495.         function SelectDetector(event, doReload)
  7496.         {
  7497.             var uri =  event.target.getAttribute("id");
  7498.             var prefvalue = uri.substring('chardet.'.length, uri.length);
  7499.             if ("off" == prefvalue) { // "off" is special value to turn off the detectors
  7500.                 prefvalue = "";
  7501.             }
  7502.  
  7503.             try {
  7504.                 var pref = Components.classes["@mozilla.org/preferences-service;1"]
  7505.                 .getService(Components.interfaces.nsIPrefBranch);
  7506.                 var str =  Components.classes["@mozilla.org/supports-string;1"]
  7507.                 .createInstance(Components.interfaces.nsISupportsString);
  7508.  
  7509.                 str.data = prefvalue;
  7510.                 pref.setComplexValue("intl.charset.detector",
  7511.                 Components.interfaces.nsISupportsString, str);
  7512.                 if (doReload) window._content.location.reload();
  7513.             }
  7514.             catch (ex) {
  7515.                 dump("Failed to set the intl.charset.detector preference.\n");
  7516.             }
  7517.         }
  7518.  
  7519.         function SetForcedDetector(doReload)
  7520.         {
  7521.             BrowserSetForcedDetector(doReload);
  7522.         }
  7523.  
  7524.         function SetForcedCharset(charset)
  7525.         {
  7526.             BrowserSetForcedCharacterSet(charset);
  7527.         }
  7528.  
  7529.         function BrowserSetDefaultCharacterSet(aCharset)
  7530.         {
  7531.             // no longer needed; set when setting Force; see bug 79608
  7532.         }
  7533.  
  7534.         function BrowserSetForcedCharacterSet(aCharset)
  7535.         {
  7536.             var docCharset = getBrowser().docShell.QueryInterface(
  7537.             Components.interfaces.nsIDocCharset);
  7538.             docCharset.charset = aCharset;
  7539.             BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  7540.         }
  7541.  
  7542.         function BrowserSetForcedDetector(doReload)
  7543.         {
  7544.             getBrowser().documentCharsetInfo.forcedDetector = true;
  7545.             if (doReload)
  7546.             BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  7547.         }
  7548.  
  7549.         function UpdateCurrentCharset()
  7550.         {
  7551.             var menuitem = null;
  7552.  
  7553.             // exctract the charset from DOM
  7554.             var wnd = document.commandDispatcher.focusedWindow;
  7555.             if ((window == wnd) || (wnd == null)) wnd = window._content;
  7556.             menuitem = document.getElementById('charset.' + wnd.document.characterSet);
  7557.  
  7558.             if (menuitem) {
  7559.                 // uncheck previously checked item to workaround Mac checkmark problem
  7560.                 // bug 98625
  7561.                 if (gPrevCharset) {
  7562.                     var pref_item = document.getElementById('charset.' + gPrevCharset);
  7563.                     if (pref_item)
  7564.                     pref_item.setAttribute('checked', 'false');
  7565.                 }
  7566.                 menuitem.setAttribute('checked', 'true');
  7567.             }
  7568.         }
  7569.  
  7570.         function UpdateCharsetDetector()
  7571.         {
  7572.             // showStack();
  7573.             var prefvalue;
  7574.  
  7575.             try {
  7576.                 var pref = Components.classes["@mozilla.org/preferences-service;1"]
  7577.                 .getService(Components.interfaces.nsIPrefBranch);
  7578.                 prefvalue = pref.getComplexValue("intl.charset.detector",
  7579.                 Components.interfaces.nsIPrefLocalizedString).data;
  7580.             }
  7581.             catch (ex) {
  7582.                 prefvalue = "";
  7583.             }
  7584.  
  7585.             if (prefvalue == "") prefvalue = "off";
  7586.             // dump("intl.charset.detector = "+ prefvalue + "\n");
  7587.  
  7588.             prefvalue = 'chardet.' + prefvalue;
  7589.             var menuitem = document.getElementById(prefvalue);
  7590.  
  7591.             if (menuitem) {
  7592.                 menuitem.setAttribute('checked', 'true');
  7593.             }
  7594.         }
  7595.  
  7596.         function UpdateMenus(event)
  7597.         {
  7598.             // use setTimeout workaround to delay checkmark the menu
  7599.             // when onmenucomplete is ready then use it instead of oncreate
  7600.             // see bug 78290 for the detail
  7601.             UpdateCurrentCharset();
  7602.             setTimeout(UpdateCurrentCharset, 0);
  7603.             UpdateCharsetDetector();
  7604.             setTimeout(UpdateCharsetDetector, 0);
  7605.         }
  7606.  
  7607.         function CreateMenu(node)
  7608.         {
  7609.             // dump (" Calling CreateMenu to make a charset menu from within Browser.js\n\n");
  7610.             // showStack();
  7611.             var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  7612.             observerService.notifyObservers(null, "charsetmenu-selected", node);
  7613.         }
  7614.  
  7615.         function charsetLoadListener (event)
  7616.         {
  7617.             var charset = window._content.document.characterSet;
  7618.  
  7619.             if (charset.length > 0 && (charset != gLastBrowserCharset)) {
  7620.                 if (!gCharsetMenu)
  7621.                 gCharsetMenu = Components.classes['@mozilla.org/rdf/datasource;1?name=charset-menu'].getService().QueryInterface(Components.interfaces.nsICurrentCharsetListener);
  7622.                 gCharsetMenu.SetCurrentCharset(charset);
  7623.                 gPrevCharset = gLastBrowserCharset;
  7624.                 gLastBrowserCharset = charset;
  7625.             }
  7626.         }
  7627.  
  7628.  
  7629.         /* Begin Page Style Functions */
  7630.         function getStyleSheetArray(frame)
  7631.         {
  7632.             var styleSheets = frame.document.styleSheets;
  7633.             var styleSheetsArray = new Array(styleSheets.length);
  7634.             for (var i = 0; i < styleSheets.length; i++) {
  7635.                 styleSheetsArray[i] = styleSheets[i];
  7636.             }
  7637.             return styleSheetsArray;
  7638.         }
  7639.  
  7640.         function getAllStyleSheets(frameset)
  7641.         {
  7642.             var styleSheetsArray = getStyleSheetArray(frameset);
  7643.             for (var i = 0; i < frameset.frames.length; i++) {
  7644.                 var frameSheets = getAllStyleSheets(frameset.frames[i]);
  7645.                 styleSheetsArray = styleSheetsArray.concat(frameSheets);
  7646.             }
  7647.             return styleSheetsArray;
  7648.         }
  7649.  
  7650.         function stylesheetFillPopup(menuPopup)
  7651.         {
  7652.             var noStyle = menuPopup.firstChild;
  7653.             var persistentOnly = noStyle.nextSibling;
  7654.             var sep = persistentOnly.nextSibling;
  7655.             while (sep.nextSibling)
  7656.             menuPopup.removeChild(sep.nextSibling);
  7657.  
  7658.             var styleSheets = getAllStyleSheets(window._content);
  7659.             var currentStyleSheets = [];
  7660.             var styleDisabled = getMarkupDocumentViewer().authorStyleDisabled;
  7661.             var haveAltSheets = false;
  7662.             var altStyleSelected = false;
  7663.  
  7664.             for (var i = 0; i < styleSheets.length; ++i) {
  7665.                 var currentStyleSheet = styleSheets[i];
  7666.  
  7667.                 // Skip any stylesheets that don't match the screen media type.
  7668.                 var media = currentStyleSheet.media.mediaText.toLowerCase();
  7669.                 if (media && (media.indexOf("screen") == -1) && (media.indexOf("all") == -1))
  7670.                 continue;
  7671.  
  7672.                 if (currentStyleSheet.title) {
  7673.                     if (!currentStyleSheet.disabled)
  7674.                     altStyleSelected = true;
  7675.  
  7676.                     haveAltSheets = true;
  7677.  
  7678.                     var lastWithSameTitle = null;
  7679.                     if (currentStyleSheet.title in currentStyleSheets)
  7680.                     lastWithSameTitle = currentStyleSheets[currentStyleSheet.title];
  7681.  
  7682.                     if (!lastWithSameTitle) {
  7683.                         var menuItem = document.createElement("menuitem");
  7684.                         menuItem.setAttribute("type", "radio");
  7685.                         menuItem.setAttribute("label", currentStyleSheet.title);
  7686.                         menuItem.setAttribute("data", currentStyleSheet.title);
  7687.                         menuItem.setAttribute("checked", !currentStyleSheet.disabled && !styleDisabled);
  7688.                         menuPopup.appendChild(menuItem);
  7689.                         currentStyleSheets[currentStyleSheet.title] = menuItem;
  7690.                     } else {
  7691.                         if (currentStyleSheet.disabled)
  7692.                         lastWithSameTitle.removeAttribute("checked");
  7693.                     }
  7694.                 }
  7695.             }
  7696.  
  7697.             noStyle.setAttribute("checked", styleDisabled);
  7698.             persistentOnly.setAttribute("checked", !altStyleSelected && !styleDisabled);
  7699.             persistentOnly.hidden = (window._content.document.preferredStylesheetSet) ? true : false;
  7700.             sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets;
  7701.             return true;
  7702.         }
  7703.  
  7704.         function stylesheetInFrame(frame, title) {
  7705.             var docStyleSheets = frame.document.styleSheets;
  7706.  
  7707.             for (var i = 0; i < docStyleSheets.length; ++i) {
  7708.                 if (docStyleSheets[i].title == title)
  7709.                 return true;
  7710.             }
  7711.             return false;
  7712.         }
  7713.  
  7714.         function stylesheetSwitchFrame(frame, title) {
  7715.             var docStyleSheets = frame.document.styleSheets;
  7716.  
  7717.             for (var i = 0; i < docStyleSheets.length; ++i) {
  7718.                 var docStyleSheet = docStyleSheets[i];
  7719.  
  7720.                 if (title == "_nostyle")
  7721.                 docStyleSheet.disabled = true;
  7722.             else if (docStyleSheet.title)
  7723.             docStyleSheet.disabled = (docStyleSheet.title != title);
  7724.         else if (docStyleSheet.disabled)
  7725.         docStyleSheet.disabled = false;
  7726.     }
  7727. }
  7728.  
  7729. function stylesheetSwitchAll(frameset, title) {
  7730.     if (!title || title == "_nostyle" || stylesheetInFrame(frameset, title)) {
  7731.         stylesheetSwitchFrame(frameset, title);
  7732.     }
  7733.     for (var i = 0; i < frameset.frames.length; i++) {
  7734.         stylesheetSwitchAll(frameset.frames[i], title);
  7735.     }
  7736. }
  7737.  
  7738. function setStyleDisabled(disabled) {
  7739.     getMarkupDocumentViewer().authorStyleDisabled = disabled;
  7740. }
  7741.  
  7742. /* End of the Page Style functions */
  7743.  
  7744. function clearObsoletePrefs()
  7745. {
  7746.     // removed 10/03/2003
  7747.     try {
  7748.         PREF.clearUserPref("timebomb.first_launch_time");
  7749.     } catch (e) {}
  7750.  
  7751.     // removed 10/16/2003
  7752.     // migrate firebird cookie prefs, if they exist.
  7753.     try {
  7754.         PREF.clearUserPref("network.cookie.enable");
  7755.         // No error: it means this pref was not the default one, cookie were disabled.
  7756.         PREF.SetIntPref("network.cookie.cookieBehavior", 2);
  7757.     } catch (e) {
  7758.         try {
  7759.             PREF.clearUserPref("network.cookie.enableForOriginatingWebsiteOnly");
  7760.             // No error: it means that enableForOriginatingWebsiteOnly was true.
  7761.             PREF.SetIntPref("network.cookie.cookieBehavior", 1);
  7762.         } catch (e) {
  7763.             // here, either we already have migrated the cookie pref
  7764.             // or the new and old behavior are the same (0). In any case: nothing to do.
  7765.         }
  7766.     }
  7767.  
  7768.     // removed 03/09/2003
  7769.     // last of the forked cookie prefs
  7770.     try {
  7771.         PREF.clearUserPref("network.cookie.enableForCurrentSessionOnly");
  7772.         // No error, therefore we were limiting cookies to session
  7773.         PREF.setIntPref("network.cookie.lifetimePolicy", 2);
  7774.     } catch (e) {
  7775.         // nothing to do in this case
  7776.     }
  7777.  
  7778.     try {
  7779.         PREF.clearUserPref("network.cookie.warnAboutCookies");
  7780.         // No error: the pref is set to ask for cookies, set the correct pref
  7781.         // This will replace the setting if enableForCurrentSessionOnly was
  7782.         // also true, because dialogs explictly allow accepting for session
  7783.         PREF.setIntPref("network.cookie.lifetimePolicy", 1);
  7784.     } catch (e) {
  7785.         // nothing to do in this case
  7786.     }
  7787.  
  7788.     // removed 10/22/2003
  7789.     try {
  7790.         PREF.clearUserPref("browser.search.defaultengine");
  7791.     } catch (e) {}
  7792.  
  7793.     // removed 11/01/2003
  7794.     try {
  7795.         PREF.clearUserPref("print.use_global_printsettings");
  7796.     } catch (e) {}
  7797.     try {
  7798.         PREF.clearUserPref("print.save_print_settings");
  7799.     } catch (e) {}
  7800.  
  7801. }
  7802.  
  7803. var BrowserOffline = {
  7804.     /////////////////////////////////////////////////////////////////////////////
  7805.     // BrowserOffline Public Methods
  7806.     init: function ()
  7807.     {
  7808.         var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  7809.         os.addObserver(this, "network:offline-status-changed", false);
  7810.  
  7811.         if (!this._uiElement)
  7812.         this._uiElement = document.getElementById("goOfflineMenuitem");
  7813.  
  7814.         // set the initial state
  7815.         var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  7816.         var isOffline = false;
  7817.         try {
  7818.             isOffline = gPrefService.getBoolPref("browser.offline");
  7819.         }
  7820.         catch (e) { }
  7821.         ioService.offline = isOffline;
  7822.  
  7823.         this._updateOfflineUI(isOffline);
  7824.     },
  7825.  
  7826.     uninit: function ()
  7827.     {
  7828.         try {
  7829.             var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  7830.             os.removeObserver(this, "network:offline-status-changed");
  7831.         } catch (ex) {
  7832.         }
  7833.     },
  7834.  
  7835.     toggleOfflineStatus: function ()
  7836.     {
  7837.         if (!this._canGoOffline()) {
  7838.             this._updateOfflineUI(false);
  7839.             return;
  7840.         }
  7841.  
  7842.         var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  7843.         ioService.offline = !ioService.offline;
  7844.  
  7845.         gPrefService.setBoolPref("browser.offline", ioService.offline);
  7846.     },
  7847.  
  7848.     /////////////////////////////////////////////////////////////////////////////
  7849.     // nsIObserver
  7850.     observe: function (aSubject, aTopic, aState)
  7851.     {
  7852.         if (aTopic != "network:offline-status-changed")
  7853.         return;
  7854.  
  7855.         this._updateOfflineUI(aState == "offline");
  7856.     },
  7857.  
  7858.     /////////////////////////////////////////////////////////////////////////////
  7859.     // BrowserOffline Implementation Methods
  7860.     _canGoOffline: function ()
  7861.     {
  7862.         var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  7863.         if (os) {
  7864.             try {
  7865.                 var cancelGoOffline = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool);
  7866.                 os.notifyObservers(cancelGoOffline, "offline-requested", null);
  7867.  
  7868.                 // Something aborted the quit process.
  7869.                 if (cancelGoOffline.data)
  7870.                 return false;
  7871.             }
  7872.             catch (ex) {
  7873.             }
  7874.         }
  7875.         return true;
  7876.     },
  7877.  
  7878.     _uiElement: null,
  7879.     _updateOfflineUI: function (aOffline)
  7880.     {
  7881.         var offlineLocked = gPrefService.prefIsLocked("network.online");
  7882.         if (offlineLocked)
  7883.         this._uiElement.setAttribute("disabled", "true");
  7884.  
  7885.         this._uiElement.setAttribute("checked", aOffline);
  7886.     }
  7887. };
  7888.  
  7889. function WindowIsClosing()
  7890. {
  7891.     var browser = getBrowser();
  7892.     var cn = browser.tabContainer.childNodes;
  7893.     var numtabs = cn.length;
  7894.     var reallyClose = browser.warnAboutClosingTabs(true);
  7895.  
  7896.     for (var i = 0; reallyClose && i < numtabs; ++i) {
  7897.         var ds = browser.getBrowserForTab(cn[i]).docShell;
  7898.  
  7899.         if (ds.contentViewer && !ds.contentViewer.permitUnload())
  7900.         reallyClose = false;
  7901.     }
  7902.  
  7903.     if (reallyClose)
  7904.     return closeWindow(false);
  7905.  
  7906.     return reallyClose;
  7907. }
  7908.  
  7909. var MailIntegration = {
  7910.     sendLinkForContent: function ()
  7911.     {
  7912.         this.sendMessage(Components.lookupMethod(window._content, 'location').call(window._content).href,
  7913.         Components.lookupMethod(window._content.document, 'title').call(window._content.document));
  7914.     },
  7915.  
  7916.     sendMessage: function (aBody, aSubject)
  7917.     {
  7918.         // generate a mailto url based on the url and the url's title
  7919.         var mailtoUrl = aBody ? "mailto:?body=" + encodeURIComponent(aBody) + "&subject=" + encodeURIComponent(aSubject) : "mailto:";
  7920.  
  7921.         var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  7922.         var uri = ioService.newURI(mailtoUrl, null, null);
  7923.  
  7924.         // now pass this url to the operating system
  7925.         this._launchExternalUrl(uri);
  7926.     },
  7927.  
  7928.     // a generic method which can be used to pass arbitrary urls to the operating system.
  7929.     // aURL --> a nsIURI which represents the url to launch
  7930.     _launchExternalUrl: function(aURL)
  7931.     {
  7932.         var extProtocolSvc = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"].getService(Components.interfaces.nsIExternalProtocolService);
  7933.         if (extProtocolSvc)
  7934.             extProtocolSvc.loadUrl(aURL);
  7935.     },
  7936.  
  7937.     readMail: function ()
  7938.     {
  7939.         var shell = getShellService();
  7940.         if (shell)
  7941.             shell.openPreferredApplication(Components.interfaces.nsIShellService.APPLICATION_MAIL);
  7942.     },
  7943.  
  7944.     readNews: function ()
  7945.     {
  7946.         var shell = getShellService();
  7947.         if (shell)
  7948.             shell.openPreferredApplication(Components.interfaces.nsIShellService.APPLICATION_NEWS);
  7949.     },
  7950.  
  7951.     updateUnreadCount: function ()
  7952.     {
  7953.         var shell = Components.classes["@mozilla.org/browser/shell-service;1"]
  7954.                               .getService(Components.interfaces.nsIWindowsShellService);
  7955.         var unreadCount = shell.unreadMailCount;
  7956.         var message = gNavigatorBundle.getFormattedString("mailUnreadTooltip", [unreadCount]);
  7957.         var element = document.getElementById("mail-button");
  7958.         if (element)
  7959.             element.setAttribute("tooltiptext", message);
  7960.  
  7961.         message = gNavigatorBundle.getFormattedString("mailUnreadMenuitem", [unreadCount]);
  7962.         element = document.getElementById("Browser:ReadMail");
  7963.         if (element)
  7964.             element.setAttribute("label", message);
  7965.     }
  7966. };
  7967.  
  7968. function BrowserOpenExtensions(aOpenMode)
  7969. {
  7970.     const EMTYPE = "Extension:Manager";
  7971.  
  7972.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  7973.     .getService(Components.interfaces.nsIWindowMediator);
  7974.     var needToOpen = true;
  7975.     var windowType = EMTYPE + "-" + aOpenMode;
  7976.     var windows = wm.getEnumerator(windowType);
  7977.     while (windows.hasMoreElements()) {
  7978.         var theEM = windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindowInternal);
  7979.         if (theEM.document.documentElement.getAttribute("windowtype") == windowType) {
  7980.             theEM.focus();
  7981.             needToOpen = false;
  7982.             break;
  7983.         }
  7984.     }
  7985.  
  7986.     if (needToOpen) {
  7987.         const EMURL = "chrome://mozapps/content/extensions/extensions.xul?type=" + aOpenMode;
  7988.         const EMFEATURES = "chrome,dialog=no,resizable";
  7989.         window.openDialog(EMURL, "", EMFEATURES);
  7990.     }
  7991. }
  7992.  
  7993. function AutofillEdit()
  7994. {
  7995.     const EMTYPE = "AutoFill:Manager";
  7996.  
  7997.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  7998.     .getService(Components.interfaces.nsIWindowMediator);
  7999.     var needToOpen = true;
  8000.     var windowType = EMTYPE;
  8001.     var windows = wm.getEnumerator(windowType);
  8002.     while (windows.hasMoreElements()) {
  8003.         var theEM = windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindowInternal);
  8004.         var wtype=theEM.document.documentElement.getAttribute("windowtype");
  8005.         dump("window type:"+wtype+"\n");
  8006.         if (theEM.document.documentElement.getAttribute("windowtype") == windowType) {
  8007.             theEM.focus();
  8008.             needToOpen = false;
  8009.             break;
  8010.         }
  8011.     }
  8012.     if (needToOpen) {
  8013.         const EMURL = "chrome://browser/content/pref/pref.xul";
  8014.         const EMFEATURES = "chrome,dialog=no,resizable";
  8015.         window.openDialog(EMURL, "", EMFEATURES);
  8016.     }
  8017. }
  8018.  
  8019. // MERC - JCH: Combined datacard and passcard button behaviour.
  8020. // Check whether page is passcardable first. If page isn't, then
  8021. // assume it's datacardable.
  8022. function DoCombinedAutofill()
  8023. {
  8024.     // Does page have password/username fields?
  8025.     // (The boolean means: true = ignore whether there is text in fields,
  8026.     // false = insist that both fields have text otherwise return false).
  8027.     if (CheckIsPasscardable(true)) {
  8028.         DoPasscardOneTime();
  8029.     } else {
  8030.         datacardButton();
  8031.     }
  8032. }
  8033.  
  8034. // MERC - JCH: Fired when datacard-passcard button fill form menu item invoked.
  8035. function DoCombinedFill(menuitem, doSubmit)
  8036. {
  8037.     if (CheckIsPasscardable(true)) {
  8038.         fillUsernamePassword(menuitem, doSubmit);
  8039.     } else {
  8040.         if (doSubmit)
  8041.             datacardUtils.DoAutoFillAndSubmit();
  8042.         else
  8043.             datacardUtils.DoAutoFill();
  8044.     }
  8045. }
  8046.  
  8047. // MERC - JCH: Fired when datacard-passcard button save form menu item invoked.
  8048. function DoCombinedSave()
  8049. {
  8050.     if (CheckIsPasscardable(true)) {
  8051.         savePasscard();
  8052.     } else {
  8053.         datacardUtils.SaveDatacard();
  8054.     }
  8055. }
  8056.  
  8057. // MERC - JCH: Fired when datacard-passcard button drop-down menu is opened.
  8058. function UpdateCombinedMenu(menuitem)
  8059. {
  8060.     clearDatacardMenu();
  8061.     clearPasscardMenu();
  8062.     if (CheckIsPasscardable(true)) {
  8063.         updatePasscardMenu(menuitem);
  8064.     } else {
  8065.         updateDatacardMenu();
  8066.     }
  8067. }
  8068.  
  8069.  
  8070. function AddKeywordForSearchField()
  8071. {
  8072.     var node = document.popupNode;
  8073.     var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  8074.                               .getService(Components.interfaces.nsIIOService);
  8075.     var uri = Components.classes["@mozilla.org/network/standard-url;1"]
  8076.                         .getService(Components.interfaces.nsIURI);
  8077.     uri.spec = node.ownerDocument.URL;
  8078.  
  8079.     var keywordURL = ioService.newURI(node.form.action, node.ownerDocument.characterSet, uri);
  8080.     var spec = keywordURL.spec;
  8081.     var postData = "";
  8082.  
  8083.     if (node.form.method.toUpperCase() == "POST" &&
  8084.     (node.form.enctype == "application/x-www-form-urlencoded" || node.form.enctype == "")) {
  8085.         for (var i = 0; i < node.form.elements.length; ++i) {
  8086.             var e = node.form.elements[i];
  8087.             if (e.type.toLowerCase() == "text" || e.type.toLowerCase() == "hidden" ||
  8088.             e.localName.toLowerCase() == "textarea")
  8089.             postData += escape(e.name + "=" + (e == node ? "%s" : e.value)) + "&";
  8090.         else if (e.localName.toLowerCase() == "select" && e.selectedIndex >= 0)
  8091.         postData += escape(e.name + "=" + e.options[e.selectedIndex].value) + "&";
  8092.     else if ((e.type.toLowerCase() == "checkbox" ||
  8093.     e.type.toLowerCase() == "radio") && e.checked)
  8094.     postData += escape(e.name + "=" + e.value) + "&";
  8095. }
  8096. }
  8097. else {
  8098.     spec += "?" + escape(node.name) + "=%s";
  8099.     for (var i = 0; i < node.form.elements.length; ++i) {
  8100.         var e = node.form.elements[i];
  8101.         if (e == node) // avoid duplication of the target field value, which was populated above.
  8102.         continue;
  8103.  
  8104.         if (e.type.toLowerCase() == "text" || e.type.toLowerCase() == "hidden" ||
  8105.         e.localName.toLowerCase() == "textarea")
  8106.         spec += "&" + escape(e.name) + "=" + escape(e.value);
  8107.     else if (e.localName.toLowerCase() == "select" && e.selectedIndex >= 0)
  8108.     spec += "&" + escape(e.name) + "=" + escape(e.options[e.selectedIndex].value);
  8109. else if ((e.type.toLowerCase() == "checkbox" ||
  8110. e.type.toLowerCase() == "radio") && e.checked)
  8111. spec += "&" + escape(e.name) + "=" + escape(e.value);
  8112. }
  8113. }
  8114. openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "",
  8115. "centerscreen,chrome,dialog,resizable,dependent",
  8116. "", spec, null, node.ownerDocument.characterSet, null, null,
  8117. false, "", true, postData);
  8118. }
  8119.  
  8120. // MERC - This function opens the options panel as specified by the
  8121. // optionToOpen parameter we need to setup string constants for all of these
  8122. // panels, ie WEB_FEATURES = 2 so anyone can call any panel
  8123. function openPrefs(optionToOpen) {
  8124.     // WARNING: KLUGE ALERT!!!
  8125.     gPrefService.setIntPref('browser.preferences.lastpanel', optionToOpen);
  8126.     openPreferences();
  8127. }
  8128.  
  8129. // MERC (DP): opens the site controls prefs dialog with the entry for the
  8130. // current tab selected.
  8131. function openSiteControlPrefs() {
  8132.     var url = gBrowser.currentURI.spec;
  8133.  
  8134.     // is this a controlled site?
  8135.     var controlledSite = sitecontrols.getControlledSiteFromURL(url);
  8136.     var site;
  8137.     if (!controlledSite) {
  8138.         site = sitecontrols.DEFAULT_SITE;
  8139.     } else {
  8140.         site = controlledSite;
  8141.     }
  8142.  
  8143.     gPrefService.setCharPref('browser.preferences.selectedSite', site);
  8144.     openPrefs(3);
  8145. }
  8146.  
  8147. function getTridentDocument()
  8148. {
  8149.     var hpDoc = null;
  8150.     try
  8151.     {
  8152.         hpDoc = gBrowser.contentDocument.QueryInterface(nsIHTMLPluginDocument);
  8153.     }
  8154.     catch(e) { } // Not trident
  8155.     return hpDoc;
  8156. }
  8157.  
  8158. // MERC (DP): enables/disables the "Clear Download Manager History" menu item in the
  8159. // downloads toolbar button dropdown
  8160. function updateDownloadsMenu(menu) {
  8161.     var dlMgr = Components.classes["@mozilla.org/download-manager;1"].getService(Components.interfaces.nsIDownloadManager);
  8162.  
  8163.     var clearDownloadsItem = document.getElementById('clearDownloadsHistory');
  8164.     var clearDownloadsCmd = document.getElementById('History:ClearDownloads');
  8165.  
  8166.     if(dlMgr.canCleanUp) {
  8167.         clearDownloadsItem.removeAttribute('disabled');
  8168.         clearDownloadsCmd.removeAttribute('disabled');
  8169.     } else {
  8170.         clearDownloadsItem.setAttribute('disabled', 'true');
  8171.         clearDownloadsCmd.setAttribute('disabled', 'true');
  8172.     }
  8173. }
  8174.  
  8175.  
  8176. // Clear out the specific datacards from the menu
  8177. function clearDatacardMenu() {
  8178.     var menu = document.getElementById('combinedFormFillPopup');
  8179.     if (!menu) return;
  8180.     var dcSep = document.getElementById('combinedFormFillDatacardSep');
  8181.     if (!dcSep) return;
  8182.     dcSep.setAttribute('hidden', 'true');
  8183.     var node = dcSep;
  8184.     while (node) {
  8185.         var temp = node;
  8186.         node = node.nextSibling;
  8187.         if (temp.hasAttribute('datacard'))
  8188.             menu.removeChild(temp);
  8189.     }
  8190. }
  8191.  
  8192. // MERC - JCH: Element IDs were modified to work with the 
  8193. // new combined datacard-passcard button.
  8194. function updateDatacardMenu() {
  8195.     // Grab the menu items
  8196.     var formFill = document.getElementById('combinedFillFormMenuItem');
  8197.     var formFillAndSubmit = document.getElementById('combinedFillAndSubmitMenuItem');
  8198.     var save = document.getElementById('combinedSaveMenuItem');
  8199.     // See if the current page is fillable
  8200.     var htmlFields = datacardUtils.RipFields();
  8201.     var fillable = datacardUtils.IsPageAutoFillable(
  8202.                                    gBrowser.currentURI,
  8203.                                    htmlFields,
  8204.                                    true);  // check for data
  8205.     var isBlacklisted = datacardUtils.IsSiteBlacklisted(gBrowser.currentURI);
  8206.     if (fillable) {
  8207.         if (!isBlacklisted && datacardUtils.DatacardsExist()) {
  8208.             var menu = document.getElementById('combinedFormFillPopup');
  8209.             var dcSep = document.getElementById('combinedFormFillDatacardSep');
  8210.             var pcSep = document.getElementById('combinedFormFillPasscardSep');
  8211.             formFill.removeAttribute('disabled');
  8212.             formFillAndSubmit.removeAttribute('disabled');
  8213.             dcSep.removeAttribute('hidden');
  8214.             var allDatacards = datacardUtils.GetDatacardList();
  8215.             var siteDatacard = datacardUtils.FindDatacardForURI(gBrowser.currentURI);
  8216.             for (var i = 0; i < allDatacards.length; i++) {
  8217.                 var item = document.createElement('menuitem');
  8218.                 item.setAttribute('label', allDatacards[i]);
  8219.                 item.setAttribute('type', 'checkbox');
  8220.                 item.setAttribute('tooltiptext', 'Use this datacard');
  8221.                 item.setAttribute('datacard', 'true');
  8222.                 if (allDatacards[i] == siteDatacard)
  8223.                     item.setAttribute('checked', 'true');
  8224.                 item.setAttribute('oncommand', 'datacardUtils.DoAutoFill(undefined,"'+allDatacards[i]+'");');
  8225.                 menu.insertBefore(item, pcSep);
  8226.             }
  8227.         } else {
  8228.             formFill.setAttribute('disabled','true');
  8229.             formFillAndSubmit.setAttribute('disabled','true');
  8230.         }
  8231.     } else {
  8232.         formFill.setAttribute('disabled','true');
  8233.         formFillAndSubmit.setAttribute('disabled','true');
  8234.     }
  8235.  
  8236.     // check if the user has entered any data on the page    
  8237.     var bHasData = false;
  8238.     for (var j = 0; j < htmlFields.values.length; j++) {
  8239.         if (htmlFields.values[j] != '') {
  8240.             bHasData = true;
  8241.             break;
  8242.         }
  8243.     }
  8244.  
  8245.     // enable/disable the Save Form menu option
  8246.     if (!isBlacklisted && (fillable || bHasData))
  8247.         save.removeAttribute('disabled');
  8248.     else
  8249.         save.setAttribute('disabled','true');
  8250. }
  8251.  
  8252. function datacardButton() {
  8253.     if (gPrefService.getPrefType('datacard.fillandsubmit') &&
  8254.         gPrefService.getBoolPref('datacard.fillandsubmit'))
  8255.     {
  8256.         datacardUtils.DoAutoFillAndSubmit();
  8257.     } else {
  8258.         datacardUtils.DoAutoFill();
  8259.     }
  8260. }
  8261.  
  8262.  
  8263. var gCurrentNotificationBar = null;
  8264.  
  8265. /*
  8266. JMC: Enforces order of precedence between all possible
  8267. simultaneous notification bars...
  8268. */
  8269. function displayNotificationBar(barId, extraData)
  8270. {
  8271.     dump("browser.js: Trying to show notification bar for : " + barId + "\n");
  8272.     // Simple case - no other bars
  8273.     if (!gCurrentNotificationBar) {
  8274.         showNBar(barId, extraData);
  8275.     } else if (barPriority(barId) >= barPriority(gCurrentNotificationBar)) {
  8276.         showNBar(barId, extraData);
  8277.     } else {
  8278.         dump("browser.js: Not showing it - not important enough.\n");
  8279.     }
  8280. }
  8281.  
  8282.  
  8283. function hideNotificationBar(barId, thisBrowser)
  8284. {
  8285.     if (gCurrentNotificationBar == barId) {
  8286.         thisBrowser.hideMessage(thisBrowser.selectedBrowser, "top");
  8287.         gCurrentNotificationBar = null;
  8288.     }
  8289. }
  8290.  
  8291.  
  8292. function barPriority(barId)
  8293. {
  8294.     var priority;
  8295.     switch (barId) {
  8296.     case "phishing" :
  8297.         priority = 9;
  8298.         break;
  8299.     case "spyware" :
  8300.         priority = 10;
  8301.         break;
  8302.     case "webmail" :
  8303.         priority = 1;
  8304.         break;
  8305.     case "rss" :
  8306.         priority = 2;
  8307.         break;
  8308.     case "popup" :
  8309.         priority = 3;
  8310.         break;
  8311.     case "datacard" :
  8312.         priority = 4;
  8313.         break;
  8314.     case "passcard" :
  8315.         priority = 5;
  8316.         break;
  8317.     case "xpi" :
  8318.         priority = 6;
  8319.         break;
  8320.     case "missing-plugin" :
  8321.         priority = 6;
  8322.         break;
  8323.     }
  8324.     return priority;
  8325. }
  8326.  
  8327.  
  8328. function showNBar(barId, extraData)
  8329. {
  8330.     dump("browser.js: Showing bar : " + barId + "\n");
  8331.     var browser = gBrowser.selectedBrowser;
  8332.     var tabbrowser = getBrowser();
  8333.     var bundle_browser = document.getElementById("bundle_browser");
  8334.     var brandBundle = document.getElementById("bundle_brand");
  8335.     var brandShortName = brandBundle.getString("brandShortName");
  8336.     var imgIcon = "chrome://browser/skin/Info.png";
  8337.     var message = "";
  8338.     var buttonString = "";
  8339.     var deckIdx = 0;
  8340.     var aSource;
  8341.     var aPopup;
  8342.     var aDocShell;
  8343.  
  8344.     switch (barId) {
  8345.     case "phishing" :
  8346.         // don't show bar if pref is not set
  8347.         if (!gPrefService.getBoolPref("trustsettings.showwarnings")) return;
  8348.         var siteURL = extraData[0];
  8349.         var matchingPartners = blacklistUtils.lastSitePartners.join(", ");
  8350.         message = bundle_browser.getFormattedString("phishingNotification", [siteURL.host, matchingPartners]);
  8351.         deckIdx = 3;
  8352.         break;
  8353.  
  8354.     case "spyware" :
  8355.         // don't show bar if pref is not set
  8356.         if (!gPrefService.getBoolPref("trustsettings.showwarnings")) return;
  8357.         var siteURL = extraData[0];
  8358.         var matchingPartners = blacklistUtils.lastSitePartners.join(", ");
  8359.         message = bundle_browser.getFormattedString("spywareNotification", [siteURL.host, matchingPartners]);
  8360.         deckIdx = 4;
  8361.         break;
  8362.  
  8363.     case "webmail" :
  8364.         deckIdx = 5;
  8365.         imgIcon = extraData[0];
  8366.         message = extraData[1];
  8367.         break;
  8368.  
  8369.     case "rss" :
  8370.         deckIdx = 0;
  8371.         message = bundle_browser.getFormattedString("rssWarning", [brandShortName]);
  8372.         aPopup = "blockedRSSOptions";
  8373.         imgIcon = "chrome://browser/skin/page-livemarks.png";
  8374.         break;
  8375.  
  8376.     case "popup" :
  8377.         deckIdx = 6;
  8378.         //var popupCount = gBrowser.selectedBrowser.pageReport.length;
  8379.         //if (popupCount > 1)
  8380.         //    message = bundle_browser.getFormattedString("popupWarningMultiple", [brandShortName, popupCount]);
  8381.         //else
  8382.         message = bundle_browser.getFormattedString("popupWarning", [brandShortName]);
  8383.         break;
  8384.  
  8385.     case "datacard" :
  8386.         deckIdx = 2;
  8387.         break;
  8388.  
  8389.     case "passcard" :
  8390.         deckIdx = 1;
  8391.         message = bundle_browser.getString("passcardMsg");
  8392.         imgIcon = "chrome://browser/skin/icons/passwordsm_h.png";
  8393.         break;
  8394.  
  8395.     case "xpi" :
  8396.         deckIdx = 0;
  8397.         imgIcon = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
  8398.         var messageKey = "xpinstallWarning";
  8399.         var buttonKey = "xpinstallWarningButton";
  8400.         var shell = extraData[0];
  8401.         var host = browser.docShell.QueryInterface(Components.interfaces.nsIWebNavigation).currentURI.host;
  8402.         aSource = "xpinstall-install-edit-permissions";
  8403.         if (!gPrefService.getBoolPref("xpinstall.enabled")) {
  8404.             message = bundle_browser.getFormattedString("xpinstallDisabledWarning",    [brandShortName, host]);
  8405.             buttonString = bundle_browser.getString("xpinstallDisabledWarningButton");
  8406.         }
  8407.         else {
  8408.             message = bundle_browser.getFormattedString(messageKey, [brandShortName, host]);
  8409.             buttonString = bundle_browser.getString(buttonKey);
  8410.         }
  8411.         aDocShell = shell;
  8412.         break;
  8413.  
  8414.     case "missing-plugin" :
  8415.         browser = extraData[0];
  8416.         imgIcon = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
  8417.         message = bundle_browser.getString("missingpluginsMessage.title");
  8418.         buttonString = bundle_browser.getString("missingpluginsMessage.button.label");
  8419.         aSource = "missing-plugin";
  8420.         break;
  8421.     }
  8422.  
  8423.     gBrowser.hideMessage(browser, "both");
  8424.     dump('Bar will show message : ' + message + '\n');
  8425.     gBrowser.showMessage(browser, imgIcon, message, buttonString,
  8426.                          aDocShell, aSource, aPopup, "top", true, deckIdx);
  8427.     gCurrentNotificationBar = barId;
  8428. }
  8429.  
  8430.  
  8431. // MERC - JCH
  8432. function openFormfillPrefs()
  8433. {
  8434.     gPrefService.setCharPref('browser.preferences.formfillORpasscard', 'formfilltab');
  8435.     openPrefs(5);
  8436. }
  8437.  
  8438.  
  8439. // MERC - JCH: This is called from nsHTMLPluginDocument.cpp.
  8440. function IsTridentFillable()
  8441. {
  8442.     if (blacklistUtils.IsSiteInPhishList(gBrowser.currentURI)) {
  8443.             displayNotificationBar("phishing",[gBrowser.currentURI]);
  8444.             // ShowPhishingSiteWarning();
  8445.         } else if (blacklistUtils.IsSiteInSpywareList(gBrowser.currentURI)) {
  8446.             displayNotificationBar("spyware",[gBrowser.currentURI]);
  8447.         }
  8448.         
  8449.     datacardUtils.DoPageLoadedCheck();
  8450. }
  8451.  
  8452.  
  8453. // MERC (DP): simply calls toggleDisplayEngineSiteControl() for the current tab.
  8454. // called from nsHTMLPluginDocument::ToggleEngine()
  8455. function BrowserToggleDisplayEngineSiteControl()
  8456. {
  8457.     //dump("Browser Engine Toggle : \n\n");
  8458.     //showStack();
  8459.     gBrowser.mCurrentTab.toggleDisplayEngineSiteControl();
  8460. }
  8461.  
  8462.  
  8463. function BrowserClosedByCloseButton()
  8464. {
  8465.     var webBrowserPrint = PrintUtils.getWebBrowserPrint();
  8466.     if (webBrowserPrint.doingPrintPreview) {
  8467.         // setTimeout(FinallyClose, 10);
  8468.         PrintUtils.exitPrintPreview();
  8469.     }
  8470.     else {
  8471.         FinallyClose();
  8472.     }
  8473. }
  8474.  
  8475.  
  8476. function FinallyClose()
  8477. {
  8478.     if (WindowIsClosing())
  8479.         window.close();
  8480. }
  8481.  
  8482. //Merc , SLiu
  8483. function ShowPrintErrorDialogForTrident(errorId)
  8484. {
  8485.     const bundleURL = "chrome://global/locale/printing.properties";
  8486.  
  8487.     const sbsContractID = "@mozilla.org/intl/stringbundle;1";
  8488.     const sbsIID = Components.interfaces.nsIStringBundleService;
  8489.     const sbs = Components.classes[sbsContractID].getService(sbsIID);
  8490.  
  8491.     const lsContractID = "@mozilla.org/intl/nslocaleservice;1";
  8492.     const lsIID = Components.interfaces.nsILocaleService;
  8493.     const ls = Components.classes[lsContractID].getService(lsIID);
  8494.     var appLocale = ls.getApplicationLocale();
  8495.     var strBundle = sbs.createBundle(bundleURL, appLocale);
  8496.     var titleStr=null;
  8497.     var msg=null;
  8498.     if(errorId==PRINT_PREVIEW_REQ_WHILE_TRIDENT_LOADING_ERROR)
  8499.     {
  8500.         titleStr=strBundle.GetStringFromName("printpreview_error_dialog_title");
  8501.         msg=strBundle.GetStringFromName("NS_ERROR_GFX_PRINTER_DOC_IS_BUSY_PP");
  8502.     }
  8503. else if(errorId==PRINT_REQ_WHILE_TRIDENT_LOADING_ERROR)
  8504. {
  8505.     titleStr=strBundle.GetStringFromName("print_req_error_dialog_title");
  8506.     msg=strBundle.GetStringFromName("NS_ERROR_GFX_PRINTER_DOC_IS_BUSY");
  8507. }
  8508. if(titleStr && msg)
  8509. {
  8510.     var promptSvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  8511.     promptSvc.alert(null,titleStr, msg);
  8512. }
  8513. }
  8514.  
  8515. /////////////// livemark handling
  8516.  
  8517. // MERC - JCH: Receives RSS data from Trident. Called from nsHTMLPluginDocument.cpp.
  8518. function OnTridentLinkFound(href, rel, title, type, doc)
  8519. {
  8520.     var link = document.createElementNS(XHTML_NS, "link");
  8521.     link.setAttribute("href", href);
  8522.     link.setAttribute("title", title);
  8523.     link.setAttribute("type", type);
  8524.     link.setAttribute("rel", rel);
  8525.     
  8526.     var event = new Object();
  8527.     event.target = link;
  8528.     event.isTrusted = true;
  8529.     livemarkOnLinkAdded(event, doc);
  8530. }
  8531.  
  8532.  
  8533.  
  8534. // XXX this event listener can/should probably be combined with the onLinkAdded
  8535. // listener in tabbrowser.xml, which only listens for favicons and then passes
  8536. // them to onLinkIconAvailable in the ProgressListener.  We could extend the
  8537. // progress listener to have a generic onLinkAvailable and have tabbrowser pass
  8538. // along all events.  It should give us the browser for the tab, as well as
  8539. // the actual event.
  8540. // MERC - JCH: Added the extra 'doc' argument to allow Trident RSS feed data
  8541. // to display properly.
  8542. function livemarkOnLinkAdded(event, doc)
  8543. {
  8544.     dump("~~~~~~ BROWSER.JS livemarkOnLinkAdded() ~~~~~~~~\n");
  8545.  
  8546.     // dump ("Think doc is " + doc);
  8547.  
  8548.       if (!event.isTrusted)
  8549.         return;
  8550.  
  8551.     if (!gLivemarksButton)
  8552.     gLivemarksButton = document.getElementById("livemark-button");
  8553.  
  8554.     // from tabbrowser.xml
  8555.     // mechanism for reading properties of the underlying XPCOM object
  8556.     // (ignoring potential getters/setters added by malicious content)
  8557.     var safeGetProperty = function(obj, propname) {
  8558.         return Components.lookupMethod(obj, propname).call(obj);
  8559.     }
  8560.  
  8561.     var erel = event.target.rel;
  8562.     var etype = event.target.type;
  8563.     var etitle = event.target.title;
  8564.  
  8565.     // this is a blogger post service URL; so skip it
  8566.     if (erel && erel == "service.post")
  8567.     return;
  8568.  
  8569.     if (etype == "application/rss+xml" ||
  8570.     etype == "application/atom+xml" ||
  8571.     etype == "application/x.atom+xml" ||
  8572.     etitle.indexOf("RSS") != -1 ||
  8573.     etitle.indexOf("Atom") != -1 ||
  8574.     etitle.indexOf("rss") != -1)
  8575.     {
  8576.         // const targetDoc;
  8577.         var targetDoc;
  8578.         if (doc != null) {
  8579.             targetDoc = doc;
  8580.         } else {
  8581.             targetDoc = safeGetProperty(event.target, "ownerDocument");
  8582.         }
  8583.  
  8584.         // find which tab this is for, and set the attribute on the browser
  8585.         // should there be a getTabForDocument method on tabbedbrowser?
  8586.         var browserForLink = null;
  8587.         if (gBrowser.mTabbedMode) {
  8588.             var browserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
  8589.             if (browserIndex == -1) {
  8590.                 dump ("Uhoh - couldn't get browserindex for targetdoc");
  8591.                 
  8592.                 return;
  8593.             }
  8594.             browserForLink = gBrowser.getBrowserAtIndex(browserIndex);
  8595.         } else if (gBrowser.mCurrentBrowser.contentDocument == targetDoc) {
  8596.             browserForLink = gBrowser.mCurrentBrowser;
  8597.         }
  8598.         
  8599.  
  8600.         if (!browserForLink) {
  8601.             // ??? this really shouldn't happen..
  8602.             dump("Uhoh - couldn't find browserForLink");
  8603.             return;
  8604.         }
  8605.  
  8606.         var livemarkLinks = [];
  8607.         if (browserForLink.livemarkLinks != null)
  8608.             livemarkLinks = browserForLink.livemarkLinks;
  8609.  
  8610.         var wrapper = new XPCNativeWrapper(event.target, "href", "type", "title");
  8611.  
  8612.         livemarkLinks.push({ href: wrapper.href,
  8613.                              type: wrapper.type,
  8614.                              title: wrapper.title});
  8615.  
  8616.         browserForLink.livemarkLinks = livemarkLinks;
  8617.         if ((browserForLink == gBrowser || browserForLink == gBrowser.mCurrentBrowser) && gLivemarksButton)
  8618.         gLivemarksButton.setAttribute("livemarks", "true");
  8619.  
  8620.     }
  8621. }
  8622.  
  8623. // this is called both from onload and also whenever the user
  8624. // switches tabs; we update whether we show or hide the livemark
  8625. // button based on whether the window has livemarks set.
  8626. function updatePageLivemarks()
  8627. {
  8628.     // dump("~~~~~~ BROWSER.JS updatePageLivemarks() ~~~~~~~~\n");
  8629.     
  8630.     if (!gLivemarksButton)
  8631.     gLivemarksButton = document.getElementById("livemark-button");
  8632.  
  8633.     if (!gLivemarksButton)
  8634.         return;
  8635.  
  8636.     var livemarkLinks = gBrowser.mCurrentBrowser.livemarkLinks;
  8637.     if (!livemarkLinks || livemarkLinks.length == 0) {
  8638.         gLivemarksButton.removeAttribute("livemarks");
  8639.         gLivemarksButton.setAttribute("tooltiptext", gNavigatorBundle.getString("livemarkNoLivemarksTooltip"));
  8640.     } else {
  8641.         gLivemarksButton.setAttribute("livemarks", "true");
  8642.         gLivemarksButton.setAttribute("tooltiptext", gNavigatorBundle.getString("livemarkHasLivemarksTooltip"));
  8643.     }
  8644. }
  8645.  
  8646. // MERC - JCH: Called from nsHTMLPluginDocument.cpp to remove livemarks button
  8647. function wrappedUpdatePageLivemarks()
  8648. {
  8649.     // Clear livemark data
  8650.     gBrowser.mCurrentBrowser.livemarkLinks = null;
  8651.  
  8652.     updatePageLivemarks();
  8653. }
  8654.  
  8655.  
  8656. function livemarkFillPopup(menuPopup)
  8657. {
  8658.     dump("~~~~~~ BROWSER.JS livemarkFillPopup() ~~~~~~~~\n");
  8659.     var livemarkLinks = gBrowser.mCurrentBrowser.livemarkLinks;
  8660.     if (livemarkLinks == null) {
  8661.         // XXX hack -- menu opening depends on setting of an "open"
  8662.         // attribute, and the menu refuses to open if that attribute is
  8663.         // set (because it thinks it's already open).  onpopupshowing gets
  8664.         // called after the attribute is unset, and it doesn't get unset
  8665.         // if we return false.  so we unset it here; otherwise, the menu
  8666.         // refuses to work past this point.
  8667.         menuPopup.parentNode.removeAttribute("open");
  8668.         return false;
  8669.     }
  8670.  
  8671.     while (menuPopup.firstChild) {
  8672.         menuPopup.removeChild(menuPopup.firstChild);
  8673.     }
  8674.  
  8675.     for (var i = 0; i < livemarkLinks.length; i++) {
  8676.         var markinfo = livemarkLinks[i];
  8677.  
  8678.         var menuItem = document.createElement("menuitem");
  8679.         var baseTitle = markinfo.title || markinfo.href;
  8680.         var labelStr = gNavigatorBundle.getFormattedString("livemarkSubscribeTo", [baseTitle]);
  8681.         menuItem.setAttribute("label", labelStr);
  8682.         menuItem.setAttribute("data", markinfo.href);
  8683.         menuItem.setAttribute("tooltiptext", markinfo.href);
  8684.         menuPopup.appendChild(menuItem);
  8685.     }
  8686.  
  8687.     return true;
  8688. }
  8689.  
  8690. function livemarkAddMark(wincontent, data, altRef) 
  8691. {
  8692.     dump("~~~~~~ BROWSER.JS livemarkAddMark() ~~~~~~~~\n");
  8693.     var title = wincontent.document.title;
  8694.     //  BookmarksUtils.addLivemark(wincontent.document.baseURI, data, title);
  8695.     var refURI;
  8696.     if (altRef) {
  8697.         try {
  8698.             var channels = gBrowser.contentDocument.getElementsByTagName('channel');
  8699.             refURI = channels[0].getAttribute('rdf:about');
  8700.         } catch (ex) {}
  8701.     }
  8702.     if (!refURI) {
  8703.         refURI = wincontent.document.baseURI;
  8704.     }
  8705.  
  8706.     spui.addLivemark(refURI, data, title);
  8707.     reshuffleToolbars(true);
  8708. }
  8709.  
  8710. function updatePageFavIcon(aBrowser, aListener) {
  8711.     var uri = aBrowser.currentURI;
  8712.  
  8713.     if (!gBrowser.shouldLoadFavIcon(uri))
  8714.     return;
  8715.  
  8716.     // if we made it here with this null, then no <link> was found for
  8717.     // the page load.  We try to fetch a generic favicon.ico.
  8718.     if (aBrowser.mFavIconURL == null) {
  8719.         aBrowser.mFavIconURL = gBrowser.buildFavIconString(uri);
  8720. //        dump( "))      WMWMWMWMWMW===> updatePageFavIcon built default path: \""+aBrowser.mFavIconURL+"\"\n" );
  8721.         // give it to the listener as well
  8722.         // XXX - there is no listener for non-tabbed-mode: this is why
  8723.         // the urlbar has no favicon when you switch from tabbed mode to
  8724.         // non-tabbed-mode.
  8725.         if (aListener)
  8726.         aListener.mIcon = aBrowser.mFavIconURL;
  8727.     }
  8728. //    dump( "))      WMWMWMWMWMW===> updatePageFavIcon resulted in: \""+aBrowser.mFavIconURL+"\"\n" );
  8729.  
  8730.     if (aBrowser == gBrowser.mCurrentBrowser)
  8731.     PageProxySetIcon(aBrowser.mFavIconURL);
  8732.  
  8733.     if (aBrowser.mFavIconURL != null)
  8734.     BookmarksUtils.loadFavIcon(uri.spec, aBrowser.mFavIconURL);
  8735. }
  8736.  
  8737. function getUILink(item)
  8738. {
  8739.     var regionBundle = document.getElementById("bundle_browser_region");
  8740.  
  8741.     if (item == "tellAFriend")
  8742.     return regionBundle.getString("tellAFriendURL");
  8743.  
  8744.     if (item == "promote")
  8745.     return regionBundle.getString("promoteURL");
  8746.  
  8747.     return "";
  8748. }
  8749.  
  8750. function isBidiEnabled(){
  8751.     var rv = false;
  8752.  
  8753.     var systemLocale;
  8754.     try {
  8755.         var localService = Components.classes["@mozilla.org/intl/nslocaleservice;1"]
  8756.         .getService(Components.interfaces.nsILocaleService);
  8757.         systemLocale = localService.getSystemLocale().getCategory("NSILOCALE_CTYPE").substr(0,3);
  8758.     } catch (e){}
  8759.  
  8760.     rv = ( (systemLocale == "he-") || (systemLocale == "ar-") || (systemLocale == "syr") ||
  8761.     (systemLocale == "fa-") || (systemLocale == "ur-") );
  8762.  
  8763.     if (!rv) {
  8764.         // check the overriding pref
  8765.         var mPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  8766.         try {
  8767.             rv = mPrefs.getBoolPref("bidi.browser.ui");
  8768.         }
  8769.         catch (e){}
  8770.     }
  8771.  
  8772.     return rv;
  8773. }
  8774.  
  8775. function GetFrameDocumentsFromWindow(aWindow){
  8776.     if (aWindow.getComputedStyle(aWindow.document.body, "").direction == "ltr")
  8777.     aWindow.document.dir = "rtl";
  8778. else
  8779.     aWindow.document.dir = "ltr";
  8780.  
  8781.     for (var run = 0; run < aWindow.frames.length; run++)
  8782.     GetFrameDocumentsFromWindow(aWindow.frames[run]);
  8783. }
  8784.  
  8785. function SwitchDocumentDirection(){
  8786.     GetFrameDocumentsFromWindow(window.content);
  8787. }
  8788.  
  8789. function SwitchFocusedTextEntryDirection() {
  8790.     if (isBidiEnabled())
  8791.     {
  8792.         var focusedElement = document.commandDispatcher.focusedElement;
  8793.         if (focusedElement)
  8794.         if (window.getComputedStyle(focusedElement, "").direction == "ltr")
  8795.         focusedElement.style.direction = "rtl";
  8796.     else
  8797.         focusedElement.style.direction = "ltr";
  8798.     }
  8799. }
  8800.  
  8801.  
  8802. function missingPluginInstaller(){
  8803.     this.missingPlugins = new Object();
  8804. }
  8805.  
  8806. missingPluginInstaller.prototype.installSinglePlugin = function(aEvent){
  8807.     var tabbrowser = getBrowser();
  8808.     var missingPluginsArray = new Object;
  8809.  
  8810.     var tagMimetype;
  8811.     var pluginsPage;
  8812.     if (aEvent.target.localName.toLowerCase() == "applet") {
  8813.         tagMimetype = "application/x-java-vm";
  8814.     } else if (aEvent.target.localName.toLowerCase() == "object") {
  8815.         tagMimetype = aEvent.target.type;
  8816.         pluginsPage = aEvent.target.getAttribute("codebase");
  8817.     } else {
  8818.         tagMimetype = aEvent.target.type;
  8819.         pluginsPage = aEvent.target.getAttribute("pluginspage");
  8820.     }
  8821.  
  8822.     missingPluginsArray[tagMimetype] = {mimetype: tagMimetype, pluginsPage: pluginsPage};
  8823.  
  8824.     if (missingPluginsArray) {
  8825.         window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  8826.         "PFSWindow", "modal,chrome,resizable=yes", {plugins: missingPluginsArray, tab: tabbrowser.mCurrentTab});
  8827.     }
  8828.  
  8829.     aEvent.preventDefault();
  8830. }
  8831.  
  8832. missingPluginInstaller.prototype.newMissingPlugin = function(aEvent){
  8833.     // For broken non-object plugin tags, register a click handler so
  8834.     // that the user can click the plugin replacement to get the new
  8835.     // plugin. Object tags can, and often do, deal with that themselves,
  8836.     // so don't stomp on the page developers toes.
  8837.  
  8838.     if (aEvent.target.localName.toLowerCase() != "object") {
  8839.         aEvent.target.addEventListener("click",
  8840.         gMissingPluginInstaller.installSinglePlugin,
  8841.         false);
  8842.     }
  8843.  
  8844.     var tabbrowser = getBrowser();
  8845.     const browsers = tabbrowser.mPanelContainer.childNodes;
  8846.  
  8847.     var window = aEvent.target.ownerDocument.__parent__;
  8848.     // walk up till the toplevel window
  8849.     while (window.parent != window)
  8850.     window = window.parent;
  8851.  
  8852.     var i = 0;
  8853.     for (; i < browsers.length; i++) {
  8854.         if (tabbrowser.getBrowserAtIndex(i).contentWindow == window)
  8855.         break;
  8856.     }
  8857.  
  8858.     var tab = tabbrowser.mTabContainer.childNodes[i];
  8859.  
  8860.     if (!gMissingPluginInstaller.missingPlugins)
  8861.     gMissingPluginInstaller.missingPlugins = new Object();
  8862.  
  8863.     if (!gMissingPluginInstaller.missingPlugins[tab])
  8864.     gMissingPluginInstaller.missingPlugins[tab] = new Object();
  8865.  
  8866.     var tagMimetype;
  8867.     var pluginsPage;
  8868.     if (aEvent.target.localName.toLowerCase() == "applet") {
  8869.         tagMimetype = "application/x-java-vm";
  8870.     } else if (aEvent.target.localName.toLowerCase() == "object") {
  8871.         tagMimetype = aEvent.target.type;
  8872.         pluginsPage = aEvent.target.getAttribute("codebase");
  8873.     } else {
  8874.         tagMimetype = aEvent.target.type;
  8875.         pluginsPage = aEvent.target.getAttribute("pluginspage");
  8876.     }
  8877.  
  8878.     gMissingPluginInstaller.missingPlugins[tab][tagMimetype] = {
  8879.         mimetype: tagMimetype,
  8880.         pluginsPage: pluginsPage
  8881.     };
  8882.  
  8883.         displayNotificationBar("missing-plugin", [tabbrowser.getBrowserAtIndex(i)]);
  8884. }
  8885.  
  8886. missingPluginInstaller.prototype.clearMissingPlugins = function(aTab){
  8887.     this.missingPlugins[aTab] = null;
  8888. }
  8889.  
  8890.  
  8891. missingPluginInstaller.prototype.observe = function(aSubject, aTopic, aData){
  8892.     switch (aTopic) {
  8893.         case "missing-plugin":
  8894.         // get the urls of missing plugins
  8895.         var tabbrowser = getBrowser();
  8896.         var missingPluginsArray = gMissingPluginInstaller.missingPlugins[tabbrowser.mCurrentTab];
  8897.  
  8898.         if (missingPluginsArray) {
  8899.             window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  8900.             "PFSWindow", "modal,chrome,resizable=yes", {plugins: missingPluginsArray, tab: tabbrowser.mCurrentTab});
  8901.         }
  8902.         hideNotificationBar(tabbrowser, "xpi");
  8903.         // tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top");
  8904.         break;
  8905.     }
  8906. }
  8907. var gMissingPluginInstaller = new missingPluginInstaller();
  8908.  
  8909. function AboutTabBrowsing() {
  8910.     var aboutPage = gPrefService.getCharPref("browser.tabs.abouturl");
  8911.  
  8912.     loadURI(aboutPage);
  8913. }
  8914.  
  8915. function AboutSiteControls() {
  8916.     var aboutPage = gPrefService.getCharPref("browser.sitecontrols.abouturl");
  8917.  
  8918.     loadURI(aboutPage);
  8919. }
  8920.  
  8921.  
  8922. function submitFormdata(fNew,fAction,fMeathod,elementList) {
  8923.     // fNew is boolean: true means open in a new tab, false means open in this tab
  8924.     // fAction is the URL for the post
  8925.     // fMeathod is "post" or "get"
  8926.     // elementList must be an Array() of element-value pairs
  8927.     //             where elementList[n].value is put into elementList[n].name input
  8928.     //                         NOTE: if elementList[n].type is defined it will be set as well
  8929.     //                               i.e. for passwords
  8930.     //initially, it puts the form onto an existing tab
  8931.     try {
  8932.         if (fNew) {
  8933.             BrowserOpenTab();
  8934.         }
  8935.         var myDoc=document.getElementById("content").selectedBrowser.contentDocument;
  8936.         var retval=document.getElementById("content").selectedBrowser;
  8937.         var body=myDoc.getElementsByTagName("body")[0];
  8938.         var myForm=myDoc.createElement("form");
  8939.         myForm.name="readyForMe";
  8940.         var newInput;
  8941.         if (!elementList || elementList.length < 1) {
  8942.             dump("submitFormdata not doing much: no elements\n");
  8943.         } else {
  8944.             for (var i = 0;i<elementList.length;i++) {
  8945.                 newInput=myDoc.createElement("input");
  8946.                 newInput.name=elementList[i].name;
  8947.                 newInput.value=elementList[i].value;
  8948.                 if (elementList[i].type) {
  8949.                     newInput.type=elementList[i].type;
  8950.                 }
  8951.                 myForm.appendChild(newInput);
  8952.                 dump("Added input name="+elementList[i].name+"\n");
  8953.             }
  8954.         }
  8955.         myForm.action=fAction;
  8956.         myForm.method=fMeathod;
  8957.         myForm.target="_self";
  8958.         body.appendChild(myForm);
  8959.         dump("submitting form\n");
  8960.         myForm.submit();
  8961.         dump("done submitPost()\n");
  8962.     } catch (ex) {
  8963.         dump("Exception in browser.js: submitFormdata\n");
  8964.         dump(ex);
  8965.     }
  8966. }
  8967.  
  8968. function webmailHandleURI(urlStr,extra) {
  8969.     webmail.debug("webmailHandleURI();");
  8970.     webmail.handleURI(urlStr);
  8971. }
  8972.  
  8973. function SetTridentCookies(cookieStr)
  8974. {
  8975. //    dump ("Setting Trident Cookies with " + cookieStr + "\n\n");
  8976.     return true;
  8977. }
  8978.  
  8979. function OpenSecurityCenter() {
  8980.     // MERC (rpaul) quick function to open security center tab of site control preferences
  8981.     var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  8982.     if (prefs)
  8983.             prefs.setCharPref("browser.sitecontrols.prefs", "prefsTab");
  8984.     
  8985.     openPrefs(3);
  8986. }