Bug 1515877 - Turn on ESLint in mailnews/base; r=aceman
authorGeoff Lankow <geoff@darktrojan.net>
Tue, 16 Apr 2019 12:48:24 +1200
changeset 26353 d34239c5e7a0
parent 26352 b86fe81c7f28
child 26354 cbd032bfb562
push id15798
push usergeoff@darktrojan.net
push dateTue, 16 Apr 2019 04:15:07 +0000
treeherdercomm-central@ffedede7fa10 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersaceman
bugs1515877
Bug 1515877 - Turn on ESLint in mailnews/base; r=aceman
.eslintignore
mailnews/base/content/dateFormat.js
mailnews/base/content/folderProps.js
mailnews/base/content/folderWidgets.xml
mailnews/base/content/jsTreeView.js
mailnews/base/content/junkCommands.js
mailnews/base/content/junkLog.js
mailnews/base/content/markByDate.js
mailnews/base/content/msgAccountCentral.js
mailnews/base/content/msgFolderPickerOverlay.js
mailnews/base/content/msgPrintEngine.js
mailnews/base/content/msgSelectOfflineFolders.js
mailnews/base/content/msgSynchronize.js
mailnews/base/content/newFolderDialog.js
mailnews/base/content/newmailalert.js
mailnews/base/content/newsError.js
mailnews/base/content/renameFolderDialog.js
mailnews/base/content/retention.js
mailnews/base/content/shutdownWindow.js
mailnews/base/content/subscribe.js
mailnews/base/content/virtualFolderListEdit.js
mailnews/base/content/virtualFolderProperties.js
mailnews/base/prefs/content/AccountManager.js
mailnews/base/prefs/content/AccountManager.xul
mailnews/base/prefs/content/AccountWizard.js
mailnews/base/prefs/content/AccountWizard.xul
mailnews/base/prefs/content/SmtpServerEdit.js
mailnews/base/prefs/content/accountUtils.js
mailnews/base/prefs/content/am-addressing.js
mailnews/base/prefs/content/am-copies.js
mailnews/base/prefs/content/am-help.js
mailnews/base/prefs/content/am-identities-list.js
mailnews/base/prefs/content/am-identity-edit.js
mailnews/base/prefs/content/am-junk.js
mailnews/base/prefs/content/am-main.js
mailnews/base/prefs/content/am-offline.js
mailnews/base/prefs/content/am-offline.xul
mailnews/base/prefs/content/am-prefs.js
mailnews/base/prefs/content/am-server-advanced.js
mailnews/base/prefs/content/am-server.js
mailnews/base/prefs/content/am-serverwithnoidentities.js
mailnews/base/prefs/content/am-smtp.js
mailnews/base/prefs/content/amUtils.js
mailnews/base/prefs/content/aw-accname.js
mailnews/base/prefs/content/aw-accounttype.js
mailnews/base/prefs/content/aw-done.js
mailnews/base/prefs/content/aw-identity.js
mailnews/base/prefs/content/aw-incoming.js
mailnews/base/prefs/content/aw-outgoing.js
mailnews/base/prefs/content/converterDialog.js
mailnews/base/prefs/content/removeAccount.js
mailnews/base/search/content/CustomHeaders.js
mailnews/base/search/content/FilterEditor.js
mailnews/base/search/content/FilterEditor.xul
mailnews/base/search/content/searchTerm.js
mailnews/base/search/content/searchWidgets.js
mailnews/base/search/content/searchWidgets.xml
mailnews/base/search/content/viewLog.js
mailnews/base/search/src/nsMsgTraitService.js
mailnews/base/src/folderLookupService.js
mailnews/base/src/msgAsyncPrompter.js
mailnews/base/src/msgOAuth2Module.js
mailnews/base/src/newMailNotificationService.js
mailnews/base/src/nsMailNewsCommandLineHandler.js
mailnews/base/src/virtualFolderWrapper.js
mailnews/base/util/IOUtils.js
mailnews/base/util/JXON.js
mailnews/base/util/OAuth2.jsm
mailnews/base/util/OAuth2Providers.jsm
mailnews/base/util/StringBundle.js
mailnews/base/util/converterWorker.js
mailnews/base/util/errUtils.js
mailnews/base/util/folderUtils.jsm
mailnews/base/util/hostnameUtils.jsm
mailnews/base/util/iteratorUtils.jsm
mailnews/base/util/jsTreeSelection.js
mailnews/base/util/mailnewsMigrator.js
mailnews/base/util/msgDBCacheManager.js
mailnews/base/util/templateUtils.js
mailnews/base/util/traceHelper.js
mailnews/jar.mn
--- a/.eslintignore
+++ b/.eslintignore
@@ -57,21 +57,16 @@ editor/ui/dialogs/content/EditorSaveAsCh
 editor/ui/dialogs/content/EdLinkChecker.js
 editor/ui/dialogs/content/EdLinkChecker.xul
 editor/ui/dialogs/content/EdSnapToGrid.js
 editor/ui/dialogs/content/EdSnapToGrid.xul
 editor/ui/texzilla/**
 
 # mailnews exclusions
 mailnews/mailnews.js
-mailnews/base/content/*
-mailnews/base/prefs/*
-mailnews/base/search/*
-mailnews/base/src/*
-mailnews/base/util/*
 mailnews/build/*
 mailnews/compose/*
 mailnews/db/*
 mailnews/imap/*
 mailnews/import/*
 mailnews/intl/*
 mailnews/jsaccount/*
 mailnews/mime/*
--- a/mailnews/base/content/dateFormat.js
+++ b/mailnews/base/content/dateFormat.js
@@ -13,146 +13,125 @@ var gSearchDateFormat = 0;
 var gSearchDateSeparator;
 var gSearchDateLeadingZeros;
 
 /**
  * Get the short date format option of the current locale.
  * This supports the common case which the date separator is
  * either '/', '-', '.' and using Christian year.
  */
-function initLocaleShortDateFormat()
-{
+function initLocaleShortDateFormat() {
   try {
     const dateFormatter = new Services.intl.DateTimeFormat(undefined,
       { dateStyle: "short" });
     var aDate = new Date(1999, 11, 1);
-    var dateString = dateFormatter.format(aDate).replace(/ /g,"");
+    var dateString = dateFormatter.format(aDate).replace(/ /g, "");
 
     // find out the separator
     var possibleSeparators = "/-.";
     var arrayOfStrings;
-    for (let i = 0; i < possibleSeparators.length; ++i)
-    {
+    for (let i = 0; i < possibleSeparators.length; ++i) {
       arrayOfStrings = dateString.split(possibleSeparators[i]);
-      if (arrayOfStrings.length == 3)
-      {
+      if (arrayOfStrings.length == 3) {
         gSearchDateSeparator = possibleSeparators[i];
         break;
       }
     }
 
     // check the format option
-    if (arrayOfStrings.length != 3)  // no successful split
-    {
+    if (arrayOfStrings.length != 3) { // no successful split
       Cu.reportError("initLocaleShortDateFormat: could not analyze the date format, defaulting to mm/dd/yyyy");
-    }
-    else
-    {
+    } else {
       // The date will contain a zero if the system settings include leading zeros.
       gSearchDateLeadingZeros = dateString.includes("0");
 
       // match 1 as number, since that will match both "1" and "01"
-      if (arrayOfStrings[0] == 1)
-      {
+      if (arrayOfStrings[0] == 1) {
         // 01.12.1999 or 01.1999.12
         gSearchDateFormat = arrayOfStrings[1] == "12" ? 5 : 6;
-      }
-      else if (arrayOfStrings[1] == 1)
-      {
+      } else if (arrayOfStrings[1] == 1) {
         // 12.01.1999 or 1999.01.12
         gSearchDateFormat = arrayOfStrings[0] == "12" ? 3 : 2;
-      }
-      else  // implies arrayOfStrings[2] == 1
-      {
+      } else { // implies arrayOfStrings[2] == 1
         // 12.1999.01 or 1999.12.01
         gSearchDateFormat = arrayOfStrings[0] == "12" ? 4 : 1;
       }
     }
-  }
-  catch (e)
-  {
+  } catch (e) {
     Cu.reportError("initLocaleShortDateFormat: caught an exception: " + e);
     gSearchDateFormat = 0;
   }
 }
 
-function initializeSearchDateFormat()
-{
+function initializeSearchDateFormat() {
   if (gSearchDateFormat > 0)
     return;
 
   // get a search date format option and a separator
   try {
     gSearchDateFormat =
       Services.prefs.getComplexValue("mailnews.search_date_format",
                                      Ci.nsIPrefLocalizedString).data;
 
     gSearchDateFormat = parseInt(gSearchDateFormat);
 
     // if the option is 0 then try to use the format of the current locale
-    if (gSearchDateFormat == 0)
+    if (gSearchDateFormat == 0) {
       initLocaleShortDateFormat();
-    else
-    {
+    } else {
       // initialize the search date format based on preferences
       if (gSearchDateFormat < 1 || gSearchDateFormat > 6)
         gSearchDateFormat = 3;
 
       gSearchDateSeparator =
         Services.prefs.getComplexValue("mailnews.search_date_separator",
                                        Ci.nsIPrefLocalizedString).data;
 
       gSearchDateLeadingZeros =
         (Services.prefs.getComplexValue(
            "mailnews.search_date_leading_zeros",
            Ci.nsIPrefLocalizedString).data == "true");
     }
-  }
-  catch (e)
-  {
+  } catch (e) {
     Cu.reportError("initializeSearchDateFormat: caught an exception: " + e);
     gSearchDateFormat = 0;
   }
 
-  if (gSearchDateFormat == 0)
-  {
+  if (gSearchDateFormat == 0) {
     // Set to mm/dd/yyyy in case we couldn't determine in any way.
     gSearchDateFormat = 3;
     gSearchDateSeparator = "/";
     gSearchDateLeadingZeros = true;
   }
 }
 
-function convertPRTimeToString(tm)
-{
+function convertPRTimeToString(tm) {
   var time = new Date();
   // PRTime is in microseconds, JavaScript time is in milliseconds
   // so divide by 1000 when converting
   time.setTime(tm / 1000);
 
   return convertDateToString(time);
 }
 
-function convertDateToString(time)
-{
+function convertDateToString(time) {
   initializeSearchDateFormat();
 
   var year = time.getFullYear();
   var month = time.getMonth() + 1;  // since js month is 0-11
   if (gSearchDateLeadingZeros && month < 10)
     month = "0" + month;
   var date = time.getDate();  // day
   if (gSearchDateLeadingZeros && date < 10)
     date = "0" + date;
 
   var dateStr;
   var sep = gSearchDateSeparator;
 
-  switch (gSearchDateFormat)
-  {
+  switch (gSearchDateFormat) {
     case 1:
       dateStr = year + sep + month + sep + date;
       break;
     case 2:
       dateStr = year + sep + date + sep + month;
       break;
     case 3:
      dateStr = month + sep + date + sep + year;
@@ -168,26 +147,24 @@ function convertDateToString(time)
       break;
     default:
       dump("valid search date format option is 1-6\n");
   }
 
   return dateStr;
 }
 
-function convertStringToPRTime(str)
-{
+function convertStringToPRTime(str) {
   initializeSearchDateFormat();
 
   var arrayOfStrings = str.split(gSearchDateSeparator);
   var year, month, date;
 
   // set year, month, date based on the format option
-  switch (gSearchDateFormat)
-  {
+  switch (gSearchDateFormat) {
     case 1:
       year = arrayOfStrings[0];
       month = arrayOfStrings[1];
       date = arrayOfStrings[2];
       break;
     case 2:
       year = arrayOfStrings[0];
       month = arrayOfStrings[2];
--- a/mailnews/base/content/folderProps.js
+++ b/mailnews/base/content/folderProps.js
@@ -1,193 +1,174 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from retention.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {Gloda} = ChromeUtils.import("resource:///modules/gloda/gloda.js");
 
 var gMsgFolder;
 var gLockedPref = null;
 
 document.addEventListener("dialogaccept", folderPropsOKButton);
 
 // The folderPropsSink is the class that gets notified of an imap folder's properties
 
 var gFolderPropsSink = {
-    setFolderType: function(folderTypeString)
-    {
+    setFolderType(folderTypeString) {
       var typeLabel = document.getElementById("folderType.text");
-      if (typeLabel)
-      {
-        typeLabel.setAttribute("value",folderTypeString);
+      if (typeLabel) {
+        typeLabel.setAttribute("value", folderTypeString);
       }
       // get the element for the folder type label and set value on it.
     },
 
-    setFolderTypeDescription: function(folderDescription)
-    {
+    setFolderTypeDescription(folderDescription) {
       var folderTypeLabel = document.getElementById("folderDescription.text");
       if (folderTypeLabel)
         folderTypeLabel.setAttribute("value", folderDescription);
     },
 
-    setFolderPermissions: function(folderPermissions)
-    {
+    setFolderPermissions(folderPermissions) {
       var permissionsLabel = document.getElementById("folderPermissions.text");
       var descTextNode =  document.createTextNode(folderPermissions);
       permissionsLabel.appendChild(descTextNode);
     },
 
-    serverDoesntSupportACL : function()
-    {
+    serverDoesntSupportACL() {
       var typeLabel = document.getElementById("folderTypeLabel");
       if (typeLabel)
         typeLabel.setAttribute("hidden", "true");
       var permissionsLabel = document.getElementById("permissionsDescLabel");
       if (permissionsLabel)
         permissionsLabel.setAttribute("hidden", "true");
-
     },
 
-    setQuotaStatus : function(folderQuotaStatus)
-    {
+    setQuotaStatus(folderQuotaStatus) {
       var quotaStatusLabel = document.getElementById("folderQuotaStatus");
-      if(quotaStatusLabel)
+      if (quotaStatusLabel)
         quotaStatusLabel.setAttribute("value", folderQuotaStatus);
     },
 
-    showQuotaData : function(showData)
-    {
+    showQuotaData(showData) {
       var quotaStatusLabel = document.getElementById("folderQuotaStatus");
       var folderQuotaData = document.getElementById("folderQuotaData");
 
-      if(quotaStatusLabel && folderQuotaData)
-      {
+      if (quotaStatusLabel && folderQuotaData) {
         quotaStatusLabel.hidden = showData;
-        folderQuotaData.hidden = ! showData;
+        folderQuotaData.hidden = !showData;
       }
     },
 
-    setQuotaData : function(root, usedKB, maxKB)
-    {
+    setQuotaData(root, usedKB, maxKB) {
       var quotaRoot = document.getElementById("quotaRoot");
       if (quotaRoot)
         quotaRoot.setAttribute("value", '"' + root + '"');
 
       var percentage = (maxKB != 0) ? Math.round(usedKB / maxKB * 100) : 0;
 
       var quotaPercentageBar = document.getElementById("quotaPercentageBar");
       if (quotaPercentageBar)
         quotaPercentageBar.setAttribute("value", percentage);
 
       var bundle = document.getElementById("bundle_messenger");
-      if(bundle)
-      {
+      if (bundle) {
         var usedFreeCaption = bundle.getFormattedString("quotaUsedFree", [usedKB, maxKB], 2);
         var quotaCaption = document.getElementById("quotaUsedFree");
-        if(quotaCaption)
+        if (quotaCaption)
           quotaCaption.setAttribute("value", usedFreeCaption);
 
         var percentUsedCaption = bundle.getFormattedString("quotaPercentUsed", [percentage], 1);
         var percentUsed = document.getElementById("quotaPercentUsed");
-        if(percentUsed)
+        if (percentUsed)
           percentUsed.setAttribute("value", percentUsedCaption);
       }
-    }
+    },
 
 };
 
-function doEnabling()
-{
+function doEnabling() {
   var nameTextbox = document.getElementById("name");
   document.documentElement.getButton("accept").disabled = !nameTextbox.value;
 }
 
-function folderPropsOKButton(event)
-{
-  if (gMsgFolder)
-  {
+function folderPropsOKButton(event) {
+  if (gMsgFolder) {
     // set charset attributes
     var folderCharsetList = document.getElementById("folderCharsetList");
 
     // Log to the Error Console the charset value for the folder
     // if it is unknown to us. Value will be preserved by the menu-item.
-    if (folderCharsetList.selectedIndex == -1)
-    {
+    if (folderCharsetList.selectedIndex == -1) {
       Cu.reportError("Unknown folder encoding; folder=" +
         gMsgFolder.name + ", charset=" + gMsgFolder.charset);
     }
 
     gMsgFolder.charset = folderCharsetList.getAttribute("value");
     gMsgFolder.charsetOverride = document.getElementById("folderCharsetOverride")
                                          .checked;
 
-    if(document.getElementById("offline.selectForOfflineFolder").checked ||
+    if (document.getElementById("offline.selectForOfflineFolder").checked ||
       document.getElementById("offline.selectForOfflineNewsgroup").checked)
       gMsgFolder.setFlag(Ci.nsMsgFolderFlags.Offline);
     else
       gMsgFolder.clearFlag(Ci.nsMsgFolderFlags.Offline);
 
-    if(document.getElementById("folderCheckForNewMessages").checked)
+    if (document.getElementById("folderCheckForNewMessages").checked)
       gMsgFolder.setFlag(Ci.nsMsgFolderFlags.CheckNew);
     else
       gMsgFolder.clearFlag(Ci.nsMsgFolderFlags.CheckNew);
 
     let glodaCheckbox = document.getElementById("folderIncludeInGlobalSearch");
     if (!glodaCheckbox.hidden) {
-      if(glodaCheckbox.checked) {
+      if (glodaCheckbox.checked) {
         // We pass true here so that folders such as trash and junk can still
         // have a priority set.
         Gloda.resetFolderIndexingPriority(gMsgFolder, true);
       } else {
         Gloda.setFolderIndexingPriority(gMsgFolder,
           Gloda.getFolderForFolder(gMsgFolder).kIndexingNeverPriority);
       }
     }
 
     var retentionSettings = saveCommonRetentionSettings(gMsgFolder.retentionSettings);
     retentionSettings.useServerDefaults = document.getElementById("retention.useDefault").checked;
     gMsgFolder.retentionSettings = retentionSettings;
-
   }
 
-  try
-  {
+  try {
     // This throws an exception when an illegal folder name was entered.
-    okCallback(document.getElementById("name").value, window.arguments[0].name,
-               gMsgFolder.URI);
-  }
-  catch (e)
-  {
+    top.okCallback(document.getElementById("name").value, window.arguments[0].name,
+                   gMsgFolder.URI);
+  } catch (e) {
     event.preventDefault();
   }
 }
 
-function folderPropsOnLoad()
-{
+function folderPropsOnLoad() {
   // look in arguments[0] for parameters
   if (window.arguments && window.arguments[0]) {
-    if ( window.arguments[0].title ) {
+    if (window.arguments[0].title) {
       document.title = window.arguments[0].title;
     }
-    if ( window.arguments[0].okCallback ) {
+    if (window.arguments[0].okCallback) {
       top.okCallback = window.arguments[0].okCallback;
     }
   }
 
   // fill in folder name, based on what they selected in the folder pane
   if (window.arguments[0].folder) {
     gMsgFolder = window.arguments[0].folder;
   } else {
     dump("passed null for folder, do nothing\n");
   }
 
-  if(window.arguments[0].name)
-  {
+  if (window.arguments[0].name) {
     // Initialize name textbox with the given name and remember this
     // value so we can tell whether the folder needs to be renamed
     // when the dialog is accepted.
     var nameTextbox = document.getElementById("name");
     nameTextbox.value = window.arguments[0].name;
 
 //  name.setSelectionRange(0,-1);
 //  name.focusTextField();
@@ -198,45 +179,42 @@ function folderPropsOnLoad()
   // Do this first, because of gloda we may want to override some of the hidden
   // statuses.
   hideShowControls(serverType);
 
   if (gMsgFolder) {
     // We really need a functioning database, so we'll detect problems
     // and create one if we have to.
     try {
-      var db = gMsgFolder.getDatabase(null);
-    }
-    catch (e) {
+      gMsgFolder.getDatabase(null);
+    } catch (e) {
       gMsgFolder.updateFolder(window.arguments[0].msgWindow);
     }
 
     var locationTextbox = document.getElementById("location");
 
     // Decode the displayed mailbox:// URL as it's useful primarily for debugging,
     // whereas imap and news urls are sent around.
     locationTextbox.value = (serverType == "imap" || serverType == "nntp") ?
         gMsgFolder.folderURL : decodeURI(gMsgFolder.folderURL);
 
     if (gMsgFolder.canRename)
       document.getElementById("name").removeAttribute("readonly");
 
     if (gMsgFolder.getFlag(Ci.nsMsgFolderFlags.Offline)) {
-
-      if(serverType == "imap" || serverType == "pop3")
+      if (serverType == "imap" || serverType == "pop3")
         document.getElementById("offline.selectForOfflineFolder").checked = true;
 
-      if(serverType == "nntp")
+      if (serverType == "nntp")
         document.getElementById("offline.selectForOfflineNewsgroup").checked = true;
-    }
-    else {
-      if(serverType == "imap" || serverType == "pop3")
+    } else {
+      if (serverType == "imap" || serverType == "pop3")
         document.getElementById("offline.selectForOfflineFolder").checked = false;
 
-      if(serverType == "nntp")
+      if (serverType == "nntp")
         document.getElementById("offline.selectForOfflineNewsgroup").checked = false;
     }
 
     // select the menu item
     var folderCharsetList = document.getElementById("folderCharsetList");
     folderCharsetList.value = gMsgFolder.charset;
 
     // set override checkbox
@@ -256,18 +234,17 @@ function folderPropsOnLoad()
     } else {
       // otherwise, the user can choose whether this file gets indexed
       let glodaFolder = Gloda.getFolderForFolder(gMsgFolder);
       glodaCheckbox.checked =
         glodaFolder.indexingPriority != glodaFolder.kIndexingNeverPriority;
     }
   }
 
-  if (serverType == "imap")
-  {
+  if (serverType == "imap") {
     var imapFolder = gMsgFolder.QueryInterface(Ci.nsIMsgImapMailFolder);
     if (imapFolder)
       imapFolder.fillInFolderProps(gFolderPropsSink);
   }
 
   var retentionSettings = gMsgFolder.retentionSettings;
   initCommonRetentionSettings(retentionSettings);
   document.getElementById("retention.useDefault").checked = retentionSettings.useServerDefaults;
@@ -284,32 +261,30 @@ function folderPropsOnLoad()
     document.getElementById("sizeOnDisk").value = sizeOnDisk;
   } catch (e) { }
 
   // select the initial tab
   if (window.arguments[0].tabID) {
     try {
       document.getElementById("folderPropTabBox").selectedTab =
         document.getElementById(window.arguments[0].tabID);
-    }
-    catch (ex) {}
+    } catch (ex) {}
   }
   onCheckKeepMsg();
   onUseDefaultRetentionSettings();
 }
 
-function hideShowControls(serverType)
-{
+function hideShowControls(serverType) {
   let controls = document.querySelectorAll("[hidefor]");
   var len = controls.length;
-  for (var i=0; i<len; i++) {
+  for (var i = 0; i < len; i++) {
     var control = controls[i];
     var hideFor = control.getAttribute("hidefor");
     if (!hideFor)
-      throw "hidefor empty";
+      throw new Error("hidefor empty");
 
     // hide unsupported server type
     // adding support for hiding multiple server types using hideFor="server1,server2"
     var hideForBool = false;
     var hideForTokens = hideFor.split(",");
     for (var j = 0; j < hideForTokens.length; j++) {
       if (hideForTokens[j] == serverType) {
         hideForBool = true;
@@ -318,68 +293,60 @@ function hideShowControls(serverType)
     }
     control.hidden = hideForBool;
   }
 
   // hide the privileges button if the imap folder doesn't have an admin url
   // mabye should leave this hidden by default and only show it in this case instead
   try {
     var imapFolder = gMsgFolder.QueryInterface(Ci.nsIMsgImapMailFolder);
-    if (imapFolder)
-    {
+    if (imapFolder) {
       var privilegesButton = document.getElementById("imap.FolderPrivileges");
-      if (privilegesButton)
-      {
+      if (privilegesButton) {
         if (!imapFolder.hasAdminUrl)
           privilegesButton.setAttribute("hidden", "true");
       }
     }
-  }
-  catch (ex) {}
+  } catch (ex) {}
 
-  if (gMsgFolder)
-  {
+  if (gMsgFolder) {
     // Hide "check for new mail" checkbox if this is an Inbox.
     if (gMsgFolder.getFlag(Ci.nsMsgFolderFlags.Inbox))
       document.getElementById("folderCheckForNewMessages").hidden = true;
     // Retention policy doesn't apply to Drafts/Templates/Outbox.
     if (gMsgFolder.isSpecialFolder(Ci.nsMsgFolderFlags.Drafts |
                                    Ci.nsMsgFolderFlags.Templates |
                                    Ci.nsMsgFolderFlags.Queue, true))
       document.getElementById("Retention").hidden = true;
   }
 }
 
-function onOfflineFolderDownload()
-{
+function onOfflineFolderDownload() {
   // we need to create a progress window and pass that in as the second parameter here.
   gMsgFolder.downloadAllForOffline(null, window.arguments[0].msgWindow);
 }
 
-function onFolderPrivileges()
-{
+function onFolderPrivileges() {
   var imapFolder = gMsgFolder.QueryInterface(Ci.nsIMsgImapMailFolder);
   if (imapFolder)
     imapFolder.folderPrivileges(window.arguments[0].msgWindow);
   // let's try closing the modal dialog to see if it fixes the various problems running this url
   window.close();
 }
 
 
-function onUseDefaultRetentionSettings()
-{
+function onUseDefaultRetentionSettings() {
   var useDefault = document.getElementById("retention.useDefault").checked;
-  document.getElementById('retention.keepMsg').disabled = useDefault;
-  document.getElementById('retention.keepNewMsgMinLabel').disabled = useDefault;
-  document.getElementById('retention.keepOldMsgMinLabel').disabled = useDefault;
+  document.getElementById("retention.keepMsg").disabled = useDefault;
+  document.getElementById("retention.keepNewMsgMinLabel").disabled = useDefault;
+  document.getElementById("retention.keepOldMsgMinLabel").disabled = useDefault;
 
   var keepMsg = document.getElementById("retention.keepMsg").value;
   const nsIMsgRetentionSettings = Ci.nsIMsgRetentionSettings;
-  document.getElementById('retention.keepOldMsgMin').disabled =
+  document.getElementById("retention.keepOldMsgMin").disabled =
     useDefault || (keepMsg != nsIMsgRetentionSettings.nsMsgRetainByAge);
-  document.getElementById('retention.keepNewMsgMin').disabled =
+  document.getElementById("retention.keepNewMsgMin").disabled =
     useDefault || (keepMsg != nsIMsgRetentionSettings.nsMsgRetainByNumHeaders);
 }
 
-function RebuildSummaryInformation()
-{
+function RebuildSummaryInformation() {
   window.arguments[0].rebuildSummaryCallback(gMsgFolder);
 }
--- a/mailnews/base/content/folderWidgets.xml
+++ b/mailnews/base/content/folderWidgets.xml
@@ -102,89 +102,89 @@
          - one of them, append the mode="foo" attribute to the element.  When
          - building the menu, we will then use this._filters[mode] as a filter
          - function to eliminate folders that should not be shown.
          -
          - Note that extensions should feel free to plug in here!
         -->
       <field name="_filters"><![CDATA[({
         // Returns true if messages can be filed in the folder
-        filing: function filter_filing(aFolder) {
+        filing(aFolder) {
           if (!aFolder.server.canFileMessagesOnServer)
             return false;
 
           return (aFolder.canFileMessages || aFolder.hasSubFolders);
         },
 
         // Returns true if we can get mail for this folder. (usually this just
         // means the "root" fake folder)
-        getMail: function filter_getMail(aFolder) {
+        getMail(aFolder) {
           if (aFolder.isServer && aFolder.server.type != "none")
             return true;
           if (aFolder.server.type == "nntp" || aFolder.server.type == "rss")
             return true;
           return false;
         },
 
         // Returns true if we can add filters to this folder/account
-        filters: function filter_filter(aFolder) {
+        filters(aFolder) {
           // We can always filter news
           if (aFolder.server.type == "nntp")
             return true;
 
           return aFolder.server.canHaveFilters;
         },
 
-        subscribe: function filter_subscribe(aFolder) {
+        subscribe(aFolder) {
           return aFolder.canSubscribe;
         },
 
-        newFolder: function filter_newFolder(aFolder) {
+        newFolder(aFolder) {
           return aFolder.canCreateSubfolders &&
                  aFolder.server.canCreateFoldersOnServer;
         },
 
-        deferred: function filter_defered(aFolder) {
+        deferred(aFolder) {
           return aFolder.server.canCreateFoldersOnServer &&
                  !aFolder.supportsOffline;
         },
 
         // Folders that are not in a deferred account
-        notDeferred: function(aFolder) {
+        notDeferred(aFolder) {
           let server = aFolder.server;
           return !(server instanceof Ci.nsIPop3IncomingServer &&
                    server.deferredToAccount);
         },
 
         // Folders that can be searched.
-        search: function filter_search(aFolder) {
+        search(aFolder) {
           if (!aFolder.server.canSearchMessages ||
               aFolder.getFlag(Ci.nsMsgFolderFlags.Virtual))
             return false;
           return true;
         },
 
         // Folders that can subscribe feeds.
-        feeds: function filter_feeds(aFolder) {
+        feeds(aFolder) {
           if (aFolder.server.type != "rss" ||
               aFolder.getFlag(Ci.nsMsgFolderFlags.Trash) ||
               aFolder.getFlag(Ci.nsMsgFolderFlags.Virtual))
             return false;
           return true;
         },
 
-        junk: function filter_junk(aFolder) {
+        junk(aFolder) {
           // Don't show servers (nntp & any others) which do not allow search or filing
           // I don't really understand why canSearchMessages is needed, but it was included in
           // earlier code, so I include it as well.
           if (!aFolder.server.canFileMessagesOnServer || !aFolder.server.canSearchMessages)
             return false;
           // show parents that might have usable subfolders, or usable folders
           return aFolder.hasSubFolders || aFolder.canFileMessages;
-        }
+        },
       })]]></field>
 
       <!--
          - The maximum number of entries in the "Recent" menu
         -->
       <field name="_MAXRECENT">15</field>
 
       <!--
@@ -195,117 +195,116 @@
       <!--
          - Our listener to let us know when folders change/appear/disappear so
          - we can know to rebuild ourselves.
         -->
       <field name="_listener">
           <![CDATA[({
         _menu: this,
         _clearMenu(menu) {
-          //xxx I'm not quite sure why this isn't always a function (bug 514445)
+          // xxx I'm not quite sure why this isn't always a function (bug 514445)
           if (menu._teardown)
             menu._teardown();
         },
-        OnItemAdded: function act_add(aRDFParentItem, aItem) {
+        OnItemAdded(aRDFParentItem, aItem) {
           if (!(aItem instanceof Ci.nsIMsgFolder))
             return;
           if (this._filterFunction && !this._filterFunction(aItem)) {
             return;
           }
-          //xxx we can optimize this later
+          // xxx we can optimize this later
           this._clearMenu(this._menu);
         },
 
-        OnItemRemoved: function act_remove(aRDFParentItem, aItem) {
+        OnItemRemoved(aRDFParentItem, aItem) {
           if (!(aItem instanceof Ci.nsIMsgFolder))
             return;
           if (this._filterFunction && !this._filterFunction(aItem)) {
             return;
           }
-          //xxx we can optimize this later
+          // xxx we can optimize this later
           this._clearMenu(this._menu);
         },
 
-        //xxx I stole this listener list from nsMsgFolderDatasource.cpp, but
-        //    someone should really document what events are fired when, so that
-        //    we make sure we're updating at the right times.
-        OnItemPropertyChanged: function(aItem, aProperty, aOld, aNew) {},
-        OnItemIntPropertyChanged: function(aItem, aProperty, aOld, aNew) {
+        // xxx I stole this listener list from nsMsgFolderDatasource.cpp, but
+        //     someone should really document what events are fired when, so that
+        //     we make sure we're updating at the right times.
+        OnItemPropertyChanged(aItem, aProperty, aOld, aNew) {},
+        OnItemIntPropertyChanged(aItem, aProperty, aOld, aNew) {
           if (aItem instanceof Ci.nsIMsgFolder) {
             if (aProperty == "FolderFlag") {
               if (this._menu.getAttribute("showFavorites") != "true" ||
                   !this._menu._initializedSpecials.has("favorites"))
                 return;
 
               if ((aOld & Ci.nsMsgFolderFlags.Favorite) !=
                  (aNew & Ci.nsMsgFolderFlags.Favorite))
                setTimeout(this._clearMenu, 0, this._menu);
             }
           }
           var child = this._getChildForItem(aItem);
           if (child)
             this._menu._setCssSelectors(child._folder, child);
         },
-        OnItemBoolPropertyChanged: function(aItem, aProperty, aOld, aNew) {
+        OnItemBoolPropertyChanged(aItem, aProperty, aOld, aNew) {
           var child = this._getChildForItem(aItem);
           if (child)
             this._menu._setCssSelectors(child._folder, child);
         },
-        OnItemUnicharPropertyChanged: function(aItem, aProperty, aOld, aNew) {
+        OnItemUnicharPropertyChanged(aItem, aProperty, aOld, aNew) {
           var child = this._getChildForItem(aItem);
           if (child)
             this._menu._setCssSelectors(child._folder, child);
         },
-        OnItemPropertyFlagChanged: function(aItem, aProperty, aOld, aNew) {},
-        OnItemEvent: function(aFolder, aEvent) {
+        OnItemPropertyFlagChanged(aItem, aProperty, aOld, aNew) {},
+        OnItemEvent(aFolder, aEvent) {
           if (aEvent == "MRMTimeChanged") {
             if (this._menu.getAttribute("showRecent") != "true" ||
                 !this._menu._initializedSpecials.has("recent") ||
                 !this._menu.firstChild || !this._menu.firstChild.firstChild)
               return;
             // if this folder is already in the recent menu, return.
             if (this._getChildForItem(aFolder,
                                       this._menu.firstChild.firstChild))
               return;
-          }
-          // Special casing folder renames here, since they require more work
-          // since sort-order may have changed.
-          else if (aEvent == "RenameCompleted") {
+          } else if (aEvent == "RenameCompleted") {
+            // Special casing folder renames here, since they require more work
+            // since sort-order may have changed.
             if (!this._getChildForItem(aFolder))
               return;
+          } else {
+            return;
           }
-          else
-            return;
           // folder renamed, or new recent folder, so rebuild.
           setTimeout(this._clearMenu, 0, this._menu);
         },
 
         /**
          * Helper function to check and see whether we have a menuitem for this
          * particular nsIMsgFolder
          *
          * @param aItem  the nsIMsgFolder to check
          * @param aMenu  (optional) menu to look in, defaults to this._menu.
          * @returns      null if no child for that folder exists, otherwise the
          *               menuitem for that child
          */
-        _getChildForItem: function act__itemIsChild(aItem, aMenu) {
+        _getChildForItem(aItem, aMenu) {
           aMenu = aMenu || this._menu;
           if (!aMenu || !aMenu.hasChildNodes())
             return null;
 
            if (!(aItem instanceof Ci.nsIMsgFolder))
              return null;
            for (let i = 0; i < aMenu.childNodes.length; i++) {
              let folder = aMenu.childNodes[i]._folder;
              if (folder && folder.URI == aItem.URI)
                return aMenu.childNodes[i];
            }
            return null;
-        }
+        },
       })]]></field>
 
        <!--
          - True if we have already built our menu-items and are now just
          - listening for changes.
          -->
       <field name="_initialized">false</field>
 
@@ -382,17 +381,18 @@
             this._listener._filterFunction = filterFunction;
           } else {
             folders = aFolders;
             this._listener._filterFunction = function(folder) { return true; };
           }
 
           if (excludeServers.length > 0) {
             folders = folders.filter(function(aFolder) {
-              return !(excludeServers.indexOf(aFolder.server.key) != -1); });
+              return !excludeServers.includes(aFolder.server.key);
+            });
           }
 
           /* This code block will do the following: Add a menu item that refers
              back to the parent folder when there is a showFileHereLabel
              attribute or no mode attribute. However the code won't add such a
              menu item if one of the following conditions is met:
              (*) There is no parent folder
              (*) Folder is server and showAccountsFileHere is explicitly false
@@ -424,17 +424,17 @@
               }
               // Eww. have to support some legacy code here...
               menuitem.setAttribute("id", this._parentFolder.URI);
               this.appendChild(menuitem);
 
               if (this._parentFolder.noSelect)
                 menuitem.setAttribute("disabled", "true");
 
-              var sep= document.createElement("menuseparator");
+              let sep = document.createElement("menuseparator");
               sep.setAttribute("generated", "true");
               this.appendChild(sep);
             }
           }
 
           let globalInboxFolder = null;
           // See if this is the toplevel menu (usually with accounts).
           if (!this._parentFolder) {
@@ -468,32 +468,30 @@
             // If we're the root of the folder hierarchy, then we actually don't
             // want to sort the folders, but rather the accounts to which the
             // folders belong.  Since that sorting was already done, we don't need
             // to do anything for that case here.
           } else {
             // Sorts the list of folders. We give first priority to the sortKey
             // property if it is available, otherwise a case-insensitive
             // comparison of names.
-            folders = folders.sort(function nameCompare(a, b) {
-              return a.compareSortKeys(b);
-            });
+            folders = folders.sort((a, b) => a.compareSortKeys(b));
           }
 
           /* In some cases, the user wants to have a list of subfolders for only
            * some account types (or maybe all of them). So we use this to
            * determine what the user wanted.
            */
            var shouldExpand;
            var labels = null;
            if (this.getAttribute("expandFolders") == "true" ||
                !this.hasAttribute("expandFolders")) {
-             shouldExpand = function (e) { return true; };
+             shouldExpand = () => true;
            } else if (this.getAttribute("expandFolders") == "false") {
-             shouldExpand = function (e) { return false; };
+             shouldExpand = () => false;
            } else {
              /* We want a subfolder list for only some servers. We also may need
               * to create headers to select the servers. If so, then headlabels
               * is a comma-delimited list of labels corresponding to the server
               * types specified in expandFolders.
               */
              var types = this.getAttribute("expandFolders").split(/ *, */);
              // Set the labels. labels[type] = label
@@ -502,17 +500,17 @@
                labels = {};
                // If the length isn't equal, don't give them any of the labels,
                // since any combination will probably be wrong.
                if (labelNames.length == types.length) {
                  for (var index in types)
                    labels[types[index]] = labelNames[index];
                }
              }
-             shouldExpand = function (e) { return types.indexOf(e) != -1; };
+             shouldExpand = (e) => types.includes(e);
            }
 
           // We need to call this, or hasSubFolders will always return false.
           // Remove this workaround when Bug 502900 is fixed.
           this.MailUtils.discoverFolders();
           this._serversOnly = true;
 
           for (let folder of folders) {
@@ -526,18 +524,18 @@
               node = document.createElement("menuitem");
               // Grumble, grumble, legacy code support
               node.setAttribute("id", folder.URI);
               node.setAttribute("class", "folderMenuItem menuitem-iconic");
               node.setAttribute("generated", "true");
               this.appendChild(node);
             } else {
               this._serversOnly = false;
-              //xxx this is slightly problematic in that we haven't confirmed
-              //    whether any of the subfolders will pass the filter
+              // xxx this is slightly problematic in that we haven't confirmed
+              //     whether any of the subfolders will pass the filter
               node = document.createElement("menu");
               node.setAttribute("class", "folderMenuItem menu-iconic");
               node.setAttribute("generated", "true");
               this.appendChild(node);
 
               // Create the submenu
               // (We must use cloneNode here because on OS X the native menu
               // functionality and very sad limitations of XBL1 cause the bindings
@@ -565,26 +563,26 @@
 
               // If there are labels, add the labels now
               if (labels) {
                 var serverNode = document.createElement("menuitem");
                 serverNode.setAttribute("label", labels[folder.server.type]);
                 serverNode._folder = folder;
                 serverNode.setAttribute("generated", "true");
                 popup.appendChild(serverNode);
-                var sep = document.createElement("menuseparator");
+                let sep = document.createElement("menuseparator");
                 sep.setAttribute("generated", "true");
                 popup.appendChild(sep);
               }
 
               popup.setAttribute("generated", "true");
               node.appendChild(popup);
             }
 
-            if (disableServers.indexOf(folder.server.key) != -1)
+            if (disableServers.includes(folder.server.key))
               node.setAttribute("disabled", "true");
 
             node._folder = folder;
             let label = "";
             if (mode == "deferred" && folder.isServer &&
                 folder.server.rootFolder == globalInboxFolder) {
               label = this._stringBundle.get("globalInbox", [folder.prettyName]);
             } else {
@@ -653,18 +651,22 @@
               break;
             case "favorites":
               specialFolders = specialFolders.filter(folder => folder.getFlag(Ci.nsMsgFolderFlags.Favorite));
               break;
           }
 
           // Cache the pretty names so that they do not need to be fetched
           // _MAXRECENT^2 times later.
-          let specialFoldersMap = specialFolders.map(
-            function (f) { return { folder: f, name: f.prettyName } });
+          let specialFoldersMap = specialFolders.map(function(f) {
+            return {
+              folder: f,
+              name: f.prettyName,
+            };
+          });
 
           // Because we're scanning across multiple accounts, we can end up with
           // several folders with the same name. Find those dupes.
           let dupeNames = new Set();
           for (let i = 0; i < specialFoldersMap.length; i++) {
             for (let j = i + 1; j < specialFoldersMap.length; j++) {
               if (specialFoldersMap[i].name == specialFoldersMap[j].name)
                 dupeNames.add(specialFoldersMap[i].name);
@@ -732,18 +734,17 @@
               aMenuNode.setAttribute("BiffState", state);
               break;
             }
           }
 
           aMenuNode.setAttribute("IsServer", aFolder.isServer);
           aMenuNode.setAttribute("IsSecure", aFolder.server.isSecure);
           aMenuNode.setAttribute("ServerType", aFolder.server.type);
-          aMenuNode.setAttribute("IsFeedFolder",
-            (this.FeedUtils.getFeedUrlsInFolder(aFolder) ? true : false));
+          aMenuNode.setAttribute("IsFeedFolder", !!this.FeedUtils.getFeedUrlsInFolder(aFolder));
         ]]></body>
       </method>
 
       <!--
          - This function returns a formatted display name for a menulist
          - selected folder.  The desired format is set as the 'displayformat'
          - attribute of the folderpicker's <menulist>, one of:
          - 'name' (default) - Folder
@@ -782,20 +783,22 @@
       <method name="selectFolder">
         <parameter name="aFolder"/>
         <body><![CDATA[
           // Set the label of the menulist element as if aFolder had been selected.
           function setupParent(aFolder, aMenulist, aNoFolders) {
             let menupopup = aMenulist.menupopup;
             if (aFolder) {
               aMenulist.setAttribute("label", menupopup.getDisplayName(aFolder));
+            } else if (aNoFolders) {
+              aMenulist.setAttribute("label", menupopup._stringBundle.getString("noFolders"));
+            } else if (menupopup._serversOnly) {
+              aMenulist.setAttribute("label", menupopup._stringBundle.getString("chooseAccount"));
             } else {
-              aMenulist.setAttribute("label", menupopup._stringBundle.getString(
-                aNoFolders ? "noFolders" :
-                             (menupopup._serversOnly ? "chooseAccount" : "chooseFolder")));
+              aMenulist.setAttribute("label", menupopup._stringBundle.getString("chooseFolder"));
             }
             aMenulist.setAttribute("value",
               aFolder ? aFolder.URI : "");
             aMenulist.setAttribute("IsServer",
               aFolder ? aFolder.isServer : false);
             aMenulist.setAttribute("IsSecure",
               aFolder ? aFolder.server.isSecure : false);
             aMenulist.setAttribute("ServerType",
@@ -824,29 +827,26 @@
           // If the caller specified a folder to select and it was not
           // found, or if the caller didn't pass a folder (meaning a logical
           // and valid folder wasn't determined), don't blow up but reset
           // attributes and set a nice Choose Folder label so the user may
           // select a valid folder per the filter for this picker. If there are
           // no children, then no folder passed the filter; disable the menulist
           // as there's nothing to choose from.
           let noFolders;
-          if (!this.childElementCount)
-          {
+          if (!this.childElementCount) {
             this.parentNode.setAttribute("disabled", true);
             noFolders = true;
-          }
-          else
-          {
+          } else {
             this.parentNode.removeAttribute("disabled");
             noFolders = false;
           }
 
           setupParent(folder, this.parentNode, noFolders);
-          return folder ? true : false;
+          return !!folder;
         ]]></body>
       </method>
 
       <!--
          - Removes all menu-items for this popup, resets all fields, and
          - removes the listener.  This function is invoked when a change
          - that affects this menu is detected by our listener.
         -->
--- a/mailnews/base/content/jsTreeView.js
+++ b/mailnews/base/content/jsTreeView.js
@@ -28,103 +28,103 @@ PROTO_TREE_VIEW.prototype = {
   get rowCount() {
     return this._rowMap.length;
   },
 
   /**
    * CSS files will cue off of these.  Note that we reach into the rowMap's
    * items so that custom data-displays can define their own properties
    */
-  getCellProperties: function jstv_getCellProperties(aRow, aCol) {
+  getCellProperties(aRow, aCol) {
     return this._rowMap[aRow].getProperties(aCol);
   },
 
   /**
    * The actual text to display in the tree
    */
-  getCellText: function jstv_getCellText(aRow, aCol) {
+  getCellText(aRow, aCol) {
     return this._rowMap[aRow].getText(aCol.id);
   },
 
   /**
    * The jstv items take care of assigning this when building children lists
    */
-  getLevel: function jstv_getLevel(aIndex) {
+  getLevel(aIndex) {
     return this._rowMap[aIndex].level;
   },
 
   /**
    * This is easy since the jstv items assigned the _parent property when making
    * the child lists
    */
-  getParentIndex: function jstv_getParentIndex(aIndex) {
+  getParentIndex(aIndex) {
     return this._rowMap.indexOf(this._rowMap[aIndex]._parent);
   },
 
   /**
    * This is duplicative for our normal jstv views, but custom data-displays may
    * want to do something special here
    */
-  getRowProperties: function jstv_getRowProperties(aRow) {
+  getRowProperties(aRow) {
     return this._rowMap[aRow].getProperties();
   },
 
   /**
    * If an item in our list has the same level and parent as us, it's a sibling
    */
-  hasNextSibling: function jstv_hasNextSibling(aIndex, aNextIndex) {
+  hasNextSibling(aIndex, aNextIndex) {
     let targetLevel = this._rowMap[aIndex].level;
     for (let i = aNextIndex + 1; i < this._rowMap.length; i++) {
       if (this._rowMap[i].level == targetLevel)
         return true;
       if (this._rowMap[i].level < targetLevel)
         return false;
     }
     return false;
   },
 
   /**
    * If we have a child-list with at least one element, we are a container.
    */
-  isContainer: function jstv_isContainer(aIndex) {
+  isContainer(aIndex) {
     return this._rowMap[aIndex].children.length > 0;
   },
 
-  isContainerEmpty: function jstv_isContainerEmpty(aIndex) {
+  isContainerEmpty(aIndex) {
     // If the container has no children, the container is empty.
     return !this._rowMap[aIndex].children.length;
   },
 
   /**
    * Just look at the jstv item here
    */
-  isContainerOpen: function jstv_isContainerOpen(aIndex) {
+  isContainerOpen(aIndex) {
     return this._rowMap[aIndex].open;
   },
 
-  isEditable: function jstv_isEditable(aRow, aCol) {
+  isEditable(aRow, aCol) {
     // We don't support editing rows in the tree yet.
     return false;
   },
 
-  isSeparator: function jstv_isSeparator(aIndex) {
+  isSeparator(aIndex) {
     // There are no separators in our trees
     return false;
   },
 
-  isSorted: function jstv_isSorted() {
+  isSorted() {
     // We do our own customized sorting
     return false;
   },
 
-  setTree: function jstv_setTree(aTree) {
+  setTree(aTree) {
     this._tree = aTree;
   },
 
-  recursivelyAddToMap: function jstv_recursivelyAddToMap(aChild, aNewIndex) {
+  recursivelyAddToMap(aChild, aNewIndex) {
     // When we add sub-children, we're going to need to increase our index
     // for the next add item at our own level.
     let currentCount = this._rowMap.length;
     if (aChild.children.length && aChild.open) {
       for (let [i, child] of this._rowMap[aNewIndex].children.entries()) {
         let index = aNewIndex + i + 1;
         this._rowMap.splice(index, 0, child);
         aNewIndex += this.recursivelyAddToMap(child, index);
@@ -132,18 +132,17 @@ PROTO_TREE_VIEW.prototype = {
     }
     return this._rowMap.length - currentCount;
   },
 
   /**
    * Opens or closes a container with children.  The logic here is a bit hairy, so
    * be very careful about changing anything.
    */
-  toggleOpenState: function jstv_toggleOpenState(aIndex) {
-
+  toggleOpenState(aIndex) {
     // Ok, this is a bit tricky.
     this._rowMap[aIndex]._open = !this._rowMap[aIndex].open;
 
     if (!this._rowMap[aIndex].open) {
       // We're closing the current container.  Remove the children
 
       // Note that we can't simply splice out children.length, because some of
       // them might have children too.  Find out how many items we're actually
@@ -170,60 +169,60 @@ PROTO_TREE_VIEW.prototype = {
 
       // Note that these children may have been open when we were last closed,
       // and if they are, we also have to add those grandchildren to the map
       let oldCount = this._rowMap.length;
       this.recursivelyAddToMap(this._rowMap[aIndex], aIndex);
 
       // Add this container to the persist map
       let id = this._rowMap[aIndex].id;
-      if (this._persistOpenMap.indexOf(id) == -1)
+      if (!this._persistOpenMap.includes(id))
         this._persistOpenMap.push(id);
 
       // Notify the tree of changes
       if (this._tree)
         this._tree.rowCountChanged(aIndex + 1, this._rowMap.length - oldCount);
     }
 
     // Invalidate the toggled row, so that the open/closed marker changes
     if (this._tree)
       this._tree.invalidateRow(aIndex);
   },
 
   // We don't implement any of these at the moment
-  canDrop: function jstv_canDrop(aIndex, aOrientation) {},
-  drop: function jstv_drop(aRow, aOrientation) {},
-  performAction: function jstv_performAction(aAction) {},
-  performActionOnCell: function jstv_performActionOnCell(aAction, aRow, aCol) {},
-  performActionOnRow: function jstv_performActionOnRow(aAction, aRow) {},
-  selectionChanged: function jstv_selectionChanged() {},
-  setCellText: function jstv_setCellText(aRow, aCol, aValue) {},
-  setCellValue: function jstv_setCellValue(aRow, aCol, aValue) {},
-  getCellValue: function jstv_getCellValue(aRow, aCol) {},
-  getColumnProperties: function jstv_getColumnProperties(aCol) { return ""; },
-  getImageSrc: function jstv_getImageSrc(aRow, aCol) {},
-  getProgressMode: function jstv_getProgressMode(aRow, aCol) {},
-  cycleCell: function jstv_cycleCell(aRow, aCol) {},
-  cycleHeader: function jstv_cycleHeader(aCol) {},
+  canDrop(aIndex, aOrientation) {},
+  drop(aRow, aOrientation) {},
+  performAction(aAction) {},
+  performActionOnCell(aAction, aRow, aCol) {},
+  performActionOnRow(aAction, aRow) {},
+  selectionChanged() {},
+  setCellText(aRow, aCol, aValue) {},
+  setCellValue(aRow, aCol, aValue) {},
+  getCellValue(aRow, aCol) {},
+  getColumnProperties(aCol) { return ""; },
+  getImageSrc(aRow, aCol) {},
+  getProgressMode(aRow, aCol) {},
+  cycleCell(aRow, aCol) {},
+  cycleHeader(aCol) {},
 
   _tree: null,
 
   /**
    * An array of jstv items, where each item corresponds to a row in the tree
    */
   _rowMap: null,
 
   /**
    * This is a javascript map of which containers we had open, so that we can
    * persist their state over-time.  It is designed to be used as a JSON object.
    */
   _persistOpenMap: null,
 
-  _restoreOpenStates: function jstv__restoreOpenStates() {
+  _restoreOpenStates() {
     // Note that as we iterate through here, .length may grow
     for (let i = 0; i < this._rowMap.length; i++) {
-      if (this._persistOpenMap.indexOf(this._rowMap[i].id) != -1)
+      if (this._persistOpenMap.includes(this._rowMap[i].id))
         this.toggleOpenState(i);
     }
   },
 
   QueryInterface: ChromeUtils.generateQI(["nsITreeView"]),
 };
--- a/mailnews/base/content/junkCommands.js
+++ b/mailnews/base/content/junkCommands.js
@@ -11,25 +11,24 @@
   *
   *   window.MsgStatusFeedback
   *
   *   One of:
   *     GetSelectedIndices(view) (in suite)
   *     gFolderDisplay (in mail)
   *
   *   messenger
-  *   gMessengerBundle
   *   gDBView
-  *   either gMsgFolderSelected or gFolderDisplay
   *   MsgJunkMailInfo(aCheckFirstUse)
-  *   SetNextMessageAfterDelete()
-  *   pref
   *   msgWindow
   */
 
+/* globals ClearMessagePane, gDBView, gFolderDisplay, MarkSelectedMessagesRead, messenger,
+   MsgJunkMailInfo, msgWindow, nsMsgViewIndex_None */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 /*
  * determineActionsForJunkMsgs
  *
  * Determines the actions that should be carried out on the messages
@@ -38,43 +37,40 @@ var {MailUtils} = ChromeUtils.import("re
  * @param aFolder
  *        the folder with messages being marked as junk
  *
  * @return an object with two properties: 'markRead' (boolean) indicating
  *         whether the messages should be marked as read, and 'junkTargetFolder'
  *         (nsIMsgFolder) specifying where the messages should be moved, or
  *         null if they should not be moved.
  */
-function determineActionsForJunkMsgs(aFolder)
-{
+function determineActionsForJunkMsgs(aFolder) {
   var actions = { markRead: false, junkTargetFolder: null };
   var spamSettings = aFolder.server.spamSettings;
 
   // note we will do moves/marking as read even if the spam
   // feature is disabled, since the user has asked to use it
   // despite the disabling
 
   actions.markRead = spamSettings.markAsReadOnSpam;
   actions.junkTargetFolder = null;
 
   // move only when the corresponding setting is activated
   // and the currently viewed folder is not the junk folder.
   if (spamSettings.moveOnSpam &&
-      !(aFolder.flags & Ci.nsMsgFolderFlags.Junk))
-  {
+      !aFolder.getFlag(Ci.nsMsgFolderFlags.Junk)) {
     var spamFolderURI = spamSettings.spamFolderURI;
-    if (!spamFolderURI)
-    {
+    if (!spamFolderURI) {
       // XXX TODO
       // we should use nsIPromptService to inform the user of the problem,
       // e.g. when the junk folder was accidentally deleted.
-      dump('determineActionsForJunkMsgs: no spam folder found, not moving.');
+      dump("determineActionsForJunkMsgs: no spam folder found, not moving.");
+    } else {
+      actions.junkTargetFolder = MailUtils.getOrCreateFolder(spamFolderURI);
     }
-    else
-      actions.junkTargetFolder = MailUtils.getOrCreateFolder(spamFolderURI);
   }
 
   return actions;
 }
 
 /**
  * performActionsOnJunkMsgs
  *
@@ -84,39 +80,34 @@ function determineActionsForJunkMsgs(aFo
  *        the folder with messages being marked as junk
  *
  * @param aJunkMsgHdrs
  *        nsIArray containing headers (nsIMsgDBHdr) of new junk messages
  *
  * @param aGoodMsgHdrs
  *        nsIArray containing headers (nsIMsgDBHdr) of new good messages
  */
- function performActionsOnJunkMsgs(aFolder, aJunkMsgHdrs, aGoodMsgHdrs)
-{
-  if (aFolder instanceof Ci.nsIMsgImapMailFolder) // need to update IMAP custom flags
-  {
-    if (aJunkMsgHdrs.length)
-    {
-      var junkMsgKeys = new Array();
-      for (var i = 0; i < aJunkMsgHdrs.length; i++)
+function performActionsOnJunkMsgs(aFolder, aJunkMsgHdrs, aGoodMsgHdrs) {
+  if (aFolder instanceof Ci.nsIMsgImapMailFolder) { // need to update IMAP custom flags
+    if (aJunkMsgHdrs.length) {
+      var junkMsgKeys = [];
+      for (let i = 0; i < aJunkMsgHdrs.length; i++)
         junkMsgKeys[i] = aJunkMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr).messageKey;
       aFolder.storeCustomKeywords(null, "Junk", "NonJunk", junkMsgKeys, junkMsgKeys.length);
     }
 
-    if (aGoodMsgHdrs.length)
-    {
-      var goodMsgKeys = new Array();
-      for (var i = 0; i < aGoodMsgHdrs.length; i++)
+    if (aGoodMsgHdrs.length) {
+      let goodMsgKeys = [];
+      for (let i = 0; i < aGoodMsgHdrs.length; i++)
         goodMsgKeys[i] = aGoodMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr).messageKey;
       aFolder.storeCustomKeywords(null, "NonJunk", "Junk", goodMsgKeys, goodMsgKeys.length);
     }
   }
 
-  if (aJunkMsgHdrs.length)
-  {
+  if (aJunkMsgHdrs.length) {
     var actionParams = determineActionsForJunkMsgs(aFolder);
     if (actionParams.markRead)
       aFolder.markMessagesRead(aJunkMsgHdrs, true);
 
     if (actionParams.junkTargetFolder)
       MailServices.copy
                   .CopyMessages(aFolder, aJunkMsgHdrs, actionParams.junkTargetFolder,
                     true /* isMove */, null, msgWindow, true /* allow undo */);
@@ -130,88 +121,82 @@ function determineActionsForJunkMsgs(aFo
  * and implementing junk processing callback
  *
  * @param aFolder
  *        the folder with messages to be analyzed for junk
  * @param aTotalMessages
  *        Number of messages to process, used for progress report only
  */
 
-function MessageClassifier(aFolder, aTotalMessages)
-{
+function MessageClassifier(aFolder, aTotalMessages) {
   this.mFolder = aFolder;
   this.mJunkMsgHdrs = Cc["@mozilla.org/array;1"]
                         .createInstance(Ci.nsIMutableArray);
   this.mGoodMsgHdrs = Cc["@mozilla.org/array;1"]
                         .createInstance(Ci.nsIMutableArray);
-  this.mMessages = new Object();
-  this.mMessageQueue = new Array();
+  this.mMessages = {};
+  this.mMessageQueue = [];
   this.mTotalMessages = aTotalMessages;
   this.mProcessedMessages = 0;
   this.firstMessage = true;
   this.lastStatusTime = Date.now();
 }
 
-MessageClassifier.prototype =
-{
+MessageClassifier.prototype = {
   /**
    * analyzeMessage
    *
    * Starts the message classification process for a message. If the message
    * sender's address is whitelisted, the message is skipped.
    *
    * @param aMsgHdr
    *        The header (nsIMsgDBHdr) of the message to classify.
    * @param aSpamSettings
    *        nsISpamSettings object with information about whitelists
    */
-  analyzeMessage: function(aMsgHdr, aSpamSettings)
-  {
+  analyzeMessage(aMsgHdr, aSpamSettings) {
     var junkscoreorigin = aMsgHdr.getStringProperty("junkscoreorigin");
     if (junkscoreorigin == "user") // don't override user-set junk status
       return;
 
     // check whitelisting
-    if (aSpamSettings.checkWhiteList(aMsgHdr))
-    {
+    if (aSpamSettings.checkWhiteList(aMsgHdr)) {
       // message is ham from whitelist
       var db = aMsgHdr.folder.msgDatabase;
       db.setStringProperty(aMsgHdr.messageKey, "junkscore",
                            Ci.nsIJunkMailPlugin.IS_HAM_SCORE);
       db.setStringProperty(aMsgHdr.messageKey, "junkscoreorigin", "whitelist");
       this.mGoodMsgHdrs.appendElement(aMsgHdr);
       return;
     }
 
     var messageURI = aMsgHdr.folder.generateMessageURI(aMsgHdr.messageKey) + "?fetchCompleteMessage=true";
     this.mMessages[messageURI] = aMsgHdr;
-    if (this.firstMessage)
-    {
+    if (this.firstMessage) {
       this.firstMessage = false;
       MailServices.junk.classifyMessage(messageURI, msgWindow, this);
+    } else {
+      this.mMessageQueue.push(messageURI);
     }
-    else
-      this.mMessageQueue.push(messageURI);
   },
 
   /*
    * nsIJunkMailClassificationListener implementation
    * onMessageClassified
    *
    * Callback function from nsIJunkMailPlugin with classification results
    *
    * @param aClassifiedMsgURI
    *        URI of classified message
    * @param aClassification
    *        Junk classification (0: UNCLASSIFIED, 1: GOOD, 2: JUNK)
    * @param aJunkPercent
    *        0 - 100 indicator of junk likelihood, with 100 meaning probably junk
    */
-  onMessageClassified: function(aClassifiedMsgURI, aClassification, aJunkPercent)
-  {
+  onMessageClassified(aClassifiedMsgURI, aClassification, aJunkPercent) {
     if (!aClassifiedMsgURI)
       return; // ignore end of batch
     var nsIJunkMailPlugin = Ci.nsIJunkMailPlugin;
     var score = (aClassification == nsIJunkMailPlugin.JUNK) ?
       nsIJunkMailPlugin.IS_SPAM_SCORE : nsIJunkMailPlugin.IS_HAM_SCORE;
     const statusDisplayInterval = 1000; // milliseconds between status updates
 
     // set these props via the db (instead of the message header
@@ -224,44 +209,40 @@ MessageClassifier.prototype =
     db.setStringProperty(msgHdr.messageKey, "junkpercent", aJunkPercent);
 
     if (aClassification == nsIJunkMailPlugin.JUNK)
       this.mJunkMsgHdrs.appendElement(msgHdr);
     else if (aClassification == nsIJunkMailPlugin.GOOD)
       this.mGoodMsgHdrs.appendElement(msgHdr);
 
     var nextMsgURI = this.mMessageQueue.shift();
-    if (nextMsgURI)
-    {
+    if (nextMsgURI) {
       ++this.mProcessedMessages;
-      if (Date.now() > this.lastStatusTime + statusDisplayInterval)
-      {
+      if (Date.now() > this.lastStatusTime + statusDisplayInterval) {
         this.lastStatusTime = Date.now();
         var percentDone = 0;
         if (this.mTotalMessages)
           percentDone = Math.round(this.mProcessedMessages * 100 / this.mTotalMessages);
         var percentStr = percentDone + "%";
         window.MsgStatusFeedback.showStatusString(
             document.getElementById("bundle_messenger")
             .getFormattedString("junkAnalysisPercentComplete",
             [percentStr]));
       }
 
       MailServices.junk.classifyMessage(nextMsgURI, msgWindow, this);
-    }
-    else
-    {
+    } else {
       window.MsgStatusFeedback.showStatusString(
           document.getElementById("bundle_messenger")
           .getString("processingJunkMessages"));
       performActionsOnJunkMsgs(this.mFolder, this.mJunkMsgHdrs, this.mGoodMsgHdrs);
       window.MsgStatusFeedback.showStatusString("");
     }
-  }
-}
+  },
+};
 
 /*
  * filterFolderForJunk
  *
  * Filter all messages in the current folder for junk
  */
 function filterFolderForJunk() { processFolderForJunk(true); }
 
@@ -274,87 +255,74 @@ function analyzeMessagesForJunk() { proc
 
 /*
  * processFolderForJunk
  *
  * Filter messages in the current folder for junk
  *
  * @param aAll: true to filter all messages, else filter selection
  */
-function processFolderForJunk(aAll)
-{
+function processFolderForJunk(aAll) {
   MsgJunkMailInfo(true);
 
-  if (aAll)
-  {
+  let indices;
+  if (aAll) {
     // need to expand all threads, so we analyze everything
     gDBView.doCommand(Ci.nsMsgViewCommandType.expandAll);
     var treeView = gDBView.QueryInterface(Ci.nsITreeView);
     var count = treeView.rowCount;
     if (!count)
       return;
-  }
-  else
-  {
+  } else {
     // suite uses GetSelectedIndices, mail uses gFolderDisplay.selectedMessages
-    var indices = typeof GetSelectedIndices != "undefined" ?
-                    GetSelectedIndices(gDBView) :
-                    gFolderDisplay.selectedIndices;
+    indices = typeof window.GetSelectedIndices != "undefined" ?
+                window.GetSelectedIndices(gDBView) :
+                gFolderDisplay.selectedIndices;
     if (!indices || !indices.length)
       return;
   }
   var totalMessages = aAll ? count : indices.length;
 
   // retrieve server and its spam settings via the header of an arbitrary message
-  for (var i = 0; i < totalMessages; i++)
-  {
-    var index = aAll ? i : indices[i];
-    try
-    {
+  for (let i = 0; i < totalMessages; i++) {
+    let index = aAll ? i : indices[i];
+    try {
       var tmpMsgURI = gDBView.getURIForViewIndex(index);
       break;
-    }
-    catch (e)
-    {
+    } catch (e) {
       // dummy headers will fail, so look for another
       continue;
     }
   }
   if (!tmpMsgURI)
     return;
 
   var tmpMsgHdr = messenger.messageServiceFromURI(tmpMsgURI).messageURIToMsgHdr(tmpMsgURI);
   var spamSettings = tmpMsgHdr.folder.server.spamSettings;
 
   // create a classifier instance to classify messages in the folder.
   var msgClassifier = new MessageClassifier(tmpMsgHdr.folder, totalMessages);
 
-  for ( i = 0; i < totalMessages; i++)
-  {
-    var index = aAll ? i : indices[i];
-    try
-    {
+  for (let i = 0; i < totalMessages; i++) {
+    let index = aAll ? i : indices[i];
+    try {
       var msgURI = gDBView.getURIForViewIndex(index);
       var msgHdr = messenger.messageServiceFromURI(msgURI).messageURIToMsgHdr(msgURI);
       msgClassifier.analyzeMessage(msgHdr, spamSettings);
-    }
-    catch (ex)
-    {
+    } catch (ex) {
       // blow off errors here - dummy headers will fail
-      var msgURI = null;
     }
   }
   if (msgClassifier.firstMessage) // the async plugin was not used, maybe all whitelisted?
     performActionsOnJunkMsgs(msgClassifier.mFolder,
                              msgClassifier.mJunkMsgHdrs,
                              msgClassifier.mGoodMsgHdrs);
 }
 
-function JunkSelectedMessages(setAsJunk)
-{
+function JunkSelectedMessages(setAsJunk) {
   MsgJunkMailInfo(true);
 
   // When the user explicitly marks a message as junk, we can mark it as read,
   // too. This is independent of the "markAsReadOnSpam" pref, which applies
   // only to automatically-classified messages.
   // Note that this behaviour should match the one in the back end for marking
   // as junk via clicking the 'junk' column.
 
@@ -366,31 +334,28 @@ function JunkSelectedMessages(setAsJunk)
 }
 
 /**
  * Delete junk messages in the current folder. This provides the guarantee that
  * the method will be synchronous if no messages are deleted.
  *
  * @returns The number of messages deleted.
  */
-function deleteJunkInFolder()
-{
+function deleteJunkInFolder() {
   MsgJunkMailInfo(true);
 
   // use direct folder commands if possible so we don't mess with the selection
   let selectedFolder = gFolderDisplay.displayedFolder;
-  if ( !(selectedFolder.flags & Ci.nsMsgFolderFlags.Virtual) )
-  {
+  if (!selectedFolder.getFlag(Ci.nsMsgFolderFlags.Virtual)) {
     var junkMsgHdrs = Cc["@mozilla.org/array;1"]
                         .createInstance(Ci.nsIMutableArray);
     var enumerator = gDBView.msgFolder.messages;
-    while (enumerator.hasMoreElements())
-    {
-      var msgHdr = enumerator.getNext().QueryInterface(Ci.nsIMsgDBHdr);
-      var junkScore = msgHdr.getStringProperty("junkscore");
+    while (enumerator.hasMoreElements()) {
+      let msgHdr = enumerator.getNext().QueryInterface(Ci.nsIMsgDBHdr);
+      let junkScore = msgHdr.getStringProperty("junkscore");
       if (junkScore == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE)
         junkMsgHdrs.appendElement(msgHdr);
     }
 
     if (junkMsgHdrs.length)
       gDBView.msgFolder.deleteMessages(junkMsgHdrs, msgWindow, false, false, null, true);
     return junkMsgHdrs.length;
   }
@@ -407,31 +372,29 @@ function deleteJunkInFolder()
 
   var treeSelection = treeView.selection;
 
   var clearedSelection = false;
 
   // select the junk messages
   var messageUri;
   let numMessagesDeleted = 0;
-  for (var i = 0; i < count; ++i)
-  {
+  for (let i = 0; i < count; ++i) {
     try {
       messageUri = gDBView.getURIForViewIndex(i);
+    } catch (ex) {
+      continue; // blow off errors for dummy rows
     }
-    catch (ex) {continue;} // blow off errors for dummy rows
-    var msgHdr = messenger.messageServiceFromURI(messageUri).messageURIToMsgHdr(messageUri);
-    var junkScore = msgHdr.getStringProperty("junkscore");
+    let msgHdr = messenger.messageServiceFromURI(messageUri).messageURIToMsgHdr(messageUri);
+    let junkScore = msgHdr.getStringProperty("junkscore");
     var isJunk = (junkScore == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE);
     // if the message is junk, select it.
-    if (isJunk)
-    {
+    if (isJunk) {
       // only do this once
-      if (!clearedSelection)
-      {
+      if (!clearedSelection) {
         // clear the current selection
         // since we will be deleting all selected messages
         treeSelection.clearSelection();
         clearedSelection = true;
         treeSelection.selectEventsSuppressed = true;
       }
       treeSelection.rangedSelect(i, i, true /* augment */);
       numMessagesDeleted++;
@@ -442,15 +405,16 @@ function deleteJunkInFolder()
   // there was no junk, so bail.
   if (!clearedSelection)
     return 0;
 
   treeSelection.selectEventsSuppressed = false;
   // delete the selected messages
   //
   // We'll leave no selection after the delete
-  gNextMessageViewIndexAfterDelete = nsMsgViewIndex_None;
+  if ("gNextMessageViewIndexAfterDelete" in window) {
+    window.gNextMessageViewIndexAfterDelete = nsMsgViewIndex_None;
+  }
   gDBView.doCommand(Ci.nsMsgViewCommandType.deleteMsg);
   treeSelection.clearSelection();
   ClearMessagePane();
   return numMessagesDeleted;
 }
-
--- a/mailnews/base/content/junkLog.js
+++ b/mailnews/base/content/junkLog.js
@@ -3,31 +3,27 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 var gLogView;
 var gLogFile;
 
-function onLoad()
-{
+function onLoad() {
   gLogView = document.getElementById("logView");
   gLogView.docShell.allowJavascript = false; // for security, disable JS
 
   gLogFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
   gLogFile.append("junklog.html");
 
-  if (gLogFile.exists())
-  {
+  if (gLogFile.exists()) {
     // convert the file to a URL so we can load it.
     gLogView.setAttribute("src", Services.io.newFileURI(gLogFile).spec);
   }
 }
 
-function clearLog()
-{
-  if (gLogFile.exists())
-  {
+function clearLog() {
+  if (gLogFile.exists()) {
     gLogFile.remove(false);
     gLogView.setAttribute("src", "about:blank"); // we don't have a log file to show
   }
 }
--- a/mailnews/base/content/markByDate.js
+++ b/mailnews/base/content/markByDate.js
@@ -1,133 +1,126 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from dateFormat.js */
+
 var MILLISECONDS_PER_HOUR   = 60 * 60 * 1000;
 var MICROSECONDS_PER_DAY    = 1000 * MILLISECONDS_PER_HOUR * 24;
 
 document.addEventListener("dialogaccept", onAccept);
 
-function onLoad()
-{
+function onLoad() {
   var upperDateBox = document.getElementById("upperDate");
   // focus the upper bound control - this is where we expect most users to enter
   // a date
   upperDateBox.focus();
 
   // and give it an initial date - "yesterday"
   var initialDate = new Date();
-  initialDate.setHours( 0 );
-  initialDate.setTime( initialDate.getTime() - MILLISECONDS_PER_HOUR );
+  initialDate.setHours(0);
+  initialDate.setTime(initialDate.getTime() - MILLISECONDS_PER_HOUR);
     // note that this is sufficient - though it is at the end of the previous day,
     // we convert it to a date string, and then the time part is truncated
-  upperDateBox.value = convertDateToString( initialDate );
+  upperDateBox.value = convertDateToString(initialDate);
   upperDateBox.select();  // allows to start overwriting immediately
 }
 
-function onAccept()
-{
+function onAccept() {
   // get the times as entered by the user
-  var lowerDateString = document.getElementById( "lowerDate" ).value;
+  var lowerDateString = document.getElementById("lowerDate").value;
   // the fallback for the lower bound, if not entered, is the "beginning of
   // time" (1970-01-01), which actually is simply 0 :)
-  var prLower = lowerDateString ? convertStringToPRTime( lowerDateString ) : 0;
+  var prLower = lowerDateString ? convertStringToPRTime(lowerDateString) : 0;
 
-  var upperDateString = document.getElementById( "upperDate" ).value;
+  var upperDateString = document.getElementById("upperDate").value;
   var prUpper;
-  if ( upperDateString == "" )
-  {
+  if (upperDateString == "") {
     // for the upper bound, the fallback is "today".
     var dateThisMorning = new Date();
-    dateThisMorning.setMilliseconds( 0 );
-    dateThisMorning.setSeconds( 0 );
-    dateThisMorning.setMinutes( 0 );
-    dateThisMorning.setHours( 0 );
+    dateThisMorning.setMilliseconds(0);
+    dateThisMorning.setSeconds(0);
+    dateThisMorning.setMinutes(0);
+    dateThisMorning.setHours(0);
     // Javascript time is in milliseconds, PRTime is in microseconds
     prUpper = dateThisMorning.getTime() * 1000;
+  } else {
+    prUpper = convertStringToPRTime(upperDateString);
   }
-  else
-    prUpper = convertStringToPRTime( upperDateString );
 
   // for the upper date, we have to do a correction:
   // if the user enters a date, then she means (hopefully) that all messages sent
   // at this day should be marked, too, but the PRTime calculated from this would
   // point to the beginning of the day. So we need to increment it by
   // [number of micro seconds per day]. This will denote the first microsecond of
   // the next day then, which is later used as exclusive boundary
   prUpper += MICROSECONDS_PER_DAY;
 
-  markInDatabase( prLower, prUpper );
+  markInDatabase(prLower, prUpper);
 }
 
 /** marks all headers in the database, whose time is between the two
   given times, as read.
   @param lower
     PRTime for the lower bound - this boundary is inclusive
   @param upper
     PRTime for the upper bound - this boundary is exclusive
 */
-function markInDatabase( lower, upper )
-{
+function markInDatabase(lower, upper) {
   var messageFolder;
   var messageDatabase;
   // extract the database
-  if ( window.arguments && window.arguments[0] )
-  {
+  if (window.arguments && window.arguments[0]) {
     messageFolder = window.arguments[0];
     messageDatabase = messageFolder.msgDatabase;
   }
 
-  if ( !messageDatabase )
-  {
-    dump( "markByDate::markInDatabase: there /is/ no database to operate on!\n" );
+  if (!messageDatabase) {
+    dump("markByDate::markInDatabase: there /is/ no database to operate on!\n");
     return;
   }
 
   // the headers which are going to be marked
-  var headers = Cc["@mozilla.org/array;1"].createInstance( Ci.nsIMutableArray );
-  var searchSession = Cc["@mozilla.org/messenger/searchSession;1"].createInstance( Ci.nsIMsgSearchSession );
-  var searchTerms = Cc["@mozilla.org/array;1"].createInstance( Ci.nsIMutableArray );
-  searchSession.addScopeTerm( Ci.nsMsgSearchScope.offlineMail, messageFolder );
+  var headers = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
+  var searchSession = Cc["@mozilla.org/messenger/searchSession;1"].createInstance(Ci.nsIMsgSearchSession);
+  var searchTerms = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
+  searchSession.addScopeTerm(Ci.nsMsgSearchScope.offlineMail, messageFolder);
 
   const nsMsgSearchAttrib = Ci.nsMsgSearchAttrib;
   const nsMsgSearchOp = Ci.nsMsgSearchOp;
 
   var searchTerm = searchSession.createTerm();
   searchTerm.attrib = nsMsgSearchAttrib.Date;
   searchTerm.op = nsMsgSearchOp.IsBefore;
   var value = searchTerm.value;
   value.attrib = nsMsgSearchAttrib.Date;
   value.date = upper;
   searchTerm.value = value;
-  searchTerms.appendElement( searchTerm );
+  searchTerms.appendElement(searchTerm);
 
-  if ( lower )
-  {
+  if (lower) {
     searchTerm = searchSession.createTerm();
     searchTerm.booleanAnd = true;
     searchTerm.attrib = nsMsgSearchAttrib.Date;
     searchTerm.op = nsMsgSearchOp.IsAfter;
     value = searchTerm.value;
     value.attrib = nsMsgSearchAttrib.Date;
     value.date = lower;
     searchTerm.value = value;
-    searchTerms.appendElement( searchTerm );
+    searchTerms.appendElement(searchTerm);
   }
 
-  var filterEnumerator = messageDatabase.getFilterEnumerator( searchTerms );
+  var filterEnumerator = messageDatabase.getFilterEnumerator(searchTerms);
 
-  if ( filterEnumerator )
-  {
+  if (filterEnumerator) {
     var keepGoing;
     var numMatches = {};
-    do
-    {
+    do {
       keepGoing = messageDatabase.nextMatchingHdrs(filterEnumerator, 0, 0, headers, numMatches);
     }
-    while ( keepGoing );
+    while (keepGoing);
   }
 
-  if ( headers.length )
-    messageFolder.markMessagesRead( headers, true );
+  if (headers.length)
+    messageFolder.markMessagesRead(headers, true);
 }
--- a/mailnews/base/content/msgAccountCentral.js
+++ b/mailnews/base/content/msgAccountCentral.js
@@ -1,19 +1,22 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from ../../../mail/base/content/mailCore.js */
+/* import-globals-from ../prefs/content/AccountManager.js */
+/* import-globals-from ../prefs/content/accountUtils.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 var selectedServer = null;
 
-function OnInit()
-{
+function OnInit() {
     // Set the header for the page.
     // Title contains the brand name of the application and the account
     // type (mail/news) and the name of the account
     try {
         let msgFolder    = null;
         let title;
 
         // Get the brand name
@@ -47,71 +50,70 @@ function OnInit()
           title = brandName;
           SetItemDisplay("AccountsHeader", true);
           SetItemDisplay("CreateAccount", true);
           SetItemDisplay("CreateAccounts", true);
         }
 
         // Set the title for the document
         document.getElementById("AccountCentralTitle").setAttribute("value", title);
-    }
-    catch(ex) {
+    } catch (ex) {
         Cu.reportError("Error getting selected account: " + ex + "\n");
     }
 }
 
 // Show items in the AccountCentral page depending on the capabilities
 // of the given account
-function ArrangeAccountCentralItems(server, msgFolder)
-{
+/* eslint-disable complexity */
+function ArrangeAccountCentralItems(server, msgFolder) {
     let exceptions = [];
     let protocolInfo = null;
     try {
       protocolInfo = server.protocolInfo;
     } catch (e) {
       exceptions.push(e);
     }
 
     // Is this a RSS account?
-    let displayRssHeader = server && server.type == 'rss';
+    let displayRssHeader = server && server.type == "rss";
 
-    /***** Email header and items : Begin *****/
+    /* Email header and items : Begin */
 
     // Read Messages
     let canGetMessages = false;
     try {
         canGetMessages = protocolInfo && protocolInfo.canGetMessages;
         SetItemDisplay("ReadMessages", canGetMessages && !displayRssHeader);
     } catch (e) { exceptions.push(e); }
 
     // Compose Messages link
     let showComposeMsgLink = false;
     try {
         showComposeMsgLink = protocolInfo && protocolInfo.showComposeMsgLink;
         SetItemDisplay("ComposeMessage", showComposeMsgLink);
     } catch (e) { exceptions.push(e); }
 
     // Junk mail settings (false, until ready for prime time)
-    let canControlJunkEmail = false
+    let canControlJunkEmail = false;
     try {
         canControlJunkEmail = false && protocolInfo &&
                               protocolInfo.canGetIncomingMessages &&
                               protocolInfo.canGetMessages;
         SetItemDisplay("JunkSettingsMail", canControlJunkEmail);
     } catch (e) { exceptions.push(e); }
 
     // Display Email header, only if any of the items are displayed
     let displayEmailHeader = !displayRssHeader &&
                              (canGetMessages || showComposeMsgLink ||
                               canControlJunkEmail);
     SetItemDisplay("EmailHeader", displayEmailHeader);
 
-    /***** Email header and items : End *****/
+    /* Email header and items : End */
 
-    /***** News header and items : Begin *****/
+    /* News header and items : Begin */
 
     // Subscribe to Newsgroups
     let canSubscribe = false;
     try {
         canSubscribe = msgFolder && msgFolder.canSubscribe &&
                        protocolInfo && !protocolInfo.canGetMessages;
         SetItemDisplay("SubscribeNewsgroups", canSubscribe);
     } catch (e) { exceptions.push(e); }
@@ -124,54 +126,53 @@ function ArrangeAccountCentralItems(serv
                              !protocolInfo.canGetMessages;
         SetItemDisplay("JunkSettingsNews", canControlJunkNews);
     } catch (e) { exceptions.push(e); }
 
     // Display News header, only if any of the items are displayed
     let displayNewsHeader = canSubscribe || canControlJunkNews;
     SetItemDisplay("NewsHeader", displayNewsHeader);
 
-    /***** News header and items : End *****/
+    /* News header and items : End */
 
-    /***** RSS header and items : Begin *****/
+    /* RSS header and items : Begin */
 
     // Display RSS header, only if this is RSS account
     SetItemDisplay("rssHeader", displayRssHeader);
 
     // Subscribe to RSS Feeds
     SetItemDisplay("SubscribeRSS", displayRssHeader);
 
-    /***** RSS header and items : End *****/
+    /* RSS header and items : End */
 
     // If either of above sections exists, show section separators
     SetItemDisplay("MessagesSection",
                    displayNewsHeader || displayEmailHeader || displayRssHeader);
 
-    /***** Accounts : Begin *****/
+    /* Accounts : Begin */
 
     // Account Settings if a server is found
     let canShowAccountSettings = server != null;
     SetItemDisplay("AccountSettings", canShowAccountSettings);
 
     // Show New Mail Account Wizard if not prohibited by pref
     let canShowCreateAccount = false;
     try {
         canShowCreateAccount = !Services.prefs
           .prefIsLocked("mail.disable_new_account_addition");
         SetItemDisplay("CreateAccount", canShowCreateAccount);
         SetItemDisplay("CreateAccounts", canShowCreateAccount);
     } catch (e) { exceptions.push(e); }
 
     // Display Accounts header, only if any of the items are displayed
-    let displayAccountsHeader = canShowAccountSettings || canShowCreateAccount;
     SetItemDisplay("AccountsHeader", canShowCreateAccount);
 
-    /***** Accounts : End *****/
+    /* Accounts : End */
 
-    /***** Advanced Features header and items : Begin *****/
+    /* Advanced Features header and items : Begin */
 
     // Search Messages
     let canSearchMessages = false;
     try {
         canSearchMessages = server && server.canSearchMessages;
         SetItemDisplay("SearchMessages", canSearchMessages);
     } catch (e) { exceptions.push(e); }
 
@@ -194,102 +195,94 @@ function ArrangeAccountCentralItems(serv
     let supportsOffline = false;
     try {
         supportsOffline = server && server.offlineSupportLevel != 0;
         SetItemDisplay("OfflineSettings", supportsOffline);
     } catch (e) { exceptions.push(e); }
 
     // Display Adv Features header, only if any of the items are displayed
     let displayAdvFeatures = canSearchMessages || canHaveFilters ||
-                             canSubscribeImapFolders|| supportsOffline;
+                             canSubscribeImapFolders || supportsOffline;
     SetItemDisplay("AdvancedFeaturesHeader", displayAdvFeatures);
 
-    /***** Advanced Featuers header and items : End *****/
+    /* Advanced Featuers header and items : End */
 
     // If either of above features exist, show section separators
     SetItemDisplay("AccountsSection", displayAdvFeatures);
 
     while (exceptions.length) {
         Cu.reportError("Error in setting AccountCentral Items: "
             + exceptions.pop() + "\n");
     }
 }
+/* eslint-enable complexity */
 
 // Show the item if the item feature is supported
-function SetItemDisplay(elemId, displayThisItem)
-{
+function SetItemDisplay(elemId, displayThisItem) {
     if (displayThisItem) {
         let elem = document.getElementById(elemId);
         if (elem)
             elem.setAttribute("collapsed", false);
 
         let elemSpacer = document.getElementById(elemId + ".spacer");
         if (elemSpacer)
             elemSpacer.setAttribute("collapsed", false);
     }
 }
 
 // From the current folder tree, return the selected server or null
-function GetSelectedServer()
-{
+function GetSelectedServer() {
     let currentFolder = GetSelectedMsgFolder();
     return currentFolder ? currentFolder.server : null;
 }
 
 // From the current folder tree, return the selected folder,
 // the root folder of default account or null
-function GetSelectedMsgFolder()
-{
+function GetSelectedMsgFolder() {
     return window.parent.GetSelectedMsgFolders()[0] ||
            window.parent.GetDefaultAccountRootFolder();
 }
 
 /**
  * Open Inbox for selected server.
  * If needed, open the twisty and select Inbox.
  */
-function ReadMessages()
-{
+function ReadMessages() {
     if (!selectedServer)
         return;
     try {
         window.parent.OpenInboxForServer(selectedServer);
-    }
-    catch(ex) {
+    } catch (ex) {
         Cu.reportError("Error opening Inbox for server: " + ex + "\n");
     }
 }
 
 // Trigger composer for a new message
-function ComposeAMessage(event)
-{
+function ComposeAMessage(event) {
     // Pass event to allow holding Shift key for toggling HTML vs. plaintext format
     window.parent.MsgNewMessage(event);
 }
 
 /**
  * Open AccountManager to view settings for a given account
  * @param selectPage  the xul file name for the viewing page,
  *                    null for the account main page, other pages are
  *                    'am-server.xul', 'am-copies.xul', 'am-offline.xul',
  *                    'am-addressing.xul', 'am-smtp.xul'
  */
-function ViewSettings(selectPage)
-{
+function ViewSettings(selectPage) {
     window.parent.MsgAccountManager(selectPage);
 }
 
 // Open AccountWizard to create an account
-function CreateNewAccount()
-{
+function CreateNewAccount() {
     window.parent.msgOpenAccountWizard();
 }
 
-function CreateNewAccountTB(type)
-{
+function CreateNewAccountTB(type) {
   if (type == "mail") {
     AddMailAccount();
     return;
   }
 
   if (type == "feeds") {
     AddFeedAccount();
     return;
@@ -302,36 +295,32 @@ function CreateNewAccountTB(type)
           win.gFolderTreeView.selectFolder(
               this.gCurrentAccount.incomingServer.rootMsgFolder);
         }
       },
       type);
 }
 
 // Bring up search interface for selected account
-function SearchMessages()
-{
+function SearchMessages() {
     window.parent.MsgSearchMessages();
 }
 
 // Open filters window
-function CreateMsgFilters()
-{
+function CreateMsgFilters() {
     window.parent.MsgFilters(null, null);
 }
 
 // Open Subscribe dialog
-function Subscribe()
-{
+function Subscribe() {
     if (!selectedServer)
         return;
-    if (selectedServer.type == 'rss')
+    if (selectedServer.type == "rss")
         window.parent.openSubscriptionsDialog(selectedServer.rootFolder);
     else
         window.parent.MsgSubscribe();
 }
 
 // Open junk mail settings dialog
-function JunkSettings()
-{
+function JunkSettings() {
     // TODO: function does not exist yet, will throw an exception if exposed
     window.parent.MsgJunkMail();
 }
--- a/mailnews/base/content/msgFolderPickerOverlay.js
+++ b/mailnews/base/content/msgFolderPickerOverlay.js
@@ -3,97 +3,92 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 var gMessengerBundle;
 
 // call this from dialog onload() to set the menu item to the correct value
-function MsgFolderPickerOnLoad(pickerID)
-{
+function MsgFolderPickerOnLoad(pickerID) {
   var uri = null;
   try {
     uri = window.arguments[0].preselectedURI;
-  }
-  catch (ex) {
+  } catch (ex) {
     uri = null;
   }
 
   if (uri) {
-    //dump("on loading, set titled button to " + uri + "\n");
+    // dump("on loading, set titled button to " + uri + "\n");
 
     // verify that the value we are attempting to
     // pre-flight the menu with is valid for this
     // picker type
     var msgfolder = MailUtils.getExistingFolder(uri);
           if (!msgfolder) return;
-    
+
     var verifyFunction = null;
 
     switch (pickerID) {
       case "msgNewFolderPicker":
         verifyFunction = msgfolder.canCreateSubfolders;
         break;
       case "msgRenameFolderPicker":
         verifyFunction = msgfolder.canRename;
         break;
       default:
         verifyFunction = msgfolder.canFileMessages;
         break;
     }
 
     if (verifyFunction) {
-      SetFolderPicker(uri,pickerID);
+      SetFolderPicker(uri, pickerID);
     }
   }
 }
 
-function PickedMsgFolder(selection,pickerID)
-{
-  var selectedUri = selection.getAttribute('id');
-  SetFolderPicker(selectedUri,pickerID);
+function PickedMsgFolder(selection, pickerID) {
+  var selectedUri = selection.getAttribute("id");
+  SetFolderPicker(selectedUri, pickerID);
 }
 
-function SetFolderPickerElement(uri, picker)
-{
+function SetFolderPickerElement(uri, picker) {
   var msgfolder = MailUtils.getExistingFolder(uri);
 
   if (!msgfolder)
     return;
 
   var selectedValue = null;
   var serverName;
 
-  if (msgfolder.isServer)
+  if (msgfolder.isServer) {
     selectedValue = msgfolder.name;
-  else {
-    if (msgfolder.server)
+  } else {
+    if (msgfolder.server) {
       serverName = msgfolder.server.prettyName;
-    else {
+    } else {
      dump("Can't find server for " + uri + "\n");
      serverName = "???";
     }
 
-  switch (picker.id) {
-    case "runFiltersFolder":
-      selectedValue = msgfolder.name;
-      break;
-    case "msgTrashFolderPicker":
-      selectedValue = msgfolder.name;
-      break;
-    default:
-      if (!gMessengerBundle)
-        gMessengerBundle = document.getElementById("bundle_messenger");
-      selectedValue = gMessengerBundle.getFormattedString("verboseFolderFormat",
-        [msgfolder.name, serverName]);
-      break;
+    switch (picker.id) {
+      case "runFiltersFolder":
+        selectedValue = msgfolder.name;
+        break;
+      case "msgTrashFolderPicker":
+        selectedValue = msgfolder.name;
+        break;
+      default:
+        if (!gMessengerBundle)
+          gMessengerBundle = document.getElementById("bundle_messenger");
+        selectedValue = gMessengerBundle.getFormattedString("verboseFolderFormat",
+          [msgfolder.name, serverName]);
+        break;
     }
   }
 
-  picker.setAttribute("label",selectedValue);
-  picker.setAttribute("uri",uri);
+  picker.setAttribute("label", selectedValue);
+  picker.setAttribute("uri", uri);
 }
 
-function SetFolderPicker(uri,pickerID)
-{
+function SetFolderPicker(uri, pickerID) {
   SetFolderPickerElement(uri, document.getElementById(pickerID));
 }
--- a/mailnews/base/content/msgPrintEngine.js
+++ b/mailnews/base/content/msgPrintEngine.js
@@ -1,96 +1,92 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* This is where functions related to the print engine are kept */
 
+/* import-globals-from ../../../../toolkit/components/printing/content/printUtils.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 /* globals for a particular window */
 var printEngineContractID      = "@mozilla.org/messenger/msgPrintEngine;1";
 var printEngineWindow;
 var printEngine;
 var printSettings = null;
 var printOpener = null;
 
 /* Functions related to startup */
-function OnLoadPrintEngine()
-{
+function OnLoadPrintEngine() {
   PrintEngineCreateGlobals();
   InitPrintEngineWindow();
   printEngine.startPrintOperation(printSettings);
 }
 
-function PrintEngineCreateGlobals()
-{
+function PrintEngineCreateGlobals() {
   /* get the print engine instance */
   printEngine = Cc[printEngineContractID].createInstance();
   printEngine = printEngine.QueryInterface(Ci.nsIMsgPrintEngine);
   printSettings = PrintUtils.getPrintSettings();
   if (printSettings) {
     printSettings.isCancelled = false;
   }
 }
 
 var PrintPreviewListener = {
-  getPrintPreviewBrowser: function () {
+  getPrintPreviewBrowser() {
     var browser = document.getElementById("ppBrowser");
     if (!browser) {
       browser = document.createElement("browser");
       browser.setAttribute("id", "ppBrowser");
       browser.setAttribute("flex", "1");
       browser.setAttribute("disablehistory", "true");
       browser.setAttribute("disablesecurity", "true");
       browser.setAttribute("type", "content");
       document.documentElement.appendChild(browser);
     }
     return browser;
   },
-  getSourceBrowser: function () {
+  getSourceBrowser() {
     return document.getElementById("content");
   },
-  getNavToolbox: function () {
+  getNavToolbox() {
     return document.getElementById("content");
   },
-  onEnter: function () {
+  onEnter() {
     setPPTitle(document.getElementById("content").contentDocument.title);
     document.getElementById("content").collapsed = true;
     printEngine.showWindow(true);
   },
-  onExit: function () {
+  onExit() {
     window.close();
-  }
+  },
 };
 
-function setPPTitle(aTitle)
-{
+function setPPTitle(aTitle) {
   let title = aTitle;
   let gBrandBundle = document.getElementById("bundle_brand");
   let msgBundle = document.getElementById("bundle_messenger");
   let brandStr = gBrandBundle.getString("brandShortName");
   if (brandStr) {
     title = msgBundle.getFormattedString("PreviewTitle", [title, brandStr]);
   }
   document.title = title;
 }
 
 // Pref listener constants
-var gStartupPPObserver =
-{
-  observe: function(subject, topic, prefName)
-  {
+var gStartupPPObserver = {
+  observe(subject, topic, prefName) {
     PrintUtils.printPreview(PrintPreviewListener);
-  }
+  },
 };
 
-function ReplaceWithSelection()
-{
+function ReplaceWithSelection() {
   if (!printOpener.content)
     return;
 
   var selection = printOpener.content.getSelection();
 
   if (selection != "") {
     var range = selection.getRangeAt(0);
     var contents = range.cloneContents();
@@ -100,18 +96,17 @@ function ReplaceWithSelection()
     /* Replace the content of <body> with the users' selection. */
     if (aBody) {
       aBody.innerHTML = "";
       aBody.appendChild(contents);
     }
   }
 }
 
-function InitPrintEngineWindow()
-{
+function InitPrintEngineWindow() {
   /* Store the current opener for later access in ReplaceWithSelection() */
   printOpener = opener;
 
   /* Register the event listener to be able to replace the document
    * content with the user selection when loading is finished.
    */
   document.getElementById("content").addEventListener("load", ReplaceWithSelection, true);
 
@@ -155,28 +150,24 @@ function InitPrintEngineWindow()
       printEngine.setPrintURICount(numSelected);
       for (var i = 0; i < numSelected; i++) {
         printEngine.addPrintURI(uriArray[i]);
       }
     }
   }
 }
 
-function ClearPrintEnginePane()
-{
-  if (window.frames["content"].location.href != "about:blank")
-    window.frames["content"].location.href = "about:blank";
+function ClearPrintEnginePane() {
+  if (window.frames.content.location.href != "about:blank")
+    window.frames.content.location.href = "about:blank";
 }
 
-function StopUrls()
-{
+function StopUrls() {
   printEngine.stopUrls();
 }
 
-function PrintEnginePrint()
-{
+function PrintEnginePrint() {
   printEngineWindow = window.openDialog("chrome://messenger/content/msgPrintEngine.xul", "", "chrome,dialog=no,all,centerscreen", false);
 }
 
-function PrintEnginePrintPreview()
-{
+function PrintEnginePrintPreview() {
   printEngineWindow = window.openDialog("chrome://messenger/content/msgPrintEngine.xul", "", "chrome,dialog=no,all,centerscreen", true);
 }
--- a/mailnews/base/content/msgSelectOfflineFolders.js
+++ b/mailnews/base/content/msgSelectOfflineFolders.js
@@ -1,56 +1,57 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from ../../../mail/base/content/folderPane.js */
+
 var gSelectOffline = {
   _treeElement: null,
   _rollbackMap: new Map(),
 
-  load: function() {
+  load() {
     let oldProps = ftvItem.prototype.getProperties;
     ftvItem.prototype.getProperties = function(aColumn) {
       if (!aColumn || aColumn.id != "syncCol")
         return oldProps.call(this, aColumn);
 
       let properties = "syncCol";
 
       if (this._folder.isServer)
         return " isServer-true";
 
       if (this._folder.getFlag(Ci.nsMsgFolderFlags.Offline))
         properties += " synchronize-true";
 
       return properties;
-    }
+    };
 
     let modeOffline = {
       __proto__: IFolderTreeMode,
 
-      generateMap: function(ftv) {
-        let filterOffline = function(aFolder) { return aFolder.supportsOffline; }
+      generateMap(ftv) {
+        let filterOffline = function(aFolder) { return aFolder.supportsOffline; };
         let accounts = gFolderTreeView._sortedAccounts()
                          .filter(acct => filterOffline(acct.incomingServer.rootFolder));
         // Force each root folder to do its local subfolder discovery.
         MailUtils.discoverFolders();
         return accounts.map(acct => new ftvItem(acct.incomingServer.rootFolder,
                                                 filterOffline));
-      }
+      },
     };
 
     this._treeElement = document.getElementById("synchronizeTree");
 
     gFolderTreeView.registerFolderTreeMode(this._treeElement.getAttribute("mode"),
                                            modeOffline, "Offline Folders");
     gFolderTreeView.load(this._treeElement);
-
   },
 
-  onKeyPress: function(aEvent) {
+  onKeyPress(aEvent) {
     // For now, only do something on space key.
     if (aEvent.charCode != aEvent.DOM_VK_SPACE)
       return;
 
     let selection = this._treeElement.view.selection;
     let start = {};
     let end = {};
     let numRanges = selection.getRangeCount();
@@ -58,50 +59,50 @@ var gSelectOffline = {
     for (let range = 0; range < numRanges; range++) {
       selection.getRangeAt(range, start, end);
       for (let i = start.value; i <= end.value; i++) {
         this._toggle(i);
       }
     }
   },
 
-  onClick: function(aEvent) {
+  onClick(aEvent) {
     // We only care about button 0 (left click) events.
     if (aEvent.button != 0)
       return;
 
     let treeCellInfo = this._treeElement.getCellAt(aEvent.clientX);
 
     if (treeCellInfo.row == -1 || treeCellInfo.col.id != "syncCol")
       return;
 
     this._toggle(treeCellInfo.row);
   },
 
-  _toggle: function(aRow) {
+  _toggle(aRow) {
     let folder = gFolderTreeView._rowMap[aRow]._folder;
 
     if (folder.isServer)
       return;
 
     // Save our current state for rollback, if necessary.
     if (!this._rollbackMap.has(folder))
       this._rollbackMap.set(folder, folder.getFlag(Ci.nsMsgFolderFlags.Offline));
 
     folder.toggleFlag(Ci.nsMsgFolderFlags.Offline);
     gFolderTreeView._tree.invalidateRow(aRow);
   },
 
-  onAccept: function() {
+  onAccept() {
     gFolderTreeView.unload();
   },
 
-  onCancel: function() {
+  onCancel() {
     gFolderTreeView.unload();
     for (let [folder, value] of this._rollbackMap) {
       if (value != folder.getFlag(Ci.nsMsgFolderFlags.Offline))
         folder.toggleFlag(Ci.nsMsgFolderFlags.Offline);
     }
-  }
+  },
 };
 
 document.addEventListener("dialogaccept", gSelectOffline.onAccept);
 document.addEventListener("dialogcancel", gSelectOffline.onCancel);
--- a/mailnews/base/content/msgSynchronize.js
+++ b/mailnews/base/content/msgSynchronize.js
@@ -9,18 +9,17 @@ var {MailUtils} = ChromeUtils.import("re
 var gSynchronizeTree = null;
 var gParentMsgWindow;
 var gMsgWindow;
 
 var gInitialFolderStates = {};
 
 document.addEventListener("dialogaccept", syncOkButton);
 
-function OnLoad()
-{
+function OnLoad() {
     if (window.arguments && window.arguments[0]) {
         if (window.arguments[0].msgWindow) {
             gParentMsgWindow = window.arguments[0].msgWindow;
         }
     }
 
     document.getElementById("syncMail").checked =
       Services.prefs.getBoolPref("mailnews.offline_sync_mail");
@@ -29,106 +28,98 @@ function OnLoad()
     document.getElementById("sendMessage").checked =
       Services.prefs.getBoolPref("mailnews.offline_sync_send_unsent");
     document.getElementById("workOffline").checked =
       Services.prefs.getBoolPref("mailnews.offline_sync_work_offline");
 
     return true;
 }
 
-function syncOkButton()
-{
+function syncOkButton() {
     var syncMail = document.getElementById("syncMail").checked;
     var syncNews = document.getElementById("syncNews").checked;
     var sendMessage = document.getElementById("sendMessage").checked;
     var workOffline = document.getElementById("workOffline").checked;
 
     Services.prefs.setBoolPref("mailnews.offline_sync_mail", syncMail);
     Services.prefs.setBoolPref("mailnews.offline_sync_news", syncNews);
     Services.prefs.setBoolPref("mailnews.offline_sync_send_unsent", sendMessage);
     Services.prefs.setBoolPref("mailnews.offline_sync_work_offline", workOffline);
 
     if (syncMail || syncNews || sendMessage || workOffline) {
         var offlineManager = Cc["@mozilla.org/messenger/offline-manager;1"]
                                .getService(Ci.nsIMsgOfflineManager);
-        if(offlineManager)
-            offlineManager.synchronizeForOffline(syncNews, syncMail, sendMessage, workOffline, gParentMsgWindow)
+        if (offlineManager)
+            offlineManager.synchronizeForOffline(syncNews, syncMail, sendMessage, workOffline, gParentMsgWindow);
     }
 }
 
-function OnSelect()
-{
+function OnSelect() {
    top.window.openDialog("chrome://messenger/content/msgSelectOfflineFolders.xul", "",
                          "centerscreen,chrome,modal,titlebar,resizable=yes");
    return true;
 }
 
 // All the code below is only used by Seamonkey.
 
-function selectOkButton()
-{
+function selectOkButton() {
     return true;
 }
 
-function selectCancelButton()
-{
+function selectCancelButton() {
     for (var resourceValue in gInitialFolderStates) {
       let folder = MailUtils.getExistingFolder(resourceValue);
       if (gInitialFolderStates[resourceValue])
         folder.setFlag(Ci.nsMsgFolderFlags.Offline);
       else
         folder.clearFlag(Ci.nsMsgFolderFlags.Offline);
     }
     return true;
 }
 
-function selectOnLoad()
-{
+function selectOnLoad() {
     gMsgWindow = Cc["@mozilla.org/messenger/msgwindow;1"]
                    .createInstance(Ci.nsIMsgWindow);
     gMsgWindow.domWindow = window;
     gMsgWindow.rootDocShell.appType = Ci.nsIDocShell.APP_TYPE_MAIL;
 
-    gSynchronizeTree = document.getElementById('synchronizeTree');
+    gSynchronizeTree = document.getElementById("synchronizeTree");
 
-    SortSynchronizePane('folderNameCol', '?folderTreeNameSort');
+    SortSynchronizePane("folderNameCol", "?folderTreeNameSort");
 }
 
-function SortSynchronizePane(column, sortKey)
-{
+function SortSynchronizePane(column, sortKey) {
     var node = FindInWindow(window, column);
-    if(!node) {
-        dump('Couldnt find sort column\n');
+    if (!node) {
+        dump("Couldnt find sort column\n");
         return;
     }
 
     node.setAttribute("sort", sortKey);
     node.setAttribute("sortDirection", "natural");
     var col = gSynchronizeTree.columns[column];
     gSynchronizeTree.view.cycleHeader(col);
 }
 
-function FindInWindow(currentWindow, id)
-{
+function FindInWindow(currentWindow, id) {
     var item = currentWindow.document.getElementById(id);
-    if(item)
-    return item;
+    if (item)
+      return item;
 
-    for(var i = 0; i < currentWindow.frames.length; i++) {
+    for (var i = 0; i < currentWindow.frames.length; i++) {
         var frameItem = FindInWindow(currentWindow.frames[i], id);
-        if(frameItem)
+        if (frameItem)
             return frameItem;
     }
 
     return null;
 }
 
 
-function onSynchronizeClick(event)
-{
+function onSynchronizeClick(event) {
     // we only care about button 0 (left click) events
     if (event.button != 0)
       return;
 
     let treeCellInfo = gSynchronizeTree.getCellAt(event.clientX, event.clientY);
     if (treeCellInfo.row == -1)
       return;
 
@@ -139,49 +130,43 @@ function onSynchronizeClick(event)
         if (!(gSynchronizeTree.view.isContainerOpen(treeCellInfo.row))) {
             var serverType = folder.server.type;
             // imap is the only server type that does folder discovery
             if (serverType != "imap") return;
 
             if (folder.isServer) {
                 var server = folder.server;
                 server.performExpand(gMsgWindow);
-            }
-            else {
+            } else {
                 var imapFolder = folderResource.QueryInterface(Ci.nsIMsgImapMailFolder);
                 if (imapFolder) {
                   imapFolder.performExpand(gMsgWindow);
                 }
             }
         }
-    }
-    else {
-      if (treeCellInfo.col.id == "syncCol") {
+    } else if (treeCellInfo.col.id == "syncCol") {
         UpdateNode(GetFolderResource(gSynchronizeTree, treeCellInfo.row), treeCellInfo.row);
-      }
     }
 }
 
-function onSynchronizeTreeKeyPress(event)
-{
+function onSynchronizeTreeKeyPress(event) {
     // for now, only do something on space key
     if (event.charCode != KeyEvent.DOM_VK_SPACE)
       return;
 
     var treeSelection = gSynchronizeTree.view.selection;
-    for (var i=0;i<treeSelection.getRangeCount();i++) {
+    for (let i = 0; i < treeSelection.getRangeCount(); i++) {
       var start = {}, end = {};
-      treeSelection.getRangeAt(i,start,end);
-      for (var k=start.value;k<=end.value;k++)
+      treeSelection.getRangeAt(i, start, end);
+      for (let k = start.value; k <= end.value; k++)
         UpdateNode(GetFolderResource(gSynchronizeTree, k), k);
     }
 }
 
-function UpdateNode(resource, row)
-{
+function UpdateNode(resource, row) {
     var folder = resource.QueryInterface(Ci.nsIMsgFolder);
 
     if (folder.isServer)
       return;
 
     if (!(resource.Value in gInitialFolderStates)) {
       gInitialFolderStates[resource.Value] = folder.getFlag(Ci.nsMsgFolderFlags.Offline);
     }
--- a/mailnews/base/content/newFolderDialog.js
+++ b/mailnews/base/content/newFolderDialog.js
@@ -5,33 +5,32 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var FOLDERS = 1;
 var MESSAGES = 2;
 var dialog;
 
 document.addEventListener("dialogaccept", onOK);
 
-function onLoad()
-{
+function onLoad() {
   var windowArgs = window.arguments[0];
 
   dialog = {};
 
   dialog.nameField = document.getElementById("name");
   dialog.nameField.focus();
 
   // call this when OK is pressed
   dialog.okCallback = windowArgs.okCallback;
 
   // pre select the folderPicker, based on what they selected in the folder pane
   dialog.folder = windowArgs.folder;
   try {
     document.getElementById("MsgNewFolderPopup").selectFolder(windowArgs.folder);
-  } catch(ex) {
+  } catch (ex) {
     // selected a child folder
       document.getElementById("msgNewFolderPicker")
           .setAttribute("label", windowArgs.folder.prettyName);
   }
 
   // can folders contain both folders and messages?
   if (windowArgs.dualUseFolders) {
     dialog.folderType = FOLDERS | MESSAGES;
@@ -48,37 +47,32 @@ function onLoad()
 }
 
 function onFolderSelect(event) {
   dialog.folder = event.target._folder;
   document.getElementById("msgNewFolderPicker")
           .setAttribute("label", dialog.folder.prettyName);
 }
 
-function onOK()
-{
+function onOK() {
   var name = dialog.nameField.value;
-  var uri = dialog.folder;
 
   // do name validity check?
 
   // make sure name ends in  "/" if folder to create can only contain folders
   if ((dialog.folderType == FOLDERS) && !name.endsWith("/"))
     dialog.okCallback(name + "/", dialog.folder);
   else
     dialog.okCallback(name, dialog.folder);
 }
 
-function onFoldersOnly()
-{
+function onFoldersOnly() {
   dialog.folderType = FOLDERS;
 }
 
-function onMessagesOnly()
-{
+function onMessagesOnly() {
   dialog.folderType = MESSAGES;
 }
 
-function doEnabling()
-{
+function doEnabling() {
   document.documentElement.getButton("accept").disabled = !dialog.nameField.value;
 }
 
--- a/mailnews/base/content/newmailalert.js
+++ b/mailnews/base/content/newmailalert.js
@@ -14,18 +14,17 @@ var NS_ALERT_TOP = 4;
 var gNumNewMsgsToShowInAlert = 4; // the more messages we show in the alert, the larger it will be
 var gOpenTime = 4000; // total time the alert should stay up once we are done animating.
 
 var gAlertListener = null;
 var gPendingPreviewFetchRequests = 0;
 var gUserInitiated = false;
 var gOrigin = 0; // Default value: alert from bottom right.
 
-function prefillAlertInfo()
-{
+function prefillAlertInfo() {
   // unwrap all the args....
   // arguments[0] --> nsIArray of folders with new mail
   // arguments[1] --> the observer to call back with notifications about the alert
   // arguments[2] --> user initiated boolean. true if the user initiated opening the alert
   //                 (which means skip the fade effect and don't auto close the alert)
   // arguments[3] --> the alert origin returned by the look and feel
   var foldersWithNewMail = window.arguments[0];
   gAlertListener = window.arguments[1];
@@ -36,31 +35,30 @@ function prefillAlertInfo()
   // for the account that has new mail. If we can't find a folder, just
   // return to avoid the exception and empty dialog in upper left-hand corner.
   if (!foldersWithNewMail || foldersWithNewMail.length < 1)
     return;
   let rootFolder = foldersWithNewMail.queryElementAt(0, Ci.nsIWeakReference)
                                      .QueryReferent(Ci.nsIMsgFolder);
 
   // Generate an account label string based on the root folder.
-  var label = document.getElementById('alertTitle');
+  var label = document.getElementById("alertTitle");
   var totalNumNewMessages = rootFolder.getNumNewMessages(true);
   let message = document.getElementById("bundle_messenger")
                         .getString("newMailAlert_message");
   label.value = PluralForm.get(totalNumNewMessages, message)
                           .replace("#1", rootFolder.prettyName)
                           .replace("#2", totalNumNewMessages);
 
   // This is really the root folder and we have to walk through the list to
   // find the real folder that has new mail in it...:(
   let allFolders = rootFolder.descendants;
-  var folderSummaryInfoEl = document.getElementById('folderSummaryInfo');
+  var folderSummaryInfoEl = document.getElementById("folderSummaryInfo");
   folderSummaryInfoEl.mMaxMsgHdrsInPopup = gNumNewMsgsToShowInAlert;
-  for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder))
-  {
+  for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
     if (folder.hasNewMessages) {
       let notify =
         // Any folder which is an inbox or ...
         folder.getFlag(Ci.nsMsgFolderFlags.Inbox) ||
         // any non-special or non-virtual folder. In other words, we don't
         // notify for Drafts|Trash|SentMail|Templates|Junk|Archive|Queue or virtual.
         !(folder.flags & (Ci.nsMsgFolderFlags.SpecialUse | Ci.nsMsgFolderFlags.Virtual));
 
@@ -69,60 +67,54 @@ function prefillAlertInfo()
         folderSummaryInfoEl.parseFolder(folder, new urlListener(folder), asyncFetch);
         if (asyncFetch.value)
           gPendingPreviewFetchRequests++;
       }
     }
   }
 }
 
-function urlListener(aFolder)
-{
+function urlListener(aFolder) {
   this.mFolder = aFolder;
 }
 
-urlListener.prototype =
-{
-  OnStartRunningUrl: function(aUrl)
-  {
+urlListener.prototype = {
+  OnStartRunningUrl(aUrl) {
   },
 
-  OnStopRunningUrl: function(aUrl, aExitCode)
-  {
+  OnStopRunningUrl(aUrl, aExitCode) {
     let folderSummaryInfoEl = document.getElementById("folderSummaryInfo");
     folderSummaryInfoEl.parseFolder(this.mFolder, null, {});
     gPendingPreviewFetchRequests--;
 
     // when we are done running all of our urls for fetching the preview text,
     // start the alert.
     if (!gPendingPreviewFetchRequests)
       showAlert();
-  }
-}
+  },
+};
 
-function onAlertLoad()
-{
+function onAlertLoad() {
   prefillAlertInfo();
 
   gOpenTime = Services.prefs.getIntPref("alerts.totalOpenTime");
 
   // bogus call to make sure the window is moved offscreen until we are ready for it.
   resizeAlert(true);
 
   // if we aren't waiting to fetch preview text, then go ahead and
   // start showing the alert.
   if (!gPendingPreviewFetchRequests)
     setTimeout(showAlert, 0); // let the JS thread unwind, to give layout
                               // a chance to recompute the styles and widths for our alert text.
 }
 
 // If the user initiated the alert, show it right away, otherwise start opening the alert with
 // the fade effect.
-function showAlert()
-{
+function showAlert() {
   if (!document.getElementById("folderSummaryInfo").hasMessages) {
     closeAlert(); // no mail, so don't bother showing the alert...
     return;
   }
 
   // resize the alert based on our current content
   resizeAlert(false);
 
@@ -140,18 +132,17 @@ function showAlert()
       alertContainer.removeEventListener("animationend", hideAlert);
       setTimeout(fadeOutAlert, gOpenTime);
     }
   });
 
   alertContainer.setAttribute("fade-in", true);
 }
 
-function resizeAlert(aMoveOffScreen)
-{
+function resizeAlert(aMoveOffScreen) {
   var alertTextBox = document.getElementById("alertTextBox");
   var alertImageBox = document.getElementById("alertImageBox");
   alertImageBox.style.minHeight = alertTextBox.scrollHeight + "px";
 
   sizeToContent();
 
   // leftover hack to get the window properly hidden when we first open it
   if (aMoveOffScreen)
@@ -165,26 +156,24 @@ function resizeAlert(aMoveOffScreen)
 
   // Offset the alert by 10 pixels from the edge of the screen
   y += gOrigin & NS_ALERT_TOP ? 10 : -10;
   x += gOrigin & NS_ALERT_LEFT ? 10 : -10;
 
   window.moveTo(x, y);
 }
 
-function fadeOutAlert()
-{
+function fadeOutAlert() {
   var alertContainer = document.getElementById("alertContainer");
   alertContainer.addEventListener("animationend", function fadeOut(event) {
     if (event.animationName == "fade-out") {
       alertContainer.removeEventListener("animationend", fadeOut);
       closeAlert();
     }
   });
   alertContainer.setAttribute("fade-out", true);
 }
 
-function closeAlert()
-{
+function closeAlert() {
   if (gAlertListener)
     gAlertListener.observe(null, "alertfinished", "");
   window.close();
 }
--- a/mailnews/base/content/newsError.js
+++ b/mailnews/base/content/newsError.js
@@ -2,17 +2,17 @@
       //   about:newserror?r=response&m=messageid&k=messagekey&f=folderuri
       // "r" is required; "m" and "f" are optional, but "k" always comes with "m".
 
       var folderUri;
 
 
       function initPage() {
         let uri = document.documentURI;
-        let query = uri.slice(uri.indexOf("?")+1);
+        let query = uri.slice(uri.indexOf("?") + 1);
         let params = {};
         for (let piece of query.split("&")) {
           let [key, value] = piece.split("=");
           params[key] = decodeURIComponent(value);
         }
 
         document.getElementById("ngResp").textContent = params.r;
 
--- a/mailnews/base/content/renameFolderDialog.js
+++ b/mailnews/base/content/renameFolderDialog.js
@@ -3,18 +3,17 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var dialog;
 
 document.addEventListener("dialogaccept", onOK);
 
-function onLoad()
-{
+function onLoad() {
   var windowArgs = window.arguments[0];
 
   dialog = {};
 
   dialog.OKButton = document.documentElement.getButton("accept");
 
   dialog.nameField = document.getElementById("name");
   dialog.nameField.value = windowArgs.name;
@@ -25,23 +24,20 @@ function onLoad()
   dialog.okCallback = windowArgs.okCallback;
 
   // pre select the folderPicker, based on what they selected in the folder pane
   dialog.preselectedFolderURI = windowArgs.preselectedURI;
 
   doEnabling();
 }
 
-function onOK()
-{
+function onOK() {
   dialog.okCallback(dialog.nameField.value, dialog.preselectedFolderURI);
 }
 
-function doEnabling()
-{
+function doEnabling() {
   if (dialog.nameField.value) {
     if (dialog.OKButton.disabled)
       dialog.OKButton.disabled = false;
-  } else {
-    if (!dialog.OKButton.disabled)
-      dialog.OKButton.disabled = true;
+  } else if (!dialog.OKButton.disabled) {
+    dialog.OKButton.disabled = true;
   }
 }
--- a/mailnews/base/content/retention.js
+++ b/mailnews/base/content/retention.js
@@ -1,42 +1,40 @@
 /*
  * -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* globals gLockedPref */// From either folderProps.js or am-offline.js.
 
-function initCommonRetentionSettings(retentionSettings)
-{
+function initCommonRetentionSettings(retentionSettings) {
   document.getElementById("retention.keepMsg").value = retentionSettings.retainByPreference;
   document.getElementById("retention.keepOldMsgMin").value =
     (retentionSettings.daysToKeepHdrs > 0) ? retentionSettings.daysToKeepHdrs : 30;
   document.getElementById("retention.keepNewMsgMin").value =
     (retentionSettings.numHeadersToKeep > 0) ? retentionSettings.numHeadersToKeep : 2000;
 
   document.getElementById("retention.applyToFlagged").checked =
     !retentionSettings.applyToFlaggedMessages;
 }
 
-function saveCommonRetentionSettings(aRetentionSettings)
-{
+function saveCommonRetentionSettings(aRetentionSettings) {
   aRetentionSettings.retainByPreference = document.getElementById("retention.keepMsg").value;
 
   aRetentionSettings.daysToKeepHdrs = document.getElementById("retention.keepOldMsgMin").value;
   aRetentionSettings.numHeadersToKeep = document.getElementById("retention.keepNewMsgMin").value;
 
   aRetentionSettings.applyToFlaggedMessages =
     !document.getElementById("retention.applyToFlagged").checked;
 
   return aRetentionSettings;
 }
 
-function onCheckKeepMsg()
-{
+function onCheckKeepMsg() {
   if (gLockedPref && gLockedPref["retention.keepMsg"]) {
     // if the pref associated with the radiobutton is locked, as indicated
     // by the gLockedPref, skip this function.  All elements in this
     // radiogroup have been locked by the function onLockPreference.
     return;
   }
 
   var keepMsg = document.getElementById("retention.keepMsg").value;
--- a/mailnews/base/content/shutdownWindow.js
+++ b/mailnews/base/content/shutdownWindow.js
@@ -8,92 +8,79 @@ var curTaskIndex = 0;
 var numTasks = 0;
 var stringBundle;
 
 var msgShutdownService = Cc["@mozilla.org/messenger/msgshutdownservice;1"]
                            .getService(Ci.nsIMsgShutdownService);
 
 document.addEventListener("dialogcancel", onCancel);
 
-function onLoad()
-{
+function onLoad() {
   numTasks = msgShutdownService.getNumTasks();
 
   stringBundle = document.getElementById("bundle_shutdown");
   document.title = stringBundle.getString("shutdownDialogTitle");
 
   updateTaskProgressLabel(1);
   updateProgressMeter(0);
 
   msgShutdownService.startShutdownTasks();
 }
 
-function updateProgressLabel(inTaskName)
-{
+function updateProgressLabel(inTaskName) {
   var curTaskLabel = document.getElementById("shutdownStatus_label");
   curTaskLabel.value = inTaskName;
 }
 
-function updateTaskProgressLabel(inCurTaskNum)
-{
+function updateTaskProgressLabel(inCurTaskNum) {
   var taskProgressLabel = document.getElementById("shutdownTask_label");
   taskProgressLabel.value = stringBundle.getFormattedString("taskProgress", [inCurTaskNum, numTasks]);
 }
 
-function updateProgressMeter(inPercent)
-{
-  var taskProgressmeter = document.getElementById('shutdown_progressmeter');
+function updateProgressMeter(inPercent) {
+  var taskProgressmeter = document.getElementById("shutdown_progressmeter");
   taskProgressmeter.value = inPercent;
 }
 
-function onCancel()
-{
+function onCancel() {
   msgShutdownService.cancelShutdownTasks();
 }
 
-function nsMsgShutdownTaskListener()
-{
+function nsMsgShutdownTaskListener() {
   msgShutdownService.setShutdownListener(this);
 }
 
 nsMsgShutdownTaskListener.prototype =
 {
   QueryInterface: ChromeUtils.generateQI(["nsIWebProgressListener",
                                           "nsISupportsWeakReference"]),
 
-  onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus)
-  {
-    if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP)
-    {
+  onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
+    if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
       window.close();
     }
   },
 
-  onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress)
-  {
+  onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
     updateProgressMeter(((aCurTotalProgress / aMaxTotalProgress) * 100));
     updateTaskProgressLabel(aCurTotalProgress + 1);
   },
 
-  onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags)
-  {
+  onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {
     // we can ignore this notification
   },
 
-  onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage)
-  {
+  onStatusChange(aWebProgress, aRequest, aStatus, aMessage) {
     if (aMessage)
       updateProgressLabel(aMessage);
   },
 
-  onSecurityChange: function(aWebProgress, aRequest, state)
-  {
-    // we can ignore this notification
-  }
-
-  onContentBlockingEvent: function(aWebProgress, aRequest, aEvent)
-  {
+  onSecurityChange(aWebProgress, aRequest, state) {
     // we can ignore this notification
   },
-}
+
+  onContentBlockingEvent(aWebProgress, aRequest, aEvent) {
+    // we can ignore this notification
+  },
+};
 
 var MsgShutdownTaskListener = new nsMsgShutdownTaskListener();
 
--- a/mailnews/base/content/subscribe.js
+++ b/mailnews/base/content/subscribe.js
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from ../../../mail/base/content/mailWindow.js */
+
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 var gSubscribeTree = null;
 var gSubscribeBody = null;
 var okCallback = null;
 var gChangeTable = {};
 var gServerURI = null;
 var gSubscribableServer = null;
@@ -16,25 +18,23 @@ var gStatusFeedback;
 var gSubscribeDeck = null;
 var gSearchView = null;
 var gSearchTree = null;
 var gSubscribeBundle;
 
 document.addEventListener("dialogaccept", subscribeOK);
 document.addEventListener("dialogcancel", subscribeCancel);
 
-function Stop()
-{
+function Stop() {
   if (gSubscribableServer) {
     gSubscribableServer.stopPopulating(msgWindow);
   }
 }
 
-function SetServerTypeSpecificTextValues()
-{
+function SetServerTypeSpecificTextValues() {
   if (!gServerURI)
     return;
 
   let serverType = MailUtils.getExistingFolder(gServerURI).server.type;
 
   // set the server specific ui elements
   let subscribeLabelString = gSubscribeBundle.getString("subscribeLabel-" + serverType);
   let currentListTab  = "currentListTab-" + serverType;
@@ -42,44 +42,41 @@ function SetServerTypeSpecificTextValues
   let currentListTabAccesskey = gSubscribeBundle.getString(currentListTab + ".accesskey");
 
   document.getElementById("currentListTab").setAttribute("label", currentListTabLabel);
   document.getElementById("currentListTab").setAttribute("accesskey", currentListTabAccesskey);
   document.getElementById("newGroupsTab").collapsed = (serverType != "nntp"); // show newGroupsTab only for nntp servers
   document.getElementById("subscribeLabel").setAttribute("value", subscribeLabelString);
 }
 
-function onServerClick(aFolder)
-{
+function onServerClick(aFolder) {
   gServerURI = aFolder.server.serverURI;
   let serverMenu = document.getElementById("serverMenu");
   serverMenu.menupopup.selectFolder(aFolder);
 
   SetServerTypeSpecificTextValues();
   ShowCurrentList();
 }
 
 var MySubscribeListener = {
-  OnDonePopulating: function() {
+  OnDonePopulating() {
     gStatusFeedback._stopMeteors();
     document.getElementById("stopButton").disabled = true;
     document.getElementById("refreshButton").disabled = false;
     document.getElementById("currentListTab").disabled = false;
     document.getElementById("newGroupsTab").disabled = false;
-  }
+  },
 };
 
-function SetUpTree(forceToServer, getOnlyNew)
-{
+function SetUpTree(forceToServer, getOnlyNew) {
   if (!gServerURI)
     return;
 
   var server = MailUtils.getExistingFolder(gServerURI).server;
-  try
-  {
+  try {
     CleanUpSearchView();
     gSubscribableServer = server.QueryInterface(Ci.nsISubscribableServer);
 
     // enable (or disable) the search related UI
     EnableSearchUI();
 
     // clear out the text field when switching server
     gNameField.value = "";
@@ -101,54 +98,47 @@ function SetUpTree(forceToServer, getOnl
     document.getElementById("refreshButton").disabled = true;
 
     gStatusFeedback._startMeteors();
     gStatusFeedback.setStatusString("");
     gStatusFeedback.showStatusString(gSubscribeBundle.getString("pleaseWaitString"));
     document.getElementById("stopButton").disabled = false;
 
     gSubscribableServer.startPopulating(msgWindow, forceToServer, getOnlyNew);
-  }
-  catch (e)
-  {
+  } catch (e) {
     if (e.result == 0x80550014) {  // NS_MSG_ERROR_OFFLINE
       gStatusFeedback.setStatusString(gSubscribeBundle.getString("offlineState"));
     } else {
       Cu.reportError("Failed to populate subscribe tree: " + e);
       gStatusFeedback.setStatusString(gSubscribeBundle.getString("errorPopulating"));
     }
     Stop();
   }
 }
 
 
-function SubscribeOnUnload()
-{
+function SubscribeOnUnload() {
   try {
     CleanUpSearchView();
-  }
-  catch (ex) {
+  } catch (ex) {
     dump("Failed to remove the subscribe tree: " + ex + "\n");
   }
 }
 
-function EnableSearchUI()
-{
+function EnableSearchUI() {
   if (gSubscribableServer.supportsSubscribeSearch) {
-    gNameField.removeAttribute('disabled');
-    gNameFieldLabel.removeAttribute('disabled');
-  }
-  else {
-    gNameField.setAttribute('disabled',true);
-    gNameFieldLabel.setAttribute('disabled',true);
+    gNameField.removeAttribute("disabled");
+    gNameFieldLabel.removeAttribute("disabled");
+  } else {
+    gNameField.setAttribute("disabled", true);
+    gNameFieldLabel.setAttribute("disabled", true);
   }
 }
 
-function SubscribeOnLoad()
-{
+function SubscribeOnLoad() {
   gSubscribeBundle = document.getElementById("bundle_subscribe");
 
   gSubscribeTree = document.getElementById("subscribeTree");
   gSubscribeBody = document.getElementById("subscribeTreeBody");
   gSearchTree = document.getElementById("searchTree");
   gSearchTree = document.getElementById("searchTree");
   gNameField = document.getElementById("namefield");
   gNameFieldLabel = document.getElementById("namefieldlabel");
@@ -177,105 +167,95 @@ function SubscribeOnLoad()
   if (folder && folder.server instanceof Ci.nsISubscribableServer) {
     serverMenu.menupopup.selectFolder(folder.server.rootMsgFolder);
     try {
       CleanUpSearchView();
       gSubscribableServer = folder.server.QueryInterface(Ci.nsISubscribableServer);
       // Enable (or disable) the search related UI.
       EnableSearchUI();
       gServerURI = folder.server.serverURI;
-    }
-    catch (ex) {
-      //dump("not a subscribable server\n");
+    } catch (ex) {
+      // dump("not a subscribable server\n");
       CleanUpSearchView();
       gSubscribableServer = null;
       gServerURI = null;
     }
   }
 
   if (!gServerURI) {
-    //dump("subscribe: no uri\n");
-    //dump("xxx todo:  use the default news server.  right now, I'm just using the first server\n");
+    // dump("subscribe: no uri\n");
+    // dump("xxx todo:  use the default news server.  right now, I'm just using the first server\n");
 
     serverMenu.selectedIndex = 0;
 
     if (serverMenu.selectedItem) {
       gServerURI = serverMenu.selectedItem.getAttribute("id");
-    }
-    else {
-      //dump("xxx todo none of your servers are subscribable\n");
-      //dump("xxx todo fix this by disabling subscribe if no subscribable server or, add a CREATE SERVER button, like in 4.x\n");
+    } else {
+      // dump("xxx todo none of your servers are subscribable\n");
+      // dump("xxx todo fix this by disabling subscribe if no subscribable server or, add a CREATE SERVER button, like in 4.x\n");
       return;
     }
   }
 
   SetServerTypeSpecificTextValues();
 
   ShowCurrentList();
 
   gNameField.focus();
 }
 
-function subscribeOK()
-{
+function subscribeOK() {
   if (top.okCallback) {
     top.okCallback(top.gChangeTable);
   }
   Stop();
   if (gSubscribableServer) {
     gSubscribableServer.subscribeCleanup();
   }
 }
 
-function subscribeCancel()
-{
+function subscribeCancel() {
   Stop();
   if (gSubscribableServer) {
     gSubscribableServer.subscribeCleanup();
   }
 }
 
-function SetState(name, state)
-{
+function SetState(name, state) {
   var changed = gSubscribableServer.setState(name, state);
   if (changed)
     StateChanged(name, state);
 }
 
-function StateChanged(name,state)
-{
+function StateChanged(name, state) {
   if (gServerURI in gChangeTable) {
     if (name in gChangeTable[gServerURI]) {
       var oldValue = gChangeTable[gServerURI][name];
       if (oldValue != state)
         delete gChangeTable[gServerURI][name];
-    }
-    else {
+    } else {
       gChangeTable[gServerURI][name] = state;
     }
-  }
-  else {
+  } else {
     gChangeTable[gServerURI] = {};
     gChangeTable[gServerURI][name] = state;
   }
 }
 
-function InSearchMode()
-{
+function InSearchMode() {
   // search is the second card in the deck
   return (gSubscribeDeck.getAttribute("selectedIndex") == "1");
 }
 
-function SearchOnClick(event)
-{
+function SearchOnClick(event) {
   // we only care about button 0 (left click) events
   if (event.button != 0 || event.originalTarget.localName != "treechildren") return;
 
   let treeCellInfo = gSearchTree.getCellAt(event.clientX, event.clientY);
-  if (treeCellInfo.row == -1 || treeCellInfo.row > gSearchView.rowCount-1)
+  if (treeCellInfo.row == -1 || treeCellInfo.row > gSearchView.rowCount - 1)
     return;
 
   if (treeCellInfo.col.id == "subscribedColumn2") {
     if (event.detail != 2) {
       // single clicked on the check box
       // (in the "subscribedColumn2" column) reverse state
       // if double click, do nothing
       ReverseStateFromRow(treeCellInfo.row);
@@ -284,206 +264,185 @@ function SearchOnClick(event)
     // double clicked on a row, reverse state
     ReverseStateFromRow(treeCellInfo.row);
   }
 
   // invalidate the row
   InvalidateSearchTreeRow(treeCellInfo.row);
 }
 
-function ReverseStateFromRow(aRow)
-{
+function ReverseStateFromRow(aRow) {
   // To determine if the row is subscribed or not,
   // we get the properties for the "subscribedColumn2" cell in the row
   // and look for the "subscribed" property.
   // If the "subscribed" string is in the list of properties
   // we are subscribed.
-  let col = gSearchTree.columns["nameColumn2"];
+  let col = gSearchTree.columns.nameColumn2;
   let name = gSearchView.getCellValue(aRow, col);
   let isSubscribed = gSubscribableServer.isSubscribed(name);
   SetStateFromRow(aRow, !isSubscribed);
 }
 
-function SetStateFromRow(row, state)
-{
-  var col = gSearchTree.columns["nameColumn2"];
+function SetStateFromRow(row, state) {
+  var col = gSearchTree.columns.nameColumn2;
   var name = gSearchView.getCellValue(row, col);
   SetState(name, state);
 }
 
-function SetSubscribeState(state)
-{
+function SetSubscribeState(state) {
   try {
     // we need to iterate over the tree selection, and set the state for
     // all rows in the selection
     var inSearchMode = InSearchMode();
     var view = inSearchMode ? gSearchView : gSubscribeTree.view;
     var colId = inSearchMode ? "nameColumn2" : "nameColumn";
 
     var sel = view.selection;
     for (var i = 0; i < sel.getRangeCount(); ++i) {
       var start = {}, end = {};
       sel.getRangeAt(i, start, end);
       for (var k = start.value; k <= end.value; ++k) {
-        if (inSearchMode)
+        if (inSearchMode) {
           SetStateFromRow(k, state);
-        else {
+        } else {
           let name = view.getCellValue(k, gSubscribeTree.columns[colId]);
           SetState(name, state, k);
         }
       }
     }
 
     if (inSearchMode) {
       // force a repaint
       InvalidateSearchTree();
     }
-  }
-  catch (ex) {
+  } catch (ex) {
     dump("SetSubscribedState failed:  " + ex + "\n");
   }
 }
 
-function ReverseStateFromNode(row)
-{
-  let name = gSubscribeTree.view.getCellValue(row, gSubscribeTree.columns["nameColumn"]);
+function ReverseStateFromNode(row) {
+  let name = gSubscribeTree.view.getCellValue(row, gSubscribeTree.columns.nameColumn);
   SetState(name, !gSubscribableServer.isSubscribed(name), row);
 }
 
-function SubscribeOnClick(event)
-{
+function SubscribeOnClick(event) {
   // we only care about button 0 (left click) events
   if (event.button != 0 || event.originalTarget.localName != "treechildren")
    return;
 
   let treeCellInfo = gSubscribeTree.getCellAt(event.clientX, event.clientY);
   if (treeCellInfo.row == -1 || treeCellInfo.row > (gSubscribeTree.view.rowCount - 1))
     return;
 
   if (event.detail == 2) {
     // only toggle subscribed state when double clicking something
     // that isn't a container
     if (!gSubscribeTree.view.isContainer(treeCellInfo.row)) {
       ReverseStateFromNode(treeCellInfo.row);
-      return;
     }
-  }
-  else if (event.detail == 1)
-  {
+  } else if (event.detail == 1) {
     // if the user single clicks on the subscribe check box, we handle it here
     if (treeCellInfo.col.id == "subscribedColumn")
       ReverseStateFromNode(treeCellInfo.row);
   }
 }
 
-function Refresh()
-{
+function Refresh() {
   // clear out the textfield's entry
   gNameField.value = "";
 
   var newGroupsTab = document.getElementById("newGroupsTab");
   SetUpTree(true, newGroupsTab.selected);
 }
 
-function ShowCurrentList()
-{
+function ShowCurrentList() {
   // clear out the textfield's entry on call of Refresh()
   gNameField.value = "";
 
   // make sure the current list tab is selected
   document.getElementById("subscribeTabs").selectedIndex = 0;
 
   // try loading the hostinfo before talk to server
   SetUpTree(false, false);
 }
 
-function ShowNewGroupsList()
-{
+function ShowNewGroupsList() {
   // clear out the textfield's entry
   gNameField.value = "";
 
   // make sure the new groups tab is selected
   document.getElementById("subscribeTabs").selectedIndex = 1;
 
   // force it to talk to the server and get new groups
   SetUpTree(true, true);
 }
 
-function InvalidateSearchTreeRow(row)
-{
-    gSearchTree.invalidateRow(row);
+function InvalidateSearchTreeRow(row) {
+  gSearchTree.invalidateRow(row);
 }
 
-function InvalidateSearchTree()
-{
-    gSearchTree.invalidate();
+function InvalidateSearchTree() {
+  gSearchTree.invalidate();
 }
 
-function SwitchToNormalView()
-{
+function SwitchToNormalView() {
   // the first card in the deck is the "normal" view
-  gSubscribeDeck.setAttribute("selectedIndex","0");
+  gSubscribeDeck.setAttribute("selectedIndex", "0");
 }
 
-function SwitchToSearchView()
-{
+function SwitchToSearchView() {
   // the second card in the deck is the "search" view
-  gSubscribeDeck.setAttribute("selectedIndex","1");
+  gSubscribeDeck.setAttribute("selectedIndex", "1");
 }
 
-function Search()
-{
+function Search() {
   var searchValue = gNameField.value;
   if (searchValue.length && gSubscribableServer.supportsSubscribeSearch) {
     SwitchToSearchView();
     gSubscribableServer.setSearchValue(searchValue);
 
     if (!gSearchView && gSubscribableServer) {
     gSearchView = gSubscribableServer.QueryInterface(Ci.nsITreeView);
       gSearchView.selection = null;
     gSearchTree.view = gSearchView;
   }
-  }
-  else {
+  } else {
     SwitchToNormalView();
   }
 }
 
-function CleanUpSearchView()
-{
+function CleanUpSearchView() {
   if (gSearchView) {
     gSearchView.selection = null;
     gSearchView = null;
   }
 }
 
-function onSearchTreeKeyPress(event)
-{
+function onSearchTreeKeyPress(event) {
   // for now, only do something on space key
   if (event.charCode != KeyEvent.DOM_VK_SPACE)
     return;
 
   var treeSelection = gSearchView.selection;
-  for (var i=0;i<treeSelection.getRangeCount();i++) {
+  for (let i = 0; i < treeSelection.getRangeCount(); i++) {
     var start = {}, end = {};
-    treeSelection.getRangeAt(i,start,end);
-    for (var k=start.value;k<=end.value;k++)
+    treeSelection.getRangeAt(i, start, end);
+    for (let k = start.value; k <= end.value; k++)
       ReverseStateFromRow(k);
 
     // force a repaint
     InvalidateSearchTree();
   }
 }
 
-function onSubscribeTreeKeyPress(event)
-{
+function onSubscribeTreeKeyPress(event) {
   // for now, only do something on space key
   if (event.charCode != KeyEvent.DOM_VK_SPACE)
     return;
 
   var treeSelection = gSubscribeTree.view.selection;
-  for (var i=0;i<treeSelection.getRangeCount();i++) {
+  for (let i = 0; i < treeSelection.getRangeCount(); i++) {
     var start = {}, end = {};
-    treeSelection.getRangeAt(i,start,end);
-    for (var k=start.value;k<=end.value;k++)
+    treeSelection.getRangeAt(i, start, end);
+    for (let k = start.value; k <= end.value; k++)
       ReverseStateFromNode(k);
   }
 }
--- a/mailnews/base/content/virtualFolderListEdit.js
+++ b/mailnews/base/content/virtualFolderListEdit.js
@@ -1,61 +1,63 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from ../../../mail/base/content/folderPane.js */
+
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 var gSelectVirtual = {
   _treeElement: null,
   _selectedList: new Set(),
 
-  load: function() {
+  load() {
     if (window.arguments[0].searchFolderURIs) {
-      let srchFolderUriArray = window.arguments[0].searchFolderURIs.split('|');
+      let srchFolderUriArray = window.arguments[0].searchFolderURIs.split("|");
       for (let uri of srchFolderUriArray) {
         this._selectedList.add(MailUtils.getOrCreateFolder(uri));
       }
     }
 
     // Now tweak the folder tree for our purposes here.
     let oldProps = ftvItem.prototype.getProperties;
     ftvItem.prototype.getProperties = function(aColumn) {
       if (!aColumn || aColumn.id != "selectedCol")
         return oldProps.call(this, aColumn);
 
       let properties = "selectedColumn";
       if (gSelectVirtual._selectedList.has(this._folder))
         properties += " selected-true";
 
       return properties;
-    }
+    };
 
     let modeVirtual = {
       __proto__: IFolderTreeMode,
 
-      generateMap: function(ftv) {
+      generateMap(ftv) {
         let accounts = gFolderTreeView._sortedAccounts();
         // Force each root folder to do its local subfolder discovery.
         MailUtils.discoverFolders();
         let filterVirtual = function(aFolder) {
           return !aFolder.getFlag(Ci.nsMsgFolderFlags.Virtual);
-        }
+        };
         return accounts.map(acct => new ftvItem(acct.incomingServer.rootFolder,
                                                 filterVirtual));
-      }
+      },
     };
     this._treeElement = document.getElementById("folderPickerTree");
 
     gFolderTreeView.registerFolderTreeMode(this._treeElement.getAttribute("mode"),
                                            modeVirtual, "Virtual Folders");
     gFolderTreeView.load(this._treeElement);
   },
 
-  onKeyPress: function(aEvent) {
+  onKeyPress(aEvent) {
     // For now, only do something on space key.
     if (aEvent.charCode != aEvent.DOM_VK_SPACE)
       return;
 
     let selection = this._treeElement.view.selection;
     let start = {};
     let end = {};
     let numRanges = selection.getRangeCount();
@@ -63,46 +65,46 @@ var gSelectVirtual = {
     for (let range = 0; range < numRanges; range++) {
       selection.getRangeAt(range, start, end);
       for (let i = start.value; i <= end.value; i++) {
         this._toggle(i);
       }
     }
   },
 
-  onClick: function(aEvent) {
+  onClick(aEvent) {
     // We only care about button 0 (left click) events.
     if (aEvent.button != 0)
       return;
 
     let treeCellInfo = this._treeElement.getCellAt(aEvent.clientX, aEvent.clientY);
     if (treeCellInfo.row == -1 || treeCellInfo.col.id != "selectedCol")
       return;
 
     this._toggle(treeCellInfo.row);
   },
 
-  _toggle: function(aRow) {
+  _toggle(aRow) {
     let folder = gFolderTreeView._rowMap[aRow]._folder;
     if (this._selectedList.has(folder))
       this._selectedList.delete(folder);
     else
       this._selectedList.add(folder);
 
     gFolderTreeView._tree.invalidateRow(aRow);
   },
 
-  onAccept: function() {
+  onAccept() {
     gFolderTreeView.unload();
     // XXX We should just pass the folder objects around...
     let uris = [...this._selectedList.values()].map(folder => folder.URI).join("|");
 
     if (window.arguments[0].okCallback)
       window.arguments[0].okCallback(uris);
   },
 
-  onCancel: function() {
+  onCancel() {
     gFolderTreeView.unload();
-  }
+  },
 };
 
 document.addEventListener("dialogaccept", gSelectVirtual.onAccept);
 document.addEventListener("dialogcancel", gSelectVirtual.onCancel);
--- a/mailnews/base/content/virtualFolderProperties.js
+++ b/mailnews/base/content/virtualFolderProperties.js
@@ -1,13 +1,15 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from ../search/content/searchTerm.js */
+
 var gPickedFolder;
 var gMailView = null;
 var msgWindow; // important, don't change the name of this variable. it's really a global used by commandglue.js
 var gSearchTermSession; // really an in memory temporary filter we use to read in and write out the search terms
 var gSearchFolderURIs = "";
 var gMessengerBundle = null;
 
 var nsMsgSearchScope = Ci.nsMsgSearchScope;
@@ -18,60 +20,54 @@ var {MailServices} = ChromeUtils.import(
 var {
   VirtualFolderHelper,
 } = ChromeUtils.import("resource:///modules/virtualFolderWrapper.js");
 var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 document.addEventListener("dialogaccept", onOK);
 
-function onLoad()
-{
+function onLoad() {
   var windowArgs = window.arguments[0];
   var acceptButton = document.documentElement.getButton("accept");
 
   gMessengerBundle = document.getElementById("bundle_messenger");
 
   // call this when OK is pressed
   msgWindow = windowArgs.msgWindow;
 
   initializeSearchWidgets();
 
   setSearchScope(nsMsgSearchScope.offlineMail);
-  if (windowArgs.editExistingFolder)
-  {
+  if (windowArgs.editExistingFolder) {
     acceptButton.label =
         document.documentElement.getAttribute("editFolderAcceptButtonLabel");
     acceptButton.accesskey =
         document.documentElement.getAttribute("editFolderAcceptButtonAccessKey");
     InitDialogWithVirtualFolder(windowArgs.folder);
-  }
-  else // we are creating a new virtual folder
-  {
+  } else { // we are creating a new virtual folder
     acceptButton.label =
         document.documentElement.getAttribute("newFolderAcceptButtonLabel");
     acceptButton.accesskey =
         document.documentElement.getAttribute("newFolderAcceptButtonAccessKey");
     // it is possible that we were given arguments to pre-fill the dialog with...
     gSearchTermSession = Cc["@mozilla.org/messenger/searchSession;1"]
                            .createInstance(Ci.nsIMsgSearchSession);
 
-    if (windowArgs.searchTerms) // then add them to our search session
-    {
+    if (windowArgs.searchTerms) { // then add them to our search session
       for (let searchTerm of fixIterator(windowArgs.searchTerms,
                                          Ci.nsIMsgSearchTerm))
         gSearchTermSession.appendTerm(searchTerm);
     }
-    if (windowArgs.folder)
-    {
+    if (windowArgs.folder) {
       // pre select the folderPicker, based on what they selected in the folder pane
       gPickedFolder = windowArgs.folder;
       try {
         document.getElementById("msgNewFolderPopup").selectFolder(windowArgs.folder);
-      } catch(ex) {
+      } catch (ex) {
         document.getElementById("msgNewFolderPicker")
                 .setAttribute("label", windowArgs.folder.prettyName);
       }
 
       // if the passed in URI is not a server then pre-select it as the folder to search
       if (!windowArgs.folder.isServer)
         gSearchFolderURIs = windowArgs.folder.URI;
     }
@@ -84,63 +80,58 @@ function onLoad()
     if (windowArgs.searchFolderURIs)
       gSearchFolderURIs = windowArgs.searchFolderURIs;
 
     setupSearchRows(gSearchTermSession.searchTerms);
     doEnabling(); // we only need to disable/enable the OK button for new virtual folders
   }
 
   if (typeof windowArgs.searchOnline != "undefined")
-    document.getElementById('searchOnline').checked = windowArgs.searchOnline;
+    document.getElementById("searchOnline").checked = windowArgs.searchOnline;
   updateOnlineSearchState();
   updateFoldersCount();
 }
 
-function setupSearchRows(aSearchTerms)
-{
+function setupSearchRows(aSearchTerms) {
   if (aSearchTerms && aSearchTerms.length > 0)
-    initializeSearchRows(nsMsgSearchScope.offlineMail, aSearchTerms); // load the search terms for the folder
+    initializeSearchRows(Ci.nsMsgSearchScope.offlineMail, aSearchTerms); // load the search terms for the folder
   else
     onMore(null);
 }
 
-function updateOnlineSearchState()
-{
+function updateOnlineSearchState() {
   var enableCheckbox = false;
-  var checkbox = document.getElementById('searchOnline');
+  var checkbox = document.getElementById("searchOnline");
   // only enable the checkbox for selection, for online servers
-  var srchFolderUriArray = gSearchFolderURIs.split('|');
-  if (srchFolderUriArray[0])
-  {
+  var srchFolderUriArray = gSearchFolderURIs.split("|");
+  if (srchFolderUriArray[0]) {
     var realFolder = MailUtils.getOrCreateFolder(srchFolderUriArray[0]);
-    enableCheckbox =  realFolder.server.offlineSupportLevel; // anything greater than 0 is an online server like IMAP or news
+    enableCheckbox = realFolder.server.offlineSupportLevel; // anything greater than 0 is an online server like IMAP or news
   }
 
-  if (enableCheckbox)
-    checkbox.removeAttribute('disabled');
-  else
-  {
-    checkbox.setAttribute('disabled', true);
+  if (enableCheckbox) {
+    checkbox.removeAttribute("disabled");
+  } else {
+    checkbox.setAttribute("disabled", true);
     checkbox.checked = false;
   }
 }
 
-function InitDialogWithVirtualFolder(aVirtualFolder)
-{
+function InitDialogWithVirtualFolder(aVirtualFolder) {
   let virtualFolderWrapper =
     VirtualFolderHelper.wrapVirtualFolder(window.arguments[0].folder);
 
   // when editing an existing folder, hide the folder picker that stores the parent location of the folder
   document.getElementById("chooseFolderLocationRow").collapsed = true;
   let folderNameField = document.getElementById("existingName");
   folderNameField.hidden = false;
 
   gSearchFolderURIs = virtualFolderWrapper.searchFolderURIs;
   updateFoldersCount();
-  document.getElementById('searchOnline').checked = virtualFolderWrapper.onlineSearch;
+  document.getElementById("searchOnline").checked = virtualFolderWrapper.onlineSearch;
   gSearchTermSession = virtualFolderWrapper.searchTermsSession;
 
   setupSearchRows(gSearchTermSession.searchTerms);
 
   // set the name of the folder
   let folderBundle = document.getElementById("bundle_folder");
   let name = folderBundle.getFormattedString("verboseFolderFormat",
                [aVirtualFolder.prettyName, aVirtualFolder.server.prettyName]);
@@ -151,31 +142,28 @@ function InitDialogWithVirtualFolder(aVi
 }
 
 function onFolderPick(aEvent) {
   gPickedFolder = aEvent.target._folder;
   document.getElementById("msgNewFolderPopup")
           .selectFolder(gPickedFolder);
 }
 
-function onOK(event)
-{
+function onOK(event) {
   var name = document.getElementById("name").value;
-  var searchOnline = document.getElementById('searchOnline').checked;
+  var searchOnline = document.getElementById("searchOnline").checked;
 
-  if (!gSearchFolderURIs)
-  {
+  if (!gSearchFolderURIs) {
     Services.prompt.alert(window, null,
-                          gMessengerBundle.getString('alertNoSearchFoldersSelected'));
+                          gMessengerBundle.getString("alertNoSearchFoldersSelected"));
     event.preventDefault();
     return;
   }
 
-  if (window.arguments[0].editExistingFolder)
-  {
+  if (window.arguments[0].editExistingFolder) {
     // update the search terms
     saveSearchTerms(gSearchTermSession.searchTerms, gSearchTermSession);
     // save the settings
     let virtualFolderWrapper =
       VirtualFolderHelper.wrapVirtualFolder(window.arguments[0].folder);
     virtualFolderWrapper.searchTerms = gSearchTermSession.searchTerms;
     virtualFolderWrapper.searchFolders = gSearchFolderURIs;
     virtualFolderWrapper.onlineSearch = searchOnline;
@@ -183,73 +171,67 @@ function onOK(event)
 
     MailServices.accounts.saveVirtualFolders();
 
     if (window.arguments[0].onOKCallback)
       window.arguments[0].onOKCallback(virtualFolderWrapper.virtualFolder.URI);
     return;
   }
   var uri = gPickedFolder.URI;
-  if (name && uri) // create a new virtual folder
-  {
+  if (name && uri) { // create a new virtual folder
     // check to see if we already have a folder with the same name and alert the user if so...
     var parentFolder = MailUtils.getOrCreateFolder(uri);
 
     // sanity check the name based on the logic used by nsMsgBaseUtils.cpp. It can't start with a '.', it can't end with a '.', '~' or ' '.
     // it can't contain a ';' or '#'.
-    if (/^\.|[\.\~ ]$|[\;\#]/.test(name))
-    {
+    if (/^\.|[\.\~ ]$|[\;\#]/.test(name)) {
       Services.prompt.alert(window, null,
                             gMessengerBundle.getString("folderCreationFailed"));
       event.preventDefault();
       return;
-    }
-    else if (parentFolder.containsChildNamed(name))
-    {
+    } else if (parentFolder.containsChildNamed(name)) {
       Services.prompt.alert(window, null,
                             gMessengerBundle.getString("folderExists"));
       event.preventDefault();
       return;
     }
 
     saveSearchTerms(gSearchTermSession.searchTerms, gSearchTermSession);
     VirtualFolderHelper.createNewVirtualFolder(name, parentFolder, gSearchFolderURIs,
                                                gSearchTermSession.searchTerms,
                                                searchOnline);
   }
 }
 
-function doEnabling()
-{
+function doEnabling() {
   var acceptButton = document.documentElement.getButton("accept");
   acceptButton.disabled = !document.getElementById("name").value;
 }
 
-function chooseFoldersToSearch()
-{
+function chooseFoldersToSearch() {
   // if we have some search folders already, then root the folder picker dialog off the account
   // for those folders. Otherwise fall back to the preselectedfolderURI which is the parent folder
   // for this new virtual folder.
-  var dialog = window.openDialog("chrome://messenger/content/virtualFolderListEdit.xul", "",
-                                 "chrome,titlebar,modal,centerscreen,resizable",
-                                 {searchFolderURIs:gSearchFolderURIs,
-                                  okCallback:onFolderListDialogCallback});
+  window.openDialog("chrome://messenger/content/virtualFolderListEdit.xul", "",
+                    "chrome,titlebar,modal,centerscreen,resizable",
+                    {
+                      searchFolderURIs: gSearchFolderURIs,
+                      okCallback: onFolderListDialogCallback,
+                    });
 }
 
 // callback routine from chooseFoldersToSearch
-function onFolderListDialogCallback(searchFolderURIs)
-{
+function onFolderListDialogCallback(searchFolderURIs) {
   gSearchFolderURIs = searchFolderURIs;
   updateFoldersCount();
   updateOnlineSearchState(); // we may have changed the server type we are searching...
 }
 
-function updateFoldersCount()
-{
-  let srchFolderUriArray = gSearchFolderURIs.split('|');
+function updateFoldersCount() {
+  let srchFolderUriArray = gSearchFolderURIs.split("|");
   let folderCount = gSearchFolderURIs ? srchFolderUriArray.length : 0;
   let foldersList = document.getElementById("chosenFoldersCount");
   foldersList.textContent =
     PluralForm.get(folderCount, gMessengerBundle.getString("virtualFolderSourcesChosen"))
               .replace("#1", folderCount);
   if (folderCount > 0) {
     let folderNames = [];
     for (let folderURI of srchFolderUriArray) {
@@ -259,13 +241,12 @@ function updateFoldersCount()
       folderNames.push(name);
     }
     foldersList.setAttribute("tooltiptext", folderNames.join("\n"));
   } else {
     foldersList.removeAttribute("tooltiptext");
   }
 }
 
-function onEnterInSearchTerm()
-{
+function onEnterInSearchTerm() {
   // stub function called by the core search widget code...
   // nothing for us to do here
 }
--- a/mailnews/base/prefs/content/AccountManager.js
+++ b/mailnews/base/prefs/content/AccountManager.js
@@ -20,16 +20,20 @@
  * - the card containing the relevant page is brought to the front
  * - each form element in the page is filled in with an appropriate value
  *   from the current account's hashtable
  * - in the IFRAME inside the page, if there is an onInit() method,
  *   it is called. The onInit method can further update this page based
  *   on values set in the previous step.
  */
 
+/* import-globals-from accountUtils.js */
+/* import-globals-from am-prefs.js */
+/* import-globals-from amUtils.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {BrowserUtils} = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm");
 var {Gloda} = ChromeUtils.import("resource:///modules/gloda/gloda.js");
 var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 var {allAccountsSorted} = ChromeUtils.import("resource:///modules/folderUtils.jsm");
 var {cleanUpHostName, isLegalHostNameOrIP} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
 
@@ -84,38 +88,37 @@ var gDangerousLocalStorageDirs = [
   { dirsvc: "Trsh",     OS: "Darwin" },
   // Mac OS system folder
   { dir:    "/System",  OS: "Darwin" },
   // devices folder
   { dir:    "/dev",     OS: "Darwin,Linux" },
   // process info folder
   { dir:    "/proc",    OS: "Linux" },
   // system state folder
-  { dir:    "/sys",     OS: "Linux" }
+  { dir:    "/sys",     OS: "Linux" },
 ];
 
 // This sets an attribute in a xul element so that we can later
 // know what value to substitute in a prefstring.  Different
 // preference types set different attributes.  We get the value
 // in the same way as the function getAccountValue() determines it.
 function updateElementWithKeys(account, element, type) {
-  switch (type)
-  {
+  switch (type) {
     case "identity":
-      element["identitykey"] = account.defaultIdentity.key;
+      element.identitykey = account.defaultIdentity.key;
       break;
     case "pop3":
     case "imap":
     case "nntp":
     case "server":
-      element["serverkey"] = account.incomingServer.key;
+      element.serverkey = account.incomingServer.key;
       break;
     case "smtp":
       if (MailServices.smtp.defaultServer)
-        element["serverkey"] = MailServices.smtp.defaultServer.key;
+        element.serverkey = MailServices.smtp.defaultServer.key;
       break;
     default:
 //      dump("unknown element type! "+type+"\n");
   }
 }
 
 function hideShowControls(serverType) {
   let controls = document.querySelectorAll("[hidefor]");
@@ -149,34 +152,33 @@ function onLoad() {
   // Arguments can have two properties: (1) "server," the nsIMsgIncomingServer
   // to select initially and (2) "selectPage," the page for that server to that
   // should be selected.
   if ("arguments" in window && window.arguments[0]) {
     selectedServer = window.arguments[0].server;
     selectPage = window.arguments[0].selectPage;
   }
 
-  accountArray = new Object();
-  gGenericAttributeTypes = new Object();
+  accountArray = {};
+  gGenericAttributeTypes = {};
 
   gAccountTree.load();
 
   setTimeout(selectServer, 0, selectedServer, selectPage);
 
   // Make sure the account manager window fits the screen.
   document.getElementById("accountManager").style.maxHeight =
     (window.screen.availHeight - 30) + "px";
 }
 
 function onUnload() {
   gAccountTree.unload();
 }
 
-function selectServer(server, selectPageId)
-{
+function selectServer(server, selectPageId) {
   let childrenNode = document.getElementById("account-tree-children");
 
   // Default to showing the first account.
   let accountNode = childrenNode.firstChild;
 
   // Find the tree-node for the account we want to select
   if (server) {
     for (let i = 0; i < childrenNode.childNodes.length; i++) {
@@ -209,18 +211,17 @@ function selectServer(server, selectPage
 
   let lastItem = accountNode.lastChild.lastChild;
   if (lastItem.localName == "treeitem")
     index = accountTree.view.getIndexOfItem(lastItem);
 
   accountTree.ensureRowIsVisible(index);
 }
 
-function replaceWithDefaultSmtpServer(deletedSmtpServerKey)
-{
+function replaceWithDefaultSmtpServer(deletedSmtpServerKey) {
   // First we replace the smtpserverkey in every identity.
   let am = MailServices.accounts;
   for (let identity of fixIterator(am.allIdentities,
                                    Ci.nsIMsgIdentity)) {
     if (identity.smtpServerKey == deletedSmtpServerKey)
       identity.smtpServerKey = "";
   }
 
@@ -257,18 +258,18 @@ function onAccept(aDoChecks) {
     if (!checkUserServerChanges(true))
       return false;
 
     if (!checkAccountNameIsValid())
       return false;
   }
 
   // Run checks as if the page was being left.
-  if ("onLeave" in top.frames["contentFrame"]) {
-    if (!top.frames["contentFrame"].onLeave()) {
+  if ("onLeave" in top.frames.contentFrame) {
+    if (!top.frames.contentFrame.onLeave()) {
       // Prevent closing Account manager if user declined the changes.
       return false;
     }
   }
 
   if (!onSave())
     return false;
 
@@ -285,18 +286,17 @@ function onAccept(aDoChecks) {
 }
 
 /**
  * Runs when Cancel button is used.
  *
  * This function must not be called onCancel(), because it would call itself
  * recursively for pages that don't have an onCancel() implementation.
  */
-function onNotAccept(event)
-{
+function onNotAccept(event) {
   // If onCancel() present in current page frame, call it.
   if ("onCancel" in top.frames.contentFrame) {
     top.frames.contentFrame.onCancel(event);
   }
 }
 
 /**
  * See if the given path to a directory is usable on the current OS.
@@ -317,17 +317,17 @@ function checkDirectoryIsValid(aLocalPat
   if (Services.appinfo.OS == "WINNT") {
     // Do not allow some special filenames on Windows.
     // Taken from mozilla/widget/windows/nsDataObj.cpp::MangleTextToValidFilename()
     let dirLeafName = aLocalPath.leafName;
     const kForbiddenNames = [
       "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
       "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
       "CON", "PRN", "AUX", "NUL", "CLOCK$" ];
-    if (kForbiddenNames.indexOf(dirLeafName) != -1)
+    if (kForbiddenNames.includes(dirLeafName))
       return false;
   }
 
   // The directory must be readable and writable to work as a mail store.
   if (!(aLocalPath.isReadable() && aLocalPath.isWritable()))
     return false;
 
   return true;
@@ -356,33 +356,32 @@ function checkDirectoryIsAllowed(aLocalP
    *                       Darwin = OS X
    *                       Linux  = Linux
    *        safeSubdirs : An array of directory names that are allowed to be used
    *                      under the tested directory.
    * @param aLocalPath  An nsIFile of the directory to check, intended for message storage.
    */
   function checkLocalDirectoryIsSafe(aDirToCheck, aLocalPath) {
     if (aDirToCheck.OS) {
-      if (aDirToCheck.OS.split(",").indexOf(Services.appinfo.OS) == -1)
+      if (!(aDirToCheck.OS.split(",").includes(Services.appinfo.OS)))
         return true;
     }
 
     let testDir = null;
     if ("dirsvc" in aDirToCheck) {
       try {
         testDir = Services.dirsvc.get(aDirToCheck.dirsvc, Ci.nsIFile);
       } catch (e) {
         Cu.reportError("The special folder " + aDirToCheck.dirsvc +
           " cannot be retrieved on this platform: " + e);
       }
 
       if (!testDir)
         return true;
-    }
-    else if ("dir" in aDirToCheck) {
+    } else if ("dir" in aDirToCheck) {
       testDir = Cc["@mozilla.org/file/local;1"]
                   .createInstance(Ci.nsIFile);
       testDir.initWithPath(aDirToCheck.dir);
       if (!testDir.exists())
         return true;
     } else {
       Cu.reportError("No directory to check?");
       return true;
@@ -442,17 +441,17 @@ function checkDirectoryIsAllowed(aLocalP
  * aLocalPath  the nsIFile of a directory to check.
  */
 function checkDirectoryIsUsable(aLocalPath) {
   const kAlertTitle = document.getElementById("bundle_prefs")
                               .getString("prefPanel-server");
   const originalPath = aLocalPath;
 
   let invalidPath = false;
-  try{
+  try {
     aLocalPath.normalize();
   } catch (e) { invalidPath = true; }
 
   if (invalidPath || !checkDirectoryIsValid(aLocalPath)) {
     let alertString = document.getElementById("bundle_prefs")
                               .getFormattedString("localDirectoryInvalid",
                                                   [originalPath.path]);
     Services.prompt.alert(window, kAlertTitle, alertString);
@@ -466,18 +465,17 @@ function checkDirectoryIsUsable(aLocalPa
     Services.prompt.alert(window, kAlertTitle, alertNotAllowed);
     return false;
   }
 
   // Check that no other account has this same or dependent local directory.
   let allServers = MailServices.accounts.allServers;
 
   for (let server of fixIterator(allServers,
-                                 Ci.nsIMsgIncomingServer))
-  {
+                                 Ci.nsIMsgIncomingServer)) {
     if (server.key == currentAccount.incomingServer.key)
       continue;
 
     let serverPath = server.localPath;
     try {
       serverPath.normalize();
       let alertStringID = null;
       if (serverPath.equals(aLocalPath))
@@ -519,17 +517,17 @@ function checkUserServerChanges(showAler
 
   var accountValues = getValueArrayFor(currentAccount);
   if (!accountValues)
     return true;
 
   let currentServer = currentAccount ? currentAccount.incomingServer : null;
 
   // If this type doesn't exist (just removed) then return.
-  if (!("server" in accountValues) || !accountValues["server"])
+  if (!("server" in accountValues) || !accountValues.server)
     return true;
 
   // Get the new username, hostname and type from the page.
   var typeElem = getPageFormElement("server.type");
   var hostElem = getPageFormElement("server.realHostName");
   var userElem = getPageFormElement("server.realUsername");
   if (typeElem && userElem && hostElem) {
   var newType = getFormElementValue(typeElem);
@@ -548,21 +546,19 @@ function checkUserServerChanges(showAler
   }
   alertText = null;
   // If something is changed then check if the new user/host already exists.
   if ((oldUser != newUser) || (oldHost != newHost)) {
     newUser = newUser.trim();
     newHost = cleanUpHostName(newHost);
     if (checkUser && (newUser == "")) {
       alertText = prefBundle.getString("userNameEmpty");
-    }
-    else if (!isLegalHostNameOrIP(newHost)) {
+    } else if (!isLegalHostNameOrIP(newHost)) {
       alertText = prefBundle.getString("enterValidServerName");
-    }
-    else {
+    } else {
       let sameServer = MailServices.accounts
                                    .findRealServer(newUser, newHost, newType, 0);
       if (sameServer && (sameServer != currentServer)) {
         alertText = prefBundle.getString("modifiedAccountExists");
       } else {
         // New hostname passed all checks. We may have cleaned it up so set
         // the new value back into the input element.
         setFormElementValue(hostElem, newHost);
@@ -686,23 +682,21 @@ function onSave() {
 
  return true;
 }
 
 function onAddAccount() {
   MsgAccountWizard();
 }
 
-function AddMailAccount()
-{
+function AddMailAccount() {
   NewMailAccount(MailServices.mailSession.topmostMsgWindow);
 }
 
-function AddIMAccount()
-{
+function AddIMAccount() {
   window.openDialog("chrome://messenger/content/chat/imAccountWizard.xul",
                     "", "chrome,modal,titlebar,centerscreen");
 }
 
 /**
  * Highlight the default account row in the account tree,
  * optionally un-highlight the previous one.
  *
@@ -783,17 +777,17 @@ function onRemoveAccount(event) {
     return;
 
   let serverList = [];
   let accountTreeNode = document.getElementById("account-tree-children");
   // build the list of servers in the account tree (order is important)
   for (let i = 0; i < accountTreeNode.childNodes.length; i++) {
     if ("_account" in accountTreeNode.childNodes[i]) {
       let curServer = accountTreeNode.childNodes[i]._account.incomingServer;
-      if (serverList.indexOf(curServer) == -1)
+      if (!serverList.includes(curServer))
         serverList.push(curServer);
     }
   }
 
   // get position of the current server in the server list
   let serverIndex = serverList.indexOf(server);
 
   // After the current server is deleted, choose the next server/account,
@@ -802,18 +796,21 @@ function onRemoveAccount(event) {
     serverIndex--;
   else
     serverIndex++;
 
   // Need to save these before the account and its server is removed.
   let serverId = server.serverURI;
 
   // Confirm account deletion.
-  let removeArgs = { server: server, account: currentAccount,
-                     result: false };
+  let removeArgs = {
+    server,
+    account: currentAccount,
+    result: false,
+  };
 
   window.openDialog("chrome://messenger/content/removeAccount.xul",
                     "removeAccount",
                     "chrome,titlebar,modal,centerscreen,resizable=no",
                     removeArgs);
 
   // If result is true, the account was removed.
   if (!removeArgs.result)
@@ -829,51 +826,50 @@ function onRemoveAccount(event) {
     selectServer(serverList[serverIndex], null);
 
   // Either the default account was deleted so there is a new one
   // or the default account was not changed. Either way, there is
   // no need to unmark the old one.
   markDefaultServer(MailServices.accounts.defaultAccount, null);
 }
 
-function saveAccount(accountValues, account)
-{
+function saveAccount(accountValues, account) {
   var identity = null;
   var server = null;
 
   if (account) {
     identity = account.defaultIdentity;
     server = account.incomingServer;
   }
 
   for (var type in accountValues) {
     var typeArray = accountValues[type];
 
     for (var slot in typeArray) {
       var dest;
       try {
-      if (type == "identity")
-        dest = identity;
-      else if (type == "server")
-        dest = server;
-      else if (type == "pop3")
-        dest = server.QueryInterface(Ci.nsIPop3IncomingServer);
-      else if (type == "imap")
-        dest = server.QueryInterface(Ci.nsIImapIncomingServer);
-      else if (type == "none")
-        dest = server.QueryInterface(Ci.nsINoIncomingServer);
-      else if (type == "nntp")
-        dest = server.QueryInterface(Ci.nsINntpIncomingServer);
-      else if (type == "smtp")
-        dest = MailServices.smtp.defaultServer;
-
+        if (type == "identity")
+          dest = identity;
+        else if (type == "server")
+          dest = server;
+        else if (type == "pop3")
+          dest = server.QueryInterface(Ci.nsIPop3IncomingServer);
+        else if (type == "imap")
+          dest = server.QueryInterface(Ci.nsIImapIncomingServer);
+        else if (type == "none")
+          dest = server.QueryInterface(Ci.nsINoIncomingServer);
+        else if (type == "nntp")
+          dest = server.QueryInterface(Ci.nsINntpIncomingServer);
+        else if (type == "smtp")
+          dest = MailServices.smtp.defaultServer;
       } catch (ex) {
         // don't do anything, just means we don't support that
       }
-      if (dest == undefined) continue;
+      if (dest == undefined)
+        continue;
 
       if ((type in gGenericAttributeTypes) && (slot in gGenericAttributeTypes[type])) {
         var methodName = "get";
         switch (gGenericAttributeTypes[type][slot]) {
           case "int":
             methodName += "Int";
             break;
           case "wstring":
@@ -890,41 +886,40 @@ function saveAccount(accountValues, acco
             if (typeArray[slot] == "false")
               typeArray[slot] = false;
             else if (typeArray[slot] == "true")
               typeArray[slot] = true;
 
             methodName += "Bool";
             break;
           default:
-            dump("unexpected preftype: " + preftype + "\n");
+            dump("unexpected preftype: " + gGenericAttributeTypes[type][slot] + "\n");
             break;
         }
         methodName += ((methodName + "Value") in dest ? "Value" : "Attribute");
         if (dest[methodName](slot) != typeArray[slot]) {
           methodName = methodName.replace("get", "set");
           dest[methodName](slot, typeArray[slot]);
         }
-      }
-      else if (slot in dest && typeArray[slot] != undefined && dest[slot] != typeArray[slot]) {
+      } else if (slot in dest && typeArray[slot] != undefined && dest[slot] != typeArray[slot]) {
         try {
           dest[slot] = typeArray[slot];
         } catch (ex) {
           // hrm... need to handle special types here
         }
       }
     }
   }
 
   // if we made account changes to the spam settings, we'll need to re-initialize
   // our settings object
   if (server && server.spamSettings) {
     try {
       server.spamSettings.initialize(server);
-    } catch(e) {
+    } catch (e) {
       let accountName = getAccountValue(account, getValueArrayFor(account), "server",
                                         "prettyName", null, false);
       let alertText = document.getElementById("bundle_prefs")
                               .getFormattedString("junkSettingsBroken", [accountName]);
       let review = Services.prompt.confirmEx(window, null, alertText,
         (Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_YES) +
         (Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_NO),
         null, null, null, null, {});
@@ -1019,43 +1014,41 @@ function updateBlockedItems(aItems, aMus
         (!aMustBeTrue || Services.prefs.getBoolPref(prefstring)))
       item.setAttribute("disabled", true);
   }
 }
 
 /**
  * Set enabled/disabled state for the control.
  */
-function setEnabled(control, enabled)
-{
+function setEnabled(control, enabled) {
   if (!control)
     return;
 
   if (enabled)
     control.removeAttribute("disabled");
   else
     control.setAttribute("disabled", true);
 }
 
 // Called when someone clicks on an account. Figure out context by what they
 // clicked on. This is also called when an account is removed. In this case,
 // nothing is selected.
-function onAccountTreeSelect(pageId, account)
-{
+function onAccountTreeSelect(pageId, account) {
   let tree = document.getElementById("accounttree");
 
   let changeView = pageId && account;
   if (!changeView) {
     if (tree.view.selection.count < 1)
       return false;
 
     let node = tree.view.getItemAtIndex(tree.currentIndex);
     account = ("_account" in node) ? node._account : null;
 
-    pageId = node.getAttribute("PageTag")
+    pageId = node.getAttribute("PageTag");
   }
 
   if (pageId == currentPageId && account == currentAccount)
     return true;
 
   if (document.getElementById("contentFrame").contentDocument.getElementById("server.localPath")) {
     // Check if user/host names have been changed or the Local Directory is invalid.
     if (!checkUserServerChanges(false)) {
@@ -1080,18 +1073,18 @@ function onAccountTreeSelect(pageId, acc
   if (currentPageId) {
     // Change focus to the account tree first so that any 'onchange' handlers
     // on elements in the current page have a chance to run before the page
     // is saved and replaced by the new one.
     tree.focus();
   }
 
   // Provide opportunity to do cleanups or checks when the current page is being left.
-  if ("onLeave" in top.frames["contentFrame"])
-    top.frames["contentFrame"].onLeave();
+  if ("onLeave" in top.frames.contentFrame)
+    top.frames.contentFrame.onLeave();
 
   // save the previous page
   savePage(currentAccount);
 
   let changeAccount = (account != currentAccount);
 
   if (changeView)
     selectServer(account.incomingServer, pageId);
@@ -1120,68 +1113,65 @@ function onAccountTreeSelect(pageId, acc
 function onPanelLoaded(pageId) {
   if (pageId != pendingPageId) {
     // if we're reloading the current page, we'll assume the
     // page has asked itself to be completely reloaded from
     // the prefs. to do this, clear out the the old entry in
     // the account data, and then restore theh page
     if (pageId == currentPageId) {
       var serverId = currentAccount ?
-                     currentAccount.incomingServer.serverURI : "global"
+                     currentAccount.incomingServer.serverURI :
+                     "global";
       delete accountArray[serverId];
       restorePage(currentPageId, currentAccount);
     }
   } else {
     restorePage(pendingPageId, pendingAccount);
   }
 
   // probably unnecessary, but useful for debugging
   pendingAccount = null;
   pendingPageId = null;
 }
 
-function pageURL(pageId)
-{
+function pageURL(pageId) {
   // If we have a special non account manager pane (e.g. about:blank),
   // do not translate it into ChromePackageName URL.
   if (!pageId.startsWith("am-"))
     return pageId;
 
   let chromePackageName;
   try {
     // we could compare against "main","server","copies","offline","addressing",
     // "smtp" and "advanced" first to save the work, but don't,
     // as some of these might be turned into extensions (for thunderbird)
     let packageName = pageId.split("am-")[1].split(".xul")[0];
     chromePackageName = MailServices.accounts.getChromePackageName(packageName);
-  }
-  catch (ex) {
+  } catch (ex) {
     chromePackageName = "messenger";
   }
   return "chrome://" + chromePackageName + "/content/" + pageId;
 }
 
-function loadPage(pageId)
-{
+function loadPage(pageId) {
   const loadURIOptions = {
     triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
   };
   document.getElementById("contentFrame")
           .webNavigation.loadURI(pageURL(pageId), loadURIOptions);
 }
 
 // save the values of the widgets to the given server
-function savePage(account)
-{
+function savePage(account) {
   if (!account)
     return;
 
   // tell the page that it's about to save
-  if ("onSave" in top.frames["contentFrame"])
-    top.frames["contentFrame"].onSave();
+  if ("onSave" in top.frames.contentFrame)
+    top.frames.contentFrame.onSave();
 
   var accountValues = getValueArrayFor(account);
   if (!accountValues)
     return;
 
   var pageElements = getPageFormElements();
   if (!pageElements)
     return;
@@ -1199,30 +1189,30 @@ function savePage(account)
                         getFormElementValue(pageElements[i]));
       }
     }
   }
 }
 
 function setAccountValue(accountValues, type, slot, value) {
   if (!(type in accountValues))
-    accountValues[type] = new Object();
+    accountValues[type] = {};
 
   accountValues[type][slot] = value;
 }
 
 function getAccountValue(account, accountValues, type, slot, preftype, isGeneric) {
   if (!(type in accountValues))
-    accountValues[type] = new Object();
+    accountValues[type] = {};
 
   // fill in the slot from the account if necessary
   if (!(slot in accountValues[type]) || accountValues[type][slot] == undefined) {
     var server;
     if (account)
-      server= account.incomingServer;
+      server = account.incomingServer;
     var source = null;
     try {
     if (type == "identity")
       source = account.defaultIdentity;
     else if (type == "server")
       source = account.incomingServer;
     else if (type == "pop3")
       source = server.QueryInterface(Ci.nsIPop3IncomingServer);
@@ -1235,17 +1225,17 @@ function getAccountValue(account, accoun
     else if (type == "smtp")
       source = MailServices.smtp.defaultServer;
     } catch (ex) {
     }
 
     if (source) {
       if (isGeneric) {
         if (!(type in gGenericAttributeTypes))
-          gGenericAttributeTypes[type] = new Object();
+          gGenericAttributeTypes[type] = {};
 
         // we need the preftype later, for setting when we save.
         gGenericAttributeTypes[type][slot] = preftype;
         var methodName = "get";
         switch (preftype) {
           case "int":
             methodName += "Int";
             break;
@@ -1259,42 +1249,39 @@ function getAccountValue(account, accoun
             methodName += "Bool";
             break;
           default:
             dump("unexpected preftype: " + preftype + "\n");
             break;
         }
         methodName += ((methodName + "Value") in source ? "Value" : "Attribute");
         accountValues[type][slot] = source[methodName](slot);
-      }
-      else if (slot in source) {
+      } else if (slot in source) {
         accountValues[type][slot] = source[slot];
       } else {
         accountValues[type][slot] = null;
       }
-    }
-    else {
+    } else {
       accountValues[type][slot] = null;
     }
   }
   return accountValues[type][slot];
 }
 
 // restore the values of the widgets from the given server
-function restorePage(pageId, account)
-{
+function restorePage(pageId, account) {
   if (!account)
     return;
 
   var accountValues = getValueArrayFor(account);
   if (!accountValues)
     return;
 
-  if ("onPreInit" in top.frames["contentFrame"])
-    top.frames["contentFrame"].onPreInit(account, accountValues);
+  if ("onPreInit" in top.frames.contentFrame)
+    top.frames.contentFrame.onPreInit(account, accountValues);
 
   var pageElements = getPageFormElements();
   if (!pageElements)
     return;
 
   // restore the value from the account
   for (let i = 0; i < pageElements.length; i++) {
     if (pageElements[i].id) {
@@ -1307,38 +1294,38 @@ function restorePage(pageId, account)
         // elements that do have data, we get the values at poke them in.
         if (pageElements[i].localName != "button") {
           var value = getAccountValue(account, accountValues, type, slot, pageElements[i].getAttribute("preftype"), (pageElements[i].getAttribute("genericattr") == "true"));
           setFormElementValue(pageElements[i], value);
         }
         var element = pageElements[i];
         switch (type) {
           case "identity":
-            element["identitykey"] = account.defaultIdentity.key;
+            element.identitykey = account.defaultIdentity.key;
             break;
           case "pop3":
           case "imap":
           case "nntp":
           case "server":
-            element["serverkey"] = account.incomingServer.key;
+            element.serverkey = account.incomingServer.key;
             break;
           case "smtp":
             if (MailServices.smtp.defaultServer)
-              element["serverkey"] = MailServices.smtp.defaultServer.key;
+              element.serverkey = MailServices.smtp.defaultServer.key;
             break;
         }
         var isLocked = getAccountValueIsLocked(pageElements[i]);
         setEnabled(pageElements[i], !isLocked);
       }
     }
   }
 
   // tell the page that new values have been loaded
-  if ("onInit" in top.frames["contentFrame"])
-    top.frames["contentFrame"].onInit(pageId, account.incomingServer.serverURI);
+  if ("onInit" in top.frames.contentFrame)
+    top.frames.contentFrame.onInit(pageId, account.incomingServer.serverURI);
 
   // everything has succeeded, vervied by setting currentPageId
   currentPageId = pageId;
   currentAccount = account;
 }
 
 /**
  * Gets the value of a widget in current the account settings page,
@@ -1364,18 +1351,17 @@ function getFormElementValue(formElement
         return localfile;
       }
       return null;
     }
     if ((type == "textbox") || ("value" in formElement)) {
       return formElement.value.trim();
     }
     return null;
-  }
-  catch (ex) {
+  } catch (ex) {
     Cu.reportError("getFormElementValue failed, ex=" + ex + "\n");
   }
   return null;
 }
 
 /**
  * Sets the value of a widget in current the account settings page,
  * automatically setting the right property of it depending on element type.
@@ -1383,148 +1369,138 @@ function getFormElementValue(formElement
  * @param formElement  A XUL input element.
  * @param value        The value to store in the element.
  */
 function setFormElementValue(formElement, value) {
   var type = formElement.localName;
   if (type == "checkbox") {
     if (value == null) {
       formElement.checked = false;
+    } else if (formElement.getAttribute("reversed")) {
+      formElement.checked = !value;
     } else {
-      if (formElement.getAttribute("reversed"))
-        formElement.checked = !value;
-      else
-        formElement.checked = value;
+      formElement.checked = value;
     }
-  }
-  else if (type == "radiogroup" || type == "menulist") {
+  } else if (type == "radiogroup" || type == "menulist") {
     if (value == null)
       formElement.selectedIndex = 0;
     else
       formElement.value = value;
-  }
-  // handle nsIFile
-  else if (type == "textbox" &&
-           formElement.getAttribute("datatype") == "nsIFile") {
+  } else if (type == "textbox" && formElement.getAttribute("datatype") == "nsIFile") {
+    // handle nsIFile
     if (value) {
       let localfile = value.QueryInterface(Ci.nsIFile);
       try {
         formElement.value = localfile.path;
       } catch (ex) {
         dump("Still need to fix uninitialized nsIFile problem!\n");
       }
     } else {
       formElement.value = "";
     }
-  }
-  else if (type == "textbox") {
+  } else if (type == "textbox") {
     if (value == null)
       formElement.value = null;
     else
       formElement.value = value;
-  }
-  else if (type == "label") {
+  } else if (type == "label") {
     formElement.value = value || "";
-  }
-  // let the form figure out what to do with it
-  else {
-    if (value == null)
-      formElement.value = null;
-    else
-      formElement.value = value;
+  } else if (value == null) { // let the form figure out what to do with it
+    formElement.value = null;
+  } else {
+    formElement.value = value;
   }
 }
 
 //
 // conversion routines - get data associated
 // with a given pageId, serverId, etc
 //
 
 // helper routine for account manager panels to get the current account for the selected server
-function getCurrentAccount()
-{
+function getCurrentAccount() {
   return currentAccount;
 }
 
 /**
  * Get the array of persisted form elements for the given page.
  */
 function getPageFormElements() {
   // Uses getElementsByAttribute() which returns a live NodeList which is usually
   // faster than e.g. querySelector().
-  if ("getElementsByAttribute" in top.frames["contentFrame"].document)
-    return top.frames["contentFrame"].document
+  if ("getElementsByAttribute" in top.frames.contentFrame.document) {
+    return top.frames.contentFrame.document
               .getElementsByAttribute("wsm_persist", "true");
+  }
 
   return null;
 }
 
 /**
  * Get a single persisted form element in the current page.
  *
  * @param aId  ID of the element requested.
  */
 function getPageFormElement(aId) {
-  let elem = top.frames["contentFrame"].document.getElementById(aId);
+  let elem = top.frames.contentFrame.document.getElementById(aId);
   if (elem && (elem.getAttribute("wsm_persist") == "true"))
     return elem;
 
   return null;
 }
 
 // get the value array for the given account
 function getValueArrayFor(account) {
   var serverId = account ? account.incomingServer.serverURI : "global";
 
   if (!(serverId in accountArray)) {
-    accountArray[serverId] = new Object();
+    accountArray[serverId] = {};
     accountArray[serverId]._account = account;
   }
 
   return accountArray[serverId];
 }
 
 var gAccountTree = {
-  load: function at_load() {
+  load() {
     this._build();
 
     MailServices.accounts.addIncomingServerListener(this);
   },
-  unload: function at_unload() {
+  unload() {
     MailServices.accounts.removeIncomingServerListener(this);
   },
-  onServerLoaded: function at_onServerLoaded(aServer) {
+  onServerLoaded(aServer) {
     this._build();
   },
-  onServerUnloaded: function at_onServerUnloaded(aServer) {
+  onServerUnloaded(aServer) {
     this._build();
   },
-  onServerChanged: function at_onServerChanged(aServer) {},
+  onServerChanged(aServer) {},
 
   _dataStore: Services.xulStore,
 
   /**
    * Retrieve from XULStore.json whether the account should be expanded (open)
    * in the account tree.
    *
    * @param aAccountKey  key of the account to check
    */
-  _getAccountOpenState: function at_getAccountOpenState(aAccountKey) {
+  _getAccountOpenState(aAccountKey) {
     if (!this._dataStore.hasValue(document.documentURI, aAccountKey, "open")) {
-    // If there was no value stored, use opened state.
+      // If there was no value stored, use opened state.
       return "true";
-    } else {
-      // Retrieve the persisted value from XULStore.json.
-      // It is stored under the URI of the current document and ID of the XUL element.
-      return this._dataStore
-                 .getValue(document.documentURI, aAccountKey, "open");
     }
+    // Retrieve the persisted value from XULStore.json.
+    // It is stored under the URI of the current document and ID of the XUL element.
+    return this._dataStore
+               .getValue(document.documentURI, aAccountKey, "open");
   },
 
-  _build: function at_build() {
+  _build() {
     var bundle = document.getElementById("bundle_prefs");
     function getString(aString) { return bundle.getString(aString); }
     var panels = [{string: getString("prefPanel-server"), src: "am-server.xul"},
                   {string: getString("prefPanel-copies"), src: "am-copies.xul"},
                   {string: getString("prefPanel-synchronization"), src: "am-offline.xul"},
                   {string: getString("prefPanel-diskspace"), src: "am-offline.xul"},
                   {string: getString("prefPanel-addressing"), src: "am-addressing.xul"},
                   {string: getString("prefPanel-junk"), src: "am-junk.xul"}];
@@ -1584,40 +1560,40 @@ var gAccountTree = {
                         .getService(Ci.nsIMsgAccountManagerExtension);
             if (svc.showPanel(server)) {
               let bundleName = "chrome://" + svc.chromePackageName +
                                "/locale/am-" + svc.name + ".properties";
               let bundle = Services.strings.createBundle(bundleName);
               let title = bundle.GetStringFromName("prefPanel-" + svc.name);
               panelsToKeep.push({string: title, src: "am-" + svc.name + ".xul"});
             }
-          } catch(e) {
+          } catch (e) {
             // Fetching of this extension panel failed so do not show it,
             // just log error.
             let extName = data || "(unknown)";
             Cu.reportError("Error accessing panel from extension '" +
                            extName + "': " + e);
           }
         }
         amChrome = server.accountManagerChrome;
-      } catch(e) {
+      } catch (e) {
         // Show only a placeholder in the account list saying this account
         // is broken, with no child panels.
         let accountID = (accountName || accountKey);
         Cu.reportError("Error accessing account " + accountID + ": " + e);
         accountName = "Invalid account " + accountID;
         panelsToKeep.length = 0;
       }
 
       // Create the top level tree-item.
-      var treeitem = document.createElement("treeitem");
+      let treeitem = document.createElement("treeitem");
       mainTree.appendChild(treeitem);
-      var treerow = document.createElement("treerow");
+      let treerow = document.createElement("treerow");
       treeitem.appendChild(treerow);
-      var treecell = document.createElement("treecell");
+      let treecell = document.createElement("treecell");
       treerow.appendChild(treecell);
       treecell.setAttribute("label", accountName);
       treeitem.setAttribute("PageTag", amChrome);
       // Add icons based on account type.
       if (server) {
         treecell.setAttribute("properties", "folderNameCol isServer-true" +
                               " serverType-" + server.type);
         // For IM accounts, we can try to fetch a protocol specific icon.
@@ -1650,20 +1626,20 @@ var gAccountTree = {
         treeitem.setAttribute("persist", "open");
       }
       treeitem._account = account;
     }
 
     markDefaultServer(MailServices.accounts.defaultAccount, null);
 
     // Now add the outgoing server node.
-    var treeitem = document.createElement("treeitem");
+    let treeitem = document.createElement("treeitem");
     mainTree.appendChild(treeitem);
-    var treerow = document.createElement("treerow");
+    let treerow = document.createElement("treerow");
     treeitem.appendChild(treerow);
-    var treecell = document.createElement("treecell");
+    let treecell = document.createElement("treecell");
     treerow.appendChild(treecell);
     treecell.setAttribute("label", getString("prefPanel-smtp"));
     treeitem.setAttribute("PageTag", "am-smtp.xul");
     treecell.setAttribute("properties",
                           "folderNameCol isServer-true serverType-smtp");
-  }
+  },
 };
--- a/mailnews/base/prefs/content/AccountManager.xul
+++ b/mailnews/base/prefs/content/AccountManager.xul
@@ -16,17 +16,19 @@
         buttons="accept,cancel"
         onload="onLoad(event);"
         onunload="onUnload();">
 <stringbundle id="bundle_brand" src="chrome://branding/locale/brand.properties"/>
 <stringbundle id="bundle_prefs" src="chrome://messenger/locale/prefs.properties"/>
 <script type="application/javascript" src="chrome://messenger/content/accountUtils.js"/>
 <script type="application/javascript" src="chrome://messenger/content/am-prefs.js"/>
 <script type="application/javascript" src="chrome://messenger/content/AccountManager.js"/>
+#ifdef MOZ_SUITE
 <script type="application/javascript" src="chrome://messenger/content/am-help.js"/>
+#endif
 <script type="application/javascript" src="chrome://messenger/content/amUtils.js"/>
 
   <hbox flex="1">
     <vbox style="&accountTree.width;">
       <tree flex="1" onselect="onAccountTreeSelect(null, null);" id="accounttree"
             seltype="single" hidecolumnpicker="true">
         <treecols>
           <treecol id="AccountCol" flex="1" primary="true" hideheader="true"/>
--- a/mailnews/base/prefs/content/AccountWizard.js
+++ b/mailnews/base/prefs/content/AccountWizard.js
@@ -1,13 +1,22 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from accountUtils.js */
+/* import-globals-from amUtils.js */
+/* import-globals-from aw-accounttype.js */
+/* import-globals-from aw-identity.js */
+/* import-globals-from aw-incoming.js */
+/* import-globals-from aw-outgoing.js */
+/* import-globals-from aw-accname.js */
+/* import-globals-from aw-done.js */
+
 /* the okCallback is used for sending a callback for the parent window */
 var okCallback = null;
 /* The account wizard creates new accounts */
 
 /*
   data flow into the account wizard like this:
 
   For new accounts:
@@ -93,39 +102,35 @@ function onAccountWizardLoad() {
   let donePage = document.getElementById("done");
   donePage.addEventListener("pageshow", donePageInit);
 
   gPrefsBundle = document.getElementById("bundle_prefs");
   gMessengerBundle = document.getElementById("bundle_messenger");
 
   /* We are checking here for the callback argument */
   if (window.arguments && window.arguments[0]) {
-    if(window.arguments[0].okCallback )
-    {
-      //dump("There is okCallback");
+    if (window.arguments[0].okCallback) {
+      // dump("There is okCallback");
       top.okCallback = window.arguments[0].okCallback;
     }
   }
 
   checkForInvalidAccounts();
 
   // It is fine if there is no default account, this is expected the first
   // time you launch mail on a new profile.
   gDefaultAccount = MailServices.accounts.defaultAccount;
 
   // Set default value for global inbox checkbox
   var checkGlobalInbox = document.getElementById("deferStorage");
-  try {
-    checkGlobalInbox.checked = Services.prefs.getBoolPref("mail.accountwizard.deferstorage");
-  } catch(e) {}
+  checkGlobalInbox.checked = Services.prefs.getBoolPref("mail.accountwizard.deferstorage", false);
 }
 
-function onCancel()
-{
-  if ("ActivationOnCancel" in this && ActivationOnCancel())
+function onCancel() {
+  if ("ActivationOnCancel" in this && this.ActivationOnCancel())
     return false;
   var firstInvalidAccount = getFirstInvalidAccount();
   var closeWizard = true;
 
   // if the user cancels the the wizard when it pops up because of
   // an invalid account (example, a webmail account that activation started)
   // we just force create it by setting some values and calling the FinishAccount()
   // see bug #47521 for the full discussion
@@ -139,52 +144,50 @@ function onCancel()
     // set the email if it doesn't exist
     if (!pageData.identity.email || !pageData.identity.email.value) {
       setPageData(pageData, "identity", "email", "user@domain.invalid");
     }
 
     // call FinishAccount() and not onFinish(), since the "finish"
     // button may be disabled
     FinishAccount();
-  }
-  else {
+  } else {
     // since this is not an invalid account
     // really cancel if the user hits the "cancel" button
     // if the length of the account list is less than 1, there are no accounts
     if (MailServices.accounts.accounts.length < 1) {
       let confirmMsg = gPrefsBundle.getString("cancelWizard");
       let confirmTitle = gPrefsBundle.getString("accountWizard");
       let result = Services.prompt.confirmEx(window, confirmTitle, confirmMsg,
         (Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0) +
         (Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_1),
-        gPrefsBundle.getString('WizardExit'),
-        gPrefsBundle.getString('WizardContinue'),
-        null, null, {value:0});
+        gPrefsBundle.getString("WizardExit"),
+        gPrefsBundle.getString("WizardContinue"),
+        null, null, {value: 0});
 
       if (result == 1)
         closeWizard = false;
     }
 
-    if(top.okCallback && closeWizard) {
+    if (top.okCallback && closeWizard) {
       var state = false;
       top.okCallback(state);
     }
   }
   return closeWizard;
 }
 
-function FinishAccount()
-{
+function FinishAccount() {
   try {
     var pageData = GetPageData();
 
-    var accountData= gCurrentAccountData;
+    var accountData = gCurrentAccountData;
 
     if (!accountData)
-      accountData = new Object;
+      accountData = {};
 
     // we may need local folders before account is "Finished"
     // if it's a pop3 account which defers to Local Folders.
     verifyLocalFoldersAccount();
 
     PageDataToAccountData(pageData, accountData);
 
     FixupAccountDataForIsp(accountData);
@@ -207,68 +210,61 @@ function FinishAccount()
       if (document.getElementById("downloadMsgs").checked) {
         window.opener.gNewAccountToLoad = gCurrentAccount; // load messages for new POP account
       }
     }
 
     // in case we crash, force us a save of the prefs file NOW
     try {
       MailServices.accounts.saveAccountInfo();
-    }
-    catch (ex) {
+    } catch (ex) {
       dump("Error saving account info: " + ex + "\n");
     }
     window.close();
-    if(top.okCallback)
-    {
+    if (top.okCallback) {
       var state = true;
-      //dump("finish callback");
+      // dump("finish callback");
       top.okCallback(state);
     }
-  }
-  catch(ex) {
-    dump("FinishAccount failed, " + ex +"\n");
+  } catch (ex) {
+    dump("FinishAccount failed, " + ex + "\n");
   }
 }
 
 // prepopulate pageData with stuff from accountData
 // use: to prepopulate the wizard with account information
-function AccountDataToPageData(accountData, pageData)
-{
+function AccountDataToPageData(accountData, pageData) {
   if (!accountData) {
     dump("null account data! clearing..\n");
     // handle null accountData as if it were an empty object
     // so that we clear-out any old pagedata from a
     // previous accountdata. The trick is that
     // with an empty object, accountData.identity.slot is undefined,
     // so this will clear out the prefill data in setPageData
 
-    accountData = new Object;
-    accountData.incomingServer = new Object;
-    accountData.identity = new Object;
-    accountData.smtp = new Object;
+    accountData = {};
+    accountData.incomingServer = {};
+    accountData.identity = {};
+    accountData.smtp = {};
   }
 
   var server = accountData.incomingServer;
 
   if (server.type == undefined) {
     // clear out the old server data
-    //setPageData(pageData, "accounttype", "mailaccount", undefined);
-    //        setPageData(pageData, "accounttype", "newsaccount", undefined);
+    // setPageData(pageData, "accounttype", "mailaccount", undefined);
+    // setPageData(pageData, "accounttype", "newsaccount", undefined);
     setPageData(pageData, "server", "servertype", undefined);
     setPageData(pageData, "server", "hostname", undefined);
-
-  }
-  else {
+  } else {
     if (server.type == "nntp") {
       setPageData(pageData, "accounttype", "newsaccount", true);
       setPageData(pageData, "accounttype", "mailaccount", false);
       setPageData(pageData, "newsserver", "hostname", server.hostName);
-    }
-    else {
+    } else {
       setPageData(pageData, "accounttype", "mailaccount", true);
       setPageData(pageData, "accounttype", "newsaccount", false);
       setPageData(pageData, "server", "servertype", server.type);
       setPageData(pageData, "server", "hostname", server.hostName);
     }
     setPageData(pageData, "accounttype", "otheraccount", false);
   }
 
@@ -277,18 +273,17 @@ function AccountDataToPageData(accountDa
   setPageData(pageData, "accname", "prettyName", server.prettyName || "");
   setPageData(pageData, "accname", "userset", false);
 
   var identity;
 
   if (accountData.identity) {
       dump("This is an accountdata\n");
       identity = accountData.identity;
-  }
-  else if (accountData.identities) {
+  } else if (accountData.identities) {
       identity = accountData.identities.queryElementAt(0, Ci.nsIMsgIdentity);
       dump("this is an account, id= " + identity + "\n");
   }
 
   setPageData(pageData, "identity", "email", identity.email || "");
   setPageData(pageData, "identity", "fullName", identity.fullName || "");
 
   var smtp;
@@ -297,59 +292,56 @@ function AccountDataToPageData(accountDa
       smtp = accountData.smtp;
       setPageData(pageData, "server", "smtphostname", smtp.hostname);
       setPageData(pageData, "login", "smtpusername", smtp.username);
   }
 }
 
 // take data from each page of pageData and dump it into accountData
 // use: to put results of wizard into a account-oriented object
-function PageDataToAccountData(pageData, accountData)
-{
+function PageDataToAccountData(pageData, accountData) {
   if (!accountData.identity)
-    accountData.identity = new Object;
+    accountData.identity = {};
   if (!accountData.incomingServer)
-    accountData.incomingServer = new Object;
+    accountData.incomingServer = {};
   if (!accountData.smtp)
-    accountData.smtp = new Object;
+    accountData.smtp = {};
   if (!accountData.pop3)
-    accountData.pop3 = new Object;
+    accountData.pop3 = {};
   if (!accountData.imap)
-    accountData.imap = new Object;
+    accountData.imap = {};
 
   var identity = accountData.identity;
   var server = accountData.incomingServer;
   var smtp = accountData.smtp;
   var pop3 = accountData.pop3;
   var imap = accountData.imap;
 
   if (pageData.identity.email)
     identity.email = pageData.identity.email.value;
   if (pageData.identity.fullName)
     identity.fullName = pageData.identity.fullName.value;
 
   server.type = getCurrentServerType(pageData);
   server.hostName = getCurrentHostname(pageData);
-  if (getCurrentServerIsDeferred(pageData))
-  {
-    try
-    {
+  if (getCurrentServerIsDeferred(pageData)) {
+    try {
       let localFoldersServer = MailServices.accounts.localFoldersServer;
       let localFoldersAccount = MailServices.accounts.FindAccountForServer(localFoldersServer);
       pop3.deferredToAccount = localFoldersAccount.key;
       pop3.deferGetNewMail = true;
       server["ServerType-pop3"] = pop3;
+    } catch (ex) {
+      dump("exception setting up deferred account" + ex);
     }
-    catch (ex) {dump ("exception setting up deferred account" + ex);}
   }
   if (serverIsNntp(pageData)) {
     // this stuff probably not relevant
     dump("not setting username/password/etc\n");
-  }
-  else {
+  } else {
     if (pageData.login) {
       if (pageData.login.username)
         server.username = pageData.login.username.value;
       if (pageData.login.password)
         server.password = pageData.login.password.value;
       if (pageData.login.smtpusername)
         smtp.username = pageData.login.smtpusername.value;
     }
@@ -359,68 +351,59 @@ function PageDataToAccountData(pageData,
       dump("pageData.server.smtphostname.value = " + pageData.server.smtphostname + "\n");
       if (pageData.server.smtphostname &&
           pageData.server.smtphostname.value)
         smtp.hostname = pageData.server.smtphostname.value;
     }
     if (pageData.identity && pageData.identity.smtpServerKey)
       identity.smtpServerKey = pageData.identity.smtpServerKey.value;
 
-    if (pageData.server.port &&
-        pageData.server.port.value)
-    {
-      if (server.type == 'imap')
-      {
+    if (pageData.server.port && pageData.server.port.value) {
+      if (server.type == "imap") {
         imap.port = pageData.server.port.value;
         server["ServerType-imap"] = imap;
-      }
-      else if (server.type == 'pop3')
-      {
+      } else if (server.type == "pop3") {
         pop3.port = pageData.server.port.value;
         server["ServerType-pop3"] = pop3;
       }
     }
 
     if (pageData.server.leaveMessagesOnServer &&
-        pageData.server.leaveMessagesOnServer.value)
-    {
+        pageData.server.leaveMessagesOnServer.value) {
       pop3.leaveMessagesOnServer = pageData.server.leaveMessagesOnServer.value;
       server["ServerType-pop3"] = pop3;
     }
   }
 
   if (pageData.accname) {
     if (pageData.accname.prettyName)
       server.prettyName = pageData.accname.prettyName.value;
   }
-
 }
 
 // given an accountData structure, create an account
 // (but don't fill in any fields, that's for finishAccount()
-function createAccount(accountData)
-{
+function createAccount(accountData) {
   // Retrieve the server (data) from the account data.
   var server = accountData.incomingServer;
 
   // for news, username is always null
   var username = (server.type == "nntp") ? null : server.username;
   dump("MailServices.accounts.createIncomingServer(" +
        username + ", " + server.hostName + ", " + server.type + ")\n");
   // Create a (actual) server.
   server = MailServices.accounts.createIncomingServer(username, server.hostName, server.type);
 
   dump("MailServices.accounts.createAccount()\n");
   // Create an account.
   let account = MailServices.accounts.createAccount();
 
   // only create an identity for this account if we really have one
   // (use the email address as a check)
-  if (accountData.identity && accountData.identity.email)
-  {
+  if (accountData.identity && accountData.identity.email) {
     dump("MailServices.accounts.createIdentity()\n");
     // Create an identity.
     let identity = MailServices.accounts.createIdentity();
 
     // New nntp identities should use plain text by default;
     // we want that GNKSA (The Good Net-Keeping Seal of Approval).
     if (server.type == "nntp")
       identity.composeHtml = false;
@@ -435,20 +418,18 @@ function createAccount(accountData)
   // Set the new account to use the new server.
   account.incomingServer = server;
   server.valid = true;
   return account;
 }
 
 // given an accountData structure, copy the data into the
 // given account, incoming server, and so forth
-function finishAccount(account, accountData)
-{
+function finishAccount(account, accountData) {
   if (accountData.incomingServer) {
-
     var destServer = account.incomingServer;
     var srcServer = accountData.incomingServer;
     copyObjectToInterface(destServer, srcServer, true);
 
     // See if there are any protocol-specific attributes.
     // If so, we use the type to get the IID, QueryInterface
     // as appropriate, then copy the data over.
     const typeProperty = "ServerType-" + srcServer.type;
@@ -460,64 +441,61 @@ function finishAccount(account, accountD
       var IID;
       try {
         IID = destServer.protocolInfo.serverIID;
       } catch (ex) {
         Cu.reportError("Could not get IID for " + srcServer.type + ": " + ex);
       }
 
       if (IID) {
-        destProtocolServer = destServer.QueryInterface(IID);
-        srcProtocolServer = srcServer["ServerType-" + srcServer.type];
+        let destProtocolServer = destServer.QueryInterface(IID);
+        let srcProtocolServer = srcServer["ServerType-" + srcServer.type];
 
         dump("Copying over " + srcServer.type + "-specific data\n");
         copyObjectToInterface(destProtocolServer, srcProtocolServer, false);
       }
     }
 
-    account.incomingServer.valid=true;
+    account.incomingServer.valid = true;
     // hack to cause an account loaded notification now the server is valid
-    account.incomingServer = account.incomingServer;
+    account.incomingServer = account.incomingServer; // eslint-disable-line no-self-assign
   }
 
   // copy identity info
   var destIdentity = account.identities.length ?
                      account.identities.queryElementAt(0, nsIMsgIdentity) :
                      null;
 
-  if (destIdentity) // does this account have an identity?
-  {
+  if (destIdentity) { // does this account have an identity?
       if (accountData.identity && accountData.identity.email) {
           // fixup the email address if we have a default domain
-          var emailArray = accountData.identity.email.split('@');
+          let emailArray = accountData.identity.email.split("@");
           if (emailArray.length < 2 && accountData.domain) {
-              accountData.identity.email += '@' + accountData.domain;
+              accountData.identity.email += "@" + accountData.domain;
           }
 
           copyObjectToInterface(destIdentity, accountData.identity, true);
-          destIdentity.valid=true;
+          destIdentity.valid = true;
       }
 
       /**
        * If signature file need to be set, get the path to the signature file.
        * Signature files, if exist, are placed under default location. Get
        * default files location for messenger using directory service. Signature
        * file name should be extracted from the account data to build the complete
        * path for signature file. Once the path is built, set the identity's signature pref.
        */
-      if (destIdentity.attachSignature)
-      {
+      if (destIdentity.attachSignature) {
           var sigFileName = accountData.signatureFileName;
           let sigFile = MailServices.mailSession.getDataFilesDir("messenger");
           sigFile.append(sigFileName);
           destIdentity.signature = sigFile;
       }
 
-      if (accountData.smtp.hostname && !destIdentity.smtpServerKey)
-      {
+      if (accountData.smtp.hostname && !destIdentity.smtpServerKey) {
           // hostname + no key => create a new SMTP server.
 
           let smtpServer = MailServices.smtp.createServer();
           var isDefaultSmtpServer;
           if (!MailServices.smtp.defaultServer.hostname) {
             MailServices.smtp.defaultServer = smtpServer;
             isDefaultSmtpServer = true;
           }
@@ -527,29 +505,26 @@ function finishAccount(account, accountD
           // If it's the default server we created, make the identity use
           // "Use Default" by default.
           destIdentity.smtpServerKey =
             (isDefaultSmtpServer) ? "" : smtpServer.key;
        }
    } // if the account has an identity...
 
    if (this.FinishAccountHook != undefined) {
-       FinishAccountHook(accountData.domain);
+       this.FinishAccountHook(accountData.domain);
    }
 }
 
 // Helper method used by copyObjectToInterface which attempts to set dest[attribute] as a generic
 // attribute on the xpconnect object, src.
 // This routine skips any attribute that begins with ServerType-
-function setGenericAttribute(dest, src, attribute)
-{
-  if (!(attribute.toLowerCase().startsWith("servertype-")) && src[attribute])
-  {
-    switch (typeof src[attribute])
-    {
+function setGenericAttribute(dest, src, attribute) {
+  if (!(attribute.toLowerCase().startsWith("servertype-")) && src[attribute]) {
+    switch (typeof src[attribute]) {
       case "string":
         dest.setUnicharAttribute(attribute, src[attribute]);
         break;
       case "boolean":
         dest.setBoolAttribute(attribute, src[attribute]);
         break;
       case "number":
         dest.setIntAttribute(attribute, src[attribute]);
@@ -561,108 +536,94 @@ function setGenericAttribute(dest, src, 
   }
 }
 
 // copy over all attributes from dest into src that already exist in src
 // the assumption is that src is an XPConnect interface full of attributes
 // @param useGenericFallback if we can't set an attribute directly on src, then fall back
 //        and try setting it generically. This assumes that src supports setIntAttribute, setUnicharAttribute
 //        and setBoolAttribute.
-function copyObjectToInterface(dest, src, useGenericFallback)
-{
+function copyObjectToInterface(dest, src, useGenericFallback) {
   if (!dest) return;
   if (!src) return;
 
   var attribute;
-  for (attribute in src)
-  {
-    if (dest.__lookupSetter__(attribute))
-    {
+  for (attribute in src) {
+    if (dest.__lookupSetter__(attribute)) {
       if (dest[attribute] != src[attribute])
         dest[attribute] = src[attribute];
+    } else if (useGenericFallback) { // fall back to setting the attribute generically
+      setGenericAttribute(dest, src, attribute);
     }
-    else if (useGenericFallback) // fall back to setting the attribute generically
-      setGenericAttribute(dest, src, attribute);
   } // for each attribute in src we want to copy
 }
 
 // check if there already is a "Local Folders"
 // if not, create it.
-function verifyLocalFoldersAccount()
-{
+function verifyLocalFoldersAccount() {
   var localMailServer = null;
   try {
     localMailServer = MailServices.accounts.localFoldersServer;
-  }
-  catch (ex) {
+  } catch (ex) {
          // dump("exception in findserver: " + ex + "\n");
     localMailServer = null;
   }
 
   try {
-    if (!localMailServer)
-    {
+    if (!localMailServer) {
       // dump("Creating local mail account\n");
       // creates a copy of the identity you pass in
       MailServices.accounts.createLocalMailAccount();
       try {
         localMailServer = MailServices.accounts.localFoldersServer;
-      }
-      catch (ex) {
+      } catch (ex) {
         dump("error!  we should have found the local mail server after we created it.\n");
         localMailServer = null;
       }
     }
+  } catch (ex) {
+    dump("Error in verifyLocalFoldersAccount" + ex + "\n");
   }
-  catch (ex) {dump("Error in verifyLocalFoldersAccount" + ex + "\n");  }
-
 }
 
-function setupCopiesAndFoldersServer(account, accountIsDeferred, accountData)
-{
+function setupCopiesAndFoldersServer(account, accountIsDeferred, accountData) {
   try {
     var server = account.incomingServer;
 
     // This function sets up the default send preferences. The send preferences
     // go on identities, so there is no need to continue without any identities.
     if (server.type == "rss" || account.identities.length == 0)
       return false;
     let identity = account.identities.queryElementAt(0, Ci.nsIMsgIdentity);
     // For this server, do we default the folder prefs to this server, or to the "Local Folders" server
     // If it's deferred, we use the local folders account.
     var defaultCopiesAndFoldersPrefsToServer = !accountIsDeferred && server.defaultCopiesAndFoldersPrefsToServer;
 
     var copiesAndFoldersServer = null;
-    if (defaultCopiesAndFoldersPrefsToServer)
-    {
+    if (defaultCopiesAndFoldersPrefsToServer) {
       copiesAndFoldersServer = server;
-    }
-    else
-    {
-      if (!MailServices.accounts.localFoldersServer)
-      {
+    } else {
+      if (!MailServices.accounts.localFoldersServer) {
         dump("error!  we should have a local mail server at this point\n");
         return false;
       }
       copiesAndFoldersServer = MailServices.accounts.localFoldersServer;
     }
 
     setDefaultCopiesAndFoldersPrefs(identity, copiesAndFoldersServer, accountData);
-
   } catch (ex) {
     // return false (meaning we did not setupCopiesAndFoldersServer)
     // on any error
     dump("Error in setupCopiesAndFoldersServer: " + ex + "\n");
     return false;
   }
   return true;
 }
 
-function setDefaultCopiesAndFoldersPrefs(identity, server, accountData)
-{
+function setDefaultCopiesAndFoldersPrefs(identity, server, accountData) {
   var rootFolder = server.rootFolder;
 
   // we need to do this or it is possible that the server's draft,
   // stationery fcc folder will not be in rdf
   //
   // this can happen in a couple cases
   // 1) the first account we create, creates the local mail.  since
   // local mail was just created, it obviously hasn't been opened,
@@ -696,54 +657,50 @@ function setDefaultCopiesAndFoldersPrefs
   // Note the capital F, D and S!
   var draftFolder = (accountData.identity && accountData.identity.DraftFolder ?
     accountData.identity.DraftFolder : "Drafts");
   var stationeryFolder = (accountData.identity && accountData.identity.StationeryFolder ?
     accountData.identity.StationeryFolder : "Templates");
   var fccFolder = (accountData.identity && accountData.identity.FccFolder ?
     accountData.identity.FccFolder : "Sent");
 
-  identity.draftFolder = msgFolder.server.serverURI+ folderDelim + draftFolder;
-  identity.stationeryFolder = msgFolder.server.serverURI+ folderDelim + stationeryFolder;
-  identity.fccFolder = msgFolder.server.serverURI+ folderDelim + fccFolder;
+  identity.draftFolder = msgFolder.server.serverURI + folderDelim + draftFolder;
+  identity.stationeryFolder = msgFolder.server.serverURI + folderDelim + stationeryFolder;
+  identity.fccFolder = msgFolder.server.serverURI + folderDelim + fccFolder;
 
   // Note the capital F, D and S!
   identity.fccFolderPickerMode = (accountData.identity &&
     accountData.identity.FccFolder ? 1 : gDefaultSpecialFolderPickerMode);
   identity.draftsFolderPickerMode = (accountData.identity &&
     accountData.identity.DraftFolder ? 1 : gDefaultSpecialFolderPickerMode);
   identity.tmplFolderPickerMode = (accountData.identity &&
     accountData.identity.StationeryFolder ? 1 : gDefaultSpecialFolderPickerMode);
 }
 
-function AccountExists(userName, hostName, serverType)
-{
+function AccountExists(userName, hostName, serverType) {
   return MailServices.accounts.findRealServer(userName, hostName, serverType, 0);
 }
 
-function getFirstInvalidAccount()
-{
+function getFirstInvalidAccount() {
   let invalidAccounts = getInvalidAccounts(MailServices.accounts.accounts);
 
   if (invalidAccounts.length > 0)
     return invalidAccounts[0];
-  else
-    return null;
+  return null;
 }
 
-function checkForInvalidAccounts()
-{
+function checkForInvalidAccounts() {
   var firstInvalidAccount = getFirstInvalidAccount();
 
   if (firstInvalidAccount) {
     var pageData = GetPageData();
     dump("We have an invalid account, " + firstInvalidAccount + ", let's use that!\n");
     gCurrentAccount = firstInvalidAccount;
 
-    var accountData = new Object;
+    var accountData = {};
     accountData.incomingServer = firstInvalidAccount.incomingServer;
     accountData.identity = firstInvalidAccount.identities.queryElementAt(0,
       nsIMsgIdentity);
     accountData.smtp = MailServices.smtp.defaultServer;
     AccountDataToPageData(accountData, pageData);
 
     gCurrentAccountData = accountData;
 
@@ -755,40 +712,37 @@ function checkForInvalidAccounts()
 
 // sets the page data, automatically creating the arrays as necessary
 function setPageData(pageData, tag, slot, value) {
   if (!pageData[tag]) pageData[tag] = [];
 
   if (value == undefined) {
     // clear out this slot
     if (pageData[tag][slot]) delete pageData[tag][slot];
-  }
-  else {
+  } else {
     // pre-fill this slot
     if (!pageData[tag][slot]) pageData[tag][slot] = [];
     pageData[tag][slot].id = slot;
     pageData[tag][slot].value = value;
   }
 }
 
 // value of checkbox on the first page
 function serverIsNntp(pageData) {
   if (pageData.accounttype.newsaccount)
     return pageData.accounttype.newsaccount.value;
   return false;
 }
 
-function getUsernameFromEmail(aEmail)
-{
+function getUsernameFromEmail(aEmail) {
   var username = aEmail.substr(0, aEmail.indexOf("@"));
   return username;
 }
 
-function getCurrentUserName(pageData)
-{
+function getCurrentUserName(pageData) {
   var userName = "";
 
   if (pageData.login) {
     if (pageData.login.username) {
       userName = pageData.login.username.value;
     }
   }
   if (userName == "") {
@@ -813,33 +767,30 @@ function getCurrentServerIsDeferred(page
     serverDeferred = pageData.server.deferStorage.value;
 
   return serverDeferred;
 }
 
 function getCurrentHostname(pageData) {
   if (serverIsNntp(pageData))
     return pageData.newsserver.hostname.value;
-  else
-    return pageData.server.hostname.value;
+  return pageData.server.hostname.value;
 }
 
-function GetPageData()
-{
+function GetPageData() {
   if (!gPageData)
-    gPageData = new Object;
+    gPageData = {};
 
   return gPageData;
 }
 
 // does any cleanup work for the the account data
 // - sets the username from the email address if it's not already set
 // - anything else?
-function FixupAccountDataForIsp(accountData)
-{
+function FixupAccountDataForIsp(accountData) {
   // no fixup for news
   // setting the username does bad things
   // see bugs #42105 and #154213
   if (accountData.incomingServer.type == "nntp")
     return;
 
   var email = accountData.identity.email;
 
@@ -868,18 +819,17 @@ function onFlush() {
   Services.prefs.setBoolPref("nglayout.debug.disable_xul_cache", true);
   Services.prefs.setBoolPref("nglayout.debug.disable_xul_cache", false);
 }
 
 /** If there are no default accounts..
   * this is will be the new default, so enable
   * check for mail at startup
   */
-function EnableCheckMailAtStartUpIfNeeded(newAccount)
-{
+function EnableCheckMailAtStartUpIfNeeded(newAccount) {
   // Check if default account existed.
   // If no such account, make this one the default account
   // and turn on the new mail check at startup for the current account
   if (!gDefaultAccount) {
     MailServices.accounts.defaultAccount = newAccount;
     newAccount.incomingServer.loginAtStartUp = true;
     newAccount.incomingServer.downloadOnBiff = true;
   }
--- a/mailnews/base/prefs/content/AccountWizard.xul
+++ b/mailnews/base/prefs/content/AccountWizard.xul
@@ -21,17 +21,16 @@
         style="&accountWizard.size;"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml">
 
   <stringbundle id="bundle_prefs" src="chrome://messenger/locale/prefs.properties"/>
   <stringbundle id="bundle_messenger" src="chrome://messenger/locale/messenger.properties"/>
   <script type="application/javascript" src="chrome://messenger/content/accountUtils.js"/>
   <script type="application/javascript" src="chrome://messenger/content/amUtils.js"/>
   <script type="application/javascript" src="chrome://messenger/content/AccountWizard.js"/>
-  <script type="application/javascript" src="chrome://messenger/content/ispUtils.js"/>
   <script type="application/javascript" src="chrome://messenger/content/aw-accounttype.js"/>
   <script type="application/javascript" src="chrome://messenger/content/aw-identity.js"/>
   <script type="application/javascript" src="chrome://messenger/content/aw-incoming.js"/>
   <script type="application/javascript" src="chrome://messenger/content/aw-outgoing.js"/>
   <script type="application/javascript" src="chrome://messenger/content/aw-accname.js"/>
   <script type="application/javascript" src="chrome://messenger/content/aw-done.js"/>
 
   <!-- Account Type page : Displays choices of mail and news accounts that user can create -->
--- a/mailnews/base/prefs/content/SmtpServerEdit.js
+++ b/mailnews/base/prefs/content/SmtpServerEdit.js
@@ -15,24 +15,22 @@ var gSmtpHostname;
 var gSmtpPort;
 var gSmtpAuthMethod;
 var gSmtpSocketType;
 var gPort;
 var gDefaultPort;
 
 document.addEventListener("dialogaccept", onAccept);
 
-function onLoad(event)
-{
+function onLoad(event) {
   gSmtpServer = window.arguments[0].server;
   initSmtpSettings(gSmtpServer);
 }
 
-function onAccept(event)
-{
+function onAccept(event) {
   if (!isLegalHostNameOrIP(cleanUpHostName(gSmtpHostname.value))) {
     let prefsBundle = document.getElementById("bundle_prefs");
     let brandBundle = document.getElementById("bundle_brand");
     let alertTitle = brandBundle.getString("brandShortName");
     let alertMsg = prefsBundle.getString("enterValidServerName");
     Services.prompt.alert(window, alertTitle, alertMsg);
 
     window.arguments[0].result = false;
@@ -106,92 +104,85 @@ function initSmtpSettings(server) {
     hideUnlessSelected(document.getElementById("authMethod-any"));
 
     // "STARTTLS, if available" is vulnerable to MITM attacks so we shouldn't
     // allow users to choose it anymore. Hide the option unless the user already
     // has it set.
     hideUnlessSelected(document.getElementById("connectionSecurityType-1"));
 }
 
-function hideUnlessSelected(element)
-{
+function hideUnlessSelected(element) {
   element.hidden = !element.selected;
 }
 
-function setLabelFromStringBundle(elementID, stringName)
-{
+function setLabelFromStringBundle(elementID, stringName) {
   document.getElementById(elementID).label =
     document.getElementById("bundle_messenger").getString(stringName);
 }
 
 // Disables xul elements that have associated preferences locked.
-function onLockPreference()
-{
+function onLockPreference() {
   try {
     let allPrefElements = {
       hostname:     gSmtpHostname,
       description:  gSmtpDescription,
       port:         gSmtpPort,
       authMethod:   gSmtpAuthMethod,
-      try_ssl:      gSmtpSocketType
+      try_ssl:      gSmtpSocketType,
     };
     disableIfLocked(allPrefElements);
   } catch (e) { // non-fatal
     Cu.reportError("Error while getting locked prefs: " + e);
   }
 }
 
 /**
  * Does the work of disabling an element given the array which contains xul id/prefstring pairs.
  *
  * @param prefstrArray  array of XUL elements to check
  *
  * TODO: try to merge this with disableIfLocked function in am-offline.js (bug 755885)
  */
-function disableIfLocked(prefstrArray)
-{
+function disableIfLocked(prefstrArray) {
   let finalPrefString = "mail.smtpserver." +
     MailServices.smtp.defaultServer.key + ".";
   let smtpPrefBranch = Services.prefs.getBranch(finalPrefString);
 
   for (let prefstring in prefstrArray)
     if (smtpPrefBranch.prefIsLocked(prefstring))
       prefstrArray[prefstring].disabled = true;
 }
 
-function saveSmtpSettings(server)
-{
-    //dump("Saving to " + server + "\n");
+function saveSmtpSettings(server) {
+    // dump("Saving to " + server + "\n");
     if (server) {
         server.hostname = cleanUpHostName(gSmtpHostname.value);
         server.description = gSmtpDescription.value;
         server.port = gSmtpPort.value;
         server.authMethod = gSmtpAuthMethod.value;
         server.username = gSmtpUsername.value;
         server.socketType = gSmtpSocketType.value;
     }
 }
 
-function authMethodChanged(userAction)
-{
+function authMethodChanged(userAction) {
   var noUsername = gSmtpAuthMethod.value == Ci.nsMsgAuthMethod.none;
   gSmtpUsername.disabled = noUsername;
   gSmtpUsernameLabel.disabled = noUsername;
 }
 
 /**
  * Resets the default port to SMTP or SMTPS, dependending on
  * the |gSmtpSocketType| value, and sets the port to use to this default,
  * if that's appropriate.
  *
  * @param userAction  false for dialog initialization,
  *                    true for user action.
  */
-function sslChanged(userAction)
-{
+function sslChanged(userAction) {
   const DEFAULT_SMTP_PORT = "587";
   const DEFAULT_SMTPS_PORT = "465";
   var socketType = gSmtpSocketType.value;
   var otherDefaultPort;
   var prevDefaultPort = gDefaultPort.value;
 
   if (socketType == Ci.nsMsgSocketType.SSL) {
     gDefaultPort.value = DEFAULT_SMTPS_PORT;
--- a/mailnews/base/prefs/content/accountUtils.js
+++ b/mailnews/base/prefs/content/accountUtils.js
@@ -1,26 +1,29 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountManager.js */
+/* globals SelectFolder */// From messageWindow.js or msgMail3PaneWindow.js.
+/* globals MsgGetMessage */// From mailWindowOverlay.js.
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 
-var gAnyValidIdentity = false; //If there are no valid identities for any account
+var gAnyValidIdentity = false; // If there are no valid identities for any account
 // returns the first account with an invalid server or identity
 
 var gNewAccountToLoad = null;   // used to load new messages if we come from the mail3pane
 
-function getInvalidAccounts(accounts)
-{
+function getInvalidAccounts(accounts) {
     let numAccounts = accounts.length;
-    let invalidAccounts = new Array;
+    let invalidAccounts = [];
     let numIdentities = 0;
     for (let i = 0; i < numAccounts; i++) {
         let account = accounts.queryElementAt(i, Ci.nsIMsgAccount);
         try {
             if (!account.incomingServer.valid) {
                 invalidAccounts[invalidAccounts.length] = account;
                 // skip to the next account
                 continue;
@@ -32,18 +35,17 @@ function getInvalidAccounts(accounts)
 
         var identities = account.identities;
         numIdentities = identities.length;
 
         for (var j = 0; j < numIdentities; j++) {
             let identity = identities.queryElementAt(j, Ci.nsIMsgIdentity);
             if (identity.valid) {
               gAnyValidIdentity = true;
-            }
-            else {
+            } else {
               invalidAccounts[invalidAccounts.length] = account;
             }
         }
     }
     return invalidAccounts;
 }
 
 function showMailIntegrationDialog() {
@@ -73,21 +75,19 @@ function showMailIntegrationDialog() {
  *                      compose window. This last condition is so that we open
  *                      the account wizard if the user does not have any
  *                      identities defined and tries to compose mail.
  * @param wizardOpen optional param that allows the caller to specify a
  *                   different method to open a wizard. The wizardOpen method
  *                   takes wizardCallback as an argument. The wizardCallback
  *                   doesn't take any arguments.
  */
-function verifyAccounts(wizardCallback, needsIdentity, wizardOpen)
-{
+function verifyAccounts(wizardCallback, needsIdentity, wizardOpen) {
   var openWizard = false;
   var prefillAccount;
-  var state=true;
   var ret = true;
 
     try {
         // migrate quoting preferences from global to per account. This function returns
         // true if it had to migrate, which we will use to mean this is a just migrated
         // or new profile
         var newProfile = migrateGlobalQuotingPrefs(MailServices.accounts.allIdentities);
 
@@ -101,95 +101,80 @@ function verifyAccounts(wizardCallback, 
         }
 
         // if there are no accounts, or all accounts are "invalid"
         // then kick off the account migration. Or if this is a new (to Mozilla) profile.
         // MCD can set up accounts without the profile being used yet
         if (newProfile) {
           // check if MCD is configured. If not, say this is not a new profile
           // so that we don't accidentally remigrate non MCD profiles.
-          var adminUrl;
-          try {
-            adminUrl = Services.prefs.getCharPref("autoadmin.global_config_url");
-          }
-          catch (ex) {}
+          var adminUrl = Services.prefs.getCharPref("autoadmin.global_config_url", "");
           if (!adminUrl)
             newProfile = false;
         }
-        if ((newProfile  && !accountCount) || accountCount == invalidAccounts.length)
+        if ((newProfile && !accountCount) || accountCount == invalidAccounts.length)
           openWizard = true;
 
         // openWizard is true if messenger migration returns some kind of
         // error (including those cases where there is nothing to migrate).
         // prefillAccount is non-null if there is at least one invalid account.
         // gAnyValidIdentity is true when you've got at least one *valid*
         // identity. Since local and RSS folders are identity-less accounts, if you
         // only have one of those, it will be false.
         // needsIdentity is true only when verifyAccounts is called from the
         // compose window. This last condition is so that we open the account
         // wizard if the user does not have any identities defined and tries to
         // compose mail.
 
-        if (openWizard || prefillAccount || ((!gAnyValidIdentity) && needsIdentity))
-        {
+        if (openWizard || prefillAccount || ((!gAnyValidIdentity) && needsIdentity)) {
           if (wizardOpen != undefined)
-            wizardOpen(wizardCallback)
+            wizardOpen(wizardCallback);
           else
             MsgAccountWizard(wizardCallback);
           ret = false;
-        }
-        else
-        {
+        } else {
           var localFoldersExists;
-          try
-          {
+          try {
             localFoldersExists = MailServices.accounts.localFoldersServer;
-          }
-          catch (ex)
-          {
+          } catch (ex) {
             localFoldersExists = false;
           }
 
           // we didn't create the MsgAccountWizard - we need to verify that local folders exists.
           if (!localFoldersExists)
             MailServices.accounts.createLocalMailAccount();
         }
 
         // This will do nothing on platforms without a shell service
-        const NS_SHELLSERVICE_CID = "@mozilla.org/suite/shell-service;1"
-        if (NS_SHELLSERVICE_CID in Cc)
-        {
+        if ("@mozilla.org/suite/shell-service;1" in Cc) {
           // hack, set a time out to do this, so that the window can load first
           setTimeout(showMailIntegrationDialog, 0);
         }
         return ret;
-    }
-    catch (ex) {
+    } catch (ex) {
         dump("error verifying accounts " + ex + "\n");
         return false;
     }
 }
 
 // we do this from a timer because if this is called from the onload=
 // handler, then the parent window doesn't appear until after the wizard
 // has closed, and this is confusing to the user
-function MsgAccountWizard(wizardCallback)
-{
+function MsgAccountWizard(wizardCallback) {
   setTimeout(function() { msgOpenAccountWizard(wizardCallback); }, 0);
 }
 
 /**
  * Open the Old Mail Account Wizard, or focus it if it's already open.
  *
  * @param wizardCallback if the wizard is run, callback when it is done.
  * @param type - optional account type token, for Tb.
  * @see msgNewMailAccount below for the new implementation.
  */
-function msgOpenAccountWizard(wizardCallback, type)
-{
+function msgOpenAccountWizard(wizardCallback, type) {
   gNewAccountToLoad = null;
 
   window.openDialog("chrome://messenger/content/AccountWizard.xul", "AccountWizard",
                     "chrome,modal,titlebar,centerscreen",
                     {okCallback: wizardCallback, acctType: type});
 
   loadInboxForNewAccount();
 
@@ -198,29 +183,33 @@ function msgOpenAccountWizard(wizardCall
   // TODO Better fix: select newly created account (in all cases)
   if (typeof(getCurrentAccount) == "function" && // in AccountManager, not menu
       !getCurrentAccount())
     selectServer(null, null);
 }
 
 function initAccountWizardTB(args) {
   let type = args[0] && args[0].acctType;
-  let selType = type == "newsgroups" ? "newsaccount" :
-                type == "movemail" ? "movemail" : null;
+  let selType = null;
+  if (type == "newsgroups") {
+    selType = "newsaccount";
+  } else if (type == "movemail") {
+    selType = "Movemail";
+  }
   let accountwizard = document.getElementById("AccountWizard");
   let acctyperadio = document.getElementById("acctyperadio");
   let feedRadio = acctyperadio.querySelector("radio[value='Feeds']");
   if (feedRadio)
     feedRadio.remove();
   if (selType) {
-    acctyperadio.selectedItem = acctyperadio.querySelector("radio[value='"+selType+"']");
+    acctyperadio.selectedItem = acctyperadio.querySelector("radio[value='" + selType + "']");
     accountwizard.advance("identitypage");
+  } else {
+    acctyperadio.selectedItem = acctyperadio.getItemAtIndex(0);
   }
-  else
-    acctyperadio.selectedItem = acctyperadio.getItemAtIndex(0);
 }
 
 function AddFeedAccount() {
   window.openDialog("chrome://messenger-newsblog/content/feedAccountWizard.xul",
                     "", "chrome,modal,titlebar,centerscreen");
 }
 
 /**
@@ -228,72 +217,66 @@ function AddFeedAccount() {
  * and page of settings. If the window is already open it is only focused.
  *
  * @param selectPage  The xul file name for the viewing page or
  *                    null for the account main page. Other pages are
  *                    'am-server.xul', 'am-copies.xul', 'am-offline.xul',
  *                    'am-addressing.xul', 'am-smtp.xul'
  * @param  aServer    The server of the account to select. Optional.
  */
-function MsgAccountManager(selectPage, aServer)
-{
+function MsgAccountManager(selectPage, aServer) {
     var existingAccountManager = Services.wm.getMostRecentWindow("mailnews:accountmanager");
 
-    if (existingAccountManager)
+    if (existingAccountManager) {
         existingAccountManager.focus();
-    else {
+    } else {
         if (!aServer) {
-          if (typeof GetSelectedMsgFolders === "function") {
-            let folders = GetSelectedMsgFolders();
+          if (typeof window.GetSelectedMsgFolders === "function") {
+            let folders = window.GetSelectedMsgFolders();
             if (folders.length > 0)
               aServer = folders[0].server;
           }
-          if (!aServer && (typeof GetDefaultAccountRootFolder === "function")) {
-            let folder = GetDefaultAccountRootFolder();
+          if (!aServer && (typeof window.GetDefaultAccountRootFolder === "function")) {
+            let folder = window.GetDefaultAccountRootFolder();
             if (folder instanceof Ci.nsIMsgFolder)
               aServer = folder.server;
           }
         }
 
         window.openDialog("chrome://messenger/content/AccountManager.xul",
                           "AccountManager",
                           "chrome,centerscreen,modal,titlebar,resizable",
-                          { server: aServer, selectPage: selectPage });
+                          { server: aServer, selectPage });
     }
 }
 
-function loadInboxForNewAccount()
-{
+function loadInboxForNewAccount() {
   // gNewAccountToLoad is set in the final screen of the Account Wizard if a POP account
   // was created, the download messages box is checked, and the wizard was opened from the 3pane
   if (gNewAccountToLoad) {
     var rootMsgFolder = gNewAccountToLoad.incomingServer.rootMsgFolder;
     const kInboxFlag = Ci.nsMsgFolderFlags.Inbox;
     var inboxFolder = rootMsgFolder.getFolderWithFlags(kInboxFlag);
     SelectFolder(inboxFolder.URI);
     window.focus();
     setTimeout(MsgGetMessage, 0);
     gNewAccountToLoad = null;
   }
 }
 
 // returns true if we migrated - it knows this because 4.x did not have the
 // pref mailnews.quotingPrefs.version, so if it's not set, we're either
 // migrating from 4.x, or a much older version of Mozilla.
-function migrateGlobalQuotingPrefs(allIdentities)
-{
+function migrateGlobalQuotingPrefs(allIdentities) {
   // if reply_on_top and auto_quote exist then, if non-default
   // migrate and delete, if default just delete.
   var reply_on_top = 0;
   var auto_quote = true;
-  var quotingPrefs = 0;
+  var quotingPrefs = Services.prefs.getIntPref("mailnews.quotingPrefs.version", 0);
   var migrated = false;
-  try {
-    quotingPrefs = Services.prefs.getIntPref("mailnews.quotingPrefs.version");
-  } catch (ex) {}
 
   // If the quotingPrefs version is 0 then we need to migrate our preferences
   if (quotingPrefs == 0) {
     migrated = true;
     try {
       reply_on_top = Services.prefs.getIntPref("mailnews.reply_on_top");
       auto_quote = Services.prefs.getBoolPref("mail.auto_quote");
     } catch (ex) {}
@@ -312,18 +295,17 @@ function migrateGlobalQuotingPrefs(allId
     Services.prefs.setIntPref("mailnews.quotingPrefs.version", 1);
   }
   return migrated;
 }
 
 // we do this from a timer because if this is called from the onload=
 // handler, then the parent window doesn't appear until after the wizard
 // has closed, and this is confusing to the user
-function NewMailAccount(msgWindow, okCallback, extraData)
-{
+function NewMailAccount(msgWindow, okCallback, extraData) {
   if (!msgWindow)
     throw new Error("NewMailAccount must be given a msgWindow.");
 
   // Populate the extra data.
   if (!extraData)
     extraData = {};
   extraData.msgWindow = msgWindow;
 
@@ -371,17 +353,17 @@ function NewMailAccountProvisioner(aMsgW
   if (!tabmail) {
     Cu.reportError("Could not find a tabmail in the 3pane!");
     return;
   }
 
   // If there's already an accountProvisionerTab open, just focus it instead
   // of opening a new dialog.
   let apTab = tabmail.getTabInfoForCurrentOrFirstModeInstance(
-    tabmail.tabModes["accountProvisionerTab"]);
+    tabmail.tabModes.accountProvisionerTab);
 
   if (apTab) {
     tabmail.switchToTab(apTab);
     return;
   }
 
   // XXX make sure these are all defined in all contexts... to be on the safe
   // side, just get a mail:3pane and borrow the functions from it?
@@ -425,31 +407,28 @@ function NewMailAccountProvisioner(aMsgW
  *
  * @param msgWindow a msgWindow for us to use to verify the accounts.
  * @param okCallback an optional callback for us to call back to if
  *                   everything's okay.
  * @param extraData an optional param that allows us to pass data in and
  *                  out.  Used in the upcoming AccountProvisioner add-on.
  * @see msgOpenAccountWizard above for the previous implementation.
  */
-function msgNewMailAccount(msgWindow, okCallback, extraData)
-{
+function msgNewMailAccount(msgWindow, okCallback, extraData) {
   if (!msgWindow)
     throw new Error("msgNewMailAccount must be given a msgWindow.");
 
   let existingWindow = Services.wm.getMostRecentWindow("mail:autoconfig");
   if (existingWindow) {
     existingWindow.focus();
   } else if (AppConstants.MOZ_APP_NAME == "thunderbird") {
     // disabling modal for the time being, see 688273 REMOVEME
     window.openDialog("chrome://messenger/content/accountcreation/emailWizard.xul",
                       "AccountSetup", "chrome,titlebar,centerscreen",
-                      {msgWindow:msgWindow,
-                       okCallback:okCallback,
-                       extraData:extraData});
+                      { msgWindow, okCallback, extraData });
   }
 
   /*
   // TODO: Enable this block of code once the dialog above is made modal.
   // If we started with no servers at all and "smtp servers" list selected,
   // refresh display somehow. Bug 58506.
   // TODO Better fix: select newly created account (in all cases)
   let existingAccountManager =
--- a/mailnews/base/prefs/content/am-addressing.js
+++ b/mailnews/base/prefs/content/am-addressing.js
@@ -1,68 +1,61 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from am-prefs.js */
+/* import-globals-from amUtils.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
-function onLoad()
-{
-  parent.onPanelLoaded('am-addressing.xul');
+function onLoad() {
+  parent.onPanelLoaded("am-addressing.xul");
 }
 
-function onInit(aPageId, aServerId)
-{
+function onInit(aPageId, aServerId) {
   onInitCompositionAndAddressing();
 }
 
-function onInitCompositionAndAddressing()
-{
+function onInitCompositionAndAddressing() {
   LDAPenabling();
   quoteEnabling();
 }
 
-function onEditDirectories()
-{
+function onEditDirectories() {
   window.openDialog("chrome://messenger/content/addressbook/pref-editdirectories.xul",
                     "editDirectories", "chrome,modal=yes,resizable=no", null);
 }
 
-function onPreInit(account, accountValues)
-{
+function onPreInit(account, accountValues) {
 }
 
-function LDAPenabling()
-{
+function LDAPenabling() {
   onCheckItem("identity.directoryServer", ["directories"]);
   onCheckItem("editButton", ["directories"]);
 }
 
-function quoteEnabling()
-{
+function quoteEnabling() {
   var placebox = document.getElementById("placeBox");
 
   if (document.getElementById("identity.replyOnTop").value == "1") {
     placebox.firstChild.removeAttribute("disabled");
     placebox.lastChild.removeAttribute("disabled");
-  }
-  else {
+  } else {
     placebox.firstChild.setAttribute("disabled", "true");
     placebox.lastChild.setAttribute("disabled", "true");
   }
 }
 
 /**
  * Open the Preferences dialog on the tab with Addressing options.
  */
-function showGlobalAddressingPrefs()
-{
+function showGlobalAddressingPrefs() {
   openPrefsFromAccountManager("paneCompose", "addressingTab", null, "addressing_pane");
 }
 
 /**
  * Open the Preferences dialog on the tab with Composing options.
  */
-function showGlobalComposingPrefs()
-{
+function showGlobalComposingPrefs() {
   openPrefsFromAccountManager("paneCompose", "generalTab", null, "composing_messages_pane");
 }
--- a/mailnews/base/prefs/content/am-copies.js
+++ b/mailnews/base/prefs/content/am-copies.js
@@ -1,42 +1,41 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountManager.js */
+
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 var gFccRadioElemChoice, gDraftsRadioElemChoice, gArchivesRadioElemChoice, gTmplRadioElemChoice;
 var gFccRadioElemChoiceLocked, gDraftsRadioElemChoiceLocked, gArchivesRadioElemChoiceLocked, gTmplRadioElemChoiceLocked;
 var gDefaultPickerMode = "1";
 
 var gFccFolderWithDelim, gDraftsFolderWithDelim, gArchivesFolderWithDelim, gTemplatesFolderWithDelim;
 var gAccount;
 var gCurrentServerId;
 
-function onPreInit(account, accountValues)
-{
+function onPreInit(account, accountValues) {
   gAccount = account;
   var type = parent.getAccountValue(account, accountValues, "server", "type", null, false);
   hideShowControls(type);
 }
 
 /*
  * Set the global radio element choices and initialize folder/account pickers.
  * Also, initialize other UI elements (cc, bcc, fcc picker controller checkboxes).
  */
-function onInit(aPageId, aServerId)
-{
+function onInit(aPageId, aServerId) {
   gCurrentServerId = aServerId;
     onInitCopiesAndFolders();
 }
 
-function onInitCopiesAndFolders()
-{
+function onInitCopiesAndFolders() {
     SetGlobalRadioElemChoices();
 
     SetFolderDisplay(gFccRadioElemChoice, gFccRadioElemChoiceLocked,
                      "fcc",
                      "msgFccAccountPicker",
                      "identity.fccFolder",
                      "msgFccFolderPicker");
 
@@ -62,18 +61,17 @@ function onInitCopiesAndFolders()
     setupBccTextbox(true);
     setupFccItems();
     setupArchiveItems();
 
     SetSpecialFolderNamesWithDelims();
 }
 
 // Initialize the picker mode choices (account/folder picker) into global vars
-function SetGlobalRadioElemChoices()
-{
+function SetGlobalRadioElemChoices() {
     var pickerModeElement = document.getElementById("identity.fccFolderPickerMode");
     gFccRadioElemChoice = pickerModeElement.getAttribute("value");
     gFccRadioElemChoiceLocked = pickerModeElement.getAttribute("disabled");
     if (!gFccRadioElemChoice) gFccRadioElemChoice = gDefaultPickerMode;
 
     pickerModeElement = document.getElementById("identity.archivesFolderPickerMode");
     gArchivesRadioElemChoice = pickerModeElement.getAttribute("value");
     gArchivesRadioElemChoiceLocked = pickerModeElement.getAttribute("disabled");
@@ -95,18 +93,17 @@ function SetGlobalRadioElemChoices()
  * preferences file. Default picker mode, if none specified at this stage, is
  * set to 1 i.e., Other picker displaying the folder value read from the
  * preferences file.
  */
 function SetFolderDisplay(pickerMode, disableMode,
                           radioElemPrefix,
                           accountPickerId,
                           folderPickedField,
-                          folderPickerId)
-{
+                          folderPickerId) {
     if (!pickerMode)
         pickerMode = gDefaultPickerMode;
 
     var selectAccountRadioId = radioElemPrefix + "_selectAccount";
     var selectAccountRadioElem = document.getElementById(selectAccountRadioId);
     var selectFolderRadioId = radioElemPrefix + "_selectFolder";
     var selectFolderRadioElem = document.getElementById(selectFolderRadioId);
     var accountPicker = document.getElementById(accountPickerId);
@@ -117,40 +114,39 @@ function SetFolderDisplay(pickerMode, di
     // Get message folder from the given uri.
     // There is no need to check for the existence of special folders as
     // these folders are created on demand at runtime in case of imap accounts.
     // For POP3 accounts, special folders are created at the account creation time.
     var msgFolder = MailUtils.getOrCreateFolder(uri);
     InitFolderDisplay(msgFolder.server.rootFolder, accountPicker);
     InitFolderDisplay(msgFolder, folderPicker);
 
-    switch (pickerMode)
-    {
+    switch (pickerMode) {
         case "0" :
             rg.selectedItem = selectAccountRadioElem;
             SetPickerEnabling(accountPickerId, folderPickerId);
             break;
 
-        case "1"  :
+        case "1" :
             rg.selectedItem = selectFolderRadioElem;
             SetPickerEnabling(folderPickerId, accountPickerId);
             break;
 
         default :
             dump("Error in setting initial folder display on pickers\n");
             break;
     }
 
     // Check to see if we need to lock page elements. Disable radio buttons
     // and account/folder pickers when locked.
     if (disableMode) {
-      selectAccountRadioElem.setAttribute("disabled","true");
-      selectFolderRadioElem.setAttribute("disabled","true");
-      accountPicker.setAttribute("disabled","true");
-      folderPicker.setAttribute("disabled","true");
+      selectAccountRadioElem.setAttribute("disabled", "true");
+      selectFolderRadioElem.setAttribute("disabled", "true");
+      accountPicker.setAttribute("disabled", "true");
+      folderPicker.setAttribute("disabled", "true");
     }
 }
 
 // Initialize the folder display based on prefs values
 function InitFolderDisplay(folder, folderPicker) {
     folderPicker.menupopup.selectFolder(folder);
     folderPicker.folder = folder;
 }
@@ -158,145 +154,137 @@ function InitFolderDisplay(folder, folde
 /**
  * Capture any menulist changes and update the folder property.
  *
  * @param aGroup the prefix for the menulist we're handling (e.g. "drafts")
  * @param aType "Account" for the account picker or "Folder" for the folder
  *        picker
  * @param aEvent the event that we're responding to
  */
-function noteSelectionChange(aGroup, aType, aEvent)
-{
-  var checkedElem = document.getElementById(aGroup+"_select"+aType);
+function noteSelectionChange(aGroup, aType, aEvent) {
+  var checkedElem = document.getElementById(aGroup + "_select" + aType);
   var folder = aEvent.target._folder;
   var modeValue = checkedElem.value;
   var radioGroup = checkedElem.radioGroup.getAttribute("id");
   var picker;
 
   switch (radioGroup) {
     case "doFcc" :
       gFccRadioElemChoice = modeValue;
-      picker = document.getElementById("msgFcc"+aType+"Picker");
+      picker = document.getElementById("msgFcc" + aType + "Picker");
       break;
 
     case "messageArchives" :
       gArchivesRadioElemChoice = modeValue;
-      picker = document.getElementById("msgArchives"+aType+"Picker");
+      picker = document.getElementById("msgArchives" + aType + "Picker");
       updateArchiveHierarchyButton(folder);
       break;
 
     case "messageDrafts" :
       gDraftsRadioElemChoice = modeValue;
-      picker = document.getElementById("msgDrafts"+aType+"Picker");
+      picker = document.getElementById("msgDrafts" + aType + "Picker");
       break;
 
     case "messageTemplates" :
       gTmplRadioElemChoice = modeValue;
-      picker = document.getElementById("msgStationery"+aType+"Picker");
+      picker = document.getElementById("msgStationery" + aType + "Picker");
       break;
   }
 
   picker.folder = folder;
   picker.menupopup.selectFolder(folder);
 }
 
 // Need to append special folders when account picker is selected.
 // Create a set of global special folder vars to be suffixed to the
 // server URI of the selected account.
-function SetSpecialFolderNamesWithDelims()
-{
+function SetSpecialFolderNamesWithDelims() {
     var folderDelim = "/";
     /* we use internal names known to everyone like "Sent", "Templates" and "Drafts" */
 
     gFccFolderWithDelim = folderDelim + "Sent";
     gArchivesFolderWithDelim = folderDelim + "Archives";
     gDraftsFolderWithDelim = folderDelim + "Drafts";
     gTemplatesFolderWithDelim = folderDelim + "Templates";
 }
 
 // Save all changes on this page
-function onSave()
-{
+function onSave() {
     onSaveCopiesAndFolders();
 }
 
-function onSaveCopiesAndFolders()
-{
-    SaveFolderSettings( gFccRadioElemChoice,
+function onSaveCopiesAndFolders() {
+    SaveFolderSettings(gFccRadioElemChoice,
                         "doFcc",
                         gFccFolderWithDelim,
                         "msgFccAccountPicker",
                         "msgFccFolderPicker",
                         "identity.fccFolder",
-                        "identity.fccFolderPickerMode" );
+                        "identity.fccFolderPickerMode");
 
-    SaveFolderSettings( gArchivesRadioElemChoice,
+    SaveFolderSettings(gArchivesRadioElemChoice,
                         "messageArchives",
                         gArchivesFolderWithDelim,
                         "msgArchivesAccountPicker",
                         "msgArchivesFolderPicker",
                         "identity.archiveFolder",
-                        "identity.archivesFolderPickerMode" );
+                        "identity.archivesFolderPickerMode");
 
-    SaveFolderSettings( gDraftsRadioElemChoice,
+    SaveFolderSettings(gDraftsRadioElemChoice,
                         "messageDrafts",
                         gDraftsFolderWithDelim,
                         "msgDraftsAccountPicker",
                         "msgDraftsFolderPicker",
                         "identity.draftFolder",
-                        "identity.draftsFolderPickerMode" );
+                        "identity.draftsFolderPickerMode");
 
-    SaveFolderSettings( gTmplRadioElemChoice,
+    SaveFolderSettings(gTmplRadioElemChoice,
                         "messageTemplates",
                         gTemplatesFolderWithDelim,
                         "msgStationeryAccountPicker",
                         "msgStationeryFolderPicker",
                         "identity.stationeryFolder",
-                        "identity.tmplFolderPickerMode" );
+                        "identity.tmplFolderPickerMode");
 }
 
 // Save folder settings and radio element choices
 function SaveFolderSettings(radioElemChoice,
                             radioGroupId,
                             folderSuffix,
                             accountPickerId,
                             folderPickerId,
                             folderElementId,
-                            folderPickerModeId)
-{
+                            folderPickerModeId) {
     var formElement = document.getElementById(folderElementId);
     var uri;
 
     if (radioElemChoice == "0" ||
         !document.getElementById(folderPickerId).value) {
       // Default or revert to default if no folder chosen.
       radioElemChoice = "0";
       uri = document.getElementById(accountPickerId).folder.URI;
       if (uri) {
         // Create Folder URI.
         uri = uri + folderSuffix;
       }
-    }
-    else if (radioElemChoice == "1") {
+    } else if (radioElemChoice == "1") {
       uri = document.getElementById(folderPickerId).folder.URI;
-    }
-    else {
-      dump ("Error saving folder preferences.\n");
+    } else {
+      dump("Error saving folder preferences.\n");
       return;
     }
 
     formElement.setAttribute("value", uri);
 
     formElement = document.getElementById(folderPickerModeId);
     formElement.setAttribute("value", radioElemChoice);
 }
 
 // Check the Fcc Self item and setup associated picker state
-function setupFccItems()
-{
+function setupFccItems() {
   let checked = document.getElementById("identity.doFcc").checked;
   document.querySelectorAll(".depends-on-do-fcc").forEach(e => {
     if (checked) {
       e.removeAttribute("disabled");
     } else {
       e.setAttribute("disabled", "true");
     }
   });
@@ -319,66 +307,64 @@ function setupFccItems()
 
     default :
       dump("Error in setting Fcc elements.\n");
       break;
   }
 }
 
 // Disable CC textbox if CC checkbox is not checked
-function setupCcTextbox(init)
-{
+function setupCcTextbox(init) {
     var ccChecked = document.getElementById("identity.doCc").checked;
     var ccTextbox = document.getElementById("identity.doCcList");
 
     ccTextbox.disabled = !ccChecked;
 
     if (ccChecked) {
         if (ccTextbox.value == "") {
             ccTextbox.value = document.getElementById("identity.email").value;
             if (!init)
                 ccTextbox.select();
         }
     } else if ((ccTextbox.value == document.getElementById("identity.email").value) ||
-               (init && ccTextbox.getAttribute("value") == ""))
+               (init && ccTextbox.getAttribute("value") == "")) {
         ccTextbox.value = "";
+    }
 }
 
 // Disable BCC textbox if BCC checkbox is not checked
-function setupBccTextbox(init)
-{
+function setupBccTextbox(init) {
     var bccChecked = document.getElementById("identity.doBcc").checked;
     var bccTextbox = document.getElementById("identity.doBccList");
 
     bccTextbox.disabled = !bccChecked;
 
     if (bccChecked) {
         if (bccTextbox.value == "") {
             bccTextbox.value = document.getElementById("identity.email").value;
             if (!init)
                 bccTextbox.select();
         }
     } else if ((bccTextbox.value == document.getElementById("identity.email").value) ||
-               (init && bccTextbox.getAttribute("value") == ""))
+               (init && bccTextbox.getAttribute("value") == "")) {
         bccTextbox.value = "";
+    }
 }
 
 // Enable and disable pickers based on the radio element clicked
-function SetPickerEnabling(enablePickerId, disablePickerId)
-{
+function SetPickerEnabling(enablePickerId, disablePickerId) {
     var activePicker = document.getElementById(enablePickerId);
     activePicker.removeAttribute("disabled");
 
     var inactivePicker = document.getElementById(disablePickerId);
     inactivePicker.setAttribute("disabled", "true");
 }
 
 // Set radio element choices and picker states
-function setPickersState(enablePickerId, disablePickerId, event)
-{
+function setPickersState(enablePickerId, disablePickerId, event) {
   SetPickerEnabling(enablePickerId, disablePickerId);
 
   var radioElemValue = event.target.value;
 
   switch (event.target.id) {
     case "fcc_selectAccount":
     case "fcc_selectFolder":
       gFccRadioElemChoice = radioElemValue;
@@ -394,24 +380,22 @@ function setPickersState(enablePickerId,
       gDraftsRadioElemChoice = radioElemValue;
       break;
     case "tmpl_selectAccount":
     case "tmpl_selectFolder":
       gTmplRadioElemChoice = radioElemValue;
       break;
     default:
       dump("Error in setting picker state.\n");
-      return;
   }
 }
 
 // This routine is to restore the correct radio element
 // state when the fcc self checkbox broadcasts the change
-function SetRadioButtons(selectPickerId, unselectPickerId)
-{
+function SetRadioButtons(selectPickerId, unselectPickerId) {
   var activeRadioElem = document.getElementById(selectPickerId);
   activeRadioElem.radioGroup.selectedItem = activeRadioElem;
 }
 
 /**
  * Enable/disable the archive hierarchy button depending on what folder is
  * currently selected (Gmail IMAP folders should have the button disabled, since
  * changing the archive hierarchy does nothing there.
@@ -456,17 +440,16 @@ function setupArchiveItems() {
         SetPickerEnabling("msgArchivesFolderPicker", "msgArchivesAccountPicker");
       SetRadioButtons("archive_selectFolder", "archive_selectAccount");
       updateArchiveHierarchyButton(document.getElementById(
                                    "msgArchivesFolderPicker").folder);
       break;
 
     default:
       dump("Error in setting Archive elements.\n");
-      return;
   }
 }
 
 /**
  * Open a dialog to edit the folder hierarchy used when archiving messages.
  */
 function ChangeArchiveHierarchy() {
   let identity = parent.gIdentity || parent.getCurrentAccount().defaultIdentity;
--- a/mailnews/base/prefs/content/am-help.js
+++ b/mailnews/base/prefs/content/am-help.js
@@ -1,13 +1,17 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// This file is SeaMonkey-only.
+
+/* globals openHelp */// suite/components/helpviewer/content/contextHelp.js
+
 /**
  * Key value pairs to derive the tag based on the page loaded.
  * Each key is the page loaded when user clicks on one of the items on
  * the accounttree of the AccountManager window.
  * Value is a tag that is preset which will be used to display
  * context sensitive help.
  */
 var pageTagPairs = {
@@ -16,22 +20,21 @@ var pageTagPairs = {
   "chrome://messenger/content/am-copies.xul": "mail_copies",
   "chrome://messenger/content/am-addressing.xul": "mail_addressing_settings",
   "chrome://messenger/content/am-junk.xul": "mail-account-junk",
   "chrome://messenger/content/am-offline.xul": "mail-offline-accounts",
   "chrome://messenger/content/am-smtp.xul": "mail_smtp",
   "chrome://messenger/content/am-smime.xul": "mail_security_settings",
   "chrome://messenger/content/am-serverwithnoidentities.xul": "mail_local_folders_settings",
   "chrome://messenger/content/am-mdn.xul": "mail-account-receipts",
-}
+};
 
-function doHelpButton()
-{
+function doHelpButton() {
   // Get the URI of the page loaded in the AccountManager's content frame.
-  var pageSourceURI = contentFrame.location.href;
+  var pageSourceURI = top.frames.contentFrame.location.href;
   // Get the help tag corresponding to the page loaded.
   var helpTag = pageTagPairs[pageSourceURI];
 
   // If the help tag is generic or offline, check if there is a need to set tags per server type
   if ((helpTag == "mail") || (helpTag == "mail-offline-accounts")) {
     // Get server type, as we may need to set help tags per server type for some pages
     var serverType = GetServerType();
 
@@ -52,25 +55,24 @@ function doHelpButton()
         helpTag = "mail_offline_" + serverType;
         break;
 
       default :
         break;
     }
   }
 
-  if ( helpTag )
+  if (helpTag)
     openHelp(helpTag);
   else
-    openHelp('mail');
+    openHelp("mail");
 }
 
 /**
  * Get server type of the selected item
  */
-function GetServerType()
-{
+function GetServerType() {
   var serverType = null;
   var currentAccount = parent.getCurrentAccount();
   if (currentAccount)
     serverType = currentAccount.incomingServer.type;
   return serverType;
 }
--- a/mailnews/base/prefs/content/am-identities-list.js
+++ b/mailnews/base/prefs/content/am-identities-list.js
@@ -13,18 +13,17 @@ var gEditButton;
 var gSetDefaultButton;
 var gDeleteButton;
 
 var gAccount = null;  // the account we are showing the identities for
 
 document.addEventListener("dialogaccept", onOk);
 document.addEventListener("dialogcancel", onOk);
 
-function onLoad()
-{
+function onLoad() {
   gIdentityListBox  = document.getElementById("identitiesList");
   gAddButton        = document.getElementById("cmd_add");
   gEditButton       = document.getElementById("cmd_edit");
   gSetDefaultButton = document.getElementById("cmd_default");
   gDeleteButton     = document.getElementById("cmd_delete");
 
   // extract the account
   gAccount = window.arguments[0].account;
@@ -36,29 +35,25 @@ function onLoad()
   refreshIdentityList(0);
 }
 
 /**
  * Rebuilds the listbox holding the list of identities.
  *
  * @param aSelectIndex  Attempt to select the identity with this index.
  */
-function refreshIdentityList(aSelectIndex)
-{
+function refreshIdentityList(aSelectIndex) {
   // Remove all children.
   while (gIdentityListBox.hasChildNodes())
     gIdentityListBox.lastChild.remove();
 
   // Build the list from the identities array.
   let identities = gAccount.identities;
-  for (let identity of fixIterator(identities,
-                                   Ci.nsIMsgIdentity))
-  {
-    if (identity.valid)
-    {
+  for (let identity of fixIterator(identities, Ci.nsIMsgIdentity)) {
+    if (identity.valid) {
       let label = document.createElement("label");
       label.setAttribute("value", identity.identityName);
 
       let listitem = document.createElement("richlistitem");
       listitem.appendChild(label);
       listitem.setAttribute("key", identity.key);
       gIdentityListBox.appendChild(listitem);
     }
@@ -74,93 +69,85 @@ function refreshIdentityList(aSelectInde
   gIdentityListBox.selectedIndex = aSelectIndex;
 }
 
 /**
  * Opens the identity editor dialog.
  *
  * @param identity  the identity (if any) to load in the dialog
  */
-function openIdentityEditor(identity)
-{
-  let args = { identity: identity, account: gAccount, result: false };
+function openIdentityEditor(identity) {
+  let args = { identity, account: gAccount, result: false };
 
   let indexToSelect = identity ? gIdentityListBox.selectedIndex :
                                  gIdentityListBox.itemCount;
 
   window.openDialog("am-identity-edit.xul", "",
                     "chrome,modal,resizable,centerscreen", args);
 
   if (args.result)
     refreshIdentityList(indexToSelect);
 }
 
-function getSelectedIdentity()
-{
+function getSelectedIdentity() {
   if (gIdentityListBox.selectedItems.length != 1)
     return null;
 
   var identityKey = gIdentityListBox.selectedItems[0].getAttribute("key");
   let identities = gAccount.identities;
-  for (let identity of fixIterator(identities,
-                                   Ci.nsIMsgIdentity))
-  {
+  for (let identity of fixIterator(identities, Ci.nsIMsgIdentity)) {
     if (identity.valid && identity.key == identityKey)
       return identity;
   }
 
   return null; // no identity found
 }
 
-function onEdit(event)
-{
-  var id = (event.target.localName == 'listbox') ? null : getSelectedIdentity();
+function onEdit(event) {
+  var id = (event.target.localName == "listbox") ? null : getSelectedIdentity();
   openIdentityEditor(id);
 }
 
 /**
  * Enable/disable buttons depending on number of identities and current selection.
  */
-function updateButtons()
-{
+function updateButtons() {
   // In this listbox there should always be one item selected.
   if (gIdentityListBox.selectedItems.length != 1 || gIdentityListBox.itemCount == 0) {
     // But in case this is not met (e.g. there is no identity for some reason,
     // or the list is being rebuilt), disable all buttons.
     gEditButton.setAttribute("disabled", "true");
     gDeleteButton.setAttribute("disabled", "true");
     gSetDefaultButton.setAttribute("disabled", "true");
     return;
   }
 
   gEditButton.setAttribute("disabled", "false");
   gDeleteButton.setAttribute("disabled", (gIdentityListBox.itemCount <= 1) ? "true" : "false");
   gSetDefaultButton.setAttribute("disabled", (gIdentityListBox.selectedIndex == 0) ? "true" : "false");
   // The Add command is always enabled.
 }
 
-function onSetDefault(event)
-{
+function onSetDefault(event) {
   let identity = getSelectedIdentity();
   if (!identity)
     return;
 
   // If the first identity is selected, there is nothing to do.
   if (gIdentityListBox.selectedIndex == 0)
     return;
 
   gAccount.defaultIdentity = identity;
   // Rebuilt the identity list and select the moved identity again.
   refreshIdentityList(0);
   // Update gloda's myContact with the new default identity.
   Gloda._initMyIdentities();
 }
 
-function onDelete(event)
-{
+function onDelete(event) {
   if (gIdentityListBox.itemCount <= 1)  // don't support deleting the last identity
     return;
 
   // get delete confirmation
   let selectedIdentity = getSelectedIdentity();
 
   let prefsBundle = document.getElementById("bundle_prefs");
   let confirmTitle = prefsBundle.getFormattedString("identity-delete-confirm-title",
@@ -177,12 +164,11 @@ function onDelete(event)
 
   let selectedItemIndex = gIdentityListBox.selectedIndex;
 
   gAccount.removeIdentity(selectedIdentity);
 
   refreshIdentityList(selectedItemIndex);
 }
 
-function onOk()
-{
+function onOk() {
   window.arguments[0].result = true;
 }
--- a/mailnews/base/prefs/content/am-identity-edit.js
+++ b/mailnews/base/prefs/content/am-identity-edit.js
@@ -1,23 +1,25 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from am-addressing.js */
+/* import-globals-from am-copies.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 
 var gIdentity = null;  // the identity we are editing (may be null for a new identity)
 var gAccount = null;   // the account the identity is (or will be) associated with
 
 document.addEventListener("dialogaccept", onOk);
 
-function onLoadIdentityProperties()
-{
+function onLoadIdentityProperties() {
   // extract the account
   gIdentity = window.arguments[0].identity;
   gAccount = window.arguments[0].account;
   let prefBundle = document.getElementById("bundle_prefs");
 
   // Make the dialog the same height and 90% of the width of the main Account
   // manager page when the Account manager is not maximized.
   let accountDialog = Services.wm.getMostRecentWindow("mailnews:accountmanager")
@@ -40,116 +42,108 @@ function onLoadIdentityProperties()
   loadSMTPServerList();
 
   initIdentityValues(gIdentity);
   initCopiesAndFolder(gIdentity);
   initCompositionAndAddressing(gIdentity);
 }
 
 // based on the values of gIdentity, initialize the identity fields we expose to the user
-function initIdentityValues(identity)
-{
+function initIdentityValues(identity) {
   function initSmtpServer(aServerKey) {
     // Select a server in the SMTP server menulist by its key.
     // The value of the identity.smtpServerKey is null when the
     // "use default server" option is used so, if we get that passed in, select
     // the useDefaultItem representing this option by using the value of "".
     document.getElementById("identity.smtpServerKey").value = aServerKey || "";
   }
 
-  if (identity)
-  {
-    document.getElementById('identity.fullName').value = identity.fullName;
-    document.getElementById('identity.email').value = identity.email;
-    document.getElementById('identity.replyTo').value = identity.replyTo;
-    document.getElementById('identity.organization').value = identity.organization;
-    document.getElementById('identity.attachSignature').checked = identity.attachSignature;
-    document.getElementById('identity.htmlSigText').value = identity.htmlSigText;
-    document.getElementById('identity.htmlSigFormat').checked = identity.htmlSigFormat;
+  if (identity) {
+    document.getElementById("identity.fullName").value = identity.fullName;
+    document.getElementById("identity.email").value = identity.email;
+    document.getElementById("identity.replyTo").value = identity.replyTo;
+    document.getElementById("identity.organization").value = identity.organization;
+    document.getElementById("identity.attachSignature").checked = identity.attachSignature;
+    document.getElementById("identity.htmlSigText").value = identity.htmlSigText;
+    document.getElementById("identity.htmlSigFormat").checked = identity.htmlSigFormat;
 
     if (identity.signature)
-      document.getElementById('identity.signature').value = identity.signature.path;
+      document.getElementById("identity.signature").value = identity.signature.path;
 
-    document.getElementById('identity.attachVCard').checked = identity.attachVCard;
-    document.getElementById('identity.escapedVCard').value = identity.escapedVCard;
+    document.getElementById("identity.attachVCard").checked = identity.attachVCard;
+    document.getElementById("identity.escapedVCard").value = identity.escapedVCard;
     initSmtpServer(identity.smtpServerKey);
 
     // This field does not exist for the default identity shown in the am-main.xul pane.
     let idLabel = document.getElementById("identity.label");
     if (idLabel)
       idLabel.value = identity.label;
-  }
-  else
-  {
+  } else {
     // We're adding an identity, use the best default we have.
     initSmtpServer(gAccount.defaultIdentity.smtpServerKey);
   }
 
   setupSignatureItems();
 }
 
-function initCopiesAndFolder(identity)
-{
+function initCopiesAndFolder(identity) {
   // if we are editing an existing identity, use it...otherwise copy our values from the default identity
   var copiesAndFoldersIdentity = identity ? identity : gAccount.defaultIdentity;
 
-  document.getElementById('identity.fccFolder').value = copiesAndFoldersIdentity.fccFolder;
-  document.getElementById('identity.draftFolder').value = copiesAndFoldersIdentity.draftFolder;
-  document.getElementById('identity.archiveFolder').value = copiesAndFoldersIdentity.archiveFolder;
-  document.getElementById('identity.stationeryFolder').value = copiesAndFoldersIdentity.stationeryFolder;
+  document.getElementById("identity.fccFolder").value = copiesAndFoldersIdentity.fccFolder;
+  document.getElementById("identity.draftFolder").value = copiesAndFoldersIdentity.draftFolder;
+  document.getElementById("identity.archiveFolder").value = copiesAndFoldersIdentity.archiveFolder;
+  document.getElementById("identity.stationeryFolder").value = copiesAndFoldersIdentity.stationeryFolder;
 
-  document.getElementById('identity.fccFolderPickerMode').value = copiesAndFoldersIdentity.fccFolderPickerMode ? copiesAndFoldersIdentity.fccFolderPickerMode : 0;
-  document.getElementById('identity.draftsFolderPickerMode').value = copiesAndFoldersIdentity.draftsFolderPickerMode ? copiesAndFoldersIdentity.draftsFolderPickerMode : 0;
-  document.getElementById('identity.archivesFolderPickerMode').value = copiesAndFoldersIdentity.archivesFolderPickerMode ? copiesAndFoldersIdentity.archivesFolderPickerMode : 0;
-  document.getElementById('identity.tmplFolderPickerMode').value = copiesAndFoldersIdentity.tmplFolderPickerMode ? copiesAndFoldersIdentity.tmplFolderPickerMode : 0;
+  document.getElementById("identity.fccFolderPickerMode").value = copiesAndFoldersIdentity.fccFolderPickerMode ? copiesAndFoldersIdentity.fccFolderPickerMode : 0;
+  document.getElementById("identity.draftsFolderPickerMode").value = copiesAndFoldersIdentity.draftsFolderPickerMode ? copiesAndFoldersIdentity.draftsFolderPickerMode : 0;
+  document.getElementById("identity.archivesFolderPickerMode").value = copiesAndFoldersIdentity.archivesFolderPickerMode ? copiesAndFoldersIdentity.archivesFolderPickerMode : 0;
+  document.getElementById("identity.tmplFolderPickerMode").value = copiesAndFoldersIdentity.tmplFolderPickerMode ? copiesAndFoldersIdentity.tmplFolderPickerMode : 0;
 
-  document.getElementById('identity.doCc').checked = copiesAndFoldersIdentity.doCc;
-  document.getElementById('identity.doCcList').value = copiesAndFoldersIdentity.doCcList;
-  document.getElementById('identity.doBcc').checked = copiesAndFoldersIdentity.doBcc;
-  document.getElementById('identity.doBccList').value = copiesAndFoldersIdentity.doBccList;
-  document.getElementById('identity.doFcc').checked = copiesAndFoldersIdentity.doFcc;
-  document.getElementById('identity.fccReplyFollowsParent').checked = copiesAndFoldersIdentity.fccReplyFollowsParent;
-  document.getElementById('identity.showSaveMsgDlg').checked = copiesAndFoldersIdentity.showSaveMsgDlg;
-  document.getElementById('identity.archiveEnabled').checked = copiesAndFoldersIdentity.archiveEnabled;
+  document.getElementById("identity.doCc").checked = copiesAndFoldersIdentity.doCc;
+  document.getElementById("identity.doCcList").value = copiesAndFoldersIdentity.doCcList;
+  document.getElementById("identity.doBcc").checked = copiesAndFoldersIdentity.doBcc;
+  document.getElementById("identity.doBccList").value = copiesAndFoldersIdentity.doBccList;
+  document.getElementById("identity.doFcc").checked = copiesAndFoldersIdentity.doFcc;
+  document.getElementById("identity.fccReplyFollowsParent").checked = copiesAndFoldersIdentity.fccReplyFollowsParent;
+  document.getElementById("identity.showSaveMsgDlg").checked = copiesAndFoldersIdentity.showSaveMsgDlg;
+  document.getElementById("identity.archiveEnabled").checked = copiesAndFoldersIdentity.archiveEnabled;
 
   onInitCopiesAndFolders(); // am-copies.js method
 }
 
-function initCompositionAndAddressing(identity)
-{
+function initCompositionAndAddressing(identity) {
   // if we are editing an existing identity, use it...otherwise copy our values from the default identity
   var addressingIdentity = identity ? identity : gAccount.defaultIdentity;
 
-  document.getElementById('identity.directoryServer').value = addressingIdentity.directoryServer;
-  document.getElementById('identity.overrideGlobal_Pref').value = addressingIdentity.overrideGlobalPref;
-  let autoCompleteElement = document.getElementById('identity.autocompleteToMyDomain');
+  document.getElementById("identity.directoryServer").value = addressingIdentity.directoryServer;
+  document.getElementById("identity.overrideGlobal_Pref").value = addressingIdentity.overrideGlobalPref;
+  let autoCompleteElement = document.getElementById("identity.autocompleteToMyDomain");
   if (autoCompleteElement) // Thunderbird does not have this element.
     autoCompleteElement.checked = addressingIdentity.autocompleteToMyDomain;
 
-  document.getElementById('identity.composeHtml').checked = addressingIdentity.composeHtml;
-  document.getElementById('identity.autoQuote').checked = addressingIdentity.autoQuote;
-  document.getElementById('identity.replyOnTop').value = addressingIdentity.replyOnTop;
-  document.getElementById('identity.sig_bottom').value = addressingIdentity.sigBottom;
-  document.getElementById('identity.sig_on_reply').checked = addressingIdentity.sigOnReply;
-  document.getElementById('identity.sig_on_fwd').checked = addressingIdentity.sigOnForward;
+  document.getElementById("identity.composeHtml").checked = addressingIdentity.composeHtml;
+  document.getElementById("identity.autoQuote").checked = addressingIdentity.autoQuote;
+  document.getElementById("identity.replyOnTop").value = addressingIdentity.replyOnTop;
+  document.getElementById("identity.sig_bottom").value = addressingIdentity.sigBottom;
+  document.getElementById("identity.sig_on_reply").checked = addressingIdentity.sigOnReply;
+  document.getElementById("identity.sig_on_fwd").checked = addressingIdentity.sigOnForward;
 
   onInitCompositionAndAddressing(); // am-addressing.js method
 }
 
-function onOk(event)
-{
+function onOk(event) {
   if (!validEmailAddress()) {
     event.preventDefault();
     return;
   }
 
   // if we are adding a new identity, create an identity, set the fields and add it to the
   // account.
-  if (!gIdentity)
-  {
+  if (!gIdentity) {
     // ask the account manager to create a new identity for us
     gIdentity = MailServices.accounts.createIdentity();
 
     // copy in the default identity settings so we inherit lots of stuff like the default drafts folder, etc.
     gIdentity.copy(gAccount.defaultIdentity);
 
     // assume the identity is valid by default?
     gIdentity.valid = true;
@@ -165,109 +159,101 @@ function onOk(event)
   saveCopiesAndFolderSettings(gIdentity);
   saveAddressingAndCompositionSettings(gIdentity);
 
   window.arguments[0].result = true;
 }
 
 // returns false and prompts the user if
 // the identity does not have an email address
-function validEmailAddress()
-{
-  var emailAddress = document.getElementById('identity.email').value;
+function validEmailAddress() {
+  var emailAddress = document.getElementById("identity.email").value;
 
   // quickly test for an @ sign to test for an email address. We don't have
   // to be anymore precise than that.
-  if (!emailAddress.includes("@"))
-  {
+  if (!emailAddress.includes("@")) {
     // alert user about an invalid email address
 
     var prefBundle = document.getElementById("bundle_prefs");
 
     Services.prompt.alert(window, prefBundle.getString("identity-edit-req-title"),
                           prefBundle.getString("identity-edit-req"));
     return false;
   }
 
   return true;
 }
 
-function saveIdentitySettings(identity)
-{
-  if (identity)
-  {
-    let idLabel = document.getElementById('identity.label');
+function saveIdentitySettings(identity) {
+  if (identity) {
+    let idLabel = document.getElementById("identity.label");
     if (idLabel)
       identity.label = idLabel.value;
-    identity.fullName = document.getElementById('identity.fullName').value;
-    identity.email = document.getElementById('identity.email').value;
-    identity.replyTo = document.getElementById('identity.replyTo').value;
-    identity.organization = document.getElementById('identity.organization').value;
-    identity.attachSignature = document.getElementById('identity.attachSignature').checked;
-    identity.htmlSigText = document.getElementById('identity.htmlSigText').value;
-    identity.htmlSigFormat = document.getElementById('identity.htmlSigFormat').checked;
+    identity.fullName = document.getElementById("identity.fullName").value;
+    identity.email = document.getElementById("identity.email").value;
+    identity.replyTo = document.getElementById("identity.replyTo").value;
+    identity.organization = document.getElementById("identity.organization").value;
+    identity.attachSignature = document.getElementById("identity.attachSignature").checked;
+    identity.htmlSigText = document.getElementById("identity.htmlSigText").value;
+    identity.htmlSigFormat = document.getElementById("identity.htmlSigFormat").checked;
 
-    identity.attachVCard = document.getElementById('identity.attachVCard').checked;
-    identity.escapedVCard = document.getElementById('identity.escapedVCard').value;
-    identity.smtpServerKey = document.getElementById('identity.smtpServerKey').value;
+    identity.attachVCard = document.getElementById("identity.attachVCard").checked;
+    identity.escapedVCard = document.getElementById("identity.escapedVCard").value;
+    identity.smtpServerKey = document.getElementById("identity.smtpServerKey").value;
 
-    var attachSignaturePath = document.getElementById('identity.signature').value;
+    let attachSignaturePath = document.getElementById("identity.signature").value;
     identity.signature = null; // this is important so we don't accidentally inherit the default
 
-    if (attachSignaturePath)
-    {
+    if (attachSignaturePath) {
       // convert signature path back into a nsIFile
       var sfile = Cc["@mozilla.org/file/local;1"]
                   .createInstance(Ci.nsIFile);
       sfile.initWithPath(attachSignaturePath);
       if (sfile.exists())
         identity.signature = sfile;
     }
   }
 }
 
-function saveCopiesAndFolderSettings(identity)
-{
+function saveCopiesAndFolderSettings(identity) {
   onSaveCopiesAndFolders(); // am-copies.js routine
 
-  identity.fccFolder =  document.getElementById('identity.fccFolder').value;
-  identity.draftFolder = document.getElementById('identity.draftFolder').value;
-  identity.archiveFolder = document.getElementById('identity.archiveFolder').value;
-  identity.stationeryFolder = document.getElementById('identity.stationeryFolder').value;
-  identity.fccFolderPickerMode = document.getElementById('identity.fccFolderPickerMode').value;
-  identity.draftsFolderPickerMode = document.getElementById('identity.draftsFolderPickerMode').value;
-  identity.archivesFolderPickerMode = document.getElementById('identity.archivesFolderPickerMode').value;
-  identity.tmplFolderPickerMode = document.getElementById('identity.tmplFolderPickerMode').value;
-  identity.doCc = document.getElementById('identity.doCc').checked;
-  identity.doCcList = document.getElementById('identity.doCcList').value;
-  identity.doBcc = document.getElementById('identity.doBcc').checked;
-  identity.doBccList = document.getElementById('identity.doBccList').value;
-  identity.doFcc = document.getElementById('identity.doFcc').checked;
-  identity.fccReplyFollowsParent = document.getElementById('identity.fccReplyFollowsParent').checked;
-  identity.showSaveMsgDlg = document.getElementById('identity.showSaveMsgDlg').checked;
-  identity.archiveEnabled = document.getElementById('identity.archiveEnabled').checked;
+  identity.fccFolder =  document.getElementById("identity.fccFolder").value;
+  identity.draftFolder = document.getElementById("identity.draftFolder").value;
+  identity.archiveFolder = document.getElementById("identity.archiveFolder").value;
+  identity.stationeryFolder = document.getElementById("identity.stationeryFolder").value;
+  identity.fccFolderPickerMode = document.getElementById("identity.fccFolderPickerMode").value;
+  identity.draftsFolderPickerMode = document.getElementById("identity.draftsFolderPickerMode").value;
+  identity.archivesFolderPickerMode = document.getElementById("identity.archivesFolderPickerMode").value;
+  identity.tmplFolderPickerMode = document.getElementById("identity.tmplFolderPickerMode").value;
+  identity.doCc = document.getElementById("identity.doCc").checked;
+  identity.doCcList = document.getElementById("identity.doCcList").value;
+  identity.doBcc = document.getElementById("identity.doBcc").checked;
+  identity.doBccList = document.getElementById("identity.doBccList").value;
+  identity.doFcc = document.getElementById("identity.doFcc").checked;
+  identity.fccReplyFollowsParent = document.getElementById("identity.fccReplyFollowsParent").checked;
+  identity.showSaveMsgDlg = document.getElementById("identity.showSaveMsgDlg").checked;
+  identity.archiveEnabled = document.getElementById("identity.archiveEnabled").checked;
 }
 
-function saveAddressingAndCompositionSettings(identity)
-{
-  identity.directoryServer = document.getElementById('identity.directoryServer').value;
-  identity.overrideGlobalPref = document.getElementById('identity.overrideGlobal_Pref').value == "true";
-  let autoCompleteElement = document.getElementById('identity.autocompleteToMyDomain');
+function saveAddressingAndCompositionSettings(identity) {
+  identity.directoryServer = document.getElementById("identity.directoryServer").value;
+  identity.overrideGlobalPref = document.getElementById("identity.overrideGlobal_Pref").value == "true";
+  let autoCompleteElement = document.getElementById("identity.autocompleteToMyDomain");
   if (autoCompleteElement) // Thunderbird does not have this element.
     identity.autocompleteToMyDomain = autoCompleteElement.checked;
-  identity.composeHtml = document.getElementById('identity.composeHtml').checked;
-  identity.autoQuote = document.getElementById('identity.autoQuote').checked;
-  identity.replyOnTop = document.getElementById('identity.replyOnTop').value;
-  identity.sigBottom = document.getElementById('identity.sig_bottom').value == 'true';
-  identity.sigOnReply = document.getElementById('identity.sig_on_reply').checked;
-  identity.sigOnForward = document.getElementById('identity.sig_on_fwd').checked;
+  identity.composeHtml = document.getElementById("identity.composeHtml").checked;
+  identity.autoQuote = document.getElementById("identity.autoQuote").checked;
+  identity.replyOnTop = document.getElementById("identity.replyOnTop").value;
+  identity.sigBottom = document.getElementById("identity.sig_bottom").value == "true";
+  identity.sigOnReply = document.getElementById("identity.sig_on_reply").checked;
+  identity.sigOnForward = document.getElementById("identity.sig_on_fwd").checked;
 }
 
-function selectFile()
-{
+function selectFile() {
   const nsIFilePicker = Ci.nsIFilePicker;
 
   var fp = Cc["@mozilla.org/filepicker;1"]
              .createInstance(nsIFilePicker);
 
   var prefBundle = document.getElementById("bundle_prefs");
   var title = prefBundle.getString("choosefile");
   fp.init(window, title, nsIFilePicker.modeOpen);
@@ -283,143 +269,132 @@ function selectFile()
   fp.open(rv => {
     if (rv != nsIFilePicker.returnOK || !fp.file) {
       return;
     }
     document.getElementById("identity.signature").value = fp.file.path;
   });
 }
 
-function GetSigFolder()
-{
+function GetSigFolder() {
   var sigFolder = null;
-  try
-  {
+  try {
     var account = parent.getCurrentAccount();
     var identity = account.defaultIdentity;
     var signatureFile = identity.signature;
 
-    if (signatureFile)
-    {
+    if (signatureFile) {
       signatureFile = signatureFile.QueryInterface(Ci.nsIFile);
       sigFolder = signatureFile.parent;
 
       if (!sigFolder.exists())
           sigFolder = null;
     }
-  }
-  catch (ex) {
+  } catch (ex) {
       dump("failed to get signature folder..\n");
   }
   return sigFolder;
 }
 
 // Signature textbox is active unless option to select from file is checked.
 // If a signature is need to be attached, the associated items which
 // displays the absolute path to the signature (in a textbox) and the way
 // to select a new signature file (a button) are enabled. Otherwise, they
 // are disabled. Check to see if the attachSignature is locked to block
 // broadcasting events.
-function setupSignatureItems()
-{
+function setupSignatureItems() {
   var signature = document.getElementById("identity.signature");
   var browse = document.getElementById("identity.sigbrowsebutton");
   var htmlSigText = document.getElementById("identity.htmlSigText");
   var htmlSigFormat = document.getElementById("identity.htmlSigFormat");
   var attachSignature = document.getElementById("identity.attachSignature");
   var checked = attachSignature.checked;
 
-  if (checked)
-  {
+  if (checked) {
     htmlSigText.setAttribute("disabled", "true");
     htmlSigFormat.setAttribute("disabled", "true");
-  }
-  else
-  {
+  } else {
     htmlSigText.removeAttribute("disabled");
     htmlSigFormat.removeAttribute("disabled");
   }
 
   if (checked && !getAccountValueIsLocked(signature))
     signature.removeAttribute("disabled");
   else
     signature.setAttribute("disabled", "true");
 
   if (checked && !getAccountValueIsLocked(browse))
     browse.removeAttribute("disabled");
   else
     browse.setAttribute("disabled", "true");
 }
 
-function editVCardCallback(escapedVCardStr)
-{
+function editVCardCallback(escapedVCardStr) {
   var escapedVCard = document.getElementById("identity.escapedVCard");
   escapedVCard.value = escapedVCardStr;
 }
 
-function editVCard()
-{
+function editVCard() {
   var escapedVCard = document.getElementById("identity.escapedVCard");
 
   // read vCard hidden value from UI
   window.openDialog("chrome://messenger/content/addressbook/abNewCardDialog.xul",
                     "",
                     "chrome,modal,resizable=no,centerscreen",
-                    {escapedVCardStr:escapedVCard.value, okCallback:editVCardCallback,
-                     titleProperty:"editVCardTitle", hideABPicker:true});
+                    {
+                      escapedVCardStr: escapedVCard.value,
+                      okCallback: editVCardCallback,
+                      titleProperty: "editVCardTitle",
+                      hideABPicker: true,
+                    });
 }
 
-function getAccountForFolderPickerState()
-{
+function getAccountForFolderPickerState() {
   return gAccount;
 }
 
 /**
  * Build the SMTP server list for display.
  */
-function loadSMTPServerList()
-{
+function loadSMTPServerList() {
   var smtpServerList = document.getElementById("identity.smtpServerKey");
   let servers = MailServices.smtp.servers;
   let defaultServer = MailServices.smtp.defaultServer;
   let currentValue = smtpServerList.value;
 
   var smtpPopup = smtpServerList.menupopup;
   while (smtpPopup.lastChild.nodeName != "menuseparator")
     smtpPopup.lastChild.remove();
 
-  while (servers.hasMoreElements())
-  {
+  while (servers.hasMoreElements()) {
     var server = servers.getNext();
 
-    if (server instanceof Ci.nsISmtpServer)
-    {
+    if (server instanceof Ci.nsISmtpServer) {
       var serverName = "";
       if (server.description)
-        serverName = server.description + ' - ';
+        serverName = server.description + " - ";
       else if (server.username)
-        serverName = server.username + ' - ';
+        serverName = server.username + " - ";
       serverName += server.hostname;
 
       if (defaultServer.key == server.key)
         serverName += " " + document.getElementById("bundle_messenger")
                                     .getString("defaultServerTag");
 
       smtpServerList.appendItem(serverName, server.key);
     }
   }
 
   smtpServerList.value = currentValue;
 }
 
 /**
  * Open dialog for editing properties of currently selected SMTP server.
  */
-function editCurrentSMTP()
-{
+function editCurrentSMTP() {
   let smtpKey = document.getElementById("identity.smtpServerKey").value;
   let server = (smtpKey === "") ? MailServices.smtp.defaultServer :
                                   MailServices.smtp.getServerByKey(smtpKey);
 
   let args = editSMTPServer(server);
   if (args.result)
     loadSMTPServerList();
 }
--- a/mailnews/base/prefs/content/am-junk.js
+++ b/mailnews/base/prefs/content/am-junk.js
@@ -1,24 +1,25 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/.
- */
+ * file, you can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* import-globals-from AccountManager.js */
+
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 
 var gDeferredToAccount = "";
 
-function onInit(aPageId, aServerId)
-{
+function onInit(aPageId, aServerId) {
   // manually adjust several pref UI elements
-  document.getElementById('server.spamLevel.visible').setAttribute("checked",
-    document.getElementById('server.spamLevel').value > 0);
+  document.getElementById("server.spamLevel.visible").setAttribute("checked",
+    document.getElementById("server.spamLevel").value > 0);
 
   let deferredToURI = null;
   if (gDeferredToAccount)
     deferredToURI = MailServices.accounts
                                 .getAccount(gDeferredToAccount)
                                 .incomingServer.serverURI;
 
   let spamActionTargetAccountElement =
@@ -102,54 +103,50 @@ function onInit(aPageId, aServerId)
     serverFilterList.selectedIndex = 0;
 
   // enable or disable the useServerFilter checkbox
   onCheckItem("useServerFilterList", ["server.useServerFilter"]);
 
   updateJunkTargetsAndRetention();
 }
 
-function onPreInit(account, accountValues)
-{
+function onPreInit(account, accountValues) {
   if (getAccountValue(account, accountValues, "server", "type", null, false) == "pop3")
     gDeferredToAccount = getAccountValue(account, accountValues,
                                          "pop3", "deferredToAccount",
                                          null, false);
 
   buildServerFilterMenuList();
 }
 
 /**
  * Called when someone checks or unchecks the adaptive junk mail checkbox.
  * set the value of the hidden element accordingly
  *
  * @param aValue  the boolean value of the checkbox
  */
-function updateSpamLevel(aValue)
-{
-  document.getElementById('server.spamLevel').value = aValue ? 100 : 0;
+function updateSpamLevel(aValue) {
+  document.getElementById("server.spamLevel").value = aValue ? 100 : 0;
   onAdaptiveJunkToggle();
 }
 
 /**
  * Propagate changes to the server filter menu list back to
  * our hidden wsm element.
  */
-function onServerFilterListChange()
-{
-  document.getElementById('server.serverFilterName').value =
+function onServerFilterListChange() {
+  document.getElementById("server.serverFilterName").value =
     document.getElementById("useServerFilterList").value;
 }
 
 /**
  * Called when someone checks or unchecks the adaptive junk mail checkbox.
  * We need to enable or disable the whitelist accordingly.
  */
-function onAdaptiveJunkToggle()
-{
+function onAdaptiveJunkToggle() {
   onCheckItem("whiteListAbURI", ["server.spamLevel.visible"]);
   onCheckItem("whiteListLabel", ["server.spamLevel.visible"]);
 
   // Enable/disable individual listbox rows.
   // Setting enable/disable on the parent listbox does not seem to work.
   let wList = document.getElementById("whiteListAbURI");
   let wListDisabled = wList.disabled;
 
@@ -173,43 +170,40 @@ function updateJunkTargetsAndRetention()
   updateJunkRetention();
 }
 
 /**
  * Enable/disable the folder pickers depending on which radio item is selected.
  */
 function updateJunkTargets() {
   onCheckItem("actionTargetAccount", ["server.moveOnSpam", "moveTargetMode0"]);
-  onCheckItem("actionTargetFolder",  ["server.moveOnSpam", "moveTargetMode1"]);
+  onCheckItem("actionTargetFolder", ["server.moveOnSpam", "moveTargetMode1"]);
 }
 
 /**
  * Enable/disable the junk deletion interval depending on the state
  * of the controlling checkbox.
  */
 function updateJunkRetention() {
   onCheckItem("server.purgeSpamInterval", ["server.purgeSpam", "server.moveOnSpam"]);
 }
 
-function onSave()
-{
+function onSave() {
   onSaveWhiteList();
 }
 
 /**
  * Propagate changes to the whitelist menu list back to
  * our hidden wsm element.
  */
-function onSaveWhiteList()
-{
+function onSaveWhiteList() {
   var wList = document.getElementById("whiteListAbURI");
   var wlArray = [];
 
-  for (var i = 0; i < wList.getRowCount(); i++)
-  {
+  for (let i = 0; i < wList.getRowCount(); i++) {
     // Due to bug 448582, do not trust any properties of the listitems
     // as they may not return the right value or may even not exist.
     // Always get the attributes only.
     var wlNode = wList.getItemAtIndex(i);
     if (wlNode.firstChild.getAttribute("checked") == "true") {
       let abURI = wlNode.getAttribute("value");
       wlArray.push(abURI);
     }
@@ -218,42 +212,39 @@ function onSaveWhiteList()
   document.getElementById("server.whiteListAbURI").setAttribute("value", wlValue);
   document.getElementById("server.useWhiteList").checked = (wlValue != "");
 }
 
 /**
  * Called when a new value is chosen in one of the junk target folder pickers.
  * Sets the menu label according to the folder name.
  */
-function onActionTargetChange(aEvent, aWSMElementId)
-{
+function onActionTargetChange(aEvent, aWSMElementId) {
   let folder = aEvent.target._folder;
   document.getElementById(aWSMElementId).value = folder.URI;
   document.getElementById("actionFolderPopup").selectFolder(folder);
 }
 
 /**
  * Enumerates over the "ISPDL" directories, calling buildServerFilterListFromDir
  * for each one.
  */
-function buildServerFilterMenuList()
-{
+function buildServerFilterMenuList() {
   const KEY_ISP_DIRECTORY_LIST = "ISPDL";
   let ispHeaderList = document.getElementById("useServerFilterList");
 
   // Ensure the menulist is empty.
   ispHeaderList.removeAllItems();
 
   // Now walk through the isp directories looking for sfd files.
   let ispDirectories = Services.dirsvc.get(KEY_ISP_DIRECTORY_LIST,
                                            Ci.nsISimpleEnumerator);
 
   let menuEntries = [];
-  while (ispDirectories.hasMoreElements())
-  {
+  while (ispDirectories.hasMoreElements()) {
     let ispDirectory = ispDirectories.getNext()
                                      .QueryInterface(Ci.nsIFile);
     if (ispDirectory)
       menuEntries.push.apply(menuEntries, buildServerFilterListFromDir(ispDirectory, menuEntries));
   }
 
   menuEntries.sort((a, b) => a.localeCompare(b));
   for (let entry of menuEntries) {
@@ -264,36 +255,34 @@ function buildServerFilterMenuList()
 /**
  * Helper function called by buildServerFilterMenuList. Enumerates over the
  * passed in directory looking for .sfd files. For each entry found, it gets
  * appended to the menu list.
  *
  * @param aDir              directory to look for .sfd files
  * @param aExistingEntries  Filter names already found.
  */
-function buildServerFilterListFromDir(aDir, aExistingEntries)
-{
+function buildServerFilterListFromDir(aDir, aExistingEntries) {
   let newEntries = [];
   // Now iterate over each file in the directory looking for .sfd files.
   const kSuffix = ".sfd";
   let entries = aDir.directoryEntries
                     .QueryInterface(Ci.nsIDirectoryEnumerator);
 
   while (entries.hasMoreElements()) {
     let entry = entries.nextFile;
     // we only care about files that end in .sfd
     if (entry.isFile() && entry.leafName.endsWith(kSuffix)) {
       let fileName = entry.leafName.slice(0, -kSuffix.length);
       // If we've already added an item with this name, then don't add it again.
-      if (aExistingEntries.indexOf(fileName) == -1)
+      if (!aExistingEntries.includes(fileName))
         newEntries.push(fileName);
     }
   }
   return newEntries;
 }
 
 /**
  * Open the Preferences dialog on the Junk settings tab.
  */
-function showGlobalJunkPrefs()
-{
+function showGlobalJunkPrefs() {
   openPrefsFromAccountManager("paneSecurity", "junkTab", null, "junk_pane");
 }
--- a/mailnews/base/prefs/content/am-main.js
+++ b/mailnews/base/prefs/content/am-main.js
@@ -1,51 +1,50 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from am-identity-edit.js */
+
 var gAccount;
 
-function onInit(aPageId, aServerId)
-{
+function onInit(aPageId, aServerId) {
   var accountName = document.getElementById("server.prettyName");
   var title = document.querySelector("#am-main-title .dialogheader-title");
   var defaultTitle = title.getAttribute("defaultTitle");
   var titleValue;
 
-  if(accountName.value)
-    titleValue = defaultTitle+" - <"+accountName.value+">";
+  if (accountName.value)
+    titleValue = defaultTitle + " - <" + accountName.value + ">";
   else
     titleValue = defaultTitle;
 
   title.setAttribute("value", titleValue);
   document.title = titleValue;
 
   setupSignatureItems();
 }
 
-function onPreInit(account, accountValues)
-{
+function onPreInit(account, accountValues) {
   gAccount = account;
   loadSMTPServerList();
 }
 
-function manageIdentities()
-{
+function manageIdentities() {
   // We want to save the current identity information before bringing up the multiple identities
   // UI. This ensures that the changes are reflected in the identity list dialog
   // onSave();
 
   if (!gAccount)
     return;
 
   var accountName = document.getElementById("server.prettyName").value;
 
-  var args = { account: gAccount, accountName: accountName, result: false };
+  var args = { account: gAccount, accountName, result: false };
 
   // save the current identity settings so they show up correctly
   // if the user just changed them in the manage identities dialog
   var identity = gAccount.defaultIdentity;
   saveIdentitySettings(identity);
 
   window.openDialog("am-identities-list.xul", "", "chrome,modal,resizable=no,centerscreen", args);
 
--- a/mailnews/base/prefs/content/am-offline.js
+++ b/mailnews/base/prefs/content/am-offline.js
@@ -1,26 +1,29 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountManager.js */
+/* import-globals-from ../../content/retention.js */
+
+var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
 
 var gIncomingServer;
 var gServerType;
 var gImapIncomingServer;
 var gPref = null;
 var gLockedPref = null;
 var gOfflineMap = null; // map of folder URLs to offline flags
 var gOfflineFolders;    // initial state of allFoldersOffline checkbox
 var gToggleOccurred = false;
 
-function onInit(aPageId, aServerId)
-{
+function onInit(aPageId, aServerId) {
     onLockPreference();
 
     // init values here
     initServerSettings();
     initRetentionSettings();
     initDownloadSettings();
     initOfflineSettings();
 
@@ -29,50 +32,46 @@ function onInit(aPageId, aServerId)
     onCheckItem("nntp.removeBodyMin", "nntp.removeBody");
     onCheckKeepMsg();
 }
 
 /**
  * Store initial offline flag for each folder and the allFoldersOffline
  * checkbox. Use to restore the flags and checkbox if edits are canceled.
  */
-function initOfflineSettings()
-{
+function initOfflineSettings() {
     gOfflineMap = collectOfflineFolders();
     gOfflineFolders = document.getElementById("offline.folders").checked;
     gToggleOccurred = false;
 }
 
-function initServerSettings()
-{
+function initServerSettings() {
     document.getElementById("offline.notDownload").checked =  gIncomingServer.limitOfflineMessageSize;
     document.getElementById("autosync.notDownload").checked =  gIncomingServer.limitOfflineMessageSize;
-    if(gIncomingServer.maxMessageSize > 0)
+    if (gIncomingServer.maxMessageSize > 0)
         document.getElementById("offline.notDownloadMin").value = gIncomingServer.maxMessageSize;
     else
         document.getElementById("offline.notDownloadMin").value = "50";
 
-    if(gServerType == "imap") {
+    if (gServerType == "imap") {
         gImapIncomingServer = gIncomingServer.QueryInterface(Ci.nsIImapIncomingServer);
         document.getElementById("offline.folders").checked =  gImapIncomingServer.offlineDownload;
     }
 }
 
-function initRetentionSettings()
-{
+function initRetentionSettings() {
   let retentionSettings = gIncomingServer.retentionSettings;
   initCommonRetentionSettings(retentionSettings);
 
   document.getElementById("nntp.removeBody").checked = retentionSettings.cleanupBodiesByDays;
   document.getElementById("nntp.removeBodyMin").value =
     (retentionSettings.daysToKeepBodies > 0) ? retentionSettings.daysToKeepBodies : 30;
 }
 
-function initDownloadSettings()
-{
+function initDownloadSettings() {
   let downloadSettings = gIncomingServer.downloadSettings;
   document.getElementById("nntp.downloadMsg").checked = downloadSettings.downloadByDate;
   document.getElementById("nntp.notDownloadRead").checked = downloadSettings.downloadUnreadOnly;
   document.getElementById("nntp.downloadMsgMin").value =
     (downloadSettings.ageLimitOfMsgsToDownload > 0) ?
       downloadSettings.ageLimitOfMsgsToDownload : 30;
 
   // Figure out what the most natural division of the autosync pref into
@@ -90,18 +89,17 @@ function initDownloadSettings()
   if (autosyncPrefValue <= 0) {
     // Special-case values <= 0 to have an interval of "All" and disabled
     // controls for value and interval.
     autosyncSelect.value = 0;
     autosyncInterval.value = 1;
     autosyncInterval.disabled = true;
     autosyncValue.value = 30;
     autosyncValue.disabled = true;
-  }
-  else {
+  } else {
     // Otherwise, get the list of possible intervals, in order from
     // largest to smallest.
     let valuesToTest = [];
     for (let i = autosyncInterval.itemCount - 1; i >= 0; i--)
       valuesToTest.push(autosyncInterval.getItemAtIndex(i).value);
 
     // and find the first one that divides the preference evenly.
     for (let i in valuesToTest) {
@@ -114,18 +112,17 @@ function initDownloadSettings()
     }
     autosyncInterval.disabled = false;
     autosyncValue.disabled = false;
   }
   autosyncPref.value = autosyncPrefValue;
 }
 
 
-function onPreInit(account, accountValues)
-{
+function onPreInit(account, accountValues) {
   gServerType = getAccountValue(account, accountValues, "server", "type", null, false);
   hideShowControls(gServerType);
   gIncomingServer = account.incomingServer;
   gIncomingServer.type = gServerType;
 
   // 10 is OFFLINE_SUPPORT_LEVEL_REGULAR, see nsIMsgIncomingServer.idl
   // currently, there is no offline without diskspace
   var titleStringID = (gIncomingServer.offlineSupportLevel >= 10) ?
@@ -145,28 +142,26 @@ function onPreInit(account, accountValue
       var retentionLabel = document.getElementById("retentionDescriptionPop");
       retentionLabel.setAttribute("hidden", "true");
       var applyToFlaggedCheckbox = document.getElementById("retention.applyToFlagged");
       applyToFlaggedCheckbox.setAttribute("hidden", "true");
     }
   }
 }
 
-function onClickSelect()
-{
+function onClickSelect() {
     top.window.openDialog("chrome://messenger/content/msgSelectOfflineFolders.xul",
                           "", "centerscreen,chrome,modal,titlebar,resizable=yes");
     return true;
 }
 
 /**
  * Handle updates to the Autosync
  */
-function onAutosyncChange()
-{
+function onAutosyncChange() {
   let autosyncSelect = document.getElementById("autosyncSelect");
   let autosyncInterval = document.getElementById("autosyncInterval");
   let autosyncValue = document.getElementById("autosyncValue");
   let autosyncPref = document.getElementById("imap.autoSyncMaxAgeDays");
 
   // If we're not done initializing, don't do anything.
   // (See initDownloadSettings() for more details.)
   if (autosyncPref.value == "")
@@ -186,38 +181,35 @@ function onAutosyncChange()
   if (autosyncValue.value > max)
     autosyncValue.value = Math.floor(max);
 
   autosyncInterval.disabled = false;
   autosyncValue.disabled = false;
   autosyncPref.value = autosyncValue.value * autosyncInterval.value;
 }
 
-function onAutosyncNotDownload()
-{
+function onAutosyncNotDownload() {
   // This function is called when the autosync version of offline.notDownload
   // is changed it simply copies the new checkbox value over to the element
   // driving the preference.
   document.getElementById("offline.notDownload").checked =
     document.getElementById("autosync.notDownload").checked;
   onCheckItem("offline.notDownloadMin", "offline.notDownload");
 }
 
-function onCancel()
-{
+function onCancel() {
     // restore the offline flags for all folders
     restoreOfflineFolders(gOfflineMap);
     document.getElementById("offline.folders").checked = gOfflineFolders;
 }
 
 /**
  * Prompt to avoid unexpected folder sync changes.
  */
-function onLeave()
-{
+function onLeave() {
   let changed = false;
   if (gToggleOccurred) {
     let allFolders = gIncomingServer.rootFolder.descendants;
     for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
       if (gOfflineMap[folder.folderURL] !=
           folder.getFlag(Ci.nsMsgFolderFlags.Offline)) {
         // A change to the Offline flag to a folder was made.
         changed = true;
@@ -235,30 +227,29 @@ function onLeave()
     let title = prefBundle.getString("confirmSyncChangesTitle");
     let question = prefBundle.getString("confirmSyncChanges");
     let discard = prefBundle.getString("confirmSyncChangesDiscard");
     let result = Services.prompt
                          .confirmEx(window, title, question,
                                     (Services.prompt.BUTTON_TITLE_SAVE * Services.prompt.BUTTON_POS_0) +
                                     (Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_1),
                                     null, discard, null,
-                                    null, {value:0});
+                                    null, {value: 0});
     if (result == 1) {
       // User clicked Discard button, so restore the online/offline changes for
       // the current account.  Changes made through the "Advanced..." dialog to
       // other accounts will not be restored.
       onCancel();
       return false;
     }
   }
   return true;
 }
 
-function onSave()
-{
+function onSave() {
     var downloadSettings =
       Cc["@mozilla.org/msgDatabase/downloadSettings;1"]
         .createInstance(Ci.nsIMsgDownloadSettings);
 
     gIncomingServer.limitOfflineMessageSize = document.getElementById("offline.notDownload").checked;
     gIncomingServer.maxMessageSize = document.getElementById("offline.notDownloadMin").value;
 
     var retentionSettings = saveCommonRetentionSettings(gIncomingServer.retentionSettings);
@@ -277,125 +268,115 @@ function onSave()
         // Set the pref on the incomingserver, and set the flag on all folders.
         gImapIncomingServer.offlineDownload = document.getElementById("offline.folders").checked;
     }
 }
 
 // Does the work of disabling an element given the array which contains xul id/prefstring pairs.
 // Also saves the id/locked state in an array so that other areas of the code can avoid
 // stomping on the disabled state indiscriminately.
-function disableIfLocked( prefstrArray )
-{
+function disableIfLocked(prefstrArray) {
     if (!gLockedPref)
-      gLockedPref = new Array;
+      gLockedPref = [];
 
-    for (var i=0; i<prefstrArray.length; i++) {
+    for (let i = 0; i < prefstrArray.length; i++) {
         var id = prefstrArray[i].id;
         var element = document.getElementById(id);
         if (gPref.prefIsLocked(prefstrArray[i].prefstring)) {
             element.disabled = true;
             gLockedPref[id] = true;
         } else {
             element.removeAttribute("disabled");
             gLockedPref[id] = false;
         }
     }
 }
 
 // Disables xul elements that have associated preferences locked.
-function onLockPreference()
-{
-    var isDownloadLocked = false;
-    var isGetNewLocked = false;
+function onLockPreference() {
     var initPrefString = "mail.server";
     var finalPrefString;
 
     // This panel does not use the code in AccountManager.js to handle
     // the load/unload/disable.  keep in mind new prefstrings and changes
     // to code in AccountManager, and update these as well.
     var allPrefElements = [
-      { prefstring:"limit_offline_message_size", id:"offline.notDownload"},
-      { prefstring:"limit_offline_message_size", id:"autosync.notDownload"},
-      { prefstring:"max_size", id:"offline.notDownloadMin"},
-      { prefstring:"downloadUnreadOnly", id:"nntp.notDownloadRead"},
-      { prefstring:"downloadByDate", id:"nntp.downloadMsg"},
-      { prefstring:"ageLimit", id:"nntp.downloadMsgMin"},
-      { prefstring:"retainBy", id:"retention.keepMsg"},
-      { prefstring:"daysToKeepHdrs", id:"retention.keepOldMsgMin"},
-      { prefstring:"numHdrsToKeep", id:"retention.keepNewMsgMin"},
-      { prefstring:"daysToKeepBodies", id:"nntp.removeBodyMin"},
-      { prefstring:"cleanupBodies", id:"nntp.removeBody" },
-      { prefstring:"applyToFlagged", id:"retention.applyToFlagged"},
-      { prefstring:"disable_button.selectFolder", id:"selectNewsgroupsButton"},
-      { prefstring:"disable_button.selectFolder", id:"selectImapFoldersButton"}
+      { prefstring: "limit_offline_message_size", id: "offline.notDownload" },
+      { prefstring: "limit_offline_message_size", id: "autosync.notDownload" },
+      { prefstring: "max_size", id: "offline.notDownloadMin" },
+      { prefstring: "downloadUnreadOnly", id: "nntp.notDownloadRead" },
+      { prefstring: "downloadByDate", id: "nntp.downloadMsg" },
+      { prefstring: "ageLimit", id: "nntp.downloadMsgMin" },
+      { prefstring: "retainBy", id: "retention.keepMsg" },
+      { prefstring: "daysToKeepHdrs", id: "retention.keepOldMsgMin" },
+      { prefstring: "numHdrsToKeep", id: "retention.keepNewMsgMin" },
+      { prefstring: "daysToKeepBodies", id: "nntp.removeBodyMin" },
+      { prefstring: "cleanupBodies", id: "nntp.removeBody" },
+      { prefstring: "applyToFlagged", id: "retention.applyToFlagged" },
+      { prefstring: "disable_button.selectFolder", id: "selectNewsgroupsButton" },
+      { prefstring: "disable_button.selectFolder", id: "selectImapFoldersButton" },
     ];
 
     finalPrefString = initPrefString + "." + gIncomingServer.key + ".";
     gPref = Services.prefs.getBranch(finalPrefString);
 
-    disableIfLocked( allPrefElements );
+    disableIfLocked(allPrefElements);
 }
 
-function onCheckItem(changeElementId, checkElementId)
-{
+function onCheckItem(changeElementId, checkElementId) {
     var element = document.getElementById(changeElementId);
     var checked = document.getElementById(checkElementId).checked;
-    if(checked && !gLockedPref[checkElementId] ) {
+    if (checked && !gLockedPref[checkElementId]) {
         element.removeAttribute("disabled");
-    }
-    else {
+    } else {
         element.setAttribute("disabled", "true");
     }
 }
 
-function toggleOffline()
-{
+function toggleOffline() {
     let offline = document.getElementById("offline.folders").checked;
     let allFolders = gIncomingServer.rootFolder.descendants;
     for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
       if (offline)
         folder.setFlag(Ci.nsMsgFolderFlags.Offline);
       else
         folder.clearFlag(Ci.nsMsgFolderFlags.Offline);
     }
     gToggleOccurred = true;
 }
 
-function collectOfflineFolders()
-{
+function collectOfflineFolders() {
     let offlineFolderMap = {};
     let allFolders = gIncomingServer.rootFolder.descendants;
     for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder))
       offlineFolderMap[folder.folderURL] = folder.getFlag(Ci.nsMsgFolderFlags.Offline);
 
     return offlineFolderMap;
 }
 
-function restoreOfflineFolders(offlineFolderMap)
-{
+function restoreOfflineFolders(offlineFolderMap) {
     let allFolders = gIncomingServer.rootFolder.descendants;
     for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
       if (offlineFolderMap[folder.folderURL])
         folder.setFlag(Ci.nsMsgFolderFlags.Offline);
       else
         folder.clearFlag(Ci.nsMsgFolderFlags.Offline);
     }
 }
 
 /**
  * Checks if the user selected a permanent removal of messages from a server
  * listed in the confirmfor attribute and warns about it.
  *
  * @param aRadio  The radiogroup element containing the retention options.
  */
-function warnServerRemove(aRadio)
-{
+function warnServerRemove(aRadio) {
   let confirmFor = aRadio.getAttribute("confirmfor");
 
-  if (confirmFor && confirmFor.split(',').includes(gServerType) && aRadio.value != 1) {
+  if (confirmFor && confirmFor.split(",").includes(gServerType) && aRadio.value != 1) {
     let prefBundle = document.getElementById("bundle_prefs");
     let title = prefBundle.getString("removeFromServerTitle");
     let question = prefBundle.getString("removeFromServer");
     if (!Services.prompt.confirm(window, title, question)) {
       // If the user doesn't agree, fall back to not deleting anything.
       aRadio.value = 1;
       onCheckKeepMsg();
     }
--- a/mailnews/base/prefs/content/am-offline.xul
+++ b/mailnews/base/prefs/content/am-offline.xul
@@ -145,17 +145,17 @@
     <hbox align="center" class="indent">
       <checkbox id="retention.applyToFlagged"
                 label="&retentionApplyToFlagged.label;" hidefor=""
                 accesskey="&retentionApplyToFlagged.accesskey;"
                 checked="true"/>
     </hbox>
     <hbox align="center" class="indent" hidefor="movemail,pop3,imap,none,rss">
         <checkbox id="nntp.removeBody" accesskey="&nntpRemoveMsgBody.accesskey;"
-                  label="&nntpRemoveMsgBody.label;" oncommand="onCheckItem('nntp.removeBodyMin','nntp.removeBody');"/>
+                  label="&nntpRemoveMsgBody.label;" oncommand="onCheckItem('nntp.removeBodyMin', 'nntp.removeBody');"/>
         <textbox id="nntp.removeBodyMin" size="2" value="30"
                  type="number" min="1"
                  aria-labelledby="nntp.removeBody nntp.removeBodyMin daysOldMsg"/>
         <label value="&daysOld.label;" control="nntp.removeBodyMin" id="daysOldMsg"/>
     </hbox>
     </vbox>
     </groupbox>
   </vbox>
--- a/mailnews/base/prefs/content/am-prefs.js
+++ b/mailnews/base/prefs/content/am-prefs.js
@@ -16,18 +16,17 @@ var {Services} = ChromeUtils.import("res
  * @param aStr  The string is a prefstring with a token %tokenname%.
  * @param aElement  The xul element has an attribute of name |tokenname|
  *                  whose value is substituted into the string and returned
  *                  by the function.
  *
  * Any tokens which do not have associated attribute value
  * are not substituted, and left in the string as-is.
  */
-function substPrefTokens(aStr, aElement)
-{
+function substPrefTokens(aStr, aElement) {
   let tokenpat = /%(\w+)%/;
   let token;
   let newprefstr = "";
 
   let prefPartsArray = aStr.split(".");
   /* here's a little loop that goes through
      each part of the string separated by a dot, and
      if any parts are of the form %string%, it will replace
@@ -58,18 +57,17 @@ function substPrefTokens(aStr, aElement)
  * A simple function to check if a pref in an element is locked.
  *
  * @param aElement  a xul element with the pref related attributes
  *                 (pref, preftype, prefstring)
  * @return  whether the prefstring specified in that element is
  *          locked (true/false).
  *          If it does not have a valid prefstring, a false is returned.
  */
-function getAccountValueIsLocked(aElement)
-{
+function getAccountValueIsLocked(aElement) {
   let prefstring = aElement.getAttribute("prefstring");
   if (prefstring) {
     let prefstr = substPrefTokens(prefstring, aElement);
     // see if the prefstring is locked
     if (prefstr)
       return Services.prefs.prefIsLocked(prefstr);
   }
   return false;
@@ -81,18 +79,17 @@ function getAccountValueIsLocked(aElemen
  *
  * @param aChangeElementId  Slave element which should be enabled
  *                          if all the checkElementIDs are checked.
  *                          Otherwise it gets disabled.
  * @param aCheckElementIds  An array of IDs of the master elements.
  *
  * See bug 728681 for the pattern on how this is used.
  */
-function onCheckItem(aChangeElementId, aCheckElementIds)
-{
+function onCheckItem(aChangeElementId, aCheckElementIds) {
   let elementToControl = document.getElementById(aChangeElementId);
   let disabled = false;
 
   for (let notifyId of aCheckElementIds) {
     let notifyElement = document.getElementById(notifyId);
     let notifyElementState = null;
     if ("checked" in notifyElement)
       notifyElementState = notifyElement.checked;
--- a/mailnews/base/prefs/content/am-server-advanced.js
+++ b/mailnews/base/prefs/content/am-server-advanced.js
@@ -10,66 +10,57 @@ document.addEventListener("dialogaccept"
 
 // pull stuff out of window.arguments
 var gServerSettings = window.arguments[0];
 
 var gFirstDeferredAccount;
 // initialize the controls with the "gServerSettings" argument
 
 var gControls;
-function getControls()
-{
+function getControls() {
   if (!gControls)
     gControls = document.getElementsByAttribute("amsa_persist", "true");
   return gControls;
 }
 
-function getLocalFoldersAccount()
-{
+function getLocalFoldersAccount() {
   return MailServices.accounts
     .FindAccountForServer(MailServices.accounts.localFoldersServer);
 }
 
-function onLoad()
-{
+function onLoad() {
   var prettyName = gServerSettings.serverPrettyName;
 
   if (prettyName)
     document.getElementById("serverPrettyName").value =
       document.getElementById("bundle_prefs")
               .getFormattedString("forAccount", [prettyName]);
 
-  if (gServerSettings.serverType == "imap")
-  {
+  if (gServerSettings.serverType == "imap") {
     document.getElementById("pop3Panel").hidden = true;
-  }
-  else if (gServerSettings.serverType == "pop3")
-  {
+  } else if (gServerSettings.serverType == "pop3") {
     document.getElementById("imapPanel").hidden = true;
     let radioGroup = document.getElementById("folderStorage");
 
     gFirstDeferredAccount = gServerSettings.deferredToAccount;
     let folderPopup = document.getElementById("deferredServerPopup");
 
     // The current account should not be shown in the folder picker
     // of the "other account" option.
     folderPopup._teardown();
     folderPopup.setAttribute("excludeServers",
                              gServerSettings.account.incomingServer.key);
     folderPopup._ensureInitialized();
 
-    if (gFirstDeferredAccount.length)
-    {
+    if (gFirstDeferredAccount.length) {
       // The current account is deferred.
       let account = MailServices.accounts.getAccount(gFirstDeferredAccount);
       radioGroup.value = "otherAccount";
       folderPopup.selectFolder(account.incomingServer.rootFolder);
-    }
-    else
-    {
+    } else {
       // Current account is not deferred.
       radioGroup.value = "currentAccount";
       // If there are no suitable accounts to defer to, then the menulist is
       // disabled by the picker with an appropriate message.
       folderPopup.selectFolder();
       if (gServerSettings.account.incomingServer.isDeferredTo) {
         // Some other account already defers to this account
         // therefore this one can't be deferred further.
@@ -78,82 +69,73 @@ function onLoad()
     }
 
     let picker = document.getElementById("deferredServerFolderPicker");
     picker.disabled = radioGroup.selectedIndex != 1;
   }
 
   var controls = getControls();
 
-  for (var i = 0; i < controls.length; i++)
-  {
+  for (let i = 0; i < controls.length; i++) {
     var slot = controls[i].id;
-    if (slot in gServerSettings)
-    {
+    if (slot in gServerSettings) {
       if (controls[i].localName == "checkbox")
         controls[i].checked = gServerSettings[slot];
       else
         controls[i].value = gServerSettings[slot];
     }
   }
 }
 
-function onOk(event)
-{
+function onOk(event) {
   // Handle account deferral settings for POP3 accounts.
-  if (gServerSettings.serverType == "pop3")
-  {
+  if (gServerSettings.serverType == "pop3") {
     var radioGroup = document.getElementById("folderStorage");
     var gPrefsBundle = document.getElementById("bundle_prefs");
     let picker = document.getElementById("deferredServerFolderPicker");
 
     // This account wasn't previously deferred, but is now deferred.
-    if (radioGroup.value != "currentAccount" && !gFirstDeferredAccount.length)
-    {
+    if (radioGroup.value != "currentAccount" && !gFirstDeferredAccount.length) {
       // If the user hasn't selected a folder, keep the default.
       if (!picker.selectedItem)
         return;
 
       var confirmDeferAccount =
         gPrefsBundle.getString("confirmDeferAccountWarning");
 
       var confirmTitle = gPrefsBundle.getString("confirmDeferAccountTitle");
 
       if (!Services.prompt.confirm(window, confirmTitle, confirmDeferAccount)) {
         event.preventDefault();
         return;
       }
     }
-    switch (radioGroup.value)
-    {
+    switch (radioGroup.value) {
       case "currentAccount":
-        gServerSettings['deferredToAccount'] = "";
+        gServerSettings.deferredToAccount = "";
         break;
       case "otherAccount":
         let server = picker.selectedItem._folder.server;
         let account = MailServices.accounts.FindAccountForServer(server);
-        gServerSettings['deferredToAccount'] = account.key;
+        gServerSettings.deferredToAccount = account.key;
         break;
     }
   }
 
   // Save the controls back to the "gServerSettings" array.
   var controls = getControls();
-  for (var i = 0; i < controls.length; i++)
-  {
+  for (let i = 0; i < controls.length; i++) {
     var slot = controls[i].id;
-    if (slot in gServerSettings)
-    {
+    if (slot in gServerSettings) {
       if (controls[i].localName == "checkbox")
         gServerSettings[slot] = controls[i].checked;
       else
         gServerSettings[slot] = controls[i].value;
     }
   }
 }
 
 
 // Set radio element choices and picker states
-function updateInboxAccount(enablePicker)
-{
+function updateInboxAccount(enablePicker) {
   document.getElementById("deferredServerFolderPicker").disabled = !enablePicker;
   document.getElementById("deferGetNewMail").disabled = !enablePicker;
 }
--- a/mailnews/base/prefs/content/am-server.js
+++ b/mailnews/base/prefs/content/am-server.js
@@ -1,13 +1,15 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountManager.js */
+
 var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 var {BrowserUtils} = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm");
 
 var gServer;
 var gOriginalStoreType;
 
@@ -20,17 +22,17 @@ function clickStoreTypeMenu(aStoreTypeEl
     return;
   }
 
   // Response from migration dialog modal. If the conversion is complete
   // 'response.newRootFolder' will hold the path to the new account root folder,
   // otherwise 'response.newRootFolder' will be null.
   let response = { newRootFolder: null };
   // Send 'response' as an argument to converterDialog.xhtml.
-  window.openDialog("converterDialog.xhtml","mailnews:mailstoreconverter",
+  window.openDialog("converterDialog.xhtml", "mailnews:mailstoreconverter",
                     "modal,centerscreen,resizable=no,width=700,height=130", gServer,
                     aStoreTypeElement.value, response);
   changeStoreType(response);
 }
 
 /**
  * Revert store type to the original store type if converter modal closes
  * before migration is complete, otherwise change original store type to
@@ -57,27 +59,25 @@ function changeStoreType(aResponse) {
   } else {
     // The conversion failed or was cancelled.
     // Restore selected item to what was selected before conversion.
     document.getElementById("server.storeTypeMenulist").value =
       gOriginalStoreType;
   }
 }
 
-function onSave()
-{
+function onSave() {
   let storeContractID = document.getElementById("server.storeTypeMenulist")
                                 .selectedItem
                                 .value;
   document.getElementById("server.storeContractID")
           .setAttribute("value", storeContractID);
 }
 
-function onInit(aPageId, aServerId)
-{
+function onInit(aPageId, aServerId) {
   initServerType();
 
   onCheckItem("server.biffMinutes", ["server.doBiff"]);
   onCheckItem("nntp.maxArticles", ["nntp.notifyOn"]);
   setupMailOnServerUI();
   setupFixedUI();
   let serverType = document.getElementById("server.type").getAttribute("value");
   if (serverType == "imap")
@@ -102,32 +102,29 @@ function onInit(aPageId, aServerId)
   // Disable store type change if store has not been used yet.
   storeTypeElement.setAttribute("disabled",
     gServer.getBoolValue("canChangeStoreType") ?
       "false" : !Services.prefs.getBoolPref("mail.store_conversion_enabled"));
   // Initialise 'gOriginalStoreType' to the item that was originally selected.
   gOriginalStoreType = storeTypeElement.value;
 }
 
-function onPreInit(account, accountValues)
-{
+function onPreInit(account, accountValues) {
   var type = parent.getAccountValue(account, accountValues, "server", "type", null, false);
   hideShowControls(type);
 
   gServer = account.incomingServer;
 
-  if(!account.incomingServer.canEmptyTrashOnExit)
-  {
+  if (!account.incomingServer.canEmptyTrashOnExit) {
     document.getElementById("server.emptyTrashOnExit").setAttribute("hidden", "true");
     document.getElementById("imap.deleteModel.box").setAttribute("hidden", "true");
   }
 }
 
-function initServerType()
-{
+function initServerType() {
   var serverType = document.getElementById("server.type").getAttribute("value");
   var propertyName = "serverType-" + serverType;
 
   var messengerBundle = document.getElementById("bundle_messenger");
   var verboseName = messengerBundle.getString(propertyName);
   setDivText("servertype.verbose", verboseName);
 
   secureSelect(true);
@@ -146,82 +143,72 @@ function initServerType()
 
   // Hide deprecated/hidden auth options, unless selected
   hideUnlessSelected(document.getElementById("authMethod-no"));
   hideUnlessSelected(document.getElementById("authMethod-old"));
   hideUnlessSelected(document.getElementById("authMethod-anysecure"));
   hideUnlessSelected(document.getElementById("authMethod-any"));
 }
 
-function hideUnlessSelected(element)
-{
+function hideUnlessSelected(element) {
   element.hidden = !element.selected;
 }
 
-function setLabelFromStringBundle(elementID, stringName)
-{
+function setLabelFromStringBundle(elementID, stringName) {
   document.getElementById(elementID).label =
       document.getElementById("bundle_messenger").getString(stringName);
 }
 
-function setDivText(divname, value)
-{
+function setDivText(divname, value) {
   var div = document.getElementById(divname);
   if (!div)
     return;
   div.setAttribute("value", value);
 }
 
 
-function onAdvanced()
-{
+function onAdvanced() {
   // Store the server type and, if an IMAP or POP3 server,
   // the settings needed for the IMAP/POP3 tab into the array
   var serverSettings = {};
   var serverType = document.getElementById("server.type").getAttribute("value");
   serverSettings.serverType = serverType;
 
   serverSettings.serverPrettyName = gServer.prettyName;
   serverSettings.account = top.getCurrentAccount();
 
-  if (serverType == "imap")
-  {
+  if (serverType == "imap") {
     serverSettings.dualUseFolders = document.getElementById("imap.dualUseFolders").checked;
     serverSettings.usingSubscription = document.getElementById("imap.usingSubscription").checked;
     serverSettings.maximumConnectionsNumber = document.getElementById("imap.maximumConnectionsNumber").getAttribute("value");
     // string prefs
     serverSettings.personalNamespace = document.getElementById("imap.personalNamespace").getAttribute("value");
     serverSettings.publicNamespace = document.getElementById("imap.publicNamespace").getAttribute("value");
     serverSettings.serverDirectory = document.getElementById("imap.serverDirectory").getAttribute("value");
     serverSettings.otherUsersNamespace = document.getElementById("imap.otherUsersNamespace").getAttribute("value");
     serverSettings.overrideNamespaces = document.getElementById("imap.overrideNamespaces").checked;
-  }
-  else if (serverType == "pop3")
-  {
+  } else if (serverType == "pop3") {
     serverSettings.deferGetNewMail = document.getElementById("pop3.deferGetNewMail").checked;
     serverSettings.deferredToAccount = document.getElementById("pop3.deferredToAccount").getAttribute("value");
   }
 
   window.openDialog("chrome://messenger/content/am-server-advanced.xul",
                     "_blank", "chrome,modal,titlebar", serverSettings);
 
-  if (serverType == "imap")
-  {
+  if (serverType == "imap") {
     document.getElementById("imap.dualUseFolders").checked = serverSettings.dualUseFolders;
     document.getElementById("imap.usingSubscription").checked = serverSettings.usingSubscription;
     document.getElementById("imap.maximumConnectionsNumber").setAttribute("value", serverSettings.maximumConnectionsNumber);
     // string prefs
     document.getElementById("imap.personalNamespace").setAttribute("value", serverSettings.personalNamespace);
     document.getElementById("imap.publicNamespace").setAttribute("value", serverSettings.publicNamespace);
     document.getElementById("imap.serverDirectory").setAttribute("value", serverSettings.serverDirectory);
     document.getElementById("imap.otherUsersNamespace").setAttribute("value", serverSettings.otherUsersNamespace);
     document.getElementById("imap.overrideNamespaces").checked = serverSettings.overrideNamespaces;
-  }
-  else if (serverType == "pop3")
-  {
+  } else if (serverType == "pop3") {
     document.getElementById("pop3.deferGetNewMail").checked = serverSettings.deferGetNewMail;
     document.getElementById("pop3.deferredToAccount").setAttribute("value", serverSettings.deferredToAccount);
     let pop3Server = gServer.QueryInterface(Ci.nsIPop3IncomingServer);
     // we're explicitly setting this so we'll go through the SetDeferredToAccount method
     pop3Server.deferredToAccount = serverSettings.deferredToAccount;
     // Setting the server to be deferred causes a rebuild of the account tree,
     // losing the current selection. Reselect the current server again as it
     // didn't really disappear.
@@ -267,20 +254,18 @@ function onAdvanced()
                                spamActionTargetAccount);
         parent.setAccountValue(accountValues, "server", "spamActionTargetFolder",
                                spamActionTargetFolder);
       }
     }
   }
 }
 
-function secureSelect(aLoading)
-{
+function secureSelect(aLoading) {
     var socketType = document.getElementById("server.socketType").value;
-    var serverType = document.getElementById("server.type").value;
     var defaultPort = gServer.protocolInfo.getDefaultServerPort(false);
     var defaultPortSecure = gServer.protocolInfo.getDefaultServerPort(true);
     var port = document.getElementById("server.port");
     var portDefault = document.getElementById("defaultPort");
     var prevDefaultPort = portDefault.value;
 
     if (socketType == Ci.nsMsgSocketType.SSL) {
       portDefault.value = defaultPortSecure;
@@ -294,49 +279,45 @@ function secureSelect(aLoading)
 
     // switch "insecure password" label
     setLabelFromStringBundle("authMethod-password-cleartext",
         socketType == Ci.nsMsgSocketType.SSL ||
         socketType == Ci.nsMsgSocketType.alwaysSTARTTLS ?
         "authPasswordCleartextViaSSL" : "authPasswordCleartextInsecurely");
 }
 
-function setupMailOnServerUI()
-{
+function setupMailOnServerUI() {
   onCheckItem("pop3.deleteMailLeftOnServer", ["pop3.leaveMessagesOnServer"]);
   setupAgeMsgOnServerUI();
 }
 
-function setupAgeMsgOnServerUI()
-{
+function setupAgeMsgOnServerUI() {
   const kLeaveMsgsId = "pop3.leaveMessagesOnServer";
   const kDeleteByAgeId = "pop3.deleteByAgeFromServer";
   onCheckItem(kDeleteByAgeId, [kLeaveMsgsId]);
   onCheckItem("daysEnd", [kLeaveMsgsId]);
   onCheckItem("pop3.numDaysToLeaveOnServer", [kLeaveMsgsId, kDeleteByAgeId]);
 }
 
-function setupFixedUI()
-{
+function setupFixedUI() {
   var controls = [document.getElementById("fixedServerName"),
                   document.getElementById("fixedUserName"),
                   document.getElementById("fixedServerPort")];
 
   var len = controls.length;
-  for (var i=0; i<len; i++) {
+  for (let i = 0; i < len; i++) {
     var fixedElement = controls[i];
     var otherElement = document.getElementById(fixedElement.getAttribute("use"));
 
     fixedElement.setAttribute("collapsed", "true");
     otherElement.removeAttribute("collapsed");
   }
 }
 
-function BrowseForNewsrc()
-{
+function BrowseForNewsrc() {
   const nsIFilePicker = Ci.nsIFilePicker;
   const nsIFile = Ci.nsIFile;
 
   var newsrcTextBox = document.getElementById("nntp.newsrcFilePath");
   var fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
   fp.init(window,
           document.getElementById("browseForNewsrc").getAttribute("filepickertitle"),
           nsIFilePicker.modeSave);
@@ -360,54 +341,51 @@ function BrowseForNewsrc()
   fp.open(rv => {
     if (rv != nsIFilePicker.returnOK || !fp.file) {
       return;
     }
     newsrcTextBox.value = fp.file.path;
   });
 }
 
-function setupImapDeleteUI(aServerId)
-{
+function setupImapDeleteUI(aServerId) {
   // read delete_model preference
   var deleteModel = document.getElementById("imap.deleteModel").getAttribute("value");
   selectImapDeleteModel(deleteModel);
 
   // read trash folder path preference
   var trashFolderName = getTrashFolderName();
 
   // set folderPicker menulist
   var trashPopup = document.getElementById("msgTrashFolderPopup");
   trashPopup._teardown();
   trashPopup._parentFolder = MailUtils.getOrCreateFolder(aServerId);
   trashPopup._ensureInitialized();
 
   // Convert the folder path in Unicode to MUTF-7.
-  let manager = Cc['@mozilla.org/charset-converter-manager;1']
+  let manager = Cc["@mozilla.org/charset-converter-manager;1"]
                   .getService(Ci.nsICharsetConverterManager);
   // Escape backslash and double-quote with another backslash before encoding.
-  let trashMutf7 = manager.unicodeToMutf7(trashFolderName.replace(/([\\"])/g, '\\$1'));
+  let trashMutf7 = manager.unicodeToMutf7(trashFolderName.replace(/([\\"])/g, "\\$1"));
   // TODO: There is something wrong here, selectFolder() fails even if the
   // folder does exist. Try to fix in bug 802609.
   let trashFolder = MailUtils.getOrCreateFolder(aServerId + "/" + trashMutf7);
   try {
     trashPopup.selectFolder(trashFolder);
-  } catch(ex) {
+  } catch (ex) {
     trashPopup.parentNode.setAttribute("label", trashFolder.prettyName);
   }
   trashPopup.parentNode.folder = trashFolder;
 }
 
-function selectImapDeleteModel(choice)
-{
+function selectImapDeleteModel(choice) {
   // set deleteModel to selected mode
   document.getElementById("imap.deleteModel").setAttribute("value", choice);
 
-  switch (choice)
-  {
+  switch (choice) {
     case "0" : // markDeleted
       // disable folderPicker
       document.getElementById("msgTrashFolderPicker").setAttribute("disabled", "true");
       break;
     case "1" : // moveToTrashFolder
       // enable folderPicker
       document.getElementById("msgTrashFolderPicker").removeAttribute("disabled");
       break;
@@ -417,42 +395,40 @@ function selectImapDeleteModel(choice)
       break;
     default :
       dump("Error in enabling/disabling server.TrashFolderPicker\n");
       break;
   }
 }
 
 // Capture any menulist changes from folderPicker
-function folderPickerChange(aEvent)
-{
+function folderPickerChange(aEvent) {
   var folder = aEvent.target._folder;
   // Since we need to deal with localised folder names, we simply use
   // the path of the URI like we do in nsImapIncomingServer::DiscoveryDone().
   // Note that the path is returned with a leading slash which we need to remove.
   var folderPath = Services.io.newURI(folder.URI).pathQueryRef.substring(1);
   // We need to convert that from MUTF-7 to Unicode.
-  var manager = Cc['@mozilla.org/charset-converter-manager;1']
+  var manager = Cc["@mozilla.org/charset-converter-manager;1"]
                   .getService(Ci.nsICharsetConverterManager);
   var trashUnicode = manager.mutf7ToUnicode(
     Services.netUtils.unescapeString(folderPath, Ci.nsINetUtil.ESCAPE_URL_PATH));
 
   // Set the value to be persisted.
   document.getElementById("imap.trashFolderName")
           .setAttribute("value", trashUnicode);
 
   // Update the widget to show/do correct things even for subfolders.
   var trashFolderPicker = document.getElementById("msgTrashFolderPicker");
   trashFolderPicker.menupopup.selectFolder(folder);
 }
 
 // Get trash_folder_name from prefs. Despite its name this returns
 // a folder path, for example INBOX/Trash.
-function getTrashFolderName()
-{
+function getTrashFolderName() {
   var trashFolderName = document.getElementById("imap.trashFolderName").getAttribute("value");
   // if the preference hasn't been set, set it to a sane default
   if (!trashFolderName) {
     trashFolderName = "Trash";  // XXX Is this a useful default?
-    document.getElementById("imap.trashFolderName").setAttribute("value",trashFolderName);
+    document.getElementById("imap.trashFolderName").setAttribute("value", trashFolderName);
   }
   return trashFolderName;
 }
--- a/mailnews/base/prefs/content/am-serverwithnoidentities.js
+++ b/mailnews/base/prefs/content/am-serverwithnoidentities.js
@@ -1,13 +1,14 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {BrowserUtils} = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm");
 
 var gAccount;
 var gOriginalStoreType;
 
 /**
  * Called when the store type menu is clicked.
  * @param {Object} aStoreTypeElement - store type menu list element.
@@ -17,17 +18,17 @@ function clickStoreTypeMenu(aStoreTypeEl
     return;
   }
 
   // Response from migration dialog modal. If the conversion is complete
   // 'response.newRootFolder' will hold the path to the new account root folder,
   // otherwise 'response.newRootFolder' will be null.
   let response = { newRootFolder: null };
   // Send 'response' as an argument to converterDialog.xhtml.
-  window.openDialog("converterDialog.xhtml","mailnews:mailstoreconverter",
+  window.openDialog("converterDialog.xhtml", "mailnews:mailstoreconverter",
                     "modal,centerscreen,width=800,height=180",
                     gAccount.incomingServer,
                     aStoreTypeElement.value, response);
   changeStoreType(response);
 }
 
 /**
  * Revert store type to the original store type if converter modal closes
@@ -67,17 +68,16 @@ function onInit(aPageId, aServerId) {
   // Initialise 'gOriginalStoreType' to the item that was originally selected.
   gOriginalStoreType = storeTypeElement.value;
 }
 
 function onPreInit(account, accountValues) {
   gAccount = account;
 }
 
-function onSave()
-{
+function onSave() {
   let storeContractID = document.getElementById("server.storeTypeMenulist")
                                 .selectedItem
                                 .value;
   document.getElementById("server.storeContractID")
           .setAttribute("value", storeContractID);
 }
 
--- a/mailnews/base/prefs/content/am-smtp.js
+++ b/mailnews/base/prefs/content/am-smtp.js
@@ -1,135 +1,123 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from amUtils.js */
+
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 
-var gSmtpServerListWindow =
-{
+var gSmtpServerListWindow = {
   mBundle: null,
   mServerList: null,
   mAddButton: null,
   mEditButton: null,
   mDeleteButton: null,
   mSetDefaultServerButton: null,
 
-  onLoad: function()
-  {
-    parent.onPanelLoaded('am-smtp.xul');
+  onLoad() {
+    parent.onPanelLoaded("am-smtp.xul");
 
     this.mBundle = document.getElementById("bundle_messenger");
     this.mServerList = document.getElementById("smtpList");
     this.mAddButton = document.getElementById("addButton");
     this.mEditButton = document.getElementById("editButton");
     this.mDeleteButton = document.getElementById("deleteButton");
     this.mSetDefaultServerButton = document.getElementById("setDefaultButton");
 
     this.refreshServerList("", false);
 
     this.updateButtons();
   },
 
-  onSelectionChanged: function(aEvent)
-  {
+  onSelectionChanged(aEvent) {
     var server = this.getSelectedServer();
     if (!server)
       return;
 
     this.updateButtons();
     this.updateServerInfoBox(server);
   },
 
-  onDeleteServer: function (aEvent)
-  {
+  onDeleteServer(aEvent) {
     var server = this.getSelectedServer();
     if (!server)
       return;
 
     // confirm deletion
     let cancel = Services.prompt.confirmEx(window,
       this.mBundle.getString("smtpServers-confirmServerDeletionTitle"),
       this.mBundle.getFormattedString("smtpServers-confirmServerDeletion",
                                       [server.hostname], 1),
       Services.prompt.STD_YES_NO_BUTTONS, null, null, null, null, { });
 
-    if (!cancel)
-    {
+    if (!cancel) {
       MailServices.smtp.deleteServer(server);
       parent.replaceWithDefaultSmtpServer(server.key);
       this.refreshServerList("", true);
     }
   },
 
-  onAddServer: function (aEvent)
-  {
+  onAddServer(aEvent) {
     this.openServerEditor(null);
   },
 
-  onEditServer: function (aEvent)
-  {
+  onEditServer(aEvent) {
     let server = this.getSelectedServer();
     if (!server)
       return;
 
     this.openServerEditor(server);
   },
 
-  onSetDefaultServer: function(aEvent)
-  {
+  onSetDefaultServer(aEvent) {
     let server = this.getSelectedServer();
     if (!server)
       return;
 
     MailServices.smtp.defaultServer = server;
     this.refreshServerList(MailServices.smtp.defaultServer.key, true);
   },
 
-  updateButtons: function()
-  {
+  updateButtons() {
     let server = this.getSelectedServer();
 
     // can't delete default server
-    if (server && MailServices.smtp.defaultServer == server)
-    {
+    if (server && MailServices.smtp.defaultServer == server) {
       this.mSetDefaultServerButton.setAttribute("disabled", "true");
       this.mDeleteButton.setAttribute("disabled", "true");
-    }
-    else
-    {
+    } else {
       this.mSetDefaultServerButton.removeAttribute("disabled");
       this.mDeleteButton.removeAttribute("disabled");
     }
 
     if (!server)
       this.mEditButton.setAttribute("disabled", "true");
     else
       this.mEditButton.removeAttribute("disabled");
   },
 
-  updateServerInfoBox: function(aServer)
-  {
+  updateServerInfoBox(aServer) {
     var noneSelected = this.mBundle.getString("smtpServerList-NotSpecified");
 
-    document.getElementById('nameValue').value = aServer.hostname;
-    document.getElementById('descriptionValue').value = aServer.description || noneSelected;
-    document.getElementById('portValue').value = aServer.port;
-    document.getElementById('userNameValue').value = aServer.username || noneSelected;
-    document.getElementById('useSecureConnectionValue').value =
+    document.getElementById("nameValue").value = aServer.hostname;
+    document.getElementById("descriptionValue").value = aServer.description || noneSelected;
+    document.getElementById("portValue").value = aServer.port;
+    document.getElementById("userNameValue").value = aServer.username || noneSelected;
+    document.getElementById("useSecureConnectionValue").value =
       this.mBundle.getString("smtpServer-ConnectionSecurityType-" +
       aServer.socketType);
 
     const AuthMethod = Ci.nsMsgAuthMethod;
     const SocketType = Ci.nsMsgSocketType;
     var authStr = "";
-    switch (aServer.authMethod)
-    {
+    switch (aServer.authMethod) {
       case AuthMethod.none:
         authStr = "authNo";
         break;
       case AuthMethod.passwordEncrypted:
         authStr = "authPasswordEncrypted";
         break;
       case AuthMethod.GSSAPI:
         authStr = "authKerberos";
@@ -154,18 +142,17 @@ var gSmtpServerListWindow =
         Cu.reportError("Warning: unknown value for smtpserver... authMethod: " +
           aServer.authMethod);
     }
     if (authStr)
       document.getElementById("authMethodValue").value =
           this.mBundle.getString(authStr);
   },
 
-  refreshServerList: function(aServerKeyToSelect, aFocusList)
-  {
+  refreshServerList(aServerKeyToSelect, aFocusList) {
     // remove all children
     while (this.mServerList.hasChildNodes())
       this.mServerList.lastChild.remove();
 
     this.fillSmtpServers(this.mServerList,
                          MailServices.smtp.servers,
                          MailServices.smtp.defaultServer);
 
@@ -173,91 +160,83 @@ var gSmtpServerListWindow =
       this.setSelectedServer(this.mServerList.querySelector('[key="' + aServerKeyToSelect + '"]'));
     else // select the default server
       this.setSelectedServer(this.mServerList.querySelector('[default="true"]'));
 
     if (aFocusList)
       this.mServerList.focus();
   },
 
-  fillSmtpServers: function(aListBox, aServers, aDefaultServer)
-  {
+  fillSmtpServers(aListBox, aServers, aDefaultServer) {
     if (!aListBox || !aServers)
       return;
 
-    while (aServers.hasMoreElements())
-    {
+    while (aServers.hasMoreElements()) {
       var server = aServers.getNext();
 
-      if (server instanceof Ci.nsISmtpServer)
-      {
+      if (server instanceof Ci.nsISmtpServer) {
         var isDefault = (aDefaultServer.key == server.key);
 
         var listitem = this.createSmtpListItem(server, isDefault);
         aListBox.appendChild(listitem);
       }
     }
   },
 
-  createSmtpListItem: function(aServer, aIsDefault)
-  {
+  createSmtpListItem(aServer, aIsDefault) {
     var listitem = document.createElement("richlistitem");
     var serverName = "";
 
     if (aServer.description)
-      serverName = aServer.description + ' - ';
+      serverName = aServer.description + " - ";
     else if (aServer.username)
-      serverName = aServer.username + ' - ';
+      serverName = aServer.username + " - ";
 
     serverName += aServer.hostname;
 
-    if (aIsDefault)
-    {
+    if (aIsDefault) {
       serverName += " " + this.mBundle.getString("defaultServerTag");
       listitem.setAttribute("default", "true");
     }
 
     let label = document.createElement("label");
     label.setAttribute("value", serverName);
     listitem.appendChild(label);
     listitem.setAttribute("key", aServer.key);
     listitem.setAttribute("class", "smtpServerListItem");
 
     // give it some unique id
     listitem.id = "smtpServer." + aServer.key;
     return listitem;
   },
 
-  openServerEditor: function(aServer)
-  {
+  openServerEditor(aServer) {
     let args = editSMTPServer(aServer);
 
     // now re-select the server which was just added
     if (args.result)
       this.refreshServerList(aServer ? aServer.key : args.addSmtpServer, true);
 
     return args.result;
   },
 
-  setSelectedServer: function(aServer)
-  {
+  setSelectedServer(aServer) {
     if (!aServer)
       return;
 
     setTimeout(function(aServerList) {
       aServerList.ensureElementIsVisible(aServer);
       aServerList.selectItem(aServer);
     }, 0, this.mServerList);
   },
 
-  getSelectedServer: function()
-  {
+  getSelectedServer() {
     // The list of servers is a single selection listbox
     // therefore 1 item is always selected.
     // But if there are no SMTP servers defined yet, nothing will be selected.
     let selection = this.mServerList.selectedItem;
     if (!selection)
       return null;
 
     let serverKey = selection.getAttribute("key");
     return MailServices.smtp.getServerByKey(serverKey);
-  }
+  },
 };
--- a/mailnews/base/prefs/content/amUtils.js
+++ b/mailnews/base/prefs/content/amUtils.js
@@ -3,18 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
 var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
 
-function BrowseForLocalFolders()
-{
+function BrowseForLocalFolders() {
   const nsIFilePicker = Ci.nsIFilePicker;
   const nsIFile = Ci.nsIFile;
 
   var currentFolderTextBox = document.getElementById("server.localPath");
   var fp = Cc["@mozilla.org/filepicker;1"]
              .createInstance(nsIFilePicker);
 
   fp.init(window,
@@ -44,18 +43,17 @@ function BrowseForLocalFolders()
 
 /**
  * Return server/folder name formatted with server name if needed.
  *
  * @param aTargetFolder  nsIMsgFolder to format name for
  *                       If target.isServer then only its name is returned.
  *                       Otherwise return the name as "<foldername> on <servername>".
  */
-function prettyFolderName(aTargetFolder)
-{
+function prettyFolderName(aTargetFolder) {
   if (aTargetFolder.isServer)
     return aTargetFolder.prettyName;
 
   return document.getElementById("bundle_messenger")
                  .getFormattedString("verboseFolderFormat",
                                      [aTargetFolder.prettyName,
                                       aTargetFolder.server.prettyName]);
 }
@@ -63,18 +61,17 @@ function prettyFolderName(aTargetFolder)
 /**
  * Checks validity of junk target server name and folder.
  *
  * @param aTargetURI  the URI specification to check
  * @param aIsServer   true if the URI specifies only a server (without folder)
  *
  * @return  the value of aTargetURI if it is valid (usable), otherwise null
  */
-function checkJunkTargetFolder(aTargetURI, aIsServer)
-{
+function checkJunkTargetFolder(aTargetURI, aIsServer) {
   try {
     // Does the target account exist?
     let targetServer;
     if (aIsServer) {
       targetServer = MailUtils.getOrCreateFolder(aTargetURI + "/Junk").server;
     } else {
       targetServer = MailUtils.getExistingFolder(aTargetURI).server;
     }
@@ -93,18 +90,17 @@ function checkJunkTargetFolder(aTargetUR
  * Finds a usable target for storing Junk mail.
  * If the passed in server URI is not usable, choose Local Folders.
  *
  * @param aTargetURI  the URI of a server or folder to try first
  * @param aIsServer   true if the URI specifies only a server (without folder)
  *
  * @return  the server/folder URI of a usable target for storing Junk
  */
-function chooseJunkTargetFolder(aTargetURI, aIsServer)
-{
+function chooseJunkTargetFolder(aTargetURI, aIsServer) {
   let server = null;
 
   if (aTargetURI) {
     server = MailUtils.getOrCreateFolder(aTargetURI).server;
     if (!server.canCreateFoldersOnServer || !server.canSearchMessages ||
         (server.rootFolder != server.rootMsgFolder))
       server = null;
   }
@@ -132,18 +128,17 @@ function chooseJunkTargetFolder(aTargetU
  *          newTargetAccount new safe junk target folder
  *          newMoveOnSpam    new moveOnSpam value
  */
 function sanitizeJunkTargets(aSpamActionTargetAccount,
                              aSpamActionTargetFolder,
                              aProposedTarget,
                              aMoveTargetModeValue,
                              aServerSpamSettings,
-                             aMoveOnSpam)
-{
+                             aMoveOnSpam) {
   // Check if folder targets are valid.
   aSpamActionTargetAccount = checkJunkTargetFolder(aSpamActionTargetAccount, true);
   if (!aSpamActionTargetAccount) {
     // If aSpamActionTargetAccount is not valid,
     // reset to default behavior to NOT move junk messages...
     if (aMoveTargetModeValue == aServerSpamSettings.MOVE_TARGET_MODE_ACCOUNT)
       aMoveOnSpam = false;
 
@@ -191,21 +186,19 @@ function openPrefsFromAccountManager(aTB
 
 /**
  * Check if the given account name already exists in any account.
  *
  * @param aAccountName  The account name string to look for.
  * @param aAccountKey   Optional. The key of an account that is skipped when
  *                      searching the name. If unset, do not skip any account.
  */
-function accountNameExists(aAccountName, aAccountKey)
-{
+function accountNameExists(aAccountName, aAccountKey) {
   for (let account of fixIterator(MailServices.accounts.accounts,
-                                  Ci.nsIMsgAccount))
-  {
+                                  Ci.nsIMsgAccount)) {
     if (account.key != aAccountKey && account.incomingServer &&
         aAccountName == account.incomingServer.prettyName) {
       return true;
     }
   }
 
   return false;
 }
--- a/mailnews/base/prefs/content/aw-accname.js
+++ b/mailnews/base/prefs/content/aw-accname.js
@@ -1,19 +1,20 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountWizard.js */
+
 var gPrefsBundle;
 
-function acctNamePageValidate()
-{
+function acctNamePageValidate() {
   var accountname = document.getElementById("prettyName").value;
-  var canAdvance = accountname ? true : false;
+  var canAdvance = !!accountname;
 
   // Check if this accountname already exists. If so, return false so that
   // user can enter a different unique account name.
   if (canAdvance && accountNameExists(accountname))
     canAdvance = false;
 
   document.documentElement.canAdvance = canAdvance;
 }
@@ -22,21 +23,20 @@ function acctNamePageUnload() {
   var pageData = parent.GetPageData();
   var accountname = document.getElementById("prettyName").value;
   setPageData(pageData, "accname", "prettyName", accountname);
   // Set this to true so we know the user has set the name.
   setPageData(pageData, "accname", "userset", true);
   return true;
 }
 
-function acctNamePageInit()
-{
+function acctNamePageInit() {
     gPrefsBundle = document.getElementById("bundle_prefs");
     var accountNameInput = document.getElementById("prettyName");
-    if (accountNameInput.value=="") {
+    if (accountNameInput.value == "") {
         var pageData = parent.GetPageData();
         var type = parent.getCurrentServerType(pageData);
         var accountName;
 
         if (type == "nntp")
             accountName = pageData.newsserver.hostname.value;
         else
             accountName = pageData.identity.email.value;
--- a/mailnews/base/prefs/content/aw-accounttype.js
+++ b/mailnews/base/prefs/content/aw-accounttype.js
@@ -1,15 +1,16 @@
 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-function setAccountTypeData()
-{
+/* import-globals-from AccountWizard.js */
+
+function setAccountTypeData() {
   var rg = document.getElementById("acctyperadio");
   var selectedItemId = rg.selectedItem.id;
   var mail = selectedItemId == "mailaccount";
   var news = selectedItemId == "newsaccount";
 
   var pageData = parent.GetPageData();
   setPageData(pageData, "accounttype", "mailaccount", mail);
   setPageData(pageData, "accounttype", "newsaccount", news);
@@ -45,22 +46,22 @@ function setupWizardPanels() {
   } else { // An account created by an extension and XUL overlays
     let pages = document.getElementById("acctyperadio").selectedItem.value;
     if (pages == "movemail") {
       wizardPanels = ["identitypage", "outgoingpage", "accnamepage"];
       setPageData(pageData, "server", "servertype", "movemail");
       setPageData(pageData, "server", "hostname", "localhost");
       setPageData(pageData, "server", "port", "");
     } else {
-      wizardPanels = button.value.split(/ *, */);
+      wizardPanels = pages.split(/ *, */);
     }
   }
   wizardPanels.push("done");
 
   // Set up order of panels
   for (let i = 0; i < (wizardPanels.length - 1); i++)
     setNextPage(wizardPanels[i], wizardPanels[i + 1]);
 
   // make the account type page go to the very first of our approved wizard panels...this is usually going to
   // be accounttype --> identitypage unless we were configured to skip the identity page
-  setNextPage("accounttype",wizardPanels[0]);
+  setNextPage("accounttype", wizardPanels[0]);
 }
 
--- a/mailnews/base/prefs/content/aw-done.js
+++ b/mailnews/base/prefs/content/aw-done.js
@@ -1,13 +1,15 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountWizard.js */
+
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 
 var gPrefsBundle;
 
 function donePageInit() {
     var pageData = parent.GetPageData();
     gPrefsBundle = document.getElementById("bundle_prefs");
 
@@ -17,97 +19,94 @@ function donePageInit() {
 
     var email = "";
     if (pageData.identity && pageData.identity.email) {
         // fixup the email
         email = pageData.identity.email.value;
     }
     setDivTextFromForm("identity.email", email);
 
-    var userName="";
+    let userName = "";
     if (pageData.login && pageData.login.username)
         userName = pageData.login.username.value;
     if (!userName && email)
         userName = getUsernameFromEmail(email);
 
     // Hide the "username" field if we don't want to show information
     // on the incoming server.
     setDivTextFromForm("server.username", hideIncoming ? null : userName);
 
-    var smtpUserName="";
+    let smtpUserName = "";
     if (pageData.login && pageData.login.smtpusername)
         smtpUserName = pageData.login.smtpusername.value;
     if (!smtpUserName && email)
         smtpUserName = getUsernameFromEmail(email);
     setDivTextFromForm("smtpServer.username", smtpUserName);
 
     if (pageData.accname && pageData.accname.prettyName) {
       setDivTextFromForm("account.name", pageData.accname.prettyName.value);
     } else {
       setDivTextFromForm("account.name", "");
     }
 
     // Show mail servers (incoming & outgoing) details based on current account
     // data.
     if (!serverIsNntp(pageData)) {
-        var incomingServerName="";
+        let incomingServerName = "";
         if (pageData.server && pageData.server.hostname) {
             incomingServerName = pageData.server.hostname.value;
         }
         // Hide the incoming server name field if the user specified
         // wizardHideIncoming in the ISP defaults file
         setDivTextFromForm("server.name", hideIncoming ? null : incomingServerName);
         setDivTextFromForm("server.port", pageData.server.port ? pageData.server.port.value : null);
-        var incomingServerType="";
+        let incomingServerType = "";
         if (pageData.server && pageData.server.servertype) {
             incomingServerType = pageData.server.servertype.value;
         }
         setDivTextFromForm("server.type", incomingServerType.toUpperCase());
 
-        var smtpServerName="";
+        let smtpServerName = "";
         if (pageData.server && pageData.server.smtphostname) {
           let smtpServer = MailServices.smtp.defaultServer;
           smtpServerName = pageData.server.smtphostname.value;
           if (!smtpServerName && smtpServer && smtpServer.hostname)
               smtpServerName = smtpServer.hostname;
         }
         setDivTextFromForm("smtpServer.name", smtpServerName);
-    }
-    else {
+    } else {
         setDivTextFromForm("server.name", null);
         setDivTextFromForm("server.type", null);
         setDivTextFromForm("server.port", null);
         setDivTextFromForm("smtpServer.name", null);
     }
 
     if (serverIsNntp(pageData)) {
-        var newsServerName="";
+        let newsServerName = "";
         if (pageData.newsserver && pageData.newsserver.hostname)
             newsServerName = pageData.newsserver.hostname.value;
         if (newsServerName) {
             // No need to show username for news account
             setDivTextFromForm("server.username", null);
         }
         setDivTextFromForm("newsServer.name", newsServerName);
         setDivTextFromForm("server.port", null);
-    }
-    else {
+    } else {
         setDivTextFromForm("newsServer.name", null);
     }
 
     var isPop = false;
     if (pageData.server && pageData.server.servertype) {
       isPop = (pageData.server.servertype.value == "pop3");
     }
 
     hideShowDownloadMsgsUI(isPop);
 }
 
-function hideShowDownloadMsgsUI(isPop)
-{
+function hideShowDownloadMsgsUI(isPop) {
   // only show the "download messages now" UI
   // if this is a pop account, we are online, and this was opened
   // from the 3 pane
   var downloadMsgs = document.getElementById("downloadMsgs");
   if (isPop) {
     if (!Services.io.offline) {
       if (window.opener.location.href == "chrome://messenger/content/messenger.xul") {
         downloadMsgs.hidden = false;
@@ -116,26 +115,24 @@ function hideShowDownloadMsgsUI(isPop)
     }
   }
 
   // else hide it
   downloadMsgs.hidden = true;
 }
 
 function setDivTextFromForm(divid, value) {
-
     // collapse the row if the div has no value
     var div = document.getElementById(divid);
     if (!value) {
-        div.setAttribute("collapsed","true");
+        div.setAttribute("collapsed", "true");
         return;
     }
-    else {
-        div.removeAttribute("collapsed");
-    }
+
+    div.removeAttribute("collapsed");
 
     // otherwise fill in the .text element
-    div = document.getElementById(divid+".text");
+    div = document.getElementById(divid + ".text");
     if (!div) return;
 
     // set the value
     div.setAttribute("value", value);
 }
--- a/mailnews/base/prefs/content/aw-identity.js
+++ b/mailnews/base/prefs/content/aw-identity.js
@@ -1,18 +1,19 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountWizard.js */
+
 var gCurrentDomain;
 var gPrefsBundle;
 
-function identityPageValidate()
-{
+function identityPageValidate() {
   var canAdvance = false;
   var name = document.getElementById("fullName").value;
   let email = document.getElementById("email").value.trim();
 
   if (name && email) {
     canAdvance = gCurrentDomain ? emailNameIsLegal(email) : emailNameAndDomainAreLegal(email);
 
     if (gCurrentDomain && canAdvance) {
@@ -27,89 +28,82 @@ function identityPageValidate()
           parent.AccountExists(usernameWithDomain, hostName, serverType))
         canAdvance = false;
     }
   }
 
   document.documentElement.canAdvance = canAdvance;
 }
 
-function identityPageUnload()
-{
+function identityPageUnload() {
   var pageData = parent.GetPageData();
   var name = document.getElementById("fullName").value;
   let email = document.getElementById("email").value.trim();
   setPageData(pageData, "identity", "fullName", name);
   setPageData(pageData, "identity", "email", email);
 
   return true;
 }
 
 // This is for the case when the code appends the domain
 // unnecessarily.
 // This simply gets rid  of "@domain" from "foo@domain"
 
-function fixPreFilledEmail()
-{
+function fixPreFilledEmail() {
   var emailElement = document.getElementById("email");
   var email = emailElement.value;
-  var emailArray = email.split('@');
+  var emailArray = email.split("@");
 
   if (gCurrentDomain) {
     // check if user entered an @ sign even though we have a domain
     if (emailArray.length >= 2) {
       email = emailArray[0];
       emailElement.value = email;
     }
   }
 }
 
 /**
  * This function checks for common illegal characters.
  * It shouldn't be too strict, since we do more extensive tests later.
  */
-function emailNameIsLegal(aString)
-{
+function emailNameIsLegal(aString) {
   return aString && !/[^!-?A-~]/.test(aString);
 }
 
-function emailNameAndDomainAreLegal(aString)
-{
+function emailNameAndDomainAreLegal(aString) {
   return /^[!-?A-~]+\@[A-Za-z0-9.-]+$/.test(aString);
 }
 
-function identityPageInit()
-{
+function identityPageInit() {
   gCurrentDomain = null;
   gPrefsBundle = document.getElementById("bundle_prefs");
   clearEmailTextItems();
   setEmailDescriptionText();
   checkForFullName();
   checkForEmail();
   fixPreFilledEmail();
   identityPageValidate();
 }
 
-function clearEmailTextItems()
-{
+function clearEmailTextItems() {
   var emailDescText = document.getElementById("emailDescText");
 
   if (emailDescText.hasChildNodes())
     emailDescText.firstChild.remove();
 
   var postEmailText = document.getElementById("postEmailText");
   postEmailText.setAttribute("value", "");
   postEmailText.hidden = true;
 }
 
 // Use email example data that ISP has provided. ISP data, if available
 // for the choice user has made, will be read into CurrentAccountData.
 // Default example data from properties will be used when the info is missing.
-function setEmailDescriptionText()
-{
+function setEmailDescriptionText() {
     var emailDescText = document.getElementById("emailDescText");
     var emailFieldLabel = document.getElementById("emailFieldLabel");
 
     // Set the default field label
     emailFieldLabel.setAttribute("value", gPrefsBundle.getString("emailFieldText"));
 
     // Check for obtained values and set with default values if needed
     var username = gPrefsBundle.getString("exampleEmailUserName");
@@ -125,16 +119,15 @@ function setEmailDescriptionText()
     emailDescText.appendChild(emailDescTextNode);
 }
 
 function checkForFullName() {
   // var name = document.getElementById("fullName");
   // We currently have no way to propose any useful name here.
 }
 
-function checkForEmail()
-{
+function checkForEmail() {
     var email = document.getElementById("email");
     var pageData = parent.GetPageData();
     if (pageData && pageData.identity && pageData.identity.email) {
         email.value = pageData.identity.email.value;
     }
 }
--- a/mailnews/base/prefs/content/aw-incoming.js
+++ b/mailnews/base/prefs/content/aw-incoming.js
@@ -1,21 +1,22 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountWizard.js */
+
 var {cleanUpHostName, isLegalHostNameOrIP} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
 
 var gOnMailServersPage;
 var gOnNewsServerPage;
 var gProtocolInfo = null;
 
-function incomingPageValidate()
-{
+function incomingPageValidate() {
   var canAdvance = true;
   var hostName;
 
   if (gOnMailServersPage) {
     hostName = document.getElementById("incomingServer").value;
     if (!isLegalHostNameOrIP(cleanUpHostName(hostName)))
       canAdvance = false;
   }
@@ -32,56 +33,52 @@ function incomingPageValidate()
     if (gProtocolInfo && gProtocolInfo.requiresUsername && !username ||
         parent.AccountExists(username, hostName, serverType))
       canAdvance = false;
   }
 
   document.documentElement.canAdvance = canAdvance;
 }
 
-function incomingPageUnload()
-{
+function incomingPageUnload() {
   var pageData = parent.GetPageData();
 
   if (gOnMailServersPage) {
     var incomingServerName = document.getElementById("incomingServer");
     setPageData(pageData, "server", "hostname", cleanUpHostName(incomingServerName.value));
     var serverport = document.getElementById("serverPort").value;
     setPageData(pageData, "server", "port", serverport);
     var username = document.getElementById("username").value;
     setPageData(pageData, "login", "username", username);
-  }
-  else if (gOnNewsServerPage) {
+  } else if (gOnNewsServerPage) {
     var newsServerName = document.getElementById("newsServer");
     setPageData(pageData, "newsserver", "hostname", cleanUpHostName(newsServerName.value));
   }
 
   return true;
 }
 
 function incomingPageInit() {
   gOnMailServersPage = (document.documentElement.currentPage.id == "incomingpage");
   gOnNewsServerPage = (document.documentElement.currentPage.id == "newsserver");
-  if (gOnNewsServerPage)
-  {
+  var pageData = parent.GetPageData();
+  if (gOnNewsServerPage) {
     var newsServer = document.getElementById("newsServer");
-    var pageData = parent.GetPageData();
     if (pageData.newsserver && pageData.newsserver.hostname)
       newsServer.value = pageData.newsserver.hostname.value;
   }
 
   var incomingServerbox = document.getElementById("incomingServerbox");
   var serverTypeBox = document.getElementById("serverTypeBox");
   if (incomingServerbox && serverTypeBox) {
     incomingServerbox.removeAttribute("hidden");
     serverTypeBox.removeAttribute("hidden");
   }
 
   // Server type selection (pop3 or imap) is for mail accounts only
-  var pageData = parent.GetPageData();
   var isMailAccount = pageData.accounttype.mailaccount.value;
   var isOtherAccount = pageData.accounttype.otheraccount.value;
   if (isMailAccount) {
     var serverTypeRadioGroup = document.getElementById("servertype");
     /*
      * Check to see if the radiogroup has any value. If there is no
      * value, this must be the first time user visiting this page in the
      * account setup process. So, the default is set to pop3. If there
@@ -101,18 +98,17 @@ function incomingPageInit() {
                "imap" : "pop3");
       serverTypeRadioGroup.selectedItem = serverTypeRadioItem;      // Set pop3 server type as default selection
     }
     var leaveMessages = document.getElementById("leaveMessagesOnServer");
     var deferStorage = document.getElementById("deferStorage");
     setServerType();
     setServerPrefs(leaveMessages);
     setServerPrefs(deferStorage);
-  }
-  else if (isOtherAccount) {
+  } else if (isOtherAccount) {
     document.getElementById("deferStorageBox").hidden = true;
   }
 
   if (pageData.server && pageData.server.hostname) {
     var incomingServerTextBox = document.getElementById("incomingServer");
     if (incomingServerTextBox && incomingServerTextBox.value == "")
       incomingServerTextBox.value = pageData.server.hostname.value;
   }
@@ -128,30 +124,28 @@ function incomingPageInit() {
     if (gProtocolInfo.requiresUsername) {
       // since we require a username, use the uid from the email address
       loginNameInput.value = parent.getUsernameFromEmail(pageData.identity.email.value);
     }
   }
   incomingPageValidate();
 }
 
-function setServerType()
-{
+function setServerType() {
   var pageData = parent.GetPageData();
   var serverType = document.getElementById("servertype").value;
   var deferStorageBox = document.getElementById("deferStorageBox");
   var leaveMessages = document.getElementById("leaveMsgsOnSrvrBox");
   var port = serverType == "pop3" ? 110 : 143;
 
   document.getElementById("serverPort").value = port;
   document.getElementById("defaultPortValue").value = port;
 
   deferStorageBox.hidden = serverType == "imap";
   leaveMessages.hidden = serverType == "imap";
   setPageData(pageData, "server", "servertype", serverType);
   setPageData(pageData, "server", "port", port);
   incomingPageValidate();
 }
 
-function setServerPrefs(aThis)
-{
+function setServerPrefs(aThis) {
   setPageData(parent.GetPageData(), "server", aThis.id, aThis.checked);
 }
--- a/mailnews/base/prefs/content/aw-outgoing.js
+++ b/mailnews/base/prefs/content/aw-outgoing.js
@@ -1,13 +1,15 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+/* import-globals-from AccountWizard.js */
+
 var {cleanUpHostName, isLegalHostNameOrIP} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
 var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
 
 var gProtocolInfo = null;
 var gPrefsBundle;
 
 function outgoingPageValidate() {
   let canAdvance = true;
@@ -52,91 +54,85 @@ function outgoingPageInit() {
     var haveSmtpBox = document.getElementById("haveSmtp");
 
     var boxToHide;
     var boxToShow;
 
     if (smtpServer && smtpServer.hostname) {
       // we have a hostname, so modify and show the static text and
       // store the value of the default smtp server in the textbox.
-      modifyStaticText(smtpServer.hostname, "1")
+      modifyStaticText(smtpServer.hostname, "1");
       boxToShow = haveSmtpBox;
       boxToHide = noSmtpBox;
-    }
-    else {
+    } else {
       // no default hostname yet
       boxToShow = noSmtpBox;
       boxToHide = haveSmtpBox;
     }
 
     if (boxToHide)
       boxToHide.setAttribute("hidden", "true");
 
     if (boxToShow)
       boxToShow.removeAttribute("hidden");
 
     var smtpNameInput = document.getElementById("smtpusername");
     smtpServer = MailServices.smtp.defaultServer;
     if (smtpServer && smtpServer.hostname && smtpServer.username) {
       // we have a default SMTP server, so modify and show the static text
       // and store the username for the default server in the textbox.
-      modifyStaticText(smtpServer.username, "2")
+      modifyStaticText(smtpServer.username, "2");
       hideShowLoginSettings(2, 1, 3);
       smtpNameInput.value = smtpServer.username;
-    }
-    else {
+    } else {
       // no default SMTP server yet, so need to compare
       // incoming and outgoing server names
       var smtpServerName = pageData.server.smtphostname.value;
       var incomingServerName = pageData.server.hostname.value;
       if (smtpServerName == incomingServerName) {
         // incoming and outgoing server names are the same, so show
         // the static text and make sure textbox blank for later tests.
-        modifyStaticText(smtpServerName, "3")
+        modifyStaticText(smtpServerName, "3");
         hideShowLoginSettings(3, 1, 2);
         smtpNameInput.value = "";
-      }
-      else {
+      } else {
         // incoming and outgoing server names are different, so set smtp
         // username's textbox to be the same as incoming's one, unless already set.
         hideShowLoginSettings(1, 2, 3);
+        var loginNameInput = document.getElementById("username");
         smtpNameInput.value = smtpNameInput.value || loginNameInput.value;
       }
     }
     outgoingPageValidate();
 }
 
-function modifyStaticText(smtpMod, smtpBox)
-{
+function modifyStaticText(smtpMod, smtpBox) {
   // modify the value in the smtp display if we already have a
   // smtp server so that the single string displays the hostname
   // or username for the smtp server.
-  var smtpStatic = document.getElementById("smtpStaticText"+smtpBox);
+  var smtpStatic = document.getElementById("smtpStaticText" + smtpBox);
   if (smtpStatic && smtpStatic.hasChildNodes())
     smtpStatic.childNodes[0].nodeValue = smtpStatic.getAttribute("prefix") +
                                          smtpMod + smtpStatic.getAttribute("suffix");
 }
 
-function hideShowLoginSettings(aEle, bEle, cEle)
-{
+function hideShowLoginSettings(aEle, bEle, cEle) {
     document.getElementById("loginSet" + aEle).hidden = false;
     document.getElementById("loginSet" + bEle).hidden = true;
     document.getElementById("loginSet" + cEle).hidden = true;
 }
 
-var savedPassword="";
+var savedPassword = "";
 
 function onSavePassword(target) {
     dump("savePassword changed! (" + target.checked + ")\n");
     var passwordField = document.getElementById("server.password");
     if (!passwordField) return;
 
     if (target.checked) {
         passwordField.removeAttribute("disabled");
         passwordField.value = savedPassword;
-    }
-    else {
+    } else {
         passwordField.setAttribute("disabled", "true");
         savedPassword = passwordField.value;
         passwordField.value = "";
     }
-
 }
--- a/mailnews/base/prefs/content/converterDialog.js
+++ b/mailnews/base/prefs/content/converterDialog.js
@@ -101,32 +101,32 @@ function placeAccountName(aServer) {
     // its hostname which is "Local Folders".
     // TODO: maybe test against .key != MailServices.accounts.localFoldersServer.key ?
     let deferredToAccountName = deferredToAccount.incomingServer.hostName;
     if (deferredToAccountName != "Local Folders") {
       deferredToAccountName = deferredToAccount.incomingServer.username;
     }
 
     if (aServer.rootFolder.filePath.path != deferredToRootFolder) {
-      document.getElementById("warningSpan").innerHTML =
+      document.getElementById("warningSpan").textContent =
         bundle.formatStringFromName(