Merge mozilla-central into the branch for asynchronous plugin painting on Windows.
authorBenjamin Smedberg <benjamin@smedbergs.us>
Fri, 05 Nov 2010 15:56:28 -0400
changeset 57228 0aaabea2708e4ff27340b91a5337bc788231b1ae
parent 57227 671bd739dbff035d5b1df3ce1e53e2974efdc3a2 (current diff)
parent 56941 99de996537efa0fbf8152dd28b063d9f40745e4b (diff)
child 57229 4ab9ea27785d333afa1fd8f22c8222ee015b8807
push id16846
push userbsmedberg@mozilla.com
push dateWed, 10 Nov 2010 15:29:47 +0000
treeherdermozilla-central@bdbef533364f [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
Merge mozilla-central into the branch for asynchronous plugin painting on Windows.
dom/plugins/PluginInstanceParent.cpp
dom/plugins/PluginModuleParent.cpp
dom/plugins/PluginModuleParent.h
ipc/ipdl/ipdl/lower.py
layout/generic/nsObjectFrame.cpp
modules/plugin/test/crashtests/crashtests.list
services/crypto/modules/threaded.js
testing/mozmill/tests/firefox/testPrivateBrowsing/testStartStopPBMode.js
--- 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/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -377,17 +377,18 @@ nsAccessNode::ScrollTo(PRUint32 aScrollT
   nsIFrame *frame = GetFrame();
   NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIContent> content = frame->GetContent();
   NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
 
   PRInt16 vPercent, hPercent;
   nsCoreUtils::ConvertScrollTypeToPercents(aScrollType, &vPercent, &hPercent);
-  return shell->ScrollContentIntoView(content, vPercent, hPercent);
+  return shell->ScrollContentIntoView(content, vPercent, hPercent,
+                                      nsIPresShell::SCROLL_OVERFLOW_HIDDEN);
 }
 
 NS_IMETHODIMP
 nsAccessNode::ScrollToPoint(PRUint32 aCoordinateType, PRInt32 aX, PRInt32 aY)
 {
   nsIFrame *frame = GetFrame();
   if (!frame)
     return NS_ERROR_FAILURE;
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -2363,17 +2363,18 @@ nsAccessible::DispatchClickEvent(nsICont
 {
   if (IsDefunct())
     return;
 
   nsCOMPtr<nsIPresShell> presShell = GetPresShell();
 
   // Scroll into view.
   presShell->ScrollContentIntoView(aContent, NS_PRESSHELL_SCROLL_ANYWHERE,
-                                   NS_PRESSHELL_SCROLL_ANYWHERE);
+                                   NS_PRESSHELL_SCROLL_ANYWHERE,
+                                   nsIPresShell::SCROLL_OVERFLOW_HIDDEN);
 
   // Fire mouse down and mouse up events.
   PRBool res = nsCoreUtils::DispatchMouseEvent(NS_MOUSE_BUTTON_DOWN, presShell,
                                                aContent);
   if (!res)
     return;
 
   nsCoreUtils::DispatchMouseEvent(NS_MOUSE_BUTTON_UP, presShell, aContent);
--- 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>
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
@@ -3980,16 +3980,37 @@ var XULBrowserWindow = {
 
   setOverLink: function (link) {
     // Encode bidirectional formatting characters.
     // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
     link = link.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
                         encodeURIComponent);
     gURLBar.setOverLink(link);
   },
+  
+  // Called before links are navigated to to allow us to retarget them if needed.
+  onBeforeLinkTraversal: function(originalTarget, linkURI, linkNode, isAppTab) {
+    // Don't modify non-default targets or targets that aren't in top-level app
+    // tab docshells (isAppTab will be false for app tab subframes).
+    if (originalTarget != "" || !isAppTab)
+      return originalTarget;
+
+    let docURI = linkNode.ownerDocument.documentURIObject;
+    try {
+      let docURIDomain = Services.eTLD.getBaseDomain(docURI, 0);
+      let linkURIDomain = Services.eTLD.getBaseDomain(linkURI, 0);
+      // External links from within app tabs should always open in new tabs
+      // instead of replacing the app tab's page (Bug 575561)
+      if (docURIDomain != linkURIDomain)
+        return "_blank";
+    } catch(e) {
+      // If getBaseDomain fails, we return originalTarget below.
+    }
+    return originalTarget;
+  },
 
   onLinkIconAvailable: function (aIconURL) {
     if (gProxyFavIcon && gBrowser.userTypedValue === null)
       PageProxySetIcon(aIconURL); // update the favicon in the URL bar
   },
 
   onProgressChange: function (aWebProgress, aRequest,
                               aCurSelfProgress, aMaxSelfProgress,
@@ -4697,24 +4718,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>
@@ -821,22 +457,17 @@
 <deck flex="1" id="tab-view-deck">
 <vbox flex="1">
 
   <toolbox id="navigator-toolbox"
            defaultmode="icons" mode="icons"
 #ifdef WINCE
            defaulticonsize="small" iconsize="small"
 #endif
-#ifdef XP_WIN
            tabsontop="true"
-#endif
-#ifdef XP_MACOSX
-           tabsontop="true"
-#endif
            persist="tabsontop">
     <!-- Menu -->
     <toolbar type="menubar" id="toolbar-menubar" class="chromeclass-menubar" customizable="true"
              defaultset="menubar-items"
              mode="icons" iconsize="small" defaulticonsize="small"
              lockiconsize="true"
 #ifdef MENUBAR_CAN_AUTOHIDE
              toolbarname="&menubarCmd.label;"
@@ -1016,21 +647,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/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -186,16 +186,18 @@
           if (aTab.hidden)
             this.showTab(aTab);
 
           this.moveTabTo(aTab, this._numPinnedTabs);
           aTab.setAttribute("pinned", "true");
           this.tabContainer._positionPinnedTabs();
           this.tabContainer.adjustTabstrip();
 
+          this.getBrowserForTab(aTab).docShell.isAppTab = true;
+
           let event = document.createEvent("Events");
           event.initEvent("TabPinned", true, false);
           aTab.dispatchEvent(event);
         ]]></body>
       </method>
 
       <method name="unpinTab">
         <parameter name="aTab"/>
@@ -205,16 +207,18 @@
 
           this.moveTabTo(aTab, this._numPinnedTabs - 1);
           aTab.setAttribute("fadein", "true");
           aTab.removeAttribute("pinned");
           aTab.style.MozMarginStart = "";
           this.tabContainer._positionPinnedTabs();
           this.tabContainer.adjustTabstrip();
 
+          this.getBrowserForTab(aTab).docShell.isAppTab = false;
+
           let event = document.createEvent("Events");
           event.initEvent("TabUnpinned", true, false);
           aTab.dispatchEvent(event);
         ]]></body>
       </method>
 
       <method name="previewTab">
         <parameter name="aTab"/>
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -140,16 +140,17 @@ endif
                  browser_bug555224.js \
                  browser_bug555767.js \
                  browser_bug556061.js \
                  browser_bug559991.js \
                  browser_bug561623.js \
                  browser_bug561636.js \
                  browser_bug562649.js \
                  browser_bug563588.js \
+                 browser_bug575561.js \
                  browser_bug577121.js \
                  browser_bug579872.js \
                  browser_bug580956.js \
                  browser_bug581242.js \
                  browser_bug581253.js \
                  browser_bug581947.js \
                  browser_bug585785.js \
                  browser_bug585830.js \
@@ -213,16 +214,18 @@ endif
                  alltabslistener.html \
                  zoom_test.html \
                  dummy_page.html \
                  browser_tabMatchesInAwesomebar.js \
                  file_bug550565_popup.html \
                  file_bug550565_favicon.ico \
                  browser_overLinkInLocationBar.js \
                  browser_aboutHome.js \
+                 app_bug575561.html \
+                 app_subframe_bug575561.html \
                  $(NULL)
 
 # compartment-disabled
 #                 browser_popupUI.js \
 #                 browser_tab_dragdrop.js \
 
 ifneq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 _BROWSER_FILES += \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/app_bug575561.html
@@ -0,0 +1,16 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=575561
+-->
+  <head>
+    <title>Test for links in app tabs</title>
+  </head>
+  <body>
+    <a href="http://example.com/browser/browser/base/content/test/dummy_page.html">same domain</a>
+    <a href="http://test1.example.com/browser/browser/base/content/test/dummy_page.html">same domain (different subdomain)</a>
+    <a href="http://example.org/browser/browser/base/content/test/dummy_page.html">different domain</a>
+    <a href="http://example.org/browser/browser/base/content/test/dummy_page.html" target="foo">different domain (with target)</a>
+    <iframe src="app_subframe_bug575561.html"></iframe>
+  </body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/app_subframe_bug575561.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=575561
+-->
+  <head>
+    <title>Test for links in app tab subframes</title>
+  </head>
+  <body>
+    <a href="http://example.org/browser/browser/base/content/test/dummy_page.html">different domain</a>
+  </body>
+</html>
--- 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);
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_bug575561.js
@@ -0,0 +1,77 @@
+function test() {
+  waitForExplicitFinish();
+
+  // Pinned: Link to the same domain should not open a new tab
+  // Tests link to http://example.com/browser/browser/base/content/test/dummy_page.html  
+  testLink(0, true, false, function() {
+    // Pinned: Link to the same domain should not open a new tab
+    // Tests link to http://test1.example.com/browser/browser/base/content/test/dummy_page.html
+    testLink(1, true, false, function() {
+      // Pinned: Link to a different domain should open a new tab
+      // Tests link to http://example.org/browser/browser/base/content/test/dummy_page.html
+      testLink(2, true, true, function() {
+        // Not Pinned: Link to a different domain should not open a new tab
+        // Tests link to http://example.org/browser/browser/base/content/test/dummy_page.html
+        testLink(2, false, false, function() {
+          // Pinned: Targetted link should open a new tab
+          // Tests link to http://example.org/browser/browser/base/content/test/dummy_page.html with target="foo"
+          testLink(3, true, true, function() {
+            // Pinned: Link in a subframe should not open a new tab
+            // Tests link to http://example.org/browser/browser/base/content/test/dummy_page.html in subframe
+            testLink(0, true, false, finish, true);
+          });
+        });
+      });
+    });
+  });
+}
+
+function testLink(aLinkIndex, pinTab, expectNewTab, nextTest, testSubFrame) {
+  let appTab = gBrowser.addTab("http://example.com/browser/browser/base/content/test/app_bug575561.html", {skipAnimation: true});
+  if (pinTab)
+    gBrowser.pinTab(appTab);
+  gBrowser.selectedTab = appTab;
+  appTab.linkedBrowser.addEventListener("load", onLoad, true);
+
+  let loadCount = 0;
+  function onLoad() {
+    loadCount++;
+    if (loadCount < 2)
+      return;
+
+    appTab.linkedBrowser.removeEventListener("load", onLoad, true);
+
+    let browser = gBrowser.getBrowserForTab(appTab);
+    if (testSubFrame)
+      browser = browser.contentDocument.getElementsByTagName("iframe")[0];
+
+    let links = browser.contentDocument.getElementsByTagName("a");
+
+    if (expectNewTab)
+      gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen, true);
+    else
+      browser.addEventListener("load", onPageLoad, true);
+
+    info("Clicking " + links[aLinkIndex].textContent);
+    EventUtils.sendMouseEvent({type:"click"}, links[aLinkIndex], browser.contentWindow);
+
+    function onPageLoad() {
+      browser.removeEventListener("load", onPageLoad, true);
+      is(browser.contentDocument.location.href, links[aLinkIndex].href, "Link should not open in a new tab");
+      executeSoon(function(){
+        gBrowser.removeTab(appTab);
+        nextTest();
+      });
+    }
+
+    function onTabOpen(event) {
+      gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen, true);
+      ok(true, "Link should open a new tab");
+      executeSoon(function(){
+        gBrowser.removeTab(appTab);
+        gBrowser.removeCurrentTab();
+        nextTest();
+      });
+    }
+  }
+}
--- 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
@@ -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/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/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/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 ::::: */
 
