about:startup - merge with trunk, again. try: -b o -p linux,linux64,macosx64,win32 -m all -u crashtest -t all
authorDaniel Brooks <db48x@db48x.net>
Fri, 05 Nov 2010 21:50:30 -0500
changeset 58871 79ab64089a080e04c8e8c0e916d6357e2e96f205
parent 58870 9d230d75d8573e8beaead1776de4adaba8353123 (current diff)
parent 56982 8a5b02198b90ec36289e393febdb48b1d136313f (diff)
child 58872 97a4aa8ca939962635f391aef5b612eadefcbb7a
push id17440
push userdb48x@yahoo.com
push dateWed, 08 Dec 2010 04:15:54 +0000
treeherdermozilla-central@a89f24bf1798 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone2.0b8pre
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
about:startup - merge with trunk, again. try: -b o -p linux,linux64,macosx64,win32 -m all -u crashtest -t all
browser/base/content/browser.js
browser/base/content/tabview/infoitems.js
testing/mozmill/tests/firefox/testPrivateBrowsing/testStartStopPBMode.js
toolkit/content/license.html
toolkit/themes/pinstripe/global/jar.mn
toolkit/themes/winstripe/global/jar.mn
--- a/Makefile.in
+++ b/Makefile.in
@@ -166,17 +166,17 @@ endif
 SYM_STORE_SOURCE_DIRS := $(topsrcdir)
 
 include $(topsrcdir)/toolkit/mozapps/installer/package-name.mk
 
 ifdef MOZ_SYMBOLS_EXTRA_BUILDID
 EXTRA_BUILDID := -$(MOZ_SYMBOLS_EXTRA_BUILDID)
 endif
 
-SYMBOL_INDEX_NAME = \
+export SYMBOL_INDEX_NAME = \
   $(MOZ_APP_NAME)-$(MOZ_APP_VERSION)-$(OS_TARGET)-$(BUILDID)$(EXTRA_BUILDID)-symbols.txt
 
 buildsymbols:
 ifdef MOZ_CRASHREPORTER
 	echo building symbol store
 	$(RM) -rf $(DIST)/crashreporter-symbols
 	$(RM) -f "$(DIST)/$(SYMBOL_ARCHIVE_BASENAME).zip"
 	$(NSINSTALL) -D $(DIST)/crashreporter-symbols
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -54,19 +54,19 @@ pref("browser.chromeURL","chrome://brows
 pref("browser.hiddenWindowChromeURL", "chrome://browser/content/hiddenWindow.xul");
 
 // Enables some extra Extension System Logging (can reduce performance)
 pref("extensions.logging.enabled", false);
 
 // Preferences for AMO integration
 pref("extensions.getAddons.cache.enabled", true);
 pref("extensions.getAddons.maxResults", 15);
-pref("extensions.getAddons.get.url", "https://services.addons.mozilla.org/%LOCALE%/%APP%/api/%API_VERSION%/search/guid:%IDS%");
+pref("extensions.getAddons.get.url", "https://services.addons.mozilla.org/%LOCALE%/%APP%/api/%API_VERSION%/search/guid:%IDS%?src=firefox");
 pref("extensions.getAddons.search.browseURL", "https://addons.mozilla.org/%LOCALE%/%APP%/search?q=%TERMS%");
-pref("extensions.getAddons.search.url", "https://services.addons.mozilla.org/%LOCALE%/%APP%/api/%API_VERSION%/search/%TERMS%/all/%MAX_RESULTS%/%OS%/%VERSION%");
+pref("extensions.getAddons.search.url", "https://services.addons.mozilla.org/%LOCALE%/%APP%/api/%API_VERSION%/search/%TERMS%/all/%MAX_RESULTS%/%OS%/%VERSION%?src=firefox");
 pref("extensions.webservice.discoverURL", "https://services.addons.mozilla.org/%LOCALE%/%APP%/discovery/%VERSION%/%OS%");
 
 // Blocklist preferences
 pref("extensions.blocklist.enabled", true);
 pref("extensions.blocklist.interval", 86400);
 // Controls what level the blocklist switches from warning about items to forcibly
 // blocking them.
 pref("extensions.blocklist.level", 2);
--- a/browser/base/Makefile.in
+++ b/browser/base/Makefile.in
@@ -77,13 +77,14 @@ endif
 
 ifneq (,$(filter windows cocoa gtk2, $(MOZ_WIDGET_TOOLKIT)))
 ifneq ($(OS_ARCH),WINCE)
 DEFINES += -DCONTEXT_COPY_IMAGE_CONTENTS=1
 endif
 endif
 
 ifneq (,$(filter windows, $(MOZ_WIDGET_TOOLKIT)))
+DEFINES += -DCAN_DRAW_IN_TITLEBAR=1
 DEFINES += -DMENUBAR_CAN_AUTOHIDE=1
 endif
 
 libs::
 	$(NSINSTALL) $(srcdir)/content/tabview/modules/* $(FINAL_TARGET)/modules/tabview
--- a/browser/base/content/aboutHome.css
+++ b/browser/base/content/aboutHome.css
@@ -99,16 +99,17 @@ body[dir="rtl"] #searchEngineLinks {
   float: left;
 }
 
 #searchEngineLogo {
   margin: 5px;
 }
 
 #searchText {
+  margin-bottom: 10px;
   width: 100%;
 }
 
 #aboutMozilla {
   text-align: center;
 }
 
 #defaultSnippets {
--- a/browser/base/content/aboutHome.xhtml
+++ b/browser/base/content/aboutHome.xhtml
@@ -67,17 +67,16 @@
       <div id="topSection">
         <div id="brandStart">
           &abouthome.brandStart;
         </div>
         <div id ="searchContainer">
           <img id="searchEngineLogo"/>
           <form name="searchForm" onsubmit="onSearchSubmit(event)">
             <input type="text" name="searchText" value="" id="searchText" maxLength="256"/>
-            <br/>
             <input type="submit" value="&abouthome.searchEngineButton.label;"/>
             <span id="searchEngineLinks">
               <a hidden="true" id="searchEngineAdvancedLink">&abouthome.searchEngineLinks.advanced;</a>
               <a hidden="true" id="searchEngineAdvancedPreferences">&abouthome.searchEngineLinks.preferences;</a>
             </span>
           </form>
         </div>
       </div>
--- a/browser/base/content/baseMenuOverlay.xul
+++ b/browser/base/content/baseMenuOverlay.xul
@@ -108,25 +108,16 @@
                   label="&helpFeedbackPage.label;"
                   oncommand="openFeedbackPage()"
                   onclick="checkForMiddleClick(this, event);"/>
         <menuitem id="helpSafeMode"
                   accesskey="&helpSafeMode.accesskey;"
                   label="&helpSafeMode.label;"
                   oncommand="safeModeRestart();"/>
         <menuseparator/>
-        <menuseparator id="updateSeparator"/>
-#ifdef XP_MACOSX
-#ifdef MOZ_UPDATER
-        <menuitem id="checkForUpdates"
-                  label="&updateCmd.label;"
-                  class="menuitem-iconic"
-                  oncommand="checkForUpdates();"/>
-#endif
-#endif
         <menuseparator id="aboutSeparator"/>
         <menuitem id="aboutName"
                   accesskey="&aboutProduct.accesskey;"
                   label="&aboutProduct.label;"
                   oncommand="openAboutDialog();"/>
       </menupopup>
     </menu>
 
new file mode 100644
--- /dev/null
+++ b/browser/base/content/browser-appmenu.inc
@@ -0,0 +1,409 @@
+# -*- Mode: HTML -*-
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is Firefox Application Menu.
+#
+# The Initial Developer of the Original Code is
+# The Mozilla Foundation.
+# Portions created by the Initial Developer are Copyright (C) 2010
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Dão Gottwald <dao@mozilla.com>
+#   Joshua M. <soapyhamhocks@gmail.com>
+#   Margaret Leibovic <margaret.leibovic@gmail.com>
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+<menupopup id="appmenu-popup"
+#ifdef MOZ_SERVICES_SYNC
+           onpopupshowing="updateEditUIVisibility();gSyncUI.updateUI();">
+#else
+           onpopupshowing="updateEditUIVisibility();">
+#endif
+  <hbox>
+    <vbox id="appmenuPrimaryPane">
+      <hbox flex="1"
+            class="split-menuitem">
+        <menuitem id="appmenu_newTab"
+                  class="menuitem-tooltip split-menuitem-item"
+                  flex="1"
+                  label="&tabCmd.label;"
+                  command="cmd_newNavigatorTab"
+                  key="key_newNavigatorTab"/>
+        <menu class="split-menuitem-menu">
+          <menupopup>
+            <menuitem id="appmenu_newTab_popup"
+                      label="&tabCmd.label;"
+                      command="cmd_newNavigatorTab"
+                      key="key_newNavigatorTab"/>
+            <menuitem id="appmenu_newNavigator"
+                      label="&newNavigatorCmd.label;"
+                      command="cmd_newNavigator"
+                      key="key_newNavigator"/>
+            <menuseparator/>
+            <menuitem id="appmenu_openFile"
+                      label="&openFileCmd.label;"
+                      command="Browser:OpenFile"
+                      key="openFileKb"/>
+          </menupopup>
+        </menu>
+      </hbox>
+      <menuitem id="appmenu_privateBrowsing"
+                class="menuitem-iconic menuitem-iconic-tooltip"
+                label="&privateBrowsingCmd.start.label;"
+                startlabel="&privateBrowsingCmd.start.label;"
+                stoplabel="&privateBrowsingCmd.stop.label;"
+                command="Tools:PrivateBrowsing"
+                key="key_privatebrowsing"/>
+      <menuitem label="&goOfflineCmd.label;"
+                id="appmenu_offlineModeRecovery"
+                type="checkbox"
+                observes="workOfflineMenuitemState"
+                oncommand="BrowserOffline.toggleOfflineStatus();"/>
+      <menuseparator class="appmenu-menuseparator"/>
+      <hbox>
+        <menuitem id="appmenu-edit-label"
+                  label="&appMenuEdit.label;"
+                  disabled="true"/>
+        <toolbarbutton id="appmenu-cut"
+                       class="appmenu-edit-button"
+                       command="cmd_cut"
+                       onclick="if (!this.disabled) hidePopup();"
+                       tooltiptext="&cutButton.tooltip;"/>
+        <toolbarbutton id="appmenu-copy"
+                       class="appmenu-edit-button"
+                       command="cmd_copy"
+                       onclick="if (!this.disabled) hidePopup();"
+                       tooltiptext="&copyButton.tooltip;"/>
+        <toolbarbutton id="appmenu-paste"
+                       class="appmenu-edit-button"
+                       command="cmd_paste"
+                       onclick="if (!this.disabled) hidePopup();"
+                       tooltiptext="&pasteButton.tooltip;"/>
+      </hbox>
+      <menuitem id="appmenu_find"
+                class="menuitem-tooltip"
+                label="&appMenuFind.label;"
+                command="cmd_find"
+                key="key_find"/>
+      <menuseparator class="appmenu-menuseparator"/>
+      <menuitem id="appmenu_savePage"
+                class="menuitem-tooltip"
+                label="&savePageCmd.label;"
+                command="Browser:SavePage"
+                key="key_savePage"/>
+      <menuitem id="appmenu_sendLink"
+                label="&sendPageCmd.label;"
+                command="Browser:SendLink"/>
+      <hbox flex="1"
+            class="split-menuitem">
+        <menuitem id="appmenu_print"
+                  class="menuitem-iconic menuitem-iconic-tooltip split-menuitem-item"
+                  flex="1"
+                  label="&printCmd.label;"
+                  command="cmd_print"
+                  key="printKb"/>
+        <menu class="split-menuitem-menu">
+          <menupopup>
+            <menuitem id="appmenu_print_popup"
+                      class="menuitem-iconic"
+                      label="&printCmd.label;"
+                      command="cmd_print"
+                      key="printKb"/>
+            <menuitem id="appmenu_printPreview"
+                      label="&printPreviewCmd.label;"
+                      command="cmd_printPreview"/>
+            <menuitem id="appmenu_printSetup"
+                      label="&printSetupCmd.label;"
+                      command="cmd_pageSetup"/>
+          </menupopup>
+        </menu>
+      </hbox>
+      <menuseparator class="appmenu-menuseparator"/>
+      <menu id="appmenu_webDeveloper"
+            label="&appMenuWebDeveloper.label;">
+        <menupopup id="appmenu_webDeveloper_popup">
+          <menuitem id="appmenu_webConsole"
+                    label="&webConsoleCmd.label;"
+                    oncommand="HUDConsoleUI.toggleHUD();"
+                    key="key_webConsole"/>
+          <menuitem id="appmenu_pageInspect"
+                    hidden="true"
+                    label="&inspectMenu.label;"
+                    type="checkbox"
+                    command="Tools:Inspect"
+                    key="key_inspect"/>
+          <menuseparator/>
+          <menuitem id="appmenu_pageSource"
+                    label="&viewPageSourceCmd.label;"
+                    command="View:PageSource"
+                    key="key_viewSource"/>
+          <menuseparator/>
+#define ID_PREFIX appmenu_developer_
+#include browser-charsetmenu.inc
+#undef ID_PREFIX
+          <menuseparator/>
+          <menuitem label="&goOfflineCmd.label;"
+                    type="checkbox"
+                    observes="workOfflineMenuitemState"
+                    oncommand="BrowserOffline.toggleOfflineStatus();"/>
+        </menupopup>
+      </menu>
+      <menuseparator class="appmenu-menuseparator"/>
+#define ID_PREFIX appmenu_
+#include browser-charsetmenu.inc
+#undef ID_PREFIX
+      <menuitem id="appmenu_fullScreen"
+                class="menuitem-tooltip"
+                label="&fullScreenCmd.label;"
+                type="checkbox"
+                observes="View:FullScreen"
+                key="key_fullScreen"/>
+      <menuitem id="appmenu-quit"
+                class="menuitem-iconic"
+#ifdef XP_WIN
+                label="&quitApplicationCmdWin.label;"
+#else
+                label="&quitApplicationCmd.label;"
+#endif
+                command="cmd_quitApplication"/>
+    </vbox>
+    <vbox id="appmenuSecondaryPane">
+      <hbox class="split-menuitem">
+        <menuitem id="appmenu_bookmarks"
+                  class="menuitem-iconic menuitem-iconic-tooltip split-menuitem-item"
+                  flex="1"
+                  label="&bookmarksMenu.label;"
+                  command="Browser:ShowAllBookmarks"
+                  key="manBookmarkKb"/>
+        <menu id="appmenu_bookmarksMenu"
+              class="split-menuitem-menu">
+          <menupopup id="appmenu_bookmarksPopup"
+                     placespopup="true"
+                     context="placesContext"
+                     openInTabs="children"
+                     oncommand="BookmarksEventHandler.onCommand(event);"
+                     onclick="BookmarksEventHandler.onClick(event);"
+                     onpopupshowing="BookmarksMenuButton.onPopupShowing(event);
+                                     if (!this.parentNode._placesView)
+                                       new PlacesMenu(event, 'place:folder=BOOKMARKS_MENU');"
+                     tooltip="bhTooltip"
+                     popupsinherittooltip="true">
+            <menuitem id="appmenu_showAllBookmarks"
+                      label="&showAllBookmarks.label;"
+                      command="Browser:ShowAllBookmarks"
+                      context=""
+                      key="manBookmarkKb"/>
+            <menuseparator/>
+            <menuitem id="appmenu_bookmarkThisPage"
+                      class="menuitem-iconic"
+                      label="&bookmarkThisPageCmd.label;"
+                      command="Browser:AddBookmarkAs"
+                      key="addBookmarkAsKb"/>
+            <menuitem id="appmenu_subscribeToPage"
+                      class="menuitem-iconic"
+                      label="&subscribeToPageMenuitem.label;"
+                      oncommand="return FeedHandler.subscribeToFeed(null, event);"
+                      onclick="checkForMiddleClick(this, event);"
+                      observes="singleFeedMenuitemState"/>
+            <menu id="appmenu_subscribeToPageMenu"
+                  class="menu-iconic"
+                  label="&subscribeToPageMenupopup.label;"
+                  observes="multipleFeedsMenuState">
+              <menupopup id="appmenu_subscribeToPageMenupopup"
+                         onpopupshowing="return FeedHandler.buildFeedList(event.target);"
+                         oncommand="return FeedHandler.subscribeToFeed(null, event);"
+                         onclick="checkForMiddleClick(this, event);"/>
+            </menu>
+            <menuseparator/>
+            <menu id="appmenu_bookmarksToolbar"
+                  placesanonid="toolbar-autohide"
+                  class="menu-iconic bookmark-item"
+                  label="&personalbarCmd.label;"
+                  container="true">
+              <menupopup id="appmenu_bookmarksToolbarPopup"
+                         placespopup="true"
+                         context="placesContext"
+                         onpopupshowing="if (!this.parentNode._placesView)
+                                           new PlacesMenu(event, 'place:folder=TOOLBAR');"/>
+            </menu>
+            <menuseparator/>
+            <!-- Bookmarks menu items -->
+            <menuseparator builder="end"
+                           class="hide-if-empty-places-result"/>
+            <menuitem id="appmenu_unsortedBookmarks"
+                      label="&appMenuUnsorted.label;"
+                      oncommand="PlacesCommandHook.showPlacesOrganizer('UnfiledBookmarks');"
+                      class="menuitem-iconic"/>
+          </menupopup>
+        </menu>
+      </hbox>
+      <hbox class="split-menuitem">
+        <menuitem id="appmenu_history"
+                  class="menuitem-iconic menuitem-iconic-tooltip split-menuitem-item"
+                  flex="1"
+                  label="&historyMenu.label;"
+                  command="Browser:ShowAllHistory"
+                  key="showAllHistoryKb"/>
+        <menu id="appmenu_historyMenu"
+              class="split-menuitem-menu">
+          <menupopup id="appmenu_historyMenupopup"
+                     placespopup="true"
+                     oncommand="this.parentNode._placesView._onCommand(event);"
+                     onclick="checkForMiddleClick(this, event);"
+                     onpopupshowing="if (!this.parentNode._placesView)
+                                       new HistoryMenu(event);"
+                     tooltip="bhTooltip"
+                     popupsinherittooltip="true">
+            <menuitem id="appmenu_showAllHistory"
+                      label="&showAllHistoryCmd2.label;"
+                      command="Browser:ShowAllHistory"
+                      key="showAllHistoryKb"/>
+            <menuseparator/>
+            <menuitem id="appmenu_sanitizeHistory"
+                      label="&clearRecentHistory.label;"
+                      key="key_sanitize"
+                      command="Tools:Sanitize"/>
+            <menuseparator class="hide-if-empty-places-result"/>
+            <menuitem id="appmenu_restoreLastSession"
+                      class="restoreLastSession"
+                      label="&historyRestoreLastSession.label;"
+                      oncommand="restoreLastSession();"
+                      disabled="true"/>
+            <menu id="appmenu_recentlyClosedTabsMenu"
+                  class="recentlyClosedTabsMenu"
+                  label="&historyUndoMenu.label;"
+                  disabled="true">
+              <menupopup id="appmenu_recentlyClosedTabsMenupopup"
+                         onpopupshowing="document.getElementById('appmenu_historyMenu')._placesView.populateUndoSubmenu();"/>
+            </menu>
+            <menu id="appmenu_recentlyClosedWindowsMenu"
+                  class="recentlyClosedWindowsMenu"
+                  label="&historyUndoWindowMenu.label;"
+                  disabled="true">
+              <menupopup id="appmenu_recentlyClosedWindowsMenupopup"
+                         onpopupshowing="document.getElementById('appmenu_historyMenu')._placesView.populateUndoWindowSubmenu();"/>
+            </menu>
+            <menuseparator/>
+          </menupopup>
+        </menu>
+      </hbox>
+      <menuitem id="appmenu_downloads"
+                class="menuitem-tooltip"
+                label="&downloads.label;"
+                command="Tools:Downloads"
+                key="key_openDownloads"/>
+      <spacer id="appmenuSecondaryPane-spacer"/>
+      <menuitem id="appmenu_addons"
+                class="menuitem-iconic menuitem-iconic-tooltip"
+                label="&addons.label;"
+                command="Tools:Addons"
+                key="key_openAddons"/>
+      <hbox class="split-menuitem">
+        <menuitem id="appmenu_customize"
+#ifdef XP_UNIX
+                  label="&preferencesCmdUnix.label;"
+#else
+                  label="&preferencesCmd.label;"
+#endif
+                  class="split-menuitem-item"
+                  flex="1"
+                  oncommand="openPreferences();"/>
+        <menu class="split-menuitem-menu"
+              label="&preferencesCmd.label;">
+          <menupopup id="appmenu_customizeMenu"
+                     onpopupshowing="onViewToolbarsPopupShowing(event, document.getElementById('appmenu_toggleTabsOnTop').previousSibling);">
+            <menuitem id="appmenu_preferences"
+#ifdef XP_UNIX
+                      label="&preferencesCmdUnix.label;"
+#else
+                      label="&preferencesCmd.label;"
+#endif
+                      oncommand="openPreferences();"/>
+            <menuseparator/>
+            <menuseparator/>
+            <menuitem id="appmenu_toggleTabsOnTop"
+                      label="&viewTabsOnTop.label;"
+                      type="checkbox"
+                      command="cmd_ToggleTabsOnTop"/>
+            <menuitem id="appmenu_toolbarLayout"
+                      label="&appMenuToolbarLayout.label;"
+                      command="cmd_CustomizeToolbars"/>
+          </menupopup>
+        </menu>
+      </hbox>
+      <hbox class="split-menuitem">
+        <menuitem id="appmenu_help"
+                  class="split-menuitem-item"
+                  flex="1"
+                  label="&helpMenu.label;"
+                  oncommand="openHelpLink('firefox-help')"/>
+        <menu class="split-menuitem-menu">
+          <menupopup id="appmenu_helpMenupopup">
+            <menuitem id="appmenu_openHelp"
+                      label="&helpMenu.label;"
+                      oncommand="openHelpLink('firefox-help')"
+                      onclick="checkForMiddleClick(this, event);"/>
+            <menuitem id="appmenu_gettingStarted"
+                      label="&appMenuGettingStarted.label;"
+                      oncommand="gBrowser.loadOneTab('http://www.mozilla.com/firefox/central/', {inBackground: false});"
+                      onclick="checkForMiddleClick(this, event);"/>
+            <menuitem id="appmenu_troubleshootingInfo"
+                      label="&helpTroubleshootingInfo.label;"
+                      oncommand="openTroubleshootingPage()"
+                      onclick="checkForMiddleClick(this,event);"/>
+            <menuitem id="appmenu_feedbackPage"
+                      label="&helpFeedbackPage.label;"
+                      oncommand="openFeedbackPage()"
+                      onclick="checkForMiddleClick(this, event);"/>
+            <menuseparator/>
+            <menuitem id="appmenu_safeMode"
+                      accesskey="&appMenuSafeMode.accesskey;"
+                      label="&appMenuSafeMode.label;"
+                      oncommand="safeModeRestart();"/>
+            <menuseparator/>
+            <menuitem id="appmenu_about"
+                      label="&aboutProduct.label;"
+                      oncommand="openAboutDialog();"/>
+          </menupopup>
+        </menu>
+      </hbox>
+#ifdef MOZ_SERVICES_SYNC
+      <spacer flex="1"/>
+      <!-- only one of sync-setup or sync-syncnow will be showing at once -->
+      <menuitem id="sync-setup-appmenu"
+                label="&syncSetup.label;"
+                observes="sync-setup-state"
+                oncommand="gSyncUI.openSetup()"/>
+      <menuitem id="sync-syncnowitem-appmenu"
+                label="&syncSyncNowItem.label;"
+                observes="sync-syncnow-state"
+                oncommand="gSyncUI.doSync(event);"/>
+#endif
+    </vbox>
+  </hbox>
+</menupopup>
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -434,21 +434,27 @@
                onpopupshowing="if (!this.parentNode._placesView)
                                  new PlacesMenu(event, 'place:folder=BOOKMARKS_MENU');"
                tooltip="bhTooltip" popupsinherittooltip="true">
       <menuitem id="menu_bookmarkThisPage"
                 label="&bookmarkThisPageCmd.label;"
                 command="Browser:AddBookmarkAs"
                 key="addBookmarkAsKb"/>
       <menuitem id="subscribeToPageMenuitem"
+#ifndef XP_MACOSX
+                class="menuitem-iconic"
+#endif
                 label="&subscribeToPageMenuitem.label;"
                 oncommand="return FeedHandler.subscribeToFeed(null, event);"
                 onclick="checkForMiddleClick(this, event);"
                 observes="singleFeedMenuitemState"/>
       <menu id="subscribeToPageMenupopup"
+#ifndef XP_MACOSX
+            class="menu-iconic"
+#endif
             label="&subscribeToPageMenupopup.label;"
             observes="multipleFeedsMenuState">
         <menupopup id="subscribeToPageSubmenuMenupopup"
                    onpopupshowing="return FeedHandler.buildFeedList(event.target);"
                    oncommand="return FeedHandler.subscribeToFeed(null, event);"
                    onclick="checkForMiddleClick(this, event);"/>
       </menu>
       <menuitem id="menu_bookmarkAllTabs"
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -75,17 +75,17 @@ toolbar[printpreview="true"] {
 #TabsToolbar {
   -moz-box-ordinal-group: 100;
 }
 
 #TabsToolbar[tabsontop="true"] {
   -moz-box-ordinal-group: 10;
 }
 
-%ifdef MENUBAR_CAN_AUTOHIDE
+%ifdef CAN_DRAW_IN_TITLEBAR
 #main-window[inFullscreen] > #titlebar {
   display: none;
 }
 
 #titlebar {
   -moz-binding: url("chrome://global/content/bindings/general.xml#windowdragbox");
 }
 %endif
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1923,16 +1923,21 @@ function BrowserGoHome(aEvent) {
   if (aEvent && "button" in aEvent &&
       aEvent.button == 2) // right-click: do nothing
     return;
 
   var homePage = gHomeButton.getHomePage();
   var where = whereToOpenLink(aEvent, false, true);
   var urls;
 
+  // Home page should open in a new tab when current tab is an app tab
+  if (where == "current" &&
+      gBrowser.selectedTab.pinned)
+    where = "tab";
+
   // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages
   switch (where) {
   case "current":
     loadOneOrMoreURIs(homePage);
     break;
   case "tabshifted":
   case "tab":
     urls = homePage.split("|");
@@ -3484,20 +3489,21 @@ function BrowserToolboxCustomizeDone(aTo
 #ifndef XP_MACOSX
     updateEditUIVisibility();
 #endif
   }
 
   PlacesToolbarHelper.customizeDone();
   BookmarksMenuButton.customizeDone();
 
+  // The url bar splitter state is dependent on whether stop/reload
+  // and the location bar are combined, so we need this ordering
+  CombinedStopReload.init();
   UpdateUrlbarSearchSplitterState();
 
-  CombinedStopReload.init();
-
   // Update the urlbar
   if (gURLBar) {
     URLBarSetURI();
     XULBrowserWindow.asyncUpdateUI();
     PlacesStarButton.updateState();
   }
 
   // Re-enable parts of the UI we disabled during the dialog
@@ -4718,24 +4724,28 @@ var TabsOnTop = {
 
 #ifdef MENUBAR_CAN_AUTOHIDE
 function updateAppButtonDisplay() {
   var displayAppButton =
     !gInPrintPreviewMode &&
     window.menubar.visible &&
     document.getElementById("toolbar-menubar").getAttribute("autohide") == "true";
 
+#ifdef CAN_DRAW_IN_TITLEBAR
   document.getElementById("titlebar").hidden = !displayAppButton;
 
   if (displayAppButton)
     document.documentElement.setAttribute("chromemargin", "0,-1,-1,-1");
   else
     document.documentElement.removeAttribute("chromemargin");
-}
-
+#endif
+}
+#endif
+
+#ifdef CAN_DRAW_IN_TITLEBAR
 function onTitlebarMaxClick() {
   if (window.windowState == window.STATE_MAXIMIZED)
     window.restore();
   else
     window.maximize();
 }
 #endif
 
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -424,393 +424,29 @@
       <iframe id="customizeToolbarSheetIFrame"
               style="&dialog.style;"
               hidden="true"/>
     </panel>
 
     <tooltip id="tabbrowser-tab-tooltip" onpopupshowing="gBrowser.createTooltip(event);"/>
   </popupset>
 
-#ifdef MENUBAR_CAN_AUTOHIDE
+#ifdef CAN_DRAW_IN_TITLEBAR
   <vbox id="titlebar">
   <hbox id="titlebar-content">
   <hbox id="appmenu-button-container" align="start">
   <button id="appmenu-button"
           type="menu"
 #ifdef XP_WIN
           label="&brandShortName;"
 #else
           label="&appMenuButton.label;"
 #endif
           style="-moz-user-focus: ignore;">
-    <menupopup id="appmenu-popup"
-#ifdef MOZ_SERVICES_SYNC
-               onpopupshowing="updateEditUIVisibility();gSyncUI.updateUI();">
-#else
-               onpopupshowing="updateEditUIVisibility();">
-#endif
-      <hbox>
-        <vbox id="appmenuPrimaryPane">
-          <hbox flex="1"
-                class="split-menuitem">
-            <menuitem id="appmenu_newTab"
-                      class="menuitem-tooltip split-menuitem-item"
-                      flex="1"
-                      label="&tabCmd.label;"
-                      command="cmd_newNavigatorTab"
-                      key="key_newNavigatorTab"/>
-              <menu class="split-menuitem-menu">
-                <menupopup>
-                  <menuitem id="appmenu_newTab_popup"
-                            label="&tabCmd.label;"
-                            command="cmd_newNavigatorTab"
-                            key="key_newNavigatorTab"/>
-                  <menuitem id="appmenu_newNavigator"
-                            label="&newNavigatorCmd.label;"
-                            command="cmd_newNavigator"
-                            key="key_newNavigator"/>
-                  <menuseparator/>
-                  <menuitem id="appmenu_openFile"
-                            label="&openFileCmd.label;"
-                            command="Browser:OpenFile"
-                            key="openFileKb"/>
-                </menupopup>
-               </menu>
-          </hbox>
-          <menuitem id="appmenu_privateBrowsing"
-                    class="menuitem-iconic menuitem-iconic-tooltip"
-                    label="&privateBrowsingCmd.start.label;"
-                    startlabel="&privateBrowsingCmd.start.label;"
-                    stoplabel="&privateBrowsingCmd.stop.label;"
-                    command="Tools:PrivateBrowsing"
-                    key="key_privatebrowsing"/>
-          <menuitem label="&goOfflineCmd.label;"
-                    id="appmenu_offlineModeRecovery"
-                    type="checkbox"
-                    observes="workOfflineMenuitemState"
-                    oncommand="BrowserOffline.toggleOfflineStatus();"/>
-          <menuseparator class="appmenu-menuseparator"/>
-          <hbox>
-            <menuitem id="appmenu-edit-label"
-                      label="&appMenuEdit.label;"
-                      disabled="true"/>
-            <toolbarbutton id="appmenu-cut"
-                           class="appmenu-edit-button"
-                           command="cmd_cut"
-                           onclick="if (!this.disabled) hidePopup();"
-                           tooltiptext="&cutButton.tooltip;"/>
-            <toolbarbutton id="appmenu-copy"
-                           class="appmenu-edit-button"
-                           command="cmd_copy"
-                           onclick="if (!this.disabled) hidePopup();"
-                           tooltiptext="&copyButton.tooltip;"/>
-            <toolbarbutton id="appmenu-paste"
-                           class="appmenu-edit-button"
-                           command="cmd_paste"
-                           onclick="if (!this.disabled) hidePopup();"
-                           tooltiptext="&pasteButton.tooltip;"/>
-          </hbox>
-          <menuitem id="appmenu_find"
-                    class="menuitem-tooltip"
-                    label="&appMenuFind.label;"
-                    command="cmd_find"
-                    key="key_find"/>
-          <menuseparator class="appmenu-menuseparator"/>
-          <menuitem id="appmenu_savePage"
-                    class="menuitem-tooltip"
-                    label="&savePageCmd.label;"
-                    command="Browser:SavePage"
-                    key="key_savePage"/>
-          <menuitem id="appmenu_sendLink"
-                    label="&sendPageCmd.label;"
-                    command="Browser:SendLink"/>
-          <hbox flex="1"
-                class="split-menuitem">
-            <menuitem id="appmenu_print"
-                      class="menuitem-iconic menuitem-iconic-tooltip split-menuitem-item"
-                      flex="1"
-                      label="&printCmd.label;"
-                      command="cmd_print"
-                      key="printKb"/>
-            <menu class="split-menuitem-menu">
-              <menupopup>
-                <menuitem id="appmenu_print_popup"
-                          class="menuitem-iconic"
-                          label="&printCmd.label;"
-                          command="cmd_print"
-                          key="printKb"/>
-                <menuitem id="appmenu_printPreview"
-                          label="&printPreviewCmd.label;"
-                          command="cmd_printPreview"/>
-                <menuitem id="appmenu_printSetup"
-                          label="&printSetupCmd.label;"
-                          command="cmd_pageSetup"/>
-              </menupopup>
-            </menu>
-          </hbox>
-          <menuseparator class="appmenu-menuseparator"/>
-          <menu id="appmenu_webDeveloper"
-                label="&appMenuWebDeveloper.label;">
-            <menupopup id="appmenu_webDeveloper_popup">
-              <menuitem id="appmenu_webConsole"
-                        label="&webConsoleCmd.label;"
-                        oncommand="HUDConsoleUI.toggleHUD();"
-                        key="key_webConsole"/>
-              <menuitem id="appmenu_pageInspect"
-                        hidden="true"
-                        label="&inspectMenu.label;"
-                        type="checkbox"
-                        command="Tools:Inspect"
-                        key="key_inspect"/>
-              <menuseparator/>
-              <menuitem id="appmenu_pageSource"
-                        label="&viewPageSourceCmd.label;"
-                        command="View:PageSource"
-                        key="key_viewSource"/>
-              <menuseparator/>
-#define ID_PREFIX appmenu_developer_
-#include browser-charsetmenu.inc
-#undef ID_PREFIX
-              <menuseparator/>
-              <menuitem label="&goOfflineCmd.label;"
-                        type="checkbox"
-                        observes="workOfflineMenuitemState"
-                        oncommand="BrowserOffline.toggleOfflineStatus();"/>
-            </menupopup>
-          </menu>
-          <menuseparator class="appmenu-menuseparator"/>
-#define ID_PREFIX appmenu_
-#include browser-charsetmenu.inc
-#undef ID_PREFIX
-          <menuitem id="appmenu_fullScreen"
-                    class="menuitem-tooltip"
-                    label="&fullScreenCmd.label;"
-                    type="checkbox"
-                    observes="View:FullScreen"
-                    key="key_fullScreen"/>
-          <menuitem id="appmenu-quit"
-                    class="menuitem-iconic"
-#ifdef XP_WIN
-                    label="&quitApplicationCmdWin.label;"
-#else
-                    label="&quitApplicationCmd.label;"
-#endif
-                    command="cmd_quitApplication"/>
-        </vbox>
-        <vbox id="appmenuSecondaryPane">
-          <hbox class="split-menuitem">
-            <menuitem id="appmenu_bookmarks"
-                      class="menuitem-iconic menuitem-iconic-tooltip split-menuitem-item"
-                      flex="1"
-                      label="&bookmarksMenu.label;"
-                      command="Browser:ShowAllBookmarks"
-                      key="manBookmarkKb"/>
-            <menu id="appmenu_bookmarksMenu"
-                  class="split-menuitem-menu">
-              <menupopup id="appmenu_bookmarksPopup"
-                         placespopup="true"
-                         context="placesContext"
-                         openInTabs="children"
-                         oncommand="BookmarksEventHandler.onCommand(event);"
-                         onclick="BookmarksEventHandler.onClick(event);"
-                         onpopupshowing="BookmarksMenuButton.onPopupShowing(event);
-                                         if (!this.parentNode._placesView)
-                                           new PlacesMenu(event, 'place:folder=BOOKMARKS_MENU');"
-                         tooltip="bhTooltip"
-                         popupsinherittooltip="true">
-                <menuitem id="appmenu_showAllBookmarks"
-                          label="&showAllBookmarks.label;"
-                          command="Browser:ShowAllBookmarks"
-                          context=""
-                          key="manBookmarkKb"/>
-                <menuseparator/>
-                <menuitem id="appmenu_bookmarkThisPage"
-                          class="menuitem-iconic"
-                          label="&bookmarkThisPageCmd.label;"
-                          command="Browser:AddBookmarkAs"
-                          key="addBookmarkAsKb"/>
-                <menuitem id="appmenu_subscribeToPage"
-                          class="menuitem-iconic"
-                          label="&subscribeToPageMenuitem.label;"
-                          oncommand="return FeedHandler.subscribeToFeed(null, event);"
-                          onclick="checkForMiddleClick(this, event);"
-                          observes="singleFeedMenuitemState"/>
-                <menu id="appmenu_subscribeToPageMenu"
-                      class="menu-iconic"
-                      label="&subscribeToPageMenupopup.label;"
-                      observes="multipleFeedsMenuState">
-                  <menupopup id="appmenu_subscribeToPageMenupopup"
-                             onpopupshowing="return FeedHandler.buildFeedList(event.target);"
-                             oncommand="return FeedHandler.subscribeToFeed(null, event);"
-                             onclick="checkForMiddleClick(this, event);"/>
-                </menu>
-                <menuseparator/>
-                <menu id="appmenu_bookmarksToolbar"
-                      placesanonid="toolbar-autohide"
-                      class="menu-iconic bookmark-item"
-                      label="&personalbarCmd.label;"
-                      container="true">
-                  <menupopup id="appmenu_bookmarksToolbarPopup"
-                             placespopup="true"
-                             context="placesContext"
-                             onpopupshowing="if (!this.parentNode._placesView)
-                                               new PlacesMenu(event, 'place:folder=TOOLBAR');"/>
-                </menu>
-                <menuseparator/>
-                <!-- Bookmarks menu items -->
-                <menuseparator builder="end"
-                               class="hide-if-empty-places-result"/>
-                <menuitem id="appmenu_unsortedBookmarks"
-                          label="&appMenuUnsorted.label;"
-                          oncommand="PlacesCommandHook.showPlacesOrganizer('UnfiledBookmarks');"
-                          class="menuitem-iconic"/>
-              </menupopup>
-            </menu>
-          </hbox>
-          <hbox class="split-menuitem">
-            <menuitem id="appmenu_history"
-                      class="menuitem-iconic menuitem-iconic-tooltip split-menuitem-item"
-                      flex="1"
-                      label="&historyMenu.label;"
-                      command="Browser:ShowAllHistory"
-                      key="showAllHistoryKb"/>
-            <menu id="appmenu_historyMenu"
-                  class="split-menuitem-menu">
-              <menupopup id="appmenu_historyMenupopup"
-                         placespopup="true"
-                         oncommand="this.parentNode._placesView._onCommand(event);"
-                         onclick="checkForMiddleClick(this, event);"
-                         onpopupshowing="if (!this.parentNode._placesView)
-                                           new HistoryMenu(event);"
-                         tooltip="bhTooltip"
-                         popupsinherittooltip="true">
-                <menuitem id="appmenu_showAllHistory"
-                          label="&showAllHistoryCmd2.label;"
-                          command="Browser:ShowAllHistory"
-                          key="showAllHistoryKb"/>
-                <menuseparator/>
-                <menuitem id="appmenu_sanitizeHistory"
-                          label="&clearRecentHistory.label;"
-                          key="key_sanitize"
-                          command="Tools:Sanitize"/>
-                <menuseparator class="hide-if-empty-places-result"/>
-                <menuitem id="appmenu_restoreLastSession"
-                          class="restoreLastSession"
-                          label="&historyRestoreLastSession.label;"
-                          oncommand="restoreLastSession();"
-                          disabled="true"/>
-                <menu id="appmenu_recentlyClosedTabsMenu"
-                      class="recentlyClosedTabsMenu"
-                      label="&historyUndoMenu.label;"
-                      disabled="true">
-                  <menupopup id="appmenu_recentlyClosedTabsMenupopup"
-                             onpopupshowing="document.getElementById('appmenu_historyMenu')._placesView.populateUndoSubmenu();"/>
-                </menu>
-                <menu id="appmenu_recentlyClosedWindowsMenu"
-                      class="recentlyClosedWindowsMenu"
-                      label="&historyUndoWindowMenu.label;"
-                      disabled="true">
-                  <menupopup id="appmenu_recentlyClosedWindowsMenupopup"
-                             onpopupshowing="document.getElementById('appmenu_historyMenu')._placesView.populateUndoWindowSubmenu();"/>
-                </menu>
-                <menuseparator/>
-              </menupopup>
-            </menu>
-          </hbox>
-            <menuitem id="appmenu_downloads"
-                      class="menuitem-tooltip"
-                      label="&downloads.label;"
-                      command="Tools:Downloads"
-                      key="key_openDownloads"/>
-            <spacer id="appmenuSecondaryPane-spacer"/>
-            <menuitem id="appmenu_addons"
-                      class="menuitem-iconic menuitem-iconic-tooltip"
-                      label="&addons.label;"
-                      command="Tools:Addons"
-                      key="key_openAddons"/>
-            <hbox class="split-menuitem">
-              <menuitem id="appmenu_customize"
-                        label="&preferencesCmd.label;"
-                        class="split-menuitem-item"
-                        flex="1"
-                        oncommand="openPreferences();"/>
-              <menu class="split-menuitem-menu"
-                    label="&preferencesCmd.label;">
-                <menupopup id="appmenu_customizeMenu"
-                           onpopupshowing="onViewToolbarsPopupShowing(event, document.getElementById('appmenu_toggleTabsOnTop').previousSibling);">
-                  <menuitem id="appmenu_preferences"
-#ifdef XP_UNIX
-                            label="&preferencesCmdUnix.label;"
-#else
-                            label="&preferencesCmd.label;"
-#endif
-                            oncommand="openPreferences();"/>
-                  <menuseparator/>
-                  <menuseparator/>
-                  <menuitem id="appmenu_toggleTabsOnTop"
-                            label="&viewTabsOnTop.label;"
-                            type="checkbox"
-                            command="cmd_ToggleTabsOnTop"/>
-                  <menuitem id="appmenu_toolbarLayout"
-                            label="&appMenuToolbarLayout.label;"
-                            command="cmd_CustomizeToolbars"/>
-                </menupopup>
-              </menu>
-            </hbox>
-            <hbox class="split-menuitem">
-              <menuitem id="appmenu_help"
-                        class="split-menuitem-item"
-                        flex="1"
-                        label="&helpMenu.label;"
-                        oncommand="openHelpLink('firefox-help')"/>
-              <menu class="split-menuitem-menu">
-                <menupopup id="appmenu_helpMenupopup">
-                  <menuitem id="appmenu_openHelp"
-                            label="&helpMenu.label;"
-                            oncommand="openHelpLink('firefox-help')"
-                            onclick="checkForMiddleClick(this, event);"/>
-                  <menuitem id="appmenu_gettingStarted"
-                            label="&appMenuGettingStarted.label;"
-                            oncommand="gBrowser.loadOneTab('http://www.mozilla.com/firefox/central/', {inBackground: false});"
-                            onclick="checkForMiddleClick(this, event);"/>
-                  <menuitem id="appmenu_troubleshootingInfo"
-                            label="&helpTroubleshootingInfo.label;"
-                            oncommand="openTroubleshootingPage()"
-                            onclick="checkForMiddleClick(this,event);"/>
-                  <menuitem id="appmenu_feedbackPage"
-                            label="&helpFeedbackPage.label;"
-                            oncommand="openFeedbackPage()"
-                            onclick="checkForMiddleClick(this, event);"/>
-                  <menuseparator/>
-                  <menuitem id="appmenu_safeMode"
-                            accesskey="&appMenuSafeMode.accesskey;"
-                            label="&appMenuSafeMode.label;"
-                            oncommand="safeModeRestart();"/>
-                  <menuseparator/>
-                  <menuitem id="appmenu_about"
-                            label="&aboutProduct.label;"
-                            oncommand="openAboutDialog();"/>
-                </menupopup>
-              </menu>
-            </hbox>
-#ifdef MOZ_SERVICES_SYNC
-            <spacer flex="1"/>
-            <!-- only one of sync-setup or sync-syncnow will be showing at once -->
-            <menuitem id="sync-setup-appmenu"
-                      label="&syncSetup.label;"
-                      observes="sync-setup-state"
-                      oncommand="gSyncUI.openSetup()"/>
-            <menuitem id="sync-syncnowitem-appmenu"
-                      label="&syncSyncNowItem.label;"
-                      observes="sync-syncnow-state"
-                      oncommand="gSyncUI.doSync(event);"/>
-#endif
-        </vbox>
-      </hbox>
-    </menupopup>
+#include browser-appmenu.inc
   </button>
   </hbox>
   <spacer id="titlebar-spacer" flex="1"/>
   <hbox id="titlebar-buttonbox">
     <toolbarbutton class="titlebar-button" id="titlebar-min" oncommand="window.minimize();"/>
     <toolbarbutton class="titlebar-button" id="titlebar-max" oncommand="onTitlebarMaxClick();"/>
     <toolbarbutton class="titlebar-button" id="titlebar-close" command="cmd_closeWindow"/>
   </hbox>
@@ -939,23 +575,26 @@
                    class="urlbar-icon"
                    onclick="PlacesStarButton.onClick(event);"/>
             <image id="go-button"
                    class="urlbar-icon"
                    tooltiptext="&goEndCap.tooltip;"
                    onclick="gURLBar.handleCommand(event);"/>
           </hbox>
           <toolbarbutton id="urlbar-go-button"
+                         class="chromeclass-toolbar-additional"
                          onclick="gURLBar.handleCommand(event);"
                          tooltiptext="&goEndCap.tooltip;"/>
           <toolbarbutton id="urlbar-reload-button"
+                         class="chromeclass-toolbar-additional"
                          command="Browser:ReloadOrDuplicate"
                          onclick="checkForMiddleClick(this, event);"
                          tooltiptext="&reloadButton.tooltip;"/>
           <toolbarbutton id="urlbar-stop-button"
+                         class="chromeclass-toolbar-additional"
                          command="Browser:Stop"
                          tooltiptext="&stopButton.tooltip;"/>
         </textbox>
       </toolbaritem>
 
       <toolbarbutton id="reload-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
                      label="&reloadCmd.label;" removable="true"
                      command="Browser:ReloadOrDuplicate"
@@ -1011,21 +650,27 @@
             <menuitem id="BMB_bookmarkThisPage"
 #ifndef XP_MACOSX
                       class="menuitem-iconic"
 #endif
                       label="&bookmarkThisPageCmd.label;"
                       command="Browser:AddBookmarkAs"
                       key="addBookmarkAsKb"/>
             <menuitem id="BMB_subscribeToPageMenuitem"
+#ifndef XP_MACOSX
+                      class="menuitem-iconic"
+#endif
                       label="&subscribeToPageMenuitem.label;"
                       oncommand="return FeedHandler.subscribeToFeed(null, event);"
                       onclick="checkForMiddleClick(this, event);"
                       observes="singleFeedMenuitemState"/>
             <menu id="BMB_subscribeToPageMenupopup"
+#ifndef XP_MACOSX
+                  class="menu-iconic"
+#endif
                   label="&subscribeToPageMenupopup.label;"
                   observes="multipleFeedsMenuState">
               <menupopup id="BMB_subscribeToPageSubmenuMenupopup"
                          onpopupshowing="return FeedHandler.buildFeedList(event.target);"
                          oncommand="return FeedHandler.subscribeToFeed(null, event);"
                          onclick="checkForMiddleClick(this, event);"/>
             </menu>
             <menuseparator/>
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -76,16 +76,18 @@ function GroupItem(listOfEls, options) {
   this.isAGroupItem = true;
   this.id = options.id || GroupItems.getNextID();
   this._isStacked = false;
   this._stackAngles = [0];
   this.expanded = null;
   this.locked = (options.locked ? Utils.copy(options.locked) : {});
   this.topChild = null;
   this.hidden = false;
+  this.fadeAwayUndoButtonDelay = 15000;
+  this.fadeAwayUndoButtonDuration = 300;
 
   this.keepProportional = false;
 
   // Variable: _activeTab
   // The <TabItem> for the groupItem's active tab.
   this._activeTab = null;
 
   // Variables: xDensity, yDensity
@@ -272,16 +274,17 @@ function GroupItem(listOfEls, options) {
   if (this.locked.bounds)
     $container.css({cursor: 'default'});
 
   if (this.locked.close)
     $close.hide();
 
   // ___ Undo Close
   this.$undoContainer = null;
+  this._undoButtonTimeoutId = null;
 
   // ___ Superclass initialization
   this._init($container[0]);
 
   if (this.$debug)
     this.$debug.css({zIndex: -1000});
 
   // ___ Children
@@ -632,46 +635,25 @@ GroupItem.prototype = Utils.extend(new I
         easing: "tabviewBounce",
         duration: 170,
         complete: function() {
           self._sendToSubscribers("groupHidden", { groupItemId: self.id });
         }
       });
     }, 50);
 
-    let remove = function() {
-      // close all children
-      let toClose = self._children.concat();
-      toClose.forEach(function(child) {
-        child.removeSubscriber(self, "close");
-        child.close();
-      });
- 
-      // remove all children
-      self.removeAll();
-      GroupItems.unregister(self);
-      self._sendToSubscribers("close");
-      self.removeTrenches();
-
-      iQ(self.container).remove();
-      self.$undoContainer.remove();
-      self.$undoContainer = null;
-      Items.unsquish();
-
-      self.deleteData();
-    };
-
     this.$undoContainer.click(function(e) {
       // Only do this for clicks on this actual element.
       if (e.target.nodeName != self.$undoContainer[0].nodeName)
         return;
 
       self.$undoContainer.fadeOut(function() {
         iQ(this).remove();
         self.hidden = false;
+        self._cancelFadeAwayUndoButtonTimer();
         self.$undoContainer = null;
 
         iQ(self.container).show().animate({
           "-moz-transform": "scale(1)",
           "opacity": 1
         }, {
           duration: 170,
           complete: function() {
@@ -681,41 +663,102 @@ GroupItem.prototype = Utils.extend(new I
           }
         });
 
         self._sendToSubscribers("groupShown", { groupItemId: self.id });
       });
     });
 
     undoClose.click(function() {
-      self.$undoContainer.fadeOut(remove);
+      self._cancelFadeAwayUndoButtonTimer();
+      self.$undoContainer.fadeOut(function() { self._removeHiddenGroupItem(); });
     });
 
-    // After 15 seconds, fade away.
-    const WAIT = 15000;
-    const FADE = 300;
+    this.setupFadeAwayUndoButtonTimer();
+    // Cancel the fadeaway if you move the mouse over the undo
+    // button, and restart the countdown once you move out of it.
+    this.$undoContainer.mouseover(function() { 
+      self._cancelFadeAwayUndoButtonTimer();
+    });
+    this.$undoContainer.mouseout(function() {
+      self.setupFadeAwayUndoButtonTimer();
+    });
+  },
+
+  // ----------
+  // Sets up fade away undo button timeout. 
+  setupFadeAwayUndoButtonTimer: function() {
+    let self = this;
 
-    let fadeaway = function() {
-      if (self.$undoContainer)
+    if (!this._undoButtonTimeoutId) {
+      this._undoButtonTimeoutId = setTimeout(function() { 
+        self._fadeAwayUndoButton(); 
+      }, this.fadeAwayUndoButtonDelay);
+    }
+  },
+  
+  // ----------
+  // Cancels the fade away undo button timeout. 
+  _cancelFadeAwayUndoButtonTimer: function() {
+    clearTimeout(this._undoButtonTimeoutId);
+    this._undoButtonTimeoutId = null;
+  }, 
+
+  // ----------
+  // Fades away the undo button
+  _fadeAwayUndoButton: function() {
+    let self = this;
+
+    if (this.$undoContainer) {
+      // if there is one or more orphan tabs or there is more than one group 
+      // and other groupS are not empty, fade away the undo button.
+      let shouldFadeAway = GroupItems.getOrphanedTabs().length > 0;
+      
+      if (!shouldFadeAway && GroupItems.groupItems.length > 1) {
+        shouldFadeAway = 
+          GroupItems.groupItems.some(function(groupItem) {
+            return (groupItem != self && groupItem.getChildren().length > 0);
+          });
+      }
+      if (shouldFadeAway) {
         self.$undoContainer.animate({
           color: "transparent",
           opacity: 0
         }, {
-          duration: FADE,
-          complete: remove
+          duration: this.fadeAwayUndoButtonDuration,
+          complete: function() { self._removeHiddenGroupItem(); }
         });
-    };
+      }
+    }
+  },
+
+  // ----------
+  // Removes the group item, its children and its container.
+  _removeHiddenGroupItem: function() {
+    let self = this;
 
-    let timeoutId = setTimeout(fadeaway, WAIT);
-    // Cancel the fadeaway if you move the mouse over the undo
-    // button, and restart the countdown once you move out of it.
-    this.$undoContainer.mouseover(function() clearTimeout(timeoutId));
-    this.$undoContainer.mouseout(function() {
-      timeoutId = setTimeout(fadeaway, WAIT);
+    // close all children
+    let toClose = this._children.concat();
+    toClose.forEach(function(child) {
+      child.removeSubscriber(self, "close");
+      child.close();
     });
+ 
+    // remove all children
+    this.removeAll();
+    GroupItems.unregister(this);
+    this._sendToSubscribers("close");
+    this.removeTrenches();
+
+    iQ(this.container).remove();
+    this.$undoContainer.remove();
+    this.$undoContainer = null;
+    Items.unsquish();
+
+    this.deleteData();
   },
 
   // ----------
   // Function: add
   // Adds an item to the groupItem.
   // Parameters:
   //
   //   a - The item to add. Can be an <Item>, a DOM element or an iQ object.
deleted file mode 100644
--- a/browser/base/content/tabview/infoitems.js
+++ /dev/null
@@ -1,252 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is infoitems.js.
- *
- * The Initial Developer of the Original Code is
- * the Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2010
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Ian Gilman <ian@iangilman.com>
- * Aza Raskin <aza@mozilla.com>
- * Michael Yoshitaka Erlewine <mitcho@mitcho.com>
- * Ehsan Akhgari <ehsan@mozilla.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-// **********
-// Title: infoitems.js
-
-// ##########
-// Class: InfoItem
-// An <Item> in TabView used for displaying information, such as the welcome video.
-// Note that it implements the <Subscribable> interface.
-//
-// ----------
-// Constructor: InfoItem
-//
-// Parameters:
-//   bounds - a <Rect> for where the item should be located
-//   options - various options for this infoItem (see below)
-//
-// Possible options:
-//   locked - see <Item.locked>; default is {}
-//   dontPush - true if this infoItem shouldn't push away on creation; default is false
-//   immediately - place the item immediately, without animation
-function InfoItem(bounds, options) {
-  try {
-    Utils.assertThrow(Utils.isRect(bounds), 'bounds');
-
-    if (typeof options == 'undefined')
-      options = {};
-
-    this._inited = false;
-    this.isAnInfoItem = true;
-    this.defaultSize = bounds.size();
-    this.locked = (options.locked ? Utils.copy(options.locked) : {});
-    this.bounds = new Rect(bounds);
-    this.isDragging = false;
-
-    var self = this;
-
-    var $container = iQ('<div>')
-      .addClass('info-item')
-      .css(this.bounds)
-      .appendTo('body');
-
-    this.$contents = iQ('<div>')
-      .appendTo($container);
-
-    var $close = iQ('<div>')
-      .addClass('close')
-      .click(function() {
-        self.close();
-      })
-      .appendTo($container);
-
-    // ___ locking
-    if (this.locked.bounds)
-      $container.css({cursor: 'default'});
-
-    if (this.locked.close)
-      $close.hide();
-
-    // ___ Superclass initialization
-    this._init($container[0]);
-
-    if (this.$debug)
-      this.$debug.css({zIndex: -1000});
-
-    // ___ Finish Up
-    if (!this.locked.bounds)
-      this.draggable();
-
-    // ___ Position
-    if (!options.dontPush)
-      this.snap(options.immediately);
-
-    this._inited = true;
-    this.save();
-  } catch(e) {
-    Utils.log(e);
-  }
-};
-
-// ----------
-InfoItem.prototype = Utils.extend(new Item(), new Subscribable(), {
-
-  // ----------
-  // Function: getStorageData
-  // Returns all of the info worth storing about this item.
-  getStorageData: function InfoItem_getStorageData() {
-    var data = null;
-
-    try {
-      data = {
-        bounds: this.getBounds(),
-        locked: Utils.copy(this.locked)
-      };
-    } catch(e) {
-      Utils.log(e);
-    }
-
-    return data;
-  },
-
-  // ----------
-  // Function: save
-  // Saves this item to persistent storage.
-  save: function InfoItem_save() {
-    try {
-      if (!this._inited) // too soon to save now
-        return;
-
-      var data = this.getStorageData();
-
-    } catch(e) {
-      Utils.log(e);
-    }
-  },
-
-  // ----------
-  // Function: setBounds
-  // Sets the bounds with the given <Rect>, animating unless "immediately" is false.
-  setBounds: function InfoItem_setBounds(rect, immediately) {
-    try {
-      Utils.assertThrow(Utils.isRect(rect), 'InfoItem.setBounds: rect must be a real rectangle!');
-
-      // ___ Determine what has changed
-      var css = {};
-
-      if (rect.left != this.bounds.left)
-        css.left = rect.left;
-
-      if (rect.top != this.bounds.top)
-        css.top = rect.top;
-
-      if (rect.width != this.bounds.width)
-        css.width = rect.width;
-
-      if (rect.height != this.bounds.height)
-        css.height = rect.height;
-
-      if (Utils.isEmptyObject(css))
-        return;
-
-      this.bounds = new Rect(rect);
-      Utils.assertThrow(Utils.isRect(this.bounds), 
-          'InfoItem.setBounds: this.bounds must be a real rectangle!');
-
-      // ___ Update our representation
-      if (immediately) {
-        iQ(this.container).css(css);
-      } else {
-        TabItems.pausePainting();
-        iQ(this.container).animate(css, {
-          duration: 350,
-          easing: "tabviewBounce",
-          complete: function() {
-            TabItems.resumePainting();
-          }
-        });
-      }
-
-      this._updateDebugBounds();
-      this.setTrenches(rect);
-      this.save();
-    } catch(e) {
-      Utils.log(e);
-    }
-  },
-
-  // ----------
-  // Function: setZ
-  // Set the Z order for the item's container.
-  setZ: function InfoItem_setZ(value) {
-    try {
-      Utils.assertThrow(typeof value == 'number', 'value must be a number');
-
-      this.zIndex = value;
-
-      iQ(this.container).css({zIndex: value});
-
-      if (this.$debug)
-        this.$debug.css({zIndex: value + 1});
-    } catch(e) {
-      Utils.log(e);
-    }
-  },
-
-  // ----------
-  // Function: close
-  // Closes the item.
-  close: function InfoItem_close() {
-    try {
-      this._sendToSubscribers("close");
-      this.removeTrenches();
-      iQ(this.container).fadeOut(function() {
-        iQ(this).remove();
-        Items.unsquish();
-      });
-
-    } catch(e) {
-      Utils.log(e);
-    }
-  },
-
-  // ----------
-  // Function: html
-  // Sets the item's container's html to the specified value.
-  html: function InfoItem_html(value) {
-    try {
-      Utils.assertThrow(typeof value == 'string', 'value must be a string');
-      this.$contents.html(value);
-    } catch(e) {
-      Utils.log(e);
-    }
-  }
-});
--- a/browser/base/content/tabview/tabview.js
+++ b/browser/base/content/tabview/tabview.js
@@ -47,13 +47,10 @@ XPCOMUtils.defineLazyGetter(this, "gPriv
 
 #include iq.js
 #include storage.js
 #include items.js
 #include groupitems.js
 #include tabitems.js
 #include drag.js
 #include trench.js
-#include infoitems.js
 #include ui.js
 #include search.js
-
-
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -244,26 +244,29 @@ let UI = {
     this._reorderTabsOnHide = null;
     this._frameInitialized = false;
   },
   
   // Function: reset
   // Resets the Panorama view to have just one group with all tabs
   // and, if firstTime == true, add the welcome video/tab
   reset: function UI_reset(firstTime) {
-    let padding = 10;
-    let infoWidth = 350;
-    let infoHeight = 232;
+    let padding = Trenches.defaultRadius;
+    let welcomeWidth = 300;
     let pageBounds = Items.getPageBounds();
     pageBounds.inset(padding, padding);
 
+    let $actions = iQ("#actions");
+    if ($actions)
+      pageBounds.width -= $actions.width();
+
     // ___ make a fresh groupItem
     let box = new Rect(pageBounds);
-    box.width = 
-      Math.min(box.width * 0.667, pageBounds.width - (infoWidth + padding));
+    box.width = Math.min(box.width * 0.667,
+                         pageBounds.width - (welcomeWidth + padding));
     box.height = box.height * 0.667;
 
     GroupItems.groupItems.forEach(function(group) {
       group.close();
     });
     
     let options = {
       bounds: box,
@@ -275,27 +278,28 @@ let UI = {
       if (item.parent)
         item.parent.remove(item);
       groupItem.add(item, null, {immediately: true});
     });
     
     if (firstTime) {
       gPrefBranch.setBoolPref("experienced_first_run", true);
 
-      // ___ make info item
-      let video = 
-        "http://videos-cdn.mozilla.net/firefox4beta/tabcandy_howto.webm";
-      let html =
-        "<div class='intro'>"
-          + "<video src='" + video + "' width='100%' preload controls>"
-        + "</div>";
-      let infoBox = new Rect(box.right + padding, box.top,
-                         infoWidth, infoHeight);
-      let infoItem = new InfoItem(infoBox);
-      infoItem.html(html);
+      let url = gPrefBranch.getCharPref("welcome_url");
+      let newTab = gBrowser.loadOneTab(url, {inBackground: true});
+      let newTabItem = newTab.tabItem;
+      let parent = newTabItem.parent;
+      Utils.assert(parent, "should have a parent");
+
+      newTabItem.parent.remove(newTabItem);
+      let aspect = TabItems.tabHeight / TabItems.tabWidth;
+      let welcomeBounds = new Rect(box.right + padding, box.top,
+                                   welcomeWidth, welcomeWidth * aspect);
+      newTabItem.setBounds(welcomeBounds, true);
+      GroupItems.setActiveGroupItem(groupItem);
     }
   },
 
   // Function: blurAll
   // Blurs any currently focused element
   //
   blurAll: function UI_blurAll() {
     iQ(":focus").each(function(element) {
--- a/browser/base/content/test/browser_bug553455.js
+++ b/browser/base/content/test/browser_bug553455.js
@@ -28,36 +28,31 @@ function wait_for_notification(aCallback
     aCallback(PopupNotifications.panel);
   }, false);
 }
 
 function wait_for_install_dialog(aCallback) {
   info("Waiting for install dialog");
   Services.wm.addListener({
     onOpenWindow: function(aXULWindow) {
-      info("Install dialog opened, waiting for load");
+      info("Install dialog opened, waiting for focus");
       Services.wm.removeListener(this);
 
       var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                                 .getInterface(Ci.nsIDOMWindowInternal);
-      domwindow.addEventListener("load", function() {
-        domwindow.removeEventListener("load", arguments.callee, false);
-
+      waitForFocus(function() {
+        info("Saw install dialog");
         is(domwindow.document.location.href, XPINSTALL_URL, "Should have seen the right window open");
 
-        // Allow other window load listeners to execute before passing to callback
-        executeSoon(function() {
-          info("Saw install dialog");
-          // Override the countdown timer on the accept button
-          var button = domwindow.document.documentElement.getButton("accept");
-          button.disabled = false;
+        // Override the countdown timer on the accept button
+        var button = domwindow.document.documentElement.getButton("accept");
+        button.disabled = false;
 
-          aCallback(domwindow);
-        });
-      }, false);
+        aCallback(domwindow);
+      }, domwindow);
     },
 
     onCloseWindow: function(aXULWindow) {
     },
 
     onWindowTitleChange: function(aXULWindow, aNewTitle) {
     }
   });
@@ -592,17 +587,17 @@ var XPInstallObserver = {
     info("Observed " + aTopic + " for " + installInfo.installs.length + " installs");
     installInfo.installs.forEach(function(aInstall) {
       info("Install of " + aInstall.sourceURI.spec + " was in state " + aInstall.state);
     });
   }
 };
 
 function test() {
-  requestLongerTimeout(2);
+  requestLongerTimeout(4);
   waitForExplicitFinish();
 
   Services.prefs.setBoolPref("extensions.logging.enabled", true);
 
   Services.obs.addObserver(XPInstallObserver, "addon-install-started", false);
   Services.obs.addObserver(XPInstallObserver, "addon-install-blocked", false);
   Services.obs.addObserver(XPInstallObserver, "addon-install-failed", false);
   Services.obs.addObserver(XPInstallObserver, "addon-install-complete", false);
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -48,16 +48,17 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug580412.js \
                  browser_tabview_bug587043.js \
                  browser_tabview_bug587990.js \
                  browser_tabview_bug590606.js \
                  browser_tabview_bug591706.js \
                  browser_tabview_bug594176.js \
                  browser_tabview_bug595191.js \
                  browser_tabview_bug595518.js \
+                 browser_tabview_bug595521.js \
                  browser_tabview_bug595804.js \
                  browser_tabview_bug595930.js \
                  browser_tabview_bug595943.js \
                  browser_tabview_bug598600.js \
                  browser_tabview_dragdrop.js \
                  browser_tabview_exit_button.js \
                  browser_tabview_group.js \
                  browser_tabview_launch.js \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug595521.js
@@ -0,0 +1,101 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is a test for bug 595521.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * Raymond Lee <raymond@appcoast.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+let fadeAwayUndoButtonDelay;
+let fadeAwayUndoButtonDuration;
+
+function test() {
+  waitForExplicitFinish();
+
+  window.addEventListener("tabviewshown", testCloseLastGroup, false);
+  TabView.toggle();
+}
+
+function testCloseLastGroup() {
+  window.removeEventListener("tabviewshown", testCloseLastGroup, false);
+  ok(TabView.isVisible(), "Tab View is visible");
+
+  let contentWindow = document.getElementById("tab-view").contentWindow;
+
+  is(contentWindow.GroupItems.groupItems.length, 1, "Has one group only");
+
+  let groupItem = contentWindow.GroupItems.groupItems[0];
+  
+  let checkExistence = function() {
+    is(contentWindow.GroupItems.groupItems.length, 1, 
+       "Still has one group after delay");
+
+    EventUtils.sendMouseEvent(
+      { type: "click" }, groupItem.$undoContainer[0], contentWindow);
+  };
+
+  groupItem.addSubscriber(groupItem, "groupHidden", function() {
+    groupItem.removeSubscriber(groupItem, "groupHidden");
+    // it should still stay after 3 ms.
+    setTimeout(checkExistence, 3);
+  });
+
+  groupItem.addSubscriber(groupItem, "groupShown", function() {
+    groupItem.removeSubscriber(groupItem, "groupShown");
+
+    let endGame = function() {
+      window.removeEventListener("tabviewhidden", endGame, false);
+      ok(!TabView.isVisible(), "Tab View is hidden");
+
+      groupItem.fadeAwayUndoButtonDelay = fadeAwayUndoButtonDelay;
+      groupItem.fadeAwayUndoButtonDuration = fadeAwayUndoButtonDuration;
+
+      finish();
+    };
+    window.addEventListener("tabviewhidden", endGame, false);
+
+    TabView.toggle();
+  });
+
+  let closeButton = groupItem.container.getElementsByClassName("close");
+  ok(closeButton, "Group item close button exists");
+
+  // store the original values
+  fadeAwayUndoButtonDelay = groupItem.fadeAwayUndoButtonDelay;
+  fadeAwayUndoButtonDuration = groupItem.fadeAwayUndoButtonDuration;
+
+  // set both fade away delay and duration to 1ms
+  groupItem.fadeAwayUndoButtonDelay = 1;
+  groupItem.fadeAwayUndoButtonDuration = 1;
+
+  EventUtils.sendMouseEvent({ type: "click" }, closeButton[0], contentWindow);
+}
--- a/browser/base/content/test/tabview/browser_tabview_bug598600.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug598600.js
@@ -30,25 +30,18 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 let newWin;
-let prefService;
-
 function test() {
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
-  prefService = 
-    Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).
-      getBranch("browser.panorama.");
-  // make sure we don't trigger the 'first run' behavior
-  prefService.setBoolPref("experienced_first_run", true);
 
   waitForExplicitFinish();
 
   // open a new window and setup the window state.
   newWin = openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no");
   newWin.addEventListener("load", function(event) {
     this.removeEventListener("load", arguments.callee, false);
 
@@ -99,17 +92,16 @@ function test() {
       newWin.removeEventListener("tabviewshown", onTabViewShow, false);
 
       let contentWindow = newWin.document.getElementById("tab-view").contentWindow;
 
       is(contentWindow.GroupItems.groupItems.length, 2, "Has two group items");
       is(contentWindow.GroupItems.getOrphanedTabs().length, 0, "No orphan tabs");
 
       // clean up and finish
-      prefService.setBoolPref("experienced_first_run", false);
       newWin.close();
 
       finish();
     }
     newWin.addEventListener("tabviewshown", onTabViewShow, false);
     newWin.TabView.toggle();
   }, false);
 }
--- a/browser/base/content/test/tabview/browser_tabview_firstrun_pref.js
+++ b/browser/base/content/test/tabview/browser_tabview_firstrun_pref.js
@@ -39,52 +39,64 @@ var prefsBranch = Cc["@mozilla.org/prefe
                   getService(Ci.nsIPrefService).
                   getBranch("browser.panorama.");
 
 function test() {
   waitForExplicitFinish();
 
   ok(!TabView.isVisible(), "Main window TabView is hidden");
 
+  ok(experienced(), "should start as experienced");
+
   prefsBranch.setBoolPref("experienced_first_run", false);
-  ok(!experienced(), "not experienced");
+  ok(!experienced(), "set to not experienced");
 
   newWindowWithTabView(checkFirstRun, part2);
 }
 
 function experienced() {
   return prefsBranch.prefHasUserValue("experienced_first_run") &&
     prefsBranch.getBoolPref("experienced_first_run");
 }
 
 function checkFirstRun(win) {
   let contentWindow = win.document.getElementById("tab-view").contentWindow;
   
-  let infoItems = contentWindow.iQ(".info-item");
-  is(infoItems.length, 1, "There should be an info item");
-
+  is(win.gBrowser.tabs.length, 2, "There should be two tabs");
+  
   let groupItems = contentWindow.GroupItems.groupItems;
   is(groupItems.length, 1, "There should be one group");
+  is(groupItems[0].getChildren().length, 1, "...with one child");
+
+  let orphanTabCount = contentWindow.GroupItems.getOrphanedTabs().length;
+  is(orphanTabCount, 1, "There should also be an orphaned tab");
   
   ok(experienced(), "we're now experienced");
 }
 
 function part2() {
   newWindowWithTabView(checkNotFirstRun, endGame);
 }
 
 function checkNotFirstRun(win) {
   let contentWindow = win.document.getElementById("tab-view").contentWindow;
   
-  let infoItems = contentWindow.iQ(".info-item");
-  is(infoItems.length, 0, "There should be no info items");
+  is(win.gBrowser.tabs.length, 1, "There should be one tab");
+  
+  let groupItems = contentWindow.GroupItems.groupItems;
+  is(groupItems.length, 1, "There should be one group");
+  is(groupItems[0].getChildren().length, 1, "...with one child");
+
+  let orphanTabCount = contentWindow.GroupItems.getOrphanedTabs().length;
+  is(orphanTabCount, 0, "There should also be no orphaned tabs");
 }
 
 function endGame() {
   ok(!TabView.isVisible(), "Main window TabView is still hidden");
+  ok(experienced(), "should finish as experienced");
   finish();
 }
 
 function newWindowWithTabView(callback, completeCallback) {
   let charsetArg = "charset=" + window.content.document.characterSet;
   let win = window.openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no,height=800,width=800",
                               "about:blank", charsetArg, null, null, true);
   let onLoad = function() {
--- a/browser/base/content/test/tabview/browser_tabview_launch.js
+++ b/browser/base/content/test/tabview/browser_tabview_launch.js
@@ -50,23 +50,38 @@ function test() {
   ok(button, "Tab View button exists");
   button.doCommand();
 }
 
 // ----------
 function onTabViewLoadedAndShown() {
   window.removeEventListener("tabviewshown", onTabViewLoadedAndShown, false);
   
-  ok(TabView.isVisible(), "Tab View is visible. Count: " + tabViewShownCount);
-  tabViewShownCount++;
+  // Evidently sometimes isVisible (which is based on the selectedIndex of the
+  // tabview deck) isn't updated immediately when called from button.doCommand,
+  // so we add a little timeout here to get outside of the doCommand call.
+  // If the initial timeout isn't enough, we keep waiting in case it's taking
+  // longer than expected.
+  // See bug 594909.
+  let deck = document.getElementById("tab-view-deck");
+  function waitForSwitch() {
+    if (deck.selectedIndex == 1) {
+      ok(TabView.isVisible(), "Tab View is visible. Count: " + tabViewShownCount);
+      tabViewShownCount++;
+      
+      // kick off the series
+      window.addEventListener("tabviewshown", onTabViewShown, false);
+      window.addEventListener("tabviewhidden", onTabViewHidden, false);
+      TabView.toggle();
+    } else {
+      setTimeout(waitForSwitch, 10);
+    }
+  }
   
-  // kick off the series
-  window.addEventListener("tabviewshown", onTabViewShown, false);
-  window.addEventListener("tabviewhidden", onTabViewHidden, false);
-  TabView.toggle();
+  setTimeout(waitForSwitch, 1);
 }
 
 // ----------
 function onTabViewShown() {
   // add the count to the message so we can track things more easily.
   ok(TabView.isVisible(), "Tab View is visible. Count: " + tabViewShownCount);
   tabViewShownCount++;
   TabView.toggle();
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -156,17 +156,17 @@
           insertLocation = insertLocation.nextSibling;
         if (insertLocation) {
           pasteAndGo = document.createElement("menuitem");
           let label = Services.strings.createBundle("chrome://browser/locale/browser.properties").
                                    GetStringFromName("pasteAndGo.label");
           pasteAndGo.setAttribute("label", label);
           pasteAndGo.setAttribute("anonid", "paste-and-go");
           pasteAndGo.setAttribute("oncommand",
-              "gURLBar.value = ''; goDoCommand('cmd_paste'); gURLBar.handleCommand();");
+              "gURLBar.select(); goDoCommand('cmd_paste'); gURLBar.handleCommand();");
           cxmenu.insertBefore(pasteAndGo, insertLocation.nextSibling);
         }
       ]]></constructor>
 
       <destructor><![CDATA[
         this._prefs.removeObserver("", this);
         this._prefs = null;
         this.inputField.controllers.removeController(this._copyCutController);
@@ -267,18 +267,23 @@
             // Things may go wrong when adding url to session history,
             // but don't let that interfere with the loading of the url.
             Cu.reportError(ex);
           }
 
           if (aTriggeringEvent instanceof MouseEvent) {
             // We have a mouse event (from the go button), so use the standard
             // UI link behaviors
-            openUILink(url, aTriggeringEvent, false, false,
-                       true /* allow third party fixup */, postData);
+            let where = whereToOpenLink(aTriggeringEvent, false, false);
+            if (where != "current") {
+              this.handleRevert();
+              content.focus();
+            }
+            openUILinkIn(url, where,
+                        { allowThirdPartyFixup: true, postData: postData });
             return;
           }
 
           if (aTriggeringEvent && aTriggeringEvent.altKey) {
             this.handleRevert();
             content.focus();
             gBrowser.loadOneTab(url, {
                                 postData: postData,
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -407,19 +407,18 @@ function isBidiEnabled() {
   } catch (e) {}
 
   return rv;
 }
 
 function openAboutDialog() {
   var enumerator = Services.wm.getEnumerator("Browser:About");
   while (enumerator.hasMoreElements()) {
+    // Only open one about window (Bug 599573)
     let win = enumerator.getNext();
-    if (win.opener != window)
-      continue;
     win.focus();
     return;
   }
 
 #ifdef XP_MACOSX
   var features = "chrome,resizable=no,minimizable=no";
 #else
   var features = "chrome,centerscreen,dependent";
@@ -481,117 +480,22 @@ function openTroubleshootingPage()
 /**
  * Opens the feedback page for this version of the application.
  */
 function openFeedbackPage()
 {
   openUILinkIn("http://input.mozilla.com/feedback", "tab");
 }
 
-
-#ifdef MOZ_UPDATER
-/**
- * Opens the update manager and checks for updates to the application.
- */
-function checkForUpdates()
-{
-  var um = 
-      Components.classes["@mozilla.org/updates/update-manager;1"].
-      getService(Components.interfaces.nsIUpdateManager);
-  var prompter = 
-      Components.classes["@mozilla.org/updates/update-prompt;1"].
-      createInstance(Components.interfaces.nsIUpdatePrompt);
-
-  // If there's an update ready to be applied, show the "Update Downloaded"
-  // UI instead and let the user know they have to restart the browser for
-  // the changes to be applied. 
-  if (um.activeUpdate && um.activeUpdate.state == "pending")
-    prompter.showUpdateDownloaded(um.activeUpdate);
-  else
-    prompter.checkForUpdates();
-}
-#endif
-
-#ifdef MOZ_UPDATER
-/**
- * Updates an element to reflect the state of available update services.
- */
-function setupCheckForUpdates(checkForUpdates, aStringBundle)
-{
-  var updates = 
-      Components.classes["@mozilla.org/updates/update-service;1"].
-      getService(Components.interfaces.nsIApplicationUpdateService);
-  var um = 
-      Components.classes["@mozilla.org/updates/update-manager;1"].
-      getService(Components.interfaces.nsIUpdateManager);
-
-  // Disable the UI if the update enabled pref has been locked by the 
-  // administrator or if we cannot update for some other reason
-  var canCheckForUpdates = updates.canCheckForUpdates;
-  checkForUpdates.setAttribute("disabled", !canCheckForUpdates);
-  if (!canCheckForUpdates)
-    return; 
-
-  var activeUpdate = um.activeUpdate;
-
-  // If there's an active update, substitute its name into the label
-  // we show for this item, otherwise display a generic label.
-  function getStringWithUpdateName(key) {
-    if (activeUpdate && activeUpdate.name)
-      return aStringBundle.formatStringFromName(key, [activeUpdate.name], 1);
-    return aStringBundle.GetStringFromName(key + "Fallback");
-  }
-
-  // By default, show "Check for Updates..."
-  var key = "default";
-  if (activeUpdate) {
-    switch (activeUpdate.state) {
-    case "downloading":
-      // If we're downloading an update at present, show the text:
-      // "Downloading Firefox x.x..." otherwise we're paused, and show
-      // "Resume Downloading Firefox x.x..."
-      key = updates.isDownloading ? "downloading" : "resume";
-      break;
-    case "pending":
-      // If we're waiting for the user to restart, show: "Apply Downloaded
-      // Updates Now..."
-      key = "pending";
-      break;
-    }
-  }
-  checkForUpdates.label = getStringWithUpdateName("updatesItem_" + key);
-  checkForUpdates.accessKey = aStringBundle.
-                              GetStringFromName("updatesItem_" + key + ".accesskey");
-  if (um.activeUpdate && updates.isDownloading)
-    checkForUpdates.setAttribute("loading", "true");
-  else
-    checkForUpdates.removeAttribute("loading");
-}
-#endif
-
 function buildHelpMenu()
 {
   // Enable/disable the "Report Web Forgery" menu item.  safebrowsing object
   // may not exist in OSX
   if (typeof safebrowsing != "undefined")
     safebrowsing.setReportPhishingMenu();
-
-#ifdef XP_MACOSX
-#ifdef MOZ_UPDATER
-  var checkForUpdates = document.getElementById("checkForUpdates");
-  var browserBundle = document.getElementById("bundle_browser").stringBundle;
-  setupCheckForUpdates(checkForUpdates, browserBundle);
-#else  
-  // Needed by safebrowsing for inserting its menuitem so just hide it
-  document.getElementById("updateSeparator").hidden = true;
-#endif
-#else
-  // Needed by safebrowsing for inserting its menuitem so just hide it
-  document.getElementById("updateSeparator").hidden = true;
-#endif
 }
 
 function isElementVisible(aElement)
 {
   if (!aElement)
     return false;
 
   // If aElement or a direct or indirect parent is hidden or collapsed,
--- a/browser/branding/nightly/pref/firefox-branding.js
+++ b/browser/branding/nightly/pref/firefox-branding.js
@@ -1,10 +1,11 @@
 pref("startup.homepage_override_url","http://www.mozilla.org/projects/%APP%/%VERSION%/whatsnew/");
 pref("startup.homepage_welcome_url","http://www.mozilla.org/projects/%APP%/%VERSION%/firstrun/");
+pref("browser.panorama.welcome_url", "http://www.mozilla.com/firefox/panorama/");
 // The time interval between checks for a new version (in seconds)
 // nightly=8 hours, official=24 hours
 pref("app.update.interval", 28800);
 // The time interval between the downloading of mar file chunks in the
 // background (in seconds)
 pref("app.update.download.backgroundInterval", 60);
 // URL user can browse to manually if for some reason all update installation
 // attempts fail.
--- a/browser/branding/unofficial/pref/firefox-branding.js
+++ b/browser/branding/unofficial/pref/firefox-branding.js
@@ -1,10 +1,11 @@
 pref("startup.homepage_override_url","http://www.mozilla.org/projects/%APP%/%VERSION%/whatsnew/");
 pref("startup.homepage_welcome_url","http://www.mozilla.org/projects/%APP%/%VERSION%/firstrun/");
+pref("browser.panorama.welcome_url", "http://www.mozilla.com/firefox/panorama/");
 // The time interval between checks for a new version (in seconds)
 // nightly=8 hours, official=24 hours
 pref("app.update.interval", 28800);
 // The time interval between the downloading of mar file chunks in the
 // background (in seconds)
 pref("app.update.download.backgroundInterval", 60);
 // URL user can browse to manually if for some reason all update installation
 // attempts fail.
--- a/browser/components/places/content/browserPlacesViews.js
+++ b/browser/components/places/content/browserPlacesViews.js
@@ -494,20 +494,20 @@ PlacesViewBase.prototype = {
     // Here we need the <menu>.
     if (elt.localName == "menupopup")
       elt = elt.parentNode;
 
     if (!aNewTitle && elt.localName != "toolbarbutton") {
       // Many users consider toolbars as shortcuts containers, so explicitly
       // allow empty labels on toolbarbuttons.  For any other element try to be
       // smarter, guessing a title from the uri.
-      elt.label = PlacesUIUtils.getBestTitle(aPlacesNode);
+      elt.setAttribute("label", PlacesUIUtils.getBestTitle(aPlacesNode));
     }
     else {
-      elt.label = aNewTitle;
+      elt.setAttribute("label", aNewTitle);
     }
   },
 
   nodeRemoved:
   function PVB_nodeRemoved(aParentPlacesNode, aPlacesNode, aIndex) {
     let parentElt = aParentPlacesNode._DOMElement;
     let elt = aPlacesNode._DOMElement;
 
--- a/browser/components/places/tests/browser/browser_views_liveupdate.js
+++ b/browser/components/places/tests/browser/browser_views_liveupdate.js
@@ -286,18 +286,18 @@ var bookmarksObserver = {
         let cellText = tree.view.getCellText(aElementOrTreeIndex,
                                              tree.columns.getColumnAt(0));
         if (!aNewValue)
           return cellText == PlacesUIUtils.getBestTitle(tree.view.nodeForTreeIndex(aElementOrTreeIndex));
         return cellText == aNewValue;
       }
       else {
         if (!aNewValue && aElementOrTreeIndex.localName != "toolbarbutton")
-          return aElementOrTreeIndex.label == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode);
-        return aElementOrTreeIndex.label == aNewValue;
+          return aElementOrTreeIndex.getAttribute("label") == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode);
+        return aElementOrTreeIndex.getAttribute("label") == aNewValue;
       }
     };
 
     for (var i = 0; i < views.length; i++) {
       var [node, index, valid] = searchItemInView(aItemId, views[i], validator);
       isnot(node, null, "Found changed Places node in " + views[i]);
       is(node.title, aNewValue, "Node has correct title: " + aNewValue);
       ok(valid, "Node element has correct label: " + aNewValue);
--- a/browser/components/privatebrowsing/src/nsPrivateBrowsingService.js
+++ b/browser/components/privatebrowsing/src/nsPrivateBrowsingService.js
@@ -464,18 +464,20 @@ PrivateBrowsingService.prototype = {
   },
 
   // nsICommandLineHandler
 
   handle: function PBS_handle(aCmdLine) {
     if (aCmdLine.handleFlag("private", false))
       ; // It has already been handled
     else if (aCmdLine.handleFlag("private-toggle", false)) {
+      if (this._autoStarted) {
+        throw Cr.NS_ERROR_ABORT;
+      }
       this.privateBrowsingEnabled = !this.privateBrowsingEnabled;
-      this._autoStarted = false;
       this._lastChangedByCommandLine = true;
     }
   },
 
   get helpInfo() {
     return "  -private           Enable private browsing mode.\n" +
            "  -private-toggle    Toggle private browsing mode.\n";
   },
--- a/browser/components/safebrowsing/content/report-phishing-overlay.xul
+++ b/browser/components/safebrowsing/content/report-phishing-overlay.xul
@@ -47,21 +47,21 @@
   <broadcasterset id="mainBroadcasterSet">
     <broadcaster id="reportPhishingBroadcaster" disabled="true"/>
     <broadcaster id="reportPhishingErrorBroadcaster" disabled="true"/>
   </broadcasterset>
   <menupopup id="menu_HelpPopup">
     <menuitem id="menu_HelpPopup_reportPhishingtoolmenu"
               label="&reportPhishSiteMenu.title2;"
               accesskey="&reportPhishSiteMenu.accesskey;"
-              insertbefore="updateSeparator"
+              insertbefore="aboutSeparator"
               observes="reportPhishingBroadcaster"
               oncommand="openUILink(safebrowsing.getReportURL('Phish'), event);"
               onclick="checkForMiddleClick(this, event);"/>
     <menuitem id="menu_HelpPopup_reportPhishingErrortoolmenu"
               label="&safeb.palm.notforgery.label2;"
               accesskey="&reportPhishSiteMenu.accesskey;"
-              insertbefore="updateSeparator"
+              insertbefore="aboutSeparator"
               observes="reportPhishingErrorBroadcaster"
               oncommand="openUILinkIn(safebrowsing.getReportURL('Error'), 'tab');"
               onclick="checkForMiddleClick(this, event);"/>
   </menupopup>
 </overlay>
--- a/browser/components/search/content/search.xml
+++ b/browser/components/search/content/search.xml
@@ -600,17 +600,17 @@
                  insertLocation.getAttribute("cmd") != "cmd_paste")
             insertLocation = insertLocation.nextSibling;
           if (insertLocation) {
             element = document.createElementNS(kXULNS, "menuitem");
             label = this._stringBundle.getString("cmd_pasteAndSearch");
             element.setAttribute("label", label);
             element.setAttribute("anonid", "paste-and-search");
             element.setAttribute("oncommand",
-                "BrowserSearch.searchBar.value = ''; goDoCommand('cmd_paste'); BrowserSearch.searchBar.handleSearchCommand();");
+                "BrowserSearch.searchBar.select(); goDoCommand('cmd_paste'); BrowserSearch.searchBar.handleSearchCommand();");
             cxmenu.insertBefore(element, insertLocation.nextSibling);
             pasteAndSearch = element;
           }
 
           element = document.createElementNS(kXULNS, "menuitem");
           label = this._stringBundle.getString("cmd_clearHistory");
           akey = this._stringBundle.getString("cmd_clearHistory_accesskey");
           element.setAttribute("label", label);
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -208,16 +208,17 @@
 @BINPATH@/components/necko_file.xpt
 @BINPATH@/components/necko_ftp.xpt
 @BINPATH@/components/necko_http.xpt
 @BINPATH@/components/necko_res.xpt
 @BINPATH@/components/necko_socket.xpt
 @BINPATH@/components/necko_strconv.xpt
 @BINPATH@/components/necko_viewsource.xpt
 @BINPATH@/components/necko_wifi.xpt
+@BINPATH@/components/necko_wyciwyg.xpt
 @BINPATH@/components/necko.xpt
 @BINPATH@/components/loginmgr.xpt
 @BINPATH@/components/parentalcontrols.xpt
 @BINPATH@/components/places.xpt
 @BINPATH@/components/plugin.xpt
 @BINPATH@/components/pref.xpt
 @BINPATH@/components/prefetch.xpt
 @BINPATH@/components/profile.xpt
--- a/browser/locales/all-locales
+++ b/browser/locales/all-locales
@@ -1,56 +1,61 @@
 af
 ak
 ar
 as
+ast
 be
 bg
 bn-BD
 bn-IN
 br
 bs
 ca
 cs
 cy
 da
 de
 el
 en-GB
 en-ZA
 eo
 es-AR
+es-CL
 es-ES
 es-MX
 et
 eu
 fa
 fi
 fr
 fy-NL
 ga-IE
+gd
 gl
 gu-IN
 he
 hi-IN
 hr
 hu
 hy-AM
 id
 is
 it
 ja
 ja-JP-mac
 ka
+km
 kn
 ko
 ku
 lg
 lt
 lv
+mai
 mk
 ml
 mn
 mr
 nb-NO
 nl
 nn-NO
 nso
@@ -66,15 +71,16 @@ ru
 si
 sk
 sl
 son
 sq
 sr
 sv-SE
 ta
+ta-LK
 te
 th
 tr
 uk
 vi
 zh-CN
 zh-TW
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -66,17 +66,17 @@ can reach it easily. -->
 <!ENTITY menubarCmd.label "Menu Bar">
 <!ENTITY menubarCmd.accesskey "M">
 <!ENTITY navbarCmd.label "Navigation Toolbar">
 <!ENTITY navbarCmd.accesskey "N">
 <!ENTITY personalbarCmd.label "Bookmarks Toolbar">
 <!ENTITY personalbarCmd.accesskey "B">
 <!ENTITY bookmarksToolbarItem.label "Bookmarks Toolbar Items">
 <!ENTITY addonBarCmd.label "Add-on Bar">
-<!ENTITY addonBarCmd.accesskey "B">
+<!ENTITY addonBarCmd.accesskey "A">
 
 <!ENTITY pageSourceCmd.label "Page Source">
 <!ENTITY pageSourceCmd.accesskey "o">
 <!ENTITY pageSourceCmd.commandkey "u">
 <!ENTITY pageInfoCmd.label "Page Info">
 <!ENTITY pageInfoCmd.accesskey "I">
 <!ENTITY pageInfoCmd.commandkey "i">
 <!ENTITY fullScreenCmd.label "Full Screen">
--- a/browser/locales/shipped-locales
+++ b/browser/locales/shipped-locales
@@ -12,41 +12,45 @@ de
 el
 en-GB
 en-US
 en-ZA
 eo
 es-AR
 es-ES
 et
+eu
 fi
 fr
 fy-NL
 ga-IE
+gd
 he
 hu
 hy-AM
 id
 is
 it
 ja linux win32
 ja-JP-mac osx
 ko
 ku
 lg
 lt
 lv
+mk
 nb-NO
 nl
 nn-NO
 nso
 pa-IN
 pl
 pt-BR
 pt-PT
+rm
 ro
 ru
 sk
 son
 sq
 sv-SE
 tr
 uk
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -228,17 +228,17 @@ menuitem.bookmark-item {
   list-style-image: url("moz-icon://stock/gtk-directory?size=menu");
 }
 
 .bookmark-item[query][hostContainer][open] {
   list-style-image: url("moz-icon://stock/gtk-directory?size=menu");
 }
 
 /* Stock icons for the menu bar items */
-menuitem:not([type]) {
+menuitem:not([type]):not(.menuitem-tooltip):not(.menuitem-iconic-tooltip) {
   -moz-binding: url("chrome://global/content/bindings/menu.xml#menuitem-iconic");
 }
 
 #placesContext_open\:newwindow,
 #menu_newNavigator,
 #context-openlink,
 #context-openframe {
   list-style-image: url("chrome://browser/skin/Toolbar-small.png");
@@ -467,16 +467,23 @@ menuitem:not([type]) {
   -moz-image-region: rect(0px 32px 16px 16px);
 }
 
 #bookmarksShowAll {
   list-style-image: url("chrome://browser/skin/Toolbar-small.png");
   -moz-image-region: rect(0px 48px 16px 32px);
 }
 
+#subscribeToPageMenuitem:not([disabled]),
+#subscribeToPageMenupopup,
+#BMB_subscribeToPageMenuitem:not([disabled]),
+#BMB_subscribeToPageMenupopup {
+  list-style-image: url("chrome://browser/skin/page-livemarks.png");
+}
+
 #bookmarksToolbarFolderMenu,
 #BMB_bookmarksToolbar {
   list-style-image: url("chrome://browser/skin/places/bookmarksToolbar.png");
 }
 
 #BMB_bookmarkThisPage {
   list-style-image: url("chrome://browser/skin/places/starPage.png");
 }
--- a/browser/themes/gnomestripe/browser/sanitizeDialog.css
+++ b/browser/themes/gnomestripe/browser/sanitizeDialog.css
@@ -31,17 +31,17 @@
 #sanitizeEverythingWarningBox {
   background-color: Window;
   border: 1px solid ThreeDDarkShadow;
   border-radius: 5px;
   padding: 16px;
 }
 
 #sanitizeEverythingWarningIcon {
-  list-style-image: url("chrome://global/skin/icons/warning-large.png");
+  list-style-image: url("moz-icon://stock/gtk-dialog-warning?size=dialog");
   padding: 0;
   margin: 0;
 }
 
 #sanitizeEverythingWarningDescBox {
   padding: 0 16px;
   margin: 0;
 }
--- a/browser/themes/gnomestripe/browser/syncCommon.css
+++ b/browser/themes/gnomestripe/browser/syncCommon.css
@@ -9,21 +9,21 @@
   max-width: 16px;
 }
 
 .statusIcon[status="active"] {
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
 }
 
 .statusIcon[status="error"] {
-  list-style-image: url("chrome://global/skin/icons/error-16.png");
+  list-style-image: url("moz-icon://stock/gtk-dialog-error?size=menu");
 }
 
 .statusIcon[status="success"] {
-  list-style-image: url("chrome://global/skin/icons/information-16.png");
+  list-style-image: url("moz-icon://stock/gtk-dialog-info?size=menu");
 }
 
 /* .data is only used by syncGenericChange.xul, but it seems unnecessary to have
    a separate stylesheet for it. */
 .data {
   font-size: 90%;
   font-weight: bold;
 }
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -1932,17 +1932,16 @@ toolbarbutton.chevron > .toolbarbutton-m
   -moz-appearance: none;
   background-color: #fffcd6;
   border: 1px solid #dad8b6;
   padding: 5px 5px 5px 5px;
   font-weight: bold;
 }
 
 #notification-popup {
-  color: #fff;
   margin-left: -16px;
   margin-right: -16px;
 }
 
 #notification-popup-box {
   margin: 0 3px;
 }
 
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -297,24 +297,16 @@
 #appmenu_privateBrowsing {
   list-style-image: url("chrome://browser/skin/Privacy-16.png");
 }
 
 #appmenu_addons {
   list-style-image: url("chrome://mozapps/skin/extensions/extensionGeneric-16.png");
 }
 
-#BMB_subscribeToPage:not([disabled]),
-#BMB_subscribeToPageMenu,
-#appmenu_subscribeToPage:not([disabled]),
-#appmenu_subscribeToPageMenu {
-  list-style-image: url("chrome://browser/skin/feeds/feed-icons-16.png");
-  -moz-image-region: rect(0px 16px 16px 0px);
-}
-
 #BMB_bookmarkThisPage,
 #appmenu_bookmarkThisPage {
   list-style-image: url("chrome://browser/skin/places/bookmark.png");
   -moz-image-region: rect(0 16px 16px 0);
 }
 
 /* ::::: titlebar ::::: */
 
@@ -1867,17 +1859,17 @@ toolbarbutton.bookmark-item[dragover="tr
   -moz-margin-end: 10px;
 }
 
 .popup-notification-icon[popupid="geolocation"] {
   list-style-image: url(chrome://browser/skin/Geolocation-64.png);
 }
 
 .geolocation-text-link {
-  padding-top: 5px;
+  margin-top: 17px;
 }
 
 .popup-notification-icon[popupid="xpinstall-disabled"],
 .popup-notification-icon[popupid="addon-install-blocked"],
 .popup-notification-icon[popupid="addon-install-failed"],
 .popup-notification-icon[popupid="addon-install-complete"] {
   list-style-image: url(chrome://mozapps/skin/extensions/extensionGeneric.png);
   width: 32px;
@@ -1931,16 +1923,25 @@ toolbarbutton.bookmark-item[dragover="tr
 }
 
 #download-monitor {
   list-style-image: url("chrome://browser/skin/Toolbar.png");
   -moz-image-region: rect(0, 108px, 18px, 90px);
 }
 
 /* Bookmarks roots menu-items */
+#appmenu_subscribeToPage:not([disabled]),
+#appmenu_subscribeToPageMenu,
+#subscribeToPageMenuitem:not([disabled]),
+#subscribeToPageMenupopup,
+#BMB_subscribeToPageMenuitem:not([disabled]),
+#BMB_subscribeToPageMenupopup {
+  list-style-image: url("chrome://browser/skin/feeds/feedIcon16.png");
+}
+
 #bookmarksToolbarFolderMenu,
 #appmenu_bookmarksToolbar,
 #BMB_bookmarksToolbar {
   list-style-image: url("chrome://browser/skin/places/bookmarksToolbar.png");
   -moz-image-region: auto;
 }
 
 #appmenu_unsortedBookmarks,
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -355,16 +355,17 @@ user_pref("javascript.options.jitprofili
 user_pref("gfx.color_management.force_srgb", true);
 user_pref("network.manage-offline-status", false);
 user_pref("test.mousescroll", true);
 user_pref("security.default_personal_cert", "Select Automatically"); // Need to client auth test be w/o any dialogs
 user_pref("network.http.prompt-temp-redirect", false);
 user_pref("media.cache_size", 100);
 user_pref("security.warn_viewing_mixed", false);
 user_pref("app.update.enabled", false);
+user_pref("browser.panorama.experienced_first_run", true); // Assume experienced
 
 // Only load extensions from the application and user profile
 // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
 user_pref("extensions.enabledScopes", 5);
 // Disable metadata caching for installed add-ons by default
 user_pref("extensions.getAddons.cache.enabled", false);
 
 user_pref("extensions.testpilot.runStudies", false);
--- a/build/mobile/sutagent/android/AndroidManifest.xml
+++ b/build/mobile/sutagent/android/AndroidManifest.xml
@@ -60,9 +60,12 @@
 
 <uses-permission android:name="android.permission.VIBRATE"></uses-permission>
 
 
 
 <uses-permission android:name="android.permission.SET_TIME"></uses-permission>
 
 
+
+<uses-permission android:name="android.permission.SET_TIME_ZONE"></uses-permission>
+
 </manifest> 
\ No newline at end of file
--- a/build/mobile/sutagent/android/DoCommand.java
+++ b/build/mobile/sutagent/android/DoCommand.java
@@ -46,27 +46,31 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.PrintWriter;
+import java.lang.reflect.Field;
 import java.net.Socket;
 import java.net.SocketException;
 import java.net.UnknownHostException;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Calendar;
+import java.util.Collections;
 import java.util.Date;
 import java.util.GregorianCalendar;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.TimeZone;
 import java.util.Timer;
 import java.util.zip.Adler32;
 import java.util.zip.CheckedInputStream;
 import java.util.zip.CheckedOutputStream;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 import java.util.zip.ZipInputStream;
@@ -82,30 +86,33 @@ import org.apache.http.client.ClientProt
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.impl.client.DefaultHttpClient;
 
 import com.mozilla.SUTAgentAndroid.SUTAgentAndroid;
 
 import android.app.Activity;
 import android.app.ActivityManager;
+import android.app.AlarmManager;
 import android.content.ActivityNotFoundException;
 import android.content.Context;
 import android.content.ContextWrapper;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.res.Configuration;
 import android.net.Uri;
 import android.os.Build;
 import android.os.Debug;
 import android.os.Environment;
 import android.os.StatFs;
 import android.os.SystemClock;
+import android.provider.Settings;
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.WindowManager;
 
 public class DoCommand {
 	
 	String lineSep = System.getProperty("line.separator");
 	Process	pProc;
@@ -113,23 +120,23 @@ public class DoCommand {
 	InputStream	sutErr;
 	InputStream	sutOut;
 	AlertLooperThread alrt = null;
 	ContextWrapper	contextWrapper = null;
 	
 	String	currentDir = "/";
 	String	sErrorPrefix = "##AGENT-WARNING## ";
 	
-	private final String prgVersion = "SUTAgentAndroid Version 0.85";
+	private final String prgVersion = "SUTAgentAndroid Version 0.87";
 	
 	public enum Command
 		{
 		RUN ("run"),
 		EXEC ("exec"),
-		ARUN ("arun"),
+		ENVRUN ("envrun"),
 		KILL ("kill"),
 		PS ("ps"),
 		DEVINFO ("info"),
 		OS ("os"),
 		ID ("id"),
 		UPTIME ("uptime"),
 		SETTIME ("settime"),
 		SYSTIME ("systime"),
@@ -168,16 +175,18 @@ public class DoCommand {
 		HELP ("help"),
 		FTPG ("ftpg"),
 		FTPP ("ftpp"),
 		INST ("inst"),
 		UPDT ("updt"),
 		UNINST ("uninst"),
 		TEST ("test"),
 		VER ("ver"),
+		TZGET ("tzget"),
+		TZSET ("tzset"),
 		UNKNOWN ("unknown");
 		
 		private final String theCmd;
 		
 		Command(String theCmd) { this.theCmd = theCmd; }
 
 		public String theCmd() {return theCmd;}
 		
@@ -202,32 +211,43 @@ public class DoCommand {
 		}
 	
 	public String processCommand(String theCmdLine, PrintWriter out, BufferedInputStream in, OutputStream cmdOut)
 		{
 		String 	strReturn = "";
 		Command	cCmd = null;
 		Command cSubCmd = null;
 		
-		String [] Argv = parseCmdLine(theCmdLine);
+		String [] Argv = parseCmdLine2(theCmdLine);
 		
 		int Argc = Argv.length;
 		
 		cCmd = Command.getCmd(Argv[0]);
 		
 		switch(cCmd)
 			{
 			case VER:
 				strReturn = prgVersion;
 				break;
 				
 			case CLOK:
 				strReturn = GetClok();
 				break;
 				
+			case TZGET:
+				strReturn = GetTimeZone();
+				break;
+				
+			case TZSET:
+				if (Argc == 2)
+					strReturn = SetTimeZone(Argv[1]);
+				else
+					strReturn = sErrorPrefix + "Wrong number of arguments for settz command!";
+				break;
+				
 			case UPDT:
 				strReturn = StartUpdateOMatic(Argv[1], Argv[2]);
 				break;
 			
 			case SETTIME:
 				strReturn = SetSystemTime(Argv[1], Argv[2], cmdOut);
 				break;
 			
@@ -322,26 +342,16 @@ public class DoCommand {
 					}
 				else
 					{
 					strReturn = sErrorPrefix + "Wrong number of arguments for alrt command!";
 					}
 				break;
 				
 			case REBT:
-//				try {
-//					reboot(null);
-//					Power.reboot(null);
-//					Power.shutdown();
-//					}
-//				catch (IOException e)
-//					{
-					// TODO Auto-generated catch block
-//					e.printStackTrace();
-//					}
 				RunReboot(cmdOut);
 				break;
 				
 			case TMPD:
 				strReturn = GetTmpDir();
 				break;
 				
 			case DEVINFO:
@@ -493,16 +503,35 @@ public class DoCommand {
 			case QUIT:
 			case EXIT:
 				strReturn = Argv[0];
 				break;
 				
 			case TEST:
 //				boolean bRet = false;
 /*				
+				Configuration userConfig = new Configuration();
+				Settings.System.getConfiguration( contextWrapper.getContentResolver(), userConfig );
+				Calendar cal = Calendar.getInstance( userConfig.locale);
+				TimeZone ctz = cal.getTimeZone();
+				String sctzLongName = ctz.getDisplayName();
+				String pstzName = TimeZone.getDefault().getDisplayName();
+*/
+				String sTimeZoneName = GetTimeZone();
+				
+				TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
+				TimeZone tz2 = TimeZone.getTimeZone("GMT-08:00");
+				int	nOffset = (-8 * 3600000);
+				String [] zoneNames = TimeZone.getAvailableIDs(nOffset);
+				int nNumMatches = zoneNames.length;
+				TimeZone.setDefault(tz);
+				
+				String sOldTZ = System.setProperty("persist.sys.timezone", "America/Los_Angeles");
+				
+/*				
 				byte[] buffer = new byte [4096];
 				int	nRead = 0;
 				long lTotalRead = 0;
 
 				Context ctx = SUTAgentAndroid.me.getApplicationContext();
 
 				FTPClient ftp = new FTPClient();
 				try 
@@ -586,17 +615,17 @@ public class DoCommand {
 				catch (IOException e)
 					{
 					// TODO Auto-generated catch block
 					strReturn = e.getMessage();
 					e.printStackTrace();
 					}
 */				
 //				strReturn = InstallApplication();
-				strReturn = InstallApp(Argv[1], cmdOut);
+//				strReturn = InstallApp(Argv[1], cmdOut);
 				
 //				strReturn = UninstallApplication();
 //				String sPingCheck = SendPing("www.mozilla.org",null);
 //				if (sPingCheck.contains("3 received"))
 //					strReturn = sPingCheck;
 //				RunReboot(cmdOut);
 /*
 				try 
@@ -648,16 +677,34 @@ public class DoCommand {
 				catch (IOException e) 
 					{
 					// TODO Auto-generated catch block
 					e.printStackTrace();
 					}
 */
 				break;
 				
+			case ENVRUN:
+				if (Argc >= 2)
+					{
+					String [] theArgs = new String [Argc - 1];
+			
+					for (int lcv = 1; lcv < Argc; lcv++)
+						{
+						theArgs[lcv - 1] = Argv[lcv];
+						}
+			
+					strReturn = StartPrg2(theArgs, cmdOut);
+					}
+				else
+					{
+					strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
+					}
+				break;
+				
 			case EXEC:
 			case RUN:
 				if (Argc >= 2)
 					{
 					String [] theArgs = new String [Argc - 1];
 				
 					for (int lcv = 1; lcv < Argc; lcv++)
 						{
@@ -823,32 +870,175 @@ public class DoCommand {
 				}
 			// Kill the thread
 			alrt.quit();
 			alrt = null;
 			System.gc();
 			}
 		}
 
-	public String [] parseCmdLine(String theCmdLine) {
+	public String [] parseCmdLine2(String theCmdLine)
+		{
+		String	cmdString;
 		String	workingString;
 		String	workingString2;
+		String	workingString3;
 		List<String> lst = new ArrayList<String>();
-		int nLength = theCmdLine.length();
-		int nFirstSpace = theCmdLine.indexOf(' ');
+		int nLength = 0;
+		int nFirstSpace = -1;
+		
+		// Null cmd line
+		if (theCmdLine == null)
+			{
+			String [] theArgs = new String [1];
+			theArgs[0] = new String("");
+			return(theArgs);
+			}
+		else
+			{
+			nLength = theCmdLine.length();
+			nFirstSpace = theCmdLine.indexOf(' ');
+			}
 		
 		if (nFirstSpace == -1)
 			{
 			String [] theArgs = new String [1];
 			theArgs[0] = new String(theCmdLine);
 			return(theArgs);
 			}
 		
 		// Get the command
-		lst.add(new String(theCmdLine.substring(0, nFirstSpace)));
+		cmdString = new String(theCmdLine.substring(0, nFirstSpace)); 
+		lst.add(cmdString);
+		
+		// Jump past the command and trim
+		workingString = (theCmdLine.substring(nFirstSpace + 1, nLength)).trim();
+		
+		while ((nLength = workingString.length()) > 0)
+			{
+			int nEnd = 0;
+			int	nStart = 0;
+			
+			// if we have a quote
+			if (workingString.startsWith("\""))
+				{
+				// point to the first non quote char
+				nStart = 1;
+				// find the matching quote
+				nEnd = workingString.indexOf('"', nStart);
+				
+				char prevChar;
+				
+				while(nEnd != -1)
+					{
+					// check to see if the quotation mark has been escaped
+					prevChar = workingString.charAt(nEnd - 1);
+					if (prevChar == '\\')
+						{
+						// if escaped, point past this quotation mark and find the next
+						nEnd++;
+						if (nEnd < nLength)
+							nEnd = workingString.indexOf('"', nEnd);
+						else
+							nEnd = -1;
+						}
+					else
+						break;
+					}
+				
+				// there isn't one
+				if (nEnd == -1)
+					{
+					// point at the quote
+					nStart = 0;
+					// so find the next space
+					nEnd = workingString.indexOf(' ', nStart);
+					// there isn't one of those either
+					if (nEnd == -1)
+						nEnd = nLength;	// Just grab the rest of the cmdline
+					}
+				}
+			else // no quote so find the next space
+				{
+				nEnd = workingString.indexOf(' ', nStart);
+				// there isn't one of those
+				if (nEnd == -1)
+					nEnd = nLength;	// Just grab the rest of the cmdline
+				}
+			
+			// get the substring
+			workingString2 = workingString.substring(nStart, nEnd);
+
+			// if we have escaped quotes
+			if (workingString2.contains("\\\""))
+				{
+				do
+					{
+					// replace escaped quote with embedded quote
+					workingString3 = workingString2.replace("\\\"", "\"");
+					workingString2 = workingString3;
+					}
+				while(workingString2.contains("\\\""));
+				}
+
+			// add it to the list
+			lst.add(new String(workingString2));
+			
+			// if we are dealing with a quote
+			if (nStart > 0)
+				nEnd++; //  point past the end one
+			
+			// jump past the substring and trim it
+			workingString = (workingString.substring(nEnd)).trim();
+			}
+		
+		// ok we're done package up the results
+		int nItems = lst.size();
+		
+		String [] theArgs = new String [nItems];
+		
+		for (int lcv = 0; lcv < nItems; lcv++)
+			{
+			theArgs[lcv] = lst.get(lcv);
+			}
+	
+		return(theArgs);
+		}
+	
+	public String [] parseCmdLine(String theCmdLine) {
+		String	cmdString;
+		String	workingString;
+		String	workingString2;
+		List<String> lst = new ArrayList<String>();
+		int nLength = 0;
+		int nFirstSpace = -1;
+		
+		// Null cmd line
+		if (theCmdLine == null)
+			{
+			String [] theArgs = new String [1];
+			theArgs[0] = new String("");
+			return(theArgs);
+			}
+		else
+			{
+			nLength = theCmdLine.length();
+			nFirstSpace = theCmdLine.indexOf(' ');
+			}
+		
+		if (nFirstSpace == -1)
+			{
+			String [] theArgs = new String [1];
+			theArgs[0] = new String(theCmdLine);
+			return(theArgs);
+			}
+		
+		// Get the command
+		cmdString = new String(theCmdLine.substring(0, nFirstSpace)); 
+		lst.add(cmdString);
 		
 		// Jump past the command and trim
 		workingString = (theCmdLine.substring(nFirstSpace + 1, nLength)).trim();
 		
 		while ((nLength = workingString.length()) > 0)
 			{
 			int nEnd = 0;
 			int	nStart = 0;
@@ -866,34 +1056,39 @@ public class DoCommand {
 					// point at the quote
 					nStart = 0;
 					// so find the next space
 					nEnd = workingString.indexOf(' ', nStart);
 					// there isn't one of those either
 					if (nEnd == -1)
 						nEnd = nLength;	// Just grab the rest of the cmdline
 					}
+				else
+					{
+					nStart = 0;
+					nEnd++;
+					}
 				}
 			else // no quote so find the next space
 				{
 				nEnd = workingString.indexOf(' ', nStart);
 				// there isn't one of those
 				if (nEnd == -1)
 					nEnd = nLength;	// Just grab the rest of the cmdline
 				}
 			
 			// get the substring
 			workingString2 = workingString.substring(nStart, nEnd);
 			
 			// add it to the list
 			lst.add(new String(workingString2));
 			
 			// if we are dealing with a quote
-			if (nStart > 0)
-				nEnd++; //  point past the end one
+//			if (nStart > 0)
+//				nEnd++; //  point past the end one
 			
 			// jump past the substring and trim it
 			workingString = (workingString.substring(nEnd)).trim();
 			}
 		
 		int nItems = lst.size();
 		
 		String [] theArgs = new String [nItems];
@@ -1111,17 +1306,16 @@ public class DoCommand {
 			}
 		
 		return(sRet);
 		}
 	
 	public String StatProcess(String string)
 		{
 		String sRet = "";
-//		ActivityManager aMgr = (ActivityManager) SUTAgentAndroid.me.getSystemService(Activity.ACTIVITY_SERVICE);
 		ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
 		int	[] nPids = new int [1];
 		
 		nPids[0] = Integer.parseInt(string);
 		
 		android.os.Debug.MemoryInfo[] mi = aMgr.getProcessMemoryInfo(nPids);
 		
 		sRet  = "Dalvik Private Dirty pages         " + mi[0].dalvikPrivateDirty     + " kb\n";
@@ -1155,17 +1349,16 @@ public class DoCommand {
 			}
 		
 		return(sRet);
 		}
 	
 	public String GetAppRoot(String AppName)
 		{
 		String sRet = "";
-//		Context ctx = SUTAgentAndroid.me.getApplicationContext();
 		Context ctx = contextWrapper.getApplicationContext();
 		
 		if (ctx != null)
 			{
 			try {
 				Context appCtx = ctx.createPackageContext(AppName, 0);
 				ContextWrapper appCtxW = new ContextWrapper(appCtx);
 				sRet = appCtxW.getPackageResourcePath();
@@ -1229,18 +1422,18 @@ public class DoCommand {
 		byte[] 			buffer 		= new byte [4096];
 		int				nRead 		= 0;
 		long 			lTotalRead 	= 0;
 		MessageDigest	digest 		= null;
 		
 		try {
 			digest = java.security.MessageDigest.getInstance("MD5");
 			}
-		catch (NoSuchAlgorithmException e) {
-			// TODO Auto-generated catch block
+		catch (NoSuchAlgorithmException e)
+			{
 			e.printStackTrace();
 			}
 		
 		try {
 			FileInputStream srcFile  = new FileInputStream(sTmpFileName);
 			while((nRead = srcFile.read(buffer)) != -1)
 				{
 				digest.update(buffer, 0, nRead);
@@ -1415,22 +1608,20 @@ public class DoCommand {
 
 			if (lTotalWritten == lTotalRead)
 				sRet = sTmpSrcFileName + " copied to " + sTmpDstFileName;
 			else
 				sRet = sErrorPrefix + "Failed to copy " + sTmpSrcFileName + " [length = " + lTotalWritten + "] to " + sTmpDstFileName + " [length = " + lTotalRead + "]";
 			}
 		catch (FileNotFoundException e)
 			{
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 			} 
 		catch (IOException e)
 			{
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 			}
 
 		return (sRet);
 		}
 	
 	public String IsDirWritable(String sDir)
 		{
@@ -1529,22 +1720,16 @@ public class DoCommand {
 							strRet = "\r" + lTotalRead + " of " + lFtpSize + " bytes received " + ((lTotalRead * 100) / lFtpSize) + "% completed";
 							out.write(strRet.getBytes());
 							out.flush();
 							}
 						ftpIn.close();
 						@SuppressWarnings("unused")
 						boolean bRet = ftp.completePendingCommand();
 						outStream.flush();
-				    	/*				    	
-				    	if (ftp.retrieveFile("pub/mozilla.org/firefox/releases/3.6b4/wince-arm/en-US/firefox-3.6b4.cab", outStream))
-				    		{
-				    		outStream.flush();
-				    		}
-				    	 */				    		
 			    		outStream.close();
 						strRet = ftp.getReplyString();
 						reply = ftp.getReplyCode();
 				    	}
 					strRet = ftp.getReplyString();
 					reply = ftp.getReplyCode();
 				    ftp.logout();
 				    ftp.disconnect();
@@ -1559,26 +1744,24 @@ public class DoCommand {
 		    else
 		    	{
 		        ftp.disconnect();
 		        System.err.println("FTP server refused connection.");
 		        }
 			}
 		catch (SocketException e)
 			{
-			// TODO Auto-generated catch block
 			sRet = e.getMessage();
 			strRet = ftp.getReplyString();
 			reply = ftp.getReplyCode();
 			sRet += "\n" + strRet;
 			e.printStackTrace();
 			}
 		catch (IOException e)
 			{
-			// TODO Auto-generated catch block
 			sRet = e.getMessage();
 			strRet = ftp.getReplyString();
 			reply = ftp.getReplyCode();
 			sRet += "\n" + strRet;
 			e.printStackTrace();
 			}
 		return (sRet);
 	}
@@ -1647,26 +1830,24 @@ public class DoCommand {
 		{
 		String [] theArgs = new String [3];
 		
 		theArgs[0] = "su";
 		theArgs[1] = "-c";
 		theArgs[2] = "kill";
 
 		String sRet = sErrorPrefix + "Unable to kill " + sProcName + "\n";
-//		ActivityManager aMgr = (ActivityManager) SUTAgentAndroid.me.getSystemService(Activity.ACTIVITY_SERVICE);
 		ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
 		List <ActivityManager.RunningAppProcessInfo> lProcesses = aMgr.getRunningAppProcesses();
 		int lcv = 0;
 		String strProcName = "";
 		int	nPID = 0;
 		
 		for (lcv = 0; lcv < lProcesses.size(); lcv++)
 			{
-//			if (lProcesses.get(lcv).processName.contentEquals(sProcName))
 			if (lProcesses.get(lcv).processName.contains(sProcName))
 				{
 				strProcName = lProcesses.get(lcv).processName;
 				nPID = lProcesses.get(lcv).pid;
 				sRet = sErrorPrefix + "Failed to kill " + nPID + " " + strProcName + "\n";
 
 				theArgs[2] += " " + nPID;
 				
@@ -1679,85 +1860,74 @@ public class DoCommand {
 					}
 				catch (IOException e) 
 					{
 					sRet = e.getMessage();
 					e.printStackTrace();
 					} 
 				catch (InterruptedException e)
 					{
-					// TODO Auto-generated catch block
 					e.printStackTrace();
 					}
 
-//				SUTAgentAndroid.me.finishActivity(SUTAgentAndroid.START_PRG);
-
 				// Give the messages a chance to be processed
 				try {
 					Thread.sleep(2000);
 					}
 				catch (InterruptedException e)
 					{
 					e.printStackTrace();
 					}
-//				aMgr.restartPackage(strProcName);
 				break;
 				}
 			}
 		
 		if (nPID > 0)
 			{
 			sRet = "Successfully killed " + nPID + " " + strProcName + "\n";
 			lProcesses = aMgr.getRunningAppProcesses();
 			for (lcv = 0; lcv < lProcesses.size(); lcv++)
 				{
-//				if (lProcesses.get(lcv).processName.contentEquals(sProcName))
 				if (lProcesses.get(lcv).processName.contains(sProcName))
 					{
 					sRet = sErrorPrefix + "Unable to kill " + nPID + " " + strProcName + "\n";
 					break;
 					}
 				}
 			}
 		
 		return (sRet);
 		}
 
 	public boolean IsProcessDead(String sProcName)
 		{
 		boolean bRet = false;
-//		ActivityManager aMgr = (ActivityManager) SUTAgentAndroid.me.getSystemService(Activity.ACTIVITY_SERVICE);
 		ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
 		List <ActivityManager.ProcessErrorStateInfo> lProcesses = aMgr.getProcessesInErrorState();
 		int lcv = 0;
-//		String strProcName = "";
-//		int	nPID = 0;
 		
 		if (lProcesses != null)
 			{
 			for (lcv = 0; lcv < lProcesses.size(); lcv++)
 				{
 				if (lProcesses.get(lcv).processName.contentEquals(sProcName) && 
 					lProcesses.get(lcv).condition != ActivityManager.ProcessErrorStateInfo.NO_ERROR)
 					{
-//					strProcName = lProcesses.get(lcv).processName;
-//					nPID = lProcesses.get(lcv).pid;
 					bRet = true;
 					break;
 					}
 				}
 			}
 	
 		return (bRet);
 		}
 
 	public String GetProcessInfo()
 		{
 		String sRet = "";
-//		ActivityManager aMgr = (ActivityManager) SUTAgentAndroid.me.getSystemService(Activity.ACTIVITY_SERVICE);
 		ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
 		List <ActivityManager.RunningAppProcessInfo> lProcesses = aMgr.getRunningAppProcesses();
 		int	nProcs = lProcesses.size();
 		int lcv = 0;
 		String strProcName = "";
 		int	nPID = 0;
 		int nUser = 0;
 		
@@ -1812,22 +1982,20 @@ public class DoCommand {
 	public String GetMemoryInfo()
 		{
 		String sRet = "PA:" + GetMemoryConfig();
 		return (sRet);
 		}
 
 	public long GetMemoryConfig()
 		{
-//		ActivityManager aMgr = (ActivityManager) SUTAgentAndroid.me.getSystemService(Activity.ACTIVITY_SERVICE);
 		ActivityManager aMgr = (ActivityManager) contextWrapper.getSystemService(Activity.ACTIVITY_SERVICE);
 		ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
 		aMgr.getMemoryInfo(outInfo);
 		long lMem = outInfo.availMem;
-//		float fMem = (float) lMem / (float)(1024.0 * 1024.0);
 
 		return (lMem);
 		}
 	
 	public String RegisterTheDevice(String sSrvr, String sPort, String sData)
 		{
 		String sRet = "";
 		String line = "";
@@ -1861,22 +2029,20 @@ public class DoCommand {
 				socket.close();
 				}
 			catch(NumberFormatException e)
 				{
 				e.printStackTrace();
 				} 
 			catch (UnknownHostException e)
 				{
-				// TODO Auto-generated catch block
 				e.printStackTrace();
 				}
 			catch (IOException e)
 				{
-				// TODO Auto-generated catch block
 				sRet += "reg exception thrown";
 				e.printStackTrace();
 				}
 			}
 		return(sRet);
 		}
 	
 	public String GetInternetData(String sHost, String sPort, String sURL)
@@ -1906,79 +2072,118 @@ public class DoCommand {
 			    byte [] data = new byte [2048];
 			    int nRead = content.read(data);
 			    sRet = new String(data, 0, nRead);
 			    content.close(); // this will also close the connection
 				}
 			}
 		catch (IllegalArgumentException e)
 			{
-			// TODO Auto-generated catch block
 			sRet = e.getLocalizedMessage();
 			e.printStackTrace();
 			}
 		catch (ClientProtocolException e)
 			{
-			// TODO Auto-generated catch block
 			sRet = e.getLocalizedMessage();
 			e.printStackTrace();
 			}
 		catch (IOException e)
 			{
-			// TODO Auto-generated catch block
 			sRet = e.getLocalizedMessage();
 			e.printStackTrace();
 			}
 		
 		return(sRet);
 		}
+	
+	public String GetTimeZone()
+		{
+		String	sRet = "";
+		TimeZone tz;
+		
+		tz = TimeZone.getDefault();
+		Date now = new Date();
+		sRet = tz.getDisplayName(tz.inDaylightTime(now), TimeZone.LONG);
+		
+		return(sRet);
+		}
+	
+	public String SetTimeZone(String sTimeZone)
+		{
+		String			sRet = "Unable to set timezone to " + sTimeZone;
+		TimeZone 		tz = null;
+		AlarmManager 	amgr = null;
+		
+		if ((sTimeZone.length() > 0) && (sTimeZone.startsWith("GMT")))
+			{
+			amgr = (AlarmManager) contextWrapper.getSystemService(Context.ALARM_SERVICE);
+			if (amgr != null)
+				amgr.setTimeZone(sTimeZone);
+			}
+		else
+			{
+			String [] zoneNames = TimeZone.getAvailableIDs();
+			int nNumMatches = zoneNames.length;
+			int	lcv = 0;
+			
+			for (lcv = 0; lcv < nNumMatches; lcv++)
+				{
+				if (zoneNames[lcv].equalsIgnoreCase(sTimeZone))
+					break;
+				}
+
+			if (lcv < nNumMatches)
+				{
+				amgr = (AlarmManager) contextWrapper.getSystemService(Context.ALARM_SERVICE);
+				if (amgr != null)
+					amgr.setTimeZone(zoneNames[lcv]);
+				}
+			}
+		
+		if (amgr != null)
+			{
+			tz = TimeZone.getDefault();
+			Date now = new Date();
+			sRet = tz.getDisplayName(tz.inDaylightTime(now), TimeZone.LONG);
+			}
+		
+		return(sRet);
+		}
 
 	public String GetSystemTime()
 		{
 		String sRet = "";
 		Calendar cal = Calendar.getInstance();
 		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss:SSS");
 		sRet = sdf.format(cal.getTime());
 	
 		return (sRet);
 		}
 	
 	public String SetSystemTime(String sDate, String sTime, OutputStream out)
 		{
-//		Debug.waitForDebugger();
 		String sRet = "";
 		
-//		Intent	prgIntent = new Intent(android.provider.Settings.ACTION_DATE_SETTINGS);
-//		prgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-//		contextWrapper.startActivity(prgIntent);
-		
-		// 2010/09/22 
-		// 15:41:00
-		// 0123456789012345678
-		
 		if (((sDate != null) && (sTime != null)) && 
 			(sDate.contains("/") || sDate.contains(".")) &&
 			(sTime.contains(":")))
 			{
 			int year = Integer.parseInt(sDate.substring(0,4));
 			int month = Integer.parseInt(sDate.substring(5,7));
 			int day = Integer.parseInt(sDate.substring(8,10));
 			
 			int hour = Integer.parseInt(sTime.substring(0,2));
 			int mins = Integer.parseInt(sTime.substring(3,5));
 			int secs = Integer.parseInt(sTime.substring(6,8));
 
-			Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+			Calendar cal = new GregorianCalendar(TimeZone.getDefault());
 			cal.set(year, month - 1, day, hour, mins, secs);
 			long lMillisecs = cal.getTime().getTime();
 			
-//			boolean bRet = SystemClock.setCurrentTimeMillis(lMillisecs);
 			String sM = Long.toString(lMillisecs);
-//			long lm = 1285175618316L;
-			String sTest = cal.getTime().toGMTString();
 			String sMillis = sM.substring(0, sM.length() - 3) + "." + sM.substring(sM.length() - 3);
 			String [] theArgs = new String [3];
 		
 			theArgs[0] = "su";
 			theArgs[1] = "-c";
 			theArgs[2] = "date -u " + sMillis;
 		
 			try 
@@ -1991,17 +2196,16 @@ public class DoCommand {
 				}
 			catch (IOException e) 
 				{
 				sRet = e.getMessage();
 				e.printStackTrace();
 				} 
 			catch (InterruptedException e)
 				{
-				// TODO Auto-generated catch block
 				e.printStackTrace();
 				}
 			}
 		else
 			{
 			sRet = "Invalid argument(s)";
 			}
 
@@ -2040,34 +2244,16 @@ public class DoCommand {
 			lHold %= 60L * 1000L;
 			nSecs = (int)(lHold / 1000L);
 			nMilliseconds = (int)(lHold % 1000);
 			sRet = "" + nDays + " days " + nHours + " hours " + nMinutes + " minutes " + nSecs + " seconds " + nMilliseconds + " ms";
 			}
 
 		return (sRet);
 		}
-/*	
-	private boolean IsProcRunning(Process pProc)
-		{
-		boolean bRet = false;
-		int nExitCode = 0;
-		
-		try
-			{
-			nExitCode = pProc.exitValue();
-			}
-		catch (IllegalThreadStateException z)
-			{	
-			bRet = true;
-			}
-
-		return(bRet);
-		}
-*/
 
 	public String NewKillProc(String sProcId, OutputStream out)
 		{
 		String sRet = "";
 		String [] theArgs = new String [3];
 		
 		theArgs[0] = "su";
 		theArgs[1] = "-c";
@@ -2102,43 +2288,38 @@ public class DoCommand {
 		theArgs[0] = "ping";
 		theArgs[1] = "-c";
 		theArgs[2] = "3";
 		theArgs[3] = sIPAddr;
 		
 		try 
 			{
 			pProc = Runtime.getRuntime().exec(theArgs);
-//			sutErr = pProc.getErrorStream(); // Stderr
-//			sutIn = pProc.getOutputStream(); // Stdin
-//			sutOut = pProc.getInputStream(); // Stdout
 			RedirOutputThread outThrd = new RedirOutputThread(pProc, out);
 			outThrd.start();
 			outThrd.join(5000);
 			if (out == null)
 				sRet = outThrd.strOutput;
 			}
 		catch (IOException e) 
 			{
 			sRet = e.getMessage();
 			e.printStackTrace();
 			} 
 		catch (InterruptedException e)
 			{
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 			}
 	
 		return (sRet);
 		}
 	
 	public String GetTmpDir()
 	{
 		String 	sRet = "";
-//		Context ctx = SUTAgentAndroid.me.getApplicationContext();
 		Context ctx = contextWrapper.getApplicationContext();
         File dir = ctx.getFilesDir();
         ctx = null;
         try {
 			sRet = dir.getCanonicalPath();
 			} 
         catch (IOException e)
         	{
@@ -2240,17 +2421,16 @@ public class DoCommand {
 			}
 		catch (IOException e) 
 			{
 			sRet = e.getMessage();
 			e.printStackTrace();
 			} 
 		catch (InterruptedException e)
 			{
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 			}
 
 		return (sRet);
 		}
 	
 	public String UnInstallApp(String sApp, OutputStream out)
 		{
@@ -2264,17 +2444,16 @@ public class DoCommand {
 		try 
 			{
 			pProc = Runtime.getRuntime().exec(theArgs);
 		
 			RedirOutputThread outThrd = new RedirOutputThread(pProc, out);
 			outThrd.start();
 			outThrd.join(60000);
 			int nRet = pProc.exitValue();
-//			boolean bRet = outThrd.isAlive();
 			sRet = "\nuninst complete [" + nRet + "]";
 			}
 		catch (IOException e) 
 			{
 			sRet = e.getMessage();
 			e.printStackTrace();
 			} 
 		catch (InterruptedException e)
@@ -2398,17 +2577,16 @@ public class DoCommand {
 
 		return (sRet);
 		}
 
 	public String StartUpdateOMatic(String sPkgName, String sPkgFileName)
 		{
 		String sRet = "";
 	
-//		Context ctx = SUTAgentAndroid.me.getApplicationContext();
 		Context ctx = contextWrapper.getApplicationContext();
 		PackageManager pm = ctx.getPackageManager();
 
 		Intent prgIntent = new Intent();
 		prgIntent.setPackage("com.mozilla.UpdateOMatic");
 		prgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 
 		try {
@@ -2430,40 +2608,34 @@ public class DoCommand {
 			}
 		
 		prgIntent.putExtra("pkgName", sPkgName);
 		prgIntent.putExtra("pkgFileName", sPkgFileName);
 
 		try 
 			{
 			contextWrapper.startActivity(prgIntent);
-//			Thread.sleep(5000);
 			sRet = "exit";
 			}
 		catch(ActivityNotFoundException anf)
 			{
 			anf.printStackTrace();
 			} 
-//		catch (InterruptedException e)
-//			{
-//			e.printStackTrace();
-//			}
 	
 		ctx = null;
 		return (sRet);
 		}
 
 	public String StartJavaPrg(String [] sArgs)
 		{
 		String sRet = "";
 		String sArgList = "";
 		String sUrl = "";
 		String sRedirFileName = "";
 		
-//		Context ctx = SUTAgentAndroid.me.getApplicationContext();
 		Context ctx = contextWrapper.getApplicationContext();
 		PackageManager pm = ctx.getPackageManager();
 
 		Intent prgIntent = new Intent();
 		prgIntent.setPackage(sArgs[0]);
 		prgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 
 		try {
@@ -2481,17 +2653,17 @@ public class DoCommand {
 			}
 		catch (NameNotFoundException e)
 			{
 			e.printStackTrace();
 			}
 		
 		if (sArgs.length > 1)
 			{
-			if (sArgs[0].contains("android.browser"))
+//			if (sArgs[0].contains("android.browser"))
 				prgIntent.setAction(Intent.ACTION_VIEW);
 			
 			if (sArgs[0].contains("fennec"))
 				{
 				sArgList = "";
 				sUrl = "";
 				
 				for (int lcv = 1; lcv < sArgs.length; lcv++)
@@ -2525,20 +2697,17 @@ public class DoCommand {
 				prgIntent.setData(Uri.parse(sArgList.trim()));
 				}
 			}
 		else
 			prgIntent.setData(Uri.parse("about:blank"));
 
 		try 
 			{
-//			ctx.startActivity(prgIntent);
 			contextWrapper.startActivity(prgIntent);
-//			SUTAgentAndroid.me.startActivity(prgIntent);
-//			SUTAgentAndroid.me.startActivityForResult(prgIntent, SUTAgentAndroid.START_PRG);
 			}
 		catch(ActivityNotFoundException anf)
 			{
 			anf.printStackTrace();
 			}
 		
 		ctx = null;
 		return (sRet);
@@ -2546,31 +2715,169 @@ public class DoCommand {
 
 	public String StartPrg(String [] progArray, OutputStream out)
 		{
 		String sRet = "";
 		
 		try 
 			{
 			pProc = Runtime.getRuntime().exec(progArray);
-			sutErr = pProc.getErrorStream(); // Stderr
-			sutIn = pProc.getOutputStream(); // Stdin
-			sutOut = pProc.getInputStream(); // Stdout
 			RedirOutputThread outThrd = new RedirOutputThread(pProc, out);
 			outThrd.start();
 			outThrd.join(10000);
+			int nRetCode = pProc.exitValue();
+			sRet = "return code [" + nRetCode + "]";
 			}
 		catch (IOException e) 
 			{
 			e.printStackTrace();
 			}
 		catch (InterruptedException e)
 			{
-			// TODO Auto-generated catch block
 			e.printStackTrace();
+			sRet = "Timed out!";
+			}
+
+		return (sRet);
+		}
+/*	
+	@SuppressWarnings("unchecked")
+	public static void set(String key, String value) throws Exception
+		{
+	    Class[] classes = Collections.class.getDeclaredClasses();
+	    Map env = System.getenv();
+	    for(Class cl : classes)
+	    	{
+	        if("java.util.Collections$UnmodifiableMap".equals(cl.getName()))
+	        	{
+	            Field field = cl.getDeclaredField("m");
+	            field.setAccessible(true);
+	            Object obj = field.get(env);
+	            Map<String, String> map = (Map<String, String>) obj;
+	            map.put(key, value);
+	        	}
+	    	}
+		}
+
+*/	
+	public String StartPrg2(String [] progArray, OutputStream out)
+		{
+		String sRet = "";
+		
+		int	nArraySize = 0;
+		int	nArgs = progArray.length - 1; // 1st arg is the environment string
+		int	lcv	= 0;
+		int	temp = 0;
+
+		String sEnvString = progArray[0];
+
+		// Set up command line args stripping off the environment string
+		String [] theArgs = new String [nArgs];
+		for (lcv = 0; lcv < nArgs; lcv++)
+			{
+			theArgs[lcv] = progArray[lcv + 1];
+			}
+		
+		try 
+			{
+			String [] envStrings = sEnvString.split(",");
+			Map<String, String> newEnv = new HashMap<String, String>();
+			
+			for (lcv = 0; lcv < envStrings.length; lcv++)
+				{
+				temp = envStrings[lcv].indexOf("=");
+				if (temp > 0)
+					{
+					newEnv.put(	envStrings[lcv].substring(0, temp), 
+								envStrings[lcv].substring(temp + 1, envStrings[lcv].length()));
+					}
+				}
+			
+			Map<String, String> sysEnv = System.getenv();
+			
+			nArraySize = sysEnv.size();
+			
+			for (Map.Entry<String, String> entry : newEnv.entrySet())
+				{
+				if (!sysEnv.containsKey(entry.getKey()))
+					{
+					nArraySize++;
+					}
+				}
+			
+			String[] envArray = new String[nArraySize];
+				
+			int		i = 0;
+			int		offset;
+			String	sKey = "";
+			String 	sValue = "";
+			
+	        for (Map.Entry<String, String> entry : sysEnv.entrySet())
+	        	{
+	        	sKey = entry.getKey();
+	        	if (newEnv.containsKey(sKey))
+	        		{
+	        		sValue = newEnv.get(sKey);
+	        		if ((offset = sValue.indexOf("$" + sKey)) != -1)
+	        			{
+	        			envArray[i++] = sKey + 
+	        							"=" + 
+	        							sValue.substring(0, offset) + 
+	        							entry.getValue() + 
+	        							sValue.substring(offset + sKey.length() + 1);
+	        			}
+	        		else
+	        			envArray[i++] = sKey + "=" + sValue;
+	        		newEnv.remove(sKey);
+	        		}
+	        	else
+	        		envArray[i++] = entry.getKey() + "=" + entry.getValue();
+	        	}
+	        
+			for (Map.Entry<String, String> entry : newEnv.entrySet())
+				{
+        		envArray[i++] = entry.getKey() + "=" + entry.getValue();
+				}
+	        
+			pProc = Runtime.getRuntime().exec(theArgs, envArray);
+
+			RedirOutputThread outThrd = new RedirOutputThread(pProc, out);
+			outThrd.start();
+			outThrd.join(10000);
+			int nRetCode = pProc.exitValue();
+			sRet = "return code [" + nRetCode + "]";
+			}
+		catch(UnsupportedOperationException e)
+			{
+			if (e != null)
+				e.printStackTrace();
+			}
+		catch(ClassCastException e)
+			{
+			if (e != null)
+				e.printStackTrace();
+			}
+		catch(IllegalArgumentException e)
+			{
+			if (e != null)
+				e.printStackTrace();
+			}
+		catch(NullPointerException e)
+			{
+			if (e != null)
+				e.printStackTrace();
+			}
+		catch (IOException e) 
+			{
+			e.printStackTrace();
+			}
+		catch (InterruptedException e)
+			{
+			e.printStackTrace();
+			sRet = "Timed out!";
 			}
 
 		return (sRet);
 		}
 /*	
 	public String InstallApplication()
 		{
 		String sRet = "";
@@ -2598,60 +2905,63 @@ public class DoCommand {
 	
 		SUTAgentAndroid.me.startActivity(unInstIntent);
 
 		return(sRet);
 		}
 */
 	private String PrintUsage()
 		{
-		String sRet = "run [executable] [args]  - start program no wait\n" +
-			"exec [executable] [args] - start program wait\n" +
-			"fire [executable] [args] - start program no wait\n" +
-			"arun [executable] [args] - start program no wait\n" +
-			"kill [program name]      - kill program no path\n" +
-			"killall                  - kill all processes started\n" +
-			"ps                       - list of running processes\n" +
-			"info                     - list of device info\n" +
-			"        [os]             - os version for device\n" +
-			"        [id]             - unique identifier for device\n" +
-			"        [uptime]         - uptime for device\n" +
-			"        [systime]        - current system time on device\n" +
-			"        [screen]         - width, height and bits per pixel for device\n" +
-			"        [memory]         - physical, free, available, storage memory for device\n" +
-			"        [processes]      - list of running processes see 'ps'\n" +
-			"deadman timeout          - set the duration for the deadman timer\n" +
-			"alrt [on/off]            - start or stop sysalert behavior\n" +
-			"disk [arg]               - prints disk space info\n" +
-			"cp file1 file2           - copy file1 to file2 on device\n" +
-			"time file                - timestamp for file on device\n" +
-			"hash file                - generate hash for file on device\n" +
-			"cd directory             - change cwd on device\n" +
-			"cat file                 - cat file on device\n" +
-			"cwd                      - display cwd on device\n" +
-			"mv file1 file2           - move file1 to file2 on device\n" +
-			"push filename            - push file to device\n" +
-			"rm file                  - delete file on device\n" +
-			"rmdr directory           - delete directory on device even if not empty\n" +
-			"mkdr directory           - create directory on device\n" +
-			"dirw directory           - tests whether the directory is writable on the device\n" +
-			"stat processid           - stat process on device\n" +
-			"dead processid           - print whether the process is alive or hung on device\n" +
-			"mems                     - dump memory stats on device\n" +
-			"ls                       - print directory on device\n" +
-			"tmpd                     - print temp directory on device\n" +
-			"ping [hostname/ipaddr]   - ping a network device\n" +
-			"unzp zipfile destdir     - unzip the zipfile into the destination dir\n" +
-			"zip zipfile src          - zip the source file/dir into zipfile\n" +
-			"rebt                     - reboot device\n" +
-			"inst /path/filename.apk  - install the referenced apk file\n" +
-			"uninst packagename       - uninstall the referenced package\n" +
-			"updt pkgname pkgfile     - unpdate the referenced package\n" +
-			"clok                     - the current device time expressed as the number of millisecs since epoch\n" +
-			"settime date time        - sets the device date and time (YYYY/MM/DD HH:MM:SS)\n" +
-			"rebt                     - reboot device\n" +
-			"quit                     - disconnect SUTAgent\n" +
-			"exit                     - close SUTAgent\n" +
-			"ver                      - SUTAgent version\n" +
-			"help                     - you're reading it";
+		String sRet = 
+			"run [executable] [args]      - start program no wait\n" +
+			"exec [executable] [args]     - start program wait\n" +
+			"fire [executable] [args]     - start program no wait\n" +
+			"envrun [env pairs] [cmdline] - start program no wait\n" +
+			"kill [program name]          - kill program no path\n" +
+			"killall                      - kill all processes started\n" +
+			"ps                           - list of running processes\n" +
+			"info                         - list of device info\n" +
+			"        [os]                 - os version for device\n" +
+			"        [id]                 - unique identifier for device\n" +
+			"        [uptime]             - uptime for device\n" +
+			"        [systime]            - current system time on device\n" +
+			"        [screen]             - width, height and bits per pixel for device\n" +
+			"        [memory]             - physical, free, available, storage memory for device\n" +
+			"        [processes]          - list of running processes see 'ps'\n" +
+			"deadman timeout              - set the duration for the deadman timer\n" +
+			"alrt [on/off]                - start or stop sysalert behavior\n" +
+			"disk [arg]                   - prints disk space info\n" +
+			"cp file1 file2               - copy file1 to file2 on device\n" +
+			"time file                    - timestamp for file on device\n" +
+			"hash file                    - generate hash for file on device\n" +
+			"cd directory                 - change cwd on device\n" +
+			"cat file                     - cat file on device\n" +
+			"cwd                          - display cwd on device\n" +
+			"mv file1 file2               - move file1 to file2 on device\n" +
+			"push filename                - push file to device\n" +
+			"rm file                      - delete file on device\n" +
+			"rmdr directory               - delete directory on device even if not empty\n" +
+			"mkdr directory               - create directory on device\n" +
+			"dirw directory               - tests whether the directory is writable on the device\n" +
+			"stat processid               - stat process on device\n" +
+			"dead processid               - print whether the process is alive or hung on device\n" +
+			"mems                         - dump memory stats on device\n" +
+			"ls                           - print directory on device\n" +
+			"tmpd                         - print temp directory on device\n" +
+			"ping [hostname/ipaddr]       - ping a network device\n" +
+			"unzp zipfile destdir         - unzip the zipfile into the destination dir\n" +
+			"zip zipfile src              - zip the source file/dir into zipfile\n" +
+			"rebt                         - reboot device\n" +
+			"inst /path/filename.apk      - install the referenced apk file\n" +
+			"uninst packagename           - uninstall the referenced package\n" +
+			"updt pkgname pkgfile         - unpdate the referenced package\n" +
+			"clok                         - the current device time expressed as the number of millisecs since epoch\n" +
+			"settime date time            - sets the device date and time (YYYY/MM/DD HH:MM:SS)\n" +
+			"tzset timezone               - sets the device timezone format is GMTxhh:mm x = +/- or a recognized Olsen string\n" +
+			"tzget                        - returns the current timezone set on the device\n" +
+			"rebt                         - reboot device\n" +
+			"quit                         - disconnect SUTAgent\n" +
+			"exit                         - close SUTAgent\n" +
+			"ver                          - SUTAgent version\n" +
+			"help                         - you're reading it";
 		return (sRet);
 		}
 }
--- a/build/mobile/sutagent/android/SUTAgentAndroid.java
+++ b/build/mobile/sutagent/android/SUTAgentAndroid.java
@@ -386,17 +386,17 @@ public class SUTAgentAndroid extends Act
 					else if (nChargeLevel > 80)
 						sb.append("HIGH");
 					}
 				
 				if (BatteryManager.BATTERY_HEALTH_OVERHEAT == health)
 					{
 					sb.append("Overheated ");
 					sb.append((((float)(nBatteryTemp))/10));
-					sb.append("(C)");
+					sb.append("(C)");
 					}
 				else
 					{
 					switch(status)
 						{
 						case BatteryManager.BATTERY_STATUS_UNKNOWN:
 							// old emulator; maybe also when plugged in with no battery
 							if (present == true)
--- a/client.mk
+++ b/client.mk
@@ -64,18 +64,17 @@
 #   MOZ_PREFLIGHT      }   MOZ_BUILD_PROJECTS, before each project, after
 #   MOZ_POSTFLIGHT     }   each project, and after all projects; these
 #   MOZ_POSTFLIGHT_ALL }   variables contain space-separated lists
 #   MOZ_UNIFY_BDATE      - Set to use the same bdate for each project in
 #                          MOZ_BUILD_PROJECTS
 #
 #######################################################################
 # Defines
-#
-CVS = cvs
+
 comma := ,
 
 CWD := $(CURDIR)
 ifneq (1,$(words $(CWD)))
 $(error The mozilla directory cannot be located in a path with spaces.)
 endif
 
 ifeq "$(CWD)" "/"
@@ -102,17 +101,16 @@ endif
 MKDIR := mkdir
 SH := /bin/sh
 ifndef MAKE
 MAKE := gmake
 endif
 PERL ?= perl
 PYTHON ?= python
 
-RUN_AUTOCONF_LOCALLY = 1
 CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess)
 ifdef CONFIG_GUESS_SCRIPT
   CONFIG_GUESS = $(shell $(CONFIG_GUESS_SCRIPT))
 endif
 
 
 ####################################
 # Sanity checks
@@ -165,17 +163,16 @@ MOZ_MAKE = $(MAKE) $(MOZ_MAKE_FLAGS) -C 
 endif # MOZ_BUILD_PROJECTS
 
 # 'configure' scripts generated by autoconf.
 CONFIGURES := $(TOPSRCDIR)/configure
 CONFIGURES += $(TOPSRCDIR)/js/src/configure
 
 #######################################################################
 # Rules
-# 
 
 # The default rule is build
 build::
 
 # Print out any options loaded from mozconfig.
 all build clean depend distclean export libs install realclean::
 	@if test -f .mozconfig.out; then \
 	  cat .mozconfig.out; \
@@ -267,51 +264,44 @@ else
 # individual project in a multi-project build.
 
 ####################################
 # Configure
 
 CONFIG_STATUS = $(wildcard $(OBJDIR)/config.status)
 CONFIG_CACHE  = $(wildcard $(OBJDIR)/config.cache)
 
-ifdef RUN_AUTOCONF_LOCALLY
 EXTRA_CONFIG_DEPS := \
 	$(TOPSRCDIR)/aclocal.m4 \
 	$(wildcard $(TOPSRCDIR)/build/autoconf/*.m4) \
 	$(TOPSRCDIR)/js/src/aclocal.m4 \
 	$(NULL)
 
 $(CONFIGURES): %: %.in $(EXTRA_CONFIG_DEPS)
 	@echo Generating $@ using autoconf
 	cd $(@D); $(AUTOCONF)
-endif
 
 CONFIG_STATUS_DEPS := \
 	$(wildcard $(CONFIGURES)) \
 	$(TOPSRCDIR)/allmakefiles.sh \
 	$(TOPSRCDIR)/.mozconfig.mk \
 	$(wildcard $(TOPSRCDIR)/nsprpub/configure) \
 	$(wildcard $(TOPSRCDIR)/config/milestone.txt) \
-	$(wildcard $(TOPSRCDIR)/config/chrome-versions.sh) \
-  $(wildcard $(addsuffix confvars.sh,$(wildcard $(TOPSRCDIR)/*/))) \
+	$(wildcard $(addsuffix confvars.sh,$(wildcard $(TOPSRCDIR)/*/))) \
 	$(NULL)
 
 # configure uses the program name to determine @srcdir@. Calling it without
 #   $(TOPSRCDIR) will set @srcdir@ to "."; otherwise, it is set to the full
 #   path of $(TOPSRCDIR).
 ifeq ($(TOPSRCDIR),$(OBJDIR))
   CONFIGURE = ./configure
 else
   CONFIGURE = $(TOPSRCDIR)/configure
 endif
 
-ifdef MOZ_TOOLS
-  CONFIGURE = $(TOPSRCDIR)/configure
-endif
-
 configure-files: $(CONFIGURES)
 
 configure:: configure-files
 ifdef MOZ_BUILD_PROJECTS
 	@if test ! -d $(MOZ_OBJDIR); then $(MKDIR) $(MOZ_OBJDIR); else true; fi
 endif
 	@if test ! -d $(OBJDIR); then $(MKDIR) $(OBJDIR); else true; fi
 	@echo cd $(OBJDIR);
@@ -412,9 +402,9 @@ cleansrcdir:
 echo-variable-%:
 	@echo $($*)
 
 # This makefile doesn't support parallel execution. It does pass
 # MOZ_MAKE_FLAGS to sub-make processes, so they will correctly execute
 # in parallel.
 .NOTPARALLEL:
 
-.PHONY: checkout real_checkout depend build profiledbuild maybe_clobber_profiledbuild export libs alldep install clean realclean distclean cleansrcdir pull_all build_all clobber clobber_all pull_and_build_all everything configure preflight_all preflight postflight postflight_all
+.PHONY: checkout real_checkout depend build profiledbuild maybe_clobber_profiledbuild export libs alldep install clean realclean distclean cleansrcdir pull_all build_all clobber clobber_all pull_and_build_all everything configure preflight_all preflight postflight postflight_all upload sdk
--- a/config/Makefile.in
+++ b/config/Makefile.in
@@ -127,16 +127,17 @@ export::
 		-DMOZ_TREE_CAIRO=$(MOZ_TREE_CAIRO) \
 		-DMOZ_ENABLE_LIBXUL=$(MOZ_ENABLE_LIBXUL) \
 		-DMOZ_NATIVE_HUNSPELL=$(MOZ_NATIVE_HUNSPELL) \
 		-DMOZ_NATIVE_BZ2=$(MOZ_NATIVE_BZ2) \
 		-DMOZ_NATIVE_ZLIB=$(MOZ_NATIVE_ZLIB) \
 		-DMOZ_NATIVE_PNG=$(MOZ_NATIVE_PNG) \
 		-DMOZ_NATIVE_JPEG=$(MOZ_NATIVE_JPEG) \
 		-DMOZ_NATIVE_LIBEVENT=$(MOZ_NATIVE_LIBEVENT) \
+		-DMOZ_NATIVE_LIBVPX=$(MOZ_NATIVE_LIBVPX) \
 		$(srcdir)/system-headers | $(PERL) $(topsrcdir)/nsprpub/config/make-system-wrappers.pl system_wrappers
 	$(INSTALL) system_wrappers $(DIST)
 
 GARBAGE_DIRS += system_wrappers
 endif
 
 ifdef WRAP_STL_INCLUDES
 ifdef GNU_CXX
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -96,17 +96,16 @@ MOZ_JS_LIBS		   = @MOZ_JS_LIBS@
 
 MOZ_DEBUG	= @MOZ_DEBUG@
 MOZ_DEBUG_SYMBOLS = @MOZ_DEBUG_SYMBOLS@
 MOZ_DEBUG_ENABLE_DEFS		= @MOZ_DEBUG_ENABLE_DEFS@
 MOZ_DEBUG_DISABLE_DEFS	= @MOZ_DEBUG_DISABLE_DEFS@
 MOZ_DEBUG_FLAGS	= @MOZ_DEBUG_FLAGS@
 MOZ_DEBUG_LDFLAGS=@MOZ_DEBUG_LDFLAGS@
 MOZ_EXTENSIONS  = @MOZ_EXTENSIONS@
-MOZ_IMG_ENCODERS= @MOZ_IMG_ENCODERS@
 MOZ_JSDEBUGGER  = @MOZ_JSDEBUGGER@
 MOZ_IPC 	= @MOZ_IPC@
 MOZ_IPDL_TESTS 	= @MOZ_IPDL_TESTS@
 MOZ_LEAKY	= @MOZ_LEAKY@
 MOZ_MEMORY      = @MOZ_MEMORY@
 MOZ_PROFILING   = @MOZ_PROFILING@
 MOZ_JPROF       = @MOZ_JPROF@
 MOZ_SHARK       = @MOZ_SHARK@
@@ -227,16 +226,20 @@ MOZ_AUTH_EXTENSION = @MOZ_AUTH_EXTENSION
 MOZ_NATIVE_HUNSPELL = @SYSTEM_HUNSPELL@
 MOZ_HUNSPELL_LIBS = @MOZ_HUNSPELL_LIBS@
 MOZ_HUNSPELL_CFLAGS = @MOZ_HUNSPELL_CFLAGS@
 
 MOZ_NATIVE_LIBEVENT = @MOZ_NATIVE_LIBEVENT@
 MOZ_LIBEVENT_LIBS = @MOZ_LIBEVENT_LIBS@
 MOZ_LIBEVENT_INCLUDES = @MOZ_LIBEVENT_INCLUDES@
 
+MOZ_NATIVE_LIBVPX = @MOZ_NATIVE_LIBVPX@
+MOZ_LIBVPX_LIBS = @MOZ_LIBVPX_LIBS@
+MOZ_LIBVPX_INCLUDES = @MOZ_LIBVPX_INCLUDES@
+
 MOZ_NATIVE_ZLIB	= @SYSTEM_ZLIB@
 MOZ_NATIVE_BZ2	= @SYSTEM_BZ2@
 MOZ_NATIVE_JPEG	= @SYSTEM_JPEG@
 MOZ_NATIVE_PNG	= @SYSTEM_PNG@
 MOZ_TREE_CAIRO = @MOZ_TREE_CAIRO@
 MOZ_TREE_PIXMAN = @MOZ_TREE_PIXMAN@
 
 MOZ_UPDATE_XTERM = @MOZ_UPDATE_XTERM@
@@ -691,8 +694,21 @@ MOZ_APP_EXTRA_LIBS = @MOZ_APP_EXTRA_LIBS
 ANDROID_NDK       = @ANDROID_NDK@
 ANDROID_TOOLCHAIN = @ANDROID_TOOLCHAIN@
 ANDROID_PLATFORM  = @ANDROID_PLATFORM@
 ANDROID_SDK       = @ANDROID_SDK@
 ANDROID_TOOLS     = @ANDROID_TOOLS@
 ANDROID_VERSION   = @ANDROID_VERSION@
 
 JS_SHARED_LIBRARY = @JS_SHARED_LIBRARY@
+
+# We only want to do the pymake sanity on Windows, other os's can cope
+ifeq (,$(filter-out WINNT WINCE,$(HOST_OS_ARCH)))
+# Ensure invariants between GNU Make and pymake
+# Checked here since we want the sane error in a file that
+# actually can be found regardless of path-style.
+ifeq (_:,$(.PYMAKE)_$(findstring :,$(srcdir)))
+$(error Windows-style srcdir being used with GNU make. Did you mean to run $(topsrcdir)/build/pymake/make.py instead? [see-also: https://developer.mozilla.org/en/Gmake_vs._Pymake])
+endif
+ifeq (1_a,$(.PYMAKE)_$(firstword a$(subst /, ,$(srcdir))))
+$(error MSYS-style srcdir being used with Pymake. Did you mean to run GNU Make instead? [see-also: https://developer.mozilla.org/en/Gmake_vs._Pymake])
+endif
+endif # Windows
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -166,58 +166,58 @@ define _INSTALL_TESTS
 
 endef # do not remove the blank line!
 
 SOLO_FILE ?= $(error Specify a test filename in SOLO_FILE when using check-interactive or check-one)
 
 libs::
 	$(foreach dir,$(XPCSHELL_TESTS),$(_INSTALL_TESTS))
 	$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py \
-          $(testxpcobjdir)/all-test-dirs.list \
-          $(addprefix $(relativesrcdir)/,$(XPCSHELL_TESTS))
+	  $(testxpcobjdir)/all-test-dirs.list \
+	  $(addprefix $(relativesrcdir)/,$(XPCSHELL_TESTS))
 
 testxpcsrcdir = $(topsrcdir)/testing/xpcshell
 
 # Execute all tests in the $(XPCSHELL_TESTS) directories.
 # See also testsuite-targets.mk 'xpcshell-tests' target for global execution.
 xpcshell-tests:
 	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
-          -I$(topsrcdir)/build \
-          $(testxpcsrcdir)/runxpcshelltests.py \
-          --symbols-path=$(DIST)/crashreporter-symbols \
-          $(EXTRA_TEST_ARGS) \
-          $(DIST)/bin/xpcshell \
-          $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+	  -I$(topsrcdir)/build \
+	  $(testxpcsrcdir)/runxpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  $(EXTRA_TEST_ARGS) \
+	  $(DIST)/bin/xpcshell \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
 
 # Execute a single test, specified in $(SOLO_FILE), but don't automatically
 # start the test. Instead, present the xpcshell prompt so the user can
 # attach a debugger and then start the test.
 check-interactive:
 	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
-          -I$(topsrcdir)/build \
-          $(testxpcsrcdir)/runxpcshelltests.py \
-          --symbols-path=$(DIST)/crashreporter-symbols \
-          --test-path=$(SOLO_FILE) \
-          --profile-name=$(MOZ_APP_NAME) \
-          --interactive \
-          $(DIST)/bin/xpcshell \
-          $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+	  -I$(topsrcdir)/build \
+	  $(testxpcsrcdir)/runxpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --test-path=$(SOLO_FILE) \
+	  --profile-name=$(MOZ_APP_NAME) \
+	  --interactive \
+	  $(DIST)/bin/xpcshell \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
 
 # Execute a single test, specified in $(SOLO_FILE)
 check-one:
 	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
-          -I$(topsrcdir)/build \
-          $(testxpcsrcdir)/runxpcshelltests.py \
-          --symbols-path=$(DIST)/crashreporter-symbols \
-          --test-path=$(SOLO_FILE) \
-          --profile-name=$(MOZ_APP_NAME) \
-          --verbose \
-          $(EXTRA_TEST_ARGS) \
-          $(DIST)/bin/xpcshell \
-          $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
+	  -I$(topsrcdir)/build \
+	  $(testxpcsrcdir)/runxpcshelltests.py \
+	  --symbols-path=$(DIST)/crashreporter-symbols \
+	  --test-path=$(SOLO_FILE) \
+	  --profile-name=$(MOZ_APP_NAME) \
+	  --verbose \
+	  $(EXTRA_TEST_ARGS) \
+	  $(DIST)/bin/xpcshell \
+	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
 
 endif # XPCSHELL_TESTS
 
 ifdef CPP_UNIT_TESTS
 
 # Compile the tests to $(DIST)/bin.  Make lots of niceties available by default
 # through TestHarness.h, by modifying the list of includes and the libs against
 # which stuff links.
@@ -841,17 +841,17 @@ ifdef LIBRARY_NAME
 ifdef EXPORT_LIBRARY
 ifdef IS_COMPONENT
 ifdef BUILD_STATIC_LIBS
 	@$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_LINK_COMPS) $(STATIC_LIBRARY_NAME)
 ifdef MODULE_NAME
 	@$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_LINK_COMP_NAMES) $(MODULE_NAME)
 endif
 endif # BUILD_STATIC_LIBS
-else  # !IS_COMPONENT
+else # !IS_COMPONENT
 	$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_LINK_LIBS) $(STATIC_LIBRARY_NAME)
 endif # IS_COMPONENT
 endif # EXPORT_LIBRARY
 endif # LIBRARY_NAME
 
 # Create dependencies on static (and shared EXTRA_DSO_LIBS) libraries
 LIBS_DEPS = $(filter %.$(LIB_SUFFIX), $(LIBS))
 HOST_LIBS_DEPS = $(filter %.$(LIB_SUFFIX), $(HOST_LIBS))
@@ -869,17 +869,17 @@ vpath $(LIB_PREFIX)%.$(LIB_SUFFIX) $(_LI
 ifdef IMPORT_LIB_SUFFIX
 vpath $(LIB_PREFIX)%.$(IMPORT_LIB_SUFFIX) $(_LIBDIRS)
 endif # IMPORT_LIB_SUFFIX
 vpath $(DLL_PREFIX)%$(DLL_SUFFIX) $(_LIBDIRS)
 endif # _LIBDIRS
 
 endif # _LIBNAME_RELATIVE_PATHS
 
-# Dependancies which, if modified, should cause everything to rebuild
+# Dependencies which, if modified, should cause everything to rebuild
 GLOBAL_DEPS += Makefile Makefile.in $(DEPTH)/config/autoconf.mk $(topsrcdir)/config/config.mk
 
 ##############################################
 ifdef PARALLEL_DIRS
 libs:: $(PARALLEL_DIRS_libs)
 
 $(PARALLEL_DIRS_libs): %_libs: %/Makefile
 	+@$(call SUBMAKE,libs,$*)
@@ -1193,17 +1193,17 @@ else
 ifneq (,$(filter OSF1 BSD_OS FreeBSD NetBSD OpenBSD SunOS Darwin,$(OS_ARCH)))
 CLEANUP1	:= | egrep -v '(________64ELEL_|__.SYMDEF)'
 CLEANUP2	:= rm -f ________64ELEL_ __.SYMDEF
 else
 CLEANUP2	:= true
 endif
 SUB_LOBJS	= $(shell for lib in $(SHARED_LIBRARY_LIBS); do $(AR_LIST) $${lib} $(CLEANUP1); done;)
 endif # EXPAND_FAKELIBS
-endif # SHARED_LIBARY_LIBS
+endif # SHARED_LIBRARY_LIBS
 endif
 ifdef MOZILLA_PROBE_LIBS
 PROBE_LOBJS	= $(shell for lib in $(MOZILLA_PROBE_LIBS); do $(AR_LIST) $${lib} $(CLEANUP1); done;)
 endif
 ifdef DTRACE_PROBE_OBJ
 EXTRA_DEPS += $(DTRACE_PROBE_OBJ)
 endif
 
@@ -1573,17 +1573,17 @@ SPACE := $(EMPTY) $(EMPTY)
 # and class paths to be in the DOS form (i.e. e:/builds/...).  This function
 # does the appropriate conversion on Windows, but is a noop on other systems.
 ifeq (,$(filter-out WINNT WINCE, $(HOST_OS_ARCH)))
 ifdef CYGWIN_WRAPPER
 normalizepath = $(foreach p,$(1),$(shell cygpath -m $(p)))
 else
 # assume MSYS
 #  We use 'pwd -W' to get DOS form of the path.  However, since the given path
-#  could be a file or a nonexistent path, we cannot call 'pwd -W' directly
+#  could be a file or a non-existent path, we cannot call 'pwd -W' directly
 #  on the path.  Instead, we extract the root path (i.e. "c:/"), call 'pwd -W'
 #  on it, then merge with the rest of the path.
 root-path = $(shell echo $(1) | sed -e "s|\(/[^/]*\)/\?\(.*\)|\1|")
 non-root-path = $(shell echo $(1) | sed -e "s|\(/[^/]*\)/\?\(.*\)|\2|")
 normalizepath = $(foreach p,$(1),$(if $(filter /%,$(1)),$(patsubst %/,%,$(shell cd $(call root-path,$(1)) && pwd -W))/$(call non-root-path,$(1)),$(1)))
 endif
 else
 normalizepath = $(1)
--- a/config/system-headers
+++ b/config/system-headers
@@ -1046,8 +1046,12 @@ proxy.h
 contentaction/contentaction.h
 #endif
 #ifndef MOZ_TREE_PIXMAN
 pixman.h
 #endif
 #if MOZ_ENABLE_MEEGOTOUCHSHARE
 shareuiinterface.h
 #endif
+#if MOZ_NATIVE_LIBVPX==1
+vpx/vpx_decoder.h
+vpx/vp8dx.h
+#endif
--- a/configure.in
+++ b/configure.in
@@ -3403,21 +3403,19 @@ dnl against libSystem causes issues when
 case $target in
 *-darwin*)
     ;;
 *-beos*)
     ;;
 *-os2*)
     ;;
 *)
-    AC_CHECK_LIB(m, atan)
-    AC_CHECK_LIB(dl, dlopen,
-    AC_CHECK_HEADER(dlfcn.h, 
-        LIBS="-ldl $LIBS"
-        AC_DEFINE(HAVE_LIBDL)))
+    AC_SEARCH_LIBS(dlopen, dl, 
+        AC_CHECK_HEADER(dlfcn.h, 
+        AC_DEFINE(HAVE_DLOPEN)))
     ;;
 esac
 
 _SAVE_CFLAGS="$CFLAGS"
 CFLAGS="$CFLAGS -D_GNU_SOURCE"
 AC_CHECK_FUNCS(dladdr)
 CFLAGS="$_SAVE_CFLAGS"
 
@@ -4723,20 +4721,20 @@ dnl Detect yasm
 dnl ======================
 
 AC_MSG_CHECKING([for YASM assembler])
 AC_CHECK_PROGS(YASM, yasm, "")
 
 if test -n "$YASM"; then
   dnl Pull out yasm's version string
   changequote(,)
-  _YASM_VER_FILTER='s|.* ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*|\1|p'
+  _YASM_VER_FILTER='s|.* \([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\).*|\1|p'
   changequote([,])
 
-  YASM_VERSION=`yasm --version | sed -nre "$_YASM_VER_FILTER"`
+  YASM_VERSION=`yasm --version | sed -ne "$_YASM_VER_FILTER"`
   _YASM_MAJOR_VERSION=`echo ${YASM_VERSION} | $AWK -F\. '{ print $1 }'`
   _YASM_MINOR_VERSION=`echo ${YASM_VERSION} | $AWK -F\. '{ print $2 }'`
   _YASM_RELEASE=`      echo ${YASM_VERSION} | $AWK -F\. '{ print $3 }'`
   _YASM_BUILD=`        echo ${YASM_VERSION} | $AWK -F\. '{ print $4 }'`
 fi
 
 if test -z "$SKIP_LIBRARY_CHECKS"; then
 dnl system JPEG support
@@ -4937,17 +4935,16 @@ dnl ====================================
 MOZ_ARG_HEADER(Application)
 
 BUILD_STATIC_LIBS=
 ENABLE_TESTS=1
 MOZ_ACTIVEX_SCRIPTING_SUPPORT=
 MOZ_BRANDING_DIRECTORY=
 MOZ_OFFICIAL_BRANDING=
 MOZ_FEEDS=1
-MOZ_IMG_ENCODERS_DEFAULT="png jpeg"
 MOZ_INSTALLER=1
 MOZ_IPC=1
 MOZ_JAVAXPCOM=
 MOZ_JSDEBUGGER=1
 MOZ_JSLOADER=1
 MOZ_MATHML=1
 MOZ_MORK=
 MOZ_MORKREADER=1
@@ -5989,18 +5986,60 @@ fi
 dnl ========================================================
 dnl = Disable VP8 decoder support
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(webm,
 [  --disable-webm          Disable support for WebM media (VP8 video and Vorbis audio)],
     MOZ_WEBM=,
     MOZ_WEBM=1)
 
+dnl system libvpx Support
+dnl ========================================================
+MOZ_ARG_WITH_STRING(system-libvpx,
+[  --with-system-libvpx=[PFX]
+                          Use system libvpx [installed at prefix PFX]],
+    LIBVPX_DIR=$withval)
+
+MOZ_NATIVE_LIBVPX=
+MOZ_LIBVPX_INCLUDES=
+MOZ_LIBVPX_LIBS=
+
 if test -n "$MOZ_WEBM"; then
     AC_DEFINE(MOZ_WEBM)
+
+    if test -n "$LIBVPX_DIR" -a "$LIBVPX_DIR" != no; then
+        _SAVE_CFLAGS=$CFLAGS
+        _SAVE_LDFLAGS=$LDFLAGS
+        _SAVE_LIBS=$LIBS
+        if test "${LIBVPX_DIR}" = "yes"; then
+            LIBVPX_DIR=/usr
+        fi
+        CFLAGS="-I${LIBVPX_DIR}/include $CFLAGS"
+        LDFLAGS="-L${LIBVPX_DIR}/lib $LDFLAGS"
+        AC_CHECK_HEADER(vpx/vpx_decoder.h,
+                        [if test ! -f "${LIBVPX_DIR}/include/vpx/vpx_decoder.h"; then
+                             AC_MSG_ERROR([vpx/vpx_decoder.h found, but is not in ${LIBVPX_DIR}/include])
+                         fi],
+                        AC_MSG_ERROR([--with-system-libvpx requested but vpx/vpx_decoder.h not found]))
+        AC_CHECK_LIB(vpx, vpx_codec_dec_init_ver,
+                     [MOZ_NATIVE_LIBVPX=1
+                      MOZ_LIBVPX_INCLUDES="-I${LIBVPX_DIR}/include"
+                      MOZ_LIBVPX_LIBS="-L${LIBVPX_DIR}/lib -lvpx"],
+                     ([--with-system-libvpx requested but symbol vpx_codec_dec_init_ver not found]))
+        CFLAGS=$_SAVE_CFLAGS
+        LDFLAGS=$_SAVE_LDFLAGS
+        LIBS=$_SAVE_LIBS
+    fi
+fi
+
+AC_SUBST(MOZ_NATIVE_LIBVPX)
+AC_SUBST(MOZ_LIBVPX_INCLUDES)
+AC_SUBST(MOZ_LIBVPX_LIBS)
+
+if test -n "$MOZ_WEBM" -a -z "$MOZ_NATIVE_LIBVPX"; then
     MOZ_SYDNEYAUDIO=1
     MOZ_MEDIA=1
     case "$target_cpu" in
     arm*)
         MOZ_TREMOR=1
     ;;
     *)
         MOZ_VORBIS=1
@@ -6414,43 +6453,16 @@ dnl Ensure every extension exists, to av
 dnl when trying to build a nonexistent extension.
 for extension in $MOZ_EXTENSIONS; do
     if test ! -d "${srcdir}/extensions/${extension}"; then
         AC_MSG_ERROR([Unrecognized extension provided to --enable-extensions: ${extension}.])
     fi
 done
 
 dnl ========================================================
-dnl Image encoders
-dnl ========================================================
-MOZ_ARG_ENABLE_STRING(image-encoders,
-[  --enable-image-encoders[={mod1,mod2,default,all,none}]
-                          Enable specific image encoders],
-[ for option in `echo $enableval | sed 's/,/ /g'`; do
-    if test "$option" = "yes" -o "$option" = "all"; then
-        addencoder="$MOZ_IMG_ENCODERS_DEFAULT"
-    elif test "$option" = "no" -o "$option" = "none"; then
-        MOZ_IMG_ENCODERS=""
-        addencoder=""
-    elif test "$option" = "default"; then
-        addencoder="$MOZ_IMG_ENCODERS_DEFAULT"
-    elif test `echo "$option" | grep -c \^-` != 0; then
-        option=`echo $option | sed 's/^-//'`
-        addencoder=`echo "$MOZ_IMG_ENCODERS" | sed "s/ ${option}//"`
-    else
-        addencoder="$option"
-    fi
-    MOZ_IMG_ENCODERS="$MOZ_IMG_ENCODERS $addencoder"
-done],
-    MOZ_IMG_ENCODERS="$MOZ_IMG_ENCODERS_DEFAULT")
-
-dnl Remove dupes
-MOZ_IMG_ENCODERS=`${PERL} ${srcdir}/build/unix/uniq.pl ${MOZ_IMG_ENCODERS}`
-
-dnl ========================================================
 dnl MathML on by default
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(mathml,
 [  --disable-mathml        Disable MathML support],
     MOZ_MATHML=,
     MOZ_MATHML=1 )
 if test "$MOZ_MATHML"; then
   AC_DEFINE(MOZ_MATHML)
@@ -8843,17 +8855,16 @@ AC_SUBST(MOZ_PSM)
 AC_SUBST(MOZ_DEBUG)
 AC_SUBST(MOZ_DEBUG_SYMBOLS)
 AC_SUBST(MOZ_DEBUG_ENABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_DISABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_FLAGS)
 AC_SUBST(MOZ_DEBUG_LDFLAGS)
 AC_SUBST(WARNINGS_AS_ERRORS)
 AC_SUBST(MOZ_EXTENSIONS)
-AC_SUBST(MOZ_IMG_ENCODERS)
 AC_SUBST(MOZ_JSDEBUGGER)
 AC_SUBST(MOZ_PLUGINS)
 AC_SUBST(MOZ_LOG_REFCNT)
 AC_SUBST(MOZ_LEAKY)
 AC_SUBST(MOZ_JPROF)
 AC_SUBST(MOZ_SHARK)
 AC_SUBST(MOZ_CALLGRIND)
 AC_SUBST(MOZ_VTUNE)
new file mode 100644
--- /dev/null
+++ b/content/base/public/FromParser.h
@@ -0,0 +1,57 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Ms2ger <Ms2ger@gmail.com>.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef mozilla_dom_FromParser_h
+#define mozilla_dom_FromParser_h
+
+namespace mozilla {
+namespace dom {
+
+/**
+ * Constants for passing as aFromParser
+ */
+enum FromParser {
+  NOT_FROM_PARSER = 0,
+  FROM_PARSER_NETWORK = 1,
+  FROM_PARSER_DOCUMENT_WRITE = 1 << 1,
+  FROM_PARSER_FRAGMENT = 1 << 2,
+  FROM_PARSER_XSLT = 1 << 3
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_FromParser_h
--- a/content/base/public/Makefile.in
+++ b/content/base/public/Makefile.in
@@ -79,18 +79,19 @@ nsLineBreaker.h \
 nsReferencedElement.h \
 nsXMLNameSpaceMap.h \
 nsDOMEventTargetWrapperCache.h \
 $(NULL)
 
 EXPORTS_NAMESPACES = mozilla/dom
 
 EXPORTS_mozilla/dom = \
-Element.h \
-$(NULL)
+		Element.h \
+		FromParser.h \
+		$(NULL)
 
 ifndef DISABLE_XFORMS_HOOKS
 EXPORTS += nsIXFormsUtilityService.h
 endif
 
 SDK_XPIDLSRCS   = \
 		nsISelection.idl  \
 		$(NULL)
--- a/content/base/public/nsContentCreatorFunctions.h
+++ b/content/base/public/nsContentCreatorFunctions.h
@@ -37,41 +37,35 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsContentCreatorFunctions_h__
 #define nsContentCreatorFunctions_h__
 
 #include "nscore.h"
 #include "nsCOMPtr.h"
+#include "mozilla/dom/FromParser.h"
 
 /**
  * Functions to create content, to be used only inside Gecko
  * (mozilla/content and mozilla/layout).
  */
 
 class nsAString;
 class nsIContent;
 class nsIDocument;
 class nsINodeInfo;
 class imgIRequest;
 class nsNodeInfoManager;
 class nsGenericHTMLElement;
 
-/**
- * Constants for passing as aFromParser
- */
-#define NS_NOT_FROM_PARSER 0
-#define NS_FROM_PARSER_NETWORK 1
-#define NS_FROM_PARSER_DOCUMENT_WRITE (1 << 1)
-#define NS_FROM_PARSER_FRAGMENT (1 << 2)
-
 nsresult
 NS_NewElement(nsIContent** aResult, PRInt32 aElementType,
-              already_AddRefed<nsINodeInfo> aNodeInfo, PRUint32 aFromParser);
+              already_AddRefed<nsINodeInfo> aNodeInfo,
+              mozilla::dom::FromParser aFromParser);
 
 nsresult
 NS_NewXMLElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo);
 
 /**
  * aNodeInfoManager must not be null.
  */
 nsresult
@@ -104,23 +98,23 @@ NS_NewXMLStylesheetProcessingInstruction
  * aNodeInfoManager must not be null.
  */
 nsresult
 NS_NewXMLCDATASection(nsIContent** aInstancePtrResult,
                       nsNodeInfoManager *aNodeInfoManager);
 
 nsresult
 NS_NewHTMLElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo,
-                  PRUint32 aFromParser);
+                  mozilla::dom::FromParser aFromParser);
 
 // First argument should be nsHTMLTag, but that adds dependency to parser
 // for a bunch of files.
 already_AddRefed<nsGenericHTMLElement>
 CreateHTMLElement(PRUint32 aNodeType, already_AddRefed<nsINodeInfo> aNodeInfo,
-                  PRUint32 aFromParser);
+                  mozilla::dom::FromParser aFromParser);
 
 #ifdef MOZ_MATHML
 nsresult
 NS_NewMathMLElement(nsIContent** aResult,
                      already_AddRefed<nsINodeInfo> aNodeInfo);
 #endif
 
 #ifdef MOZ_XUL
@@ -129,17 +123,17 @@ NS_NewXULElement(nsIContent** aResult, a
 
 void
 NS_TrustedNewXULElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo);
 #endif
 
 #ifdef MOZ_SVG
 nsresult
 NS_NewSVGElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo,
-                 PRUint32 aFromParser);
+                 mozilla::dom::FromParser aFromParser);
 #endif
 
 nsresult
 NS_NewGenConImageContent(nsIContent** aResult,
                          already_AddRefed<nsINodeInfo> aNodeInfo,
                          imgIRequest* aImageRequest);
 
 nsresult
--- a/content/base/public/nsIScriptElement.h
+++ b/content/base/public/nsIScriptElement.h
@@ -53,25 +53,28 @@
 
 /**
  * Internal interface implemented by script elements
  */
 class nsIScriptElement : public nsIScriptLoaderObserver {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTELEMENT_IID)
 
-  nsIScriptElement(PRUint32 aFromParser)
+  nsIScriptElement(mozilla::dom::FromParser aFromParser)
     : mLineNumber(0),
       mAlreadyStarted(PR_FALSE),
       mMalformed(PR_FALSE),
       mDoneAddingChildren(PR_TRUE),
       mFrozen(PR_FALSE),
       mDefer(PR_FALSE),
       mAsync(PR_FALSE),
-      mParserCreated((PRUint8)aFromParser),
+      mParserCreated(aFromParser == mozilla::dom::FROM_PARSER_FRAGMENT ?
+                     mozilla::dom::NOT_FROM_PARSER : aFromParser),
+                     // Fragment parser-created scripts (if executable)
+                     // behave like script-created scripts.
       mCreatorParser(nsnull)
   {
   }
 
   /**
    * Content type identifying the scripting language. Can be empty, in
    * which case javascript will be assumed.
    */
@@ -115,20 +118,19 @@ public:
    */
   PRBool GetScriptAsync()
   {
     NS_PRECONDITION(mFrozen, "Not ready for this call yet!");
     return mAsync;  
   }
 
   /**
-   * Returns a constant defined in nsContentCreatorFunctions.h. Non-zero
-   * values mean parser-created and zero means not parser-created.
+   * Returns how the element was created.
    */
-  PRUint32 GetParserCreated()
+  mozilla::dom::FromParser GetParserCreated()
   {
     return mParserCreated;
   }
 
   void SetScriptLineNumber(PRUint32 aLineNumber)
   {
     mLineNumber = aLineNumber;
   }
@@ -151,17 +153,17 @@ public:
     mAlreadyStarted = PR_TRUE;
   }
 
   void LoseParserInsertedness()
   {
     mFrozen = PR_FALSE;
     mUri = nsnull;
     mCreatorParser = nsnull;
-    mParserCreated = NS_NOT_FROM_PARSER;
+    mParserCreated = mozilla::dom::NOT_FROM_PARSER;
   }
 
   void SetCreatorParser(nsIParser* aParser)
   {
     mCreatorParser = getter_AddRefs(NS_GetWeakReference(aParser));
   }
 
   /**
@@ -229,17 +231,17 @@ protected:
   /**
    * The effective asyncness.
    */
   PRPackedBool mAsync;
   
   /**
    * Whether this element was parser-created.
    */
-  PRUint8 mParserCreated;
+  mozilla::dom::FromParser mParserCreated;
 
   /**
    * The effective src (or null if no src).
    */
   nsCOMPtr<nsIURI> mUri;
   
   /**
    * The creator parser of a non-defer, non-async parser-inserted script.
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -4798,18 +4798,22 @@ static void ProcessViewportToken(nsIDocu
   while ((tip != end) && (*tip != '='))
     ++tip;
 
   /* If we didn't find an '=', punt. */
   if (tip == end)
     return;
 
   /* Extract the key and value. */
-  const nsAString &key = Substring(tail, tip);
-  const nsAString &value = Substring(++tip, end);
+  const nsAString &key =
+    nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(Substring(tail, tip),
+                                                        PR_TRUE);
+  const nsAString &value =
+    nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(Substring(++tip, end),
+                                                        PR_TRUE);
 
   /* Check for known keys. If we find a match, insert the appropriate
    * information into the document header. */
   nsCOMPtr<nsIAtom> key_atom = do_GetAtom(key);
   if (key_atom == nsGkAtoms::height)
     aDocument->SetHeaderData(nsGkAtoms::viewport_height, value);
   else if (key_atom == nsGkAtoms::width)
     aDocument->SetHeaderData(nsGkAtoms::viewport_width, value);
@@ -4818,50 +4822,63 @@ static void ProcessViewportToken(nsIDocu
   else if (key_atom == nsGkAtoms::minimum_scale)
     aDocument->SetHeaderData(nsGkAtoms::viewport_minimum_scale, value);
   else if (key_atom == nsGkAtoms::maximum_scale)
     aDocument->SetHeaderData(nsGkAtoms::viewport_maximum_scale, value);
   else if (key_atom == nsGkAtoms::user_scalable)
     aDocument->SetHeaderData(nsGkAtoms::viewport_user_scalable, value);
 }
 
-#define IS_SEPARATOR(c) ((c == ' ') || (c == ',') || (c == ';'))
+#define IS_SEPARATOR(c) ((c == '=') || (c == ',') || (c == ';') || \
+                         (c == '\t') || (c == '\n') || (c == '\r'))
+
 /* static */
 nsresult
 nsContentUtils::ProcessViewportInfo(nsIDocument *aDocument,
                                     const nsAString &viewportInfo) {
 
   /* We never fail. */
   nsresult rv = NS_OK;
 
   /* Iterators. */
   nsAString::const_iterator tip, tail, end;
   viewportInfo.BeginReading(tip);
   tail = tip;
   viewportInfo.EndReading(end);
 
   /* Read the tip to the first non-separator character. */
-  while ((tip != end) && IS_SEPARATOR(*tip))
+  while ((tip != end) && (IS_SEPARATOR(*tip) || nsCRT::IsAsciiSpace(*tip)))
     ++tip;
 
   /* Read through and find tokens separated by separators. */
   while (tip != end) {
-    
+
     /* Synchronize tip and tail. */
     tail = tip;
 
     /* Advance tip past non-separator characters. */
     while ((tip != end) && !IS_SEPARATOR(*tip))
       ++tip;
 
+    /* Allow white spaces that surround the '=' character */
+    if ((tip != end) && (*tip == '=')) {
+      ++tip;
+
+      while ((tip != end) && nsCRT::IsAsciiSpace(*tip))
+        ++tip;
+
+      while ((tip != end) && !(IS_SEPARATOR(*tip) || nsCRT::IsAsciiSpace(*tip)))
+        ++tip;
+    }
+
     /* Our token consists of the characters between tail and tip. */
     ProcessViewportToken(aDocument, Substring(tail, tip));
 
     /* Skip separators. */
-    while ((tip != end) && IS_SEPARATOR(*tip))
+    while ((tip != end) && (IS_SEPARATOR(*tip) || nsCRT::IsAsciiSpace(*tip)))
       ++tip;
   }
 
   return rv;
 
 }
 
 #undef IS_SEPARATOR
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -4366,17 +4366,18 @@ nsDocument::CreateElementNS(const nsAStr
   nsresult rv = nsContentUtils::GetNodeInfoFromQName(aNamespaceURI,
                                                      aQualifiedName,
                                                      mNodeInfoManager,
                                                      getter_AddRefs(nodeInfo));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIContent> content;
   PRInt32 ns = nodeInfo->NamespaceID();
-  rv = NS_NewElement(getter_AddRefs(content), ns, nodeInfo.forget(), PR_FALSE);
+  rv = NS_NewElement(getter_AddRefs(content), ns, nodeInfo.forget(),
+                     NOT_FROM_PARSER);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return CallQueryInterface(content, aReturn);
 }
 
 NS_IMETHODIMP
 nsDocument::CreateTextNode(const nsAString& aData, nsIDOMText** aReturn)
 {
@@ -6843,17 +6844,18 @@ nsDocument::CreateElem(const nsAString& 
   PRInt32 elementType = aDocumentDefaultType ? mDefaultElementType :
     aNamespaceID;
 
   nsCOMPtr<nsINodeInfo> nodeInfo;
   mNodeInfoManager->GetNodeInfo(aName, aPrefix, aNamespaceID,
                                 getter_AddRefs(nodeInfo));
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
-  return NS_NewElement(aResult, elementType, nodeInfo.forget(), PR_FALSE);
+  return NS_NewElement(aResult, elementType, nodeInfo.forget(),
+                       NOT_FROM_PARSER);
 }
 
 PRBool
 nsDocument::IsSafeToFlush() const
 {
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (!shell)
     return PR_TRUE;
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -648,17 +648,28 @@ nsFrameLoader::Show(PRInt32 marginWidth,
 #ifdef MOZ_IPC
   if (mRemoteFrame) {
     return ShowRemoteFrame(GetSubDocumentSize(frame));
   }
 #endif
 
   nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(mDocShell);
   NS_ASSERTION(baseWindow, "Found a nsIDocShell that isn't a nsIBaseWindow.");
-  baseWindow->InitWindow(nsnull, view->GetWidget(), 0, 0, 10, 10);
+  nsIntSize size;
+  if (!(frame->GetStateBits() & NS_FRAME_FIRST_REFLOW)) {
+    // We have a useful size already; use it, since we might get no
+    // more size updates.
+    size = GetSubDocumentSize(frame);
+  } else {
+    // Pick some default size for now.  Using 10x10 because that's what the
+    // code here used to do.
+    size.SizeTo(10, 10);
+  }
+  baseWindow->InitWindow(nsnull, view->GetWidget(), 0, 0,
+                         size.width, size.height);
   // This is kinda whacky, this "Create()" call doesn't really
   // create anything, one starts to wonder why this was named
   // "Create"...
   baseWindow->Create();
   baseWindow->SetVisibility(PR_TRUE);
 
   // Trigger editor re-initialization if midas is turned on in the
   // sub-document. This shouldn't be necessary, but given the way our
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -310,17 +310,17 @@ nsInProcessTabChildGlobal::InitTabChildG
 
   nsISupports* scopeSupports =
     NS_ISUPPORTS_CAST(nsPIDOMEventTarget*, this);
   JS_SetContextPrivate(cx, scopeSupports);
 
   nsresult rv =
     xpc->InitClassesWithNewWrappedGlobal(cx, scopeSupports,
                                          NS_GET_IID(nsISupports),
-                                         GetPrincipal(), EmptyCString(),
+                                         GetPrincipal(), nsnull,
                                          flags, getter_AddRefs(mGlobal));
   NS_ENSURE_SUCCESS(rv, false);
 
   JSObject* global = nsnull;
   rv = mGlobal->GetJSObject(&global);
   NS_ENSURE_SUCCESS(rv, false);
 
   JS_SetGlobalObject(cx, global);
--- a/content/base/src/nsNameSpaceManager.cpp
+++ b/content/base/src/nsNameSpaceManager.cpp
@@ -52,16 +52,18 @@
 
 #ifdef MOZ_XTF
 #include "nsIServiceManager.h"
 #include "nsIXTFService.h"
 #include "nsContentUtils.h"
 static NS_DEFINE_CID(kXTFServiceCID, NS_XTFSERVICE_CID);
 #endif
 
+using namespace mozilla::dom;
+
 #ifdef MOZ_SVG
 PRBool NS_SVGEnabled();
 #endif
 
 #define kXMLNSNameSpaceURI "http://www.w3.org/2000/xmlns/"
 #define kXMLNameSpaceURI "http://www.w3.org/XML/1998/namespace"
 #define kXHTMLNameSpaceURI "http://www.w3.org/1999/xhtml"
 #define kXLinkNameSpaceURI "http://www.w3.org/1999/xlink"
@@ -222,17 +224,17 @@ NameSpaceManagerImpl::GetNameSpaceID(con
     return nameSpaceID;
   }
 
   return kNameSpaceID_Unknown;
 }
 
 nsresult
 NS_NewElement(nsIContent** aResult, PRInt32 aElementType,
-              already_AddRefed<nsINodeInfo> aNodeInfo, PRUint32 aFromParser)
+              already_AddRefed<nsINodeInfo> aNodeInfo, FromParser aFromParser)
 {
   if (aElementType == kNameSpaceID_XHTML) {
     return NS_NewHTMLElement(aResult, aNodeInfo, aFromParser);
   }
 #ifdef MOZ_XUL
   if (aElementType == kNameSpaceID_XUL) {
     return NS_NewXULElement(aResult, aNodeInfo);
   }
--- a/content/base/src/nsScriptElement.h
+++ b/content/base/src/nsScriptElement.h
@@ -54,17 +54,17 @@ public:
   NS_DECL_NSISCRIPTLOADEROBSERVER
 
   // nsIMutationObserver
   NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATACHANGED
   NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
 
-  nsScriptElement(PRUint32 aFromParser)
+  nsScriptElement(mozilla::dom::FromParser aFromParser)
     : nsIScriptElement(aFromParser)
   {
   }
 
 protected:
   // Internal methods
 
   /**
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -152,16 +152,20 @@ nsScriptLoader::nsScriptLoader(nsIDocume
 nsScriptLoader::~nsScriptLoader()
 {
   mObservers.Clear();
 
   if (mParserBlockingRequest) {
     mParserBlockingRequest->FireScriptAvailable(NS_ERROR_ABORT);
   }
 
+  for (PRUint32 i = 0; i < mXSLTRequests.Length(); i++) {
+    mXSLTRequests[i]->FireScriptAvailable(NS_ERROR_ABORT);
+  }
+
   for (PRUint32 i = 0; i < mDeferRequests.Length(); i++) {
     mDeferRequests[i]->FireScriptAvailable(NS_ERROR_ABORT);
   }
 
   for (PRUint32 i = 0; i < mAsyncRequests.Length(); i++) {
     mAsyncRequests[i]->FireScriptAvailable(NS_ERROR_ABORT);
   }
 
@@ -572,50 +576,68 @@ nsScriptLoader::ProcessScriptElement(nsI
     // we now have a request that may or may not be still loading
     if (!async && aElement->GetScriptDeferred()) {
       // We don't want to run this yet.
       // If we come here, the script is a parser-created script and it has
       // the defer attribute but not the async attribute. Since a
       // a parser-inserted script is being run, we came here by the parser
       // running the script, which means the parser is still alive and the
       // parse is ongoing.
-      NS_ASSERTION(mDocument->GetCurrentContentSink(),
-          "Defer script on a document without an active parser; bug 592366.");
+      NS_ASSERTION(mDocument->GetCurrentContentSink() ||
+                   aElement->GetParserCreated() == FROM_PARSER_XSLT,
+          "Non-XSLT Defer script on a document without an active parser; bug 592366.");
       mDeferRequests.AppendElement(request);
       return NS_OK;
     }
     if (async) {
       mAsyncRequests.AppendElement(request);
       if (!request->mLoading) {
         // The script is available already. Run it ASAP when the event
         // loop gets a chance to spin.
         ProcessPendingRequestsAsync();
       }
       return NS_OK;
     }
-    if (!request->mLoading) {
-      // The request has already been loaded. If the script comes from the
-      // network stream, cheat for performance reasons and avoid a trip
-      // through the event loop.
-      if (aElement->GetParserCreated() == NS_FROM_PARSER_NETWORK) {
+
+    if (aElement->GetParserCreated() == FROM_PARSER_XSLT) {
+      // Need to maintain order for XSLT-inserted scripts
+      NS_ASSERTION(!mParserBlockingRequest,
+          "Parser-blocking scripts and XSLT scripts in the same doc!");
+      mXSLTRequests.AppendElement(request);
+      if (!request->mLoading) {
+        // The script is available already. Run it ASAP when the event
+        // loop gets a chance to spin.
+        ProcessPendingRequestsAsync();
+      }
+      return NS_ERROR_HTMLPARSER_BLOCK;
+    }
+    if (!request->mLoading && ReadyToExecuteScripts()) {
+      // The request has already been loaded and there are no pending style
+      // sheets. If the script comes from the network stream, cheat for
+      // performance reasons and avoid a trip through the event loop.
+      if (aElement->GetParserCreated() == FROM_PARSER_NETWORK) {
         return ProcessRequest(request);
       }
       // Otherwise, we've got a document.written script, make a trip through
       // the event loop to hide the preload effects from the scripts on the
       // Web page.
       NS_ASSERTION(!mParserBlockingRequest,
           "There can be only one parser-blocking script at a time");
+      NS_ASSERTION(mXSLTRequests.IsEmpty(),
+          "Parser-blocking scripts and XSLT scripts in the same doc!");
       mParserBlockingRequest = request;
       ProcessPendingRequestsAsync();
       return NS_ERROR_HTMLPARSER_BLOCK;
     }
-    // The script hasn't loaded yet and is parser-inserted and non-async.
-    // It'll be executed when it has loaded.
+    // The script hasn't loaded yet or there's a style sheet blocking it.
+    // The script will be run when it loads or the style sheet loads.
     NS_ASSERTION(!mParserBlockingRequest,
         "There can be only one parser-blocking script at a time");
+    NS_ASSERTION(mXSLTRequests.IsEmpty(),
+        "Parser-blocking scripts and XSLT scripts in the same doc!");
     mParserBlockingRequest = request;
     return NS_ERROR_HTMLPARSER_BLOCK;
   }
 
   // inline script
   nsCOMPtr<nsIContentSecurityPolicy> csp;
   rv = mDocument->NodePrincipal()->GetCsp(getter_AddRefs(csp));
   NS_ENSURE_SUCCESS(rv, rv);
@@ -636,28 +658,38 @@ nsScriptLoader::ProcessScriptElement(nsI
   request = new nsScriptLoadRequest(aElement, version);
   NS_ENSURE_TRUE(request, NS_ERROR_OUT_OF_MEMORY);
   request->mJSVersion = version;
   request->mLoading = PR_FALSE;
   request->mIsInline = PR_TRUE;
   request->mURI = mDocument->GetDocumentURI();
   request->mLineNo = aElement->GetScriptLineNumber();
 
-  if (aElement->GetParserCreated() == NS_NOT_FROM_PARSER) {
+  if (aElement->GetParserCreated() == FROM_PARSER_XSLT &&
+      (!ReadyToExecuteScripts() || !mXSLTRequests.IsEmpty())) {
+    // Need to maintain order for XSLT-inserted scripts
+    NS_ASSERTION(!mParserBlockingRequest,
+        "Parser-blocking scripts and XSLT scripts in the same doc!");
+    mXSLTRequests.AppendElement(request);
+    return NS_ERROR_HTMLPARSER_BLOCK;
+  }
+  if (aElement->GetParserCreated() == NOT_FROM_PARSER) {
     NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),
         "A script-inserted script is inserted without an update batch?");
     nsContentUtils::AddScriptRunner(new nsScriptRequestProcessor(this,
                                                                  request));
     return NS_OK;
   }
-  if (aElement->GetParserCreated() == NS_FROM_PARSER_NETWORK &&
+  if (aElement->GetParserCreated() == FROM_PARSER_NETWORK &&
       !ReadyToExecuteScripts()) {
     NS_ASSERTION(!mParserBlockingRequest,
         "There can be only one parser-blocking script at a time");
     mParserBlockingRequest = request;
+    NS_ASSERTION(mXSLTRequests.IsEmpty(),
+        "Parser-blocking scripts and XSLT scripts in the same doc!");
     return NS_ERROR_HTMLPARSER_BLOCK;
   }
   // We now have a document.written inline script or we have an inline script
   // from the network but there is no style sheet that is blocking scripts.
   // Don't check for style sheets blocking scripts in the document.write
   // case to avoid style sheet network activity affecting when
   // document.write returns. It's not really necessary to do this if
   // there's no document.write currently on the call stack. However,
@@ -851,44 +883,52 @@ nsScriptLoader::ProcessPendingRequests()
   if (mParserBlockingRequest &&
       !mParserBlockingRequest->mLoading &&
       ReadyToExecuteScripts()) {
     request.swap(mParserBlockingRequest);
     // nsContentSink::ScriptAvailable unblocks the parser
     ProcessRequest(request);
   }
 
+  while (ReadyToExecuteScripts() && 
+         !mXSLTRequests.IsEmpty() && 
+         !mXSLTRequests[0]->mLoading) {
+    request.swap(mXSLTRequests[0]);
+    mXSLTRequests.RemoveElementAt(0);
+    ProcessRequest(request);
+  }
+
   PRUint32 i = 0;
   while (mEnabled && i < mAsyncRequests.Length()) {
     if (!mAsyncRequests[i]->mLoading) {
       request.swap(mAsyncRequests[i]);
       mAsyncRequests.RemoveElementAt(i);
       ProcessRequest(request);
       continue;
     }
     ++i;
   }
 
-  if (mDocumentParsingDone) {
+  if (mDocumentParsingDone && mXSLTRequests.IsEmpty()) {
     while (!mDeferRequests.IsEmpty() && !mDeferRequests[0]->mLoading) {
       request.swap(mDeferRequests[0]);
       mDeferRequests.RemoveElementAt(0);
       ProcessRequest(request);
     }
   }
 
   while (!mPendingChildLoaders.IsEmpty() && ReadyToExecuteScripts()) {
     nsRefPtr<nsScriptLoader> child = mPendingChildLoaders[0];
     mPendingChildLoaders.RemoveElementAt(0);
     child->RemoveExecuteBlocker();
   }
 
   if (mDocumentParsingDone && mDocument &&
       !mParserBlockingRequest && mAsyncRequests.IsEmpty() &&
-      mDeferRequests.IsEmpty()) {
+      mXSLTRequests.IsEmpty() && mDeferRequests.IsEmpty()) {
     // No more pending scripts; time to unblock onload.
     // OK to unblock onload synchronously here, since callers must be
     // prepared for the world changing anyway.
     mDocumentParsingDone = PR_FALSE;
     mDocument->UnblockOnload(PR_TRUE);
   }
 }
 
@@ -1048,17 +1088,18 @@ nsScriptLoader::OnStreamComplete(nsIStre
   nsScriptLoadRequest* request = static_cast<nsScriptLoadRequest*>(aContext);
   NS_ASSERTION(request, "null request in stream complete handler");
   NS_ENSURE_TRUE(request, NS_ERROR_FAILURE);
 
   nsresult rv = PrepareLoadedRequest(request, aLoader, aStatus, aStringLen,
                                      aString);
   if (NS_FAILED(rv)) {
     if (mDeferRequests.RemoveElement(request) ||
-        mAsyncRequests.RemoveElement(request)) {
+        mAsyncRequests.RemoveElement(request) ||
+        mXSLTRequests.RemoveElement(request)) {
       FireScriptAvailable(rv, request);
     } else if (mParserBlockingRequest == request) {
       mParserBlockingRequest = nsnull;
       // nsContentSink::ScriptAvailable unblocks the parser
       FireScriptAvailable(rv, request);
     } else {
       mPreloads.RemoveElement(request, PreloadRequestComparator());
     }
@@ -1126,16 +1167,17 @@ nsScriptLoader::PrepareLoadedRequest(nsS
   }
 
   // This assertion could fire errorously if we ran out of memory when
   // inserting the request in the array. However it's an unlikely case
   // so if you see this assertion it is likely something else that is
   // wrong, especially if you see it more than once.
   NS_ASSERTION(mDeferRequests.IndexOf(aRequest) >= 0 ||
                mAsyncRequests.IndexOf(aRequest) >= 0 ||
+               mXSLTRequests.IndexOf(aRequest) >= 0 ||
                mPreloads.Contains(aRequest, PreloadRequestComparator()) ||
                mParserBlockingRequest,
                "aRequest should be pending!");
 
   // Mark this as loaded
   aRequest->mLoading = PR_FALSE;
 
   return NS_OK;
@@ -1178,16 +1220,17 @@ nsScriptLoader::ParsingComplete(PRBool a
     // Have to check because we apparently get ParsingComplete
     // without BeginDeferringScripts in some cases
     mDocumentParsingDone = PR_TRUE;
   }
   mDeferEnabled = PR_FALSE;
   if (aTerminated) {
     mDeferRequests.Clear();
     mAsyncRequests.Clear();
+    mXSLTRequests.Clear();
     mParserBlockingRequest = nsnull;
   }
 
   // Have to call this even if aTerminated so we'll correctly unblock
   // onload and all.
   ProcessPendingRequests();
 }
 
--- a/content/base/src/nsScriptLoader.h
+++ b/content/base/src/nsScriptLoader.h
@@ -294,16 +294,17 @@ private:
                                 nsresult aStatus,
                                 PRUint32 aStringLen,
                                 const PRUint8* aString);
 
   nsIDocument* mDocument;                   // [WEAK]
   nsCOMArray<nsIScriptLoaderObserver> mObservers;
   nsTArray<nsRefPtr<nsScriptLoadRequest> > mAsyncRequests;
   nsTArray<nsRefPtr<nsScriptLoadRequest> > mDeferRequests;
+  nsTArray<nsRefPtr<nsScriptLoadRequest> > mXSLTRequests;
   nsRefPtr<nsScriptLoadRequest> mParserBlockingRequest;
 
   // In mRequests, the additional information here is stored by the element.
   struct PreloadInfo {
     nsRefPtr<nsScriptLoadRequest> mRequest;
     nsString mCharset;
   };
 
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -426,16 +426,23 @@ include $(topsrcdir)/config/rules.mk
 		test_bug578096.html \
 		test_bug598877.html \
 		test_bug600466.html \
 		test_bug600468.html \
 		test_bug600471.html \
 		test_bug601803.html \
 		file_bug601803a.html \
 		file_bug601803b.html \
+		test_bug604660.html \
+		file_bug604660-1.xml \
+		file_bug604660-2.xsl \
+		file_bug604660-3.js \
+		file_bug604660-4.js \
+		file_bug604660-5.xml \
+		file_bug604660-6.xsl \
 		test_bug605982.html \
 		$(NULL)
 
 # This test fails on the Mac for some reason
 ifneq (,$(filter gtk2 windows,$(MOZ_WIDGET_TOOLKIT)))
 _TEST_FILES2 += 	test_copyimage.html \
 		$(NULL)
 endif
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_bug604660-1.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/xsl" href="file_bug604660-2.xsl" ?>
+<placeholder/>
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_bug604660-2.xsl
@@ -0,0 +1,19 @@
+<?xml version="1.0"?>
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
+  <xsl:template match="/">
+    <html>
+      <head>
+        <title>XSLT script execution test</title>
+      </head>
+      <body>
+        <script defer="" src="data:text/javascript,parent.scriptRan(5);"></script>
+        <script>parent.scriptRan(1);</script>
+        <script async="" src="data:text/javascript,parent.asyncRan();"></script>
+        <script src="file_bug604660-3.js"></script>
+        <script>parent.scriptRan(3);</script>
+        <script src="file_bug604660-4.js"></script>        
+      </body>
+    </html>
+  </xsl:template>
+</xsl:stylesheet>
+
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_bug604660-3.js
@@ -0,0 +1,1 @@
+parent.scriptRan(2);
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_bug604660-4.js
@@ -0,0 +1,1 @@
+parent.scriptRan(4);
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_bug604660-5.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0"?>
+<placeholder/>
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_bug604660-6.xsl
@@ -0,0 +1,9 @@
+<?xml version="1.0"?>
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
+  <xsl:template match="/">
+    <html>
+      <script>xsltProcessorCreatedScriptRan();</script>
+    </html>
+  </xsl:template>
+</xsl:stylesheet>
+
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug604660.html
@@ -0,0 +1,77 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=604660
+-->
+<head>
+  <title>Test for Bug 604660</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=604660">Mozilla Bug 604660</a>
+<script>
+SimpleTest.waitForExplicitFinish();
+var asyncState = false;
+var scriptState = 0;
+
+function scriptRan(num) {
+  ++scriptState;
+  is(scriptState, num, "Scripts ran in the wrong sequence.");
+}
+
+function asyncRan() {
+  asyncState = true;
+}
+
+</script>
+<p id="display"><iframe src="file_bug604660-1.xml" onload="iframeloaded()";></iframe></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+var xlstProcessorState = false;
+
+function xsltProcessorCreatedScriptRan() {
+  xlstProcessorState = true;
+}
+
+function iframeloaded() {
+  ok(asyncState, "Async script should have run.");
+  is(scriptState, 5, "Five scripts should have run.");
+
+  var processor = new XSLTProcessor();
+
+  var xhr = new XMLHttpRequest();
+  xhr.onreadystatechange = function() {
+    if (this.readyState == 4) {
+      processor.importStylesheet(this.responseXML);
+      xhr.onreadystatechange = function() {
+        if (this.readyState == 4) {
+          var doc = processor.transformToDocument(this.responseXML);
+          var target = document.getElementById("display");
+          target.appendChild(doc.documentElement.firstChild);
+          ok(!xlstProcessorState, "Scripts created by transformToDocument should not run.");
+
+          var fragment = processor.transformToFragment(this.responseXML, document);
+          target.appendChild(fragment.firstChild.firstChild);
+          ok(xlstProcessorState, "Scripts created by transformToFragment should run.");
+
+          SimpleTest.finish();
+        }
+      }
+      xhr.open("GET", "file_bug604660-5.xml");
+      xhr.send();
+    }
+  }
+  xhr.open("GET", "file_bug604660-6.xsl");
+  xhr.send();
+}
+</script>
+</pre>
+</body>
+</html>
+
--- a/content/base/test/test_x-frame-options.html
+++ b/content/base/test/test_x-frame-options.html
@@ -11,34 +11,45 @@
 <div id="content" style="display: none">
 
 </div>
 
 <iframe style="width:100%;height:300px;" id="harness"></iframe>
 <script class="testbody" type="text/javascript">
 
 var path = "/tests/content/base/test/";
-// contains { test_frame_id : expected_result }
-var testExpectedResults = { "control1": true,
-                            "control2": true,
-                            "deny": false,
-                            "sameorigin1": true,
-                            "sameorigin2": false
-                          };
 
 var testFramesLoaded = function() {
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   var harness = document.getElementById("harness");
 
-  for (var t in testExpectedResults) {
-    var frame = harness.contentDocument.getElementById(t);
-    // test if frame loaded by checking for a contentDocument we can access
-    test = frame.contentDocument.getElementById("test");
-    is(test != null, testExpectedResults[t], "test "+t);
-  }
+  // iframe from same origin, no X-F-O header - should load
+  var frame = harness.contentDocument.getElementById("control1");
+  var test1 = frame.contentDocument.getElementById("test").textContent;
+  is(test1, "control1", "test control1");
+
+  // iframe from different origin, no X-F-O header - should load
+  frame = harness.contentDocument.getElementById("control2");
+  var test2 = frame.contentDocument.getElementById("test").textContent;
+  is(test2, "control2", "test control2");
+
+  // iframe from same origin, X-F-O: DENY - should not load
+  frame = harness.contentDocument.getElementById("deny");
+  var test3 = frame.contentDocument.getElementById("test");
+  is(test3, null, "test deny");
+
+  // iframe from same origin, X-F-O: SAMEORIGIN - should load
+  frame = harness.contentDocument.getElementById("sameorigin1");
+  var test4 = frame.contentDocument.getElementById("test").textContent;
+  is(test4, "sameorigin1", "test sameorigin1");
+
+  // iframe from different origin, X-F-O: SAMEORIGIN - should not load
+  frame = harness.contentDocument.getElementById("sameorigin2");
+  var test5 = frame.contentDocument.getElementById("test");
+  is(test5, null, "test sameorigin2");
 
   // call tests to check principal comparison, e.g. a document can open a window
   // to a data: or javascript: document which frames an
   // X-Frame-Options: SAMEORIGIN document and the frame should load
   testFrameInJSURI();
 }
 
 // test that a document can be framed under a javascript: URL opened by the
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -338,20 +338,20 @@ WebGLContext::SetDimensions(PRInt32 widt
             }
         }
     }
 
     // if we're forcing osmesa, do it first
     if (forceOSMesa) {
         gl = gl::GLContextProviderOSMesa::CreateOffscreen(gfxIntSize(width, height), format);
         if (!gl || !InitAndValidateGL()) {
-            LogMessage("WebGL: OSMesa forced, but creating context failed -- aborting!");
+            LogMessage("OSMesa forced, but creating context failed -- aborting!");
             return NS_ERROR_FAILURE;
         }
-        LogMessage("WebGL: Using software rendering via OSMesa (THIS WILL BE SLOW)");
+        LogMessage("Using software rendering via OSMesa (THIS WILL BE SLOW)");
     }
 
 #ifdef XP_WIN
     // On Windows, we may have a choice of backends, including straight
     // OpenGL, D3D through ANGLE via EGL, or straight EGL/GLES2.
     // We don't differentiate the latter two yet, but we allow for
     // a env var to try EGL first, instead of last; there's also a pref,
     // the env var being set overrides the pref
@@ -394,18 +394,28 @@ WebGLContext::SetDimensions(PRInt32 widt
     if (!gl && useOpenGL) {
         gl = gl::GLContextProvider::CreateOffscreen(gfxIntSize(width, height), format);
         if (gl && !InitAndValidateGL()) {
             gl = nsnull;
         }
     }
 #endif
 
+    // finally, try OSMesa
     if (!gl) {
-        LogMessage("WebGL: Can't get a usable WebGL context");
+        gl = gl::GLContextProviderOSMesa::CreateOffscreen(gfxIntSize(width, height), format);
+        if (!gl || !InitAndValidateGL()) {
+            gl = nsnull;
+        } else {
+            LogMessage("Using software rendering via OSMesa (THIS WILL BE SLOW)");
+        }
+    }
+
+    if (!gl) {
+        LogMessage("Can't get a usable WebGL context");
         return NS_ERROR_FAILURE;
     }
 
 #ifdef DEBUG
     printf_stderr ("--- WebGL context created: %p\n", gl.get());
 #endif
 
     mWidth = width;
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -469,20 +469,17 @@ protected:
     // textures bound to 
     nsTArray<WebGLObjectRefPtr<WebGLTexture> > mBound2DTextures;
     nsTArray<WebGLObjectRefPtr<WebGLTexture> > mBoundCubeMapTextures;
 
     WebGLObjectRefPtr<WebGLBuffer> mBoundArrayBuffer;
     WebGLObjectRefPtr<WebGLBuffer> mBoundElementArrayBuffer;
     WebGLObjectRefPtr<WebGLProgram> mCurrentProgram;
 
-    // XXX these 3 are wrong types, and aren't used atm (except for the length of the attachments)
-    nsTArray<WebGLObjectRefPtr<WebGLTexture> > mFramebufferColorAttachments;
-    nsRefPtr<WebGLFramebuffer> mFramebufferDepthAttachment;
-    nsRefPtr<WebGLFramebuffer> mFramebufferStencilAttachment;
+    PRUint32 mMaxFramebufferColorAttachments;
 
     nsRefPtr<WebGLFramebuffer> mBoundFramebuffer;
     nsRefPtr<WebGLRenderbuffer> mBoundRenderbuffer;
 
     // lookup tables for GL name -> object wrapper
     nsRefPtrHashtable<nsUint32HashKey, WebGLTexture> mMapTextures;
     nsRefPtrHashtable<nsUint32HashKey, WebGLBuffer> mMapBuffers;
     nsRefPtrHashtable<nsUint32HashKey, WebGLProgram> mMapPrograms;
@@ -505,16 +502,17 @@ protected:
 public:
     // console logging helpers
     static void LogMessage(const char *fmt, ...);
     static void LogMessage(const char *fmt, va_list ap);
     void LogMessageIfVerbose(const char *fmt, ...);
     void LogMessageIfVerbose(const char *fmt, va_list ap);
 
     friend class WebGLTexture;
+    friend class WebGLFramebuffer;
 };
 
 // this class is a mixin for the named type wrappers, and is used
 // by WebGLObjectRefPtr to tell the object who holds references, so that
 // we can zero them out appropriately when the object is deleted, because
 // it will be unbound in the GL.
 class WebGLZeroingObject
 {
@@ -998,22 +996,24 @@ public:
 
             PRBool areAllLevel0ImagesDefined = PR_TRUE;
             for (size_t face = 0; face < mFacesCount; ++face) {
                     areAllLevel0ImagesDefined &= ImageInfoAt(0, face).mIsDefined;
             }
 
             if (!areAllLevel0ImagesDefined) {
                 if (mTarget == LOCAL_GL_TEXTURE_2D) {
-                    mContext->LogMessage("We are currently drawing stuff, but some 2D texture has not yet been "
-                                         "uploaded any image at level 0. Until it's uploaded, this texture will look black.");
+                    mContext->LogMessageIfVerbose(
+                        "We are currently drawing stuff, but some 2D texture has not yet been "
+                        "uploaded any image at level 0. Until it's uploaded, this texture will look black.");
                 } else {
-                    mContext->LogMessage("We are currently drawing stuff, but some cube map texture has not yet been "
-                                         "uploaded any image at level 0, for at least one of its six faces. "
-                                         "Until it's uploaded, this texture will look black.");
+                    mContext->LogMessageIfVerbose(
+                        "We are currently drawing stuff, but some cube map texture has not yet been "
+                        "uploaded any image at level 0, for at least one of its six faces. "
+                        "Until it's uploaded, this texture will look black.");
                 }
                 mFakeBlackStatus = DoNeedFakeBlack;
                 return PR_TRUE;
             }
 
             // ok, done with the stupid special cases above. Now actually implementing the cases defined in section 3.8.2.
 
             const char *msg_rendering_as_black
@@ -1229,16 +1229,17 @@ public:
     PRBool NextGeneration()
     {
         if (!(mGeneration+1).valid())
             return PR_FALSE; // must exit without changing mGeneration
         ++mGeneration;
         mMapUniformLocations.Clear();
         return PR_TRUE;
     }
+    
 
     already_AddRefed<WebGLUniformLocation> GetUniformLocationObject(GLint glLocation);
 
     /* Called only after LinkProgram */
     PRBool UpdateInfo(gl::GLContext *gl);
 
     /* Getters for cached program info */
     WebGLint UniformMaxNameLength() const { return mUniformMaxNameLength; }
@@ -1260,84 +1261,371 @@ protected:
     GLint mAttribMaxNameLength;
     GLint mUniformCount;
     GLint mAttribCount;
     std::vector<bool> mAttribsInUse;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(WebGLProgram, WEBGLPROGRAM_PRIVATE_IID)
 
+#define WEBGLRENDERBUFFER_PRIVATE_IID \
+    {0x3cbc2067, 0x5831, 0x4e3f, {0xac, 0x52, 0x7e, 0xf4, 0x5c, 0x04, 0xff, 0xae}}
+class WebGLRenderbuffer :
+    public nsIWebGLRenderbuffer,
+    public WebGLZeroingObject,
+    public WebGLRectangleObject,
+    public WebGLContextBoundObject
+{
+public:
+    NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLRENDERBUFFER_PRIVATE_IID)
+
+    WebGLRenderbuffer(WebGLContext *context, WebGLuint name, WebGLuint secondBufferName = 0) :
+        WebGLContextBoundObject(context),
+        mName(name),
+        mInternalFormat(0),
+        mDeleted(PR_FALSE), mInitialized(PR_FALSE)
+    { }
+
+    void Delete() {
+        if (mDeleted)
+            return;
+        ZeroOwners();
+        mDeleted = PR_TRUE;
+    }
+    PRBool Deleted() const { return mDeleted; }
+    WebGLuint GLName() const { return mName; }
+
+    PRBool Initialized() const { return mInitialized; }
+    void SetInitialized(PRBool aInitialized) { mInitialized = aInitialized; }
+
+    WebGLenum InternalFormat() const { return mInternalFormat; }
+    void SetInternalFormat(WebGLenum aInternalFormat) { mInternalFormat = aInternalFormat; }
+
+    NS_DECL_ISUPPORTS
+    NS_DECL_NSIWEBGLRENDERBUFFER
+
+protected:
+    WebGLuint mName;
+    WebGLenum mInternalFormat;
+
+    PRBool mDeleted;
+    PRBool mInitialized;
+
+    friend class WebGLFramebuffer;
+};
+
+NS_DEFINE_STATIC_IID_ACCESSOR(WebGLRenderbuffer, WEBGLRENDERBUFFER_PRIVATE_IID)
+
 #define WEBGLFRAMEBUFFER_PRIVATE_IID \
     {0x0052a16f, 0x4bc9, 0x4a55, {0x9d, 0xa3, 0x54, 0x95, 0xaa, 0x4e, 0x80, 0xb9}}
 class WebGLFramebuffer :
     public nsIWebGLFramebuffer,
     public WebGLZeroingObject,
     public WebGLRectangleObject,
     public WebGLContextBoundObject
 {
 public:
     NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLFRAMEBUFFER_PRIVATE_IID)
 
     WebGLFramebuffer(WebGLContext *context, WebGLuint name) :
         WebGLContextBoundObject(context),
-        mName(name), mDeleted(PR_FALSE)
+        mName(name), mDeleted(PR_FALSE),
+        mHasDepthAttachment(PR_FALSE),
+        mHasStencilAttachment(PR_FALSE),
+        mHasDepthStencilAttachment(PR_FALSE)
     { }
 
     void Delete() {
         if (mDeleted)
             return;
         ZeroOwners();
         mDeleted = PR_TRUE;
     }
     PRBool Deleted() { return mDeleted; }
     WebGLuint GLName() { return mName; }
 
+    nsresult FramebufferRenderbuffer(WebGLenum target,
+                                     WebGLenum attachment,
+                                     WebGLenum rbtarget,
+                                     nsIWebGLRenderbuffer *rbobj)
+    {
+        WebGLuint renderbuffername;
+        PRBool isNull;
+        WebGLRenderbuffer *wrb;
+
+        if (!mContext->GetConcreteObjectAndGLName("framebufferRenderbuffer: renderbuffer",
+                                                  rbobj, &wrb, &renderbuffername, &isNull))
+        {
+            return NS_OK;
+        }
+
+        if (target != LOCAL_GL_FRAMEBUFFER)
+            return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: target", target);
+
+        if (rbtarget != LOCAL_GL_RENDERBUFFER)
+            return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: renderbuffer target:", rbtarget);
+
+        const char *badAttachmentFormatMsg =
+            "framebufferRenderbuffer: this renderbuffer does not have a suitable format for this attachment point";
+
+        switch (attachment) {
+        case LOCAL_GL_DEPTH_ATTACHMENT:
+            if (!isNull) {
+                if (wrb->mInternalFormat != LOCAL_GL_DEPTH_COMPONENT16)
+                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
+            }
+            mDepthOrStencilRenderbufferAttachment = wrb;
+            mHasDepthAttachment = !isNull;
+            break;
+        case LOCAL_GL_STENCIL_ATTACHMENT:
+            if (!isNull) {
+                if (wrb->mInternalFormat != LOCAL_GL_STENCIL_INDEX8)
+                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
+            }
+            mDepthOrStencilRenderbufferAttachment = wrb;
+            mHasStencilAttachment = !isNull;
+            break;
+        case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
+            if (!isNull) {
+                if (wrb->mInternalFormat != LOCAL_GL_DEPTH_STENCIL)
+                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
+            }
+            mDepthOrStencilRenderbufferAttachment = wrb;
+            mHasDepthStencilAttachment = !isNull;
+            break;
+        default:
+            // finish checking that the 'attachment' parameter is among the allowed values
+            if ((attachment < LOCAL_GL_COLOR_ATTACHMENT0 ||
+                 attachment >= LOCAL_GL_COLOR_ATTACHMENT0 + mContext->mMaxFramebufferColorAttachments))
+            {
+                return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: attachment", attachment);
+            }
+            if (!isNull) {
+                if (wrb->mInternalFormat != LOCAL_GL_RGBA4 &&
+                    wrb->mInternalFormat != LOCAL_GL_RGB565 &&
+                    wrb->mInternalFormat != LOCAL_GL_RGB5_A1)
+                {
+                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
+                }
+            }
+            mColorRenderbufferAttachment = wrb;
+            break;
+        }
+
+        // dimensions are kept for readPixels primarily, function only uses COLOR_ATTACHMENT0
+        if (attachment == LOCAL_GL_COLOR_ATTACHMENT0)
+            setDimensions(wrb);
+
+        mContext->MakeContextCurrent();
+        mContext->gl->fFramebufferRenderbuffer(target, attachment, rbtarget, renderbuffername);
+
+        return NS_OK;
+    }
+
+    nsresult FramebufferTexture2D(WebGLenum target,
+                                  WebGLenum attachment,
+                                  WebGLenum textarget,
+                                  nsIWebGLTexture *tobj,
+                                  WebGLint level)
+    {
+        WebGLuint texturename;
+        PRBool isNull;
+        WebGLTexture *wtex;
+
+        if (!mContext->GetConcreteObjectAndGLName("framebufferTexture2D: texture",
+                                                  tobj, &wtex, &texturename, &isNull))
+        {
+            return NS_OK;
+        }
+
+        if (target != LOCAL_GL_FRAMEBUFFER)
+            return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: target", target);
+
+        if (!isNull && textarget != LOCAL_GL_TEXTURE_2D &&
+            (textarget < LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_X ||
+            textarget > LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z))
+            return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: invalid texture target", textarget);
+
+        if (!isNull && level > 0)
+            return mContext->ErrorInvalidValue("framebufferTexture2D: level must be 0");
+
+        switch (attachment) {
+        case LOCAL_GL_DEPTH_ATTACHMENT:
+        case LOCAL_GL_STENCIL_ATTACHMENT:
+        case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
+            return mContext->ErrorInvalidOperation("framebufferTexture2D: depth and stencil attachments can "
+                          "only be renderbuffers, not textures, as there is no suitable texture format.");
+            break;
+        default:
+            if ((attachment < LOCAL_GL_COLOR_ATTACHMENT0 ||
+                 attachment >= LOCAL_GL_COLOR_ATTACHMENT0 + mContext->mMaxFramebufferColorAttachments))
+            {
+                return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: attachment", attachment);
+            }
+            // nothing to do for color buffers. all textures have a color-renderable format.
+            break;
+        }
+
+        // dimensions are kept for readPixels primarily, function only uses COLOR_ATTACHMENT0
+        if (attachment == LOCAL_GL_COLOR_ATTACHMENT0)
+            setDimensions(wtex);
+
+        mContext->MakeContextCurrent();
+        mContext->gl->fFramebufferTexture2D(target, attachment, textarget, texturename, level);
+
+        return NS_OK;
+    }
+
+    // implement inline, as it's performance critical (called by draw-functions).
+    // the generic case for which we're optimizing is the case where there's nothing to initialize.
+    inline PRBool CheckAndInitializeRenderbuffers()
+    {
+        if (HasConflictingAttachments()) {
+            mContext->SynthesizeGLError(LOCAL_GL_INVALID_FRAMEBUFFER_OPERATION);
+            return PR_FALSE;
+        }
+
+        if ((mColorRenderbufferAttachment          && !mColorRenderbufferAttachment->Initialized()) ||
+            (mDepthOrStencilRenderbufferAttachment && !mDepthOrStencilRenderbufferAttachment->Initialized()))
+        {
+            InitializeRenderbuffers();
+        }
+
+        return PR_TRUE;
+    }
+
     NS_DECL_ISUPPORTS
     NS_DECL_NSIWEBGLFRAMEBUFFER
+
+    PRBool HasConflictingAttachments() const {
+        return int(mHasDepthAttachment) +
+               int(mHasStencilAttachment) +
+               int(mHasDepthStencilAttachment) > 1;
+    }
+
 protected:
+
+    // protected because WebGLContext should only call InitializeRenderbuffers
+    void InitializeRenderbuffers()
+    {
+        mContext->MakeContextCurrent();
+
+        if (mContext->gl->fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER) != LOCAL_GL_FRAMEBUFFER_COMPLETE)
+            return;
+
+        PRBool initializeColorBuffer = mColorRenderbufferAttachment &&
+                                       !mColorRenderbufferAttachment->Initialized();
+        PRBool initializeDepthOrStencilBuffer = mDepthOrStencilRenderbufferAttachment &&
+                                                !mDepthOrStencilRenderbufferAttachment->Initialized();
+        PRBool initializeDepthBuffer = initializeDepthOrStencilBuffer && HasDepthBuffer();
+        PRBool initializeStencilBuffer = initializeDepthOrStencilBuffer && HasStencilBuffer();
+
+        realGLboolean savedColorMask[] = {0}, savedDepthMask = 0;
+        GLuint savedStencilMask = 0;
+        GLfloat savedColorClearValue[] = {0.f}, savedDepthClearValue = 0.f;
+        GLint savedStencilClearValue = 0;
+        GLuint clearBits = 0;
+
+        realGLboolean wasScissorTestEnabled = mContext->gl->fIsEnabled(LOCAL_GL_SCISSOR_TEST);
+        mContext->gl->fDisable(LOCAL_GL_SCISSOR_TEST);
+
+        realGLboolean wasDitherEnabled = mContext->gl->fIsEnabled(LOCAL_GL_DITHER);
+        mContext->gl->fDisable(LOCAL_GL_DITHER);
+
+        mContext->gl->PushViewportRect(nsIntRect(0,0,width(),height()));
+
+        if (initializeColorBuffer) {
+            mContext->gl->fGetBooleanv(LOCAL_GL_COLOR_WRITEMASK, savedColorMask);
+            mContext->gl->fGetFloatv(LOCAL_GL_COLOR_CLEAR_VALUE, savedColorClearValue);
+            mContext->gl->fColorMask(1, 1, 1, 1);
+            mContext->gl->fClearColor(0.f, 0.f, 0.f, 0.f);
+            clearBits |= LOCAL_GL_COLOR_BUFFER_BIT;
+        }
+
+        if (initializeDepthBuffer) {
+            mContext->gl->fGetBooleanv(LOCAL_GL_DEPTH_WRITEMASK, &savedDepthMask);
+            mContext->gl->fGetFloatv(LOCAL_GL_DEPTH_CLEAR_VALUE, &savedDepthClearValue);
+            mContext->gl->fDepthMask(1);
+            mContext->gl->fClearDepth(0.f);
+            clearBits |= LOCAL_GL_DEPTH_BUFFER_BIT;
+        }
+
+        if (initializeStencilBuffer) {
+            mContext->gl->fGetIntegerv(LOCAL_GL_STENCIL_WRITEMASK, reinterpret_cast<GLint*>(&savedStencilMask));
+            mContext->gl->fGetIntegerv(LOCAL_GL_STENCIL_CLEAR_VALUE, &savedStencilClearValue);
+            mContext->gl->fStencilMask(0xffffffff);
+            mContext->gl->fClearStencil(0);
+            clearBits |= LOCAL_GL_STENCIL_BUFFER_BIT;
+        }
+
+        // the one useful line of code
+        mContext->gl->fClear(clearBits);
+
+        if (initializeColorBuffer) {
+            mContext->gl->fColorMask(savedColorMask[0],
+                                     savedColorMask[1],
+                                     savedColorMask[2],
+                                     savedColorMask[3]);
+            mContext->gl->fClearColor(savedColorClearValue[0],
+                                      savedColorClearValue[1],
+                                      savedColorClearValue[2],
+                                      savedColorClearValue[3]);
+            mColorRenderbufferAttachment->SetInitialized(PR_TRUE);
+        }
+
+        if (initializeDepthBuffer) {
+            mContext->gl->fDepthMask(savedDepthMask);
+            mContext->gl->fClearDepth(savedDepthClearValue);
+            mDepthOrStencilRenderbufferAttachment->SetInitialized(PR_TRUE);
+        }
+
+        if (initializeStencilBuffer) {
+            mContext->gl->fStencilMask(savedStencilMask);
+            mContext->gl->fClearStencil(savedStencilClearValue);
+            mDepthOrStencilRenderbufferAttachment->SetInitialized(PR_TRUE);
+        }
+
+        mContext->gl->PopViewportRect();
+
+        if (wasDitherEnabled)
+            mContext->gl->fEnable(LOCAL_GL_DITHER);
+        else
+            mContext->gl->fDisable(LOCAL_GL_DITHER);
+
+        if (wasScissorTestEnabled)
+            mContext->gl->fEnable(LOCAL_GL_DITHER);
+        else
+            mContext->gl->fDisable(LOCAL_GL_SCISSOR_TEST);
+    }
+
+    PRBool HasDepthBuffer() const {
+        return mHasDepthAttachment || mHasDepthStencilAttachment;
+    }
+
+    PRBool HasStencilBuffer() const {
+        return mHasStencilAttachment || mHasDepthStencilAttachment;
+    }
+
     WebGLuint mName;
     PRBool mDeleted;
+
+    // we only store pointers to attached renderbuffers, not to attached textures, because
+    // we will only need to initialize renderbuffers. Textures are already initialized.
+    nsRefPtr<WebGLRenderbuffer> mColorRenderbufferAttachment;
+    nsRefPtr<WebGLRenderbuffer> mDepthOrStencilRenderbufferAttachment;
+
+    // these boolean values keep track of all attachments: renderbuffers and textures.
+    // thus they are not at all redundant with the above member pointers.
+    PRBool mHasDepthAttachment;
+    PRBool mHasStencilAttachment;
+    PRBool mHasDepthStencilAttachment;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(WebGLFramebuffer, WEBGLFRAMEBUFFER_PRIVATE_IID)
 
-#define WEBGLRENDERBUFFER_PRIVATE_IID \
-    {0x3cbc2067, 0x5831, 0x4e3f, {0xac, 0x52, 0x7e, 0xf4, 0x5c, 0x04, 0xff, 0xae}}
-class WebGLRenderbuffer :
-    public nsIWebGLRenderbuffer,
-    public WebGLZeroingObject,
-    public WebGLRectangleObject,
-    public WebGLContextBoundObject
-{
-public:
-    NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLRENDERBUFFER_PRIVATE_IID)
-
-    WebGLRenderbuffer(WebGLContext *context, WebGLuint name) :
-        WebGLContextBoundObject(context),
-        mName(name), mDeleted(PR_FALSE)
-    { }
-
-    void Delete() {
-        if (mDeleted)
-            return;
-        ZeroOwners();
-        mDeleted = PR_TRUE;
-    }
-    PRBool Deleted() { return mDeleted; }
-    WebGLuint GLName() { return mName; }
-
-    NS_DECL_ISUPPORTS
-    NS_DECL_NSIWEBGLRENDERBUFFER
-protected:
-    WebGLuint mName;
-    PRBool mDeleted;
-};
-
-NS_DEFINE_STATIC_IID_ACCESSOR(WebGLRenderbuffer, WEBGLRENDERBUFFER_PRIVATE_IID)
-
 #define WEBGLUNIFORMLOCATION_PRIVATE_IID \
     {0x01a8a614, 0xb109, 0x42f1, {0xb4, 0x40, 0x8d, 0x8b, 0x87, 0x0b, 0x43, 0xa7}}
 class WebGLUniformLocation :
     public nsIWebGLUniformLocation,
     public WebGLZeroingObject,
     public WebGLContextBoundObject
 {
 public:
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -344,17 +344,17 @@ WebGLContext::BlendFuncSeparate(WebGLenu
     gl->fBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BufferData(PRInt32 dummy)
 {
     // this should never be called
-    LogMessage("BufferData");
+    LogMessageIfVerbose("BufferData");
     return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
 WebGLContext::BufferData_size(WebGLenum target, WebGLsizei size, WebGLenum usage)
 {
     WebGLBuffer *boundBuffer = NULL;
 
@@ -517,26 +517,34 @@ WebGLContext::BufferSubData_array(WebGLe
 
 NS_IMETHODIMP
 WebGLContext::CheckFramebufferStatus(WebGLenum target, WebGLenum *retval)
 {
     *retval = 0;
 
     MakeContextCurrent();
     if (target != LOCAL_GL_FRAMEBUFFER)
-        return ErrorInvalidEnum("CheckFramebufferStatus: target must be FRAMEBUFFER");
-
-    *retval = gl->fCheckFramebufferStatus(target);
+        return ErrorInvalidEnum("checkFramebufferStatus: target must be FRAMEBUFFER");
+
+    if (mBoundFramebuffer && mBoundFramebuffer->HasConflictingAttachments())
+        *retval = LOCAL_GL_FRAMEBUFFER_UNSUPPORTED;
+    else
+        *retval = gl->fCheckFramebufferStatus(target);
+
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::Clear(PRUint32 mask)
 {
     MakeContextCurrent();
+
+    if (mBoundFramebuffer && !mBoundFramebuffer->CheckAndInitializeRenderbuffers())
+        return NS_OK;
+
     gl->fClear(mask);
     Invalidate();
 
     return NS_OK;
 }
 
 GL_SAME_METHOD_4(ClearColor, ClearColor, WebGLfloat, WebGLfloat, WebGLfloat, WebGLfloat)
 
@@ -755,16 +763,17 @@ WebGLContext::DeleteRenderbuffer(nsIWebG
             must be taken when deleting a renderbuffer object if the image of the renderbuffer
             is attached to a framebuffer object. In this case, if the deleted renderbuffer object is
             attached to the currently bound framebuffer object, it is 
             automatically detached.  However, attachments to any other framebuffer objects are the
             responsibility of the application.
     */
 
     gl->fDeleteRenderbuffers(1, &rbufname);
+
     rbuf->Delete();
     mMapRenderbuffers.Remove(rbufname);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::DeleteTexture(nsIWebGLTexture *tobj)
@@ -1042,16 +1051,19 @@ WebGLContext::DrawArrays(GLenum mode, We
         return ErrorInvalidOperation("DrawArrays: bound vertex attribute buffers do not have sufficient size for given first and count");
 
     // If count is 0, there's nothing to do.
     if (count == 0)
         return NS_OK;
 
     MakeContextCurrent();
 
+    if (mBoundFramebuffer && !mBoundFramebuffer->CheckAndInitializeRenderbuffers())
+        return NS_OK;
+
     BindFakeBlackTextures();
     DoFakeVertexAttrib0(checked_firstPlusCount.value());
 
     gl->fDrawArrays(mode, first, count);
 
     UndoFakeVertexAttrib0();
     UnbindFakeBlackTextures();
 
@@ -1119,16 +1131,19 @@ WebGLContext::DrawElements(WebGLenum mod
     }
 
     // If count is 0, there's nothing to do.
     if (count == 0)
         return NS_OK;
 
     MakeContextCurrent();
 
+    if (mBoundFramebuffer && !mBoundFramebuffer->CheckAndInitializeRenderbuffers())
+        return NS_OK;
+
     BindFakeBlackTextures();
     DoFakeVertexAttrib0(checked_neededCount.value());
 
     gl->fDrawElements(mode, count, type, (GLvoid*) (byteOffset));
 
     UndoFakeVertexAttrib0();
     UnbindFakeBlackTextures();
 
@@ -1166,100 +1181,36 @@ WebGLContext::EnableVertexAttribArray(We
     MakeContextCurrent();
 
     gl->fEnableVertexAttribArray(index);
     mAttribBuffers[index].enabled = PR_TRUE;
 
     return NS_OK;
 }
 
-// XXX need to track this -- see glDeleteRenderbuffer above and man page for DeleteRenderbuffers
 NS_IMETHODIMP
 WebGLContext::FramebufferRenderbuffer(WebGLenum target, WebGLenum attachment, WebGLenum rbtarget, nsIWebGLRenderbuffer *rbobj)
 {
-    WebGLuint renderbuffername;
-    PRBool isNull;
-    WebGLRenderbuffer *wrb;
-
-    if (!GetConcreteObjectAndGLName("framebufferRenderbuffer: renderbuffer", rbobj, &wrb, &renderbuffername, &isNull))
-        return NS_OK;
-
-    if (target != LOCAL_GL_FRAMEBUFFER)
-        return ErrorInvalidEnumInfo("framebufferRenderbuffer: target", target);
-
-    if ((attachment < LOCAL_GL_COLOR_ATTACHMENT0 ||
-         attachment >= LOCAL_GL_COLOR_ATTACHMENT0 + mFramebufferColorAttachments.Length()) &&
-        attachment != LOCAL_GL_DEPTH_ATTACHMENT &&
-        attachment != LOCAL_GL_STENCIL_ATTACHMENT)
-    {
-        return ErrorInvalidEnumInfo("framebufferRenderbuffer: attachment", attachment);
-    }
-
-    if (rbtarget != LOCAL_GL_RENDERBUFFER)
-        return ErrorInvalidEnumInfo("framebufferRenderbuffer: renderbuffer target:", rbtarget);
-
-    if (!mBoundFramebuffer)
-        return ErrorInvalidOperation("FramebufferRenderbuffer: cannot modify framebuffer 0");
-
-    // dimensions are kept for readPixels primarily, function only uses COLOR_ATTACHMENT0
-    if (attachment == LOCAL_GL_COLOR_ATTACHMENT0)
-        mBoundFramebuffer->setDimensions(wrb);
-
-    MakeContextCurrent();
-
-    gl->fFramebufferRenderbuffer(target, attachment, rbtarget, renderbuffername);
-
-    return NS_OK;
+    if (mBoundFramebuffer)
+        return mBoundFramebuffer->FramebufferRenderbuffer(target, attachment, rbtarget, rbobj);
+    else
+        return ErrorInvalidOperation("framebufferRenderbuffer: cannot modify framebuffer 0");
 }
 
 NS_IMETHODIMP
 WebGLContext::FramebufferTexture2D(WebGLenum target,
                                    WebGLenum attachment,
                                    WebGLenum textarget,
                                    nsIWebGLTexture *tobj,
                                    WebGLint level)
 {
-    WebGLuint texturename;
-    PRBool isNull;
-    WebGLTexture *wtex;
-
-    if (!GetConcreteObjectAndGLName("framebufferTexture2D: texture", tobj, &wtex, &texturename, &isNull))
-        return NS_OK;
-
-    if (target != LOCAL_GL_FRAMEBUFFER)
-        return ErrorInvalidEnumInfo("framebufferTexture2D: target", target);
-
-    if ((attachment < LOCAL_GL_COLOR_ATTACHMENT0 ||
-         attachment >= LOCAL_GL_COLOR_ATTACHMENT0 + mFramebufferColorAttachments.Length()) &&
-        attachment != LOCAL_GL_DEPTH_ATTACHMENT &&
-        attachment != LOCAL_GL_STENCIL_ATTACHMENT)
-        return ErrorInvalidEnumInfo("framebufferTexture2D: attachment", attachment);
-
-    if (textarget != LOCAL_GL_TEXTURE_2D &&
-        (textarget < LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_X ||
-         textarget > LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z))
-        return ErrorInvalidEnumInfo("framebufferTexture2D: invalid texture target", textarget);
-
-    if (level != 0)
-        return ErrorInvalidValue("FramebufferTexture2D: level must be 0");
-
-    if (!mBoundFramebuffer)
-        return ErrorInvalidOperation("FramebufferTexture2D: cannot modify framebuffer 0");
-
-    // dimensions are kept for readPixels primarily, function only uses COLOR_ATTACHMENT0
-    if (attachment == LOCAL_GL_COLOR_ATTACHMENT0)
-        mBoundFramebuffer->setDimensions(wtex);
-
-    // XXXXX we need to store/reference this attachment!
-
-    MakeContextCurrent();
-
-    gl->fFramebufferTexture2D(target, attachment, textarget, texturename, level);
-
-    return NS_OK;
+    if (mBoundFramebuffer)
+        return mBoundFramebuffer->FramebufferTexture2D(target, attachment, textarget, tobj, level);
+    else
+        return ErrorInvalidOperation("framebufferTexture2D: cannot modify framebuffer 0");
 }
 
 GL_SAME_METHOD_0(Flush, Flush)
 
 GL_SAME_METHOD_0(Finish, Finish)
 
 NS_IMETHODIMP
 WebGLContext::FrontFace(WebGLenum mode)
@@ -1634,17 +1585,17 @@ WebGLContext::GetParameter(PRUint32 pnam
             wrval->SetAsArray(nsIDataType::VTYPE_INT32, nsnull,
                               2, static_cast<void*>(iv));
         }
             break;
 
         case LOCAL_GL_SCISSOR_BOX: // 4 ints
         case LOCAL_GL_VIEWPORT: // 4 ints
         {
-            GLint iv[2] = { 0 };
+            GLint iv[4] = { 0 };
             gl->fGetIntegerv(pname, iv);
             wrval->SetAsArray(nsIDataType::VTYPE_INT32, nsnull,
                               4, static_cast<void*>(iv));
         }
             break;
 
         case LOCAL_GL_COLOR_WRITEMASK: // 4 bools
         {
@@ -2535,18 +2486,16 @@ WebGLContext::ReadPixels_base(WebGLint x
 //         case LOCAL_GL_UNSIGNED_SHORT_5_5_5_1:
 //         case LOCAL_GL_UNSIGNED_SHORT_5_6_5:
       case LOCAL_GL_UNSIGNED_BYTE:
         break;
       default:
         return ErrorInvalidEnumInfo("ReadPixels: type", type);
     }
 
-    MakeContextCurrent();
-
     CheckedUint32 checked_plainRowSize = CheckedUint32(width) * size;
 
     PRUint32 packAlignment = mPixelStorePackAlignment;
 
     // alignedRowSize = row size rounded up to next multiple of packAlignment
     CheckedUint32 checked_alignedRowSize
         = ((checked_plainRowSize + packAlignment-1) / packAlignment) * packAlignment;
 
@@ -2554,16 +2503,22 @@ WebGLContext::ReadPixels_base(WebGLint x
         = (height-1) * checked_alignedRowSize + checked_plainRowSize;
 
     if (!checked_neededByteLength.valid())
         return ErrorInvalidOperation("ReadPixels: integer overflow computing the needed buffer size");
 
     if (checked_neededByteLength.value() > byteLength)
         return ErrorInvalidOperation("ReadPixels: buffer too small");
 
+    MakeContextCurrent();
+
+    // prevent readback of arbitrary video memory through uninitialized renderbuffers!
+    if (mBoundFramebuffer && !mBoundFramebuffer->CheckAndInitializeRenderbuffers())
+        return NS_OK;
+
     if (CanvasUtils::CheckSaneSubrectSize(x, y, width, height, boundWidth, boundHeight)) {
         // the easy case: we're not reading out-of-range pixels
         gl->fReadPixels(x, y, width, height, format, type, data);
     } else {
         // the rectangle doesn't fit entirely in the bound buffer. We then have to set to zero the part
         // of the buffer that correspond to out-of-range pixels. We don't want to rely on system OpenGL
         // to do that for us, because passing out of range parameters to a buggy OpenGL implementation
         // could conceivably allow to read memory we shouldn't be allowed to read. So we manually initialize
@@ -2640,42 +2595,67 @@ WebGLContext::ReadPixels_buf(WebGLint x,
     return ReadPixels_base(x, y, width, height, format, type,
                            pixels ? pixels->data : 0,
                            pixels ? pixels->byteLength : 0);
 }
 
 NS_IMETHODIMP
 WebGLContext::RenderbufferStorage(WebGLenum target, WebGLenum internalformat, WebGLsizei width, WebGLsizei height)
 {
+
+    if (!mBoundRenderbuffer || !mBoundRenderbuffer->GLName())
+        return ErrorInvalidOperation("renderbufferStorage called on renderbuffer 0");
+
     if (target != LOCAL_GL_RENDERBUFFER)
-        return ErrorInvalidEnumInfo("RenderbufferStorage: target", target);
+        return ErrorInvalidEnumInfo("renderbufferStorage: target", target);
+
+    if (width <= 0 || height <= 0)
+        return ErrorInvalidValue("renderbufferStorage: width and height must be > 0");
+
+    if (!mBoundRenderbuffer || !mBoundRenderbuffer->GLName())
+        return ErrorInvalidOperation("renderbufferStorage called on renderbuffer 0");
+
+    MakeContextCurrent();
+
+    // certain OpenGL ES renderbuffer formats may not exist on desktop OpenGL
+    WebGLenum internalformatForGL = internalformat;
 
     switch (internalformat) {
-      case LOCAL_GL_RGBA4:
-      // XXX case LOCAL_GL_RGB565:
-      case LOCAL_GL_RGB5_A1:
-      case LOCAL_GL_DEPTH_COMPONENT:
-      case LOCAL_GL_DEPTH_COMPONENT16:
-      case LOCAL_GL_STENCIL_INDEX8:
-          break;
-      default:
-          return ErrorInvalidEnumInfo("RenderbufferStorage: internalformat", internalformat);
+    case LOCAL_GL_RGBA4:
+    case LOCAL_GL_RGB5_A1:
+        // 16-bit RGBA formats are not supported on desktop GL
+        if (!gl->IsGLES2()) internalformatForGL = LOCAL_GL_RGBA8;
+        break;
+    case LOCAL_GL_RGB565:
+        // the RGB565 format is not supported on desktop GL
+        if (!gl->IsGLES2()) internalformatForGL = LOCAL_GL_RGB8;
+        break;
+    case LOCAL_GL_DEPTH_COMPONENT16:
+    case LOCAL_GL_STENCIL_INDEX8:
+        // nothing to do for these ones
+        break;
+    case LOCAL_GL_DEPTH_STENCIL:
+        // this one is available in newer OpenGL (at least since 3.1); will probably become available
+        // in OpenGL ES 3 (at least it will have some DEPTH_STENCIL) and is the same value that
+        // is otherwise provided by EXT_packed_depth_stencil and OES_packed_depth_stencil extensions
+        // which means it's supported on most GL and GL ES systems already.
+        //
+        // So we just use it hoping that it's available (perhaps as an extension) and if it's not available,
+        // we just let the GL generate an error and don't do anything about it ourselves.
+        internalformatForGL = LOCAL_GL_DEPTH24_STENCIL8;
+        break;
+    default:
+        ErrorInvalidEnumInfo("renderbufferStorage: internalformat", internalformat);
     }
 
-    if (width <= 0 || height <= 0)
-        return ErrorInvalidValue("RenderbufferStorage: width and height must be > 0");
-
-    if (mBoundRenderbuffer)
-        mBoundRenderbuffer->setDimensions(width, height);
-
-    MakeContextCurrent();
-    gl->fRenderbufferStorage(target, internalformat, width, height);
-
-    // now we need to initialize the renderbuffer to 0 as per the thread "about RenderBufferStorage"
-    // on the public_webgl list
+    gl->fRenderbufferStorage(target, internalformatForGL, width, height);
+
+    mBoundRenderbuffer->SetInternalFormat(internalformat);
+    mBoundRenderbuffer->setDimensions(width, height);
+    mBoundRenderbuffer->SetInitialized(PR_FALSE);
 
     return NS_OK;
 }
 
 GL_SAME_METHOD_2(SampleCoverage, SampleCoverage, WebGLfloat, WebGLboolean)
 
 NS_IMETHODIMP
 WebGLContext::Scissor(WebGLint x, WebGLint y, WebGLsizei width, WebGLsizei height)
@@ -3178,16 +3158,24 @@ NS_IMETHODIMP
 WebGLContext::ValidateProgram(nsIWebGLProgram *pobj)
 {
     WebGLuint progname;
     if (!GetGLName<WebGLProgram>("validateProgram", pobj, &progname))
         return NS_OK;
 
     MakeContextCurrent();
 
+#ifdef XP_MACOSX
+    if (gl->Vendor() == gl::GLContext::VendorNVIDIA) {
+        LogMessageIfVerbose("validateProgram: implemented as a no-operation "
+                            "on Mac/NVIDIA to work around a driver crash");
+        return NS_OK;
+    }
+#endif
+
     gl->fValidateProgram(progname);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::CreateFramebuffer(nsIWebGLFramebuffer **retval)
 {
@@ -3240,17 +3228,16 @@ WebGLContext::CompileShader(nsIWebGLShad
     WebGLuint shadername;
     if (!GetConcreteObjectAndGLName("compileShader", sobj, &shader, &shadername))
         return NS_OK;
     MakeContextCurrent();
 
 #if defined(USE_ANGLE)
     if (shader->NeedsTranslation() && mShaderValidation) {
         ShHandle compiler = 0;
-        int debugFlags = 0;
         ShBuiltInResources resources;
         memset(&resources, 0, sizeof(ShBuiltInResources));
 
         resources.MaxVertexAttribs = mGLMaxVertexAttribs;
         resources.MaxVertexUniformVectors = mGLMaxVertexUniformVectors;
         resources.MaxVaryingVectors = mGLMaxVaryingVectors;
         resources.MaxVertexTextureImageUnits = mGLMaxVertexTextureImageUnits;
         resources.MaxCombinedTextureImageUnits = mGLMaxTextureUnits;
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -357,20 +357,16 @@ WebGLContext::InitAndValidateGL()
     mUniformTextures.Clear();
     mBound2DTextures.Clear();
     mBoundCubeMapTextures.Clear();
 
     mBoundArrayBuffer = nsnull;
     mBoundElementArrayBuffer = nsnull;
     mCurrentProgram = nsnull;
 
-    mFramebufferColorAttachments.Clear();
-    mFramebufferDepthAttachment = nsnull;
-    mFramebufferStencilAttachment = nsnull;
-
     mBoundFramebuffer = nsnull;
     mBoundRenderbuffer = nsnull;
 
     mMapTextures.Clear();
     mMapBuffers.Clear();
     mMapPrograms.Clear();
     mMapShaders.Clear();
     mMapFramebuffers.Clear();
@@ -428,17 +424,17 @@ WebGLContext::InitAndValidateGL()
 #if 0
     // Leaving this code in here, even though it's ifdef'd out, for
     // when we support more than 1 color attachment.
     gl->fGetIntegerv(LOCAL_GL_MAX_COLOR_ATTACHMENTS, (GLint*) &val);
 #else
     // Always 1 for GLES2
     val = 1;
 #endif
-    mFramebufferColorAttachments.SetLength(val);
+    mMaxFramebufferColorAttachments = val;
 
 #if defined(DEBUG_vladimir) && defined(USE_GLES2)
     gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_FORMAT, (GLint*) &val);
     fprintf(stderr, "GL_IMPLEMENTATION_COLOR_READ_FORMAT: 0x%04x\n", val);
 
     gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_TYPE, (GLint*) &val);
     fprintf(stderr, "GL_IMPLEMENTATION_COLOR_READ_TYPE: 0x%04x\n", val);
 #endif
--- a/content/canvas/test/webgl/failing_tests.txt
+++ b/content/canvas/test/webgl/failing_tests.txt
@@ -1,27 +1,22 @@
 conformance/canvas-test.html
 conformance/constants.html
 conformance/context-attributes-alpha-depth-stencil-antialias.html
 conformance/context-attributes.html
 conformance/context-type-test.html
-conformance/framebuffer-object-attachment.html
-conformance/get-active-test.html
-conformance/gl-enum-tests.html
 conformance/gl-get-calls.html
 conformance/gl-teximage.html
 conformance/glsl-conformance.html
 conformance/methods.html
 conformance/program-test.html
 conformance/read-pixels-pack-alignment.html
 conformance/tex-image-and-sub-image-2d-with-video.html
-conformance/tex-image-with-format-and-type.html
 conformance/tex-image-with-invalid-data.html
 conformance/tex-input-validation.html
-conformance/texture-active-bind.html
 more/conformance/constants.html
 more/conformance/getContext.html
 more/conformance/quickCheckAPI.html
 more/conformance/quickCheckAPIBadArgs.html
 more/functions/bufferDataBadArgs.html
 more/functions/copyTexImage2D.html
 more/functions/copyTexImage2DBadArgs.html
 more/functions/copyTexSubImage2D.html
--- a/content/html/content/public/nsHTMLAudioElement.h
+++ b/content/html/content/public/nsHTMLAudioElement.h
@@ -46,17 +46,17 @@ typedef PRUint16 nsMediaNetworkState;
 typedef PRUint16 nsMediaReadyState;
 
 class nsHTMLAudioElement : public nsHTMLMediaElement,
                            public nsIDOMHTMLAudioElement,
                            public nsIJSNativeInitializer
 {
 public:
   nsHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     PRUint32 aFromParser = 0);
+                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLAudioElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsHTMLMediaElement::)
 
--- a/content/html/content/public/nsHTMLMediaElement.h
+++ b/content/html/content/public/nsHTMLMediaElement.h
@@ -66,17 +66,17 @@ class nsHTMLMediaElement : public nsGene
 public:
   enum CanPlayStatus {
     CANPLAY_NO,
     CANPLAY_MAYBE,
     CANPLAY_YES
   };
 
   nsHTMLMediaElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     PRUint32 aFromParser = 0);
+                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLMediaElement();
 
   /**
    * This is used when the browser is constructing a video element to play
    * a channel that we've already started loading. The src attribute and
    * <source> children are ignored.
    * @param aChannel the channel to use
    * @param aListener returns a stream listener that should receive
--- a/content/html/content/public/nsHTMLVideoElement.h
+++ b/content/html/content/public/nsHTMLVideoElement.h
@@ -41,17 +41,17 @@
 #include "nsIDOMHTMLVideoElement.h"
 #include "nsHTMLMediaElement.h"
 
 class nsHTMLVideoElement : public nsHTMLMediaElement,
                            public nsIDOMHTMLVideoElement
 {
 public:
   nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     PRUint32 aFromParser = 0);
+                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLVideoElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsHTMLMediaElement::)
 
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -2317,16 +2317,20 @@ nsGenericHTMLFormElement::nsGenericHTMLF
   : nsGenericHTMLElement(aNodeInfo)
   , mForm(nsnull)
   , mFieldSet(nsnull)
 {
 }
 
 nsGenericHTMLFormElement::~nsGenericHTMLFormElement()
 {
+  if (mFieldSet) {
+    static_cast<nsHTMLFieldSetElement*>(mFieldSet)->RemoveElement(this);
+  }
+
   // Check that this element doesn't know anything about its form at this point.
   NS_ASSERTION(!mForm, "mForm should be null at this point!");
 }
 
 NS_IMPL_QUERY_INTERFACE_INHERITED1(nsGenericHTMLFormElement,
                                    nsGenericHTMLElement,
                                    nsIFormControl)
 
@@ -2934,23 +2938,30 @@ nsGenericHTMLFormElement::UpdateFieldSet
 
   for (parent = GetParent(); parent;
        prev = parent, parent = parent->GetParent()) {
     if (parent->IsHTML(nsGkAtoms::fieldset)) {
       nsHTMLFieldSetElement* fieldset =
         static_cast<nsHTMLFieldSetElement*>(parent);
 
       if (!prev || fieldset->GetFirstLegend() != prev) {
+        if (mFieldSet) {
+          static_cast<nsHTMLFieldSetElement*>(mFieldSet)->RemoveElement(this);
+        }
         mFieldSet = fieldset;
+        fieldset->AddElement(this);
         return;
       }
     }
   }
 
   // No fieldset found.
+  if (mFieldSet) {
+    static_cast<nsHTMLFieldSetElement*>(mFieldSet)->RemoveElement(this);
+  }
   mFieldSet = nsnull;
 }
 
 void
 nsGenericHTMLFormElement::FieldSetDisabledChanged(nsEventStates aStates, PRBool aNotify)
 {
   if (!aNotify) {
     return;
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -870,16 +870,29 @@ public:
     UpdateFieldSet();
 
     // The disabled state may have change because the element might not be in
     // the first legend anymore.
     FieldSetDisabledChanged(nsEventStates(), aNotify);
   }
 
   /**
+   * This callback is called by a fieldset on all it's elements when it's being
+   * destroyed. When called, the elements should check that aFieldset is there
+   * first parent fieldset and null mFieldset in that case only.
+   *
+   * @param aFieldSet The fieldset being removed.
+   */
+  void ForgetFieldSet(nsIContent* aFieldset) {
+    if (mFieldSet == aFieldset) {
+      mFieldSet = nsnull;
+    }
+  }
+
+  /**
    * Returns if the control can be disabled.
    */
   PRBool CanBeDisabled() const;
 
 protected:
   virtual nsresult BeforeSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                                  const nsAString* aValue, PRBool aNotify);
 
@@ -982,20 +995,20 @@ PR_STATIC_ASSERT(ELEMENT_TYPE_SPECIFIC_B
  */
 
 class nsGenericHTMLFrameElement : public nsGenericHTMLElement,
                                   public nsIDOMNSHTMLFrameElement,
                                   public nsIFrameLoaderOwner
 {
 public:
   nsGenericHTMLFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                            PRUint32 aFromParser)
+                            mozilla::dom::FromParser aFromParser)
     : nsGenericHTMLElement(aNodeInfo)
   {
-    mNetworkCreated = aFromParser == NS_FROM_PARSER_NETWORK;
+    mNetworkCreated = aFromParser == mozilla::dom::FROM_PARSER_NETWORK;
   }
   virtual ~nsGenericHTMLFrameElement();
 
   // nsISupports
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr);
 
   // nsIDOMNSHTMLFrameElement
   NS_DECL_NSIDOMNSHTMLFRAMEELEMENT
@@ -1041,49 +1054,30 @@ protected:
   // using NS_FROM_PARSER_NETWORK flag.
   // If the element is modified, it may lose the flag.
   PRPackedBool            mNetworkCreated;
 };
 
 //----------------------------------------------------------------------
 
 /**
- * A macro to implement the NS_NewHTMLXXXElement() functions.
- */
-#define NS_IMPL_NS_NEW_HTML_ELEMENT(_elementName)                            \
-nsGenericHTMLElement*                                                        \
-NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo,   \
-                                  PRUint32 aFromParser)                      \
-{                                                                            \
-  return new nsHTML##_elementName##Element(aNodeInfo);                       \
-}
-
-#define NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(_elementName)               \
-nsGenericHTMLElement*                                                        \
-NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo,   \
-                                  PRUint32 aFromParser)                      \
-{                                                                            \
-  return new nsHTML##_elementName##Element(aNodeInfo, aFromParser);          \
-}
-
-/**
  * A macro to implement the getter and setter for a given string
  * valued content property. The method uses the generic GetAttr and
  * SetAttr methods.
  */
 #define NS_IMPL_STRING_ATTR(_class, _method, _atom)                  \
   NS_IMETHODIMP                                                      \
   _class::Get##_method(nsAString& aValue)                            \
   {                                                                  \
-    return GetAttrHelper(nsGkAtoms::_atom, aValue);                \
+    return GetAttrHelper(nsGkAtoms::_atom, aValue);                  \
   }                                                                  \
   NS_IMETHODIMP                                                      \
   _class::Set##_method(const nsAString& aValue)                      \
   {                                                                  \
-    return SetAttrHelper(nsGkAtoms::_atom, aValue);                \
+    return SetAttrHelper(nsGkAtoms::_atom, aValue);                  \
   }
 
 /**
  * A macro to implement the getter and setter for a given string
  * valued content property with a default value.
  * The method uses the generic GetAttr and SetAttr methods.
  */
 #define NS_IMPL_STRING_ATTR_DEFAULT_VALUE(_class, _method, _atom, _default) \
@@ -1425,36 +1419,56 @@ NS_NewHTML##_elementName##Element(alread
     NS_INTERFACE_TABLE_ENTRY(_class, _i6)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i7)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i8)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i9)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i10)                                    \
   NS_OFFSET_AND_INTERFACE_TABLE_END
 
 
-// Element class factory methods
-
+/**
+ * A macro to declare the NS_NewHTMLXXXElement() functions.
+ */
 #define NS_DECLARE_NS_NEW_HTML_ELEMENT(_elementName)                       \
 nsGenericHTMLElement*                                                      \
 NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo, \
-                                  PRUint32 aFromParser = 0);
+                                  mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
 
 #define NS_DECLARE_NS_NEW_HTML_ELEMENT_AS_SHARED(_elementName)             \
 inline nsGenericHTMLElement*                                               \
 NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo, \
-                                  PRUint32 aFromParser = 0)                \
+                                  mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER) \
 {                                                                          \
   return NS_NewHTMLSharedElement(aNodeInfo, aFromParser);                  \
 }
 
+/**
+ * A macro to implement the NS_NewHTMLXXXElement() functions.
+ */
+#define NS_IMPL_NS_NEW_HTML_ELEMENT(_elementName)                            \
+nsGenericHTMLElement*                                                        \
+NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo,   \
+                                  mozilla::dom::FromParser aFromParser)      \
+{                                                                            \
+  return new nsHTML##_elementName##Element(aNodeInfo);                       \
+}
+
+#define NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(_elementName)               \
+nsGenericHTMLElement*                                                        \
+NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo,   \
+                                  mozilla::dom::FromParser aFromParser)      \
+{                                                                            \
+  return new nsHTML##_elementName##Element(aNodeInfo, aFromParser);          \
+}
+
 // Here, we expand 'NS_DECLARE_NS_NEW_HTML_ELEMENT()' by hand.
 // (Calling the macro directly (with no args) produces compiler warnings.)
 nsGenericHTMLElement*
 NS_NewHTMLElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                  PRUint32 aFromParser = 0);
+                  mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
 
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Shared)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(SharedList)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(SharedObject)
 
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Anchor)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Area)
 #if defined(MOZ_MEDIA)
--- a/content/html/content/src/nsHTMLAudioElement.cpp
+++ b/content/html/content/src/nsHTMLAudioElement.cpp
@@ -63,19 +63,21 @@
 
 #include "nsIRenderingContext.h"
 #include "nsITimer.h"
 
 #include "nsEventDispatcher.h"
 #include "nsIDOMDocumentEvent.h"
 #include "nsIDOMProgressEvent.h"
 
+using namespace mozilla::dom;
+
 nsGenericHTMLElement*
 NS_NewHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                       PRUint32 aFromParser)
+                       FromParser aFromParser)
 {
   /*
    * nsHTMLAudioElement's will be created without a nsINodeInfo passed in
    * if someone says "var audio = new Audio();" in JavaScript, in a case like
    * that we request the nsINodeInfo from the document's nodeinfo list.
    */
   nsCOMPtr<nsINodeInfo> nodeInfo(aNodeInfo);
   if (!nodeInfo) {
@@ -102,17 +104,17 @@ NS_HTML_CONTENT_INTERFACE_TABLE3(nsHTMLA
 NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLAudioElement,
                                                nsHTMLMediaElement)
 NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLAudioElement)
 
 NS_IMPL_ELEMENT_CLONE(nsHTMLAudioElement)
 
 
 nsHTMLAudioElement::nsHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       PRUint32 aFromParser)
+                                       FromParser aFromParser)
   : nsHTMLMediaElement(aNodeInfo, aFromParser)
 {
 }
 
 nsHTMLAudioElement::~nsHTMLAudioElement()
 {
 }
 
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -51,21 +51,22 @@
 #include "nsDisplayList.h"
 #include "ImageLayers.h"
 #include "BasicLayers.h"
 
 #define DEFAULT_CANVAS_WIDTH 300
 #define DEFAULT_CANVAS_HEIGHT 150
 
 using namespace mozilla;
+using namespace mozilla::dom;
 using namespace mozilla::layers;
 
 nsGenericHTMLElement*
 NS_NewHTMLCanvasElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                        PRUint32 aFromParser)
+                        FromParser aFromParser)
 {
   return new nsHTMLCanvasElement(aNodeInfo);
 }
 
 nsHTMLCanvasElement::nsHTMLCanvasElement(already_AddRefed<nsINodeInfo> aNodeInfo)
   : nsGenericHTMLElement(aNodeInfo), mWriteOnly(PR_FALSE)
 {
 }
--- a/content/html/content/src/nsHTMLElement.cpp
+++ b/content/html/content/src/nsHTMLElement.cpp
@@ -33,16 +33,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsGenericHTMLElement.h"
 #include "nsIDOMHTMLElement.h"
 
+using namespace mozilla::dom;
 
 class nsHTMLElement : public nsGenericHTMLElement,
                       public nsIDOMHTMLElement
 {
 public:
   nsHTMLElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLElement();
 
@@ -64,17 +65,17 @@ public:
 
   virtual nsXPCClassInfo* GetClassInfo();
 };
 
 // Here, we expand 'NS_IMPL_NS_NEW_HTML_ELEMENT()' by hand.
 // (Calling the macro directly (with no args) produces compiler warnings.)
 nsGenericHTMLElement*
 NS_NewHTMLElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                  PRUint32 aFromParser)
+                  FromParser aFromParser)
 {
   return new nsHTMLElement(aNodeInfo);
 }
 
 nsHTMLElement::nsHTMLElement(already_AddRefed<nsINodeInfo> aNodeInfo)
   : nsGenericHTMLElement(aNodeInfo)
 {
 }
--- a/content/html/content/src/nsHTMLFieldSetElement.cpp
+++ b/content/html/content/src/nsHTMLFieldSetElement.cpp
@@ -53,16 +53,20 @@ nsHTMLFieldSetElement::nsHTMLFieldSetEle
   , mFirstLegend(nsnull)
 {
   // <fieldset> is always barred from constraint validation.
   SetBarredFromConstraintValidation(PR_TRUE);
 }
 
 nsHTMLFieldSetElement::~nsHTMLFieldSetElement()
 {
+  PRUint32 length = mDependentElements.Length();
+  for (PRUint32 i=0; i<length; ++i) {
+    mDependentElements[i]->ForgetFieldSet(this);
+  }
 }
 
 // nsISupports
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsHTMLFieldSetElement)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mElements)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
--- a/content/html/content/src/nsHTMLFieldSetElement.h
+++ b/content/html/content/src/nsHTMLFieldSetElement.h
@@ -36,16 +36,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsHTMLFieldSetElement_h___
 #define nsHTMLFieldSetElement_h___
 
 #include "nsGenericHTMLElement.h"
 #include "nsIDOMHTMLFieldSetElement.h"
 #include "nsIConstraintValidation.h"
+#include "nsTPtrArray.h"
 
 
 class nsHTMLFieldSetElement : public nsGenericHTMLFormElement,
                               public nsIDOMHTMLFieldSetElement,
                               public nsIConstraintValidation
 {
 public:
   using nsIConstraintValidation::GetValidationMessage;
@@ -82,16 +83,24 @@ public:
   NS_IMETHOD_(PRUint32) GetType() const { return NS_FORM_FIELDSET; }
   NS_IMETHOD Reset();
   NS_IMETHOD SubmitNamesValues(nsFormSubmission* aFormSubmission);
   virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
   virtual nsXPCClassInfo* GetClassInfo();
 
   const nsIContent* GetFirstLegend() const { return mFirstLegend; }
 
+  void AddElement(nsGenericHTMLFormElement* aElement) {
+    mDependentElements.AppendElement(aElement);
+  }
+
+  void RemoveElement(nsGenericHTMLFormElement* aElement) {
+    mDependentElements.RemoveElement(aElement);
+  }
+
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsHTMLFieldSetElement,
                                            nsGenericHTMLFormElement)
 private:
 
   /**
    * Notify all elements (in mElements) that the first legend of the fieldset
    * has now changed.
    */
@@ -99,13 +108,16 @@ private:
 
   // This function is used to generate the nsContentList (listed form elements).
   static PRBool MatchListedElements(nsIContent* aContent, PRInt32 aNamespaceID,
                                     nsIAtom* aAtom, void* aData);
 
   // listed form controls elements.
   nsRefPtr<nsContentList> mElements;
 
+  // List of elements which have this fieldset as first fieldset ancestor.
+  nsTPtrArray<nsGenericHTMLFormElement> mDependentElements;
+
   nsIContent* mFirstLegend;
 };
 
 #endif /* nsHTMLFieldSetElement_h___ */
 
--- a/content/html/content/src/nsHTMLFormElement.cpp
+++ b/content/html/content/src/nsHTMLFormElement.cpp
@@ -80,16 +80,18 @@
 #include "mozAutoDocUpdate.h"
 #include "nsIHTMLCollection.h"
 
 #include "nsIConstraintValidation.h"
 #include "nsIEventStateManager.h"
 
 #include "nsIDOMHTMLButtonElement.h"
 
+using namespace mozilla::dom;
+
 static const int NS_FORM_CONTROL_LIST_HASHTABLE_SIZE = 16;
 
 static const PRUint8 NS_FORM_AUTOCOMPLETE_ON  = 1;
 static const PRUint8 NS_FORM_AUTOCOMPLETE_OFF = 0;
 
 static const nsAttrValue::EnumTable kFormAutocompleteTable[] = {
   { "on",  NS_FORM_AUTOCOMPLETE_ON },
   { "off", NS_FORM_AUTOCOMPLETE_OFF },
@@ -229,22 +231,19 @@ ShouldBeInElements(nsIFormControl* aForm
   return PR_FALSE;
 }
 
 // nsHTMLFormElement implementation
 
 // construction, destruction
 nsGenericHTMLElement*
 NS_NewHTMLFormElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                      PRUint32 aFromParser)
+                      FromParser aFromParser)
 {
   nsHTMLFormElement* it = new nsHTMLFormElement(aNodeInfo);
-  if (!it) {
-    return nsnull;
-  }
 
   nsresult rv = it->Init();
 
   if (NS_FAILED(rv)) {
     delete it;
     return nsnull;
   }
 
--- a/content/html/content/src/nsHTMLFrameElement.cpp
+++ b/content/html/content/src/nsHTMLFrameElement.cpp
@@ -36,23 +36,24 @@
  * ***** END LICENSE BLOCK ***** */
 #include "nsIDOMHTMLFrameElement.h"
 #include "nsGenericHTMLElement.h"
 #include "nsGkAtoms.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsDOMError.h"
 
+using namespace mozilla::dom;
 
 class nsHTMLFrameElement : public nsGenericHTMLFrameElement,
                            public nsIDOMHTMLFrameElement
 {
 public:
   nsHTMLFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     PRUint32 aFromParser = NS_NOT_FROM_PARSER);
+                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLFrameElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFrameElement::)
 
@@ -76,17 +77,17 @@ public:
   virtual nsXPCClassInfo* GetClassInfo();
 };
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Frame)
 
 
 nsHTMLFrameElement::nsHTMLFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       PRUint32 aFromParser)
+                                       FromParser aFromParser)
   : nsGenericHTMLFrameElement(aNodeInfo, aFromParser)
 {
 }
 
 nsHTMLFrameElement::~nsHTMLFrameElement()
 {
 }
 
--- a/content/html/content/src/nsHTMLIFrameElement.cpp
+++ b/content/html/content/src/nsHTMLIFrameElement.cpp
@@ -43,25 +43,27 @@
 #endif
 #include "nsGkAtoms.h"
 #include "nsIDocument.h"
 #include "nsMappedAttributes.h"
 #include "nsDOMError.h"
 #include "nsRuleData.h"
 #include "nsStyleConsts.h"
 
-class nsHTMLIFrameElement : public nsGenericHTMLFrameElement,
-                            public nsIDOMHTMLIFrameElement
+using namespace mozilla::dom;
+
+class nsHTMLIFrameElement : public nsGenericHTMLFrameElement
+                          , public nsIDOMHTMLIFrameElement
 #ifdef MOZ_SVG
-                            , public nsIDOMGetSVGDocument
+                          , public nsIDOMGetSVGDocument
 #endif
 {
 public:
   nsHTMLIFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                      PRUint32 aFromParser = NS_NOT_FROM_PARSER);
+                      mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLIFrameElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFrameElement::)
 
@@ -91,17 +93,17 @@ public:
   virtual nsXPCClassInfo* GetClassInfo();
 };
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(IFrame)
 
 
 nsHTMLIFrameElement::nsHTMLIFrameElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                         PRUint32 aFromParser)
+                                         FromParser aFromParser)
   : nsGenericHTMLFrameElement(aNodeInfo, aFromParser)
 {
 }
 
 nsHTMLIFrameElement::~nsHTMLIFrameElement()
 {
 }
 
--- a/content/html/content/src/nsHTMLImageElement.cpp
+++ b/content/html/content/src/nsHTMLImageElement.cpp
@@ -71,16 +71,18 @@
 
 #include "nsIJSContextStack.h"
 #include "nsImageMapUtils.h"
 #include "nsIDOMHTMLMapElement.h"
 #include "nsEventDispatcher.h"
 
 #include "nsLayoutUtils.h"
 
+using namespace mozilla::dom;
+
 // XXX nav attrs: suppress
 
 class nsHTMLImageElement : public nsGenericHTMLElement,
                            public nsImageLoadingContent,
                            public nsIDOMHTMLImageElement,
                            public nsIJSNativeInitializer
 {
 public:
@@ -149,17 +151,17 @@ public:
   virtual nsXPCClassInfo* GetClassInfo();
 protected:
   nsPoint GetXY();
   nsSize GetWidthHeight();
 };
 
 nsGenericHTMLElement*
 NS_NewHTMLImageElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                       PRUint32 aFromParser)
+                       FromParser aFromParser)
 {
   /*
    * nsHTMLImageElement's will be created without a nsINodeInfo passed in
    * if someone says "var img = new Image();" in JavaScript, in a case like
    * that we request the nsINodeInfo from the document's nodeinfo list.
    */
   nsCOMPtr<nsINodeInfo> nodeInfo(aNodeInfo);
   if (!nodeInfo) {
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -122,16 +122,18 @@
 #include "nsTextEditRules.h"
 
 // JS headers are needed for the pattern attribute.
 #include "jsapi.h"
 #include "jscntxt.h"
 
 #include "nsHTMLInputElement.h"
 
+using namespace mozilla::dom;
+
 // XXX align=left, hspace, vspace, border? other nav4 attrs
 
 static NS_DEFINE_CID(kXULControllersCID,  NS_XULCONTROLLERS_CID);
 static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 
 // First bits are needed for the control type.
 #define NS_OUTER_ACTIVATE_EVENT   (1 << 9)
 #define NS_ORIGINAL_CHECKED_VALUE (1 << 10)
@@ -607,24 +609,24 @@ static nsresult FireEventForAccessibilit
 
 //
 // construction, destruction
 //
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Input)
 
 nsHTMLInputElement::nsHTMLInputElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       PRUint32 aFromParser)
+                                       FromParser aFromParser)
   : nsGenericHTMLFormElement(aNodeInfo),
     mType(kInputDefaultType->value),
     mBitField(0)
 {
   SET_BOOLBIT(mBitField, BF_PARSER_CREATING, aFromParser);
   SET_BOOLBIT(mBitField, BF_INHIBIT_RESTORATION,
-      aFromParser & NS_FROM_PARSER_FRAGMENT);
+      aFromParser & mozilla::dom::FROM_PARSER_FRAGMENT);
   mInputData.mState = new nsTextEditorState(this);
   NS_ADDREF(mInputData.mState);
   
   if (!gUploadLastDir)
     nsHTMLInputElement::InitUploadLastDir();
 }
 
 nsHTMLInputElement::~nsHTMLInputElement()
@@ -697,20 +699,17 @@ NS_IMPL_NSICONSTRAINTVALIDATION_EXCEPT_S
 // nsIDOMNode
 
 nsresult
 nsHTMLInputElement::Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const
 {
   *aResult = nsnull;
 
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
-  nsHTMLInputElement *it = new nsHTMLInputElement(ni.forget(), PR_FALSE);
-  if (!it) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+  nsHTMLInputElement *it = new nsHTMLInputElement(ni.forget(), NOT_FROM_PARSER);
 
   nsCOMPtr<nsINode> kungFuDeathGrip = it;
   nsresult rv = CopyInnerTo(it);
   NS_ENSURE_SUCCESS(rv, rv);
 
   switch (mType) {
     case NS_FORM_INPUT_EMAIL:
     case NS_FORM_INPUT_SEARCH:
--- a/content/html/content/src/nsHTMLInputElement.h
+++ b/content/html/content/src/nsHTMLInputElement.h
@@ -118,17 +118,17 @@ class nsHTMLInputElement : public nsGene
                            public nsIPhonetic,
                            public nsIDOMNSEditableElement,
                            public nsIConstraintValidation
 {
 public:
   using nsIConstraintValidation::GetValidationMessage;
 
   nsHTMLInputElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     PRUint32 aFromParser);
+                     mozilla::dom::FromParser aFromParser);
   virtual ~nsHTMLInputElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
 
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -116,16 +116,17 @@ static PRLogModuleInfo* gMediaElementEve
 #define LOG(type, msg)
 #define LOG_EVENT(type, msg)
 #endif
 
 #include "nsIContentSecurityPolicy.h"
 #include "nsIChannelPolicy.h"
 #include "nsChannelPolicy.h"
 
+using namespace mozilla::dom;
 using namespace mozilla::layers;
 
 // Under certain conditions there may be no-one holding references to
 // a media element from script, DOM parent, etc, but the element may still
 // fire meaningful events in the future so we can't destroy it yet:
 // 1) If the element is delaying the load event (or would be, if it were
 // in a document), then events up to loadeddata or error could be fired,
 // so we need to stay alive.
@@ -221,17 +222,17 @@ public:
   NS_IMETHOD Run() {
     // Silently cancel if our load has been cancelled.
     if (IsCancelled())
       return NS_OK;
     LOG_EVENT(PR_LOG_DEBUG, ("%p Dispatching simple event source error", mElement.get()));
     return nsContentUtils::DispatchTrustedEvent(mElement->GetOwnerDoc(),
                                                 mSource,
                                                 NS_LITERAL_STRING("error"),
-                                                PR_TRUE,
+                                                PR_FALSE,
                                                 PR_TRUE);
   }
 };
 
 /**
  * There is a reference cycle involving this class: MediaLoadListener
  * holds a reference to the nsHTMLMediaElement, which holds a reference
  * to an nsIChannel, which holds a reference to this listener.
@@ -1260,17 +1261,17 @@ NS_IMETHODIMP nsHTMLMediaElement::SetMut
   }
 
   DispatchAsyncEvent(NS_LITERAL_STRING("volumechange"));
 
   return NS_OK;
 }
 
 nsHTMLMediaElement::nsHTMLMediaElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       PRUint32 aFromParser)
+                                       FromParser aFromParser)
   : nsGenericHTMLElement(aNodeInfo),
     mCurrentLoadID(0),
     mNetworkState(nsIDOMHTMLMediaElement::NETWORK_EMPTY),
     mReadyState(nsIDOMHTMLMediaElement::HAVE_NOTHING),
     mLoadWaitStatus(NOT_WAITING),
     mVolume(1.0),
     mChannels(0),
     mRate(0),
@@ -2260,17 +2261,17 @@ nsresult nsHTMLMediaElement::DispatchEve
   if (mPausedForInactiveDocument) {
     mPendingEvents.AppendElement(aName);
     return NS_OK;
   }
 
   return nsContentUtils::DispatchTrustedEvent(GetOwnerDoc(),
                                               static_cast<nsIContent*>(this),
                                               aName,
-                                              PR_TRUE,
+                                              PR_FALSE,
                                               PR_TRUE);
 }
 
 nsresult nsHTMLMediaElement::DispatchAsyncEvent(const nsAString& aName)
 {
   LOG_EVENT(PR_LOG_DEBUG, ("%p Queuing event %s", this,
             NS_ConvertUTF16toUTF8(aName).get()));
 
--- a/content/html/content/src/nsHTMLObjectElement.cpp
+++ b/content/html/content/src/nsHTMLObjectElement.cpp
@@ -47,30 +47,31 @@
 #include "nsIDOMGetSVGDocument.h"
 #endif
 #include "nsIDOMHTMLObjectElement.h"
 #include "nsFormSubmission.h"
 #include "nsIObjectFrame.h"
 #include "nsIPluginInstance.h"
 #include "nsIConstraintValidation.h"
 
+using namespace mozilla::dom;
 
-class nsHTMLObjectElement : public nsGenericHTMLFormElement,
-                            public nsObjectLoadingContent,
-                            public nsIDOMHTMLObjectElement,
-                            public nsIConstraintValidation
+class nsHTMLObjectElement : public nsGenericHTMLFormElement
+                          , public nsObjectLoadingContent
+                          , public nsIDOMHTMLObjectElement
+                          , public nsIConstraintValidation
 #ifdef MOZ_SVG
-                            , public nsIDOMGetSVGDocument
+                          , public nsIDOMGetSVGDocument
 #endif
 {
 public:
   using nsIConstraintValidation::GetValidationMessage;
 
   nsHTMLObjectElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                      PRUint32 aFromParser = 0);
+                      mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLObjectElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
 
@@ -153,22 +154,22 @@ private:
   PRPackedBool mIsDoneAddingChildren;
 };
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Object)
 
 
 nsHTMLObjectElement::nsHTMLObjectElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                         PRUint32 aFromParser)
+                                         FromParser aFromParser)
   : nsGenericHTMLFormElement(aNodeInfo),
     mIsDoneAddingChildren(!aFromParser)
 {
   RegisterFreezableElement();
-  SetIsNetworkCreated(aFromParser == NS_FROM_PARSER_NETWORK);
+  SetIsNetworkCreated(aFromParser == FROM_PARSER_NETWORK);
 
   // <object> is always barred from constraint validation.
   SetBarredFromConstraintValidation(PR_TRUE);
 }
 
 nsHTMLObjectElement::~nsHTMLObjectElement()
 {
   UnregisterFreezableElement();
--- a/content/html/content/src/nsHTMLOptionElement.cpp
+++ b/content/html/content/src/nsHTMLOptionElement.cpp
@@ -61,23 +61,25 @@
 #include "nsNodeInfoManager.h"
 #include "nsCOMPtr.h"
 #include "nsIEventStateManager.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsContentCreatorFunctions.h"
 #include "mozAutoDocUpdate.h"
 
+using namespace mozilla::dom;
+
 /**
  * Implementation of &lt;option&gt;
  */
 
 nsGenericHTMLElement*
 NS_NewHTMLOptionElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                        PRUint32 aFromParser)
+                        FromParser aFromParser)
 {
   /*
    * nsHTMLOptionElement's will be created without a nsINodeInfo passed in
    * if someone says "var opt = new Option();" in JavaScript, in a case like
    * that we request the nsINodeInfo from the document's nodeinfo list.
    */
   nsCOMPtr<nsINodeInfo> nodeInfo(aNodeInfo);
   if (!nodeInfo) {
--- a/content/html/content/src/nsHTMLScriptElement.cpp
+++ b/content/html/content/src/nsHTMLScriptElement.cpp
@@ -53,16 +53,18 @@
 #include "nsServiceManagerUtils.h"
 #include "nsIScriptEventHandler.h"
 #include "nsIDOMDocument.h"
 #include "nsContentErrors.h"
 #include "nsIArray.h"
 #include "nsTArray.h"
 #include "nsDOMJSUtils.h"
 
+using namespace mozilla::dom;
+
 //
 // Helper class used to support <SCRIPT FOR=object EVENT=handler ...>
 // style script tags...
 //
 class nsHTMLScriptEventHandler : public nsIScriptEventHandler
 {
 public:
   nsHTMLScriptEventHandler(nsIDOMHTMLScriptElement *aOuter);
@@ -303,17 +305,17 @@ nsHTMLScriptEventHandler::Invoke(nsISupp
 
 
 class nsHTMLScriptElement : public nsGenericHTMLElement,
                             public nsIDOMHTMLScriptElement,
                             public nsScriptElement
 {
 public:
   nsHTMLScriptElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                      PRUint32 aFromParser);
+                      FromParser aFromParser);
   virtual ~nsHTMLScriptElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
 
@@ -356,17 +358,17 @@ protected:
   virtual nsresult MaybeProcessScript();
 };
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Script)
 
 
 nsHTMLScriptElement::nsHTMLScriptElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                         PRUint32 aFromParser)
+                                         FromParser aFromParser)
   : nsGenericHTMLElement(aNodeInfo)
   , nsScriptElement(aFromParser)
 {
   mDoneAddingChildren = !aFromParser;
   AddMutationObserver(this);
 }
 
 nsHTMLScriptElement::~nsHTMLScriptElement()
@@ -414,20 +416,18 @@ nsHTMLScriptElement::BindToTree(nsIDocum
 }
 
 nsresult
 nsHTMLScriptElement::Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const
 {
   *aResult = nsnull;
 
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
-  nsHTMLScriptElement* it = new nsHTMLScriptElement(ni.forget(), PR_FALSE);
-  if (!it) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+  nsHTMLScriptElement* it =
+    new nsHTMLScriptElement(ni.forget(), NOT_FROM_PARSER);
 
   nsCOMPtr<nsINode> kungFuDeathGrip = it;
   nsresult rv = CopyInnerTo(it);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // The clone should be marked evaluated if we are.
   it->mAlreadyStarted = mAlreadyStarted;
   it->mLineNumber = mLineNumber;
--- a/content/html/content/src/nsHTMLSelectElement.cpp
+++ b/content/html/content/src/nsHTMLSelectElement.cpp
@@ -135,23 +135,23 @@ nsSafeOptionListMutation::~nsSafeOptionL
 //
 
 // construction, destruction
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Select)
 
 nsHTMLSelectElement::nsHTMLSelectElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                         PRUint32 aFromParser)
+                                         FromParser aFromParser)
   : nsGenericHTMLFormElement(aNodeInfo),
     mOptions(new nsHTMLOptionCollection(this)),
     mIsDoneAddingChildren(!aFromParser),
     mDisabledChanged(PR_FALSE),
     mMutating(PR_FALSE),
-    mInhibitStateRestoration(!!(aFromParser & NS_FROM_PARSER_FRAGMENT)),
+    mInhibitStateRestoration(!!(aFromParser & FROM_PARSER_FRAGMENT)),
     mNonOptionChildren(0),
     mOptGroupCount(0),
     mSelectedIndex(-1)
 {
   // FIXME: Bug 328908, set mOptions in an Init function and get rid of null
   // checks.
 
   // DoneAddingChildren() will be called later if it's from the parser,
--- a/content/html/content/src/nsHTMLSelectElement.h
+++ b/content/html/content/src/nsHTMLSelectElement.h
@@ -239,17 +239,17 @@ class nsHTMLSelectElement : public nsGen
                             public nsIDOMHTMLSelectElement,
                             public nsISelectElement,
                             public nsIConstraintValidation
 {
 public:
   using nsIConstraintValidation::GetValidationMessage;
 
   nsHTMLSelectElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                      PRUint32 aFromParser = 0);
+                      mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLSelectElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
 
--- a/content/html/content/src/nsHTMLSharedObjectElement.cpp
+++ b/content/html/content/src/nsHTMLSharedObjectElement.cpp
@@ -52,27 +52,29 @@
 
 // XXX this is to get around conflicts with windows.h defines
 // introduced through jni.h
 #ifdef XP_WIN
 #undef GetClassName
 #undef GetObject
 #endif
 
-class nsHTMLSharedObjectElement : public nsGenericHTMLElement,
-                                  public nsObjectLoadingContent,
-                                  public nsIDOMHTMLAppletElement,
-                                  public nsIDOMHTMLEmbedElement
+using namespace mozilla::dom;
+
+class nsHTMLSharedObjectElement : public nsGenericHTMLElement
+                                , public nsObjectLoadingContent
+                                , public nsIDOMHTMLAppletElement
+                                , public nsIDOMHTMLEmbedElement
 #ifdef MOZ_SVG
-                                  , public nsIDOMGetSVGDocument
+                                , public nsIDOMGetSVGDocument
 #endif
 {
 public:
   nsHTMLSharedObjectElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                            PRUint32 aFromParser = 0);
+                            mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
   virtual ~nsHTMLSharedObjectElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
 
@@ -173,17 +175,17 @@ private:
   PRPackedBool mIsDoneAddingChildren;
 };
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(SharedObject)
 
 
 nsHTMLSharedObjectElement::nsHTMLSharedObjectElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                                     PRUint32 aFromParser)
+                                                     FromParser aFromParser)
   : nsGenericHTMLElement(aNodeInfo),
     mIsDoneAddingChildren(mNodeInfo->Equals(nsGkAtoms::embed) || !aFromParser)
 {
   RegisterFreezableElement();
 }
 
 nsHTMLSharedObjectElement::~nsHTMLSharedObjectElement()
 {
--- a/content/html/content/src/nsHTMLTextAreaElement.cpp
+++ b/content/html/content/src/nsHTMLTextAreaElement.cpp
@@ -76,33 +76,35 @@
 #include "nsDOMError.h"
 #include "mozAutoDocUpdate.h"
 #include "nsISupportsPrimitives.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsIConstraintValidation.h"
 
 #include "nsTextEditorState.h"
 
+using namespace mozilla::dom;
+
 static NS_DEFINE_CID(kXULControllersCID,  NS_XULCONTROLLERS_CID);
 
 #define NS_NO_CONTENT_DISPATCH (1 << 0)
 
 class nsHTMLTextAreaElement : public nsGenericHTMLFormElement,
                               public nsIDOMHTMLTextAreaElement,
                               public nsIDOMNSHTMLTextAreaElement,
                               public nsITextControlElement,
                               public nsIDOMNSEditableElement,
                               public nsStubMutationObserver,
                               public nsIConstraintValidation
 {
 public:
   using nsIConstraintValidation::GetValidationMessage;
 
   nsHTMLTextAreaElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                        PRUint32 aFromParser = 0);
+                        mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
 
   // nsIDOMElement
@@ -273,22 +275,22 @@ protected:
   PRBool IsMutable() const;
 };
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(TextArea)
 
 
 nsHTMLTextAreaElement::nsHTMLTextAreaElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                             PRUint32 aFromParser)
+                                             FromParser aFromParser)
   : nsGenericHTMLFormElement(aNodeInfo),
     mValueChanged(PR_FALSE),
     mHandlingSelect(PR_FALSE),
     mDoneAddingChildren(!aFromParser),
-    mInhibitStateRestoration(!!(aFromParser & NS_FROM_PARSER_FRAGMENT)),
+    mInhibitStateRestoration(!!(aFromParser & FROM_PARSER_FRAGMENT)),
     mDisabledChanged(PR_FALSE),
     mState(new nsTextEditorState(this))
 {
   AddMutationObserver(this);
 }
 
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLTextAreaElement)
--- a/content/html/content/src/nsHTMLVideoElement.cpp
+++ b/content/html/content/src/nsHTMLVideoElement.cpp
@@ -61,16 +61,18 @@
 #include "nsIRenderingContext.h"
 #include "nsITimer.h"
 
 #include "nsEventDispatcher.h"
 #include "nsIDOMDocumentEvent.h"
 #include "nsIDOMProgressEvent.h"
 #include "nsMediaError.h"
 
+using namespace mozilla::dom;
+
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Video)
 
 NS_IMPL_ADDREF_INHERITED(nsHTMLVideoElement, nsHTMLMediaElement)
 NS_IMPL_RELEASE_INHERITED(nsHTMLVideoElement, nsHTMLMediaElement)
 
 DOMCI_NODE_DATA(HTMLVideoElement, nsHTMLVideoElement)
 
 NS_INTERFACE_TABLE_HEAD(nsHTMLVideoElement)
@@ -96,17 +98,17 @@ NS_IMETHODIMP nsHTMLVideoElement::GetVid
 /* readonly attribute unsigned long videoHeight; */
 NS_IMETHODIMP nsHTMLVideoElement::GetVideoHeight(PRUint32 *aVideoHeight)
 {
   *aVideoHeight = mMediaSize.height == -1 ? 0 : mMediaSize.height;
   return NS_OK;
 }
 
 nsHTMLVideoElement::nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       PRUint32 aFromParser)
+                                       FromParser aFromParser)
   : nsHTMLMediaElement(aNodeInfo, aFromParser)
 {
 }
 
 nsHTMLVideoElement::~nsHTMLVideoElement()
 {
 }
 
--- a/content/html/content/src/nsTextEditorState.cpp
+++ b/content/html/content/src/nsTextEditorState.cpp
@@ -62,16 +62,18 @@
 #include "nsPIDOMWindow.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIDOMEventGroup.h"
 #include "nsIEditor.h"
 #include "nsTextEditRules.h"
 
 #include "nsTextEditorState.h"
 
+using namespace mozilla::dom;
+
 static NS_DEFINE_CID(kTextEditorCID, NS_TEXTEDITOR_CID);
 static NS_DEFINE_CID(kFrameSelectionCID, NS_FRAMESELECTION_CID);
 
 static nsINativeKeyBindings *sNativeInputBindings = nsnull;
 static nsINativeKeyBindings *sNativeTextAreaBindings = nsnull;
 
 struct SelectionState {
   PRInt32 mStart;
@@ -1515,17 +1517,17 @@ nsTextEditorState::CreateRootNode()
 
   // Now create a DIV and add it to the anonymous content child list.
   nsCOMPtr<nsINodeInfo> nodeInfo;
   nodeInfo = doc->NodeInfoManager()->GetNodeInfo(nsGkAtoms::div, nsnull,
                                                  kNameSpaceID_XHTML);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   nsresult rv = NS_NewHTMLElement(getter_AddRefs(mRootNode), nodeInfo.forget(),
-                                  PR_FALSE);
+                                  NOT_FROM_PARSER);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Set the necessary classes on the text control. We use class values
   // instead of a 'style' attribute so that the style comes from a user-agent
   // style sheet and is still applied even if author styles are disabled.
   nsAutoString classValue;
   classValue.AppendLiteral("anonymous-div");
   PRInt32 wrapCols = GetWrapCols();
@@ -1592,17 +1594,17 @@ be called if @placeholder is the empty s
   // Create a DIV for the placeholder
   // and add it to the anonymous content child list
   nsCOMPtr<nsINodeInfo> nodeInfo;
   nodeInfo = pNodeInfoManager->GetNodeInfo(nsGkAtoms::div, nsnull,
                                            kNameSpaceID_XHTML);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   rv = NS_NewHTMLElement(getter_AddRefs(mPlaceholderDiv), nodeInfo.forget(),
-                         PR_FALSE);
+                         NOT_FROM_PARSER);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Create the text node for the placeholder text before doing anything else
   rv = NS_NewTextNode(getter_AddRefs(placeholderText), pNodeInfoManager);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mPlaceholderDiv->AppendChildTo(placeholderText, PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
--- a/content/html/content/test/test_bug430392.html
+++ b/content/html/content/test/test_bug430392.html
@@ -9,21 +9,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=430392">Mozilla Bug 430392</a>
 <p id="display"></p>
 <div id="content">
-  <div contenteditable="true" id="edit">
-    <span contenteditable="false">A</span> ;
-    <span contenteditable="false">B</span> ;
-    <span contenteditable="false">C</span>
-  </div>
+  <div contenteditable="true" id="edit"> <span contenteditable="false">A</span> ; <span contenteditable="false">B</span> ; <span contenteditable="false">C</span> </div>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 430392 **/
 
 function test() {
   var edit = document.getElementById("edit");
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -134,21 +134,22 @@ static PRLogModuleInfo* gSinkLogModuleIn
 
 #else
 #define SINK_TRACE_NODE(_bit, _msg, _tag, _sp, _obj)
 #endif
 
 //----------------------------------------------------------------------
 
 typedef nsGenericHTMLElement*
-  (*contentCreatorCallback)(already_AddRefed<nsINodeInfo>, PRUint32 aFromParser);
+  (*contentCreatorCallback)(already_AddRefed<nsINodeInfo>,
+                            FromParser aFromParser);
 
 nsGenericHTMLElement*
 NS_NewHTMLNOTUSEDElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                         PRUint32 aFromParser)
+                         FromParser aFromParser)
 {
   NS_NOTREACHED("The element ctor should never be called");
   return nsnull;
 }
 
 #define HTML_TAG(_tag, _classname) NS_NewHTML##_classname##Element,
 #define HTML_HTMLELEMENT_TAG(_tag) NS_NewHTMLElement,
 #define HTML_OTHER(_tag) NS_NewHTMLNOTUSEDElement,
@@ -550,22 +551,22 @@ HTMLContentSink::CreateContentObject(con
 
     nodeInfo = mNodeInfoManager->GetNodeInfo(name, nsnull, kNameSpaceID_XHTML);
     NS_IF_ADDREF(mNodeInfoCache[aNodeType] = nodeInfo);
   }
 
   NS_ENSURE_TRUE(nodeInfo, nsnull);
 
   // Make the content object
-  return CreateHTMLElement(aNodeType, nodeInfo.forget(), PR_TRUE);
+  return CreateHTMLElement(aNodeType, nodeInfo.forget(), FROM_PARSER_NETWORK);
 }
 
 nsresult
 NS_NewHTMLElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo,
-                  PRUint32 aFromParser)
+                  FromParser aFromParser)
 {
   *aResult = nsnull;
 
   nsCOMPtr<nsINodeInfo> nodeInfo = aNodeInfo;
 
   nsIParserService* parserService = nsContentUtils::GetParserService();
   if (!parserService)
     return NS_ERROR_OUT_OF_MEMORY;
@@ -578,17 +579,17 @@ NS_NewHTMLElement(nsIContent** aResult, 
   *aResult = CreateHTMLElement(parserService->
                                  HTMLCaseSensitiveAtomTagToId(name),
                                nodeInfo.forget(), aFromParser).get();
   return *aResult ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
 }
 
 already_AddRefed<nsGenericHTMLElement>
 CreateHTMLElement(PRUint32 aNodeType, already_AddRefed<nsINodeInfo> aNodeInfo,
-                  PRUint32 aFromParser)
+                  FromParser aFromParser)
 {
   NS_ASSERTION(aNodeType <= NS_HTML_TAG_MAX ||
                aNodeType == eHTMLTag_userdefined,
                "aNodeType is out of bounds");
 
   contentCreatorCallback cb = sContentCreatorCallbacks[aNodeType];
 
   NS_ASSERTION(cb != NS_NewHTMLNOTUSEDElement,
@@ -2614,17 +2615,18 @@ HTMLContentSink::ProcessLINKTag(const ns
   nsresult  result = NS_OK;
 
   if (mCurrentContext) {
     // Create content object
     nsCOMPtr<nsIContent> element;
     nsCOMPtr<nsINodeInfo> nodeInfo;
     nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::link, nsnull, kNameSpaceID_XHTML);
 
-    result = NS_NewHTMLElement(getter_AddRefs(element), nodeInfo.forget(), PR_FALSE);
+    result = NS_NewHTMLElement(getter_AddRefs(element), nodeInfo.forget(),
+                               NOT_FROM_PARSER);
     NS_ENSURE_SUCCESS(result, result);
 
     nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(element));
 
     if (ssle) {
       // XXX need prefs. check here.
       if (!mInsideNoXXXTag) {
         ssle->InitStyleLinkElement(PR_FALSE);
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -214,16 +214,37 @@ ReportUseOfDeprecatedMethod(nsHTMLDocume
                                   nsnull, 0,
                                   static_cast<nsIDocument*>(aDoc)->
                                     GetDocumentURI(),
                                   EmptyString(), 0, 0,
                                   nsIScriptError::warningFlag,
                                   "DOM Events");
 }
 
+static nsresult
+RemoveFromAgentSheets(nsCOMArray<nsIStyleSheet> &aAgentSheets, const nsAString& url)
+{
+  nsCOMPtr<nsIURI> uri;
+  nsresult rv = NS_NewURI(getter_AddRefs(uri), url);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  for (PRInt32 i = aAgentSheets.Count() - 1; i >= 0; --i) {
+    nsIStyleSheet* sheet = aAgentSheets[i];
+    nsIURI* sheetURI = sheet->GetSheetURI();
+
+    PRBool equals = PR_FALSE;
+    uri->Equals(sheetURI, &equals);
+    if (equals) {
+      aAgentSheets.RemoveObjectAt(i);
+    }
+  }
+
+  return NS_OK;
+}
+
 nsresult
 NS_NewHTMLDocument(nsIDocument** aInstancePtrResult)
 {
   nsHTMLDocument* doc = new nsHTMLDocument();
   NS_ENSURE_TRUE(doc, NS_ERROR_OUT_OF_MEMORY);
 
   NS_ADDREF(doc);
   nsresult rv = doc->Init();
@@ -462,58 +483,16 @@ nsHTMLDocument::TryCacheCharset(nsICachi
     aCharsetSource = kCharsetFromCache;
 
     return PR_TRUE;
   }
 
   return PR_FALSE;
 }
 
-PRBool
-nsHTMLDocument::TryBookmarkCharset(nsIDocShell* aDocShell,
-                                   nsIChannel* aChannel,
-                                   PRInt32& aCharsetSource,
-                                   nsACString& aCharset)
-{
-  if (kCharsetFromBookmarks <= aCharsetSource) {
-    return PR_TRUE;
-  }
-
-  if (!aChannel) {
-    return PR_FALSE;
-  }
-
-  nsCOMPtr<nsICharsetResolver> bookmarksResolver =
-    do_GetService("@mozilla.org/embeddor.implemented/bookmark-charset-resolver;1");
-
-  if (!bookmarksResolver) {
-    return PR_FALSE;
-  }
-
-  PRBool wantCharset;         // ignored for now
-  nsCAutoString charset;
-  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(aDocShell));
-  nsCOMPtr<nsISupports> closure;
-  nsresult rv = bookmarksResolver->RequestCharset(webNav,
-                                                  aChannel,
-                                                  &wantCharset,
-                                                  getter_AddRefs(closure),
-                                                  charset);
-  // FIXME: Bug 337970
-  NS_ASSERTION(!wantCharset, "resolved charset notification not implemented!");
-
-  if (NS_SUCCEEDED(rv) && !charset.IsEmpty()) {
-    aCharset = charset;
-    aCharsetSource = kCharsetFromBookmarks;
-    return PR_TRUE;
-  }
-
-  return PR_FALSE;
-}
-
 static PRBool
 CheckSameOrigin(nsINode* aNode1, nsINode* aNode2)
 {
   NS_PRECONDITION(aNode1, "Null node?");
   NS_PRECONDITION(aNode2, "Null node?");
 
   PRBool equal;
   return
@@ -875,20 +854,16 @@ nsHTMLDocument::StartDocumentLoad(const 
 
       // Don't actually get the charset from the channel if this is a
       // wyciwyg channel; it'll always be UTF-16
       if (!wyciwygChannel &&
           TryChannelCharset(aChannel, charsetSource, charset)) {
         // Use the channel's charset (e.g., charset from HTTP
         // "Content-Type" header).
       }
-      else if (!scheme.EqualsLiteral("about") &&          // don't try to access bookmarks for about:blank
-               TryBookmarkCharset(docShell, aChannel, charsetSource, charset)) {
-        // Use the bookmark's charset.
-      }
       else if (cachingChan && !urlSpec.IsEmpty() &&
                TryCacheCharset(cachingChan, charsetSource, charset)) {
         // Use the cache's charset.
       }
       else if (TryDefaultCharset(muCV, charsetSource, charset)) {
         // Use the default charset.
         // previous document charset might be inherited as default charset.
       }
@@ -3156,22 +3131,30 @@ NotifyEditableStateChange(nsINode *aNode
 
 void
 nsHTMLDocument::TearingDownEditor(nsIEditor *aEditor)
 {
   if (IsEditingOn()) {
     EditingState oldState = mEditingState;
     mEditingState = eTearingDown;
 
-    nsCOMPtr<nsIEditorStyleSheets> editorss = do_QueryInterface(aEditor);
-    if (editorss) {
-      editorss->RemoveOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/contenteditable.css"));
-      if (oldState == eDesignMode)
-        editorss->RemoveOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/designmode.css"));
-    }
+    nsCOMPtr<nsIPresShell> presShell = GetShell();
+    if (!presShell)
+      return;
+
+    nsCOMArray<nsIStyleSheet> agentSheets;
+    presShell->GetAgentStyleSheets(agentSheets);
+
+    RemoveFromAgentSheets(agentSheets, NS_LITERAL_STRING("resource://gre/res/contenteditable.css"));
+    if (oldState == eDesignMode)
+      RemoveFromAgentSheets(agentSheets, NS_LITERAL_STRING("resource://gre/res/designmode.css"));
+
+    presShell->SetAgentStyleSheets(agentSheets);
+
+    presShell->ReconstructStyleData();
   }
 }
 
 nsresult
 nsHTMLDocument::TurnEditingOff()
 {
   NS_ASSERTION(mEditingState != eOff, "Editing is already off.");
 
@@ -3287,52 +3270,79 @@ nsHTMLDocument::EditingStateChanged()
     nsCOMPtr<nsIEditorDocShell> editorDocShell =
       do_QueryInterface(docshell, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     editorDocShell->GetEditor(getter_AddRefs(editor));
     if (!editor)
       return NS_ERROR_FAILURE;
 
-    nsCOMPtr<nsIEditorStyleSheets> editorss = do_QueryInterface(editor, &rv);
+    nsCOMPtr<nsIPresShell> presShell = GetShell();
+    NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
+
+    nsCOMArray<nsIStyleSheet> agentSheets;
+    rv = presShell->GetAgentStyleSheets(agentSheets);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    editorss->AddOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/contenteditable.css"));
+    nsCOMPtr<nsIURI> uri;
+    rv = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_STRING("resource://gre/res/contenteditable.css"));
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsRefPtr<nsCSSStyleSheet> sheet;
+    rv = LoadChromeSheetSync(uri, PR_TRUE, getter_AddRefs(sheet));
+    NS_ENSURE_TRUE(sheet, rv);
+
+    rv = agentSheets.AppendObject(sheet);
+    NS_ENSURE_SUCCESS(rv, rv);
 
     // Should we update the editable state of all the nodes in the document? We
     // need to do this when the designMode value changes, as that overrides
     // specific states on the elements.
     if (designMode) {
       // designMode is being turned on (overrides contentEditable).
-      editorss->AddOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/designmode.css"));
-
-      // We need to flush styles here because we're setting an XBL binding in
-      // designmode.css.
-      FlushPendingNotifications(Flush_Style);
+      rv = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_STRING("resource://gre/res/designmode.css"));
+      NS_ENSURE_SUCCESS(rv, rv);
+
+      rv = LoadChromeSheetSync(uri, PR_TRUE, getter_AddRefs(sheet));
+      NS_ENSURE_TRUE(sheet, rv);
+
+      rv = agentSheets.AppendObject(sheet);
+      NS_ENSURE_SUCCESS(rv, rv);
 
       // Disable scripting and plugins.
       rv = editSession->DisableJSAndPlugins(window);
       NS_ENSURE_SUCCESS(rv, rv);
 
       updateState = PR_TRUE;
       spellRecheckAll = oldState == eContentEditable;
     }
     else if (oldState == eDesignMode) {
       // designMode is being turned off (contentEditable is still on).
-      editorss->RemoveOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/designmode.css"));
+      RemoveFromAgentSheets(agentSheets, NS_LITERAL_STRING("resource://gre/res/designmode.css"));
 
       rv = editSession->RestoreJSAndPlugins(window);
       NS_ENSURE_SUCCESS(rv, rv);
 
       updateState = PR_TRUE;
     }
     else {
       // contentEditable is being turned on (and designMode is off).
       updateState = PR_FALSE;
     }
+
+    rv = presShell->SetAgentStyleSheets(agentSheets);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    presShell->ReconstructStyleData();
+
+    if (designMode) {
+      // We need to flush styles here because we're setting an XBL binding in
+      // designmode.css.
+      FlushPendingNotifications(Flush_Style);
+    }
   }
 
   mEditingState = newState;
 
   if (makeWindowEditable) {
     // Set the editor to not insert br's on return when in p
     // elements by default.
     // XXX Do we only want to do this for designMode?
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -304,20 +304,16 @@ protected:
                                nsACString& aCharset);
   static PRBool TryUserForcedCharset(nsIMarkupDocumentViewer* aMarkupDV,
                                      nsIDocumentCharsetInfo*  aDocInfo,
                                      PRInt32& aCharsetSource,
                                      nsACString& aCharset);
   static PRBool TryCacheCharset(nsICachingChannel* aCachingChannel,
                                 PRInt32& aCharsetSource,
                                 nsACString& aCharset);
-  static PRBool TryBookmarkCharset(nsIDocShell* aDocShell,
-                                   nsIChannel* aChannel,
-                                   PRInt32& aCharsetSource,
-                                   nsACString& aCharset);
   // aParentDocument could be null.
   PRBool TryParentCharset(nsIDocumentCharsetInfo*  aDocInfo,
                           nsIDocument* aParentDocument,
                           PRInt32& charsetSource, nsACString& aCharset);
   static PRBool UseWeakDocTypeDefault(PRInt32& aCharsetSource,
                                       nsACString& aCharset);
   static PRBool TryDefaultCharset(nsIMarkupDocumentViewer* aMarkupDV,
                                   PRInt32& aCharsetSource,
--- a/content/html/document/src/nsHTMLFragmentContentSink.cpp
+++ b/content/html/document/src/nsHTMLFragmentContentSink.cpp
@@ -70,16 +70,17 @@
 #include "nsCSSProperty.h"
 #include "mozilla/css/Declaration.h"
 #include "nsICSSStyleRule.h"
 #include "nsUnicharInputStream.h"
 #include "nsCSSStyleSheet.h"
 #include "nsICSSRuleList.h"
 #include "nsIDOMCSSRule.h"
 
+using namespace mozilla::dom;
 namespace css = mozilla::css;
 
 //
 // XXX THIS IS TEMPORARY CODE
 // There's a considerable amount of copied code from the
 // regular nsHTMLContentSink. All of it will be factored
 // at some pointe really soon!
 //
@@ -385,17 +386,18 @@ nsHTMLFragmentContentSink::OpenContainer
       nodeInfo = mNodeInfoManager->GetNodeInfo(name, 
                                                nsnull, 
                                                kNameSpaceID_XHTML);
       NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
       NS_ADDREF(mNodeInfoCache[nodeType] = nodeInfo);
     }
 
-    content = CreateHTMLElement(nodeType, nodeInfo.forget(), PR_FALSE).get();
+    content =
+      CreateHTMLElement(nodeType, nodeInfo.forget(), NOT_FROM_PARSER).get();
     NS_ENSURE_TRUE(content, NS_ERROR_OUT_OF_MEMORY);
 
     result = AddAttributes(aNode, content);
     if (NS_FAILED(result)) {
       NS_RELEASE(content);
       return result;
     }
 
@@ -472,17 +474,18 @@ nsHTMLFragmentContentSink::AddLeaf(const
           NS_ASSERTION(name, "This should not happen!");
 
           nodeInfo = mNodeInfoManager->GetNodeInfo(name, nsnull,
                                                    kNameSpaceID_XHTML);
           NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
           NS_ADDREF(mNodeInfoCache[nodeType] = nodeInfo);
         }
 
-        content = CreateHTMLElement(nodeType, nodeInfo.forget(), PR_FALSE);
+        content =
+          CreateHTMLElement(nodeType, nodeInfo.forget(), NOT_FROM_PARSER);
         NS_ENSURE_TRUE(content, NS_ERROR_OUT_OF_MEMORY);
 
         result = AddAttributes(aNode, content);
         NS_ENSURE_SUCCESS(result, result);
 
         nsIContent *parent = GetCurrentContent();
         if (!parent) {
           parent = mRoot;
--- a/content/html/document/src/nsPluginDocument.cpp
+++ b/content/html/document/src/nsPluginDocument.cpp
@@ -290,17 +290,17 @@ nsPluginDocument::CreateSyntheticPluginD
 
 
   // make plugin content
   nsCOMPtr<nsINodeInfo> nodeInfo;
   nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::embed, nsnull,
                                            kNameSpaceID_XHTML);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
   rv = NS_NewHTMLElement(getter_AddRefs(mPluginContent), nodeInfo.forget(),
-                         PR_FALSE);
+                         NOT_FROM_PARSER);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // make it a named element
   mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name,
                           NS_LITERAL_STRING("plugin"), PR_FALSE);
 
   // fill viewport and auto-resize
   NS_NAMED_LITERAL_STRING(percent100, "100%");
--- a/content/html/document/src/nsVideoDocument.cpp
+++ b/content/html/document/src/nsVideoDocument.cpp
@@ -112,17 +112,17 @@ nsVideoDocument::CreateSyntheticVideoDoc
   // make content
   nsCOMPtr<nsINodeInfo> nodeInfo;
   nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::video, nsnull,
                                            kNameSpaceID_XHTML);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_FAILURE);
 
   nsRefPtr<nsHTMLMediaElement> element =
     static_cast<nsHTMLMediaElement*>(NS_NewHTMLVideoElement(nodeInfo.forget(),
-                                     PR_FALSE));
+                                                            NOT_FROM_PARSER));
   if (!element)
     return NS_ERROR_OUT_OF_MEMORY;
   element->SetAutoplay(PR_TRUE);
   element->SetControls(PR_TRUE);
   element->LoadWithChannel(aChannel, aListener);
   UpdateTitle(aChannel);
 
   if (nsContentUtils::IsChildOfSameType(this)) {
--- a/content/html/document/test/test_bug404320.html
+++ b/content/html/document/test/test_bug404320.html
@@ -15,16 +15,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content">
   <iframe id="testIframe"></iframe>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 404320 **/
 
+SimpleTest.waitForExplicitFinish();
+
 var win = document.getElementById("testIframe").contentWindow;
 var doc = document.getElementById("testIframe").contentDocument;
 
 function testFormatBlock(tag, withAngleBrackets, shouldSucceed)
 {
   win.getSelection().selectAllChildren(doc.body.firstChild);
   doc.execCommand("FormatBlock", false,
                   withAngleBrackets ? tag : "<" + tag + ">");
@@ -71,15 +73,20 @@ var goodTags = [ "address",
                  "h6",
                  "p",
                  "pre" ];
 var badTags =  [ "b",
                  "i",
                  "span",
                  "foo" ];
 
-formatBlockTests(goodTags, true);
-formatBlockTests(badTags, false);
+function runTests() {
+  formatBlockTests(goodTags, true);
+  formatBlockTests(badTags, false);
+  SimpleTest.finish();
+}
+
+addLoadEvent(runTests);
 
 </script>
 </pre>
 </body>
 </html>
--- a/content/media/nsBuiltinDecoderStateMachine.cpp
+++ b/content/media/nsBuiltinDecoderStateMachine.cpp
@@ -1258,21 +1258,24 @@ void nsBuiltinDecoderStateMachine::Advan
       // Decode one frame and display it
       NS_ASSERTION(videoData->mTime >= mStartTime, "Should have positive frame time");
       {
         MonitorAutoExit exitMon(mDecoder->GetMonitor());
         // If we have video, we want to increment the clock in steps of the frame
         // duration.
         RenderVideoFrame(videoData);
       }
-      mDecoder->GetMonitor().NotifyAll();
       frameDuration = videoData->mEndTime - videoData->mTime;
       videoData = nsnull;
     }
 
+    // Kick the decode thread in case it filled its buffers and put itself
+    // to sleep.
+    mDecoder->GetMonitor().NotifyAll();
+
     // Cap the current time to the larger of the audio and video end time.
     // This ensures that if we're running off the system clock, we don't
     // advance the clock to after the media end time.
     if (mVideoFrameEndTime != -1 || mAudioEndTime != -1) {
       // These will be non -1 if we've displayed a video frame, or played an audio sample.
       clock_time = NS_MIN(clock_time, NS_MAX(mVideoFrameEndTime, mAudioEndTime));
       if (clock_time > GetMediaTime()) {
         // Only update the playback position if the clock time is greater
--- a/content/media/test/seek10.js
+++ b/content/media/test/seek10.js
@@ -8,17 +8,16 @@ function test_seek10(v, seekTime, is, ok
 function startTest() {
   // Must be duration*0.9 rather than seekTime, else we don't hit that problem.
   // This is probably due to the seek bisection finishing too quickly, before
   // we can close the stream.
   v.currentTime = v.duration * 0.9;
 }
 
 function done(evt) {
-  evt.stopPropagation();
   ok(true, "We don't acutally test anything...");
   finish();
 }
 
 function seeking() {
   v.onerror = done;
   v.src = "not a valid video file.";
   v.load(); // Cause the existing stream to close.
--- a/content/media/test/test_a4_tone.html
+++ b/content/media/test/test_a4_tone.html
@@ -9,17 +9,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=490705">Mozilla Bug 490705</a>
 
 <!-- mute audio, since there is no need to hear the sound for these tests -->
-<audio id='a1' onerror="event.stopPropagation();" controls></audio>
+<audio id='a1' controls></audio>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /**
 * FFT is a class for calculating the Discrete Fourier Transform of a signal
 * with the Fast Fourier Transform algorithm.
 *
--- a/content/media/test/test_autoplay.html
+++ b/content/media/test/test_autoplay.html
@@ -3,18 +3,18 @@
 <head>
   <title>Media test: autoplay attribute</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="manifest.js"></script>
 </head>
 <body>
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
-<video id='v2' onerror="event.stopPropagation();" autoplay></video><audio id='a2' onerror="event.stopPropagation();"autoplay></audio>
+<video id='v1'"></video><audio id='a1'></audio>
+<video id='v2' autoplay></video><audio id='a2' autoplay></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 var v2 = document.getElementById('v2');
 var a2 = document.getElementById('a2');
 ok(!v1.autoplay, "v1.autoplay should be false by default");
 ok(!a1.autoplay, "v1.autoplay should be false by default");
--- a/content/media/test/test_bug463162.xhtml
+++ b/content/media/test/test_bug463162.xhtml
@@ -23,17 +23,16 @@ var gExpectedResult = {
   'a2' : 'loaded',
   'a3' : 'loaded',
   'a4' : 'error',
 };
 
 var gResultCount = 0;
 
 function onError(event, id) {
-  event.stopPropagation();
   is('error', gExpectedResult[id], 'unexpected error loading ' + id);
   gResultCount++;
   dump('error('+id+') expected ' + gExpectedResult[id] + ' gResultCount=' + gResultCount + '\n');
   if (gResultCount == 4)
     SimpleTest.finish();
 }
 
 function onMetaData(id) {
@@ -42,21 +41,20 @@ function onMetaData(id) {
   dump('onMetaData('+id+') expected ' + gExpectedResult[id] + ' gResultCount=' + gResultCount + '\n');
   if (gResultCount == 4)
     SimpleTest.finish();
 }
 
 ]]>
 </script>
 
-<video id='a1' onerror="onError(event, 'a1');" onloadedmetadata="onMetaData('a1');"><sauce/><source type="bad" src="
-404"/></video>
-<video id='a2' onerror="onError(event, 'a2');" onloadedmetadata="onMetaData('a2');"><source/></video>
-<video id='a3' onerror="onError(event, 'a3');" onloadedmetadata="onMetaData('a3');"><html:source/></video>
-<video id='a4' onerror="onError(event, 'a4');" onloadedmetadata="onMetaData('a4');"><svg:source/><source type="bad" src="404"/></video>
+<video id='a1' onloadedmetadata="onMetaData('a1');"><sauce/><source type="bad" src="404" onerror="onError(event, 'a1');"/></video>
+<video id='a2' onloadedmetadata="onMetaData('a2');"><source onerror="onError(event, 'a2');"/></video>
+<video id='a3' onloadedmetadata="onMetaData('a3');"><html:source onerror="onError(event, 'a3');"/></video>
+<video id='a4' onloadedmetadata="onMetaData('a4');"><svg:source/><source onerror="onError(event, 'a4');" type="bad" src="404"/></video>
 
 <script class="testbody" type="text/javascript">
 <![CDATA[
 
 function setSource(id, res) {
   var v = document.getElementById(id);
   v.firstChild.src = res.name;
   v.firstChild.type = res.type;
--- a/content/media/test/test_can_play_type.html
+++ b/content/media/test/test_can_play_type.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=469247">Mozill
 a Bug 469247</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script type="application/javascript">
 
 var v = document.getElementById('v');
 
 function check(type, expected) {
   is(v.canPlayType(type), expected, type);
--- a/content/media/test/test_can_play_type_no_ogg.html
+++ b/content/media/test/test_can_play_type_no_ogg.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=469247">Mozill
 a Bug 469247</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script src="can_play_type_ogg.js"></script>
 
 check_ogg(document.getElementById('v'), false);
 
 mediaTestCleanup();
 </script>
--- a/content/media/test/test_can_play_type_no_wave.html
+++ b/content/media/test/test_can_play_type_no_wave.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=469247">Mozill
 a Bug 469247</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script src="can_play_type_wave.js"></script>
 
 check_wave(document.getElementById('v'), false);
 
 mediaTestCleanup();
 
--- a/content/media/test/test_can_play_type_no_webm.html
+++ b/content/media/test/test_can_play_type_no_webm.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=566245">Mozill
 a Bug 566245</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script src="can_play_type_webm.js"></script>
 
 check_webm(document.getElementById('v'), false);
 
 mediaTestCleanup();
 
--- a/content/media/test/test_can_play_type_ogg.html
+++ b/content/media/test/test_can_play_type_ogg.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=469247">Mozill
 a Bug 469247</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script src="can_play_type_ogg.js"></script>
 <script>
 check_ogg(document.getElementById('v'), true);
 
 mediaTestCleanup();
 </script>
--- a/content/media/test/test_can_play_type_wave.html
+++ b/content/media/test/test_can_play_type_wave.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=469247">Mozill
 a Bug 469247</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script src="can_play_type_wave.js"></script>
 <script>
 check_wave(document.getElementById('v'), true);
 
 mediaTestCleanup();
 </script>
--- a/content/media/test/test_can_play_type_webm.html
+++ b/content/media/test/test_can_play_type_webm.html
@@ -12,17 +12,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=566245">Mozill
 a Bug 566245</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
-<video id="v" onerror="event.stopPropagation();"></video>
+<video id="v"></video>
 
 <pre id="test">
 <script src="can_play_type_webm.js"></script>
 <script>
 check_webm(document.getElementById('v'), true);
 mediaTestCleanup();
 </script>
 </pre>
--- a/content/media/test/test_constants.html
+++ b/content/media/test/test_constants.html
@@ -6,17 +6,17 @@
 -->
 <head>
   <title>Media test: constants</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
-<video onerror="event.stopPropagation();"><source></video><audio onerror="event.stopPropagation();"><source></audio>
+<video><source></video><audio><source></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 is(HTMLElement.NETWORK_EMPTY, undefined);
 is(HTMLElement.NETWORK_IDLE, undefined);
 is(HTMLElement.NETWORK_LOADING, undefined);
 is(HTMLElement.NETWORK_NO_SOURCE, undefined);
 is(HTMLElement.HAVE_NOTHING, undefined);
 is(HTMLElement.HAVE_METADATA, undefined);
--- a/content/media/test/test_controls.html
+++ b/content/media/test/test_controls.html
@@ -2,18 +2,18 @@
 <html>
 <head>
   <title>Media test: controls</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
-<video id='v2' onerror="event.stopPropagation();" controls></video><audio id='a2' onerror="event.stopPropagation();" controls></audio>
+<video id='v1'></video><audio id='a1'></audio>
+<video id='v2' controls></video><audio id='a2' controls></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 var v2 = document.getElementById('v2');
 var a2 = document.getElementById('a2');
 ok(!v1.controls, "v1.controls should be false by default");
 ok(!a1.controls, "v1.controls should be false by default");
--- a/content/media/test/test_currentTime.html
+++ b/content/media/test/test_currentTime.html
@@ -2,17 +2,17 @@
 <html>
 <head>
   <title>Media test: currentTime</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
+<video id='v1'></video><audio id='a1'></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 is(v1.currentTime, 0.0);
 is(a1.currentTime, 0.0);
 </script>
 </pre>
--- a/content/media/test/test_decode_error.html
+++ b/content/media/test/test_decode_error.html
@@ -12,17 +12,16 @@
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var manager = new MediaTestManager;
 
 function startTest(test, token) {
   var v = document.createElement("video");
   manager.started(token);
   v.addEventListener("error", function (event) {
-    event.stopPropagation();
     var el = event.currentTarget;
     is(event.type, "error", "Expected event of type 'error'");
     ok(el.error, "Element 'error' attr expected to have a value");
     ok(el.error instanceof MediaError, "Element 'error' attr expected to be MediaError");
     is(el.error.code, MediaError.MEDIA_ERR_DECODE, "Expected a decode error");
     is(el.networkState, HTMLMediaElement.NETWORK_EMPTY, "networkState should be EMPTY");
     el._sawError = true;
   }, false);
--- a/content/media/test/test_decoder_disable.html
+++ b/content/media/test/test_decoder_disable.html
@@ -65,29 +65,28 @@ function finishTest() {
 
   branch.setBoolPref("ogg.enabled", gOldOggPref);
   branch.setBoolPref("wave.enabled", gOldWavePref);
 
   SimpleTest.finish();
 }
 
 function videoError(event, id) {
-  event.stopPropagation();
   gLoadError[id]++;
   gErrorCount++;
   if (gErrorCount >= 4) {
     finishTest();
   }
 }
 
 </script>
 
-<video id="video1" onerror="videoError(event, 'video1');">
-  <source type="video/ogg" src="320x240.ogv"/>
-  <source type="audio/wave" src="r11025_u8_c1.wav" id='s2'/>
+<video id="video1">
+  <source type="video/ogg" src="320x240.ogv" onerror="videoError(event, 'video1');"/>
+  <source type="audio/wave" src="r11025_u8_c1.wav" id='s2' onerror="videoError(event, 'video1');"/>
 </video>
 
 <video id="video2" src="320x240.ogv" onerror="videoError(event, 'video2');"></video>
 <video id="video3" src="r11025_u8_c1.wav" onerror="videoError(event, 'video3');"></video>
 
 </pre>
 
 </body>
--- a/content/media/test/test_error_in_video_document.html
+++ b/content/media/test/test_error_in_video_document.html
@@ -21,16 +21,27 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script type="application/javascript">
 
 /** Test for Bug 604067 **/
 
 var f = document.createElement("iframe");
 
 function check() {
   var v = document.body.getElementsByTagName("iframe")[0].contentDocument.body.getElementsByTagName("video")[0];
+  
+  // Debug info for Bug 608634
+  ok(true, "iframe src=" + document.body.getElementsByTagName("iframe")[0].src);
+  ok(true, "v.readyState=" + v.readyState);
+  ok(true, "v.networkState=" + v.networkState);
+  if (v.error) {
+    ok(true, "v.error.code=" + v.error.code);
+  } else {
+    ok(true, "v.error is null");
+  }
+  
   ok(v.error && v.error.code == MediaError.MEDIA_ERR_DECODE, "Must have error set to MEDIA_ERR_DECODE");
   SimpleTest.finish();
 }
 
 // Find an error test that we'd think we should be able to play (if it
 // wasn't already known to fail).
 var t = getPlayableVideo(gErrorTests);
 if (t != null) {
--- a/content/media/test/test_error_on_404.html
+++ b/content/media/test/test_error_on_404.html
@@ -39,17 +39,16 @@ function FinishedLoads() {
       return false;
     }
   }
   return true;
 }
 
 function loadError(evt) {
   // Prevent mochitest's onerror handler catching the 'error' event on bubble.
-  evt.stopPropagation();
   var v = evt.target;
   is(v._loadError, false, "Shouldn't receive multiple error events for " + v.src);
   v._loadError = true;
   is(v._loadStart, true, "Receive loadstart for " + v.src);
   is(v._loadedData, false, "Shouldn't receive loadeddata for " + v.src);
   if (FinishedLoads(videos))
     SimpleTest.finish();
 }
--- a/content/media/test/test_framebuffer.html
+++ b/content/media/test/test_framebuffer.html
@@ -9,17 +9,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=490705">Mozilla Bug 490705</a>
 
 <!-- mute audio, since there is no need to hear the sound for these tests -->
-<audio id='a1' onerror="event.stopPropagation();" controls></audio>
+<audio id='a1' controls></audio>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var testFile = "bug495794.ogg";
 var testFileDuration = 0.30;
 var testFileChannelCount = 6;
 var testFileSampleRate = 48000;
 var testFileFrameBufferLength = 6 * 1024;
--- a/content/media/test/test_info_leak.html
+++ b/content/media/test/test_info_leak.html
@@ -58,17 +58,16 @@ function nextTest() {
 
   gTestNum++;
   gEventNum = 0;
   createMedia(t.type, t.src);
 }
 
 function listener(evt) {
   //log('event ' + evt.type);
-  evt.stopPropagation();
   ok(gEventNum < gExpectedEvents.length, "Too many events received");
   var expected = (gEventNum < gExpectedEvents.length) ? gExpectedEvents[gEventNum] : "NoEvent";
   is(evt.type, expected, "Events received in wrong order");
   gEventNum++;
   if (gEventNum == gExpectedEvents.length) {
     // In one second, move onto the next test. This give a chance for any
     // other events to come in. Note: we don't expect any events to come
     // in, unless we've leaked some info, and 1 second should be enough time
--- a/content/media/test/test_load.html
+++ b/content/media/test/test_load.html
@@ -33,48 +33,63 @@ var gEventNum = 0;
 var gTestNum = 0;
 var gTestFileNum = 0;
 var gExpectedEvents = null;
 var gTest = null;
 var gTestName = "?";
 
 function listener(evt) {
   log('event ' + evt.type);
-  evt.stopPropagation();
   ok(gEventNum < gExpectedEvents.length, gTestName+" - corrent number of events received");
   var expected = (gEventNum < gExpectedEvents.length) ? gExpectedEvents[gEventNum] : "NoEvent";
   is(evt.type, expected, gTestName+" - events received in order");
   gEventNum++;
   if (gEventNum == gExpectedEvents.length) {
     setTimeout(nextTest, 0); 
   }
 }
 
+function source_error(evt) {
+  log('event source_error');
+  ok(evt.type == "error", "Should only get error events here");
+  ok(gEventNum < gExpectedEvents.length, gTestName+" - corrent number of events received");
+  var expected = (gEventNum < gExpectedEvents.length) ? gExpectedEvents[gEventNum] : "NoEvent";
+  is("source_error", expected, gTestName+" - events received in order");
+  gEventNum++;
+  if (gEventNum == gExpectedEvents.length) {
+    setTimeout(nextTest, 0); 
+  }
+}
+
 var gMedia = null;
 
 function createMedia(tag) {
   gMedia = document.createElement(tag);
   gMedia.setAttribute("preload", "auto");
   for (var i=0; i<gEventTypes.length; i++) {
     gMedia.addEventListener(gEventTypes[i], listener, false);
   }
 }
 
 function addSource(src, type) {
   var s = document.createElement("source");
+  s.addEventListener("error", source_error, false);
   s.src = src;
   s.type = type;
   gMedia.appendChild(s);
+  return s;
 }
 
 function prependSource(src, type) {
   var s = document.createElement("source");
+  s.addEventListener("error", source_error, false);
   s.src = src;
   s.type = type;
   gMedia.insertBefore(s, gMedia.firstChild);
+  return s;
 }
 
 var gTests = [
   {
     // Test 0: adding video to doc, then setting src should load implicitly.
     create:
       function(src, type) {
         document.body.appendChild(gMedia);
@@ -94,64 +109,64 @@ var gTests = [
     // and receive error events for failed loads on the source children.
     create:
       function(src, type) {
         document.body.appendChild(gMedia);
         addSource("404a", type);
         addSource("404b", type);
         addSource(src, type);
       },
-    expectedEvents: ['loadstart', 'error', 'error', 'durationchange', 'loadedmetadata', 'loadeddata']
+    expectedEvents: ['loadstart', 'source_error', 'source_error', 'durationchange', 'loadedmetadata', 'loadeddata']
   }, {
     // Test 3:  video with bad src, good <source>, ensure that <source> aren't used.
     create:
       function(src, type) {
         gMedia.src = "404a";
         addSource(src, type);
         document.body.appendChild(gMedia);
       },
     expectedEvents: ['loadstart', 'error']
   }, {
     // Test 4:  video with only bad source, loading, then adding a good source
     // -  should resume load.
     create:
       function(src, type) {
         addSource("404a", type);
-        addSource("404b", type);
-        gMedia.addEventListener("error",
+        var s2 = addSource("404b", type);
+        s2.addEventListener("error",
           function(e) {
             // Should awaken waiting load, causing successful load.
             addSource(src, type);
           },
           false);
         document.body.appendChild(gMedia);
       },
-    expectedEvents: ['loadstart', 'error', 'error', 'durationchange', 'loadedmetadata', 'loadeddata']
+    expectedEvents: ['loadstart', 'source_error', 'source_error', 'durationchange', 'loadedmetadata', 'loadeddata']
   }, {
     // Test 5: video with only 1 bad source, let it fail to load, then prepend
     // a good <source> to the video, it shouldn't be selected, because the
     // "pointer" should be after the last child - the bad source.
     prepended: false,
     create:
       function(src, type) {
         var prepended = false;
         addSource("404a", type);
-        addSource("404b", type);
-        gMedia.addEventListener("error",
+        var s2 = addSource("404b", type);
+        s2.addEventListener("error",
           function(e) {
             // Should awaken waiting load, causing successful load.
             if (!prepended) {
               prependSource(src, type);
               prepended = true;
             }
           },
           false);
         document.body.appendChild(gMedia);
       },
-    expectedEvents: ['loadstart', 'error', 'error']
+    expectedEvents: ['loadstart', 'source_error', 'source_error']
   }
 ];
 
 function nextTest() {
   if (gMedia) {
     if (gMedia.parentNode)
       gMedia.parentNode.removeChild(gMedia);
     gMedia = null;
--- a/content/media/test/test_load_candidates.html
+++ b/content/media/test/test_load_candidates.html
@@ -27,30 +27,30 @@ function finish(evt) {
   var v = evt.target;
   is(v._error, 2, "Should have received 2 error events before loaded");
   v._finished = true;
   v.parentNode.removeChild(v);
   manager.finished(v.token);
 }
 
 function errorHandler(evt) {
-  evt.stopPropagation();
   evt.target.parentNode._error++;
 }
 
 var extenstion = {
   "audio/wav" : "wav",
   "audio/x-wav": "wav",
   "video/ogg" : "ogv",
   "audio/ogg" : "oga",
   "video/webm" : "webm"
 };
 
 function startTest(test, token) {
   var v = document.createElement('video');
+  v.addEventListener("error", function(){ok(false,"Error events on source children should not bubble");}, false);
   v.token = token;
   manager.started(token);
   v._error = 0;
   v._finished = false;
   v._name = test.name;
   
   var s1 = document.createElement("source");
   s1.type = test.type;
--- a/content/media/test/test_media_selection.html
+++ b/content/media/test/test_media_selection.html
@@ -24,27 +24,25 @@ function maketest(attach_media, name, ty
           is(e.currentSrc.substring(e.currentSrc.length - name.length), name, 'test ' + token);
           // The load can go idle due to cache size limits
           ok(e.networkState >= HTMLMediaElement.NETWORK_IDLE,
               'test ' + token + ' networkState = ' + e.networkState + ' expected >= ' + HTMLMediaElement.NETWORK_IDLE);
           check_metadata(e);
           e.parentNode.removeChild(e);
           manager.finished(token);
         }, false);
-      e.addEventListener('error', function(e) { e.stopPropagation();}, false);      
     } else {
       e.addEventListener('error', function(event) {
-        event.stopPropagation();
         is(errorRun, false, "error handler should run once only!");
         errorRun = true;
         is(e.readyState, HTMLMediaElement.HAVE_NOTHING,
            'test ' + token + ' readyState should be HAVE_NOTHING when load fails.');
         e.parentNode.removeChild(e);
         manager.finished(token);
-      }, false);
+      }, true);
     }
     attach_media(e, name, type);
   }
 }
 
 function set_src(element, name, type) {
   element.src = name;
   document.body.appendChild(element);
--- a/content/media/test/test_networkState.html
+++ b/content/media/test/test_networkState.html
@@ -3,17 +3,17 @@
 <head>
   <title>Media test: networkState</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="manifest.js"></script>
 </head>
 <body onunload="mediaTestCleanup();">
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
+<video id='v1'></video><audio id='a1'></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 "use strict";
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 var passed = "truthy";
 
 try {
--- a/content/media/test/test_paused.html
+++ b/content/media/test/test_paused.html
@@ -3,17 +3,17 @@
 <head>
   <title>Media test: paused</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="manifest.js"></script>
 </head>
 <body>
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
+<video id='v1'></video><audio id='a1'></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 ok(v1.paused, "v1.paused must initially be true");
 ok(a1.paused, "a1.paused must initially be true");
 mediaTestCleanup();
 </script>
--- a/content/media/test/test_playback_errors.html
+++ b/content/media/test/test_playback_errors.html
@@ -21,17 +21,16 @@ function startTest(test, token) {
   function endedTest(v) {
     if (v._ignore)
       return;
     v._ignore = true;
     v.parentNode.removeChild(v);
     manager.finished(token);
   }
   var checkError = function(test, v) { return function(evt) {
-    evt.stopPropagation();
     v._errorCount++;
     is(v._errorCount, 1, test.name + " only one error fired");
     endedTest(v);
   }}(test, v);
   var checkEnded = function(test, v) { return function() {
     ok(false, test.name + " successfully played");
     endedTest(v);
   }}(test, v);
--- a/content/media/test/test_preload_actions.html
+++ b/content/media/test/test_preload_actions.html
@@ -265,20 +265,20 @@ var tests = [
       v._gotLoadedMetaData = false;
       v._finished = false;
       v.preload = "none";
       v._gotErrorEvent = false;
       v.addEventListener("loadedmetadata", function(e){v._gotLoadedMetaData = true;}, false);
       v.addEventListener("loadstart", function(e){v._gotLoadStart = true;}, false);
       v.addEventListener("suspend", this.suspend, false);
       v.addEventListener("ended", this.ended, false);
-      v.addEventListener("error", function(e){v._gotErrorEvent = true; e.stopPropagation();}, false);
       var s1 = document.createElement("source");
       s1.src = "not-a-real-file.404"
       s1.type = test.type;
+      s1.addEventListener("error", function(e){v._gotErrorEvent = true;}, false);
       v.appendChild(s1);
       var s2 = document.createElement("source");
       s2.src = test.name;
       s2.type = test.type;
       v.appendChild(s2);
       document.body.appendChild(v); // Causes implicit load, which will be halt at preload:none on the second resource.
     },
   },
--- a/content/media/test/test_preload_attribute.html
+++ b/content/media/test/test_preload_attribute.html
@@ -11,20 +11,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=479863">Mozilla Bug 479863</a>
 <p id="display"></p>
 <div id="content" style="display: none">
   
 </div>
 
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="ev
-ent.stopPropagation();"></audio>
-<video id='v2' onerror="event.stopPropagation();" preload="auto"></video><audio id='a2' on
-error="event.stopPropagation();" preload="auto"></audio>
+<video id='v1'></video><audio id='a1'></audio>
+<video id='v2' preload="auto"></video><audio id='a2' preload="auto"></audio>
 
 <pre id="test">
 <script type="application/javascript">
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 var v2 = document.getElementById('v2');
 var a2 = document.getElementById('a2');
 is(v1.getAttribute("preload"), undefined, "video preload via getAttribute should be undefined by default");
--- a/content/media/test/test_preload_suspend.html
+++ b/content/media/test/test_preload_suspend.html
@@ -12,22 +12,22 @@ https://bugzilla.mozilla.org/show_bug.cg
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=479863">Mozilla Bug 479863</a>
 <p id="display"></p>
 <div id="content" style="display: none">
   
 </div>
 
-<video id='v1' onerror="event.stopPropagation()"></video>
-<video id='v2' onerror="event.stopPropagation()" preload="auto"></video>
-<video id='v3' onerror="event.stopPropagation()" autoplay></video>
-<video id='v4' onerror="event.stopPropagation()"></video>
-<video id='v5' onerror="event.stopPropagation()"></video>
-<video id='v6' onerror="event.stopPropagation()"></video>
+<video id='v1'></video>
+<video id='v2' preload="auto"></video>
+<video id='v3' autoplay></video>
+<video id='v4'></video>
+<video id='v5'></video>
+<video id='v6'></video>
 
 <pre id="test">
 <script type="application/javascript">
 function is() {}
 
 var suspendCount = {};
 var expectedSuspendCount = {v1:2, v2:1, v3:1, v4:2, v5:2, v6:2};
 var totalSuspendCount = 0;
--- a/content/media/test/test_readyState.html
+++ b/content/media/test/test_readyState.html
@@ -2,17 +2,17 @@
 <html>
 <head>
   <title>Media test: readyState</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
+<video id='v1'></video><audio id='a1'></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 "use strict";
 var v1 = document.getElementById('v1');
 var a1 = document.getElementById('a1');
 var passed = "truthy";
 
 is(v1.readyState, 0);
--- a/content/media/test/test_referer.html
+++ b/content/media/test/test_referer.html
@@ -26,18 +26,16 @@ function checkComplete() {
       return;
     }
   }
 
   SimpleTest.finish();
 }
  
 function loadError(evt) {
-  // Prevent mochitest's onerror handler catching the 'error' event on bubble.
-  evt.stopPropagation();
   // If no referer is sent then the sjs returns an error
   ok(false, "check referer is sent with media request");
   evt.target._complete = true;
   checkComplete();
 }
 
 function loadedMetadata(evt) {
   // If a referer is sent then the sjs returns a valid media
--- a/content/media/test/test_seek2.html
+++ b/content/media/test/test_seek2.html
@@ -2,17 +2,17 @@
 <html>
 <head>
   <title>Media test: seek test 2</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
-<video id='v' onerror="event.stopPropagation();"></video>
+<video id='v'></video>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 // http://www.whatwg.org/specs/web-apps/current-work/#dom-media-seek
 // If the media element's readyState is HAVE_NOTHING, then the user agent
 // must raise an INVALID_STATE_ERR exception.
 var v = document.getElementById('v');
 var passed = false;
 
--- a/content/media/test/test_source.html
+++ b/content/media/test/test_source.html
@@ -3,18 +3,18 @@
 <head>
   <title>Media test: append source child</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="manifest.js"></script>
 </head>
 <body>
-<video id="v1" onerror="event.stopPropagation();"></video>
-<audio id="a1" onerror="event.stopPropagation();"></audio>
+<video id="v1"></video>
+<audio id="a1"></audio>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 var v1 = document.getElementById("v1");
 var a1 = document.getElementById("a1");
 
 is(v1.src, "", "src should be null");
 is(a1.src, "", "src should be null");
 is(v1.currentSrc, "", "currentSrc should be null");
--- a/content/media/test/test_volume.html
+++ b/content/media/test/test_volume.html
@@ -3,17 +3,17 @@
 <head>
   <title>Media test: volume attribute set</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 
-<video id='v1' onerror="event.stopPropagation();"></video><audio id='a1' onerror="event.stopPropagation();"></audio>
+<video id='v1'></video><audio id='a1'></audio>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 function test(element, value, shouldThrow) {
   var threw = false;
   try {
     element.volume = value;
--- a/content/media/wave/nsWaveDecoder.cpp
+++ b/content/media/wave/nsWaveDecoder.cpp
@@ -366,16 +366,20 @@ private:
   // True if an event to notify about a change in the playback position has
   // been queued, but not yet run.  It is set to false when the event is
   // run.  This allows coalescing of these events as they can be produced
   // many times per second.
   PRPackedBool mPositionChangeQueued;
 
   // True if paused.  Tracks only the play/paused state.
   PRPackedBool mPaused;
+
+  // True if playback of the audio stream has finished, and the audio stream
+  // has been drained. This means playback of the file has ended.
+  PRPackedBool mPlaybackEnded;
 };
 
 nsWaveStateMachine::nsWaveStateMachine(nsWaveDecoder* aDecoder,
                                        TimeDuration aBufferWaitTime,
                                        float aInitialVolume)
   : mDecoder(aDecoder),
     mStream(nsnull),
     mBufferingWait(aBufferWaitTime),
@@ -390,17 +394,18 @@ nsWaveStateMachine::nsWaveStateMachine(n
     mMonitor(nsnull),
     mState(STATE_LOADING_METADATA),
     mNextState(STATE_PAUSED),
     mPlaybackPosition(0),
     mInitialVolume(aInitialVolume),
     mSeekTime(0.0f),
     mMetadataValid(PR_FALSE),
     mPositionChangeQueued(PR_FALSE),
-    mPaused(mNextState == STATE_PAUSED)
+    mPaused(mNextState == STATE_PAUSED),
+    mPlaybackEnded(PR_FALSE)
 {
   mMonitor = nsAutoMonitor::NewMonitor("nsWaveStateMachine");
 }
 
 nsWaveStateMachine::~nsWaveStateMachine()
 {
   nsAutoMonitor::DestroyMonitor(mMonitor);
 }
@@ -411,16 +416,17 @@ nsWaveStateMachine::Shutdown()
   ChangeState(STATE_SHUTDOWN);
 }
 
 void
 nsWaveStateMachine::Play()
 {
   nsAutoMonitor monitor(mMonitor);
   mPaused = PR_FALSE;
+  mPlaybackEnded = PR_FALSE;
   if (mState == STATE_ENDED) {
     Seek(0);
     return;
   }
   if (mState == STATE_LOADING_METADATA || mState == STATE_SEEKING) {
     mNextState = STATE_PLAYING;
   } else {
     ChangeState(STATE_PLAYING);
@@ -449,16 +455,17 @@ nsWaveStateMachine::Pause()
     ChangeState(STATE_PAUSED);
   }
 }
 
 void
 nsWaveStateMachine::Seek(float aTime)
 {
   nsAutoMonitor monitor(mMonitor);
+  mPlaybackEnded = PR_FALSE;
   mSeekTime = aTime;
   if (mSeekTime < 0.0f) {
     mSeekTime = 0.0f;
   }
   if (mState == STATE_LOADING_METADATA) {
     mNextState = STATE_SEEKING;
   } else if (mState != STATE_SEEKING) {
     if (mState == STATE_ENDED) {
@@ -506,17 +513,17 @@ nsWaveStateMachine::IsSeeking()
   nsAutoMonitor monitor(mMonitor);
   return mState == STATE_SEEKING || mNextState == STATE_SEEKING;
 }
 
 PRBool
 nsWaveStateMachine::IsEnded()
 {
   nsAutoMonitor monitor(mMonitor);
-  return mState == STATE_ENDED || mState == STATE_SHUTDOWN;
+  return mPlaybackEnded;
 }
 
 nsHTMLMediaElement::NextFrameStatus
 nsWaveStateMachine::GetNextFrameStatus()
 {
   nsAutoMonitor monitor(mMonitor);
   if (mState == STATE_BUFFERING)
     return nsHTMLMediaElement::NEXT_FRAME_UNAVAILABLE_BUFFERING;
@@ -784,16 +791,18 @@ nsWaveStateMachine::Run()
         mAudioStream->Drain();
         monitor.Enter();
 
         // After the drain call the audio stream is unusable. Close it so that
         // next time audio is used a new stream is created.
         CloseAudioStream();
       }
 
+      mPlaybackEnded = PR_TRUE;
+
       if (mState == STATE_ENDED) {
         nsCOMPtr<nsIRunnable> event =
           NS_NewRunnableMethod(mDecoder, &nsWaveDecoder::PlaybackEnded);
         NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
 
         // We've finished playback. Shutdown the state machine thread, 
         // in order to save memory on thread stacks, particuarly on Linux.
         event = new ShutdownThreadEvent(mDecoder->mPlaybackThread);
@@ -813,16 +822,17 @@ nsWaveStateMachine::Run()
         if (mState != STATE_SHUTDOWN) {
           NS_WARNING("Invalid state transition");
           ChangeState(STATE_ERROR);
         }
       }
       break;
 
     case STATE_SHUTDOWN:
+      mPlaybackEnded = PR_TRUE;
       CloseAudioStream();
       return NS_OK;
     }
   }
 
   return NS_OK;
 }
 
--- a/content/media/webm/Makefile.in
+++ b/content/media/webm/Makefile.in
@@ -58,9 +58,10 @@ CPPSRCS		= \
 
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES	+= \
 		-I$(srcdir)/../../base/src \
 		-I$(srcdir)/../../html/content/src \
+		$(MOZ_LIBVPX_INCLUDES) \
 		$(NULL)
--- a/content/svg/content/src/SVGLengthListSMILType.cpp
+++ b/content/svg/content/src/SVGLengthListSMILType.cpp
@@ -175,19 +175,19 @@ SVGLengthListSMILType::ComputeDistance(c
   const SVGLengthListAndInfo& from =
     *static_cast<const SVGLengthListAndInfo*>(aFrom.mU.mPtr);
   const SVGLengthListAndInfo& to =
     *static_cast<const SVGLengthListAndInfo*>(aTo.mU.mPtr);
 
   // To understand this code, see the comments documenting our Init() method,
   // and documenting SVGLengthListAndInfo::CanZeroPadList().
 
-  NS_ASSERTION(from.CanZeroPadList() == to.CanZeroPadList() ||
-               from.CanZeroPadList() && from.Length() == 0 ||
-               to.CanZeroPadList() && to.Length() == 0,
+  NS_ASSERTION((from.CanZeroPadList() == to.CanZeroPadList()) ||
+               (from.CanZeroPadList() && from.Length() == 0) ||
+               (to.CanZeroPadList() && to.Length() == 0),
                "Only \"zero\" nsSMILValues from the SMIL engine should "
                "return PR_TRUE for CanZeroPadList() when the attribute "
                "being animated can't be zero padded");
 
   if ((from.Length() < to.Length() && !from.CanZeroPadList()) ||
       (to.Length() < from.Length() && !to.CanZeroPadList())) {
     // nsSVGUtils::ReportToConsole
     return NS_ERROR_FAILURE;
@@ -250,19 +250,19 @@ SVGLengthListSMILType::Interpolate(const
   const SVGLengthListAndInfo& end =
     *static_cast<const SVGLengthListAndInfo*>(aEndVal.mU.mPtr);
   SVGLengthListAndInfo& result =
     *static_cast<SVGLengthListAndInfo*>(aResult.mU.mPtr);
 
   // To understand this code, see the comments documenting our Init() method,
   // and documenting SVGLengthListAndInfo::CanZeroPadList().
 
-  NS_ASSERTION(start.CanZeroPadList() == end.CanZeroPadList() ||
-               start.CanZeroPadList() && start.Length() == 0 ||
-               end.CanZeroPadList() && end.Length() == 0,
+  NS_ASSERTION((start.CanZeroPadList() == end.CanZeroPadList()) ||
+               (start.CanZeroPadList() && start.Length() == 0) ||
+               (end.CanZeroPadList() && end.Length() == 0),
                "Only \"zero\" nsSMILValues from the SMIL engine should "
                "return PR_TRUE for CanZeroPadList() when the attribute "
                "being animated can't be zero padded");
 
   if ((start.Length() < end.Length() && !start.CanZeroPadList()) ||
       (end.Length() < start.Length() && !end.CanZeroPadList())) {
     // nsSVGUtils::ReportToConsole
     return NS_ERROR_FAILURE;
--- a/content/svg/content/src/nsSVGElement.h
+++ b/content/svg/content/src/nsSVGElement.h
@@ -463,17 +463,17 @@ NS_NewSVG##_elementName##Element(nsICont
                                                                              \
   return rv;                                                                 \
 }
 
 #define NS_IMPL_NS_NEW_SVG_ELEMENT_CHECK_PARSER(_elementName)                \
 nsresult                                                                     \
 NS_NewSVG##_elementName##Element(nsIContent **aResult,                       \
                                  already_AddRefed<nsINodeInfo> aNodeInfo,    \
-                                 PRUint32 aFromParser)                       \
+                                 FromParser aFromParser)                     \
 {                                                                            \
   nsRefPtr<nsSVG##_elementName##Element> it =                                \
     new nsSVG##_elementName##Element(aNodeInfo, aFromParser);                \
   if (!it)                                                                   \
     return NS_ERROR_OUT_OF_MEMORY;                                           \
                                                                              \
   nsresult rv = it->Init();                                                  \
                                                                              \
--- a/content/svg/content/src/nsSVGElementFactory.cpp
+++ b/content/svg/content/src/nsSVGElementFactory.cpp
@@ -42,16 +42,18 @@
 #include "nsIAtom.h"
 #include "nsINodeInfo.h"
 #include "nsGkAtoms.h"
 #include "nsContentDLF.h"
 #include "nsContentUtils.h"
 #include "nsSVGUtils.h"
 #include "nsDebug.h"
 
+using namespace mozilla::dom;
+
 nsresult
 NS_NewSVGAElement(nsIContent **aResult,
                   already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGAltGlyphElement(nsIContent **aResult,
                          already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGPolylineElement(nsIContent **aResult,
@@ -72,17 +74,17 @@ nsresult
 NS_NewSVGRectElement(nsIContent **aResult,
                      already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGGElement(nsIContent **aResult,
                   already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGSVGElement(nsIContent **aResult,
                     already_AddRefed<nsINodeInfo> aNodeInfo,
-                    PRUint32 aFromParser);
+                    FromParser aFromParser);
 nsresult
 NS_NewSVGForeignObjectElement(nsIContent **aResult,
                               already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGPathElement(nsIContent **aResult,
                      already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGTextElement(nsIContent **aResult,
@@ -112,17 +114,17 @@ nsresult
 NS_NewSVGDefsElement(nsIContent **aResult,
                      already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGDescElement(nsIContent **aResult,
                      already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGScriptElement(nsIContent **aResult,
                        already_AddRefed<nsINodeInfo> aNodeInfo,
-                       PRUint32 aFromParser);
+                       FromParser aFromParser);
 nsresult
 NS_NewSVGUseElement(nsIContent **aResult,
                     already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGSymbolElement(nsIContent **aResult,
                        already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGMarkerElement(nsIContent **aResult,
@@ -236,17 +238,17 @@ NS_NewSVGMpathElement(nsIContent **aResu
                       already_AddRefed<nsINodeInfo> aNodeInfo);
 nsresult
 NS_NewSVGSetElement(nsIContent **aResult,
                     already_AddRefed<nsINodeInfo> aNodeInfo);
 #endif // MOZ_SMIL
 
 nsresult
 NS_NewSVGElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo,
-                 PRUint32 aFromParser)
+                 FromParser aFromParser)
 {
   NS_PRECONDITION(NS_SVGEnabled(),
                   "creating an SVG element while SVG disabled");
 
   static const char kSVGStyleSheetURI[] = "resource://gre/res/svg.css";
 
   // this bit of code is to load svg.css on demand
   nsIDocument *doc = aNodeInfo.get()->GetDocument();
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -67,16 +67,17 @@
 #include "nsSMILAnimationController.h"
 #include "nsSMILTypes.h"
 #include "nsIContentIterator.h"
 
 nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult);
 #endif // MOZ_SMIL
 
 using namespace mozilla;
+using namespace mozilla::dom;
 
 NS_SVG_VAL_IMPL_CYCLE_COLLECTION(nsSVGTranslatePoint::DOMVal, mElement)
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsSVGTranslatePoint::DOMVal)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsSVGTranslatePoint::DOMVal)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsSVGTranslatePoint::DOMVal)
   NS_INTERFACE_MAP_ENTRY(nsIDOMSVGPoint)
@@ -191,45 +192,42 @@ NS_INTERFACE_TABLE_HEAD(nsSVGSVGElement)
                            nsIDOMSVGZoomAndPan)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(SVGSVGElement)
 NS_INTERFACE_MAP_END_INHERITING(nsSVGSVGElementBase)
 
 //----------------------------------------------------------------------
 // Implementation
 
 nsSVGSVGElement::nsSVGSVGElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                 PRUint32 aFromParser)
+                                 FromParser aFromParser)
   : nsSVGSVGElementBase(aNodeInfo),
     mCoordCtx(nsnull),
     mViewportWidth(0),
     mViewportHeight(0),
     mCurrentTranslate(0.0f, 0.0f),
     mCurrentScale(1.0f),
     mPreviousTranslate(0.0f, 0.0f),
     mPreviousScale(1.0f),
     mRedrawSuspendCount(0)
 #ifdef MOZ_SMIL
-    ,mStartAnimationOnBindToTree(!aFromParser)
+  , mStartAnimationOnBindToTree(!aFromParser)
 #endif // MOZ_SMIL
 {
 }
 
 //----------------------------------------------------------------------
 // nsIDOMNode methods
 
 // From NS_IMPL_ELEMENT_CLONE_WITH_INIT(nsSVGSVGElement)
 nsresult
 nsSVGSVGElement::Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const
 {
   *aResult = nsnull;
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
-  nsSVGSVGElement *it = new nsSVGSVGElement(ni.forget(), PR_FALSE);
-  if (!it) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+  nsSVGSVGElement *it = new nsSVGSVGElement(ni.forget(), NOT_FROM_PARSER);
 
   nsCOMPtr<nsINode> kungFuDeathGrip = it;
   nsresult rv = it->Init();
   rv |= CopyInnerTo(it);
   if (NS_SUCCEEDED(rv)) {
     kungFuDeathGrip.swap(*aResult);
   }
 
--- a/content/svg/content/src/nsSVGSVGElement.h
+++ b/content/svg/content/src/nsSVGSVGElement.h
@@ -46,16 +46,17 @@
 #include "nsIDOMSVGLocatable.h"
 #include "nsIDOMSVGZoomAndPan.h"
 #include "nsIDOMSVGMatrix.h"
 #include "nsIDOMSVGPoint.h"
 #include "nsSVGLength2.h"
 #include "nsSVGEnum.h"
 #include "nsSVGViewBox.h"
 #include "nsSVGPreserveAspectRatio.h"
+#include "mozilla/dom/FromParser.h"
 
 #ifdef MOZ_SMIL
 class nsSMILTimeContainer;
 #endif // MOZ_SMIL
 
 #define QI_AND_CAST_TO_NSSVGSVGELEMENT(base)                                  \
   (nsCOMPtr<nsIDOMSVGSVGElement>(do_QueryInterface(base)) ?                   \
    static_cast<nsSVGSVGElement*>(base.get()) : nsnull)
@@ -128,18 +129,19 @@ class nsSVGSVGElement : public nsSVGSVGE
                         public nsIDOMSVGZoomAndPan
 {
   friend class nsSVGOuterSVGFrame;
   friend class nsSVGInnerSVGFrame;
 
 protected:
   friend nsresult NS_NewSVGSVGElement(nsIContent **aResult,
                                       already_AddRefed<nsINodeInfo> aNodeInfo,
-                                      PRUint32 aFromParser);
-  nsSVGSVGElement(already_AddRefed<nsINodeInfo> aNodeInfo, PRUint32 aFromParser);
+                                      mozilla::dom::FromParser aFromParser);
+  nsSVGSVGElement(already_AddRefed<nsINodeInfo> aNodeInfo,
+                  mozilla::dom::FromParser aFromParser);
   
 public:
 
   // interfaces:
   NS_DECL_ISUPPORTS_INHERITED
 #ifdef MOZ_SMIL
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsSVGSVGElement, nsSVGSVGElementBase)
 #endif // MOZ_SMIL
--- a/content/svg/content/src/nsSVGScriptElement.cpp
+++ b/content/svg/content/src/nsSVGScriptElement.cpp
@@ -44,29 +44,31 @@
 #include "nsCOMPtr.h"
 #include "nsSVGString.h"
 #include "nsIDocument.h"
 #include "nsIURI.h"
 #include "nsNetUtil.h"
 #include "nsScriptElement.h"
 #include "nsIDOMText.h"
 
+using namespace mozilla::dom;
+
 typedef nsSVGElement nsSVGScriptElementBase;
 
 class nsSVGScriptElement : public nsSVGScriptElementBase,
                            public nsIDOMSVGScriptElement, 
                            public nsIDOMSVGURIReference,
                            public nsScriptElement
 {
 protected:
   friend nsresult NS_NewSVGScriptElement(nsIContent **aResult,
                                          already_AddRefed<nsINodeInfo> aNodeInfo,
-                                         PRUint32 aFromParser);
+                                         FromParser aFromParser);
   nsSVGScriptElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     PRUint32 aFromParser);
+                     FromParser aFromParser);
   
 public:
   // interfaces:
   
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIDOMSVGSCRIPTELEMENT
   NS_DECL_NSIDOMSVGURIREFERENCE
 
@@ -128,37 +130,34 @@ NS_INTERFACE_TABLE_HEAD(nsSVGScriptEleme
                            nsIScriptElement, nsIMutationObserver)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(SVGScriptElement)
 NS_INTERFACE_MAP_END_INHERITING(nsSVGScriptElementBase)
 
 //----------------------------------------------------------------------
 // Implementation
 
 nsSVGScriptElement::nsSVGScriptElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       PRUint32 aFromParser)
+                                       FromParser aFromParser)
   : nsSVGScriptElementBase(aNodeInfo)
   , nsScriptElement(aFromParser)
 {
   mDoneAddingChildren = !aFromParser;
   AddMutationObserver(this);
 }
 
 //----------------------------------------------------------------------
 // nsIDOMNode methods
 
 nsresult
 nsSVGScriptElement::Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const
 {
   *aResult = nsnull;
 
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
-  nsSVGScriptElement* it = new nsSVGScriptElement(ni.forget(), PR_FALSE);
-  if (!it) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+  nsSVGScriptElement* it = new nsSVGScriptElement(ni.forget(), NOT_FROM_PARSER);
 
   nsCOMPtr<nsINode> kungFuDeathGrip = it;
   nsresult rv = it->Init();
   rv |= CopyInnerTo(it);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // The clone should be marked evaluated if we are.
   it->mAlreadyStarted = mAlreadyStarted;
--- a/content/svg/content/src/nsSVGUseElement.cpp
+++ b/content/svg/content/src/nsSVGUseElement.cpp
@@ -339,17 +339,18 @@ nsSVGUseElement::CreateAnonymousContent(
       return nsnull;
 
     nsCOMPtr<nsINodeInfo> nodeInfo;
     nodeInfo = nodeInfoManager->GetNodeInfo(nsGkAtoms::svg, nsnull, kNameSpaceID_SVG);
     if (!nodeInfo)
       return nsnull;
 
     nsCOMPtr<nsIContent> svgNode;
-    NS_NewSVGSVGElement(getter_AddRefs(svgNode), nodeInfo.forget(), PR_FALSE);
+    NS_NewSVGSVGElement(getter_AddRefs(svgNode), nodeInfo.forget(),
+                        NOT_FROM_PARSER);
 
     if (!svgNode)
       return nsnull;
     
     if (newcontent->HasAttr(kNameSpaceID_None, nsGkAtoms::viewBox)) {
       nsAutoString viewbox;
       newcontent->GetAttr(kNameSpaceID_None, nsGkAtoms::viewBox, viewbox);
       svgNode->SetAttr(kNameSpaceID_None, nsGkAtoms::viewBox, viewbox, PR_FALSE);
--- a/content/svg/content/src/nsSVGUseElement.h
+++ b/content/svg/content/src/nsSVGUseElement.h
@@ -41,28 +41,29 @@
 #include "nsIDOMSVGURIReference.h"
 #include "nsIDOMSVGUseElement.h"
 #include "nsStubMutationObserver.h"
 #include "nsSVGGraphicElement.h"
 #include "nsSVGLength2.h"
 #include "nsSVGString.h"
 #include "nsTArray.h"
 #include "nsReferencedElement.h"
+#include "mozilla/dom/FromParser.h"
 
 class nsIContent;
 class nsINodeInfo;
 
 #define NS_SVG_USE_ELEMENT_IMPL_CID \
 { 0x55fb86fe, 0xd81f, 0x4ae4, \
   { 0x80, 0x3f, 0xeb, 0x90, 0xfe, 0xe0, 0x7a, 0xe9 } }
 
 nsresult
 NS_NewSVGSVGElement(nsIContent **aResult,
                     already_AddRefed<nsINodeInfo> aNodeInfo,
-                    PRUint32 aFromParser);
+                    mozilla::dom::FromParser aFromParser);
 
 typedef nsSVGGraphicElement nsSVGUseElementBase;
 
 class nsSVGUseElement : public nsSVGUseElementBase,
                         public nsIDOMSVGURIReference,
                         public nsIDOMSVGUseElement,
                         public nsStubMutationObserver
 {
--- a/content/xbl/src/nsXBLContentSink.cpp
+++ b/content/xbl/src/nsXBLContentSink.cpp
@@ -865,17 +865,17 @@ nsXBLContentSink::ConstructParameter(con
     mMethod->AddParameter(nsDependentString(name));
   }
 }
 
 nsresult
 nsXBLContentSink::CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                                 nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                                 nsIContent** aResult, PRBool* aAppendContent,
-                                PRUint32 aFromParser)
+                                FromParser aFromParser)
 {
 #ifdef MOZ_XUL
   if (!aNodeInfo->NamespaceEquals(kNameSpaceID_XUL)) {
 #endif
     return nsXMLContentSink::CreateElement(aAtts, aAttsCount, aNodeInfo,
                                            aLineNumber, aResult,
                                            aAppendContent, aFromParser);
 #ifdef MOZ_XUL
--- a/content/xbl/src/nsXBLContentSink.h
+++ b/content/xbl/src/nsXBLContentSink.h
@@ -119,17 +119,17 @@ protected:
                            nsIAtom* aTagName,
                            PRUint32 aLineNumber);
 
     PRBool NotifyForDocElement() { return PR_FALSE; }
 
     nsresult CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                            nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                            nsIContent** aResult, PRBool* aAppendContent,
-                           PRUint32 aFromParser);
+                           mozilla::dom::FromParser aFromParser);
     
     nsresult AddAttributes(const PRUnichar** aAtts, 
                            nsIContent* aContent);
 
 #ifdef MOZ_XUL    
     nsresult AddAttributesToXULPrototype(const PRUnichar **aAtts, 
                                          PRUint32 aAttsCount, 
                                          nsXULPrototypeElement* aElement);
--- a/content/xbl/src/nsXBLDocumentInfo.cpp
+++ b/content/xbl/src/nsXBLDocumentInfo.cpp
@@ -322,21 +322,19 @@ nsXBLDocGlobalObject::EnsureScriptEnviro
   JSAutoRequest ar(cx);
 
   // nsJSEnvironment set the error reporter to NS_ScriptErrorReporter so
   // we must apparently override that with our own (although it isn't clear 
   // why - see bug 339647)
   JS_SetErrorReporter(cx, XBL_ProtoErrorReporter);
 
   nsIPrincipal *principal = GetPrincipal();
-  nsCString origin;
   JSCompartment *compartment;
 
-  principal->GetOrigin(getter_Copies(origin));
-  rv = xpc_CreateGlobalObject(cx, &gSharedGlobalClass, origin, principal,
+  rv = xpc_CreateGlobalObject(cx, &gSharedGlobalClass, principal, nsnull,
                               false, &mJSObject, &compartment);
   NS_ENSURE_SUCCESS(rv, nsnull);
 
   ::JS_SetGlobalObject(cx, mJSObject);
 
   // Add an owning reference from JS back to us. This'll be
   // released when the JSObject is finalized.
   ::JS_SetPrivate(cx, mJSObject, this);
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -97,16 +97,18 @@
 #include "nsIHTMLDocument.h"
 #include "mozAutoDocUpdate.h"
 #include "nsMimeTypes.h"
 
 #ifdef MOZ_SVG
 #include "nsHtml5SVGLoadDispatcher.h"
 #endif
 
+using namespace mozilla::dom;
+
 // XXX Open Issues:
 // 1) what's not allowed - We need to figure out which HTML tags
 //    (prefixed with a HTML namespace qualifier) are explicitly not
 //    allowed (if any).
 // 2) factoring code with nsHTMLContentSink - There's some amount of
 //    common code between this and the HTML content sink. This will
 //    increase as we support more and more HTML elements. How can code
 //    from the code be factored?
@@ -486,17 +488,17 @@ nsXMLContentSink::SetParser(nsIParser* a
   mParser = aParser;
   return NS_OK;
 }
 
 nsresult
 nsXMLContentSink::CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                                 nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                                 nsIContent** aResult, PRBool* aAppendContent,
-                                PRUint32 aFromParser)
+                                FromParser aFromParser)
 {
   NS_ASSERTION(aNodeInfo, "can't create element without nodeinfo");
 
   *aResult = nsnull;
   *aAppendContent = PR_TRUE;
   nsresult rv = NS_OK;
 
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
@@ -1015,17 +1017,18 @@ nsXMLContentSink::HandleStartElement(con
     return NS_OK;
   }
   
   nsCOMPtr<nsINodeInfo> nodeInfo;
   nodeInfo = mNodeInfoManager->GetNodeInfo(localName, prefix, nameSpaceID);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   result = CreateElement(aAtts, aAttsCount, nodeInfo, aLineNumber,
-                         getter_AddRefs(content), &appendContent, PR_TRUE);
+                         getter_AddRefs(content), &appendContent,
+                         FROM_PARSER_NETWORK);
   NS_ENSURE_SUCCESS(result, result);
 
   // Have to do this before we push the new content on the stack... and have to
   // do that before we set attributes, call BindToTree, etc.  Ideally we'd push
   // on the stack inside CreateElement (which is effectively what the HTML sink
   // does), but that's hard with all the subclass overrides going on.
   nsCOMPtr<nsIContent> parent = GetCurrentContent();
   
--- a/content/xml/document/src/nsXMLContentSink.h
+++ b/content/xml/document/src/nsXMLContentSink.h
@@ -42,16 +42,17 @@
 #include "nsIXMLContentSink.h"
 #include "nsIExpatSink.h"
 #include "nsIDocumentTransformer.h"
 #include "nsTArray.h"
 #include "nsCOMPtr.h"
 #include "nsCRT.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIDTD.h"
+#include "mozilla/dom/FromParser.h"
 
 class nsIDocument;
 class nsIURI;
 class nsIContent;
 class nsINodeInfo;
 class nsIParser;
 class nsIViewManager;
 
@@ -132,17 +133,17 @@ protected:
   //  return TRUE if this call set the root element
   virtual PRBool SetDocElement(PRInt32 aNameSpaceID, 
                                nsIAtom *aTagName,
                                nsIContent *aContent);
   virtual PRBool NotifyForDocElement() { return PR_TRUE; }
   virtual nsresult CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                                  nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                                  nsIContent** aResult, PRBool* aAppendContent,
-                                 PRUint32 aFromParser);
+                                 mozilla::dom::FromParser aFromParser);
 
   // aParent is allowed to be null here if this is the root content
   // being closed
   virtual nsresult CloseElement(nsIContent* aContent);
 
   virtual nsresult FlushText(PRBool aReleaseTextNode = PR_TRUE);
 
   nsresult AddContentAsLeaf(nsIContent *aContent);
--- a/content/xml/document/src/nsXMLFragmentContentSink.cpp
+++ b/content/xml/document/src/nsXMLFragmentContentSink.cpp
@@ -58,16 +58,18 @@
 #include "nsContentUtils.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsNetUtil.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
 #include "nsTArray.h"
 #include "nsCycleCollectionParticipant.h"
 
+using namespace mozilla::dom;
+
 class nsXMLFragmentContentSink : public nsXMLContentSink,
                                  public nsIFragmentContentSink
 {
 public:
   nsXMLFragmentContentSink(PRBool aAllContent = PR_FALSE);
   virtual ~nsXMLFragmentContentSink();
 
   NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
@@ -112,17 +114,17 @@ public:
 
 protected:
   virtual PRBool SetDocElement(PRInt32 aNameSpaceID, 
                                nsIAtom *aTagName,
                                nsIContent *aContent);
   virtual nsresult CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                                  nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                                  nsIContent** aResult, PRBool* aAppendContent,
-                                 PRUint32 aFromParser);
+                                 mozilla::dom::FromParser aFromParser);
   virtual nsresult CloseElement(nsIContent* aContent);
 
   virtual void MaybeStartLayout(PRBool aIgnorePendingSheets);
 
   // nsContentSink overrides
   virtual nsresult ProcessStyleLink(nsIContent* aElement,
                                     const nsSubstring& aHref,
                                     PRBool aAlternate,
@@ -254,24 +256,24 @@ nsXMLFragmentContentSink::SetDocElement(
   // this is a fragment, not a document
   return PR_FALSE;
 }
 
 nsresult
 nsXMLFragmentContentSink::CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                                         nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                                         nsIContent** aResult, PRBool* aAppendContent,
-                                        PRUint32 aFromParser)
+                                        FromParser /*aFromParser*/)
 {
   // Claim to not be coming from parser, since we don't do any of the
   // fancy CloseElement stuff.
   nsresult rv = nsXMLContentSink::CreateElement(aAtts, aAttsCount,
                                                 aNodeInfo, aLineNumber,
                                                 aResult, aAppendContent,
-                                                PR_FALSE);
+                                                NOT_FROM_PARSER);
 
   // When we aren't grabbing all of the content we, never open a doc
   // element, we run into trouble on the first element, so we don't append,
   // and simply push this onto the content stack.
   if (!mAllContent && mContentStack.Length() == 0) {
     *aAppendContent = PR_FALSE;
   }
 
--- a/content/xslt/src/xslt/txMozillaTextOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaTextOutput.cpp
@@ -51,16 +51,18 @@
 #include "nsIParser.h"
 #include "nsICharsetAlias.h"
 #include "nsIPrincipal.h"
 #include "txURIUtils.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsContentUtils.h"
 #include "nsGkAtoms.h"
 
+using namespace mozilla::dom;
+
 txMozillaTextOutput::txMozillaTextOutput(nsIDOMDocument* aSourceDocument,
                                          nsIDOMDocument* aResultDocument,
                                          nsITransformObserver* aObserver)
 {
     mObserver = do_GetWeakReference(aObserver);
     createResultDocument(aSourceDocument, aResultDocument);
 }
 
@@ -288,11 +290,10 @@ txMozillaTextOutput::createXHTMLElement(
 {
     *aResult = nsnull;
 
     nsCOMPtr<nsINodeInfo> ni;
     ni = mDocument->NodeInfoManager()->
         GetNodeInfo(aName, nsnull, kNameSpaceID_XHTML);
     NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY);
 
-    return NS_NewHTMLElement(aResult, ni.forget(), PR_FALSE);
+    return NS_NewHTMLElement(aResult, ni.forget(), NOT_FROM_PARSER);
 }
-
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp
@@ -68,16 +68,18 @@
 #include "nsIHTMLContentSink.h"
 #include "nsContentUtils.h"
 #include "txXMLUtils.h"
 #include "nsContentSink.h"
 #include "nsINode.h"
 #include "nsContentCreatorFunctions.h"
 #include "txError.h"
 
+using namespace mozilla::dom;
+
 #define TX_ENSURE_CURRENTNODE                           \
     NS_ASSERTION(mCurrentNode, "mCurrentNode is NULL"); \
     if (!mCurrentNode)                                  \
         return NS_ERROR_UNEXPECTED
 
 txMozillaXMLOutput::txMozillaXMLOutput(const nsSubstring& aRootName,
                                        PRInt32 aRootNsID,
                                        txOutputFormat* aFormat,
@@ -252,18 +254,25 @@ txMozillaXMLOutput::endDocument(nsresult
     nsresult rv = closePrevious(PR_TRUE);
     if (NS_FAILED(rv)) {
         if (mNotifier) {
             mNotifier->OnTransformEnd(rv);
         }
         
         return rv;
     }
-    // This should really be handled by nsIDocument::EndLoad
-    mDocument->SetReadyStateInternal(nsIDocument::READYSTATE_INTERACTIVE);
+
+    if (mCreatingNewDocument) {
+        // This should really be handled by nsIDocument::EndLoad
+        mDocument->SetReadyStateInternal(nsIDocument::READYSTATE_INTERACTIVE);
+        nsScriptLoader* loader = mDocument->ScriptLoader();
+        if (loader) {
+            loader->ParsingComplete(PR_FALSE);
+        }
+    }
 
     if (!mRefreshString.IsEmpty()) {
         nsPIDOMWindow *win = mDocument->GetWindow();
         if (win) {
             nsCOMPtr<nsIRefreshURI> refURI =
                 do_QueryInterface(win->GetDocShell());
             if (refURI) {
                 refURI->SetupRefreshURIFromHeader(mDocument->GetDocBaseURI(),
@@ -305,30 +314,42 @@ txMozillaXMLOutput::endElement()
 
     // Handle html-elements
     if (!mNoFixup) {
         if (element->IsHTML()) {
             rv = endHTMLElement(element);
             NS_ENSURE_SUCCESS(rv, rv);
         }
 
-        // Handle script elements
-        if (element->Tag() == nsGkAtoms::script &&
-            (element->IsHTML() ||
-            element->GetNameSpaceID() == kNameSpaceID_SVG)) {
+        // Handle elements that are different when parser-created
+        PRInt32 ns = element->GetNameSpaceID();
+        nsIAtom* localName = element->Tag();
+
+        if ((ns == kNameSpaceID_XHTML && (localName == nsGkAtoms::script ||
+                                          localName == nsGkAtoms::title ||
+                                          localName == nsGkAtoms::object ||
+                                          localName == nsGkAtoms::applet ||
+                                          localName == nsGkAtoms::select ||
+                                          localName == nsGkAtoms::textarea)) ||
+            (ns == kNameSpaceID_SVG && (localName == nsGkAtoms::script ||
+                                        localName == nsGkAtoms::title))) {
 
             rv = element->DoneAddingChildren(PR_TRUE);
 
             // If the act of insertion evaluated the script, we're fine.
             // Else, add this script element to the array of loading scripts.
             if (rv == NS_ERROR_HTMLPARSER_BLOCK) {
                 nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(element);
                 rv = mNotifier->AddScriptElement(sele);
                 NS_ENSURE_SUCCESS(rv, rv);
             }
+        } else if (ns == kNameSpaceID_XHTML &&
+                   (localName == nsGkAtoms::input ||
+                    localName == nsGkAtoms::button)) {
+          element->DoneCreatingElement();
         }
     }
 
     if (mCreatingNewDocument) {
         // Handle all sorts of stylesheets
         nsCOMPtr<nsIStyleSheetLinkingElement> ssle =
             do_QueryInterface(mCurrentNode);
         if (ssle) {
@@ -426,16 +447,23 @@ txMozillaXMLOutput::processingInstructio
 
 nsresult
 txMozillaXMLOutput::startDocument()
 {
     if (mNotifier) {
         mNotifier->OnTransformStart();
     }
 
+    if (mCreatingNewDocument) {
+        nsScriptLoader* loader = mDocument->ScriptLoader();
+        if (loader) {
+            loader->BeginDeferringScripts();
+        }
+    }
+
     return NS_OK;
 }
 
 nsresult
 txMozillaXMLOutput::startElement(nsIAtom* aPrefix, nsIAtom* aLocalName,
                                  nsIAtom* aLowercaseLocalName,
                                  const PRInt32 aNsID)
 {
@@ -531,17 +559,19 @@ txMozillaXMLOutput::startElementInternal
     mTableState = NORMAL;
     mOpenedElementIsHTML = PR_FALSE;
 
     // Create the element
     nsCOMPtr<nsINodeInfo> ni;
     ni = mNodeInfoManager->GetNodeInfo(aLocalName, aPrefix, aNsID);
     NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY);
 
-    NS_NewElement(getter_AddRefs(mOpenedElement), aNsID, ni.forget(), PR_FALSE);
+    NS_NewElement(getter_AddRefs(mOpenedElement), aNsID, ni.forget(),
+                  mCreatingNewDocument ?
+                  FROM_PARSER_XSLT : FROM_PARSER_FRAGMENT);
 
     // Set up the element and adjust state
     if (!mNoFixup) {
         if (aNsID == kNameSpaceID_XHTML) {
             mOpenedElementIsHTML = (mOutputFormat.mMethod == eHTMLOutput);
             rv = startHTMLElement(mOpenedElement, mOpenedElementIsHTML);
             NS_ENSURE_SUCCESS(rv, rv);
 
@@ -942,17 +972,19 @@ txMozillaXMLOutput::createHTMLElement(ns
 
     *aResult = nsnull;
 
     nsCOMPtr<nsINodeInfo> ni;
     ni = mNodeInfoManager->GetNodeInfo(aName, nsnull,
                                        kNameSpaceID_XHTML);
     NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY);
 
-    return NS_NewHTMLElement(aResult, ni.forget(), PR_FALSE);
+    return NS_NewHTMLElement(aResult, ni.forget(), mCreatingNewDocument ?
+        FROM_PARSER_XSLT : FROM_PARSER_FRAGMENT);
+
 }
 
 txTransformNotifier::txTransformNotifier()
     : mPendingStylesheetCount(0),
       mInTransform(PR_FALSE)      
 {
 }
 
--- a/content/xul/document/src/nsXULDocument.cpp
+++ b/content/xul/document/src/nsXULDocument.cpp
@@ -3691,18 +3691,19 @@ nsXULDocument::CreateElementFromPrototyp
         newNodeInfo = mNodeInfoManager->GetNodeInfo(aPrototype->mNodeInfo->NameAtom(),
                                                     aPrototype->mNodeInfo->GetPrefixAtom(),
                                                     aPrototype->mNodeInfo->NamespaceID());
         if (!newNodeInfo) return NS_ERROR_OUT_OF_MEMORY;
         nsCOMPtr<nsIContent> content;
         PRInt32 ns = newNodeInfo->NamespaceID();
         nsCOMPtr<nsINodeInfo> xtfNi = newNodeInfo;
         rv = NS_NewElement(getter_AddRefs(content), ns, newNodeInfo.forget(),
-                           PR_FALSE);
-        if (NS_FAILED(rv)) return rv;
+                           NOT_FROM_PARSER);
+        if (NS_FAILED(rv))
+            return rv;
 
         result = content->AsElement();
 
 #ifdef MOZ_XTF
         if (result && xtfNi->NamespaceID() > kNameSpaceID_LastBuiltin) {
             result->BeginAddingChildren();
         }
 #endif
--- a/content/xul/document/src/nsXULPrototypeDocument.cpp
+++ b/content/xul/document/src/nsXULPrototypeDocument.cpp
@@ -727,22 +727,20 @@ nsXULPDGlobalObject::EnsureScriptEnviron
     // attach it as the global for this context.  Then, ::SetScriptContext
     // will re-fetch the global and set it up in our language globals array.
     if (lang_id == nsIProgrammingLanguage::JAVASCRIPT) {
       // some special JS specific code we should abstract
       JSContext *cx = (JSContext *)ctxNew->GetNativeContext();
       JSAutoRequest ar(cx);
 
       nsIPrincipal *principal = GetPrincipal();
-      nsCString origin;
       JSObject *newGlob;
       JSCompartment *compartment;
 
-      principal->GetOrigin(getter_Copies(origin));
-      rv = xpc_CreateGlobalObject(cx, &gSharedGlobalClass, origin, principal,
+      rv = xpc_CreateGlobalObject(cx, &gSharedGlobalClass, principal, nsnull,
                                   false, &newGlob, &compartment);
       NS_ENSURE_SUCCESS(rv, nsnull);
 
       ::JS_SetGlobalObject(cx, newGlob);
 
       // Add an owning reference from JS back to us. This'll be
       // released when the JSObject is finalized.
       ::JS_SetPrivate(cx, newGlob, this);
--- a/content/xul/templates/src/nsXULContentBuilder.cpp
+++ b/content/xul/templates/src/nsXULContentBuilder.cpp
@@ -1399,17 +1399,17 @@ nsXULContentBuilder::CreateElement(PRInt
 
     nsresult rv;
     nsCOMPtr<nsIContent> result;
 
     nsCOMPtr<nsINodeInfo> nodeInfo;
     nodeInfo = doc->NodeInfoManager()->GetNodeInfo(aTag, nsnull, aNameSpaceID);
 
     rv = NS_NewElement(getter_AddRefs(result), aNameSpaceID, nodeInfo.forget(),