@@ -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/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"
 
@@ -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/CSPUtils.jsm
+++ b/content/base/src/CSPUtils.jsm
@@ -375,18 +375,17 @@ CSPRep.prototype = {
         return false;
       }
     }
     return (this.allowsInlineScripts === that.allowsInlineScripts)
         && (this.allowsEvalInScripts === that.allowsEvalInScripts);
   },
 
   /**
-   * Generates string representation of the policy.  Should be fairly similar
-   * to the original.
+   * Generates canonical string representation of the policy.
    */
   toString:
   function csp_toString() {
     var dirs = [];
 
     if (this._allowEval || this._allowInlineScripts) {
       dirs.push("options " + (this._allowEval ? "eval-script" : "")
                            + (this._allowInlineScripts ? "inline-script" : ""));
@@ -602,18 +601,17 @@ CSPSourceList.prototype = {
       if (!a_sorted[i].equals(b_sorted[i])) {
         return false;
       }
     }
     return true;
   },
 
   /**
-   * Generates string representation of the Source List.
-   * Should be fairly similar to the original.
+   * Generates canonical string representation of the Source List.
    */
   toString:
   function() {
     if (this.isNone()) {
       return "'none'";
     }
     if (this._permitAllSources) {
       return "*";
@@ -634,17 +632,17 @@ CSPSourceList.prototype = {
    * Returns whether or not this source list permits all sources (*).
    */
   isAll:
   function() {
     return this._permitAllSources;
   },
 
   /**
-   * Makes a new instance that resembles this object.
+   * Makes a new deep copy of this object.
    * @returns
    *      a new CSPSourceList
    */
   clone:
   function() {
     var aSL = new CSPSourceList();
     aSL._permitAllSources = this._permitAllSources;
     for (var i in this._sources) {
@@ -946,17 +944,17 @@ CSPSource.fromString = function(aStr, se
     // is the first bit a scheme?
     else if (CSPSource.validSchemeName(chunks[0])) {
       sObj._scheme = chunks[0];
       // then the second bit *must* be a host or empty
       if (chunks[1] === "") {
         // Allow scheme-only sources!  These default to wildcard host/port,
         // especially since host and port don't always matter.
         // Example: "javascript:" and "data:" 
-        if (!sObj._host) sObj._host = "*";
+        if (!sObj._host) sObj._host = CSPHost.fromString("*");
         if (!sObj._port) sObj._port = "*";
       } else {
         // some host was defined.
         // ... remove <= 3 leading slashes (from the scheme) and parse
         var cleanHost = chunks[1].replace(/^\/{0,3}/,"");
         // ... and parse
         sObj._host = CSPHost.fromString(cleanHost);
         if (!sObj._host) {
@@ -1045,18 +1043,17 @@ CSPSource.prototype = {
     }
     // if there was no scheme (and thus no default scheme), return self.port
     if (this._self && this._self.port) return this._self.port;
 
     return undefined;
   },
 
   /**
-   * Generates string representation of the Source.
-   * Should be fairly similar to the original.
+   * Generates canonical string representation of the Source.
    */
   toString:
   function() {
     if (this._isSelf) 
       return this._self.toString();
 
     var s = "";
     if (this._scheme)
@@ -1064,17 +1061,17 @@ CSPSource.prototype = {
     if (this._host)
       s = s + this._host;
     if (this._port)
       s = s + ":" + this._port;
     return s;
   },
 
   /**
-   * Makes a new instance that resembles this object.
+   * Makes a new deep copy of this object.
    * @returns
    *      a new CSPSource
    */
   clone:
   function() {
     var aClone = new CSPSource();
     aClone._self = this._self ? this._self.clone() : undefined;
     aClone._scheme = this._scheme;
@@ -1167,23 +1164,38 @@ CSPSource.prototype = {
     else if (that._scheme === this._scheme)
       newSource._scheme = this._scheme;
     else {
       CSPError("Could not intersect " + this + " with " + that
                + " due to scheme problems.");
       return null;
     }
 
+    // NOTE: Both sources must have a host, if they don't, something funny is
+    // going on.  The fromString() factory method should have set the host to
+    // * if there's no host specified in the input. Regardless, if a host is
+    // not present either the scheme is hostless or any host should be allowed.
+    // This means we can use the other source's host as the more restrictive
+    // host expression, or if neither are present, we can use "*", but the
+    // error should still be reported.
+
     // host
-    if (!this._host)
-      newSource._host = that._host;
-    else if (!that._host)
-      newSource._host = this._host;
-    else // both this and that have hosts
+    if (this._host && that._host) {
       newSource._host = this._host.intersectWith(that._host);
+    } else if (this._host) {
+      CSPError("intersecting source with undefined host: " + that.toString());
+      newSource._host = this._host.clone();
+    } else if (that._host) {
+      CSPError("intersecting source with undefined host: " + this.toString());
+      newSource._host = that._host.clone();
+    } else {
+      CSPError("intersecting two sources with undefined hosts: " +
+               this.toString() + " and " + that.toString());
+      newSource._host = CSPHost.fromString("*");
+    }
 
     return newSource;
   },
 
   /**
    * Compares one CSPSource to another.
    *
    * @param that
@@ -1261,26 +1273,25 @@ CSPHost.fromString = function(aStr) {
       return null;
     }
   }
   return hObj;
 };
 
 CSPHost.prototype = {
   /**
-   * Generates string representation of the Source.
-   * Should be fairly similar to the original.
+   * Generates canonical string representation of the Host.
    */
   toString:
   function() {
     return this._segments.join(".");
   },
 
   /**
-   * Makes a new instance that resembles this object.
+   * Makes a new deep copy of this object.
    * @returns
    *      a new CSPHost
    */
   clone:
   function() {
     var aHost = new CSPHost();
     for (var i in this._segments) {
       aHost._segments[i] = this._segments[i];
@@ -1292,17 +1303,17 @@ CSPHost.prototype = {
    * Returns true if this host accepts the provided host (or the other way
    * around).
    * @param aHost
    *        the FQDN in question (CSPHost or String)
    * @returns
    */
   permits:
   function(aHost) {
-    if (!aHost) return false;
+    if (!aHost) aHost = CSPHost.fromString("*");
 
     if (!(aHost instanceof CSPHost)) {
       // -- compare CSPHost to String
       return this.permits(CSPHost.fromString(aHost));
     }
     var thislen = this._segments.length;
     var thatlen = aHost._segments.length;
 
--- 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/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -5320,17 +5320,17 @@ nsGenericElement::PostHandleEventForLink
           if (fm) {
             nsCOMPtr<nsIDOMElement> elem = do_QueryInterface(this);
             fm->SetFocus(elem, nsIFocusManager::FLAG_BYMOUSE |
                                nsIFocusManager::FLAG_NOSCROLL);
           }
 
           nsIEventStateManager* esm =
             aVisitor.mPresContext->EventStateManager();
-          nsEventStateManager::SetGlobalActiveContent(
+          nsEventStateManager::SetActiveManager(
             static_cast<nsEventStateManager*>(esm), this);
         }
       }
     }
     break;
 
   case NS_MOUSE_CLICK:
     if (NS_IS_MOUSE_LEFT_CLICK(aVisitor.mEvent)) {
--- 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/base/test/unit/test_csputils.js
+++ b/content/base/test/unit/test_csputils.js
@@ -30,16 +30,17 @@
  * 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 ***** */
 
 //load('CSPUtils.jsm');
 Components.utils.import('resource://gre/modules/CSPUtils.jsm');
+Components.utils.import('resource://gre/modules/NetUtil.jsm');
 
 // load the HTTP server
 do_load_httpd_js();
 
 var httpServer = new nsHttpServer();
 
 const POLICY_FROM_URI = "allow 'self'; img-src *";
 const POLICY_PORT = 9000;
@@ -185,16 +186,17 @@ test(
       do_check_neq(null, CSPSource.fromString("*.a.com"));
 
       //print(" --- Ignore the following two errors if they print ---");
       //"wildcard should not work in non-first token for host.");
       do_check_eq(null, CSPSource.fromString("x.*.a.com"));
 
       //"funny characters (#) should not work for host.");
       do_check_eq(null, CSPSource.fromString("a#2-c.com"));
+
       //print(" --- Stop ignoring errors that print ---\n");
 
       //"failed to parse host with port.");
       do_check_neq(null, CSPSource.create("a.com:23"));
       //"failed to parse host with scheme.");
       do_check_neq(null, CSPSource.create("https://a.com"));
       //"failed to parse host with scheme and port.");
       do_check_neq(null, CSPSource.create("https://a.com:200"));
@@ -224,16 +226,26 @@ test(
       //"src should inherit port *
       do_check_true(src.permits("https://foobar.com:443"));
       //"src should inherit and require https scheme
       do_check_false(src.permits("http://foobar.com"));
       //"src should inherit scheme 'https'"
       do_check_true(src.permits("https://foobar.com"));
       //"src should reject other hosts"
       do_check_false(src.permits("https://a.com"));
+
+      src = CSPSource.create("javascript:", "https://foobar.com:443");
+      //"hostless schemes should be parseable."
+      var aUri = NetUtil.newURI("javascript:alert('foo');");
+      do_check_true(src.permits(aUri));
+      //"src should reject other hosts"
+      do_check_false(src.permits("https://a.com"));
+      //"nothing else should be allowed"
+      do_check_false(src.permits("https://foobar.com"));
+
     });
 
 ///////////////////// Test the source list //////////////////////
 
 test(
     function test_CSPSourceList_fromString() {
       var sd = CSPSourceList.fromString("'none'");
       //"'none' -- should parse"
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -1634,17 +1634,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
         {
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -2069,16 +2069,17 @@ nsEventStateManager::GenerateDragGesture
       // draggesture events, make it read only so that the data doesn't
       // change during the drag.
       dataTransfer->SetReadOnly();
 
       if (status != nsEventStatus_eConsumeNoDefault) {
         PRBool dragStarted = DoDefaultDragStart(aPresContext, event, dataTransfer,
                                                 targetContent, isSelection);
         if (dragStarted) {
+          sActiveESM = nsnull;
           aEvent->flags |= NS_EVENT_FLAG_STOP_DISPATCH;
         }
       }
 
       // Note that frame event handling doesn't care about NS_DRAGDROP_GESTURE,
       // which is just as well since we don't really know which frame to
       // send it to
 
@@ -2930,29 +2931,29 @@ nsEventStateManager::PostHandleEvent(nsP
           // to obtain our parent element and put it into :active
           // instead.
           nsCOMPtr<nsIDOMElement> elt(do_QueryInterface(activeContent));
           if (!elt) {
             nsIContent* par = activeContent->GetParent();
             if (par)
               activeContent = par;
           }
-          SetGlobalActiveContent(this, activeContent);
         }
       }
       else {
         // if we're here, the event handler returned false, so stop
         // any of our own processing of a drag. Workaround for bug 43258.
         StopTrackingDragGesture();
       }
+      SetActiveManager(this, activeContent);
     }
     break;
   case NS_MOUSE_BUTTON_UP:
     {
-      ClearGlobalActiveContent();
+      ClearGlobalActiveContent(this);
       if (IsMouseEventReal(aEvent)) {
         if (!mCurrentTarget) {
           nsIFrame* targ;
           GetEventTarget(&targ);
         }
         if (mCurrentTarget) {
           ret = CheckForAndDispatchClick(presContext, (nsMouseEvent*)aEvent,
                                          aStatus);
@@ -3201,16 +3202,17 @@ nsEventStateManager::PostHandleEvent(nsP
 
         nsEventStatus status = nsEventStatus_eIgnore;
         nsCOMPtr<nsIPresShell> presShell = mPresContext->GetPresShell();
         if (presShell) {
           presShell->HandleEventWithTarget(&event, mCurrentTarget,
                                            targetContent, &status);
         }
       }
+      ClearGlobalActiveContent(this);
       break;
     }
   case NS_DRAGDROP_EXIT:
      // make sure to fire the enter and exit_synth events after the
      // NS_DRAGDROP_EXIT event, otherwise we'll clean up too early
     GenerateDragDropEnterExit(presContext, (nsGUIEvent*)aEvent);
     break;
 
@@ -4701,28 +4703,31 @@ nsEventStateManager::DoContentCommandScr
   }
 
   // The caller may want synchronous scrolling.
   sf->ScrollBy(pt, scrollUnit, nsIScrollableFrame::INSTANT);
   return NS_OK;
 }
 
 void
-nsEventStateManager::SetGlobalActiveContent(nsEventStateManager* aNewESM,
-                                            nsIContent* aContent)
+nsEventStateManager::SetActiveManager(nsEventStateManager* aNewESM,
+                                      nsIContent* aContent)
 {
   if (sActiveESM && aNewESM != sActiveESM) {
     sActiveESM->SetContentState(nsnull, NS_EVENT_STATE_ACTIVE);
   }
   sActiveESM = aNewESM;
-  if (sActiveESM) {
+  if (sActiveESM && aContent) {
     sActiveESM->SetContentState(aContent, NS_EVENT_STATE_ACTIVE);
   }
 }
 
 void
-nsEventStateManager::ClearGlobalActiveContent()
+nsEventStateManager::ClearGlobalActiveContent(nsEventStateManager* aClearer)
 {
-  if (sActiveESM) {
+  if (aClearer) {
+    aClearer->SetContentState(nsnull, NS_EVENT_STATE_ACTIVE);
+  }
+  if (sActiveESM && aClearer != sActiveESM) {
     sActiveESM->SetContentState(nsnull, NS_EVENT_STATE_ACTIVE);
   }
   sActiveESM = nsnull;
 }
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -154,18 +154,20 @@ public:
 
   NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsEventStateManager,
                                            nsIEventStateManager)
 
   static nsIDocument* sMouseOverDocument;
 
   static nsIEventStateManager* GetActiveEventStateManager() { return sActiveESM; }
 
-  static void SetGlobalActiveContent(nsEventStateManager* aNewESM,
-                                     nsIContent* aContent);
+  // Sets aNewESM to be the active event state manager, and
+  // if aContent is non-null, marks the object as active.
+  static void SetActiveManager(nsEventStateManager* aNewESM,
+                               nsIContent* aContent);
 protected:
   void UpdateCursor(nsPresContext* aPresContext, nsEvent* aEvent, nsIFrame* aTargetFrame, nsEventStatus* aStatus);
   /**
    * Turn a GUI mouse event into a mouse event targeted at the specified
    * content.  This returns the primary frame for the content (or null
    * if it goes away during the event).
    */
   nsIFrame* DispatchMouseEvent(nsGUIEvent* aEvent, PRUint32 aMessage,
@@ -410,17 +412,17 @@ protected:
   PRPackedBool mLastLineScrollConsumedY;
 
   static PRInt32 sUserInputEventDepth;
   
   static PRBool sNormalLMouseEventInProcess;
 
   static nsEventStateManager* sActiveESM;
   
-  static void ClearGlobalActiveContent();
+  static void ClearGlobalActiveContent(nsEventStateManager* aClearer);
 
   // Functions used for click hold context menus
   PRBool mClickHoldContextMenu;
   nsCOMPtr<nsITimer> mClickHoldTimer;
   void CreateClickHoldTimer ( nsPresContext* aPresContext, nsIFrame* inDownFrame,
                               nsGUIEvent* inMouseDownEvent ) ;
   void KillClickHoldTimer ( ) ;
   void FireContextClick ( ) ;
--- 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
@@ -803,17 +803,18 @@ nsGenericHTMLElement::ScrollIntoView(PRB
   if (!optional_argc) {
     aTop = PR_TRUE;
   }
 
   PRIntn vpercent = aTop ? NS_PRESSHELL_SCROLL_TOP :
     NS_PRESSHELL_SCROLL_BOTTOM;
 
   presShell->ScrollContentIntoView(this, vpercent,
-                                   NS_PRESSHELL_SCROLL_ANYWHERE);
+                                   NS_PRESSHELL_SCROLL_ANYWHERE,
+                                   nsIPresShell::SCROLL_OVERFLOW_HIDDEN);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGenericHTMLElement::GetSpellcheck(PRBool* aSpellcheck)
 {
   NS_ENSURE_ARG_POINTER(aSpellcheck);
@@ -2316,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)
 
@@ -2933,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) \
@@ -1182,16 +1176,37 @@ NS_NewHTML##_elementName##Element(alread
   }                                                                          \
   NS_IMETHODIMP                                                              \
   _class::Set##_method(const nsAString& aValue)                              \
   {                                                                          \
     return SetAttrHelper(nsGkAtoms::_atom, aValue);                        \
   }
 
 /**
+ * A macro to implement getter and setter for action and form action content
+ * attributes. It's very similar to NS_IMPL_URI_ATTR excepted that if the
+ * content attribute is the empty string, the empty string is returned.
+ */
+#define NS_IMPL_ACTION_ATTR(_class, _method, _atom)                 \
+  NS_IMETHODIMP                                                     \
+  _class::Get##_method(nsAString& aValue)                           \
+  {                                                                 \
+    GetAttr(kNameSpaceID_None, nsGkAtoms::_atom, aValue);           \
+    if (aValue.IsEmpty()) {                                         \
+      return NS_OK;                                                 \
+    }                                                               \
+    return GetURIAttr(nsGkAtoms::_atom, nsnull, aValue);            \
+  }                                                                 \
+  NS_IMETHODIMP                                                     \
+  _class::Set##_method(const nsAString& aValue)                     \
+  {                                                                 \
+    return SetAttrHelper(nsGkAtoms::_atom, aValue);                 \
+  }
+
+/**
  * A macro to implement the getter and setter for a given content
  * property that needs to set a non-negative integer. The method
  * uses the generic GetAttr and SetAttr methods. This macro is much
  * like the NS_IMPL_INT_ATTR macro except we throw an exception if
  * the set value is negative.
  */
 #define NS_IMPL_NON_NEGATIVE_INT_ATTR(_class, _method, _atom)             \
   NS_IMPL_NON_NEGATIVE_INT_ATTR_DEFAULT_VALUE(_class, _method, _atom, -1)
@@ -1404,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/nsHTMLButtonElement.cpp
+++ b/content/html/content/src/nsHTMLButtonElement.cpp
@@ -213,17 +213,17 @@ NS_IMETHODIMP
 nsHTMLButtonElement::GetForm(nsIDOMHTMLFormElement** aForm)
 {
   return nsGenericHTMLFormElement::GetForm(aForm);
 }
 
 NS_IMPL_STRING_ATTR(nsHTMLButtonElement, AccessKey, accesskey)
 NS_IMPL_BOOL_ATTR(nsHTMLButtonElement, Autofocus, autofocus)
 NS_IMPL_BOOL_ATTR(nsHTMLButtonElement, Disabled, disabled)
-NS_IMPL_STRING_ATTR(nsHTMLButtonElement, FormAction, formaction)
+NS_IMPL_ACTION_ATTR(nsHTMLButtonElement, FormAction, formaction)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLButtonElement, FormEnctype, formenctype,
                                 kFormDefaultEnctype->tag)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLButtonElement, FormMethod, formmethod,
                                 kFormDefaultMethod->tag)
 NS_IMPL_BOOL_ATTR(nsHTMLButtonElement, FormNoValidate, formnovalidate)
 NS_IMPL_STRING_ATTR(nsHTMLButtonElement, FormTarget, formtarget)
 NS_IMPL_STRING_ATTR(nsHTMLButtonElement, Name, name)
 NS_IMPL_INT_ATTR(nsHTMLButtonElement, TabIndex, tabindex)
@@ -434,17 +434,17 @@ nsHTMLButtonElement::PostHandleEvent(nsE
       case NS_MOUSE_BUTTON_DOWN:
         {
           if (aVisitor.mEvent->eventStructType == NS_MOUSE_EVENT) {
             if (static_cast<nsMouseEvent*>(aVisitor.mEvent)->button ==
                   nsMouseEvent::eLeftButton) {
               if (NS_IS_TRUSTED_EVENT(aVisitor.mEvent)) {
                 nsIEventStateManager* esm =
                   aVisitor.mPresContext->EventStateManager();
-                nsEventStateManager::SetGlobalActiveContent(
+                nsEventStateManager::SetActiveManager(
                   static_cast<nsEventStateManager*>(esm), this);
               }
               nsIFocusManager* fm = nsFocusManager::GetFocusManager();
               if (fm)
                 fm->SetFocus(this, nsIFocusManager::FLAG_BYMOUSE |
                                    nsIFocusManager::FLAG_NOSCROLL);
               aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
             } else if (static_cast<nsMouseEvent*>(aVisitor.mEvent)->button ==
--- 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
@@ -78,16 +78,20 @@
 #include "nsEventDispatcher.h"
 
 #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 },
@@ -227,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;
   }
 
@@ -370,39 +371,28 @@ nsHTMLFormElement::SetAttr(PRInt32 aName
     ForgetCurrentSubmission();
     mNotifiedObservers = notifiedObservers;
   }
   return nsGenericHTMLElement::SetAttr(aNameSpaceID, aName, aPrefix, aValue,
                                        aNotify);
 }
 
 NS_IMPL_STRING_ATTR(nsHTMLFormElement, AcceptCharset, acceptcharset)
-NS_IMPL_STRING_ATTR(nsHTMLFormElement, Action, action)
+NS_IMPL_ACTION_ATTR(nsHTMLFormElement, Action, action)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLFormElement, Autocomplete, autocomplete,
                                 kFormDefaultAutocomplete->tag)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLFormElement, Enctype, enctype,
                                 kFormDefaultEnctype->tag)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLFormElement, Method, method,
                                 kFormDefaultMethod->tag)
 NS_IMPL_BOOL_ATTR(nsHTMLFormElement, NoValidate, novalidate)
 NS_IMPL_STRING_ATTR(nsHTMLFormElement, Name, name)
 NS_IMPL_STRING_ATTR(nsHTMLFormElement, Target, target)
 
 NS_IMETHODIMP
-nsHTMLFormElement::GetMozActionUri(nsAString& aValue)
-{
-  GetAttr(kNameSpaceID_None, nsGkAtoms::action, aValue);
-  if (aValue.IsEmpty()) {
-    // Avoid resolving action="" to the base uri, bug 297761.
-    return NS_OK;
-  }
-  return GetURIAttr(nsGkAtoms::action, nsnull, aValue);
-}
-
-NS_IMETHODIMP
 nsHTMLFormElement::Submit()
 {
   // Send the submit event
   nsresult rv = NS_OK;
   nsRefPtr<nsPresContext> presContext = GetPresContext();
   if (mPendingSubmission) {
     // aha, we have a pending submission that was not flushed
     // (this happens when form.submit() is called twice)
@@ -1426,27 +1416,39 @@ nsHTMLFormElement::GetActionURL(nsIURI**
   //
   // Grab the URL string
   //
   // If the originating element is a submit control and has the formaction
   // attribute specified, it should be used. Otherwise, the action attribute
   // from the form element should be used.
   //
   nsAutoString action;
-  nsCOMPtr<nsIFormControl> formControl = do_QueryInterface(aOriginatingElement);
-  if (formControl && formControl->IsSubmitControl() &&
-      aOriginatingElement->GetAttr(kNameSpaceID_None, nsGkAtoms::formaction,
-                                   action)) {
-    // Avoid resolving action="" to the base uri, bug 297761.
-    if (!action.IsEmpty()) {
-      static_cast<nsGenericHTMLElement*>(aOriginatingElement)->
-        GetURIAttr(nsGkAtoms::formaction, nsnull, action);
+
+  if (aOriginatingElement &&
+      aOriginatingElement->HasAttr(kNameSpaceID_None, nsGkAtoms::formaction)) {
+#ifdef DEBUG
+    nsCOMPtr<nsIFormControl> formControl = do_QueryInterface(aOriginatingElement);
+    NS_ASSERTION(formControl && formControl->IsSubmitControl(),
+                 "The originating element must be a submit form control!");
+#endif // DEBUG
+
+    nsCOMPtr<nsIDOMHTMLInputElement> inputElement = do_QueryInterface(aOriginatingElement);
+    if (inputElement) {
+      inputElement->GetFormAction(action);
+    } else {
+      nsCOMPtr<nsIDOMHTMLButtonElement> buttonElement = do_QueryInterface(aOriginatingElement);
+      if (buttonElement) {
+        buttonElement->GetFormAction(action);
+      } else {
+        NS_ERROR("Originating element must be an input or button element!");
+        return NS_ERROR_UNEXPECTED;
+      }
     }
   } else {
-    GetMozActionUri(action);
+    GetAction(action);
   }
 
   //
   // Form the full action URL
   //
 
   // Get the document to form the URL.
   // We'll also need it later to get the DOM window when notifying form submit
--- 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:
@@ -957,17 +956,17 @@ NS_IMPL_STRING_ATTR(nsHTMLInputElement, 
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, AccessKey, accesskey)
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, Align, align)
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, Alt, alt)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLInputElement, Autocomplete, autocomplete,
                                 kInputDefaultAutocomplete->tag)
 NS_IMPL_BOOL_ATTR(nsHTMLInputElement, Autofocus, autofocus)
 //NS_IMPL_BOOL_ATTR(nsHTMLInputElement, Checked, checked)
 NS_IMPL_BOOL_ATTR(nsHTMLInputElement, Disabled, disabled)
-NS_IMPL_STRING_ATTR(nsHTMLInputElement, FormAction, formaction)
+NS_IMPL_ACTION_ATTR(nsHTMLInputElement, FormAction, formaction)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLInputElement, FormEnctype, formenctype,
                                 kFormDefaultEnctype->tag)
 NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLInputElement, FormMethod, formmethod,
                                 kFormDefaultMethod->tag)
 NS_IMPL_BOOL_ATTR(nsHTMLInputElement, FormNoValidate, formnovalidate)
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, FormTarget, formtarget)
 NS_IMPL_BOOL_ATTR(nsHTMLInputElement, Multiple, multiple)
 NS_IMPL_NON_NEGATIVE_INT_ATTR(nsHTMLInputElement, MaxLength, maxlength)
--- 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/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -231,12 +231,15 @@ include $(topsrcdir)/config/rules.mk
 		test_bug557087-5.html \
 		test_bug557087-6.html \
 		test_bug586763.html \
 		test_bug598643.html \
 		test_bug596350.html \
 		test_bug600155.html \
 		test_bug556007.html \
 		test_bug606817.html \
+		test_bug297761.html \
+		file_bug297761.html \
+		test_bug607145.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/file_bug297761.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <base href="http://www.mozilla.org/">
+  </head>
+  <body>
+    <form action="">
+      <input type='submit' formaction="">
+      <button type='submit' formaction=""></button>
+      <input id='i' type='image' formaction="">
+    </form>
+  </body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug297761.html
@@ -0,0 +1,78 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=297761
+-->
+<head>
+  <title>Test for Bug 297761</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/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=297761">Mozilla Bug 297761</a>
+<p id="display"></p>
+<div id="content">
+  <iframe src="file_bug297761.html"></iframe>
+  <iframe src="file_bug297761.html"></iframe>
+  <iframe src="file_bug297761.html"></iframe>
+  <iframe src="file_bug297761.html"></iframe>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 297761 **/
+
+SimpleTest.waitForExplicitFinish();
+
+var nbTests = 4;
+var curTest = 0;
+
+function nextTest()
+{
+  if (curTest == 3) {
+    frames[curTest].document.forms[0].submit();
+  } else {
+    var el = null;
+    if (curTest == 2) {
+      el = frames[curTest].document.getElementById('i');
+    } else {
+      el = frames[curTest].document.forms[0].elements[curTest];
+    }
+
+    el.focus();
+    el.click();
+  }
+}
+
+function frameLoaded(aFrame)
+{
+  var documentLocation = location.href.replace(/\.html.*/, "\.html");
+  is(aFrame.contentWindow.location.href.replace(/\?x=0&y=0/, ""),
+     documentLocation.replace(/test_bug/, "file_bug"),
+     "form should have been submitted to the document location");
+
+  if (++curTest == nbTests) {
+    SimpleTest.finish();
+  } else {
+    nextTest();
+  }
+}
+
+function runTest()
+{
+  // Initialize event handlers.
+  var frames = document.getElementsByTagName('iframe');
+  for (var i=0; i<nbTests; ++i) {
+    frames[i].setAttribute('onload', "frameLoaded(this);");
+  }
+
+  nextTest();
+}
+
+addLoadEvent(runTest);
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/content/test/test_bug392567.html
+++ b/content/html/content/test/test_bug392567.html
@@ -17,64 +17,71 @@ https://bugzilla.mozilla.org/show_bug.cg
     <input type="text" name="key" />
   </form>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 392567 **/
 
-var dataUrl = "http://mochi.test:8888/tests/content/html/content/test/bug392567.jar";
-var jarUrl = "jar:" + dataUrl + "!/index.html";
-var httpUrl = location.href.replace(/\.html.*/, "_404");
-var previousDir = location.href.replace(/test\/[^\/]*$/, "");
-
-var form = document.forms.testForm;
-var frame = frames.testFrame;
-document.getElementById("testFrame").onload = processTestResult;
+SimpleTest.waitForExplicitFinish();
 
-// List of tests to run, each test consists of form action URL and expected result URL
-var tests = [
-  [jarUrl, jarUrl + "?$PARAMS", null],
-  [jarUrl + "?jarTest1=jarTest2", jarUrl + "?$PARAMS", null],
-  [jarUrl + "?jarTest3=jarTest4#jarTest5", jarUrl + "?$PARAMS#jarTest5", null],
-  ["data:text/html,<html></html>", "data:text/html,<html></html>?$PARAMS", null],
-  ["data:text/html,<html>How%20about%20this?</html>", "data:text/html,<html>How%20about%20this?$PARAMS", null],
-  [httpUrl, httpUrl + "?$PARAMS", null],
-  [httpUrl + "?httpTest1=httpTest2", httpUrl + "?$PARAMS", null ],
-  [httpUrl + "?httpTest3=httpTest4#httpTest5", httpUrl + "?$PARAMS#httpTest5", null],
-  ["", jarUrl + "?key=value0", null],
-  [" ", jarUrl + "?key=value0", document.location],
-  ["../", previousDir + "?$PARAMS", previousDir],
-];
-
-var currentTest = -1;
-
-SimpleTest.waitForExplicitFinish(); 
-runNextTest();
-
-function runNextTest() {
-  currentTest++;
-  if (currentTest >= tests.length) {
-    SimpleTest.finish();
+function runTests()
+{
+  if (window.location.search.match(/\?key=value/)) {
     return;
   }
 
-  form.setAttribute("action", tests[currentTest][0]);
-  is(form.action, tests[currentTest][0],
-     "action IDL attribute should reflect the action content attribute");
-  is(form.mozActionUri, tests[currentTest][2] ? tests[currentTest][2] : tests[currentTest][0],
-     "mozActionUri IDL attribute should resolve the action URI");
-  form.key.value = "value" + currentTest;
-  form.submit();
+  var dataUrl = "http://mochi.test:8888/tests/content/html/content/test/bug392567.jar";
+  var jarUrl = "jar:" + dataUrl + "!/index.html";
+  var httpUrl = location.href.replace(/\.html.*/, "_404");
+  var previousDir = location.href.replace(/test\/[^\/]*$/, "");
+  var documentURL = location.href.replace(/\.html.*/, "\.html");
+
+  var form = document.forms.testForm;
+  var frame = frames.testFrame;
+  document.getElementById("testFrame").onload = processTestResult;
+
+  // List of tests to run, each test consists of form action URL and expected result URL
+  var tests = [
+    [jarUrl, jarUrl + "?$PARAMS"],
+    [jarUrl + "?jarTest1=jarTest2", jarUrl + "?$PARAMS"],
+    [jarUrl + "?jarTest3=jarTest4#jarTest5", jarUrl + "?$PARAMS#jarTest5"],
+    ["data:text/html,<html></html>", "data:text/html,<html></html>?$PARAMS"],
+    ["data:text/html,<html>How%20about%20this?</html>", "data:text/html,<html>How%20about%20this?$PARAMS"],
+    [httpUrl, httpUrl + "?$PARAMS"],
+    [httpUrl + "?httpTest1=httpTest2", httpUrl + "?$PARAMS"],
+    [httpUrl + "?httpTest3=httpTest4#httpTest5", httpUrl + "?$PARAMS#httpTest5"],
+    ["", documentURL + "?$PARAMS"],
+    [" ", documentURL + "?$PARAMS"],
+    ["../", previousDir + "?$PARAMS"],
+  ];
+
+  var currentTest = -1;
+
+  runNextTest();
+
+  function runNextTest() {
+    currentTest++;
+    if (currentTest >= tests.length) {
+      SimpleTest.finish();
+      return;
+    }
+
+    form.setAttribute("action", tests[currentTest][0]);
+    form.key.value = "value" + currentTest;
+    form.submit();
+  }
+
+  function processTestResult() {
+    var expected = tests[currentTest][1].replace(/\$PARAMS/, "key=value" + currentTest);
+    is(frame.location.href, expected, "Submitting to " + tests[currentTest][0]);
+
+    setTimeout(runNextTest, 0);
+  }
 }
 
-function processTestResult() {
-  var expected = tests[currentTest][1].replace(/\$PARAMS/, "key=value" + currentTest);
-  is(frame.location.href, expected, "Submitting to " + tests[currentTest][0]);
-
-  setTimeout(runNextTest, 0);
-}
+addLoadEvent(runTests);
 
 </script>
 </pre>
 </body>
 </html>
--- 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/content/test/test_bug566160.html
+++ b/content/html/content/test/test_bug566160.html
@@ -78,51 +78,18 @@ var gTestResults = {
   frame4: "data:text/html,?footulip=footulip",
   frame5: "data:text/html,?foobar=foobar&x=0&y=0",
   frame6: "data:text/html,?tulip2=tulip2",
   frame7: "data:text/html,?input=enter",
 };
 
 var gPendingLoad = 0; // Has to be set after depending on the frames number.
 
-function checkFormActionAttribute(aElement)
-{
-  ok("formAction" in aElement, "formAction IDL attribute should be available in "
-     + aElement);
-
-  is(aElement.formAction, "", "formAction IDL attribute should be " +
-     "undefined by default");
-  is(aElement.getAttribute('formaction'), null, "formaction content attribute " +
-     "should be the empty string by default");
-
-  aElement.formAction = "foo";
-  is(aElement.getAttribute('formaction'), "foo", "formaction content attribute " +
-     "should be 'foo'.");
-  is(aElement.formAction, "foo", "formAction IDL attribute should reflect " +
-     "the content attribute");
-
-  aElement.setAttribute('formaction', 'bar');
-  is(aElement.getAttribute('formaction'), "bar", "formaction content attribute " +
-     "should be 'foo'.");
-  is(aElement.formAction, "bar", "formAction IDL attribute should reflect " +
-     "the content attribute");
-
-  aElement.removeAttribute('formaction');
-  is(aElement.formAction, "", "formAction IDL attribute should be " +
-     "undefined by default");
-  is(aElement.getAttribute('formaction'), null, "formaction content attribute " +
-     "should be the empty string by default");
-}
-
 function runTests()
 {
-  // First of all, let's check if .formAction and @formaction work correctly.
-  checkFormActionAttribute(document.createElement('input'));
-  checkFormActionAttribute(document.createElement('button'));
-
   // We add a load event for the frames which will be called when the forms
   // will be submitted.
   var frames = [ document.getElementById('frame1'),
                  document.getElementById('frame2'),
                  document.getElementById('frame3'),
                  document.getElementById('frame3bis'),
                  document.getElementById('frame4'),
                  document.getElementById('frame5'),
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug607145.html
@@ -0,0 +1,78 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=607145
+-->
+<head>
+  <title>Test for Bug 607145</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/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=607145">Mozilla Bug 607145</a>
+<p id="display"></p>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 607145 **/
+
+/**
+ * This is not really reflecting an URL as the HTML5 specs want to.
+ * It's how .action is reflected in Gecko (might change later).
+ */
+function reflectURL(aElement, aAttr)
+{
+  var idl = aAttr;
+  var attr = aAttr.toLowerCase();
+  var elmtName = aElement.tagName.toLowerCase();
+
+  ok(idl in aElement, idl + " should be available in " + elmtName);
+
+  // Default values.
+  is(aElement[idl], "", "." + idl + " default value should be the empty string");
+  is(aElement.getAttribute(attr), null,
+     "@" + attr + " default value should be null");
+
+  var previousDir = location.href.replace(/test\/[^\/]*$/, "");
+  var dir = location.href.replace(/test_bug607145.html[^\/]*$/, "");
+  var doc = location.href.replace(/\.html.*/, ".html")
+  var values = [
+    /* value to set, resolved value */
+    [ "foo.html", dir + "foo.html" ],
+    [ "data:text/html,<html></html>", "data:text/html,<html></html>" ],
+    [ "http://example.org/", "http://example.org/" ],
+    [ "//example.org/", "http://example.org/" ],
+    [ "?foo=bar", doc + "?foo=bar" ],
+    [ "#foo", location.href + "#foo" ],
+    [ "", "" ], // TODO: doesn't follow the specs, should be location.href.
+    [ " ", location.href ],
+    [ "../", previousDir ],
+    [ "...", dir + "..." ],
+    // invalid URL
+    [ "http://a b/", "http://a b/" ], // TODO: doesn't follow the specs, should be "".
+  ];
+
+  for each (var value in values) {
+    aElement[idl] = value[0];
+    is(aElement[idl], value[1], "." + idl + " value should be " + value[1]);
+    is(aElement.getAttribute(attr), value[0],
+       "@" + attr + " value should be " + value[0]);
+  }
+
+  for each (var value in values) {
+    aElement.setAttribute(attr, value[0]);
+    is(aElement[idl], value[1], "." + idl + " value should be " + value[1]);
+    is(aElement.getAttribute(attr), value[0],
+       "@" + attr + " value should be " + value[0]);
+  }
+}
+
+reflectURL(document.createElement("form"), "action");
+reflectURL(document.createElement("input"), "formAction");
+reflectURL(document.createElement("button"), "formAction");
+
+</script>
+</pre>
+</body>
+</html>
--- 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/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/nsXULPrototypeCache.cpp
+++ b/content/xul/document/src/nsXULPrototypeCache.cpp
@@ -140,16 +140,17 @@ NS_NewXULPrototypeCache(nsISupports* aOu
     nsresult rv = result->QueryInterface(aIID, aResult);
 
     nsCOMPtr<nsIObserverService> obsSvc =
         mozilla::services::GetObserverService();
     if (obsSvc && NS_SUCCEEDED(rv)) {
         nsXULPrototypeCache *p = result;
         obsSvc->AddObserver(p, "chrome-flush-skin-caches", PR_FALSE);
         obsSvc->AddObserver(p, "chrome-flush-caches", PR_FALSE);
+        obsSvc->AddObserver(p, "startupcache-invalidate", PR_FALSE);
     }
 
     return rv;
 }
 
 /* static */ nsXULPrototypeCache*
 nsXULPrototypeCache::GetInstance()
 {
@@ -405,50 +406,59 @@ static PRBool gChecksumXULFastLoadFile =
 
 void
 nsXULPrototypeCache::AbortFastLoads()
 {
 #ifdef DEBUG_brendan
     NS_BREAK();
 #endif
 
-    // Save a strong ref to the FastLoad file, so we can remove it after we
-    // close open streams to it.
-    nsCOMPtr<nsIFile> file = gFastLoadFile;
-
     // Flush the XUL cache for good measure, in case we cached a bogus/downrev
     // script, somehow.
     Flush();
 
     // Clear the FastLoad set
     mFastLoadURITable.Clear();
 
-    if (! gFastLoadService)
-        return;
+    nsCOMPtr<nsIFastLoadService> fastLoadService = gFastLoadService;
+    nsCOMPtr<nsIFile> file = gFastLoadFile;
+
+    nsresult rv;
+
+    if (! fastLoadService) {
+        fastLoadService = do_GetFastLoadService();
+        if (! fastLoadService)
+            return;
+
+        rv = fastLoadService->NewFastLoadFile(XUL_FASTLOAD_FILE_BASENAME,
+                                              getter_AddRefs(file));
+        if (NS_FAILED(rv))
+            return;
+    }
 
     // Fetch the current input (if FastLoad file existed) or output (if we're
     // creating the FastLoad file during this app startup) stream.
     nsCOMPtr<nsIObjectInputStream> objectInput;
     nsCOMPtr<nsIObjectOutputStream> objectOutput;
-    gFastLoadService->GetInputStream(getter_AddRefs(objectInput));
-    gFastLoadService->GetOutputStream(getter_AddRefs(objectOutput));
+    fastLoadService->GetInputStream(getter_AddRefs(objectInput));
+    fastLoadService->GetOutputStream(getter_AddRefs(objectOutput));
 
     if (objectOutput) {
-        gFastLoadService->SetOutputStream(nsnull);
+        fastLoadService->SetOutputStream(nsnull);
 
         if (NS_SUCCEEDED(objectOutput->Close()) && gChecksumXULFastLoadFile)
-            gFastLoadService->CacheChecksum(gFastLoadFile,
-                                            objectOutput);
+            fastLoadService->CacheChecksum(file,
+                                           objectOutput);
     }
 
     if (objectInput) {
         // If this is the last of one or more XUL master documents loaded
         // together at app startup, close the FastLoad service's singleton
         // input stream now.
-        gFastLoadService->SetInputStream(nsnull);
+        fastLoadService->SetInputStream(nsnull);
         objectInput->Close();
     }
 
     // Now rename or remove the file.
     if (file) {
 #ifdef DEBUG
         // Remove any existing Aborted.mfasl files generated in previous runs.
         nsCOMPtr<nsIFile> existingAbortedFile;
@@ -457,23 +467,25 @@ nsXULPrototypeCache::AbortFastLoads()
             existingAbortedFile->SetLeafName(NS_LITERAL_STRING("Aborted.mfasl"));
             PRBool fileExists = PR_FALSE;
             existingAbortedFile->Exists(&fileExists);
             if (fileExists)
                 existingAbortedFile->Remove(PR_FALSE);
         }
         file->MoveToNative(nsnull, NS_LITERAL_CSTRING("Aborted.mfasl"));
 #else
-        file->Remove(PR_FALSE);
+        rv = file->Remove(PR_FALSE);
+        if (NS_FAILED(rv))
+            NS_WARNING("Failed to remove fastload file, fastload data may be outdated");
 #endif
     }
 
     // If the list is empty now, the FastLoad process is done.
-    NS_RELEASE(gFastLoadService);
-    NS_RELEASE(gFastLoadFile);
+    NS_IF_RELEASE(gFastLoadService);
+    NS_IF_RELEASE(gFastLoadFile);
 }
 
 
 void
 nsXULPrototypeCache::RemoveFromFastLoadSet(nsIURI* aURI)
 {
     mFastLoadURITable.Remove(aURI);
 }
--- 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(),
-                       PR_FALSE);
+                       NOT_FROM_PARSER);
     if (NS_FAILED(rv))
         return rv;
 
     *aResult = result;
     NS_ADDREF(*aResult);
     return NS_OK;
 }
 
--- a/docshell/base/nsDSURIContentListener.cpp
+++ b/docshell/base/nsDSURIContentListener.cpp
@@ -298,16 +298,20 @@ bool nsDSURIContentListener::CheckFrameO
         return true;
 
     if (mDocShell) {
         // We need to check the location of this window and the location of the top
         // window, if we're not the top.  X-F-O: SAMEORIGIN requires that the
         // document must be same-origin with top window.  X-F-O: DENY requires that
         // the document must never be framed.
         nsCOMPtr<nsIDOMWindow> thisWindow = do_GetInterface(static_cast<nsIDocShell*>(mDocShell));
+        // If we don't have DOMWindow there is no risk of clickjacking
+        if (!thisWindow)
+            return true;
+
         nsCOMPtr<nsIDOMWindow> topWindow;
         thisWindow->GetTop(getter_AddRefs(topWindow));
 
         // if the document is in the top window, it's not in a frame.
         if (thisWindow == topWindow)
             return true;
 
         // Find the top docshell in our parent chain that doesn't have the system
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -154,17 +154,17 @@
 #include "nsIApplicationCache.h"
 #include "nsIApplicationCacheChannel.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIPermissionManager.h"
 #include "nsStreamUtils.h"
 #include "nsIController.h"
 #include "nsPICommandUpdater.h"
 #include "nsIDOMHTMLAnchorElement.h"
-#include "nsIWebBrowserChrome2.h"
+#include "nsIWebBrowserChrome3.h"
 #include "nsITabChild.h"
 #include "nsIStrictTransportSecurityService.h"
 
 // Editor-related
 #include "nsIEditingSession.h"
 
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
@@ -706,16 +706,17 @@ nsDocShell::nsDocShell():
     mAllowDNSPrefetch(PR_TRUE),
     mCreatingDocument(PR_FALSE),
     mUseErrorPages(PR_FALSE),
     mObserveErrorPages(PR_TRUE),
     mAllowAuth(PR_TRUE),
     mAllowKeywordFixup(PR_FALSE),
     mIsOffScreenBrowser(PR_FALSE),
     mIsActive(PR_TRUE),
+    mIsAppTab(PR_FALSE),
     mFiredUnloadEvent(PR_FALSE),
     mEODForCurrentDocument(PR_FALSE),
     mURIResultedInDocument(PR_FALSE),
     mIsBeingDestroyed(PR_FALSE),
     mIsExecutingOnLoadHandler(PR_FALSE),
     mIsPrintingOrPP(PR_FALSE),
     mSavingOldViewer(PR_FALSE)
 #ifdef DEBUG
@@ -4798,16 +4799,30 @@ nsDocShell::SetIsActive(PRBool aIsActive
 NS_IMETHODIMP
 nsDocShell::GetIsActive(PRBool *aIsActive)
 {
   *aIsActive = mIsActive;
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsDocShell::SetIsAppTab(PRBool aIsAppTab)
+{
+  mIsAppTab = aIsAppTab;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDocShell::GetIsAppTab(PRBool *aIsAppTab)
+{
+  *aIsAppTab = mIsAppTab;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsDocShell::SetVisibility(PRBool aVisibility)
 {
     if (!mContentViewer)
         return NS_OK;
     if (aVisibility) {
         mContentViewer->Show();
     }
     else {
@@ -11306,18 +11321,32 @@ nsDocShell::OnLinkClick(nsIContent* aCon
   if (!IsOKToLoadURI(aURI)) {
     return NS_OK;
   }
 
   if (aContent->IsEditable()) {
     return NS_OK;
   }
 
+  nsresult rv = NS_ERROR_FAILURE;
+  nsAutoString target;
+
+  nsCOMPtr<nsIWebBrowserChrome3> browserChrome3 = do_GetInterface(mTreeOwner);
+  if (browserChrome3) {
+    nsCOMPtr<nsIDOMNode> linkNode = do_QueryInterface(aContent);
+    nsAutoString oldTarget(aTargetSpec);
+    rv = browserChrome3->OnBeforeLinkTraversal(oldTarget, aURI,
+                                               linkNode, mIsAppTab, target);
+  }
+  
+  if (NS_FAILED(rv))
+    target = aTargetSpec;  
+
   nsCOMPtr<nsIRunnable> ev =
-      new OnLinkClickEvent(this, aContent, aURI, aTargetSpec,
+      new OnLinkClickEvent(this, aContent, aURI, target.get(),
                            aPostDataStream, aHeadersDataStream);
   return NS_DispatchToCurrentThread(ev);
 }
 
 NS_IMETHODIMP
 nsDocShell::OnLinkClickSync(nsIContent *aContent,
                             nsIURI* aURI,
                             const PRUnichar* aTargetSpec,
--- a/docshell/base/nsDocShell.h
+++ b/docshell/base/nsDocShell.h
@@ -785,16 +785,17 @@ protected:
     PRPackedBool               mAllowDNSPrefetch;
     PRPackedBool               mCreatingDocument; // (should be) debugging only
     PRPackedBool               mUseErrorPages;
     PRPackedBool               mObserveErrorPages;
     PRPackedBool               mAllowAuth;
     PRPackedBool               mAllowKeywordFixup;
     PRPackedBool               mIsOffScreenBrowser;
     PRPackedBool               mIsActive;
+    PRPackedBool               mIsAppTab;
 
     // This boolean is set to true right before we fire pagehide and generally
     // unset when we embed a new content viewer.  While it's true no navigation
     // is allowed in this docshell.
     PRPackedBool               mFiredUnloadEvent;
 
     // this flag is for bug #21358. a docshell may load many urls
     // which don't result in new documents being created (i.e. a new
--- a/docshell/base/nsIDocShell.idl
+++ b/docshell/base/nsIDocShell.idl
@@ -66,17 +66,17 @@ interface nsIRequest;
 interface nsISHEntry;
 interface nsILayoutHistoryState;
 interface nsISecureBrowserUI;
 interface nsIDOMStorage;
 interface nsIPrincipal;
 interface nsIWebBrowserPrint;
 interface nsIVariant;
 
-[scriptable, uuid(74470127-87eb-4f79-8293-1616fe9cb689)]
+[scriptable, uuid(98cdbcc4-2d81-4191-a63f-b6c52085edbc)]
 interface nsIDocShell : nsISupports
 {
   /**
    * Loads a given URI.  This will give priority to loading the requested URI
    * in the object implementing	this interface.  If it can't be loaded here
    * however, the URL dispatcher will go through its normal process of content
    * loading.
    *
@@ -524,21 +524,27 @@ interface nsIDocShell : nsISupports
 
   /**
    * Sets whether a docshell is active. An active docshell is one that is
    * visible, and thus is not a good candidate for certain optimizations
    * like image frame discarding. Docshells are active unless told otherwise.
    */
   attribute boolean isActive;
 
-
   /**
    * The ID of the docshell in the session history.
    */
   readonly attribute unsigned long long historyID;
+
+  /**
+   * Sets whether a docshell is an app tab. An app tab docshell may behave
+   * differently than a non-app tab docshell in some cases, such as when
+   * handling link clicks. Docshells are not app tabs unless told otherwise.
+   */
+  attribute boolean isAppTab;
 };
 
 [uuid(5f7a2184-31b6-4d67-9c75-0c17477766e2)]
 interface nsIDocShell_MOZILLA_2_0_BRANCH : nsISupports {
   /**
    * Create a new about:blank document and content viewer.
    * @param aPrincipal the principal to use for the new document.
    */
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -69,16 +69,17 @@
 #include "nsTArray.h"
 #include "nsCSSValue.h"
 #include "nsIRunnable.h"
 #include "nsThreadUtils.h"
 #include "nsDOMEventTargetWrapperCache.h"
 
 // General helper includes
 #include "nsGlobalWindow.h"
+#include "nsHistory.h"
 #include "nsIContent.h"
 #include "nsIAttribute.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOM3Document.h"
 #include "nsIDOMXMLDocument.h"
 #include "nsIDOMNSDocument.h"
 #include "nsIDOMEvent.h"
@@ -656,17 +657,18 @@ static nsDOMClassInfoData sClassInfoData
                            ARRAY_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(MimeType, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(MimeTypeArray, nsMimeTypeArraySH,
                            ARRAY_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(BarProp, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(History, nsHistorySH,
-                           ARRAY_SCRIPTABLE_FLAGS)
+                           ARRAY_SCRIPTABLE_FLAGS |
+                           nsIXPCScriptable::WANT_PRECREATE)
   NS_DEFINE_CLASSINFO_DATA(Screen, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(DOMPrototype, nsDOMConstructorSH,
                            DOM_BASE_SCRIPTABLE_FLAGS |
                            nsIXPCScriptable::WANT_HASINSTANCE |
                            nsIXPCScriptable::DONT_ENUM_QUERY_INTERFACE)
   NS_DEFINE_CLASSINFO_DATA(DOMConstructor, nsDOMConstructorSH,
                            DOM_BASE_SCRIPTABLE_FLAGS |
@@ -4577,25 +4579,16 @@ NS_IMETHODIMP
 nsDOMClassInfo::OuterObject(nsIXPConnectWrappedNative *wrapper, JSContext * cx,
                             JSObject * obj, JSObject * *_retval)
 {
   NS_WARNING("nsDOMClassInfo::OuterObject Don't call me!");
 
   return NS_ERROR_UNEXPECTED;
 }
 
-NS_IMETHODIMP
-nsDOMClassInfo::InnerObject(nsIXPConnectWrappedNative *wrapper, JSContext * cx,
-                            JSObject * obj, JSObject * *_retval)
-{
-  NS_WARNING("nsDOMClassInfo::InnerObject Don't call me!");
-
-  return NS_ERROR_UNEXPECTED;
-}
-
 static nsresult
 GetExternalClassInfo(nsScriptNameSpaceManager *aNameSpaceManager,
                      const nsString &aName,
                      const nsGlobalNameStruct *aStruct,
                      const nsGlobalNameStruct **aResult)
 {
   NS_ASSERTION(aStruct->mType ==
                  nsGlobalNameStruct::eTypeExternalClassInfoCreator,
@@ -6182,26 +6175,26 @@ ResolvePrototype(nsIXPConnect *aXPConnec
         }
       }
     }
   }
 
   {
     JSObject *winobj = aWin->FastGetGlobalJSObject();
 
-    JSAutoEnterCompartment ac;
-    if (!ac.enter(cx, winobj)) {
-      return NS_ERROR_UNEXPECTED;
-    }
-
     JSObject *proto = nsnull;
 
     if (class_parent_name) {
       jsval val;
 
+      JSAutoEnterCompartment ac;
+      if (!ac.enter(cx, winobj)) {
+        return NS_ERROR_UNEXPECTED;
+      }
+
       if (!::JS_LookupProperty(cx, winobj, CutPrefix(class_parent_name), &val)) {
         return NS_ERROR_UNEXPECTED;
       }
 
       JSObject *tmp = JSVAL_IS_OBJECT(val) ? JSVAL_TO_OBJECT(val) : nsnull;
 
       if (tmp) {
         if (!::JS_LookupProperty(cx, tmp, "prototype", &val)) {
@@ -6215,17 +6208,18 @@ ResolvePrototype(nsIXPConnect *aXPConnec
     }
 
     if (dot_prototype) {
       JSObject *xpc_proto_proto = ::JS_GetPrototype(cx, dot_prototype);
 
       if (proto &&
           (!xpc_proto_proto ||
            JS_GET_CLASS(cx, xpc_proto_proto) == sObjectClass)) {
-        if (!::JS_SetPrototype(cx, dot_prototype, proto)) {
+        if (!JS_WrapObject(cx, &proto) ||
+            !JS_SetPrototype(cx, dot_prototype, proto)) {
           return NS_ERROR_UNEXPECTED;
         }
       }
     } else {
       dot_prototype = ::JS_NewObject(cx, &sDOMConstructorProtoClass, proto,
                                      winobj);
       NS_ENSURE_TRUE(dot_prototype, NS_ERROR_OUT_OF_MEMORY);
     }
@@ -7092,17 +7086,17 @@ nsLocationSH::PreCreate(nsISupports *nat
   if (!ds) {
     NS_WARNING("Refusing to create a location in the wrong scope");
     return NS_ERROR_UNEXPECTED;
   }
 
   nsCOMPtr<nsIScriptGlobalObject> sgo = do_GetInterface(ds);
   if (!sgo) {
     NS_WARNING("Refusing to create a location in the wrong scope because the "
-	       "docshell is being destroyed");
+               "docshell is being destroyed");
     return NS_ERROR_UNEXPECTED;
   }
 
   *parentObj = sgo->GetGlobalJSObject();
   return NS_OK;
 }
 
 // DOM Navigator helper
@@ -9910,39 +9904,48 @@ nsStringArraySH::GetProperty(nsIXPConnec
 
   return NS_SUCCESS_I_DID_SOMETHING;
 }
 
 
 // History helper
 
 NS_IMETHODIMP
+nsHistorySH::PreCreate(nsISupports *nativeObj, JSContext *cx,
+                       JSObject *globalObj, JSObject **parentObj)
+{
+  nsHistory *history = (nsHistory *)nativeObj;
+  nsIDocShell *ds = history->GetDocShell();
+  if (!ds) {
+    NS_WARNING("Refusing to create a history object in the wrong scope");
+    return NS_ERROR_UNEXPECTED;
+  }
+
+  nsCOMPtr<nsIScriptGlobalObject> sgo = do_GetInterface(ds);
+  if (!sgo) {
+    NS_WARNING("Refusing to create a history object in the wrong scope because the "
+               "docshell is being destroyed");
+    return NS_ERROR_UNEXPECTED;
+  }
+
+  *parentObj = sgo->GetGlobalJSObject();
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsHistorySH::GetProperty(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                          JSObject *obj, jsid id, jsval *vp, PRBool *_retval)
 {
   PRBool is_number = PR_FALSE;
   GetArrayIndexFromId(cx, id, &is_number);
 
   if (!is_number) {
     return NS_OK;
   }
 
-  nsresult rv =
-    sSecMan->CheckPropertyAccess(cx, obj, mData->mName, sItem_id,
-                                 nsIXPCSecurityManager::ACCESS_CALL_METHOD);
-
-  if (NS_FAILED(rv)) {
-    // Let XPConnect know that the access was not granted.
-    *_retval = PR_FALSE;
-
-    return NS_OK;
-  }
-
-  // sec check
-
   return nsStringArraySH::GetProperty(wrapper, cx, obj, id, vp, _retval);
 }
 
 nsresult
 nsHistorySH::GetStringAt(nsISupports *aNative, PRInt32 aIndex,
                          nsAString& aResult)
 {
   if (aIndex < 0) {
--- a/dom/base/nsDOMClassInfo.h
+++ b/dom/base/nsDOMClassInfo.h
@@ -1265,16 +1265,18 @@ protected:
   virtual ~nsHistorySH()
   {
   }
 
   virtual nsresult GetStringAt(nsISupports *aNative, PRInt32 aIndex,
                                nsAString& aResult);
 
 public:
+  NS_IMETHOD PreCreate(nsISupports *nativeObj, JSContext *cx,
+                       JSObject *globalObj, JSObject **parentObj);
   NS_IMETHOD GetProperty(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                          JSObject *obj, jsid id, jsval *vp, PRBool *_retval);
 
   static nsIClassInfo *doCreate(nsDOMClassInfoData* aData)
   {
     return new nsHistorySH(aData);
   }
 };
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -1795,17 +1795,18 @@ void
 nsFocusManager::ScrollIntoView(nsIPresShell* aPresShell,
                                nsIContent* aContent,
                                PRUint32 aFlags)
 {
   // if the noscroll flag isn't set, scroll the newly focused element into view
   if (!(aFlags & FLAG_NOSCROLL))
     aPresShell->ScrollContentIntoView(aContent,
                                       NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE,
-                                      NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE);
+                                      NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE,
+                                      nsIPresShell::SCROLL_OVERFLOW_HIDDEN);
 }
 
 
 void
 nsFocusManager::RaiseWindow(nsPIDOMWindow* aWindow)
 {
   // don't raise windows that are already raised or are in the process of
   // being lowered
--- a/dom/base/nsHistory.h
+++ b/dom/base/nsHistory.h
@@ -53,16 +53,17 @@ public:
   virtual ~nsHistory();
 
   // nsISupports
   NS_DECL_ISUPPORTS
 
   // nsIDOMHistory
   NS_DECL_NSIDOMHISTORY
 
+  nsIDocShell *GetDocShell() { return mDocShell; }
   void SetDocShell(nsIDocShell *aDocShell);
 
 protected:
   nsresult GetSessionHistoryFromDocShell(nsIDocShell * aDocShell,
                                          nsISHistory ** aReturn);
 
   nsIDocShell* mDocShell;
 };
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -988,20 +988,16 @@ nsJSContext::DOMOperationCallback(JSCont
     const char jsdServiceCtrID[] = "@mozilla.org/js/jsd/debugger-service;1";
     nsCOMPtr<jsdIExecutionHook> jsdHook;
     nsCOMPtr<jsdIDebuggerService> jsds = do_GetService(jsdServiceCtrID, &rv);
 
     // Check if there's a user for the debugger service that's 'on' for us
     if (NS_SUCCEEDED(rv)) {
       jsds->GetDebuggerHook(getter_AddRefs(jsdHook));
       jsds->GetIsOn(&jsds_IsOn);
-      if (jsds_IsOn) { // If this is not true, the next call would start jsd...
-        rv = jsds->OnForRuntime(cx->runtime);
-        jsds_IsOn = NS_SUCCEEDED(rv);
-      }
     }
 
     // If there is a debug handler registered for this runtime AND
     // ((jsd is on AND has a hook) OR (jsd isn't on (something else debugs)))
     // then something useful will be done with our request to debug.
     debugPossible = ((jsds_IsOn && (jsdHook != nsnull)) || !jsds_IsOn);
   }
 #endif
@@ -2529,17 +2525,17 @@ nsJSContext::CreateNativeGlobalForInner(
     nsIScriptSecurityManager *ssm = nsContentUtils::GetSecurityManager();
     ssm->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
   }
 
   nsresult rv = xpc->
           InitClassesWithNewWrappedGlobal(mContext,
                                           aNewInner, NS_GET_IID(nsISupports),
                                           aIsChrome ? systemPrincipal.get() : aPrincipal,
-                                          EmptyCString(), flags,
+                                          nsnull, flags,
                                           getter_AddRefs(jsholder));
   if (NS_FAILED(rv))
     return rv;
   jsholder->GetJSObject(reinterpret_cast<JSObject **>(aNativeGlobal));
   *aHolder = jsholder.get();
   NS_ADDREF(*aHolder);
   return NS_OK;
 }
--- a/dom/interfaces/html/nsIDOMHTMLFormElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLFormElement.idl
@@ -42,17 +42,17 @@
 /**
  * The nsIDOMHTMLFormElement interface is the interface to a [X]HTML
  * form element.
  *
  * For more information on this interface please see
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  */
 
-[scriptable, uuid(653dc482-d6db-4e85-bdd9-151fd110e7b1)]
+[scriptable, uuid(0884ce23-e069-499e-a13c-a91c8ae0fc98)]
 interface nsIDOMHTMLFormElement : nsIDOMHTMLElement
 {
            attribute DOMString            name;
 
            attribute DOMString            acceptCharset;
            attribute DOMString            action;
            attribute DOMString            autocomplete;
            attribute DOMString            enctype;
@@ -60,12 +60,9 @@ interface nsIDOMHTMLFormElement : nsIDOM
            attribute boolean              noValidate;
            attribute DOMString            target;
 
   readonly attribute nsIDOMHTMLCollection elements;
   readonly attribute long                 length;
 
   void                      submit();
   void                      reset();
-
-  // This property returns the resolved action URI.
-  readonly attribute DOMString            mozActionUri;
 };
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -77,16 +77,24 @@
 
 #include "nsIGeolocationProvider.h"
 
 #ifdef MOZ_PERMISSIONS
 #include "nsPermission.h"
 #include "nsPermissionManager.h"
 #endif
 
+#if defined(ANDROID) || defined(LINUX)
+#include <sys/time.h>
+#include <sys/resource.h>
+// TODO: For other platforms that support setpriority, figure out
+//       appropriate values of niceness
+static const int kRelativeNiceness = 10;
+#endif
+
 using namespace mozilla::ipc;
 using namespace mozilla::net;
 using namespace mozilla::places;
 using namespace mozilla::docshell;
 
 namespace mozilla {
 namespace dom {
 class AlertObserver
@@ -204,17 +212,29 @@ ContentChild::Init(MessageLoop* aIOLoop,
 #endif
 
 #ifdef MOZ_X11
     // Do this after initializing GDK, or GDK will install its own handler.
     XRE_InstallX11ErrorHandler();
 #endif
 
     NS_ASSERTION(!sSingleton, "only one ContentChild per child");
-  
+
+#if defined(ANDROID) || defined(LINUX)
+    // XXX We change the behavior of Linux child processes here. That
+    // means that, not just in Fennec, but also in Firefox, once it has
+    // child processes, those will be niced. IOW, Firefox with child processes
+    // will have different performance profiles on Linux than other
+    // platforms. This may alter Talos results and so forth.
+    char* relativeNicenessStr = getenv("MOZ_CHILD_PROCESS_RELATIVE_NICENESS");
+    setpriority(PRIO_PROCESS, 0, getpriority(PRIO_PROCESS, 0) +
+            (relativeNicenessStr ? atoi(relativeNicenessStr) :
+             kRelativeNiceness));
+#endif
+
     Open(aChannel, aParentHandle, aIOLoop);
     sSingleton = this;
 
     return true;
 }
 
 void
 ContentChild::InitXPCOM()
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -845,17 +845,17 @@ TabChild::InitTabChildGlobal()
 
   nsISupports* scopeSupports =
     NS_ISUPPORTS_CAST(nsPIDOMEventTarget*, scope);
   JS_SetContextPrivate(cx, scopeSupports);
 
   nsresult rv =
     xpc->InitClassesWithNewWrappedGlobal(cx, scopeSupports,
                                          NS_GET_IID(nsISupports),
-                                         scope->GetPrincipal(), EmptyCString(),
+                                         scope->GetPrincipal(), nsnull,
                                          flags, getter_AddRefs(mGlobal));
   NS_ENSURE_SUCCESS(rv, false);
 
   nsCOMPtr<nsPIWindowRoot> root = do_QueryInterface(chromeHandler);
   NS_ENSURE_TRUE(root, false);
   root->SetParentTarget(scope);
   
   JSObject* global = nsnull;
--- a/dom/plugins/PluginInstanceParent.cpp
+++ b/dom/plugins/PluginInstanceParent.cpp
@@ -1413,12 +1413,12 @@ PluginInstanceParent::AnswerPluginFocusC
     return false;
 #endif
 }
 
 #ifdef OS_MACOSX
 void
 PluginInstanceParent::Invalidate()
 {
-    NPRect windowRect = {0, 0, mShWidth, mShHeight};
+    NPRect windowRect = {0, 0, mShHeight, mShWidth};
     RecvNPN_InvalidateRect(windowRect);
 }
 #endif
--- a/dom/plugins/PluginModuleParent.cpp
+++ b/dom/plugins/PluginModuleParent.cpp
@@ -122,16 +122,22 @@ PluginModuleParent::PluginModuleParent(c
 
     nsContentUtils::RegisterPrefCallback(kTimeoutPref, TimeoutChanged, this);
 }
 
 PluginModuleParent::~PluginModuleParent()
 {
     NS_ASSERTION(OkToCleanup(), "unsafe destruction");
 
+#ifdef OS_MACOSX
+    if (mCATimer) {
+        mCATimer->Cancel();
+    }
+#endif
+
     if (!mShutdown) {
         NS_WARNING("Plugin host deleted the module without shutting down.");
         NPError err;
         NP_Shutdown(&err);
     }
     NS_ASSERTION(mShutdown, "NP_Shutdown didn't");
 
     if (mSubprocess) {
@@ -885,37 +891,49 @@ PluginModuleParent::RecvPluginHideWindow
     NS_NOTREACHED(
         "PluginInstanceParent::RecvPluginHideWindow not implemented!");
     return false;
 #endif
 }
 
 #ifdef OS_MACOSX
 #define DEFAULT_REFRESH_MS 20 // CoreAnimation: 50 FPS
+
+void
+CAUpdate(nsITimer *aTimer, void *aClosure) {
+    nsTObserverArray<PluginInstanceParent*> *ips =
+        static_cast<nsTObserverArray<PluginInstanceParent*> *>(aClosure);
+    nsTObserverArray<PluginInstanceParent*>::ForwardIterator iter(*ips);
+    while (iter.HasMore()) {
+        iter.GetNext()->Invalidate();
+    }
+}
+
 void
 PluginModuleParent::AddToRefreshTimer(PluginInstanceParent *aInstance) {
     if (mCATimerTargets.Contains(aInstance)) {
         return;
     }
 
     mCATimerTargets.AppendElement(aInstance);
     if (mCATimerTargets.Length() == 1) {
-        mCATimer.Start(base::TimeDelta::FromMilliseconds(DEFAULT_REFRESH_MS),
-                       this, &PluginModuleParent::CAUpdate);
+        if (!mCATimer) {
+            nsresult rv;
+            nsCOMPtr<nsITimer> xpcomTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
+            if (NS_FAILED(rv)) {
+                NS_WARNING("Could not create Core Animation timer for plugin.");
+                return;
+            }
+            mCATimer = xpcomTimer;
+        }
+        mCATimer->InitWithFuncCallback(CAUpdate, &mCATimerTargets, DEFAULT_REFRESH_MS,
+                                       nsITimer::TYPE_REPEATING_SLACK);
     }
 }
 
 void
 PluginModuleParent::RemoveFromRefreshTimer(PluginInstanceParent *aInstance) {
     PRBool visibleRemoved = mCATimerTargets.RemoveElement(aInstance);
     if (visibleRemoved && mCATimerTargets.IsEmpty()) {
-        mCATimer.Stop();
-    }
-}
-
-void
-PluginModuleParent::CAUpdate() {
-    nsTObserverArray<PluginInstanceParent*>::ForwardIterator iter(mCATimerTargets);
-    while (iter.HasMore()) {
-        iter.GetNext()->Invalidate();
+        mCATimer->Cancel();
     }
 }
 #endif
--- a/dom/plugins/PluginModuleParent.h
+++ b/dom/plugins/PluginModuleParent.h
@@ -56,16 +56,17 @@
 #include "mozilla/plugins/PluginProcessParent.h"
 #include "mozilla/plugins/PluginIdentifierParent.h"
 
 #include "nsAutoPtr.h"
 #include "nsDataHashtable.h"
 #include "nsHashKeys.h"
 #include "nsIFileStreams.h"
 #include "nsTObserverArray.h"
+#include "nsITimer.h"
 
 namespace mozilla {
 namespace plugins {
 //-----------------------------------------------------------------------------
 
 class BrowserStreamParent;
 
 /**
@@ -258,18 +259,17 @@ private:
     nsNPAPIPlugin* mPlugin;
     time_t mProcessStartTime;
     ScopedRunnableMethodFactory<PluginModuleParent> mTaskFactory;
     nsString mPluginDumpID;
     nsString mBrowserDumpID;
     nsString mHangID;
 
 #ifdef OS_MACOSX
-    void CAUpdate();
-    base::RepeatingTimer<PluginModuleParent> mCATimer;
+    nsCOMPtr<nsITimer> mCATimer;
     nsTObserverArray<PluginInstanceParent*> mCATimerTargets;
 #endif
 };
 
 } // namespace plugins
 } // namespace mozilla
 
 #endif  // ifndef dom_plugins_PluginModuleParent_h
--- a/dom/src/threads/nsDOMWorker.cpp
+++ b/dom/src/threads/nsDOMWorker.cpp
@@ -1636,25 +1636,22 @@ nsDOMWorker::CompileGlobalObject(JSConte
 
   nsISupports* scopeSupports = NS_ISUPPORTS_CAST(nsIWorkerScope*, scope);
 
   nsIXPConnect* xpc = nsContentUtils::XPConnect();
 
   const PRUint32 flags = nsIXPConnect::INIT_JS_STANDARD_CLASSES |
                          nsIXPConnect::OMIT_COMPONENTS_OBJECT;
 
-  nsCAutoString origin("DOM worker: ");
-  origin.AppendInt((PRUint64)this);
-
   nsCOMPtr<nsIXPConnectJSObjectHolder> globalWrapper;
   nsresult rv =
     xpc->InitClassesWithNewWrappedGlobal(aCx, scopeSupports,
                                          NS_GET_IID(nsISupports), nsnull,
-                                         origin, flags,
-                                         getter_AddRefs(globalWrapper));
+                                         NS_ISUPPORTS_CAST(nsIWorker*, this),
+                                         flags, getter_AddRefs(globalWrapper));
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
 
   JSObject* global;
   rv = globalWrapper->GetJSObject(&global);
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
 
   NS_ASSERTION(JS_GetGlobalObject(aCx) == global, "Global object mismatch!");
 
--- a/dom/tests/mochitest/dom-level2-html/test_button03.html
+++ b/dom/tests/mochitest/dom-level2-html/test_button03.html
@@ -94,17 +94,17 @@ function button03() {
       assertSize("Asize",2,nodeList);
 testNode = nodeList.item(0);
       formNode = testNode.form;
 
       vfaction = formNode.action;
 
       // its not clear that this test is valid
       // mozilla returns a fully expanded uri
-      is(vfaction, "...", "formLink");
+      is(vfaction, formNode.ownerDocument.location.href.replace(/button\.html/, "..."), "formLink");
        
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/html/button03</h2>
 <p>&lt;test name='button03' schemaLocation='http://www.w3.org/2001/DOM-Test-Suite/Level-1 dom1.xsd'&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;metadata&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;button03&lt;/title&gt;
--- a/dom/tests/mochitest/geolocation/test_manyCurrentConcurrent.html
+++ b/dom/tests/mochitest/geolocation/test_manyCurrentConcurrent.html
@@ -19,29 +19,38 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 SimpleTest.waitForExplicitFinish();
 resume_geolocationProvider();
 force_prompt(true);
 
-var successCallbackCalled = false;
+var successCallbackCalled = 0;
+var failureCallbackCalled = 0;
+const totalResults = 100;
 
 function successCallback(position) {
-  successCallbackCalled = true;
+  successCallbackCalled++;
+  testPassed();
 }
 
-for (var x = 0; x < 100; x++)
-  navigator.geolocation.getCurrentPosition(successCallback);
+function failureCallback(code) {
+  failureCallbackCalled++;
+  testPassed();
+}
+
+for (var x = 0; x < totalResults; x++)
+  navigator.geolocation.getCurrentPosition(successCallback, failureCallback);
 
 function testPassed() {
-  ok(successCallbackCalled, "if nothing crashed, all okay");
+  if (successCallbackCalled + failureCallbackCalled != totalResults)
+    return;
+  is(failureCallbackCalled, 0, "no failure callbacks should have been received");
   reset_prompt();
   SimpleTest.finish();
 }
-setTimeout(testPassed, 1000);
 
 </script>
 </pre>
 </body>
 </html>
 
--- a/dom/tests/mochitest/geolocation/test_manyWatchConcurrent.html
+++ b/dom/tests/mochitest/geolocation/test_manyWatchConcurrent.html
@@ -39,17 +39,17 @@ function failureCallback(code) {
 }
 
 for (var x = 0; x < totalResults; x++)
   navigator.geolocation.watchPosition(successCallback, failureCallback);
 
 function testPassed() {
   if (successCallbackCalled + failureCallbackCalled != totalResults)
     return;
-  is(failureCallbackCalled, 0, "if nothing crashed, all okay");
+  is(failureCallbackCalled, 0, "no failure callbacks should have been received");
   reset_prompt();
   SimpleTest.finish();
 }
 
 </script>
 </pre>
 </body>
 </html>
--- a/editor/composer/src/nsEditingSession.cpp
+++ b/editor/composer/src/nsEditingSession.cpp
@@ -1021,19 +1021,19 @@ nsEditingSession::EndDocumentLoad(nsIWeb
   {
     PRBool  makeEditable;
     editorDocShell->GetEditable(&makeEditable);
   
     if (makeEditable)
     {
       // To keep pre Gecko 1.9 behavior, setup editor always when
       // mMakeWholeDocumentEditable.
-      PRBool needsSetup;
+      bool needsSetup = false;
       if (mMakeWholeDocumentEditable) {
-        needsSetup = PR_TRUE;
+        needsSetup = true;
       } else {
         // do we already have an editor here?
         nsCOMPtr<nsIEditor> editor;
         rv = editorDocShell->GetEditor(getter_AddRefs(editor));
         NS_ENSURE_SUCCESS(rv, rv);
 
         needsSetup = !editor;
       }
--- a/editor/composer/src/nsEditorSpellCheck.cpp
+++ b/editor/composer/src/nsEditorSpellCheck.cpp
@@ -449,17 +449,20 @@ nsEditorSpellCheck::SetCurrentDictionary
 
 NS_IMETHODIMP    
 nsEditorSpellCheck::UninitSpellChecker()
 {
   NS_ENSURE_TRUE(mSpellChecker, NS_ERROR_NOT_INITIALIZED);
 
   // we preserve the last selected language, but ignore errors so we continue
   // to uninitialize
-  nsresult rv = SaveDefaultDictionary();
+#ifdef DEBUG
+  nsresult rv =
+#endif
+  SaveDefaultDictionary();
   NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "failed to set default dictionary");
 
   // Cleanup - kill the spell checker
   DeleteSuggestedWordList();
   mDictionaryList.Clear();
   mDictionaryIndex = 0;
   mSpellChecker = 0;
   return NS_OK;
--- a/editor/libeditor/base/ChangeCSSInlineStyleTxn.cpp
+++ b/editor/libeditor/base/ChangeCSSInlineStyleTxn.cpp
@@ -261,17 +261,17 @@ NS_IMETHODIMP ChangeCSSInlineStyleTxn::D
 }
 
 nsresult ChangeCSSInlineStyleTxn::SetStyle(PRBool aAttributeWasSet,
                                            nsAString & aValue)
 {
   NS_ASSERTION(mEditor && mElement, "bad state");
   if (!mEditor || !mElement) { return NS_ERROR_NOT_INITIALIZED; }
 
-  nsresult result;
+  nsresult result = NS_OK;
   if (aAttributeWasSet) {
     // the style attribute was set and not empty, let's recreate the declaration
     nsAutoString propertyNameString;
     mProperty->ToString(propertyNameString);
 
     nsCOMPtr<nsIDOMElementCSSInlineStyle> inlineStyles = do_QueryInterface(mElement);
     NS_ENSURE_TRUE(inlineStyles, NS_ERROR_NULL_POINTER);
     nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl;
--- a/editor/libeditor/base/DeleteRangeTxn.cpp
+++ b/editor/libeditor/base/DeleteRangeTxn.cpp
@@ -248,17 +248,17 @@ NS_IMETHODIMP DeleteRangeTxn::GetTxnDesc
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 DeleteRangeTxn::CreateTxnsToDeleteBetween(nsIDOMNode *aStartParent, 
                                           PRUint32    aStartOffset, 
                                           PRUint32    aEndOffset)
 {
-  nsresult result;
+  nsresult result = NS_OK;
   // see what kind of node we have
   nsCOMPtr<nsIDOMCharacterData> textNode = do_QueryInterface(aStartParent);
   if (textNode)
   { // if the node is a text node, then delete text content
     nsRefPtr<DeleteTextTxn> txn = new DeleteTextTxn();
     NS_ENSURE_TRUE(txn, NS_ERROR_OUT_OF_MEMORY);
 
     PRInt32 numToDel;
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -219,25 +219,28 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUO
 #pragma mark  nsIEditorMethods 
 #pragma mark -
 #endif
 
 
 NS_IMETHODIMP
 nsEditor::Init(nsIDOMDocument *aDoc, nsIPresShell* aPresShell, nsIContent *aRoot, nsISelectionController *aSelCon, PRUint32 aFlags)
 {
-  NS_PRECONDITION(nsnull!=aDoc && nsnull!=aPresShell, "bad arg");
-  if ((nsnull==aDoc) || (nsnull==aPresShell))
+  NS_PRECONDITION(aDoc && aPresShell, "bad arg");
+  if (!aDoc || !aPresShell)
     return NS_ERROR_NULL_POINTER;
 
   // First only set flags, but other stuff shouldn't be initialized now.
   // Don't move this call after initializing mDocWeak and mPresShellWeak.
   // SetFlags() can check whether it's called during initialization or not by
   // them.  Note that SetFlags() will be called by PostCreate().
-  nsresult rv = SetFlags(aFlags);
+#ifdef DEBUG
+  nsresult rv =
+#endif
+  SetFlags(aFlags);
   NS_ASSERTION(NS_SUCCEEDED(rv), "SetFlags() failed");
 
   mDocWeak = do_GetWeakReference(aDoc);  // weak reference to doc
   mPresShellWeak = do_GetWeakReference(aPresShell);   // weak reference to pres shell
   mSelConWeak = do_GetWeakReference(aSelCon);   // weak reference to selectioncontroller
 
   nsCOMPtr<nsIPresShell> ps = do_QueryReferent(mPresShellWeak);
   NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);
@@ -307,33 +310,28 @@ nsEditor::PostCreate()
   // do this before we notify listeners
   ResetModificationCount();
   
   // update the UI with our state
   NotifyDocumentListeners(eDocumentCreated);
   NotifyDocumentListeners(eDocumentStateChanged);
   
   // update nsTextStateManager and caret if we have focus
-  if (HasFocus()) {
-    nsFocusManager* fm = nsFocusManager::GetFocusManager();
-    NS_ASSERTION(fm, "no focus manager?");
-
-    nsCOMPtr<nsIContent> focusedContent = fm->GetFocusedContent();
-    if (focusedContent) {
-      nsCOMPtr<nsIPresShell> ps = do_QueryReferent(mPresShellWeak);
-      NS_ASSERTION(ps, "no pres shell even though we have focus");
-      nsPresContext* pc = ps->GetPresContext(); 
-
-      nsIMEStateManager::OnTextStateBlur(pc, nsnull);
-      nsIMEStateManager::OnTextStateFocus(pc, focusedContent);