Merge with m-c. no hand edits
authorDoug Turner <dougt@dougt.org>
Thu, 29 Apr 2010 21:04:50 -0700
changeset 46839 288aeb67ac3794b0c62098faaad3ceb58cfc8b09
parent 46838 2f30bbaa0912c4acf6fd1c5f4b6bf1d7498712d2 (current diff)
parent 41539 c8e77c61cfed9e8b4df6ddc1ad32b823dc89740a (diff)
child 46840 76eb99fc5ecd985b9c96d694c040728a236ebcd8
push idunknown
push userunknown
push dateunknown
milestone1.9.3a5pre
Merge with m-c. no hand edits
content/base/public/Makefile.in
content/base/public/nsContentUtils.h
content/base/src/Makefile.in
content/base/src/nsContentUtils.cpp
content/base/src/nsGkAtomList.h
content/html/content/src/nsGenericHTMLElement.cpp
content/media/ogg/nsChannelReader.cpp
content/media/ogg/nsChannelReader.h
content/media/ogg/nsOggDecoder.cpp
content/media/ogg/nsOggDecoder.h
content/media/ogg/nsOggHacks.h
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMClassInfoClasses.h
dom/base/nsGlobalWindow.cpp
dom/base/nsGlobalWindow.h
dom/base/nsJSEnvironment.cpp
dom/plugins/PPluginInstance.ipdl
dom/plugins/PluginInstanceChild.cpp
dom/plugins/PluginInstanceParent.cpp
dom/plugins/PluginInstanceParent.h
dom/plugins/PluginModuleChild.cpp
dom/tests/mochitest/ajax/lib/MochiKit_packed.js
dom/tests/mochitest/ajax/lib/SimpleTest.js
gfx/cairo/cairo/src/cairo-qpainter-surface.cpp
gfx/cairo/cairo/src/cairo-qpainter.h
gfx/cairo/pixman-neon.patch
ipc/glue/RPCChannel.cpp
ipc/glue/RPCChannel.h
ipc/ipdl/Makefile.in
ipc/ipdl/ipdl/cxx/ast.py
ipc/ipdl/ipdl/cxx/cgen.py
ipc/ipdl/ipdl/lower.py
ipc/ipdl/ipdl/type.py
ipc/ipdl/test/cxx/TestLatency.cpp
media/libfishsound/AUTHORS
media/libfishsound/COPYING
media/libfishsound/ChangeLog
media/libfishsound/Makefile.in
media/libfishsound/README
media/libfishsound/README_MOZILLA
media/libfishsound/bug487519.patch
media/libfishsound/bug520500.patch
media/libfishsound/endian.patch
media/libfishsound/fishsound_reset.patch
media/libfishsound/include/Makefile.in
media/libfishsound/include/fishsound/Makefile.in
media/libfishsound/include/fishsound/comments.h
media/libfishsound/include/fishsound/config.h
media/libfishsound/include/fishsound/constants.h
media/libfishsound/include/fishsound/decode.h
media/libfishsound/include/fishsound/deprecated.h
media/libfishsound/include/fishsound/encode.h
media/libfishsound/include/fishsound/fishsound.h
media/libfishsound/src/Makefile.in
media/libfishsound/src/libfishsound/Makefile.in
media/libfishsound/src/libfishsound/config.h
media/libfishsound/src/libfishsound/convert.h
media/libfishsound/src/libfishsound/convert_c.h
media/libfishsound/src/libfishsound/convert_oil.h
media/libfishsound/src/libfishsound/debug.h
media/libfishsound/src/libfishsound/fishsound.c
media/libfishsound/src/libfishsound/fishsound_comments.c
media/libfishsound/src/libfishsound/fishsound_decode.c
media/libfishsound/src/libfishsound/fishsound_encode.c
media/libfishsound/src/libfishsound/fishsound_flac.c
media/libfishsound/src/libfishsound/fishsound_speex.c
media/libfishsound/src/libfishsound/fishsound_vorbis.c
media/libfishsound/src/libfishsound/fs_compat.h
media/libfishsound/src/libfishsound/fs_vector.c
media/libfishsound/src/libfishsound/fs_vector.h
media/libfishsound/src/libfishsound/private.h
media/libfishsound/trac497.patch
media/libfishsound/update.sh
media/liboggplay/COPYING
media/liboggplay/Makefile.in
media/liboggplay/README
media/liboggplay/README_MOZILLA
media/liboggplay/aspect_ratio.patch
media/liboggplay/bug481921.patch
media/liboggplay/bug487519.patch
media/liboggplay/bug493678.patch
media/liboggplay/bug496529.patch
media/liboggplay/bug500311.patch
media/liboggplay/bug504843.patch
media/liboggplay/bug515217.patch
media/liboggplay/bug520493.patch
media/liboggplay/bug523816.patch
media/liboggplay/endian.patch
media/liboggplay/faster_seek.patch
media/liboggplay/fishsound_reset.patch
media/liboggplay/fix-17ef4ca82df28.patch
media/liboggplay/handle-read-errors.patch
media/liboggplay/include/Makefile.in
media/liboggplay/include/oggplay/Makefile.in
media/liboggplay/include/oggplay/config_win32.h
media/liboggplay/include/oggplay/oggplay.h
media/liboggplay/include/oggplay/oggplay_callback_info.h
media/liboggplay/include/oggplay/oggplay_enums.h
media/liboggplay/include/oggplay/oggplay_query.h
media/liboggplay/include/oggplay/oggplay_reader.h
media/liboggplay/include/oggplay/oggplay_seek.h
media/liboggplay/include/oggplay/oggplay_tools.h
media/liboggplay/liboggplay-199a8cea6c4fd6d.patch
media/liboggplay/oggplay_os2.patch
media/liboggplay/seek_to_key_frame.patch
media/liboggplay/src/Makefile.in
media/liboggplay/src/liboggplay/Makefile.in
media/liboggplay/src/liboggplay/config.h
media/liboggplay/src/liboggplay/cpu.c
media/liboggplay/src/liboggplay/cpu.h
media/liboggplay/src/liboggplay/oggplay.c
media/liboggplay/src/liboggplay/oggplay_buffer.c
media/liboggplay/src/liboggplay/oggplay_buffer.h
media/liboggplay/src/liboggplay/oggplay_callback.c
media/liboggplay/src/liboggplay/oggplay_callback.h
media/liboggplay/src/liboggplay/oggplay_callback_info.c
media/liboggplay/src/liboggplay/oggplay_data.c
media/liboggplay/src/liboggplay/oggplay_data.h
media/liboggplay/src/liboggplay/oggplay_file_reader.c
media/liboggplay/src/liboggplay/oggplay_file_reader.h
media/liboggplay/src/liboggplay/oggplay_private.h
media/liboggplay/src/liboggplay/oggplay_query.c
media/liboggplay/src/liboggplay/oggplay_seek.c
media/liboggplay/src/liboggplay/oggplay_tcp_reader.c
media/liboggplay/src/liboggplay/oggplay_tcp_reader.h
media/liboggplay/src/liboggplay/oggplay_tools.c
media/liboggplay/src/liboggplay/oggplay_yuv2rgb.c
media/liboggplay/src/liboggplay/oggplay_yuv2rgb_template.h
media/liboggplay/src/liboggplay/os2_semaphore.c
media/liboggplay/src/liboggplay/os2_semaphore.h
media/liboggplay/src/liboggplay/std_semaphore.h
media/liboggplay/src/liboggplay/x86/oggplay_yuv2rgb_x86.c
media/liboggplay/src/liboggplay/x86/yuv2rgb_x86.h
media/liboggplay/src/liboggplay/x86/yuv2rgb_x86_vs.h
media/liboggplay/update.sh
media/liboggz/AUTHORS
media/liboggz/COPYING
media/liboggz/ChangeLog
media/liboggz/Makefile.in
media/liboggz/README
media/liboggz/README_MOZILLA
media/liboggz/bug487519.patch
media/liboggz/bug496063.patch
media/liboggz/bug498380.patch
media/liboggz/bug504843.patch
media/liboggz/bug516847.patch
media/liboggz/bug518169.patch
media/liboggz/bug519155.patch
media/liboggz/bug520493.patch
media/liboggz/bug523335.patch
media/liboggz/bug526097.patch
media/liboggz/bug533822.patch
media/liboggz/faster_seek.patch
media/liboggz/include/Makefile.in
media/liboggz/include/oggz/Makefile.in
media/liboggz/include/oggz/config.h
media/liboggz/include/oggz/config_gcc.h
media/liboggz/include/oggz/config_win32.h
media/liboggz/include/oggz/oggz.h
media/liboggz/include/oggz/oggz_comments.h
media/liboggz/include/oggz/oggz_constants.h
media/liboggz/include/oggz/oggz_deprecated.h
media/liboggz/include/oggz/oggz_io.h
media/liboggz/include/oggz/oggz_off_t.h
media/liboggz/include/oggz/oggz_off_t_generated.h
media/liboggz/include/oggz/oggz_read.h
media/liboggz/include/oggz/oggz_seek.h
media/liboggz/include/oggz/oggz_stream.h
media/liboggz/include/oggz/oggz_table.h
media/liboggz/include/oggz/oggz_write.h
media/liboggz/key_frame_seek.patch
media/liboggz/offset_next.patch
media/liboggz/oggz_os2.patch
media/liboggz/seek.patch
media/liboggz/src/Makefile.in
media/liboggz/src/liboggz/Makefile.in
media/liboggz/src/liboggz/dirac.c
media/liboggz/src/liboggz/dirac.h
media/liboggz/src/liboggz/metric_internal.c
media/liboggz/src/liboggz/oggz.c
media/liboggz/src/liboggz/oggz_auto.c
media/liboggz/src/liboggz/oggz_auto.h
media/liboggz/src/liboggz/oggz_byteorder.h
media/liboggz/src/liboggz/oggz_comments.c
media/liboggz/src/liboggz/oggz_compat.h
media/liboggz/src/liboggz/oggz_dlist.c
media/liboggz/src/liboggz/oggz_dlist.h
media/liboggz/src/liboggz/oggz_io.c
media/liboggz/src/liboggz/oggz_macros.h
media/liboggz/src/liboggz/oggz_private.h
media/liboggz/src/liboggz/oggz_read.c
media/liboggz/src/liboggz/oggz_seek.c
media/liboggz/src/liboggz/oggz_stream.c
media/liboggz/src/liboggz/oggz_stream.h
media/liboggz/src/liboggz/oggz_stream_private.h
media/liboggz/src/liboggz/oggz_table.c
media/liboggz/src/liboggz/oggz_vector.c
media/liboggz/src/liboggz/oggz_vector.h
media/liboggz/src/liboggz/oggz_write.c
media/liboggz/update.sh
media/liboggz/wince.patch
memory/mozalloc/throw_msvc.cpp
modules/plugin/test/mochitest/Makefile.in
modules/plugin/test/testplugin/nptest.cpp
modules/plugin/test/testplugin/nptest.h
modules/plugin/test/testplugin/nptest_gtk2.cpp
netwerk/base/src/nsStandardURL.cpp
netwerk/protocol/http/src/nsHttpChannel.cpp
parser/html/nsAHtml5EncodingDeclarationHandler.h
toolkit/content/tests/chrome/bug437844.css
toolkit/content/tests/chrome/bug437844.dtd
toolkit/content/tests/chrome/bug437844.manifest
toolkit/content/widgets/browser.xml
toolkit/library/libxul-config.mk
toolkit/toolkit-makefiles.sh
toolkit/toolkit-tiers.mk
toolkit/xre/nsAppRunner.cpp
--- a/.hgignore
+++ b/.hgignore
@@ -1,14 +1,14 @@
 # .hgignore - List of filenames hg should ignore
 
 # Filenames that should be ignored wherever they appear
 ~$
 \.py(c|o)$
-(^|/)TAGS$
+(?i)(^|/)TAGS$
 (^|/)ID$
 (^|/)\.DS_Store$
 
 # User files that may appear at the root
 ^\.mozconfig
 ^mozconfig
 ^configure$
 ^config\.cache$
--- a/accessible/public/nsIAccessibilityService.h
+++ b/accessible/public/nsIAccessibilityService.h
@@ -146,17 +146,17 @@ public:
   virtual nsresult InvalidateSubtreeFor(nsIPresShell *aPresShell,
                                         nsIContent *aContent,
                                         PRUint32 aChangeType) = 0;
 
   /**
    * Notify accessibility that anchor jump has been accomplished to the given
    * target. Used by layout.
    */
-  virtual nsresult NotifyOfAnchorJumpTo(nsIContent *aTarget) = 0;
+  virtual void NotifyOfAnchorJumpTo(nsIContent *aTarget) = 0;
 
   /**
    * Fire accessible event of the given type for the given target.
    *
    * @param aEvent   [in] accessible event type
    * @param aTarget  [in] target of accessible event
    */
   virtual nsresult FireAccessibleEvent(PRUint32 aEvent,
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -35,24 +35,27 @@
  * 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 ***** */
 
 #include "nsAccessibleWrap.h"
+
+#include "nsAccUtils.h"
 #include "nsApplicationAccessibleWrap.h"
 #include "nsRootAccessible.h"
 #include "nsDocAccessibleWrap.h"
 #include "nsIAccessibleValue.h"
 #include "nsString.h"
 #include "nsAutoPtr.h"
 #include "prprf.h"
 #include "nsRoleMap.h"
+#include "nsRelUtils.h"
 #include "nsStateMap.h"
 
 #include "nsMaiInterfaceComponent.h"
 #include "nsMaiInterfaceAction.h"
 #include "nsMaiInterfaceText.h"
 #include "nsMaiInterfaceEditableText.h"
 #include "nsMaiInterfaceSelection.h"
 #include "nsMaiInterfaceValue.h"
@@ -1150,17 +1153,17 @@ nsAccessibleWrap::FirePlatformEvent(nsAc
 
     case nsIAccessibleEvent::EVENT_FOCUS:
       {
         MAI_LOG_DEBUG(("\n\nReceived: EVENT_FOCUS\n"));
         nsRefPtr<nsRootAccessible> rootAccWrap = accWrap->GetRootAccessible();
         if (rootAccWrap && rootAccWrap->mActivated) {
             atk_focus_tracker_notify(atkObj);
             // Fire state change event for focus
-            nsCOMPtr<nsIAccessibleEvent> stateChangeEvent =
+            nsRefPtr<nsAccEvent> stateChangeEvent =
               new nsAccStateChangeEvent(accessible,
                                         nsIAccessibleStates::STATE_FOCUSED,
                                         PR_FALSE, PR_TRUE);
             return FireAtkStateChangeEvent(stateChangeEvent, atkObj);
         }
       } break;
 
     case nsIAccessibleEvent::EVENT_VALUE_CHANGE:
@@ -1378,17 +1381,17 @@ nsAccessibleWrap::FirePlatformEvent(nsAc
         atk_object_notify_state_change(atkObj, ATK_STATE_SHOWING, PR_FALSE);
         break;
     }
 
     return NS_OK;
 }
 
 nsresult
-nsAccessibleWrap::FireAtkStateChangeEvent(nsIAccessibleEvent *aEvent,
+nsAccessibleWrap::FireAtkStateChangeEvent(nsAccEvent *aEvent,
                                           AtkObject *aObject)
 {
     MAI_LOG_DEBUG(("\n\nReceived: EVENT_STATE_CHANGE\n"));
 
     nsCOMPtr<nsIAccessibleStateChangeEvent> event =
         do_QueryInterface(aEvent);
     NS_ENSURE_TRUE(event, NS_ERROR_FAILURE);
 
@@ -1420,17 +1423,17 @@ nsAccessibleWrap::FireAtkStateChangeEven
                                            isEnabled);
         }
     }
 
     return NS_OK;
 }
 
 nsresult
-nsAccessibleWrap::FireAtkTextChangedEvent(nsIAccessibleEvent *aEvent,
+nsAccessibleWrap::FireAtkTextChangedEvent(nsAccEvent *aEvent,
                                           AtkObject *aObject)
 {
     MAI_LOG_DEBUG(("\n\nReceived: EVENT_TEXT_REMOVED/INSERTED\n"));
 
     nsCOMPtr<nsIAccessibleTextChangeEvent> event =
         do_QueryInterface(aEvent);
     NS_ENSURE_TRUE(event, NS_ERROR_FAILURE);
 
@@ -1438,42 +1441,40 @@ nsAccessibleWrap::FireAtkTextChangedEven
     event->GetStart(&start);
 
     PRUint32 length = 0;
     event->GetLength(&length);
 
     PRBool isInserted;
     event->IsInserted(&isInserted);
 
-    PRBool isFromUserInput;
-    aEvent->GetIsFromUserInput(&isFromUserInput);
+    PRBool isFromUserInput = aEvent->IsFromUserInput();
 
     char *signal_name = g_strconcat(isInserted ? "text_changed::insert" : "text_changed::delete",
                                     isFromUserInput ? "" : kNonUserInputEvent, NULL);
     g_signal_emit_by_name(aObject, signal_name, start, length);
     g_free (signal_name);
 
     return NS_OK;
 }
 
 nsresult
-nsAccessibleWrap::FireAtkShowHideEvent(nsIAccessibleEvent *aEvent,
+nsAccessibleWrap::FireAtkShowHideEvent(nsAccEvent *aEvent,
                                        AtkObject *aObject, PRBool aIsAdded)
 {
     if (aIsAdded)
         MAI_LOG_DEBUG(("\n\nReceived: Show event\n"));
     else
         MAI_LOG_DEBUG(("\n\nReceived: Hide event\n"));
 
     PRInt32 indexInParent = getIndexInParentCB(aObject);
     AtkObject *parentObject = getParentCB(aObject);
     NS_ENSURE_STATE(parentObject);
 
-    PRBool isFromUserInput;
-    aEvent->GetIsFromUserInput(&isFromUserInput);
+    PRBool isFromUserInput = aEvent->IsFromUserInput();
     char *signal_name = g_strconcat(aIsAdded ? "children_changed::add" :  "children_changed::remove",
                                     isFromUserInput ? "" : kNonUserInputEvent, NULL);
     g_signal_emit_by_name(parentObject, signal_name, indexInParent, aObject, NULL);
     g_free(signal_name);
 
     return NS_OK;
 }
 
--- a/accessible/src/atk/nsAccessibleWrap.h
+++ b/accessible/src/atk/nsAccessibleWrap.h
@@ -115,24 +115,20 @@ public:
       static nsCString returnedString;
       returnedString = NS_ConvertUTF16toUTF8(aString);
       return returnedString.get();
     }
 
 protected:
     virtual nsresult FirePlatformEvent(nsAccEvent *aEvent);
 
-    nsresult FireAtkStateChangeEvent(nsIAccessibleEvent *aEvent,
-                                     AtkObject *aObject);
-    nsresult FireAtkTextChangedEvent(nsIAccessibleEvent *aEvent,
-                                     AtkObject *aObject);
-    nsresult FireAtkPropChangedEvent(nsIAccessibleEvent *aEvent,
-                                     AtkObject *aObject);
-    nsresult FireAtkShowHideEvent(nsIAccessibleEvent *aEvent,
-                                  AtkObject *aObject, PRBool aIsAdded);
+    nsresult FireAtkStateChangeEvent(nsAccEvent *aEvent, AtkObject *aObject);
+    nsresult FireAtkTextChangedEvent(nsAccEvent *aEvent, AtkObject *aObject);
+    nsresult FireAtkShowHideEvent(nsAccEvent *aEvent, AtkObject *aObject,
+                                  PRBool aIsAdded);
 
     AtkObject *mAtkObject;
 
 private:
     PRUint16 CreateMaiInterfaces(void);
 };
 
 #endif /* __NS_ACCESSIBLE_WRAP_H__ */
--- a/accessible/src/atk/nsMaiInterfaceAction.cpp
+++ b/accessible/src/atk/nsMaiInterfaceAction.cpp
@@ -35,19 +35,22 @@
  * 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 ***** */
 
 #include "nsMaiInterfaceAction.h"
 
+#include "nsAccUtils.h"
 #include "nsRoleMap.h"
 #include "nsString.h"
 
+#include "nsIDOMDOMStringList.h"
+
 void
 actionInterfaceInitCB(AtkActionIface *aIface)
 {
     NS_ASSERTION(aIface, "Invalid aIface");
     if (!aIface)
         return;
 
     aIface->do_action = doActionCB;
--- a/accessible/src/atk/nsMaiInterfaceComponent.cpp
+++ b/accessible/src/atk/nsMaiInterfaceComponent.cpp
@@ -34,17 +34,21 @@
  * 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 ***** */
 
 #include "nsMaiInterfaceComponent.h"
+
 #include "nsAccessibleWrap.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
+
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentView.h"
 #include "nsIDOMAbstractView.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIInterfaceRequestorUtils.h"
 
 void
--- a/accessible/src/atk/nsMaiInterfaceTable.cpp
+++ b/accessible/src/atk/nsMaiInterfaceTable.cpp
@@ -35,16 +35,18 @@
  * 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 ***** */
 
 #include "nsMaiInterfaceTable.h"
 
+#include "nsAccUtils.h"
+
 #include "nsArrayUtils.h"
 
 void
 tableInterfaceInitCB(AtkTableIface *aIface)
 
 {
     g_return_if_fail(aIface != NULL);
 
--- a/accessible/src/base/Makefile.in
+++ b/accessible/src/base/Makefile.in
@@ -69,17 +69,18 @@ CPPSRCS = \
   nsApplicationAccessible.cpp \
   nsCaretAccessible.cpp \
   nsTextAccessible.cpp \
   nsTextEquivUtils.cpp \
   nsTextAttrs.cpp \
   $(NULL)
 
 EXPORTS = \
-  nsRootAccessible.h \
+  a11yGeneric.h \
+  nsAccessible.h \
   nsAccessNode.h \
   $(NULL)
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
copy from accessible/src/base/nsCoreUtils.h
copy to accessible/src/base/a11yGeneric.h
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/a11yGeneric.h
@@ -10,18 +10,18 @@
  * 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
- * Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2007
+ * Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2010
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Alexander Surkov <surkov.alexander@gmail.com> (original author)
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either of 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"),
@@ -31,447 +31,47 @@
  * 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 nsCoreUtils_h_
-#define nsCoreUtils_h_
-
-#include "nsAccessibilityAtoms.h"
-
-#include "nsIDOMNode.h"
-#include "nsIContent.h"
-#include "nsIBoxObject.h"
-#include "nsITreeBoxObject.h"
-#include "nsITreeColumns.h"
-
-#include "nsIFrame.h"
-#include "nsIDocShellTreeItem.h"
-#include "nsIArray.h"
-#include "nsIMutableArray.h"
-#include "nsPoint.h"
-
-class nsCoreUtils
-{
-public:
-  /**
-   * Return true if the given node has registered click, mousedown or mouseup
-   * event listeners.
-   */
-  static PRBool HasClickListener(nsIContent *aContent);
-
-  /**
-   * Dispatch click event to XUL tree cell.
-   *
-   * @param  aTreeBoxObj  [in] tree box object
-   * @param  aRowIndex    [in] row index
-   * @param  aColumn      [in] column object
-   * @param  aPseudoElm   [in] pseudo elemenet inside the cell, see
-   *                       nsITreeBoxObject for available values
-   */
-  static void DispatchClickEvent(nsITreeBoxObject *aTreeBoxObj,
-                                 PRInt32 aRowIndex, nsITreeColumn *aColumn,
-                                 const nsCString& aPseudoElt = EmptyCString());
-
-  /**
-   * Send mouse event to the given element.
-   *
-   * @param  aEventType  [in] an event type (see nsGUIEvent.h for constants)
-   * @param  aPresShell  [in] the presshell for the given element
-   * @param  aContent    [in] the element
-   */
-  static PRBool DispatchMouseEvent(PRUint32 aEventType,
-                                   nsIPresShell *aPresShell,
-                                   nsIContent *aContent);
-
-  /**
-   * Send mouse event to the given element.
-   *
-   * @param aEventType   [in] an event type (see nsGUIEvent.h for constants)
-   * @param aX           [in] x coordinate in dev pixels
-   * @param aY           [in] y coordinate in dev pixels
-   * @param aContent     [in] the element
-   * @param aFrame       [in] frame of the element
-   * @param aPresShell   [in] the presshell for the element
-   * @param aRootWidget  [in] the root widget of the element
-   */
-  static void DispatchMouseEvent(PRUint32 aEventType, PRInt32 aX, PRInt32 aY,
-                                 nsIContent *aContent, nsIFrame *aFrame,
-                                 nsIPresShell *aPresShell,
-                                 nsIWidget *aRootWidget);
-
-  /**
-   * Return an accesskey registered on the given element by
-   * nsIEventStateManager or 0 if there is no registered accesskey.
-   *
-   * @param aContent - the given element.
-   */
-  static PRUint32 GetAccessKeyFor(nsIContent *aContent);
-
-  /**
-   * Return DOM element related with the given node, i.e.
-   * a) itself if it is DOM element
-   * b) parent element if it is text node
-   * c) body element if it is HTML document node
-   * d) document element if it is document node.
-   *
-   * @param aNode  [in] the given DOM node
-   */
-  static already_AddRefed<nsIDOMElement> GetDOMElementFor(nsIDOMNode *aNode);
-
-  /**
-   * Return DOM node for the given DOM point.
-   */
-  static already_AddRefed<nsIDOMNode> GetDOMNodeFromDOMPoint(nsIDOMNode *aNode,
-                                                             PRUint32 aOffset);
-  /**
-   * Return the nsIContent* to check for ARIA attributes on -- this may not
-   * always be the DOM node for the accessible. Specifically, for doc
-   * accessibles, it is not the document node, but either the root element or
-   * <body> in HTML. Similar with GetDOMElementFor() method.
-   *
-   * @param aDOMNode  DOM node for the accessible that may be affected by ARIA
-   * @return          the nsIContent which may have ARIA markup
-   */
-  static nsIContent *GetRoleContent(nsIDOMNode *aDOMNode);
+#ifndef _a11yGeneric_H_
+#define _a11yGeneric_H_
 
-  /**
-   * Is the first passed in node an ancestor of the second?
-   * Note: A node is not considered to be the ancestor of itself.
-   *
-   * @param  aPossibleAncestorNode   [in] node to test for ancestor-ness of
-   *                                   aPossibleDescendantNode
-   * @param  aPossibleDescendantNode [in] node to test for descendant-ness of
-   *                                   aPossibleAncestorNode
-   * @return PR_TRUE                  if aPossibleAncestorNode is an ancestor of
-   *                                   aPossibleDescendantNode
-   */
-   static PRBool IsAncestorOf(nsINode *aPossibleAncestorNode,
-                              nsINode *aPossibleDescendantNode);
-
-  /**
-   * Are the first node and the second siblings?
-   *
-   * @return PR_TRUE if aDOMNode1 and aDOMNode2 have same parent
-   */
-   static PRBool AreSiblings(nsINode *aNode1, nsINode *aNode2);
-
-  /**
-   * Helper method to scroll range into view, used for implementation of
-   * nsIAccessibleText::scrollSubstringTo().
-   *
-   * @param aFrame        the frame for accessible the range belongs to.
-   * @param aStartNode    start node of a range
-   * @param aStartOffset  an offset inside the start node
-   * @param aEndNode      end node of a range
-   * @param aEndOffset    an offset inside the end node
-   * @param aScrollType   the place a range should be scrolled to
-   */
-  static nsresult ScrollSubstringTo(nsIFrame *aFrame,
-                                    nsIDOMNode *aStartNode, PRInt32 aStartIndex,
-                                    nsIDOMNode *aEndNode, PRInt32 aEndIndex,
-                                    PRUint32 aScrollType);
-
-  /** Helper method to scroll range into view, used for implementation of
-   * nsIAccessibleText::scrollSubstringTo[Point]().
-   *
-   * @param aFrame        the frame for accessible the range belongs to.
-   * @param aStartNode    start node of a range
-   * @param aStartOffset  an offset inside the start node
-   * @param aEndNode      end node of a range
-   * @param aEndOffset    an offset inside the end node
-   * @param aVPercent     how to align vertically, specified in percents
-   * @param aHPercent     how to align horizontally, specified in percents
-   */
-  static nsresult ScrollSubstringTo(nsIFrame *aFrame,
-                                    nsIDOMNode *aStartNode, PRInt32 aStartIndex,
-                                    nsIDOMNode *aEndNode, PRInt32 aEndIndex,
-                                    PRInt16 aVPercent, PRInt16 aHPercent);
-
-  /**
-   * Scrolls the given frame to the point, used for implememntation of
-   * nsIAccessNode::scrollToPoint and nsIAccessibleText::scrollSubstringToPoint.
-   *
-   * @param aScrollableFrame  the scrollable frame
-   * @param aFrame            the frame to scroll
-   * @param aPoint            the point scroll to
-   */
-  static void ScrollFrameToPoint(nsIFrame *aScrollableFrame,
-                                 nsIFrame *aFrame, const nsIntPoint& aPoint);
-
-  /**
-   * Converts scroll type constant defined in nsIAccessibleScrollType to
-   * vertical and horizontal percents.
-   */
-  static void ConvertScrollTypeToPercents(PRUint32 aScrollType,
-                                          PRInt16 *aVPercent,
-                                          PRInt16 *aHPercent);
-
-  /**
-   * Returns coordinates relative screen for the top level window.
-   *
-   * @param aNode  the DOM node hosted in the window.
-   */
-  static nsIntPoint GetScreenCoordsForWindow(nsIDOMNode *aNode);
-
-  /**
-   * Return document shell tree item for the given DOM node.
-   */
-  static already_AddRefed<nsIDocShellTreeItem>
-    GetDocShellTreeItemFor(nsIDOMNode *aNode);
-
-  /**
-   * Retrun frame for the given DOM element.
-   */
-  static nsIFrame* GetFrameFor(nsIDOMElement *aElm);
-
-  /**
-   * Retrun true if the type of given frame equals to the given frame type.
-   *
-   * @param aFrame  the frame
-   * @param aAtom   the frame type
-   */
-  static PRBool IsCorrectFrameType(nsIFrame* aFrame, nsIAtom* aAtom);
-
-  /**
-   * Return presShell for the document containing the given DOM node.
-   */
-  static already_AddRefed<nsIPresShell> GetPresShellFor(nsIDOMNode *aNode);
-
-  /**
-   * Return document node for the given document shell tree item.
-   */
-  static already_AddRefed<nsIDOMNode>
-    GetDOMNodeForContainer(nsIDocShellTreeItem *aContainer);
+#include "nsThreadUtils.h"
 
-  /**
-   * Get the ID for an element, in some types of XML this may not be the ID attribute
-   * @param aContent  Node to get the ID for
-   * @param aID       Where to put ID string
-   * @return          PR_TRUE if there is an ID set for this node
-   */
-  static PRBool GetID(nsIContent *aContent, nsAString& aID);
-
-  /**
-   * Convert attribute value of the given node to positive integer. If no
-   * attribute or wrong value then false is returned.
-   */
-  static PRBool GetUIntAttr(nsIContent *aContent, nsIAtom *aAttr,
-                            PRInt32 *aUInt);
-
-  /**
-   * Check if the given element is XLink.
-   *
-   * @param aContent  the given element
-   * @return          PR_TRUE if the given element is XLink
-   */
-  static PRBool IsXLink(nsIContent *aContent);
-
-  /**
-   * Returns language for the given node.
-   *
-   * @param aContent     [in] the given node
-   * @param aRootContent [in] container of the given node
-   * @param aLanguage    [out] language
-   */
-  static void GetLanguageFor(nsIContent *aContent, nsIContent *aRootContent,
-                             nsAString& aLanguage);
-
-  /**
-   * Return the array of elements the given node is referred to by its
-   * IDRefs attribute.
-   *
-   * @param aContent     [in] the given node
-   * @param aAttr        [in] IDRefs attribute on the given node
-   * @param aRefElements [out] result array of elements
-   */
-  static void GetElementsByIDRefsAttr(nsIContent *aContent, nsIAtom *aAttr,
-                                      nsIArray **aRefElements);
-
-  /**
-   * Return the array of elements having IDRefs that points to the given node.
-   *
-   * @param  aRootContent  [in] root element to search inside
-   * @param  aContent      [in] an element having ID attribute
-   * @param  aIDRefsAttr   [in] IDRefs attribute
-   * @param  aElements     [out] result array of elements
-   */
-  static void GetElementsHavingIDRefsAttr(nsIContent *aRootContent,
-                                          nsIContent *aContent,
-                                          nsIAtom *aIDRefsAttr,
-                                          nsIArray **aElements);
-
-  /**
-   * Helper method for GetElementsHavingIDRefsAttr.
-   */
-  static void GetElementsHavingIDRefsAttrImpl(nsIContent *aRootContent,
-                                              nsCString& aIdWithSpaces,
-                                              nsIAtom *aIDRefsAttr,
-                                              nsIMutableArray *aElements);
-
-  /**
-   * Return computed styles declaration for the given node.
-   */
-  static void GetComputedStyleDeclaration(const nsAString& aPseudoElt,
-                                          nsIDOMNode *aNode,
-                                          nsIDOMCSSStyleDeclaration **aCssDecl);
-
-  /**
-   * Search element in neighborhood of the given element by tag name and
-   * attribute value that equals to ID attribute of the given element.
-   * ID attribute can be either 'id' attribute or 'anonid' if the element is
-   * anonymous.
-   * The first matched content will be returned.
-   *
-   * @param aForNode - the given element the search is performed for
-   * @param aRelationAttrs - an array of attributes, element is attribute name of searched element, ignored if aAriaProperty passed in
-   * @param aAttrNum - how many attributes in aRelationAttrs
-   * @param aTagName - tag name of searched element, or nsnull for any -- ignored if aAriaProperty passed in
-   * @param aAncestorLevelsToSearch - points how is the neighborhood of the
-   *                                  given element big.
-   */
-  static nsIContent *FindNeighbourPointingToNode(nsIContent *aForNode,
-                                                 nsIAtom **aRelationAttrs, 
-                                                 PRUint32 aAttrNum,
-                                                 nsIAtom *aTagName = nsnull,
-                                                 PRUint32 aAncestorLevelsToSearch = 5);
-
-  /**
-   * Overloaded version of FindNeighbourPointingToNode to accept only one
-   * relation attribute.
-   */
-  static nsIContent *FindNeighbourPointingToNode(nsIContent *aForNode,
-                                                 nsIAtom *aRelationAttr, 
-                                                 nsIAtom *aTagName = nsnull,
-                                                 PRUint32 aAncestorLevelsToSearch = 5);
+// What we want is: NS_INTERFACE_MAP_ENTRY(self) for static IID accessors,
+// but some of our classes have an ambiguous base class of nsISupports which
+// prevents this from working (the default macro converts it to nsISupports,
+// then addrefs it, then returns it). Therefore, we expand the macro here and
+// change it so that it works. Yuck.
+#define NS_INTERFACE_MAP_STATIC_AMBIGUOUS(_class)                              \
+  if (aIID.Equals(NS_GET_IID(_class))) {                                       \
+    NS_ADDREF(this);                                                           \
+    *aInstancePtr = this;                                                      \
+    return NS_OK;                                                              \
+  } else
 
-  /**
-   * Search for element that satisfies the requirements in subtree of the given
-   * element. The requirements are tag name, attribute name and value of
-   * attribute.
-   * The first matched content will be returned.
-   *
-   * @param aId - value of searched attribute
-   * @param aLookContent - element that search is performed inside
-   * @param aRelationAttrs - an array of searched attributes
-   * @param aAttrNum - how many attributes in aRelationAttrs
-   * @param                 if both aAriaProperty and aRelationAttrs are null, then any element with aTagType will do
-   * @param aExcludeContent - element that is skiped for search
-   * @param aTagType - tag name of searched element, by default it is 'label' --
-   *                   ignored if aAriaProperty passed in
-   */
-  static nsIContent *FindDescendantPointingToID(const nsString *aId,
-                                                nsIContent *aLookContent,
-                                                nsIAtom **aRelationAttrs,
-                                                PRUint32 aAttrNum = 1,
-                                                nsIContent *aExcludeContent = nsnull,
-                                                nsIAtom *aTagType = nsAccessibilityAtoms::label);
-
-  /**
-   * Overloaded version of FindDescendantPointingToID to accept only one
-   * relation attribute.
-   */
-  static nsIContent *FindDescendantPointingToID(const nsString *aId,
-                                                nsIContent *aLookContent,
-                                                nsIAtom *aRelationAttr,
-                                                nsIContent *aExcludeContent = nsnull,
-                                                nsIAtom *aTagType = nsAccessibilityAtoms::label);
-
-  // Helper for FindDescendantPointingToID(), same args
-  static nsIContent *FindDescendantPointingToIDImpl(nsCString& aIdWithSpaces,
-                                                    nsIContent *aLookContent,
-                                                    nsIAtom **aRelationAttrs,
-                                                    PRUint32 aAttrNum = 1,
-                                                    nsIContent *aExcludeContent = nsnull,
-                                                    nsIAtom *aTagType = nsAccessibilityAtoms::label);
-
-  /**
-   * Return the label element for the given DOM element.
-   */
-  static nsIContent *GetLabelContent(nsIContent *aForNode);
-
-  /**
-   * Return the HTML label element for the given HTML element.
-   */
-  static nsIContent *GetHTMLLabelContent(nsIContent *aForNode);
-
-  /**
-   * Return box object for XUL treechildren element by tree box object.
-   */
-  static already_AddRefed<nsIBoxObject>
-    GetTreeBodyBoxObject(nsITreeBoxObject *aTreeBoxObj);
+#define NS_OK_DEFUNCT_OBJECT                                                   \
+  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x22)
 
-  /**
-   * Return tree box object from any levels DOMNode under the XUL tree.
-   */
-  static void
-    GetTreeBoxObject(nsIDOMNode* aDOMNode, nsITreeBoxObject** aBoxObject);
-
-  /**
-   * Return first sensible column for the given tree box object.
-   */
-  static already_AddRefed<nsITreeColumn>
-    GetFirstSensibleColumn(nsITreeBoxObject *aTree);
-
-  /**
-   * Return last sensible column for the given tree box object.
-   */
-  static already_AddRefed<nsITreeColumn>
-    GetLastSensibleColumn(nsITreeBoxObject *aTree);
-
-  /**
-   * Return sensible columns count for the given tree box object.
-   */
-  static PRUint32 GetSensibleColumnCount(nsITreeBoxObject *aTree);
-
-  /**
-   * Return sensible column at the given index for the given tree box object.
-   */
-  static already_AddRefed<nsITreeColumn>
-    GetSensibleColumnAt(nsITreeBoxObject *aTree, PRUint32 aIndex);
+#define NS_ENSURE_A11Y_SUCCESS(res, ret)                                       \
+  PR_BEGIN_MACRO                                                               \
+    nsresult __rv = res; /* Don't evaluate |res| more than once */             \
+    if (NS_FAILED(__rv)) {                                                     \
+      NS_ENSURE_SUCCESS_BODY(res, ret)                                         \
+      return ret;                                                              \
+    }                                                                          \
+    if (__rv == NS_OK_DEFUNCT_OBJECT)                                          \
+      return ret;                                                              \
+  PR_END_MACRO
 
-  /**
-   * Return next sensible column for the given column.
-   */
-  static already_AddRefed<nsITreeColumn>
-    GetNextSensibleColumn(nsITreeColumn *aColumn);
-
-  /**
-   * Return previous sensible column for the given column.
-   */
-  static already_AddRefed<nsITreeColumn>
-    GetPreviousSensibleColumn(nsITreeColumn *aColumn);
-
-  /**
-   * Return true if the given column is hidden (i.e. not sensible).
-   */
-  static PRBool IsColumnHidden(nsITreeColumn *aColumn);
-
-  /**
-   * Return true if the given node is table header element.
-   */
-  static PRBool IsHTMLTableHeader(nsIContent *aContent)
-  {
-    return aContent->NodeInfo()->Equals(nsAccessibilityAtoms::th) ||
-      aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::scope);
-  }
-
-  /**
-   * Generates frames for popup subtree.
-   *
-   * @param aNode    [in] DOM node containing the menupopup element as a child
-   * @param aIsAnon  [in] specifies whether popup should be searched inside of
-   *                  anonymous or explicit content
-   */
-  static void GeneratePopupTree(nsIDOMNode *aNode, PRBool aIsAnon = PR_FALSE);
-};
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsRunnable helpers
 ////////////////////////////////////////////////////////////////////////////////
 
 /**
  * Use NS_DECL_RUNNABLEMETHOD_ macros to declare a runnable class for the given
  * method of the given class. There are three macros:
@@ -591,9 +191,8 @@ public:                                 
 {                                                                              \
   nsCOMPtr<nsIRunnable> runnable =                                             \
     new nsRunnableMethod_##Method(Obj, Arg1, Arg2);                            \
   if (runnable)                                                                \
     NS_DispatchToMainThread(runnable);                                         \
 }
 
 #endif
-
--- a/accessible/src/base/nsARIAGridAccessible.cpp
+++ b/accessible/src/base/nsARIAGridAccessible.cpp
@@ -33,16 +33,19 @@
  * 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 ***** */
 
 #include "nsARIAGridAccessible.h"
 
+#include "nsAccUtils.h"
+
+#include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsARIAGridAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/accessible/src/base/nsAccCache.h
+++ b/accessible/src/base/nsAccCache.h
@@ -37,25 +37,21 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsAccCache_H_
 #define _nsAccCache_H_
 
 #include "nsRefPtrHashtable.h"
 #include "nsCycleCollectionParticipant.h"
 
-class nsAccessNode;
-class nsAccessible;
 class nsIAccessNode;
 
-typedef nsRefPtrHashtable<nsVoidPtrHashKey, nsAccessNode>
-  nsAccessNodeHashtable;
-
-typedef nsRefPtrHashtable<nsVoidPtrHashKey, nsAccessible>
-  nsAccessibleHashtable;
+////////////////////////////////////////////////////////////////////////////////
+// Accessible cache utils
+////////////////////////////////////////////////////////////////////////////////
 
 /**
  * Shutdown and removes the accessible from cache.
  */
 template <class T>
 static PLDHashOperator
 ClearCacheEntry(const void* aKey, nsRefPtr<T>& aAccessNode, void* aUserArg)
 {
--- a/accessible/src/base/nsAccEvent.cpp
+++ b/accessible/src/base/nsAccEvent.cpp
@@ -33,28 +33,32 @@
  * 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 ***** */
 
 #include "nsAccEvent.h"
 
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
 #include "nsApplicationAccessibleWrap.h"
 #include "nsDocAccessible.h"
+#include "nsIAccessibleText.h"
+#ifdef MOZ_XUL
+#include "nsXULTreeAccessible.h"
+#endif
 
 #include "nsIDOMDocument.h"
 #include "nsIEventStateManager.h"
 #include "nsIPersistentProperties2.h"
 #include "nsIServiceManager.h"
 #ifdef MOZ_XUL
 #include "nsIDOMXULMultSelectCntrlEl.h"
-#include "nsXULTreeAccessible.h"
 #endif
-#include "nsIAccessibleText.h"
 #include "nsIContent.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccEvent
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -188,25 +192,20 @@ nsAccEvent::GetDocAccessible()
 // nsAccEvent: protected methods
 
 already_AddRefed<nsIAccessible>
 nsAccEvent::GetAccessibleByNode()
 {
   if (!mNode)
     return nsnull;
 
-  nsCOMPtr<nsIAccessibilityService> accService = 
-    do_GetService("@mozilla.org/accessibilityService;1");
-  if (!accService)
-    return nsnull;
-
   nsCOMPtr<nsIDOMNode> DOMNode(do_QueryInterface(mNode));
 
   nsCOMPtr<nsIAccessible> accessible;
-  accService->GetAccessibleFor(DOMNode, getter_AddRefs(accessible));
+  GetAccService()->GetAccessibleFor(DOMNode, getter_AddRefs(accessible));
 
 #ifdef MOZ_XUL
   // hack for xul tree table. We need a better way for firing delayed event
   // against xul tree table. see bug 386821.
   // There will be problem if some day we want to fire delayed event against
   // the xul tree itself or an unselected treeitem.
   nsCOMPtr<nsIContent> content(do_QueryInterface(mNode));
   if (content && content->NodeInfo()->Equals(nsAccessibilityAtoms::tree,
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -37,23 +37,24 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsCoreUtils.h"
 #include "nsAccUtils.h"
 
 #include "nsIAccessibleStates.h"
 #include "nsIAccessibleTypes.h"
 
+#include "nsAccessibilityService.h"
+#include "nsAccessibilityAtoms.h"
+#include "nsAccessible.h"
+#include "nsAccTreeWalker.h"
+#include "nsARIAMap.h"
+#include "nsDocAccessible.h"
 #include "nsHyperTextAccessible.h"
 #include "nsHTMLTableAccessible.h"
-#include "nsDocAccessible.h"
-#include "nsAccessibilityAtoms.h"
-#include "nsAccTreeWalker.h"
-#include "nsAccessible.h"
-#include "nsARIAMap.h"
 #include "nsXULTreeGridAccessible.h"
 
 #include "nsIDOMXULContainerElement.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsWhitespaceTokenizer.h"
 #include "nsComponentManagerUtils.h"
 
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -32,26 +32,31 @@
  * 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 ***** */
 
 #include "nsDocAccessible.h"
+
 #include "nsIAccessible.h"
+
+#include "nsAccCache.h"
 #include "nsAccessibilityAtoms.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
+
 #include "nsHashtable.h"
 #include "nsAccessibilityService.h"
 #include "nsApplicationAccessibleWrap.h"
 #include "nsIAccessibleDocument.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
-#include "nsIDOMCSSStyleDeclaration.h"
 #include "nsIDOMCSSPrimitiveValue.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsIDOMNSDocument.h"
 #include "nsIDOMNSHTMLElement.h"
 #include "nsIDOMWindow.h"
--- a/accessible/src/base/nsAccessNode.h
+++ b/accessible/src/base/nsAccessNode.h
@@ -38,68 +38,45 @@
 
 /* For documentation of the accessibility architecture, 
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 #ifndef _nsAccessNode_H_
 #define _nsAccessNode_H_
 
-#include "nsAccCache.h"
-#include "nsAccessibilityAtoms.h"
-#include "nsCoreUtils.h"
-#include "nsAccUtils.h"
+#include "nsIAccessNode.h"
+#include "nsIAccessibleTypes.h"
 
-#include "nsIAccessibleTypes.h"
-#include "nsIAccessNode.h"
+#include "a11yGeneric.h"
+
 #include "nsIContent.h"
 #include "nsIDOMNode.h"
 #include "nsINameSpaceManager.h"
 #include "nsIStringBundle.h"
+#include "nsRefPtrHashtable.h"
 #include "nsWeakReference.h"
-#include "nsAccessibilityService.h"
+
+class nsAccessNode;
+class nsApplicationAccessible;
+class nsDocAccessible;
+class nsIAccessibleDocument;
+class nsRootAccessible;
 
 class nsIPresShell;
 class nsPresContext;
-class nsIAccessibleDocument;
 class nsIFrame;
-class nsIDOMNodeList;
-class nsRootAccessible;
-class nsApplicationAccessible;
 class nsIDocShellTreeItem;
 
+typedef nsRefPtrHashtable<nsVoidPtrHashKey, nsAccessNode>
+  nsAccessNodeHashtable;
+
 #define ACCESSIBLE_BUNDLE_URL "chrome://global-platform/locale/accessible.properties"
 #define PLATFORM_KEYS_BUNDLE_URL "chrome://global-platform/locale/platformKeys.properties"
 
-// What we want is: NS_INTERFACE_MAP_ENTRY(self) for static IID accessors,
-// but some of our classes have an ambiguous base class of nsISupports which
-// prevents this from working (the default macro converts it to nsISupports,
-// then addrefs it, then returns it). Therefore, we expand the macro here and
-// change it so that it works. Yuck.
-#define NS_INTERFACE_MAP_STATIC_AMBIGUOUS(_class) \
-  if (aIID.Equals(NS_GET_IID(_class))) { \
-  NS_ADDREF(this); \
-  *aInstancePtr = this; \
-  return NS_OK; \
-  } else
-
-#define NS_OK_DEFUNCT_OBJECT \
-NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x22)
-
-#define NS_ENSURE_A11Y_SUCCESS(res, ret)                                  \
-  PR_BEGIN_MACRO                                                          \
-    nsresult __rv = res; /* Don't evaluate |res| more than once */        \
-    if (NS_FAILED(__rv)) {                                                \
-      NS_ENSURE_SUCCESS_BODY(res, ret)                                    \
-      return ret;                                                         \
-    }                                                                     \
-    if (__rv == NS_OK_DEFUNCT_OBJECT)                                     \
-      return ret;                                                         \
-  PR_END_MACRO
-
 #define NS_ACCESSNODE_IMPL_CID                          \
 {  /* 2b07e3d7-00b3-4379-aa0b-ea22e2c8ffda */           \
   0x2b07e3d7,                                           \
   0x00b3,                                               \
   0x4379,                                               \
   { 0xaa, 0x0b, 0xea, 0x22, 0xe2, 0xc8, 0xff, 0xda }    \
 }
 
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -248,43 +248,55 @@ nsAccessibilityService::ProcessDocLoadEv
   GetAccessibleFor(docNode, getter_AddRefs(accessible));
   nsRefPtr<nsDocAccessible> docAcc = do_QueryObject(accessible);
   NS_ENSURE_TRUE(docAcc,);
 
   docAcc->FireDocLoadEvents(aEventType);
 }
 
 // nsIAccessibilityService
-nsresult
+void
 nsAccessibilityService::NotifyOfAnchorJumpTo(nsIContent *aTarget)
 {
+  nsIDocument *document = aTarget->GetCurrentDoc();
+  nsCOMPtr<nsIDOMNode> documentNode(do_QueryInterface(document));
+  if (!documentNode)
+    return;
+
   nsCOMPtr<nsIDOMNode> targetNode(do_QueryInterface(aTarget));
 
   nsCOMPtr<nsIAccessible> targetAcc;
   GetAccessibleFor(targetNode, getter_AddRefs(targetAcc));
 
+  // Getting the targetAcc above will have ensured accessible doc creation.
+  // XXX Bug 561683
+  nsRefPtr<nsDocAccessible> accessibleDoc =
+    nsAccessNode::GetDocAccessibleFor(documentNode);
+  if (!accessibleDoc)
+    return;
+
   // If the jump target is not accessible then fire an event for nearest
   // accessible in parent chain.
   if (!targetAcc) {
-    nsIDocument *document = aTarget->GetCurrentDoc();
-    nsCOMPtr<nsIDOMNode> documentNode(do_QueryInterface(document));
-    if (documentNode) {
-      nsCOMPtr<nsIAccessibleDocument> accessibleDoc =
-        nsAccessNode::GetDocAccessibleFor(documentNode);
-      if (accessibleDoc)
         accessibleDoc->GetAccessibleInParentChain(targetNode, PR_TRUE,
                                                   getter_AddRefs(targetAcc));
-    }
+        nsCOMPtr<nsIAccessNode> accNode = do_QueryInterface(targetAcc);
+        accNode->GetDOMNode(getter_AddRefs(targetNode));
   }
 
-  if (targetAcc)
-    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SCROLLING_START,
-                            targetAcc);
+  NS_ASSERTION(targetNode,
+      "No accessible in parent chain!? Expect at least a document accessible.");
+  if (!targetNode)
+    return;
 
-  return NS_OK;
+  // XXX note in rare cases the node could go away before we flush the queue,
+  // for example if the node becomes inaccessible, or is removed from the DOM.
+  accessibleDoc->FireDelayedAccessibleEvent(
+                     nsIAccessibleEvent::EVENT_SCROLLING_START,
+                     targetNode);
 }
 
 // nsIAccessibilityService
 nsresult
 nsAccessibilityService::FireAccessibleEvent(PRUint32 aEvent,
                                             nsIAccessible *aTarget)
 {
   nsEventShell::FireEvent(aEvent, aTarget);
--- a/accessible/src/base/nsAccessibilityService.h
+++ b/accessible/src/base/nsAccessibilityService.h
@@ -36,16 +36,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef __nsAccessibilityService_h__
 #define __nsAccessibilityService_h__
 
 #include "nsIAccessibilityService.h"
 
+#include "a11yGeneric.h"
 #include "nsCoreUtils.h"
 
 #include "nsCOMArray.h"
 #include "nsIObserver.h"
 #include "nsIWebProgress.h"
 #include "nsIWebProgressListener.h"
 #include "nsWeakReference.h"
 
@@ -131,17 +132,17 @@ public:
   virtual nsresult AddNativeRootAccessible(void *aAtkAccessible,
                                            nsIAccessible **aAccessible);
   virtual nsresult RemoveNativeRootAccessible(nsIAccessible *aRootAccessible);
 
   virtual nsresult InvalidateSubtreeFor(nsIPresShell *aPresShell,
                                         nsIContent *aContent,
                                         PRUint32 aChangeType);
 
-  virtual nsresult NotifyOfAnchorJumpTo(nsIContent *aTarget);
+  virtual void NotifyOfAnchorJumpTo(nsIContent *aTarget);
 
   virtual nsresult FireAccessibleEvent(PRUint32 aEvent, nsIAccessible *aTarget);
 
   // nsAccessibiltiyService
 
   /**
    * Return presentation shell for the given node.
    *
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -36,19 +36,25 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsAccessible.h"
 
 #include "nsIXBLAccessible.h"
 
+#include "nsAccUtils.h"
+#include "nsARIAMap.h"
+#include "nsDocAccessible.h"
+#include "nsEventShell.h"
+
+#include "nsAccessibilityService.h"
 #include "nsAccTreeWalker.h"
-#include "nsAccessibleRelation.h"
-#include "nsDocAccessible.h"
+#include "nsRelUtils.h"
+#include "nsTextEquivUtils.h"
 
 #include "nsIDOMElement.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsIDOMDocumentTraversal.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIDOMNodeFilter.h"
@@ -90,60 +96,16 @@
 #include "nsWhitespaceTokenizer.h"
 #include "nsAttrName.h"
 #include "nsNetUtil.h"
 
 #ifdef NS_DEBUG
 #include "nsIDOMCharacterData.h"
 #endif
 
-/**
- * nsAccessibleDOMStringList implementation
- */
-nsAccessibleDOMStringList::nsAccessibleDOMStringList()
-{
-}
-
-nsAccessibleDOMStringList::~nsAccessibleDOMStringList()
-{
-}
-
-NS_IMPL_ISUPPORTS1(nsAccessibleDOMStringList, nsIDOMDOMStringList)
-
-NS_IMETHODIMP
-nsAccessibleDOMStringList::Item(PRUint32 aIndex, nsAString& aResult)
-{
-  if (aIndex >= mNames.Length()) {
-    SetDOMStringToNull(aResult);
-  } else {
-    aResult = mNames.ElementAt(aIndex);
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsAccessibleDOMStringList::GetLength(PRUint32 *aLength)
-{
-  *aLength = mNames.Length();
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsAccessibleDOMStringList::Contains(const nsAString& aString, PRBool *aResult)
-{
-  *aResult = mNames.Contains(aString);
-
-  return NS_OK;
-}
-
-/*
- * Class nsAccessible
- */
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessible. nsISupports
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsAccessible)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsAccessible, nsAccessNode)
   NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mParent");
@@ -819,22 +781,18 @@ nsAccessible::GetStateInternal(PRUint32 
   /* readonly attribute boolean focusedChild; */
 NS_IMETHODIMP nsAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
 { 
   nsCOMPtr<nsIAccessible> focusedChild;
   if (gLastFocusedNode == mDOMNode) {
     focusedChild = this;
   }
   else if (gLastFocusedNode) {
-    nsCOMPtr<nsIAccessibilityService> accService =
-      do_GetService("@mozilla.org/accessibilityService;1");
-    NS_ENSURE_TRUE(accService, NS_ERROR_FAILURE);
-
-    accService->GetAccessibleFor(gLastFocusedNode,
-                                 getter_AddRefs(focusedChild));
+    GetAccService()->GetAccessibleFor(gLastFocusedNode,
+                                      getter_AddRefs(focusedChild));
     if (focusedChild) {
       nsCOMPtr<nsIAccessible> focusedParentAccessible;
       focusedChild->GetParent(getter_AddRefs(focusedParentAccessible));
       if (focusedParentAccessible != this) {
         focusedChild = nsnull;
       }
     }
   }
@@ -886,27 +844,27 @@ nsAccessible::GetChildAtPoint(PRInt32 aX
 
   nsIContent* content = nsnull;
   if (!foundFrame || !(content = foundFrame->GetContent())) {
     NS_IF_ADDREF(*aChild = fallbackAnswer);
     return NS_OK;
   }
 
   nsCOMPtr<nsIDOMNode> node(do_QueryInterface(content));
-  nsCOMPtr<nsIAccessibilityService> accService = GetAccService();
 
   nsCOMPtr<nsIDOMNode> relevantNode;
-  accService->GetRelevantContentNodeFor(node, getter_AddRefs(relevantNode));
+  GetAccService()->GetRelevantContentNodeFor(node,
+                                             getter_AddRefs(relevantNode));
   if (!relevantNode) {
     NS_IF_ADDREF(*aChild = fallbackAnswer);
     return NS_OK;
   }
 
   nsCOMPtr<nsIAccessible> accessible;
-  accService->GetAccessibleFor(relevantNode, getter_AddRefs(accessible));
+  GetAccService()->GetAccessibleFor(relevantNode, getter_AddRefs(accessible));
   if (!accessible) {
     // No accessible for the node with the point, so find the first
     // accessible in the DOM parent chain
     accDocument->GetAccessibleInParentChain(relevantNode, PR_TRUE,
                                             getter_AddRefs(accessible));
     if (!accessible) {
       NS_IF_ADDREF(*aChild = fallbackAnswer);
       return NS_OK;
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -36,78 +36,53 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsAccessible_H_
 #define _nsAccessible_H_
 
 #include "nsAccessNodeWrap.h"
 
-#include "nsARIAMap.h"
-#include "nsEventShell.h"
-#include "nsRelUtils.h"
-#include "nsTextEquivUtils.h"
-
 #include "nsIAccessible.h"
 #include "nsIAccessibleHyperLink.h"
 #include "nsIAccessibleSelectable.h"
 #include "nsIAccessibleValue.h"
 #include "nsIAccessibleRole.h"
 #include "nsIAccessibleStates.h"
-#include "nsIAccessibleEvent.h"
+
+#include "nsStringGlue.h"
+#include "nsTArray.h"
 
-#include "nsIDOMNodeList.h"
-#include "nsINameSpaceManager.h"
-#include "nsWeakReference.h"
-#include "nsString.h"
-#include "nsTArray.h"
-#include "nsIDOMDOMStringList.h"
+class nsAccessible;
+class nsAccEvent;
+struct nsRoleMapEntry;
 
 struct nsRect;
 class nsIContent;
 class nsIFrame;
-class nsIDOMNode;
 class nsIAtom;
 class nsIView;
 
+typedef nsRefPtrHashtable<nsVoidPtrHashKey, nsAccessible>
+  nsAccessibleHashtable;
+
 // see nsAccessible::GetAttrValue
 #define NS_OK_NO_ARIA_VALUE \
 NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x21)
 
 // see nsAccessible::GetNameInternal
 #define NS_OK_EMPTY_NAME \
 NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x23)
 
 // see nsAccessible::GetNameInternal
 #define NS_OK_NAME_FROM_TOOLTIP \
 NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x25)
 
-// Saves a data member -- if child count equals this value we haven't
-// cached children or child count yet
-enum { eChildCountUninitialized = -1 };
 
-class nsAccessibleDOMStringList : public nsIDOMDOMStringList
-{
-public:
-  nsAccessibleDOMStringList();
-  virtual ~nsAccessibleDOMStringList();
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIDOMDOMSTRINGLIST
-
-  PRBool Add(const nsAString& aName) {
-    return mNames.AppendElement(aName) != nsnull;
-  }
-
-private:
-  nsTArray<nsString> mNames;
-};
-
-
-#define NS_ACCESSIBLE_IMPL_CID                          \
+#define NS_ACCESSIBLE_IMPL_IID                          \
 {  /* 133c8bf4-4913-4355-bd50-426bd1d6e1ad */           \
   0x133c8bf4,                                           \
   0x4913,                                               \
   0x4355,                                               \
   { 0xbd, 0x50, 0x42, 0x6b, 0xd1, 0xd6, 0xe1, 0xad }    \
 }
 
 class nsAccessible : public nsAccessNodeWrap, 
@@ -122,17 +97,17 @@ public:
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsAccessible, nsAccessNode)
 
   NS_DECL_NSIACCESSIBLE
   NS_DECL_NSIACCESSIBLEHYPERLINK
   NS_DECL_NSIACCESSIBLESELECTABLE
   NS_DECL_NSIACCESSIBLEVALUE
-  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ACCESSIBLE_IMPL_CID)
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ACCESSIBLE_IMPL_IID)
 
   //////////////////////////////////////////////////////////////////////////////
   // nsAccessNode
 
   virtual nsresult Shutdown();
 
   //////////////////////////////////////////////////////////////////////////////
   // Public methods
@@ -436,12 +411,12 @@ protected:
   nsRefPtr<nsAccessible> mParent;
   nsTArray<nsRefPtr<nsAccessible> > mChildren;
   PRBool mAreChildrenInitialized;
 
   nsRoleMapEntry *mRoleMapEntry; // Non-null indicates author-supplied role; possibly state & value as well
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsAccessible,
-                              NS_ACCESSIBLE_IMPL_CID)
+                              NS_ACCESSIBLE_IMPL_IID)
 
 #endif  
 
--- a/accessible/src/base/nsApplicationAccessible.cpp
+++ b/accessible/src/base/nsApplicationAccessible.cpp
@@ -38,16 +38,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 "nsApplicationAccessible.h"
 
 #include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
 
 #include "nsIComponentManager.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIWindowMediator.h"
 #include "nsServiceManagerUtils.h"
 
 nsApplicationAccessible::nsApplicationAccessible() :
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -33,28 +33,28 @@
  * 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 ***** */
 
 #include "nsBaseWidgetAccessible.h"
+
 #include "nsAccessibilityAtoms.h"
-#include "nsIAccessibilityService.h"
-#include "nsIAccessibleDocument.h"
-#include "nsAccessibleWrap.h"
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
 #include "nsCoreUtils.h"
+#include "nsHyperTextAccessibleWrap.h"
+
 #include "nsIDOMNSHTMLElement.h"
 #include "nsGUIEvent.h"
-#include "nsHyperTextAccessibleWrap.h"
 #include "nsILink.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
-#include "nsIServiceManager.h"
 #include "nsIURI.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsLeafAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsLeafAccessible::nsLeafAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell):
 nsAccessibleWrap(aNode, aShell)
--- a/accessible/src/base/nsCaretAccessible.cpp
+++ b/accessible/src/base/nsCaretAccessible.cpp
@@ -30,20 +30,23 @@
  * 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 ***** */
 
-// NOTE: alphabetically ordered
+#include "nsCaretAccessible.h"
+
 #include "nsAccessibilityService.h"
-#include "nsCaretAccessible.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
 #include "nsIAccessibleEvent.h"
+
 #include "nsCaret.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMHTMLAnchorElement.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsIFrame.h"
 #include "nsIPresShell.h"
 #include "nsRootAccessible.h"
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -69,16 +69,20 @@
 #include "nsIView.h"
 
 #include "nsContentCID.h"
 #include "nsComponentManagerUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
 
 static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
+////////////////////////////////////////////////////////////////////////////////
+// nsCoreUtils
+////////////////////////////////////////////////////////////////////////////////
+
 PRBool
 nsCoreUtils::HasClickListener(nsIContent *aContent)
 {
   NS_ENSURE_TRUE(aContent, PR_FALSE);
   nsIEventListenerManager* listenerManager =
     aContent->GetListenerManager(PR_FALSE);
 
   return listenerManager &&
@@ -1145,8 +1149,42 @@ nsCoreUtils::GeneratePopupTree(nsIDOMNod
                                        eCaseMatters)) {
 
       child->SetAttr(kNameSpaceID_None, nsAccessibilityAtoms::menugenerated,
                      NS_LITERAL_STRING("true"), PR_TRUE);
       return;
     }
   }
 }
+
+
+////////////////////////////////////////////////////////////////////////////////
+// nsAccessibleDOMStringList
+////////////////////////////////////////////////////////////////////////////////
+
+NS_IMPL_ISUPPORTS1(nsAccessibleDOMStringList, nsIDOMDOMStringList)
+
+NS_IMETHODIMP
+nsAccessibleDOMStringList::Item(PRUint32 aIndex, nsAString& aResult)
+{
+  if (aIndex >= mNames.Length())
+    SetDOMStringToNull(aResult);
+  else
+    aResult = mNames.ElementAt(aIndex);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAccessibleDOMStringList::GetLength(PRUint32 *aLength)
+{
+  *aLength = mNames.Length();
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAccessibleDOMStringList::Contains(const nsAString& aString, PRBool *aResult)
+{
+  *aResult = mNames.Contains(aString);
+
+  return NS_OK;
+}
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/nsCoreUtils.h
@@ -44,20 +44,25 @@
 #include "nsIDOMNode.h"
 #include "nsIContent.h"
 #include "nsIBoxObject.h"
 #include "nsITreeBoxObject.h"
 #include "nsITreeColumns.h"
 
 #include "nsIFrame.h"
 #include "nsIDocShellTreeItem.h"
-#include "nsIArray.h"
+#include "nsIDOMCSSStyleDeclaration.h"
+#include "nsIDOMDOMStringList.h"
 #include "nsIMutableArray.h"
 #include "nsPoint.h"
+#include "nsTArray.h"
 
+/**
+ * Core utils.
+ */
 class nsCoreUtils
 {
 public:
   /**
    * Return true if the given node has registered click, mousedown or mouseup
    * event listeners.
    */
   static PRBool HasClickListener(nsIContent *aContent);
@@ -463,137 +468,31 @@ public:
    *
    * @param aNode    [in] DOM node containing the menupopup element as a child
    * @param aIsAnon  [in] specifies whether popup should be searched inside of
    *                  anonymous or explicit content
    */
   static void GeneratePopupTree(nsIDOMNode *aNode, PRBool aIsAnon = PR_FALSE);
 };
 
-////////////////////////////////////////////////////////////////////////////////
-// nsRunnable helpers
-////////////////////////////////////////////////////////////////////////////////
 
 /**
- * Use NS_DECL_RUNNABLEMETHOD_ macros to declare a runnable class for the given
- * method of the given class. There are three macros:
- *  NS_DECL_RUNNABLEMETHOD(Class, Method)
- *  NS_DECL_RUNNABLEMETHOD_ARG1(Class, Method, Arg1Type)
- *  NS_DECL_RUNNABLEMETHOD_ARG2(Class, Method, Arg1Type, Arg2Type)
- * Note Arg1Type and Arg2Type must be types which keeps the objects alive.
- *
- * Use NS_DISPATCH_RUNNABLEMETHOD_ macros to create an instance of declared
- * runnable class and dispatch it to main thread. Availabe macros are:
- *  NS_DISPATCH_RUNNABLEMETHOD(Method, Object)
- *  NS_DISPATCH_RUNNABLEMETHOD_ARG1(Method, Object, Arg1)
- *  NS_DISPATCH_RUNNABLEMETHOD_ARG2(Method, Object, Arg1, Arg2)
+ * nsIDOMDOMStringList implementation.
  */
-
-#define NS_DECL_RUNNABLEMETHOD_HELPER(ClassType, Method)                       \
-  void Revoke()                                                                \
-  {                                                                            \
-    NS_IF_RELEASE(mObj);                                                       \
-  }                                                                            \
-                                                                               \
-protected:                                                                     \
-  virtual ~nsRunnableMethod_##Method()                                         \
-  {                                                                            \
-    NS_IF_RELEASE(mObj);                                                       \
-  }                                                                            \
-                                                                               \
-private:                                                                       \
-  ClassType *mObj;                                                             \
-
-
-#define NS_DECL_RUNNABLEMETHOD(ClassType, Method)                              \
-class nsRunnableMethod_##Method : public nsRunnable                            \
-{                                                                              \
-public:                                                                        \
-  nsRunnableMethod_##Method(ClassType *aObj) : mObj(aObj)                      \
-  {                                                                            \
-    NS_IF_ADDREF(mObj);                                                        \
-  }                                                                            \
-                                                                               \
-  NS_IMETHODIMP Run()                                                          \
-  {                                                                            \
-    if (!mObj)                                                                 \
-      return NS_OK;                                                            \
-    (mObj-> Method)();                                                         \
-    return NS_OK;                                                              \
-  }                                                                            \
-                                                                               \
-  NS_DECL_RUNNABLEMETHOD_HELPER(ClassType, Method)                             \
-                                                                               \
-};
+class nsAccessibleDOMStringList : public nsIDOMDOMStringList
+{
+public:
+  nsAccessibleDOMStringList() {};
+  virtual ~nsAccessibleDOMStringList() {};
 
-#define NS_DECL_RUNNABLEMETHOD_ARG1(ClassType, Method, Arg1Type)               \
-class nsRunnableMethod_##Method : public nsRunnable                            \
-{                                                                              \
-public:                                                                        \
-  nsRunnableMethod_##Method(ClassType *aObj, Arg1Type aArg1) :                 \
-    mObj(aObj), mArg1(aArg1)                                                   \
-  {                                                                            \
-    NS_IF_ADDREF(mObj);                                                        \
-  }                                                                            \
-                                                                               \
-  NS_IMETHODIMP Run()                                                          \
-  {                                                                            \
-    if (!mObj)                                                                 \
-      return NS_OK;                                                            \
-    (mObj-> Method)(mArg1);                                                    \
-    return NS_OK;                                                              \
-  }                                                                            \
-                                                                               \
-  NS_DECL_RUNNABLEMETHOD_HELPER(ClassType, Method)                             \
-  Arg1Type mArg1;                                                              \
-};
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSIDOMDOMSTRINGLIST
 
-#define NS_DECL_RUNNABLEMETHOD_ARG2(ClassType, Method, Arg1Type, Arg2Type)     \
-class nsRunnableMethod_##Method : public nsRunnable                            \
-{                                                                              \
-public:                                                                        \
-                                                                               \
-  nsRunnableMethod_##Method(ClassType *aObj,                                   \
-                            Arg1Type aArg1, Arg2Type aArg2) :                  \
-    mObj(aObj), mArg1(aArg1), mArg2(aArg2)                                     \
-  {                                                                            \
-    NS_IF_ADDREF(mObj);                                                        \
-  }                                                                            \
-                                                                               \
-  NS_IMETHODIMP Run()                                                          \
-  {                                                                            \
-    if (!mObj)                                                                 \
-      return NS_OK;                                                            \
-    (mObj-> Method)(mArg1, mArg2);                                             \
-    return NS_OK;                                                              \
-  }                                                                            \
-                                                                               \
-  NS_DECL_RUNNABLEMETHOD_HELPER(ClassType, Method)                             \
-  Arg1Type mArg1;                                                              \
-  Arg2Type mArg2;                                                              \
+  PRBool Add(const nsAString& aName) {
+    return mNames.AppendElement(aName) != nsnull;
+  }
+
+private:
+  nsTArray<nsString> mNames;
 };
 
-#define NS_DISPATCH_RUNNABLEMETHOD(Method, Obj)                                \
-{                                                                              \
-  nsCOMPtr<nsIRunnable> runnable =                                             \
-    new nsRunnableMethod_##Method(Obj);                                        \
-  if (runnable)                                                                \
-    NS_DispatchToMainThread(runnable);                                         \
-}
-
-#define NS_DISPATCH_RUNNABLEMETHOD_ARG1(Method, Obj, Arg1)                     \
-{                                                                              \
-  nsCOMPtr<nsIRunnable> runnable =                                             \
-    new nsRunnableMethod_##Method(Obj, Arg1);                                  \
-  if (runnable)                                                                \
-    NS_DispatchToMainThread(runnable);                                         \
-}
-
-#define NS_DISPATCH_RUNNABLEMETHOD_ARG2(Method, Obj, Arg1, Arg2)               \
-{                                                                              \
-  nsCOMPtr<nsIRunnable> runnable =                                             \
-    new nsRunnableMethod_##Method(Obj, Arg1, Arg2);                            \
-  if (runnable)                                                                \
-    NS_DispatchToMainThread(runnable);                                         \
-}
-
 #endif
 
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -31,19 +31,24 @@
  * 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 ***** */
 
-#include "nsRootAccessible.h"
+#include "nsAccCache.h"
 #include "nsAccessibilityAtoms.h"
 #include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
+#include "nsRootAccessible.h"
+#include "nsTextEquivUtils.h"
+
 #include "nsIMutableArray.h"
 #include "nsICommandManager.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIDOMAttr.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -35,17 +35,19 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsDocAccessible_H_
 #define _nsDocAccessible_H_
 
 #include "nsHyperTextAccessibleWrap.h"
+#include "nsEventShell.h"
 #include "nsIAccessibleDocument.h"
+
 #include "nsIDocument.h"
 #include "nsIDocumentObserver.h"
 #include "nsIEditor.h"
 #include "nsIObserver.h"
 #include "nsIScrollPositionListener.h"
 #include "nsITimer.h"
 #include "nsIWeakReference.h"
 #include "nsCOMArray.h"
--- a/accessible/src/base/nsEventShell.cpp
+++ b/accessible/src/base/nsEventShell.cpp
@@ -33,16 +33,18 @@
  * 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 ***** */
 
 #include "nsEventShell.h"
 
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsEventShell
 ////////////////////////////////////////////////////////////////////////////////
 
 void
 nsEventShell::FireEvent(nsAccEvent *aEvent)
--- a/accessible/src/base/nsEventShell.h
+++ b/accessible/src/base/nsEventShell.h
@@ -36,18 +36,19 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsEventShell_H_
 #define _nsEventShell_H_
 
 #include "nsAccEvent.h"
 
+#include "a11yGeneric.h"
+
 #include "nsAutoPtr.h"
-#include "nsCoreUtils.h"
 
 class nsIPersistentProperties;
 
 /**
  * Used for everything about events.
  */
 class nsEventShell
 {
--- a/accessible/src/base/nsOuterDocAccessible.cpp
+++ b/accessible/src/base/nsOuterDocAccessible.cpp
@@ -32,18 +32,20 @@
  * 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 ***** */
 
 #include "nsOuterDocAccessible.h"
-#include "nsIAccessibilityService.h"
-#include "nsIAccessibleDocument.h"
+
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+
 #include "nsIDocument.h"
 #include "nsIServiceManager.h"
 #include "nsIContent.h"
 
 NS_IMPL_ISUPPORTS_INHERITED0(nsOuterDocAccessible, nsAccessible)
 
 nsOuterDocAccessible::nsOuterDocAccessible(nsIDOMNode* aNode, 
                                            nsIWeakReference* aShell):
--- a/accessible/src/base/nsRelUtils.cpp
+++ b/accessible/src/base/nsRelUtils.cpp
@@ -33,16 +33,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 ***** */
 
 #include "nsRelUtils.h"
 
+#include "nsAccessibilityService.h"
 #include "nsAccessNode.h"
 
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMDocumentXBL.h"
 
 #include "nsAutoPtr.h"
 #include "nsArrayUtils.h"
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -30,19 +30,21 @@
  * 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 ***** */
 
-// NOTE: alphabetically ordered
 #include "nsAccessibilityService.h"
 #include "nsApplicationAccessibleWrap.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
+#include "nsRelUtils.h"
 
 #include "nsHTMLSelectAccessible.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
--- a/accessible/src/base/nsTextAttrs.cpp
+++ b/accessible/src/base/nsTextAttrs.cpp
@@ -33,17 +33,18 @@
  * 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 ***** */
 
 #include "nsTextAttrs.h"
 
-#include "nsAccessNode.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
 #include "nsHyperTextAccessibleWrap.h"
 
 #include "gfxFont.h"
 #include "gfxUserFontSet.h"
 #include "nsIThebesFontMetrics.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // Constants and structures
--- a/accessible/src/base/nsTextAttrs.h
+++ b/accessible/src/base/nsTextAttrs.h
@@ -40,17 +40,16 @@
 #define nsTextAttrs_h_
 
 class nsHyperTextAccessible;
 
 #include "nsAccessibilityAtoms.h"
 
 #include "nsIDOMNode.h"
 #include "nsIDOMElement.h"
-#include "nsIDOMCSSStyleDeclaration.h"
 
 #include "nsIContent.h"
 #include "nsIFrame.h"
 #include "nsIPersistentProperties2.h"
 
 #include "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsTPtrArray.h"
--- a/accessible/src/base/nsTextEquivUtils.cpp
+++ b/accessible/src/base/nsTextEquivUtils.cpp
@@ -34,17 +34,19 @@
  * 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 ***** */
 
 #include "nsTextEquivUtils.h"
 
+#include "nsAccessibilityService.h"
 #include "nsAccessible.h"
+#include "nsAccUtils.h"
 
 #include "nsIDOMXULLabeledControlEl.h"
 
 #include "nsArrayUtils.h"
 
 #define NS_OK_NO_NAME_CLAUSE_HANDLED \
 NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x24)
 
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -31,19 +31,23 @@
  * 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 ***** */
 
-// NOTE: alphabetically ordered
+#include "nsHTMLFormControlAccessible.h"
+
 #include "nsAccessibilityAtoms.h"
-#include "nsHTMLFormControlAccessible.h"
+#include "nsAccUtils.h"
+#include "nsRelUtils.h"
+#include "nsTextEquivUtils.h"
+
 #include "nsIDOMDocument.h"
 #include "nsIDOMNSHTMLInputElement.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMNSHTMLElement.h"
 #include "nsIDOMNSEditableElement.h"
 #include "nsIDOMNSHTMLButtonElement.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIDOMHTMLLegendElement.h"
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -31,22 +31,23 @@
  * 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 ***** */
 
+#include "nsHTMLImageAccessible.h"
+
+#include "nsAccessibilityAtoms.h"
+#include "nsAccUtils.h"
+
 #include "imgIContainer.h"
 #include "imgIRequest.h"
-
-#include "nsHTMLImageAccessible.h"
-#include "nsAccessibilityAtoms.h"
-
 #include "nsIDocument.h"
 #include "nsIImageLoadingContent.h"
 #include "nsILink.h"
 #include "nsIPresShell.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIDOMDocument.h"
 #include "nsPIDOMWindow.h"
--- a/accessible/src/html/nsHTMLImageMapAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageMapAccessible.cpp
@@ -34,16 +34,18 @@
  * 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 ***** */
 
 #include "nsHTMLImageMapAccessible.h"
 
+#include "nsAccUtils.h"
+
 #include "nsIDOMHTMLCollection.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMHTMLAreaElement.h"
 #include "nsIFrame.h"
 #include "nsIImageFrame.h"
 #include "nsIImageMap.h"
 
--- a/accessible/src/html/nsHTMLLinkAccessible.cpp
+++ b/accessible/src/html/nsHTMLLinkAccessible.cpp
@@ -34,16 +34,18 @@
  * 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 ***** */
 
 #include "nsHTMLLinkAccessible.h"
 
+#include "nsCoreUtils.h"
+
 #include "nsILink.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLLinkAccessible
 
 nsHTMLLinkAccessible::nsHTMLLinkAccessible(nsIDOMNode* aDomNode,
                                            nsIWeakReference* aShell):
   nsHyperTextAccessibleWrap(aDomNode, aShell)
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -31,20 +31,25 @@
  * 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 ***** */
 
+#include "nsHTMLSelectAccessible.h"
+
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+#include "nsEventShell.h"
+#include "nsIAccessibleEvent.h"
+#include "nsTextEquivUtils.h"
+
 #include "nsCOMPtr.h"
-#include "nsHTMLSelectAccessible.h"
-#include "nsIAccessibilityService.h"
-#include "nsIAccessibleEvent.h"
 #include "nsIFrame.h"
 #include "nsIComboboxControlFrame.h"
 #include "nsIDocument.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLOptGroupElement.h"
 #include "nsIDOMHTMLSelectElement.h"
 #include "nsIListControlFrame.h"
 #include "nsIServiceManager.h"
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -34,35 +34,36 @@
  * 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 ***** */
 
 #include "nsHTMLTableAccessible.h"
 
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
 #include "nsDocAccessible.h"
+#include "nsRelUtils.h"
+#include "nsTextEquivUtils.h"
 
 #include "nsIDOMElement.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentRange.h"
 #include "nsIDOMRange.h"
 #include "nsISelection2.h"
 #include "nsISelectionPrivate.h"
 #include "nsINameSpaceManager.h"
-#include "nsIAccessibilityService.h"
-#include "nsIDOMCSSStyleDeclaration.h"
 #include "nsIDOMHTMLCollection.h"
 #include "nsIDOMHTMLTableCellElement.h"
 #include "nsIDOMHTMLTableElement.h"
 #include "nsIDOMHTMLTableRowElement.h"
 #include "nsIDOMHTMLTableSectionElem.h"
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
-#include "nsIServiceManager.h"
 #include "nsITableLayout.h"
 #include "nsITableCellLayout.h"
 #include "nsFrameSelection.h"
 #include "nsLayoutErrors.h"
 #include "nsArrayUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTableCellAccessible
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -35,16 +35,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 "nsHTMLTextAccessible.h"
 
 #include "nsDocAccessible.h"
+#include "nsTextEquivUtils.h"
 
 #include "nsIFrame.h"
 #include "nsPresContext.h"
 #include "nsISelection.h"
 #include "nsISelectionController.h"
 #include "nsComponentManagerUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -33,18 +33,20 @@
  * 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 ***** */
 
 #include "nsHyperTextAccessible.h"
+
 #include "nsAccessibilityAtoms.h"
 #include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
 #include "nsTextAttrs.h"
 
 #include "nsIClipboard.h"
 #include "nsContentCID.h"
 #include "nsIDOMAbstractView.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
 #include "nsPIDOMWindow.h"        
--- a/accessible/src/mac/nsAccessibleWrap.h
+++ b/accessible/src/mac/nsAccessibleWrap.h
@@ -38,24 +38,25 @@
 
 /* For documentation of the accessibility architecture, 
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 #ifndef _nsAccessibleWrap_H_
 #define _nsAccessibleWrap_H_
 
+#include "nsAccessible.h"
+#include "nsAccUtils.h"
+
 #include "nsCOMPtr.h"
 #include "nsRect.h"
 
 #include "nsTArray.h"
 #include "nsAutoPtr.h"
 
-#include "nsAccessible.h"
-
 struct AccessibleWrapper;
 struct objc_class;
 
 class nsAccessibleWrap : public nsAccessible
 {
   public: // construction, destruction
     nsAccessibleWrap(nsIDOMNode*, nsIWeakReference *aShell);
     virtual ~nsAccessibleWrap();
@@ -94,33 +95,20 @@ class nsAccessibleWrap : public nsAccess
     // return this accessible's all children, adhering to "flat" accessibles by not returning their children.
     void GetUnignoredChildren(nsTArray<nsRefPtr<nsAccessibleWrap> > &aChildrenArray);
     virtual already_AddRefed<nsIAccessible> GetUnignoredParent();
     
   protected:
 
     virtual nsresult FirePlatformEvent(nsAccEvent *aEvent);
 
-    PRBool AncestorIsFlat() {
-      // we don't create a native object if we're child of a "flat" accessible; for example, on OS X buttons 
-      // shouldn't have any children, because that makes the OS confused. 
-      //
-      // to maintain a scripting environment where the XPCOM accessible hierarchy look the same 
-      // on all platforms, we still let the C++ objects be created though.
-
-      nsAccessible* parent(GetParent());
-      while (parent) {
-        if (nsAccUtils::MustPrune(parent))
-          return PR_TRUE;
-
-        parent = parent->GetParent();
-      }
-      // no parent was flat
-      return PR_FALSE;
-    }
+  /**
+   * Return true if the parent doesn't have children to expose to AT.
+   */
+  PRBool AncestorIsFlat();
 
     // Wrapper around our native object.
     AccessibleWrapper *mNativeWrapper;
 };
 
 // Define unsupported wrap classes here
 typedef class nsHTMLTableCellAccessible    nsHTMLTableCellAccessibleWrap;
 typedef class nsHTMLTableAccessible        nsHTMLTableAccessibleWrap;
--- a/accessible/src/mac/nsAccessibleWrap.mm
+++ b/accessible/src/mac/nsAccessibleWrap.mm
@@ -304,8 +304,33 @@ nsAccessibleWrap::GetUnignoredParent()
   if (parentWrap->IsIgnored())
     return parentWrap->GetUnignoredParent();
   
   nsIAccessible *outValue = nsnull;
   NS_IF_ADDREF(outValue = parentWrap);
   
   return outValue;
 }
+
+////////////////////////////////////////////////////////////////////////////////
+// nsAccessibleWrap protected
+
+PRBool
+nsAccessibleWrap::AncestorIsFlat()
+{
+  // We don't create a native object if we're child of a "flat" accessible;
+  // for example, on OS X buttons shouldn't have any children, because that
+  // makes the OS confused. 
+  //
+  // To maintain a scripting environment where the XPCOM accessible hierarchy
+  // look the same on all platforms, we still let the C++ objects be created
+  // though.
+
+  nsAccessible* parent(GetParent());
+  while (parent) {
+    if (nsAccUtils::MustPrune(parent))
+      return PR_TRUE;
+
+    parent = parent->GetParent();
+  }
+  // no parent was flat
+  return PR_FALSE;
+}
--- a/accessible/src/msaa/CAccessibleText.cpp
+++ b/accessible/src/msaa/CAccessibleText.cpp
@@ -46,16 +46,17 @@
 #include "nsIAccessible.h"
 #include "nsIAccessibleText.h"
 #include "nsIAccessibleTypes.h"
 #include "nsIWinAccessNode.h"
 #include "nsAccessNodeWrap.h"
 #include "nsAccessibleWrap.h"
 
 #include "nsCOMPtr.h"
+#include "nsIPersistentProperties2.h"
 #include "nsString.h"
 
 #define GET_NSIACCESSIBLETEXT \
 nsCOMPtr<nsIAccessibleText> textAcc(do_QueryInterface(this));\
 NS_ASSERTION(textAcc,\
              "Subclass of CAccessibleText doesn't implement nsIAccessibleText");\
 if (!textAcc)\
   return E_FAIL;\
--- a/accessible/src/msaa/nsAccessNodeWrap.cpp
+++ b/accessible/src/msaa/nsAccessNodeWrap.cpp
@@ -32,34 +32,37 @@
  * 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 ***** */
 
 #include "nsAccessNodeWrap.h"
+
+#include "AccessibleApplication.h"
 #include "ISimpleDOMNode_i.c"
+
 #include "nsAccessibilityAtoms.h"
-#include "nsIAccessible.h"
+#include "nsAccessibilityService.h"
+#include "nsApplicationAccessibleWrap.h"
+#include "nsCoreUtils.h"
+#include "nsRootAccessible.h"
+
 #include "nsAttrName.h"
 #include "nsIDocument.h"
-#include "nsIDOMCSSStyleDeclaration.h"
 #include "nsIDOMNodeList.h"
 #include "nsIDOMNSHTMLElement.h"
 #include "nsIDOMViewCSS.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsPIDOMWindow.h"
-#include "nsRootAccessible.h"
 #include "nsIServiceManager.h"
-#include "AccessibleApplication.h"
-#include "nsApplicationAccessibleWrap.h"
 
 /// the accessible library and cached methods
 HINSTANCE nsAccessNodeWrap::gmAccLib = nsnull;
 HINSTANCE nsAccessNodeWrap::gmUserLib = nsnull;
 LPFNACCESSIBLEOBJECTFROMWINDOW nsAccessNodeWrap::gmAccessibleObjectFromWindow = nsnull;
 LPFNNOTIFYWINEVENT nsAccessNodeWrap::gmNotifyWinEvent = nsnull;
 LPFNGETGUITHREADINFO nsAccessNodeWrap::gmGetGUIThreadInfo = nsnull;
 
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -32,17 +32,21 @@
  * 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 ***** */
 
 #include "nsAccessibleWrap.h"
+
 #include "nsAccessibilityAtoms.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
+#include "nsRelUtils.h"
 
 #include "nsIAccessibleDocument.h"
 #include "nsIAccessibleSelectable.h"
 #include "nsIAccessibleEvent.h"
 #include "nsIAccessibleWin32Object.h"
 
 #include "Accessible2_i.c"
 #include "AccessibleStates.h"
--- a/accessible/src/msaa/nsDocAccessibleWrap.h
+++ b/accessible/src/msaa/nsDocAccessibleWrap.h
@@ -39,16 +39,18 @@
 /* For documentation of the accessibility architecture, 
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 #ifndef _nsDocAccessibleWrap_H_
 #define _nsDocAccessibleWrap_H_
 
 #include "ISimpleDOMDocument.h"
+
+#include "nsAccUtils.h"
 #include "nsDocAccessible.h"
 #include "nsIDocShellTreeItem.h"
 
 class nsDocAccessibleWrap: public nsDocAccessible,
                            public ISimpleDOMDocument
 {
 public:
     nsDocAccessibleWrap(nsIDOMNode *aNode, nsIWeakReference *aShell);
--- a/accessible/src/msaa/nsHyperTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsHyperTextAccessibleWrap.cpp
@@ -35,16 +35,18 @@
  * 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 ***** */
 
 #include "nsHyperTextAccessibleWrap.h"
 
+#include "nsEventShell.h"
+
 NS_IMPL_ISUPPORTS_INHERITED0(nsHyperTextAccessibleWrap,
                              nsHyperTextAccessible)
 
 IMPL_IUNKNOWN_INHERITED2(nsHyperTextAccessibleWrap,
                          nsAccessibleWrap,
                          CAccessibleHypertext,
                          CAccessibleEditableText);
 
--- a/accessible/src/msaa/nsTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsTextAccessibleWrap.cpp
@@ -35,16 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 // NOTE: alphabetically ordered
 #include "nsTextAccessibleWrap.h"
 #include "ISimpleDOMText_i.c"
 
+#include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
 
 #include "nsIFontMetrics.h"
 #include "nsIFrame.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIRenderingContext.h"
 #include "nsIComponentManager.h"
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -33,16 +33,20 @@
  * 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 ***** */
 
 #include "nsXFormsAccessible.h"
 
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+#include "nsTextEquivUtils.h"
+
 #include "nscore.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMNodeList.h"
 #include "nsIEditor.h"
 #include "nsIMutableArray.h"
 #include "nsIXFormsUtilityService.h"
 #include "nsIPlaintextEditor.h"
@@ -100,20 +104,16 @@ nsXFormsAccessible::GetBoundChildElement
 
   aValue.Truncate();
   return NS_OK;
 }
 
 void
 nsXFormsAccessible::CacheSelectChildren(nsIDOMNode *aContainerNode)
 {
-  nsIAccessibilityService *accService = GetAccService();
-  if (!accService)
-    return;
-
   nsCOMPtr<nsIDOMNode> container(aContainerNode);
   if (!container)
     container = mDOMNode;
 
   nsCOMPtr<nsIDOMNodeList> children;
   sXFormsService->GetSelectChildrenFor(container, getter_AddRefs(children));
 
   if (!children)
@@ -126,17 +126,18 @@ nsXFormsAccessible::CacheSelectChildren(
   nsRefPtr<nsAccessible> acc;
 
   for (PRUint32 index = 0; index < length; index++) {
     nsCOMPtr<nsIDOMNode> child;
     children->Item(index, getter_AddRefs(child));
     if (!child)
       continue;
 
-    accService->GetAttachedAccessibleFor(child, getter_AddRefs(accessible));
+    GetAccService()->GetAttachedAccessibleFor(child,
+                                              getter_AddRefs(accessible));
     if (!accessible)
       continue;
 
     acc = nsAccUtils::QueryObject<nsAccessible>(accessible);
     mChildren.AppendElement(acc);
     acc->SetParent(this);
   }
 }
@@ -332,32 +333,29 @@ nsXFormsSelectableAccessible::GetSelecte
   NS_ENSURE_ARG_POINTER(aAccessibles);
 
   *aAccessibles = nsnull;
 
   nsCOMPtr<nsIMutableArray> accessibles =
     do_CreateInstance(NS_ARRAY_CONTRACTID);
   NS_ENSURE_TRUE(accessibles, NS_ERROR_OUT_OF_MEMORY);
 
-  nsIAccessibilityService* accService = GetAccService();
-  NS_ENSURE_TRUE(accService, NS_ERROR_FAILURE);
-
   nsresult rv;
 
   if (mIsSelect1Element) {
     nsCOMPtr<nsIDOMNode> item;
     rv = sXFormsService->GetSelectedItemForSelect1(mDOMNode,
                                                    getter_AddRefs(item));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!item)
       return NS_OK;
 
     nsCOMPtr<nsIAccessible> accessible;
-    accService->GetAccessibleFor(item, getter_AddRefs(accessible));
+    GetAccService()->GetAccessibleFor(item, getter_AddRefs(accessible));
     NS_ENSURE_TRUE(accessible, NS_ERROR_FAILURE);
 
     accessibles->AppendElement(accessible, PR_FALSE);
     NS_ADDREF(*aAccessibles = accessibles);
     return NS_OK;
   }
 
   nsCOMPtr<nsIDOMNodeList> items;
@@ -374,17 +372,17 @@ nsXFormsSelectableAccessible::GetSelecte
     return NS_OK;
 
   for (PRUint32 index = 0; index < length; index++) {
     nsCOMPtr<nsIDOMNode> item;
     items->Item(index, getter_AddRefs(item));
     NS_ENSURE_TRUE(item, NS_ERROR_FAILURE);
 
     nsCOMPtr<nsIAccessible> accessible;
-    accService->GetAccessibleFor(item, getter_AddRefs(accessible));
+    GetAccService()->GetAccessibleFor(item, getter_AddRefs(accessible));
     NS_ENSURE_TRUE(accessible, NS_ERROR_FAILURE);
 
     accessibles->AppendElement(accessible, PR_FALSE);
   }
 
   NS_ADDREF(*aAccessibles = accessibles);
   return NS_OK;
 }
@@ -462,31 +460,28 @@ nsXFormsSelectableAccessible::RemoveChil
 
 NS_IMETHODIMP
 nsXFormsSelectableAccessible::RefSelection(PRInt32 aIndex,
                                            nsIAccessible **aAccessible)
 {
   NS_ENSURE_ARG_POINTER(aAccessible);
   *aAccessible = nsnull;
 
-  nsIAccessibilityService* accService = GetAccService();
-  NS_ENSURE_TRUE(accService, NS_ERROR_FAILURE);
-
   nsresult rv;
   if (mIsSelect1Element) {
     if (aIndex != 0)
       return NS_OK;
 
     nsCOMPtr<nsIDOMNode> item;
     rv = sXFormsService->GetSelectedItemForSelect1(mDOMNode,
                                                    getter_AddRefs(item));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (item)
-      return accService->GetAccessibleFor(item, aAccessible);
+      return GetAccService()->GetAccessibleFor(item, aAccessible);
     return NS_OK;
   }
 
   nsCOMPtr<nsIDOMNodeList> items;
   rv = sXFormsService->GetSelectedItemsForSelect(mDOMNode,
                                                  getter_AddRefs(items));
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -497,17 +492,17 @@ nsXFormsSelectableAccessible::RefSelecti
   items->GetLength(&length);
   if (aIndex < 0 || PRUint32(aIndex) >= length)
     return NS_OK;
 
   nsCOMPtr<nsIDOMNode> item;
   items->Item(aIndex, getter_AddRefs(item));
 
   nsCOMPtr<nsIAccessible> accessible;
-  return accService->GetAccessibleFor(item, getter_AddRefs(accessible));
+  return GetAccService()->GetAccessibleFor(item, getter_AddRefs(accessible));
 }
 
 NS_IMETHODIMP
 nsXFormsSelectableAccessible::IsChildSelected(PRInt32 aIndex,
                                               PRBool *aIsSelected)
 {
   NS_ENSURE_ARG_POINTER(aIsSelected);
   *aIsSelected = PR_FALSE;
--- a/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
@@ -33,16 +33,18 @@
  * 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 ***** */
 
 #include "nsXFormsFormControlsAccessible.h"
 
+#include "nsTextEquivUtils.h"
+
 // nsXFormsLabelAccessible
 
 nsXFormsLabelAccessible::
   nsXFormsLabelAccessible(nsIDOMNode *aNode, nsIWeakReference *aShell):
   nsXFormsAccessible(aNode, aShell)
 {
 }
 
--- a/accessible/src/xul/nsXULColorPickerAccessible.cpp
+++ b/accessible/src/xul/nsXULColorPickerAccessible.cpp
@@ -33,17 +33,19 @@
  * 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 ***** */
 
 #include "nsXULColorPickerAccessible.h"
 
+#include "nsAccUtils.h"
 #include "nsAccTreeWalker.h"
+#include "nsCoreUtils.h"
 
 #include "nsIDOMElement.h"
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColorPickerTileAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
--- a/accessible/src/xul/nsXULComboboxAccessible.cpp
+++ b/accessible/src/xul/nsXULComboboxAccessible.cpp
@@ -35,19 +35,20 @@
  * 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 ***** */
 
 #include "nsXULComboboxAccessible.h"
 
+#include "nsAccessibilityService.h"
+
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
-#include "nsServiceManagerUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULComboboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULComboboxAccessible::
   nsXULComboboxAccessible(nsIDOMNode* aDOMNode, nsIWeakReference* aShell) :
   nsAccessibleWrap(aDOMNode, aShell)
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -32,21 +32,26 @@
  * 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 ***** */
 
+#include "nsXULFormControlAccessible.h"
+
+#include "nsAccessibilityAtoms.h"
+#include "nsAccUtils.h"
+#include "nsAccTreeWalker.h"
+#include "nsCoreUtils.h"
+#include "nsRelUtils.h"
+
 // NOTE: alphabetically ordered
-#include "nsXULFormControlAccessible.h"
 #include "nsHTMLFormControlAccessible.h"
-#include "nsAccessibilityAtoms.h"
-#include "nsAccTreeWalker.h"
 #include "nsXULMenuAccessible.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMNSEditableElement.h"
 #include "nsIDOMXULButtonElement.h"
 #include "nsIDOMXULCheckboxElement.h"
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULTextboxElement.h"
--- a/accessible/src/xul/nsXULListboxAccessible.cpp
+++ b/accessible/src/xul/nsXULListboxAccessible.cpp
@@ -35,20 +35,22 @@
  * 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 ***** */
 
 #include "nsXULListboxAccessible.h"
 
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+
 #include "nsIDOMXULPopupElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
-#include "nsServiceManagerUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColumnsAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULColumnsAccessible::
   nsXULColumnsAccessible(nsIDOMNode *aDOMNode, nsIWeakReference *aShell) :
   nsAccessibleWrap(aDOMNode, aShell)
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -32,30 +32,34 @@
  * 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 ***** */
 
 #include "nsXULMenuAccessible.h"
+
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+#include "nsXULFormControlAccessible.h"
+
 #include "nsIDOMElement.h"
 #include "nsIDOMXULElement.h"
 #include "nsIMutableArray.h"
 #include "nsIDOMXULContainerElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsIServiceManager.h"
 #include "nsIPresShell.h"
 #include "nsIContent.h"
 #include "nsGUIEvent.h"
-#include "nsXULFormControlAccessible.h"
 #include "nsILookAndFeel.h"
 #include "nsWidgetsCID.h"
 
 
 static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 
 /** ------------------------------------------------------ */
 /**  Impl. of nsXULSelectableAccessible                    */
--- a/accessible/src/xul/nsXULSliderAccessible.cpp
+++ b/accessible/src/xul/nsXULSliderAccessible.cpp
@@ -33,18 +33,21 @@
  * 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 ***** */
 
 #include "nsXULSliderAccessible.h"
 
+#include "nsAccessibilityAtoms.h"
+
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentXBL.h"
+#include "nsIFrame.h"
 
 // nsXULSliderAccessible
 
 nsXULSliderAccessible::nsXULSliderAccessible(nsIDOMNode* aNode,
                                              nsIWeakReference* aShell) :
   nsAccessibleWrap(aNode, aShell)
 {
 }
--- a/accessible/src/xul/nsXULTabAccessible.cpp
+++ b/accessible/src/xul/nsXULTabAccessible.cpp
@@ -31,18 +31,22 @@
  * 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 ***** */
 
+#include "nsXULTabAccessible.h"
+
+#include "nsAccUtils.h"
+#include "nsRelUtils.h"
+
 // NOTE: alphabetically ordered
-#include "nsXULTabAccessible.h"
 #include "nsIDocument.h"
 #include "nsIFrame.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTabAccessible
--- a/accessible/src/xul/nsXULTextAccessible.cpp
+++ b/accessible/src/xul/nsXULTextAccessible.cpp
@@ -32,24 +32,29 @@
  * 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 ***** */
 
-// NOTE: alphabetically ordered
+// NOTE: groups are alphabetically ordered
+#include "nsXULTextAccessible.h"
+
 #include "nsAccessibilityAtoms.h"
+#include "nsAccUtils.h"
+#include "nsBaseWidgetAccessible.h"
 #include "nsCoreUtils.h"
-#include "nsBaseWidgetAccessible.h"
+#include "nsRelUtils.h"
+#include "nsTextEquivUtils.h"
+
 #include "nsIDOMXULDescriptionElement.h"
 #include "nsINameSpaceManager.h"
 #include "nsString.h"
-#include "nsXULTextAccessible.h"
 #include "nsNetUtil.h"
 
 /**
   * For XUL descriptions and labels
   */
 nsXULTextAccessible::nsXULTextAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell):
 nsHyperTextAccessibleWrap(aDomNode, aShell)
 { 
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -33,17 +33,21 @@
  * 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 ***** */
 
 #include "nsXULTreeAccessible.h"
 
+#include "nsAccCache.h"
+#include "nsAccUtils.h"
+#include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
+#include "nsRelUtils.h"
 
 #include "nsIDOMXULElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULTreeElement.h"
 #include "nsITreeSelection.h"
 #include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
--- a/accessible/src/xul/nsXULTreeGridAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeGridAccessible.cpp
@@ -33,18 +33,22 @@
  * 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 ***** */
 
 #include "nsXULTreeGridAccessibleWrap.h"
 
+#include "nsAccCache.h"
+#include "nsAccessibilityService.h"
+#include "nsAccUtils.h"
+#include "nsEventShell.h"
+
 #include "nsITreeSelection.h"
-#include "nsServiceManagerUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTreeGridAccessible::
   nsXULTreeGridAccessible(nsIDOMNode *aDOMNode, nsIWeakReference *aShell) :
   nsXULTreeAccessible(aDOMNode, aShell)
--- a/accessible/tests/mochitest/attributes/test_text.html
+++ b/accessible/tests/mochitest/attributes/test_text.html
@@ -57,17 +57,18 @@
       var spellchecker = editor.getInlineSpellChecker(true);
       spellchecker.enableRealTimeSpell = true;
 
       window.setTimeout(function()
         {
           gComputedStyle = document.defaultView.getComputedStyle(node, "");
           var defAttrs = {
             "font-style": gComputedStyle.fontStyle,
-            "font-size": (MAC) ? "8pt" : "10pt",
+            // The pt font size of the input element can vary by Linux distro.
+            "font-size": (WIN ? "10pt" : (MAC ? "8pt" : function() { return true; })),
             "background-color": gComputedStyle.backgroundColor,
             "font-weight": equalsToNormal,
             "color": gComputedStyle.color,
             "font-family": gComputedStyle.fontFamily,
             "text-position": gComputedStyle.verticalAlign
           };
           testDefaultTextAttrs(ID, defAttrs);
 
--- a/accessible/tests/mochitest/tree/test_tabbrowser.xul
+++ b/accessible/tests/mochitest/tree/test_tabbrowser.xul
@@ -83,19 +83,16 @@
             children: [
               {
                 role: ROLE_PUSHBUTTON
               }
             ]
           },
           {
             role: ROLE_PUSHBUTTON
-          },
-          {
-            role: ROLE_PUSHBUTTON
           }
         ]
       };
       var tabboxAccTree = {
         role: ROLE_PANE,
         children: [
           {
             role: ROLE_PROPERTYPAGE
--- a/browser/base/content/browser-tabPreviews.js
+++ b/browser/base/content/browser-tabPreviews.js
@@ -616,18 +616,19 @@ var allTabs = {
     while (this.container.hasChildNodes())
       this.container.removeChild(this.container.firstChild);
 
     this._initiated = false;
   },
 
   prefName: "browser.allTabs.previews",
   readPref: function allTabs_readPref() {
-    var allTabsButton = document.getAnonymousElementByAttribute(
-                          gBrowser.tabContainer, "anonid", "alltabs-button");
+    var allTabsButton = document.getElementById("alltabs-button");
+    if (!allTabsButton)
+      return;
     if (gPrefService.getBoolPref(this.prefName)) {
       allTabsButton.removeAttribute("type");
       allTabsButton.setAttribute("command", "Browser:ShowAllTabs");
     } else {
       allTabsButton.setAttribute("type", "menu");
       allTabsButton.removeAttribute("command");
       allTabsButton.removeAttribute("oncommand");
     }
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -8,20 +8,31 @@ searchbar {
 tabbrowser {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser");
 }
 
 .tabbrowser-tabs {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tabs");
 }
 
+#tabbrowser-tabs:not([overflow="true"]) + #new-tab-button,
+#tabbrowser-tabs[overflow="true"] > .tabbrowser-arrowscrollbox > .tabs-newtab-button,
+#TabsToolbar[currentset]:not([currentset*="tabbrowser-tabs,new-tab-button"]) > #tabbrowser-tabs > .tabbrowser-arrowscrollbox > .tabs-newtab-button,
+#navigator-toolbox[customizing="true"] > #TabsToolbar > #tabbrowser-tabs > .tabbrowser-arrowscrollbox > .tabs-newtab-button {
+  visibility: collapse;
+}
+
 .tabbrowser-tab {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tab");
 }
 
+#alltabs-popup {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-alltabs-popup");
+}
+
 toolbar[printpreview="true"] {
   -moz-binding: url("chrome://global/content/printPreviewBindings.xml#printpreviewtoolbar");
 }
 
 #navigator-toolbox > toolbar:not(#TabsToolbar) {
   -moz-box-ordinal-group: 50;
 }
 
@@ -150,17 +161,17 @@ toolbarbutton.bookmark-item {
   /* override default listbox width from xul.css */
   width: auto;
 }
 
 menuitem.spell-suggestion {
   font-weight: bold;
 }
 
-#sidebar-box toolbarbutton.tabs-closebutton {
+#sidebar-header > .tabs-closebutton {
   -moz-user-focus: normal;
 }
 
 /* apply Fitts' law to the notification bar's close button */
 window[sizemode="maximized"] #content .notification-inner {
   border-right: 0px !important;
 }
 
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -2191,25 +2191,25 @@ function losslessDecodeURI(aURI) {
                 //    ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '#'
                 //    (RFC 3987 section 3.2)
                 // 2. Re-encode whitespace so that it doesn't get eaten away
                 //    by the location bar (bug 410726).
                 .replace(/%(?!3B|2F|3F|3A|40|26|3D|2B|24|2C|23)|[\r\n\t]/ig,
                          encodeURIComponent);
     } catch (e) {}
 
-  // Encode invisible characters (soft hyphen, zero-width space, BOM,
-  // line and paragraph separator, word joiner, invisible times,
-  // invisible separator, object replacement character) (bug 452979)
-  value = value.replace(/[\v\x0c\x1c\x1d\x1e\x1f\u00ad\u200b\ufeff\u2028\u2029\u2060\u2062\u2063\ufffc]/g,
+  // Encode invisible characters (line and paragraph separator,
+  // object replacement character) (bug 452979)
+  value = value.replace(/[\v\x0c\x1c\x1d\x1e\x1f\u2028\u2029\ufffc]/g,
                         encodeURIComponent);
 
-  // Encode bidirectional formatting characters.
+  // Encode default ignorable characters. (bug 546013)
+  // This includes all bidirectional formatting characters.
   // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
-  value = value.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
+  value = value.replace(/[\u00ad\u034f\u115f-\u1160\u17b4-\u17b5\u180b-\u180d\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0\ufff0-\ufff8]|\ud834[\udd73-\udd7a]|[\udb40-\udb43][\udc00-\udfff]/g,
                         encodeURIComponent);
   return value;
 }
 
 function UpdateUrlbarSearchSplitterState()
 {
   var splitter = document.getElementById("urlbar-search-splitter");
   var urlbar = document.getElementById("urlbar-container");
@@ -3350,18 +3350,16 @@ function BrowserToolboxCustomizeDone(aTo
     updateEditUIVisibility();
 #endif
   }
 
   UpdateUrlbarSearchSplitterState();
 
   CombinedStopReload.init();
 
-  gHomeButton.updatePersonalToolbarStyle();
-
   // Update the urlbar
   if (gURLBar) {
     URLBarSetURI();
     XULBrowserWindow.asyncUpdateUI();
     PlacesStarButton.updateState();
   }
 
   // Re-enable parts of the UI we disabled during the dialog
@@ -3375,21 +3373,22 @@ function BrowserToolboxCustomizeDone(aTo
   // make sure to re-enable click-and-hold
   if (!getBoolPref("ui.click_hold_context_menus", false))
     SetClickAndHoldHandlers();
 #endif
 
   // XXX Shouldn't have to do this, but I do
   if (!gCustomizeSheet)
     window.focus();
-
 }
 
 function BrowserToolboxCustomizeChange() {
   gHomeButton.updatePersonalToolbarStyle();
+
+  allTabs.readPref();
 }
 
 /**
  * Update the global flag that tracks whether or not any edit UI (the Edit menu,
  * edit-related items in the context menu, and edit-related toolbar buttons
  * is visible, then update the edit commands' enabled state accordingly.  We use
  * this flag to skip updating the edit commands on focus or selection changes
  * when no UI is visible to improve performance (including pageload performance,
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -558,26 +558,60 @@
                oncommand="BookmarksEventHandler.onCommand(event);"
                onpopupshowing="BookmarksEventHandler.onPopupShowing(event);"
                tooltip="bhTooltip" popupsinherittooltip="true"/>
       </toolbaritem>
     </toolbar>
 
     <toolbar id="TabsToolbar"
              fullscreentoolbar="true"
+             customizable="true"
+             mode="icons" lockmode="true"
+             iconsize="small" defaulticonsize="small" lockiconsize="true"
+             context="toolbar-context-menu"
+             defaultset="tabbrowser-tabs,new-tab-button,alltabs-button,tabs-closebutton"
              collapsed="true">
+
       <tabs id="tabbrowser-tabs"
             class="tabbrowser-tabs"
             context="tabContextMenu"
             tabbrowser="content"
             flex="1"
             setfocus="false"
             tooltip="tabbrowser-tab-tooltip">
         <tab class="tabbrowser-tab" selected="true"/>
       </tabs>
+
+      <toolbarbutton id="new-tab-button"
+                     class="toolbarbutton-1 chromeclass-toolbar-additional"
+                     label="&tabCmd.label;"
+                     command="cmd_newNavigatorTab"
+                     tooltiptext="&newTabButton.tooltip;"
+                     ondrop="newTabButtonObserver.onDrop(event)"
+                     ondragover="newTabButtonObserver.onDragOver(event)"
+                     ondragenter="newTabButtonObserver.onDragOver(event)"
+                     ondragleave="newTabButtonObserver.onDragLeave(event)"
+                     removable="true"/>
+
+      <toolbarbutton id="alltabs-button"
+                     class="toolbarbutton-1 chromeclass-toolbar-additional tabs-alltabs-button"
+                     type="menu"
+                     label="&listAllTabs.label;"
+                     tooltiptext="&listAllTabs.label;"
+                     removable="true">
+        <menupopup id="alltabs-popup"
+                   position="after_end"/>
+      </toolbarbutton>
+
+      <toolbarbutton id="tabs-closebutton"
+                     class="close-button tabs-closebutton"
+                     command="cmd_close"
+                     label="&closeTab.label;"
+                     tooltiptext="&closeTab.label;"/>
+
     </toolbar>
 
     <toolbarpalette id="BrowserToolbarPalette">
 
       <toolbarbutton id="print-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
                      label="&printButton.label;" command="cmd_print"
                      tooltiptext="&printButton.tooltip;"/>
 
@@ -602,25 +636,16 @@
       <toolbarbutton id="bookmarks-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
                      observes="viewBookmarksSidebar"
                      tooltiptext="&bookmarksButton.tooltip;"
                      ondrop="bookmarksButtonObserver.onDrop(event)"
                      ondragover="bookmarksButtonObserver.onDragOver(event)"
                      ondragenter="bookmarksButtonObserver.onDragOver(event)"
                      ondragleave="bookmarksButtonObserver.onDragLeave(event)"/>
 
-      <toolbarbutton id="new-tab-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
-                     label="&tabCmd.label;"
-                     command="cmd_newNavigatorTab"
-                     tooltiptext="&newTabButton.tooltip;"
-                     ondrop="newTabButtonObserver.onDrop(event)"
-                     ondragover="newTabButtonObserver.onDragOver(event)"
-                     ondragenter="newTabButtonObserver.onDragOver(event)"
-                     ondragleave="newTabButtonObserver.onDragLeave(event)"/>
-
       <toolbarbutton id="new-window-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
                      label="&newNavigatorCmd.label;"
                      command="key_newNavigator"
                      tooltiptext="&newWindowButton.tooltip;"
                      ondrop="newWindowButtonObserver.onDrop(event)"
                      ondragover="newWindowButtonObserver.onDragOver(event)"
                      ondragenter="newWindowButtonObserver.onDragOver(event)"
                      ondragleave="newWindowButtonObserver.onDragLeave(event)"/>
--- a/browser/base/content/tabbrowser.css
+++ b/browser/base/content/tabbrowser.css
@@ -1,50 +1,26 @@
 .tabbrowser-tabbox {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tabbox");
 }
 
 .tabbrowser-arrowscrollbox {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-arrowscrollbox");
 }
 
-.tabs-alltabs-popup {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-alltabs-popup");
-}
-
-.tab-close-button,
-.tabs-closebutton {
+.tab-close-button {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-close-tab-button");
-}
-
-.tab-close-button {
   display: none;
 }
 
 .tabbrowser-tabs:not([closebuttons="noclose"]):not([closebuttons="closeatend"]) > .tabbrowser-tab[selected="true"] > .tab-close-button,
 .tabbrowser-tabs[closebuttons="alltabs"] > .tabbrowser-tab > .tab-close-button {
   display: -moz-box;
 }
 
-.tabbrowser-tabs:not([overflow="true"]) > .tabs-newtab-button,
-.tabbrowser-tabs[overflow="true"] > .tabbrowser-arrowscrollbox > .tabs-newtab-button {
-  visibility: collapse;
-}
-
-.tabs-newtab-button > .toolbarbutton-text {
-  display: none;
-}
-
 tabpanels {
   background-color: white;
 }
 
 .tab-drop-indicator {
   position: relative;
   z-index: 1;
 }
-
-%ifdef MOZ_WIDGET_GTK2
-/* Favicons override the "images-in-menus" metric in xul.css */
-.alltabs-item > .menu-iconic-left {
-  visibility: inherit;
-}
-%endif
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2452,27 +2452,16 @@
         <children includes="tab"/>
 # This is to ensure anything extensions put here will go before the newtab
 # button, necessary due to the previous hack.
         <children/>
         <xul:toolbarbutton class="tabs-newtab-button"
                            command="cmd_newNavigatorTab"
                            tooltiptext="&newTabButton.tooltip;"/>
       </xul:arrowscrollbox>
-      <xul:toolbarbutton class="tabs-newtab-button" anonid="newtab-button"
-                         command="cmd_newNavigatorTab"
-                         tooltiptext="&newTabButton.tooltip;"/>
-      <xul:toolbarbutton class="tabs-alltabs-button" anonid="alltabs-button"
-                         type="menu"
-                         tooltiptext="&listAllTabs.label;">
-        <xul:menupopup class="tabs-alltabs-popup" anonid="alltabs-popup"
-                       position="after_end"/>
-      </xul:toolbarbutton>
-      <xul:toolbarbutton anonid="tabs-closebutton"
-                         class="close-button tabs-closebutton"/>
     </content>
 
     <implementation implements="nsIDOMEventListener">
       <constructor>
         <![CDATA[
           this.mTabMinWidth = Services.prefs.getIntPref("browser.tabs.tabMinWidth");
           this.mTabMaxWidth = Services.prefs.getIntPref("browser.tabs.tabMaxWidth");
           this.mTabClipWidth = Services.prefs.getIntPref("browser.tabs.tabClipWidth");
@@ -2520,20 +2509,16 @@
       </field>
 
       <field name="mTabstripWidth">0</field>
 
       <field name="mTabstrip">
         document.getAnonymousElementByAttribute(this, "anonid", "arrowscrollbox");
       </field>
 
-      <field name="mTabstripClosebutton">
-        document.getAnonymousElementByAttribute(this, "anonid", "tabs-closebutton");
-      </field>
-
       <field name="_prefObserver"><![CDATA[({
         tabContainer: this,
 
         observe: function (subject, topic, data) {
           switch (data) {
             case "browser.tabs.closeButtons":
               this.tabContainer.mCloseButtons = Services.prefs.getIntPref(data);
               this.tabContainer.adjustTabstrip();
@@ -2613,17 +2598,19 @@
             else
               this.setAttribute("closebuttons", "activetab");
             break;
           case 2:
           case 3:
             this.setAttribute("closebuttons", "noclose");
             break;
           }
-          this.mTabstripClosebutton.collapsed = this.mCloseButtons != 3;
+          var tabstripClosebutton = document.getElementById("tabs-closebutton");
+          if (tabstripClosebutton && tabstripClosebutton.parentNode == this._container)
+            tabstripClosebutton.collapsed = this.mCloseButtons != 3;
         ]]></body>
       </method>
 
       <method name="_handleTabSelect">
         <body><![CDATA[
           this.mTabstrip.ensureElementIsVisible(this.selectedItem);
         ]]></body>
       </method>
@@ -2655,21 +2642,16 @@
                 this._handleTabSelect();
                 this.mTabstripWidth = width;
               }
               break;
           }
         ]]></body>
       </method>
 
-      <field name="mAllTabsPopup">
-        document.getAnonymousElementByAttribute(this, 
-                                                "anonid", "alltabs-popup");
-      </field>
-
       <field name="_animateElement">
         this.mTabstrip._scrollButtonDown;
       </field>
       
       <method name="_notifyBackgroundTab">
         <parameter name="aTab"/>
         <body><![CDATA[
           var scrollRect = this.mTabstrip.scrollClientRect;
@@ -2775,16 +2757,22 @@
           var t = this.selectedItem;
           if (event.screenX >= t.boxObject.screenX &&
               event.screenX <= t.boxObject.screenX + t.boxObject.width &&
               event.screenY >= t.boxObject.screenY &&
               event.screenY <= t.boxObject.screenY + t.boxObject.height)
             this.mTabstrip.ensureElementIsVisible(t);
         ]]></body>
       </method>
+
+      <!-- Deprecated stuff, implemented for backwards compatibility. -->
+      <property name="mTabstripClosebutton" readonly="true"
+                onget="return document.getElementById('tabs-closebutton');"/>
+      <property name="mAllTabsPopup" readonly="true"
+                onget="return document.getElementById('alltabs-popup');"/>
     </implementation>
 
     <handlers>
       <handler event="TabSelect" action="this._handleTabSelect();"/>
 
       <handler event="dblclick"><![CDATA[
         // See hack note in the tabbrowser-close-button binding
         if (!this._blockDblClick && event.button == 0 &&
@@ -2847,18 +2835,16 @@
         var pixelsToScroll = 0;
         if (this.getAttribute("overflow") == "true") {
           var targetAnonid = event.originalTarget.getAttribute("anonid");
           switch (targetAnonid) {
             case "scrollbutton-up":
               pixelsToScroll = tabStrip.scrollIncrement * -1;
               break;
             case "scrollbutton-down":
-            case "alltabs-button":
-            case "newtab-button":
               pixelsToScroll = tabStrip.scrollIncrement;
               break;
           }
           if (pixelsToScroll)
             tabStrip.scrollByPixels((ltr ? 1 : -1) * pixelsToScroll);
         }
 
         if (effects == "link") {
@@ -3073,69 +3059,64 @@
        Therefore it should only be used as a child of the tab or the tabs
        element (in both cases, when they are anonymous nodes of <tabbrowser>).
   -->
   <binding id="tabbrowser-close-tab-button"
            extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton-image">
     <handlers>
       <handler event="click" button="0"><![CDATA[
         var bindingParent = document.getBindingParent(this);
-
-        if (bindingParent.localName == "tab") {
-          let tabContainer = bindingParent.parentNode;
-          /* The only sequence in which a second click event (i.e. dblclik)
-           * can be dispatched on an in-tab close button is when it is shown
-           * after the first click (i.e. the first click event was dispatched
-           * on the tab). This happens when we show the close button only on
-           * the active tab. (bug 352021)
-           * The only sequence in which a third click event can be dispatched
-           * on an in-tab close button is when the tab was opened with a
-           * double click on the tabbar. (bug 378344)
-           * In both cases, it is most likely that the close button area has
-           * been accidentally clicked, therefore we do not close the tab.
-           *
-           * We don't want to ignore processing of more than one click event,
-           * though, since the user might actually be repeatedly clicking to
-           * close many tabs at once.
-           */
-          if (event.detail > 1 && !this._ignoredClick) {
-            this._ignoredClick = true;
+        var tabContainer = bindingParent.parentNode;
+        /* The only sequence in which a second click event (i.e. dblclik)
+         * can be dispatched on an in-tab close button is when it is shown
+         * after the first click (i.e. the first click event was dispatched
+         * on the tab). This happens when we show the close button only on
+         * the active tab. (bug 352021)
+         * The only sequence in which a third click event can be dispatched
+         * on an in-tab close button is when the tab was opened with a
+         * double click on the tabbar. (bug 378344)
+         * In both cases, it is most likely that the close button area has
+         * been accidentally clicked, therefore we do not close the tab.
+         *
+         * We don't want to ignore processing of more than one click event,
+         * though, since the user might actually be repeatedly clicking to
+         * close many tabs at once.
+         */
+        if (event.detail > 1 && !this._ignoredClick) {
+          this._ignoredClick = true;
+          return;
+        }
+
+        // Reset the "ignored click" flag
+        this._ignoredClick = false;
+
+        tabContainer.tabbrowser.removeTab(bindingParent);
+        this._blockDblClick = true;
+
+        /* XXXmano hack (see bug 343628):
+         * Since we're removing the event target, if the user
+         * double-clicks this button, the dblclick event will be dispatched
+         * with the tabbar as its event target (and explicit/originalTarget),
+         * which treats that as a mouse gesture for opening a new tab.
+         * In this context, we're manually blocking the dblclick event
+         * (see dblclick handler).
+         */
+        var self = this;
+        var clickedOnce = false;
+        function enableDblClick(event) {
+          if (event.detail == 1 && !clickedOnce) {
+            clickedOnce = true;
             return;
           }
-
-          // Reset the "ignored click" flag
-          this._ignoredClick = false;
-
-          tabContainer.tabbrowser.removeTab(bindingParent);
-          this._blockDblClick = true;
-
-          /* XXXmano hack (see bug 343628):
-           * Since we're removing the event target, if the user
-           * double-clicks this button, the dblclick event will be dispatched
-           * with the tabbar as its event target (and explicit/originalTarget),
-           * which treats that as a mouse gesture for opening a new tab.
-           * In this context, we're manually blocking the dblclick event
-           * (see dblclick handler).
-           */
-          let self = this;
-          let clickedOnce = false;
-          function enableDblClick(event) {
-            if (event.detail == 1 && !clickedOnce) {
-              clickedOnce = true;
-              return;
-            }
-            setTimeout(function() {
-              self._blockDblClick = false;
-            }, 0);
-            tabContainer.removeEventListener("click", enableDblClick, false);
-          }
-          tabContainer.addEventListener("click", enableDblClick, false);
+          setTimeout(function() {
+            self._blockDblClick = false;
+          }, 0);
+          tabContainer.removeEventListener("click", enableDblClick, false);
         }
-        else // "tabs"
-          bindingParent.tabbrowser.removeCurrentTab();
+        tabContainer.addEventListener("click", enableDblClick, false);
       ]]></handler>
 
       <handler event="dblclick" button="0" phase="capturing">
         // for the one-close-button case
         event.stopPropagation();
       </handler>
 
       <handler event="dragstart">
@@ -3208,18 +3189,17 @@
   </binding>
 
   <binding id="tabbrowser-alltabs-popup"
            extends="chrome://global/content/bindings/popup.xml#popup">
     <implementation implements="nsIDOMEventListener">
       <method name="_menuItemOnCommand">
         <parameter name="aEvent"/>
         <body><![CDATA[
-          var tabcontainer = document.getBindingParent(this);
-          tabcontainer.selectedItem = aEvent.target.tab;
+          gBrowser.selectedTab = aEvent.target.tab;
         ]]></body>
       </method>
 
       <method name="_tabOnAttrModified">
         <parameter name="aEvent"/>
         <body><![CDATA[
           var tab = aEvent.target;
           this._setMenuitemAttributes(tab.mCorrespondingMenuitem, tab);
@@ -3258,17 +3238,17 @@
               this._updateTabsVisibilityStatus();
               break;
           }
         ]]></body>
       </method>
 
       <method name="_updateTabsVisibilityStatus">
         <body><![CDATA[
-          var tabContainer = document.getBindingParent(this);
+          var tabContainer = gBrowser.tabContainer;
           // We don't want menu item decoration unless there is overflow.
           if (tabContainer.getAttribute("overflow") != "true")
             return;
 
           var tabstripBO = tabContainer.mTabstrip.scrollBoxObject;
           for (var i = 0; i < this.childNodes.length; i++) {
             var curTabBO = this.childNodes[i].tab.boxObject;
             if (curTabBO.screenX >= tabstripBO.screenX &&
@@ -3282,17 +3262,17 @@
 
       <method name="_createTabMenuItem">
         <parameter name="aTab"/>
         <body><![CDATA[
           var menuItem = document.createElementNS(
             "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", 
             "menuitem");
 
-          menuItem.setAttribute("class", "menuitem-iconic alltabs-item");
+          menuItem.setAttribute("class", "menuitem-iconic alltabs-item menuitem-with-favicon");
 
           this._setMenuitemAttributes(menuItem, aTab);
 
           // Keep some attributes of the menuitem in sync with its
           // corresponding tab (e.g. the tab label)
           aTab.mCorrespondingMenuitem = menuItem;
           menuItem.tab = aTab;
           menuItem.addEventListener("command", this, false);
@@ -3322,17 +3302,17 @@
         ]]></body>
       </method>
     </implementation>
 
     <handlers>
       <handler event="popupshowing">
       <![CDATA[
         // set up the menu popup
-        var tabcontainer = document.getBindingParent(this);
+        var tabcontainer = gBrowser.tabContainer;
         var tabs = tabcontainer.childNodes;
 
         // Listen for changes in the tab bar.
         tabcontainer.addEventListener("TabOpen", this, false);
         tabcontainer.addEventListener("TabAttrModified", this, false);
         tabcontainer.addEventListener("TabClose", this, false);
         tabcontainer.mTabstrip.addEventListener("scroll", this, false);
 
@@ -3346,17 +3326,17 @@
       <![CDATA[
         // clear out the menu popup and remove the listeners
         while (this.hasChildNodes()) {
           var menuItem = this.lastChild;
           menuItem.removeEventListener("command", this, false);
           menuItem.tab.mCorrespondingMenuitem = null;
           this.removeChild(menuItem);
         }
-        var tabcontainer = document.getBindingParent(this);
+        var tabcontainer = gBrowser.tabContainer;
         tabcontainer.mTabstrip.removeEventListener("scroll", this, false);
         tabcontainer.removeEventListener("TabOpen", this, false);
         tabcontainer.removeEventListener("TabAttrModified", this, false);
         tabcontainer.removeEventListener("TabClose", this, false);
       ]]></handler>
 
       <handler event="DOMMenuItemActive">
       <![CDATA[
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -1166,18 +1166,23 @@ BrowserGlue.prototype = {
           annosvc.setItemAnnotation(smartBookmark.itemId,
                                     SMART_BOOKMARKS_ANNO, smartBookmark.queryId,
                                     0, annosvc.EXPIRE_NEVER);
         }
         
         // If we are creating all Smart Bookmarks from ground up, add a
         // separator below them in the bookmarks menu.
         if (smartBookmarksCurrentVersion == 0 &&
-            smartBookmarkItemIds.length == 0)
-          bmsvc.insertSeparator(bmsvc.bookmarksMenuFolder, bookmarksMenuIndex);
+            smartBookmarkItemIds.length == 0) {
+          let id = bmsvc.getIdForItemAt(bmsvc.bookmarksMenuFolder,
+                                        bookmarksMenuIndex);
+          // Don't add a separator if the menu was empty or there is one already.
+          if (id != -1 && bmsvc.getItemType(id) != bmsvc.TYPE_SEPARATOR)
+            bmsvc.insertSeparator(bmsvc.bookmarksMenuFolder, bookmarksMenuIndex);
+        }
       }
     };
 
     try {
       bmsvc.runInBatchMode(callback, null);
     }
     catch(ex) {
       Components.utils.reportError(ex);
--- a/browser/components/places/tests/unit/bookmarks.corrupt.html
+++ b/browser/components/places/tests/unit/bookmarks.corrupt.html
@@ -2,18 +2,16 @@
 <!-- This is an automatically generated file.
      It will be read and overwritten.
      DO NOT EDIT! -->
 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
 <TITLE>Bookmarks</TITLE>
 <H1 LAST_MODIFIED="1177541029">Bookmarks</H1>
 
 <DL><p>
-    <DT><A HREF="https://en-US.add-ons.mozilla.com/en-US/firefox/bookmarks/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAFo9M%2F3AAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAPkSURBVHjaYmAAgrjyOnOGiKxqxT9%2F%2FvwHCCCGuNJKLpAo49KTL%2F5%2F%2F8PMABBADJFZFWwXnn%2F%2FDxJYeOLNf0aQ9AIg48%2Ff%2Fwwfvv1hAAggZpBAYlWdnrqJLcPVE4e%2Bsuy7%2FfH%2F%2B88%2FGdjY2Bj%2BcCqHMey6%2Ben%2F379%2F%2F%2F8B6unZ9ew%2Fy54jV249f6%2Bm9uXnX4Y9qyaoAAQAhAB7%2FwEAAAAAY3h%2BG1RdbeMMCgkB9%2Fr%2BAPL2%2FAC3vsyi5NG6YQFcbnwdZ3F44uru9gAAAQAAUjEVALPT7wDu9v4A5erz%2FgL19vr16PD6AAUHBgDu9PwA%2F%2F8AAO%2F2%2FgD0%2BP0A7e7x8QPYzsX38vj9g%2BPk6hkLFiAxy%2BP4AeHj5%2FXFtp9GonxaagII7AawXyprpf%2F%2FZ5L5%2Fe%2Fv9%2B%2Fff91ZN7nrG0icJSqrkknJxHm1h5Nl0J8%2F%2Fxg%2B%2FwDa%2Febzv39%2FWKQ2TG97ycIvq%2Bvn52oVxMHGxHDj8RcGQT4uEGZyCct98e3LL3YmJ2enNYxAi%2B48%2B8QQaizGIMLFBLaSlYWZgYWDWZaJhY2V%2BcvPfwz%2BeiIMf%2F%2F%2BY9CV4GAQ42Zh%2BPPvP8O%2Fv%2F%2BZmG7cff7u49c%2FDNtufGZgYmJiOHLvG8Pt1z8Yfv3%2Bz%2FDn19%2B3TCd2LNV7%2F%2FU3w7vPvxkWnHzDcOPFd4ZvQBPv3L79aM%2BS3nfMN88d%2BfyXkW0Lq6BiGAs7J8fHT9%2F%2FXTy%2BY82Lp0cdb5889hcgQJNU85JYFMXP%2B5aHqRmmZJ9kKMGAEBgtDCYYY6BFa%2BlrPc6yRf0LYYtZzG4YaNGibUNJVLuIcBNUTLMQM8ZoppdiaXnf9Xlf5z4ounDu4p57f%2Ff8Pt50SH9ZEfUuLehy93yMRBNroVAg6PV2yBbO9c94tK5v7suF3%2FlMs1o8oU27ltvIMic7fJv7uuqLJGa2UpPxlCILICBtGz1pYWooakeoDaTFgBtNWm04zl%2Fkbs53FnZ%2FZO%2BldGbFP5aaP50cj41pigi8XFjF2zp8ivpgsFMFHp0GgrQZL4DuYGCE6f3pzoBnUwRB8sYi4QGKHf7b5d8HiHWpMBsPvLKDeFiHmVEPBN0yMJyMIUhfb6gXbMkr4xtq1J6Z36eLpmiDH508LNShbDzB4kTIATguNsBqA1CHElJDhGdCGWsDkYY%2FTJh3lUelu384yTlzrtgDWVaggvG8qhDnYcEwwWi0wET%2FTNTh9Gh%2FvVn7v%2B2I%2BHlpWXS59ORgfOr7UGRkVNMUAWPtCMnHdbjjATFNKJeKpdLZYQY0crDzLUvfbHxdqfllj6a7p2VVjUqyGhYwPpZFqxYlf6hZ%2F7X3c736%2Fv4LV1blv94gEvsAAAAASUVORK5CYII%3D" ID="rdf:#$CnoJ1">Get Bookmark Add-ons</A>
-    <HR>
     <DT><H3 ID="rdf:#$ZvPhC3">Mozilla Firefox</H3>
     <DL><p>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/help/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$22iCK1">Help and Tutorials</A>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/customize/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$32iCK1">Customize Firefox</A>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/community/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$42iCK1">Get Involved</A>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/about/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">About Us</A>
         <DT><A HREF="b0rked" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">About Us</A>
     </DL><p>
--- a/browser/components/places/tests/unit/bookmarks.preplaces.html
+++ b/browser/components/places/tests/unit/bookmarks.preplaces.html
@@ -2,18 +2,16 @@
 <!-- This is an automatically generated file.
      It will be read and overwritten.
      DO NOT EDIT! -->
 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
 <TITLE>Bookmarks</TITLE>
 <H1 LAST_MODIFIED="1177541029">Bookmarks</H1>
 
 <DL><p>
-    <DT><A HREF="https://en-US.add-ons.mozilla.com/en-US/firefox/bookmarks/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAFo9M%2F3AAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAPkSURBVHjaYmAAgrjyOnOGiKxqxT9%2F%2FvwHCCCGuNJKLpAo49KTL%2F5%2F%2F8PMABBADJFZFWwXnn%2F%2FDxJYeOLNf0aQ9AIg48%2Ff%2Fwwfvv1hAAggZpBAYlWdnrqJLcPVE4e%2Bsuy7%2FfH%2F%2B88%2FGdjY2Bj%2BcCqHMey6%2Ben%2F379%2F%2F%2F8B6unZ9ew%2Fy54jV249f6%2Bm9uXnX4Y9qyaoAAQAhAB7%2FwEAAAAAY3h%2BG1RdbeMMCgkB9%2Fr%2BAPL2%2FAC3vsyi5NG6YQFcbnwdZ3F44uru9gAAAQAAUjEVALPT7wDu9v4A5erz%2FgL19vr16PD6AAUHBgDu9PwA%2F%2F8AAO%2F2%2FgD0%2BP0A7e7x8QPYzsX38vj9g%2BPk6hkLFiAxy%2BP4AeHj5%2FXFtp9GonxaagII7AawXyprpf%2F%2FZ5L5%2Fe%2Fv9%2B%2Fff91ZN7nrG0icJSqrkknJxHm1h5Nl0J8%2F%2Fxg%2B%2FwDa%2Febzv39%2FWKQ2TG97ycIvq%2Bvn52oVxMHGxHDj8RcGQT4uEGZyCct98e3LL3YmJ2enNYxAi%2B48%2B8QQaizGIMLFBLaSlYWZgYWDWZaJhY2V%2BcvPfwz%2BeiIMf%2F%2F%2BY9CV4GAQ42Zh%2BPPvP8O%2Fv%2F%2BZmG7cff7u49c%2FDNtufGZgYmJiOHLvG8Pt1z8Yfv3%2Bz%2FDn19%2B3TCd2LNV7%2F%2FU3w7vPvxkWnHzDcOPFd4ZvQBPv3L79aM%2BS3nfMN88d%2BfyXkW0Lq6BiGAs7J8fHT9%2F%2FXTy%2BY82Lp0cdb5889hcgQJNU85JYFMXP%2B5aHqRmmZJ9kKMGAEBgtDCYYY6BFa%2BlrPc6yRf0LYYtZzG4YaNGibUNJVLuIcBNUTLMQM8ZoppdiaXnf9Xlf5z4ounDu4p57f%2Ff8Pt50SH9ZEfUuLehy93yMRBNroVAg6PV2yBbO9c94tK5v7suF3%2FlMs1o8oU27ltvIMic7fJv7uuqLJGa2UpPxlCILICBtGz1pYWooakeoDaTFgBtNWm04zl%2Fkbs53FnZ%2FZO%2BldGbFP5aaP50cj41pigi8XFjF2zp8ivpgsFMFHp0GgrQZL4DuYGCE6f3pzoBnUwRB8sYi4QGKHf7b5d8HiHWpMBsPvLKDeFiHmVEPBN0yMJyMIUhfb6gXbMkr4xtq1J6Z36eLpmiDH508LNShbDzB4kTIATguNsBqA1CHElJDhGdCGWsDkYY%2FTJh3lUelu384yTlzrtgDWVaggvG8qhDnYcEwwWi0wET%2FTNTh9Gh%2FvVn7v%2B2I%2BHlpWXS59ORgfOr7UGRkVNMUAWPtCMnHdbjjATFNKJeKpdLZYQY0crDzLUvfbHxdqfllj6a7p2VVjUqyGhYwPpZFqxYlf6hZ%2F7X3c736%2Fv4LV1blv94gEvsAAAAASUVORK5CYII%3D" ID="rdf:#$CnoJ1">Get Bookmark Add-ons</A>
-    <HR>
     <DT><H3 ID="rdf:#$ZvPhC3">Mozilla Firefox</H3>
     <DL><p>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/help/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$22iCK1">Help and Tutorials</A>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/customize/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$32iCK1">Customize Firefox</A>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/community/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$42iCK1">Get Involved</A>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/about/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">About Us</A>
     </DL><p>
     <DT><H3 ADD_DATE="1177541020" LAST_MODIFIED="1177541050" ID="rdf:#$74Gpx2">test</H3>
--- a/browser/components/places/tests/unit/head_bookmarks.js
+++ b/browser/components/places/tests/unit/head_bookmarks.js
@@ -103,9 +103,9 @@ let (backup_date = new Date().toLocaleFo
 
 // Smart bookmarks constants.
 const SMART_BOOKMARKS_VERSION = 2;
 const SMART_BOOKMARKS_ON_TOOLBAR = 1;
 const SMART_BOOKMARKS_ON_MENU = 3; // Takes in count the additional separator.
 
 // Default bookmarks constants.
 const DEFAULT_BOOKMARKS_ON_TOOLBAR = 2;
-const DEFAULT_BOOKMARKS_ON_MENU = 3;
+const DEFAULT_BOOKMARKS_ON_MENU = 1;
--- a/browser/components/places/tests/unit/test_384370.js
+++ b/browser/components/places/tests/unit/test_384370.js
@@ -155,20 +155,20 @@ function testCanonicalBookmarks() {
   var query = PlacesUtils.history.getNewQuery();
   query.setFolders([PlacesUtils.bookmarks.bookmarksMenuFolder], 1);
   var result = PlacesUtils.history.executeQuery(query, PlacesUtils.history.getNewQueryOptions());
   var rootNode = result.root;
   rootNode.containerOpen = true;
 
   // 6-2: the toolbar contents are imported to the places-toolbar folder,
   // the separator above it is removed.
-  do_check_eq(rootNode.childCount, 4);
+  do_check_eq(rootNode.childCount, DEFAULT_BOOKMARKS_ON_MENU + 1);
 
   // get test folder
-  var testFolder = rootNode.getChild(3);
+  var testFolder = rootNode.getChild(DEFAULT_BOOKMARKS_ON_MENU);
   do_check_eq(testFolder.type, testFolder.RESULT_TYPE_FOLDER);
   do_check_eq(testFolder.title, "test");
 
   /*
   // add date 
   do_check_eq(PlacesUtils.bookmarks.getItemDateAdded(testFolder.itemId)/1000000, 1177541020);
   // last modified
   do_check_eq(PlacesUtils.bookmarks.getItemLastModified(testFolder.itemId)/1000000, 1177541050);
--- a/browser/components/places/tests/unit/test_457441-import-export-corrupt-bookmarks-html.js
+++ b/browser/components/places/tests/unit/test_457441-import-export-corrupt-bookmarks-html.js
@@ -120,20 +120,20 @@ function database_check() {
   // BOOKMARKS MENU
   var query = hs.getNewQuery();
   query.setFolders([bs.bookmarksMenuFolder], 1);
   var options = hs.getNewQueryOptions();
   options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
   var result = hs.executeQuery(query, options);
   var rootNode = result.root;
   rootNode.containerOpen = true;
-  do_check_eq(rootNode.childCount, 4);
+  do_check_eq(rootNode.childCount, DEFAULT_BOOKMARKS_ON_MENU + 1);
 
   // get test folder
-  var testFolder = rootNode.getChild(3);
+  var testFolder = rootNode.getChild(DEFAULT_BOOKMARKS_ON_MENU);
   do_check_eq(testFolder.type, testFolder.RESULT_TYPE_FOLDER);
   do_check_eq(testFolder.title, "test");
   // add date
   do_check_eq(bs.getItemDateAdded(testFolder.itemId)/1000000, 1177541020);
   // last modified
   do_check_eq(bs.getItemLastModified(testFolder.itemId)/1000000, 1177541050);
   testFolder = testFolder.QueryInterface(Ci.nsINavHistoryQueryResultNode);
   do_check_eq(testFolder.hasChildren, true);
--- a/browser/components/places/tests/unit/test_bookmarks_html.js
+++ b/browser/components/places/tests/unit/test_bookmarks_html.js
@@ -201,20 +201,20 @@ function testCanonicalBookmarks(aFolder)
   var query = histsvc.getNewQuery();
   query.setFolders([aFolder], 1);
   var result = histsvc.executeQuery(query, histsvc.getNewQueryOptions());
   var rootNode = result.root;
   rootNode.containerOpen = true;
 
   // 6-2: the toolbar folder and unfiled bookmarks folder imported to the
   // corresponding places folders
-  do_check_eq(rootNode.childCount, 4);
+  do_check_eq(rootNode.childCount, DEFAULT_BOOKMARKS_ON_MENU + 1);
 
   // get test folder
-  var testFolder = rootNode.getChild(3);
+  var testFolder = rootNode.getChild(DEFAULT_BOOKMARKS_ON_MENU);
   do_check_eq(testFolder.type, testFolder.RESULT_TYPE_FOLDER);
   do_check_eq(testFolder.title, "test");
 
   // add date 
   do_check_eq(bmsvc.getItemDateAdded(testFolder.itemId)/1000000, 1177541020);
   // last modified
   do_check_eq(bmsvc.getItemLastModified(testFolder.itemId)/1000000, 1177541050);
 
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -26,16 +26,18 @@
 <!ENTITY  bookmarkThisTab.accesskey          "B">
 <!ENTITY  bookmarkAllTabs.label              "Bookmark All Tabs…">
 <!ENTITY  bookmarkAllTabs.accesskey          "T">
 <!ENTITY  undoCloseTab.label                 "Undo Close Tab">
 <!ENTITY  undoCloseTab.accesskey             "U">
 <!ENTITY  closeTab.label                     "Close Tab">
 <!ENTITY  closeTab.accesskey                 "c">
 
+<!ENTITY  listAllTabs.label      "List all tabs">
+
 <!ENTITY tabCmd.label "New Tab">
 <!ENTITY tabCmd.accesskey "T">
 <!ENTITY tabCmd.commandkey "t">
 <!ENTITY openLocationCmd.label "Open Location…">
 <!ENTITY openLocationCmd.accesskey "L">
 <!ENTITY openFileCmd.label "Open File…">
 <!ENTITY openFileCmd.accesskey "O">
 <!ENTITY openFileCmd.commandkey "o">
@@ -204,17 +206,17 @@
 <!ENTITY viewMenu.label         "View"> 
 <!ENTITY viewMenu.accesskey       "V"> 
 <!ENTITY viewToolbarsMenu.label       "Toolbars"> 
 <!ENTITY viewToolbarsMenu.accesskey     "T"> 
 <!ENTITY viewSidebarMenu.label "Sidebar">
 <!ENTITY viewSidebarMenu.accesskey "e">
 <!ENTITY viewCustomizeToolbar.label       "Customize…"> 
 <!ENTITY viewCustomizeToolbar.accesskey     "C">
-<!ENTITY viewTabsOnTop.label            "Tabs on top">
+<!ENTITY viewTabsOnTop.label            "Tabs on Top">
 <!ENTITY viewTabsOnTop.accesskey        "T">
 
 <!ENTITY historyMenu.label "History">
 <!ENTITY historyMenu.accesskey "s">
 <!ENTITY historyUndoMenu.label "Recently Closed Tabs">
 <!-- LOCALIZATION NOTE (historyUndoWindowMenu): see bug 394759 -->
 <!ENTITY historyUndoWindowMenu.label "Recently Closed Windows">
 
--- a/browser/locales/en-US/chrome/browser/tabbrowser.dtd
+++ b/browser/locales/en-US/chrome/browser/tabbrowser.dtd
@@ -1,3 +1,2 @@
 <!ENTITY  closeTab.label         "Close Tab">
-<!ENTITY  listAllTabs.label      "List all tabs">
 <!ENTITY  newTabButton.tooltip        "Open a new tab">
--- a/browser/locales/en-US/profile/bookmarks.inc
+++ b/browser/locales/en-US/profile/bookmarks.inc
@@ -2,20 +2,16 @@
 
 # LOCALIZATION NOTE: The 'en-US' strings in the URLs will be replaced with
 # your locale code, and link to your translated pages as soon as they're 
 # live.
 
 #define bookmarks_title Bookmarks
 #define bookmarks_heading Bookmarks
 
-# LOCALIZATION NOTE (bookmarks_addons):
-# link title for https://en-US.add-ons.mozilla.com/en-US/firefox/bookmarks/
-#define bookmarks_addons Get Bookmark Add-ons
-
 #define bookmarks_toolbarfolder Bookmarks Toolbar Folder
 #define bookmarks_toolbarfolder_description Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
 
 # LOCALIZATION NOTE (getting_started):
 # link title for http://en-US.www.mozilla.com/en-US/firefox/central/
 #define getting_started Getting Started
 
 # LOCALIZATION NOTE (latest_headlines):
--- a/browser/locales/generic/extract-bookmarks.py
+++ b/browser/locales/generic/extract-bookmarks.py
@@ -56,20 +56,16 @@ template = '''#filter emptyLines
 
 # LOCALIZATION NOTE: The 'en-US' strings in the URLs will be replaced with
 # your locale code, and link to your translated pages as soon as they're 
 # live.
 
 #define bookmarks_title %s
 #define bookmarks_heading %s
 
-# LOCALIZATION NOTE (bookmarks_addons):
-# link title for https://en-US.add-ons.mozilla.com/en-US/firefox/bookmarks/
-#define bookmarks_addons %s
-
 #define bookmarks_toolbarfolder %s
 #define bookmarks_toolbarfolder_description %s
 
 # LOCALIZATION NOTE (getting_started):
 # link title for http://www.mozilla.com/en-US/firefox/central/
 #define getting_started %s
 
 # LOCALIZATION NOTE (latest_headlines):
--- a/browser/locales/generic/profile/bookmarks.html.in
+++ b/browser/locales/generic/profile/bookmarks.html.in
@@ -3,25 +3,22 @@
 <!-- This is an automatically generated file.
      It will be read and overwritten.
      DO NOT EDIT! -->
 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
 <TITLE>@bookmarks_title@</TITLE>
 <H1>@bookmarks_heading@</H1>
 
 <DL><p>
-    <DT><A HREF="https://addons.mozilla.org/@AB_CD@/firefox/bookmarks/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAFo9M%2F3AAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAPkSURBVHjaYmAAgrjyOnOGiKxqxT9%2F%2FvwHCCCGuNJKLpAo49KTL%2F5%2F%2F8PMABBADJFZFWwXnn%2F%2FDxJYeOLNf0aQ9AIg48%2Ff%2Fwwfvv1hAAggZpBAYlWdnrqJLcPVE4e%2Bsuy7%2FfH%2F%2B88%2FGdjY2Bj%2BcCqHMey6%2Ben%2F379%2F%2F%2F8B6unZ9ew%2Fy54jV249f6%2Bm9uXnX4Y9qyaoAAQAhAB7%2FwEAAAAAY3h%2BG1RdbeMMCgkB9%2Fr%2BAPL2%2FAC3vsyi5NG6YQFcbnwdZ3F44uru9gAAAQAAUjEVALPT7wDu9v4A5erz%2FgL19vr16PD6AAUHBgDu9PwA%2F%2F8AAO%2F2%2FgD0%2BP0A7e7x8QPYzsX38vj9g%2BPk6hkLFiAxy%2BP4AeHj5%2FXFtp9GonxaagII7AawXyprpf%2F%2FZ5L5%2Fe%2Fv9%2B%2Fff91ZN7nrG0icJSqrkknJxHm1h5Nl0J8%2F%2Fxg%2B%2FwDa%2Febzv39%2FWKQ2TG97ycIvq%2Bvn52oVxMHGxHDj8RcGQT4uEGZyCct98e3LL3YmJ2enNYxAi%2B48%2B8QQaizGIMLFBLaSlYWZgYWDWZaJhY2V%2BcvPfwz%2BeiIMf%2F%2F%2BY9CV4GAQ42Zh%2BPPvP8O%2Fv%2F%2BZmG7cff7u49c%2FDNtufGZgYmJiOHLvG8Pt1z8Yfv3%2Bz%2FDn19%2B3TCd2LNV7%2F%2FU3w7vPvxkWnHzDcOPFd4ZvQBPv3L79aM%2BS3nfMN88d%2BfyXkW0Lq6BiGAs7J8fHT9%2F%2FXTy%2BY82Lp0cdb5889hcgQJNU85JYFMXP%2B5aHqRmmZJ9kKMGAEBgtDCYYY6BFa%2BlrPc6yRf0LYYtZzG4YaNGibUNJVLuIcBNUTLMQM8ZoppdiaXnf9Xlf5z4ounDu4p57f%2Ff8Pt50SH9ZEfUuLehy93yMRBNroVAg6PV2yBbO9c94tK5v7suF3%2FlMs1o8oU27ltvIMic7fJv7uuqLJGa2UpPxlCILICBtGz1pYWooakeoDaTFgBtNWm04zl%2Fkbs53FnZ%2FZO%2BldGbFP5aaP50cj41pigi8XFjF2zp8ivpgsFMFHp0GgrQZL4DuYGCE6f3pzoBnUwRB8sYi4QGKHf7b5d8HiHWpMBsPvLKDeFiHmVEPBN0yMJyMIUhfb6gXbMkr4xtq1J6Z36eLpmiDH508LNShbDzB4kTIATguNsBqA1CHElJDhGdCGWsDkYY%2FTJh3lUelu384yTlzrtgDWVaggvG8qhDnYcEwwWi0wET%2FTNTh9Gh%2FvVn7v%2B2I%2BHlpWXS59ORgfOr7UGRkVNMUAWPtCMnHdbjjATFNKJeKpdLZYQY0crDzLUvfbHxdqfllj6a7p2VVjUqyGhYwPpZFqxYlf6hZ%2F7X3c736%2Fv4LV1blv94gEvsAAAAASUVORK5CYII%3D" ID="rdf:#$CnoJ1">@bookmarks_addons@</A>
-    <HR>
     <DT><H3 PERSONAL_TOOLBAR_FOLDER="true" ID="rdf:#$FvPhC3">@bookmarks_toolbarfolder@</H3>
 <DD>@bookmarks_toolbarfolder_description@
     <DL><p>
         <DT><A HREF="http://www.mozilla.com/@AB_CD@/firefox/central/" ID="rdf:#$GvPhC3">@getting_started@</A>
         <DT><A HREF="http://fxfeeds.mozilla.com/@AB_CD@/firefox/livebookmarks/" FEEDURL="http://fxfeeds.mozilla.com/@AB_CD@/firefox/headlines.xml" ID="rdf:#$HvPhC3">@latest_headlines@</A>
     </DL><p>
-    <HR>
     <DT><H3 ID="rdf:#$ZvPhC3">@firefox_heading@</H3>
     <DL><p>
         <DT><A HREF="http://www.mozilla.com/@AB_CD@/firefox/help/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$22iCK1">@firefox_help@</A>
         <DT><A HREF="http://www.mozilla.com/@AB_CD@/firefox/customize/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$32iCK1">@firefox_customize@</A>
         <DT><A HREF="http://www.mozilla.com/@AB_CD@/firefox/community/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$42iCK1">@firefox_community@</A>
         <DT><A HREF="http://www.mozilla.com/@AB_CD@/firefox/about/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">@firefox_about@</A>
     </DL><p>
 </DL><p>
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -1122,24 +1122,32 @@ statusbarpanel#statusbar-display {
 /* Tabs */
 #TabsToolbar {
   -moz-appearance: none;
   min-height: 0;
   padding: 0;
   -moz-box-shadow: ThreeDShadow 0 -1px inset;
 }
 
-.tabbrowser-tab {
-  border: none !important;
-  padding: 0 2px;
+#TabsToolbar > toolbarbutton,
+#TabsToolbar > toolbarpaletteitem > toolbarbutton {
   margin-bottom: 1px;
 }
 
+.tabbrowser-tab {
+  padding: 0 2px 2px;
+  margin-bottom: 1px;
+  min-height: 25px; /* reserve space for the sometimes hidden close button */
+}
+
 .tabbrowser-tab[selected="true"] {
-  margin-bottom: 0px;
+  margin-bottom: 0;
+  padding-top: 2px; /* compensates the top margin of background tabs */
+  padding-bottom: 3px; /* compensates the bottom margin of background tabs */
+  min-height: 28px;
 }
 
 .tab-icon-image {
   width: 16px;
   height: 16px;
   -moz-margin-start: 1px;
   -moz-margin-end: 4px;
   list-style-image: url("chrome://global/skin/icons/folder-item.png");
@@ -1211,56 +1219,57 @@ statusbarpanel#statusbar-display {
 .tab-drop-indicator {
   list-style-image: url(chrome://browser/skin/tabbrowser/tabDragIndicator.png);
 }
 
 /* In-tab close button */
 .tab-close-button > .toolbarbutton-icon {
   /* XXX Buttons have padding in widget/ that we don't want here but can't override with good CSS, so we must
      use evil CSS to give the impression of smaller content */
-  margin: -3px !important;
+  margin: -4px;
 }
 
 .tab-close-button {
-  padding: 0px;
-  border: none;
+  padding: 0;
   list-style-image: url("moz-icon://stock/gtk-close?size=menu");
 }
 
 .tabbrowser-tab[selected="true"] > .tab-close-button {
   /* Make this button focusable so clicking on it will not focus the tab while
      it's getting closed */
   -moz-user-focus: normal;
 }
 
 .tab-close-button:focus {
   outline: none !important;
 }
 
 /* Tabstrip new tab button */
-.tabs-newtab-button {
+.tabs-newtab-button,
+#TabsToolbar > #new-tab-button ,
+#TabsToolbar > #wrapper-new-tab-button > #new-tab-button {
   list-style-image: url("moz-icon://stock/gtk-add?size=menu");
-  border: none;
+  -moz-image-region: auto;
   margin-bottom: 1px;
 }
 
-.tabbrowser-arrowscrollbox > .tabs-newtab-button {
+.tabs-newtab-button {
   width: 32px;
 }
 
-.tabs-newtab-button > .toolbarbutton-icon {
+.tabs-newtab-button > .toolbarbutton-icon,
+#TabsToolbar > #new-tab-button > .toolbarbutton-icon,
+#TabsToolbar > #wrapper-new-tab-button > #new-tab-button > .toolbarbutton-icon {
   margin-top: -2px;
   margin-bottom: -2px;
 }
 
 /* Tabstrip close button */
 .tabs-closebutton {
   list-style-image: url("moz-icon://stock/gtk-close?size=menu");
-  border: none;
-  margin-bottom: 1px;
 }
 
 .tabs-closebutton > .toolbarbutton-icon {
   /* XXX Buttons have padding in widget/ that we don't want here but can't override with good CSS, so we must
      use evil CSS to give the impression of smaller content */
   margin: -2px;
 }
 
@@ -1277,30 +1286,26 @@ statusbarpanel#statusbar-display {
   -moz-border-radius: 4px;
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-down[notifybgtab] {
   -moz-box-shadow: 0 0 7px 5px Highlight inset;
   -moz-transition: none;
 }
 
-.tabs-alltabs-button {
-  margin-bottom: 1px;
-}
-
-.tabs-alltabs-button > .toolbarbutton-icon {
+#alltabs-button > .toolbarbutton-icon {
   list-style-image: url("chrome://browser/skin/tabbrowser/alltabs.png");
   margin: 2px 0 1px;
 }
 
-.tabs-alltabs-button[type="menu"] > .toolbarbutton-menu-dropmarker {
+#alltabs-button[type="menu"] > .toolbarbutton-menu-dropmarker {
   margin-bottom: -2px;
 }
 
-.tabs-alltabs-button[type="menu"] > .toolbarbutton-icon {
+#alltabs-button[type="menu"] > .toolbarbutton-icon {
   display: none;
 }
 
 /* All tabs menupopup */
 .alltabs-item > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/icons/folder-item.png");
   -moz-image-region: rect(0px, 16px, 16px, 0px);
 }
@@ -1309,17 +1314,17 @@ statusbarpanel#statusbar-display {
   font-weight: bold;
 }
 
 .alltabs-item[busy] > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
 }
 
 /* Sidebar */
-#sidebar-box .tabs-closebutton {
+#sidebar-header > .tabs-closebutton {
   margin-bottom: 0px !important;
   padding: 0px 2px 0px 2px !important;
 }
 
 #sidebar-throbber[loading="true"] {
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
   -moz-margin-end: 4px;
 }
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -69,17 +69,17 @@
 
 .tabbrowser-tab:-moz-lwtheme[selected="true"] {
   background-color: transparent !important;
 }
 .tabbrowser-tab:-moz-lwtheme:not([selected="true"]):not(:hover) > .tab-text {
   opacity: .8;
 }
 
-.tabbrowser-arrowscrollbox:-moz-lwtheme > .tabs-newtab-button {
+.tabs-newtab-button:-moz-lwtheme {
   width: auto;
   -moz-box-flex: 1;
   -moz-box-pack: start;
   border-style: none;
   background: none;
 }
 
 .tabbrowser-tab:-moz-lwtheme-brighttext {
@@ -90,27 +90,33 @@
 
 .tabbrowser-tab:-moz-lwtheme-brighttext[selected="true"] {
   -moz-border-left-colors: rgba(255,255,255,.6) rgba(255,255,255,.2);
   -moz-border-bottom-colors: rgba(255,255,255,.6) rgba(255,255,255,.2);
   -moz-border-right-colors: rgba(255,255,255,.6) rgba(255,255,255,.2);
 }
 
 .tabs-newtab-button:-moz-lwtheme-darktext,
-.tabs-alltabs-button:-moz-lwtheme-darktext,
-.tabbrowser-tabs:-moz-lwtheme-darktext > .tabs-closebutton,
+#TabsToolbar > #new-tab-button:-moz-lwtheme-darktext,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button:-moz-lwtheme-darktext,
+#TabsToolbar > #alltabs-button:-moz-lwtheme-darktext,
+#TabsToolbar > toolbarpaletteitem > #alltabs-button:-moz-lwtheme-darktext,
+#tabs-closebutton:-moz-lwtheme-darktext,
 .tabbrowser-arrowscrollbox:-moz-lwtheme-darktext > .scrollbutton-up,
 .tabbrowser-arrowscrollbox:-moz-lwtheme-darktext > .scrollbutton-down,
 .tabbrowser-tab:-moz-lwtheme-darktext:not([selected="true"]) {
   -moz-box-shadow: inset 0 1px 0 rgba(50,50,50,.5);
 }
 
 .tabs-newtab-button:-moz-lwtheme-brighttext,
-.tabs-alltabs-button:-moz-lwtheme-brighttext,
-.tabbrowser-tabs:-moz-lwtheme-brighttext > .tabs-closebutton,
+#TabsToolbar > #new-tab-button:-moz-lwtheme-brighttext,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button:-moz-lwtheme-brighttext,
+#TabsToolbar > #alltabs-button:-moz-lwtheme-brighttext,
+#TabsToolbar > toolbarpaletteitem > #alltabs-button:-moz-lwtheme-brighttext,
+#tabs-closebutton:-moz-lwtheme-brighttext,
 .tabbrowser-arrowscrollbox:-moz-lwtheme-brighttext > .scrollbutton-up,
 .tabbrowser-arrowscrollbox:-moz-lwtheme-brighttext > .scrollbutton-down,
 .tabbrowser-tab:-moz-lwtheme-brighttext:not([selected="true"]) {
   -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.6);
 }
 
 #main-window {
   -moz-appearance: none;
@@ -1037,30 +1043,21 @@ richlistitem[type="action"][actiontype="
 #editBookmarkPanelBottomButtons {
   margin-right: -30px;
 }
 
 /**** HUD style buttons ****/
 
 .editBookmarkPanelHeaderButton,
 .editBookmarkPanelBottomButton {
-  -moz-appearance: none;
-  background: url("chrome://browser/skin/hud-style-button-middle-background.png") repeat-x #464646 center center;
-  border-width: 3px;
-  border-style: solid;
-  -moz-border-radius: 20px;
-  -moz-border-top-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
-  -moz-border-right-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
-  -moz-border-bottom-colors: rgba(128,128,128,0.35) rgba(0,0,0,0.5) rgba(255,255,255,0.15);
-  -moz-border-left-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
+  @hudButton@
   padding: 0 9px;
   margin: 6px;
   min-width: 79px;
   min-height: 22px;
-  color: #ffffff;
 }
 
 .editBookmarkPanelHeaderButton:hover:active,
 .editBookmarkPanelBottomButton:hover:active {
   background-color: #86888B;
 }
 
 .editBookmarkPanelHeaderButton:focus,
@@ -1125,28 +1122,21 @@ richlistitem[type="action"][actiontype="
   -moz-outline-radius: 1px;
 }
 
 #editBMPanel_newFolderButton .button-text {
   display: none !important;
 }
 
 #editBMPanel_folderMenuList {
-  -moz-appearance: none;
-  background: url("chrome://browser/skin/hud-style-button-middle-background.png") repeat-x #464646 center center;
-  border: 3px solid;
+  @hudButton@
   -moz-border-radius: 5px;
-  -moz-border-top-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
-  -moz-border-right-colors: rgba(53,53,53,1) rgba(53,53,53,1) rgba(162,162,162,1);
-  -moz-border-bottom-colors: rgba(128,128,128,0.35) rgba(0,0,0,0.5) rgba(255,255,255,0.15);
-  -moz-border-left-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
   margin: 0 3px !important;
   min-height: 22px;
   -moz-padding-start: 2px;
-  color: #ffffff !important;
 }
 
 #editBMPanel_folderMenuList:focus {
   outline: 2px solid -moz-mac-focusring;
   outline-offset: -2px;
   -moz-outline-radius: 5px;
 }
 
@@ -1260,31 +1250,24 @@ richlistitem[type="action"][actiontype="
   color: #222222;
   background-color: #b3b3b3;
 }
 
 /**** expanders ****/
 
 #editBookmarkPanel .expander-up,
 #editBookmarkPanel .expander-down {
-  -moz-appearance: none;
-  background: url("chrome://browser/skin/hud-style-button-middle-background.png") repeat-x #464646 center center;
-  border: 3px solid;
+  @hudButton@
   -moz-border-radius: 5px;
-  -moz-border-top-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
-  -moz-border-right-colors: rgba(53,53,53,1) rgba(53,53,53,1) rgba(162,162,162,1);
-  -moz-border-bottom-colors: rgba(128,128,128,0.35) rgba(0,0,0,0.5) rgba(255,255,255,0.15);
-  -moz-border-left-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
   -moz-margin-start: 4px;
   -moz-margin-end: 2px;
   padding: 0;
   -moz-padding-start: 4px;
   min-width: 10px;
   min-height: 22px;
-  color: #ffffff !important;
 }
 
 #editBookmarkPanel .expander-up:focus,
 #editBookmarkPanel .expander-down:focus {
   outline: 2px solid -moz-mac-focusring;
   outline-offset: -2px;
   -moz-outline-radius: 5px;
 }
@@ -1523,17 +1506,17 @@ toolbarbutton.chevron > .toolbarbutton-m
 .tabbrowser-tab > .tab-text {
   margin-top: 3px;
   margin-bottom: 0;
   font: message-box;
   font-weight: bold;
 }
 
 .tabbrowser-tab,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button {
+.tabs-newtab-button {
   -moz-appearance: none;
   -moz-border-radius: 0 0 6px 6px;
   color: #222;
   text-shadow: 0 1px 0 rgba(255, 255, 255, 0.4);
   margin: 0 0 1px;
   padding: 0 5px;
   border-style: none solid solid;
   border-width: 3px;
@@ -1542,17 +1525,17 @@ toolbarbutton.chevron > .toolbarbutton-m
   -moz-border-left-colors: rgba(0, 0, 0, .08) rgba(0, 0, 0, .17) rgba(180, 180, 180, .29);
   -moz-background-clip: padding;
   min-width: 1px !important;
   text-align: center;
   height: 24px;
   background-image: url(chrome://browser/skin/tabbrowser/tab-bkgnd.png);
 }
 
-.tabbrowser-arrowscrollbox > .tabs-newtab-button {
+.tabs-newtab-button {
   width: 34px;
   padding-top: 1px;
 }
 
 .tabs-newtab-button > .toolbarbutton-icon:-moz-window-inactive {
   opacity: 0.75;
 }
 
@@ -1600,16 +1583,21 @@ toolbarbutton.chevron > .toolbarbutton-m
 #TabsToolbar:not(:-moz-lwtheme) {
   background: #9B9B9B url("chrome://browser/skin/tabbrowser/tabbrowser-tabs-bkgnd.png") repeat-x;
 }
 
 #TabsToolbar:not(:-moz-lwtheme):-moz-window-inactive {
   background-color: #e2e2e2;
 }
 
+#TabsToolbar > toolbarbutton,
+#TabsToolbar > toolbarpaletteitem > toolbarbutton {
+  padding: 0;
+}
+
 .tabbrowser-tabs {
   -moz-box-align: stretch;
   height: 25px;
 }
 
 .tabbrowser-tabs:not([overflow="true"]) {
   -moz-margin-start: 3px;
 }
@@ -1707,65 +1695,81 @@ toolbarbutton.chevron > .toolbarbutton-m
   background-color: transparent !important; 
 }
 
 
 /**
  * Tabstrip New Tab & All Tabs Buttons
  */
 
-.tabbrowser-tabs > .tabs-newtab-button,
-.tabs-alltabs-button {
+#TabsToolbar > #new-tab-button,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button,
+#TabsToolbar > #alltabs-button,
+#TabsToolbar > toolbarpaletteitem > #alltabs-button {
   -moz-border-start: 2px solid;
   -moz-border-end: none;
   -moz-border-left-colors: rgba(0,0,0,0.25) rgba(255,255,255,0.15);
   -moz-border-right-colors: rgba(0,0,0,0.25) rgba(255,255,255,0.15);
   margin: 0;
+}
+
+.tabs-newtab-button > .toolbarbutton-icon,
+#TabsToolbar > #new-tab-button > .toolbarbutton-icon,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button > .toolbarbutton-icon,
+#TabsToolbar > #alltabs-button > .toolbarbutton-icon,
+#TabsToolbar > toolbarpaletteitem > #alltabs-button > .toolbarbutton-icon {
   padding: 0;
 }
-.tabs-newtab-button > .toolbarbutton-icon,
-.tabs-alltabs-button > .toolbarbutton-icon {
-  padding: 0;
-}
-.tabs-newtab-button {
+
+.tabs-newtab-button,
+#TabsToolbar > #new-tab-button,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button {
   list-style-image: url(chrome://browser/skin/tabbrowser/newtab.png);
   -moz-image-region: rect(0, 18px, 20px, 0);
 }
-.tabs-newtab-button:hover {
+
+.tabs-newtab-button:hover,
+#TabsToolbar > #new-tab-button:hover {
   -moz-image-region: rect(0, 36px, 20px, 18px);
 }
-.tabs-newtab-button:hover:active {
+
+.tabs-newtab-button:hover:active,
+#TabsToolbar > #new-tab-button:hover:active {
   -moz-image-region: rect(0, 54px, 20px, 36px);
 }
-.tabs-alltabs-button {
+
+#alltabs-button {
   list-style-image: url(chrome://browser/skin/tabbrowser/alltabs-box-bkgnd-icon.png);
   -moz-image-region: rect(0, 22px, 20px, 0);
 }
-.tabs-alltabs-button:hover {
+
+#alltabs-button:hover {
   -moz-image-region: rect(0, 44px, 20px, 22px);
 }
-.tabs-alltabs-button[type="menu"][open="true"],
-.tabs-alltabs-button:hover:active {
+
+#alltabs-button[type="menu"][open="true"],
+#alltabs-button:hover:active {
   -moz-image-region: rect(0, 66px, 20px, 44px);
 }
-.tabbrowser-tabs > .tabs-newtab-button:hover,
-.tabs-alltabs-button:hover {
+
+#TabsToolbar > #new-tab-button:hover,
+#TabsToolbar > #alltabs-button:hover {
   background-color: rgba(0,0,0,0.10);
 }
-.tabbrowser-tabs > .tabs-newtab-button:hover:active,
-.tabs-alltabs-button:hover:active {
+
+#TabsToolbar > #new-tab-button:hover:active,
+#TabsToolbar > #alltabs-button:hover:active {
   background-color: rgba(0,0,0,0.20);
 }
 
-.tabs-alltabs-button[type="menu"] > .toolbarbutton-menu-dropmarker,
-.tabs-alltabs-button > .toolbarbutton-text {
+#alltabs-button[type="menu"] > .toolbarbutton-menu-dropmarker {
   display: none;
 }
 
-.tabs-alltabs-button > .toolbarbutton-icon {
+#alltabs-button > .toolbarbutton-icon {
   -moz-margin-end: 2px;
 }
 
 /* All Tabs Menupopup */
 .alltabs-item > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/tree/item.png");
 }
 
@@ -1894,28 +1898,20 @@ toolbarbutton.chevron > .toolbarbutton-m
 }
 
 #identity-popup-content-box {
   margin-top: 4px;
 }
 
 /* Popup Buttons */
 #identity-popup-more-info-button {
-  -moz-appearance: none;
-  background: url("chrome://browser/skin/hud-style-button-middle-background.png") repeat-x #464646 center center;
-  border: 3px solid;
-  -moz-border-top-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
-  -moz-border-right-colors: rgba(53,53,53,1) rgba(53,53,53,1) rgba(162,162,162,1);
-  -moz-border-bottom-colors: rgba(128,128,128,0.35) rgba(0,0,0,0.5) rgba(255,255,255,0.15);
-  -moz-border-left-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4);
-  -moz-border-radius: 20px;
+  @hudButton@
   padding: 1px 9px;
   margin: 10px 0 0;
   min-height: 0px;
-  color: #fff;	
 }
 
 #identity-popup-more-info-button > .button-box > .button-text {
   margin: 0 !important;
 }
 
 #identity-popup-more-info-button:hover:active {
   background-color: #86888B;
--- a/browser/themes/pinstripe/browser/shared.inc
+++ b/browser/themes/pinstripe/browser/shared.inc
@@ -1,1 +1,3 @@
 %include ../../../../toolkit/themes/pinstripe/global/shared.inc
+
+%define hudButton -moz-appearance: none; background: url("chrome://browser/skin/hud-style-button-middle-background.png") repeat-x #464646 center center; border: 3px solid; -moz-border-top-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4); -moz-border-right-colors: rgba(53,53,53,1) rgba(53,53,53,1) rgba(162,162,162,1); -moz-border-bottom-colors: rgba(128,128,128,0.35) rgba(0,0,0,0.5) rgba(255,255,255,0.15); -moz-border-left-colors: rgba(0,0,0,0.35) rgba(26,26,26,0.5) rgba(255,255,255,0.4); -moz-border-radius: 20px; color: #fff;
--- a/browser/themes/winstripe/browser/browser-aero.css
+++ b/browser/themes/winstripe/browser/browser-aero.css
@@ -44,34 +44,29 @@
     background-color: rgba(255,255,255,.898);
   }
 
   #urlbar[focused="true"],
   .searchbar-textbox[focused="true"] {
     background-color: white;
   }
 
-  .tabbrowser-tab:not(:-moz-lwtheme),
-  .tabbrowser-arrowscrollbox > .tabs-newtab-button:not(:-moz-lwtheme) {
+  .tabbrowser-tab:not(:-moz-lwtheme):not([selected="true"]),
+  .tabs-newtab-button:not(:-moz-lwtheme) {
     background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                  rgba(255,255,255,.4) 1px, rgba(255,255,255,.4));
     text-shadow: 0 1px 0 rgba(255,255,255,.4);
   }
 
   .tabbrowser-tab:not(:-moz-lwtheme):not([selected="true"]):hover,
-  .tabbrowser-arrowscrollbox > .tabs-newtab-button:not(:-moz-lwtheme):hover {
+  .tabs-newtab-button:not(:-moz-lwtheme):hover {
     background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                  rgba(255,255,255,.6) 1px, rgba(255,255,255,.6));
   }
 
-  .tabbrowser-tab[selected="true"]:not(:-moz-lwtheme) {
-    background-image: -moz-linear-gradient(left, transparent, transparent 1px,
-                                                 white 1px, white);
-  }
-
   #allTabs-panel,
   #ctrlTab-panel {
     background: transparent;
     -moz-appearance: -moz-win-glass;
     -moz-border-radius: 0;
     border: none;
     font: normal 1.2em "Segoe UI";
     color: black;
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -301,16 +301,28 @@ toolbarbutton[type="menu-button"][open="
   height: 18px;
 }
 
 toolbar[mode="full"] .toolbarbutton-1,
 toolbar[mode="full"] .toolbarbutton-menubutton-button {
   min-width: 57px;
 }
 
+#TabsToolbar > .toolbarbutton-1,
+#TabsToolbar > toolbarpaletteitem > .toolbarbutton-1 {
+  -moz-appearance: toolbarbutton;
+  margin: 0;
+  padding: 3px;
+  border: none !important;
+  color: inherit !important;
+  background: transparent !important;
+  text-shadow: inherit !important;
+  -moz-box-shadow: none !important;
+}
+
 /* unified back/forward button */
 
 #back-button {
   -moz-image-region: rect(0, 18px, 18px, 0);
   -moz-margin-end: 0;
 }
 
 #forward-button {
@@ -950,63 +962,69 @@ richlistitem[type="action"][actiontype="
 }
 
 .tabbrowser-tabs:not([overflow="true"]) {
   -moz-margin-start: 3px;
 }
 
 /* Tabs */
 .tabbrowser-tab,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button {
+.tabs-newtab-button {
   -moz-appearance: none;
   background: -moz-linear-gradient(left, transparent, transparent 1px,
-                                         rgba(255,255,255,.15) 1px, rgba(255,255,255,.15));
+                                         rgba(50%,50%,50%,.1) 1px, rgba(50%,50%,50%,.1));
   background-position: -6px 0;
   -moz-background-size: 200%;
   margin: 0;
   padding: 0;
   -moz-border-image: url(tabbrowser/tab.png) 3 5 3 6 / 3px 5px 3px 6px;
   -moz-border-radius: 6px 4px 0 0;
 }
 
 .tabbrowser-tab:hover,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button:hover {
+.tabs-newtab-button:hover {
   background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                rgba(255,255,255,.4) 1px, rgba(255,255,255,.4));
 }
 
 .tabbrowser-tab:-moz-lwtheme-brighttext,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button:-moz-lwtheme-brighttext {
+.tabs-newtab-button:-moz-lwtheme-brighttext {
   background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                rgba(40%,40%,40%,.6) 1px, rgba(40%,40%,40%,.6));
 }
 
 .tabbrowser-tab:-moz-lwtheme-brighttext:not([selected="true"]):hover,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button:-moz-lwtheme-brighttext:hover {
+.tabs-newtab-button:-moz-lwtheme-brighttext:hover {
   background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                rgba(60%,60%,60%,.6) 1px, rgba(60%,60%,60%,.6));
 }
 
 .tabbrowser-tab:-moz-lwtheme-darktext,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button:-moz-lwtheme-darktext {
+.tabs-newtab-button:-moz-lwtheme-darktext {
   background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                rgba(255,255,255,.4) 1px, rgba(255,255,255,.4));
 }
 
 .tabbrowser-tab:-moz-lwtheme-darktext:not([selected="true"]):hover,
-.tabbrowser-arrowscrollbox > .tabs-newtab-button:-moz-lwtheme-darktext:hover {
+.tabs-newtab-button:-moz-lwtheme-darktext:hover {
   background-image: -moz-linear-gradient(left, transparent, transparent 1px,
                                                rgba(255,255,255,.6) 1px, rgba(255,255,255,.6));
 }
 
 .tabbrowser-tab[selected="true"] {
-  background-image: -moz-linear-gradient(left, transparent, transparent 1px,
-                                               rgba(255,255,255,.4) 1px, rgba(255,255,255,.4)),
+  background-image: -moz-linear-gradient(left, transparent, transparent 1px, white 1px, white);
+  color: black;
+}
+
+#navigator-toolbox[tabsontop="true"] > #TabsToolbar > #tabbrowser-tabs > .tabbrowser-tab[selected="true"] {
+  background-image: -moz-radial-gradient(center top, white, rgba(255,255,255,0) 60%),
                     -moz-linear-gradient(left, transparent, transparent 1px,
                                                -moz-dialog 1px, -moz-dialog);
+  background-position: center center, -6px 0;
+  color: -moz-dialogText;
 }
 
 .tabbrowser-tab:-moz-lwtheme[selected="true"] {
   text-shadow: none;
 }
 
 .tabbrowser-tab:-moz-lwtheme:not([selected="true"]) {
   color: inherit;
@@ -1096,24 +1114,28 @@ richlistitem[type="action"][actiontype="
   -moz-user-focus: normal;
 }
 
 .tab-close-button:focus {
   outline: none !important;
 }
 
 /* Tab scrollbox arrow, tabstrip new tab and all-tabs buttons */
-.tabbrowser-arrowscrollbox > .scrollbutton-up:-moz-system-metric(touch-enabled),
-.tabbrowser-arrowscrollbox > .scrollbutton-down:-moz-system-metric(touch-enabled),
-.tabs-alltabs-button:-moz-system-metric(touch-enabled) {
-  min-width: .81cm;
-}
 
-.tabs-newtab-button:-moz-system-metric(touch-enabled) {
-  min-width: 1cm;
+@media all and (-moz-touch-enabled) {
+  .tabbrowser-arrowscrollbox > .scrollbutton-up,
+  .tabbrowser-arrowscrollbox > .scrollbutton-down,
+  #TabsToolbar > toolbarbutton,
+  #TabsToolbar > toolbarpaletteitem > toolbarbutton {
+    min-width: .81cm;
+  }
+
+  .tabs-newtab-button {
+    min-width: 1cm;
+  }
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-up,
 .tabbrowser-arrowscrollbox > .scrollbutton-down {
   -moz-image-region: rect(0, 15px, 17px, 0);
   margin: 0;
   padding-top: 0;
   padding-bottom: 0;
@@ -1151,54 +1173,63 @@ richlistitem[type="action"][actiontype="
   background-color: Highlight;
   -moz-transition: none;
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-down:-moz-locale-dir(rtl) {
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-left.png");
 }
 
-.tabs-newtab-button {
+.tabs-newtab-button > .toolbarbutton-icon,
+#TabsToolbar > #new-tab-button > .toolbarbutton-icon,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button > .toolbarbutton-icon,
+#alltabs-button > .toolbarbutton-icon {
+  width: auto;
+  height: auto;
+}
+
+.tabs-newtab-button,
+#TabsToolbar > #new-tab-button,
+#TabsToolbar > toolbarpaletteitem > #new-tab-button {
   list-style-image: url(chrome://browser/skin/tabbrowser/newtab.png);
   -moz-image-region: rect(0, 16px, 18px, 0);
 }
 
+.tabs-newtab-button {
+  width: 31px;
+}
+
 .tabs-newtab-button:hover:active {
   -moz-image-region: rect(0, 32px, 18px, 16px);
 }
 
-.tabbrowser-arrowscrollbox > .tabs-newtab-button {
-  width: 31px;
-}
-
-.tabs-alltabs-button > .toolbarbutton-text {
-  display: none;
-}
-
-.tabs-alltabs-button > .toolbarbutton-icon {
+#alltabs-button {
   list-style-image: url("chrome://browser/skin/tabbrowser/alltabs.png");
   -moz-image-region: rect(0, 14px, 17px, 0);
 }
 
-.tabs-alltabs-button:hover:active > .toolbarbutton-icon {
+#alltabs-button:hover:active {
   -moz-image-region: rect(0, 28px, 17px, 14px);
 }
 
-.tabs-alltabs-button[type="menu"] > .toolbarbutton-icon {
+#alltabs-button[type="menu"] {
   list-style-image: url("chrome://browser/skin/mainwindow-dropdown-arrow.png");
-  margin: 3px 0;
   -moz-image-region: rect(0, 13px, 11px, 0);
 }
 
-.tabs-alltabs-button[type="menu"] > .toolbarbutton-menu-dropmarker {
+#alltabs-button[type="menu"] > .toolbarbutton-icon {
+  margin: 3px 0;
+}
+
+#alltabs-button[type="menu"] > .toolbarbutton-menu-dropmarker {
   display: none;
 }
 
-.tabs-alltabs-button[type="menu"]:hover:active > .toolbarbutton-icon,
-.tabs-alltabs-button[type="menu"][open="true"] > .toolbarbutton-icon {
+#alltabs-button[type="menu"]:hover:active,
+#alltabs-button[type="menu"][open="true"] {
   -moz-image-region: rect(0, 26px, 11px, 13px);
 }
 
 /* All tabs menupopup */
 .alltabs-item > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/icons/folder-item.png");
   -moz-image-region: rect(0px, 16px, 16px, 0px);
 }
@@ -1230,21 +1261,16 @@ richlistitem[type="action"][actiontype="
 .tabs-closebutton:hover {
   -moz-image-region: rect(0px, 28px, 14px, 14px);
 }
 
 .tabs-closebutton:hover:active {
   -moz-image-region: rect(0px, 42px, 14px, 28px);
 }
 
-.tabbrowser-tabs > .tabs-closebutton {
-  margin: 0;
-  padding: 4px 2px 2px;
-}
-
 #sidebar-header > .tabs-closebutton {
   list-style-image: url("chrome://global/skin/icons/closeSidebar.png");
 }
 
 toolbarbutton.chevron {
   list-style-image: url("chrome://global/skin/toolbar/chevron.gif") !important;
 }
 
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -358,16 +358,18 @@ GNU_LD		= @GNU_LD@
 GNU_CC		= @GNU_CC@
 GNU_CXX		= @GNU_CXX@
 HAVE_GCC3_ABI	= @HAVE_GCC3_ABI@
 INTEL_CC	= @INTEL_CC@
 INTEL_CXX	= @INTEL_CXX@
 
 STL_FLAGS		= @STL_FLAGS@
 WRAP_STL_INCLUDES	= @WRAP_STL_INCLUDES@
+MOZ_MSVC_STL_WRAP__Throw= @MOZ_MSVC_STL_WRAP__Throw@
+MOZ_MSVC_STL_WRAP__RAISE= @MOZ_MSVC_STL_WRAP__RAISE@
 
 HOST_CC		= @HOST_CC@
 HOST_CXX	= @HOST_CXX@
 HOST_CFLAGS	= @HOST_CFLAGS@
 HOST_CXXFLAGS	= @HOST_CXXFLAGS@
 HOST_OPTIMIZE_FLAGS = @HOST_OPTIMIZE_FLAGS@
 HOST_NSPR_MDCPUCFG = @HOST_NSPR_MDCPUCFG@
 HOST_AR		= @HOST_AR@
--- a/config/stl-headers
+++ b/config/stl-headers
@@ -15,14 +15,15 @@
 new
 
 # FIXME: these headers haven't been reviewed yet, but we use them
 # unsafely in Gecko, so we might as well prevent them from
 # throwing exceptions
 algorithm
 deque
 iostream
+limits
 list
 map
 memory
 stack
 string
 vector
--- a/configure.in
+++ b/configure.in
@@ -708,38 +708,66 @@ EOF
                 AC_TRY_COMPILE([#include <exception>],
                             [std::_Throw(std::exception()); return 0;],
                             ac_cv_have_std__Throw="yes",
                             ac_cv_have_std__Throw="no")
                 CXXFLAGS="$_SAVE_CXXFLAGS"
                 AC_LANG_RESTORE
             ])
 
-        if test "$ac_cv_have_std__Throw" = "no"; then
-          AC_MSG_ERROR([Your MSVC/SDK doesn't export std::_Throw.  This breaks assumptions in Gecko.  Please file a bug describing this error along with your build configuration.])
+        if test "$ac_cv_have_std__Throw" == "yes"; then
+            AC_CACHE_CHECK(for |class __declspec(dllimport) exception| bug,
+                           ac_cv_have_dllimport_exception_bug,
+                [
+                    AC_LANG_SAVE
+                    AC_LANG_CPLUSPLUS
+                    _SAVE_CXXFLAGS="$CXXFLAGS"
+                    CXXFLAGS="${CXXFLAGS} -D_HAS_EXCEPTIONS=0"
+                    AC_TRY_LINK([#include <vector>],
+                                [std::vector<int> v; return v.at(1);],
+                                ac_cv_have_dllimport_exception_bug="no",
+                                ac_cv_have_dllimport_exception_bug="yes")
+                    CXXFLAGS="$_SAVE_CXXFLAGS"
+                    AC_LANG_RESTORE
+                ])
+            if test "$ac_cv_have_dllimport_exception_bug" = "no"; then
+                WRAP_STL_INCLUDES=1
+                MOZ_MSVC_STL_WRAP__Throw=1
+                AC_DEFINE(MOZ_MSVC_STL_WRAP__Throw)
+            fi
+        else
+            AC_CACHE_CHECK(for overridable _RAISE,
+                           ac_cv_have__RAISE,
+                [
+                    AC_LANG_SAVE
+                    AC_LANG_CPLUSPLUS
+                    _SAVE_CXXFLAGS="$CXXFLAGS"
+                    CXXFLAGS="${CXXFLAGS} -D_HAS_EXCEPTIONS=0"
+                    AC_TRY_COMPILE([#include <xstddef>
+                                    #undef _RAISE
+                                    #define _RAISE(x) externallyDefinedFunction((x).what())
+                                    #include <vector>
+                                   ],
+                                   [std::vector<int> v; return v.at(1);],
+                                   ac_cv_have__RAISE="no",
+                                   ac_cv_have__RAISE="yes")
+                    CXXFLAGS="$_SAVE_CXXFLAGS"
+                    AC_LANG_RESTORE
+                ])
+            if test "$ac_cv_have__RAISE" = "yes"; then
+                WRAP_STL_INCLUDES=1
+                MOZ_MSVC_STL_WRAP__RAISE=1
+                AC_DEFINE(MOZ_MSVC_STL_WRAP__RAISE)
+            else
+                AC_MSG_ERROR([Gecko exception wrapping doesn't understand your your MSVC/SDK.  Please file a bug describing this error and your build configuration.])
+            fi
         fi
 
-        AC_CACHE_CHECK(for |class __declspec(dllimport) exception| bug,
-                       ac_cv_have_dllimport_exception_bug,
-            [
-                AC_LANG_SAVE
-                AC_LANG_CPLUSPLUS
-                _SAVE_CXXFLAGS="$CXXFLAGS"
-                CXXFLAGS="${CXXFLAGS} -D_HAS_EXCEPTIONS=0"
-                AC_TRY_LINK([#include <vector>],
-                            [std::vector<int> v; return v.at(1);],
-                            ac_cv_have_dllimport_exception_bug="no",
-                            ac_cv_have_dllimport_exception_bug="yes")
-                CXXFLAGS="$_SAVE_CXXFLAGS"
-                AC_LANG_RESTORE
-            ])
-
-        if test "$ac_cv_have_dllimport_exception_bug" = "no"; then
+        if test "$WRAP_STL_INCLUDES" = "1"; then
             STL_FLAGS='-D_HAS_EXCEPTIONS=0 -I$(DIST)/stl_wrappers'
-            WRAP_STL_INCLUDES=1
         fi
     else
         # Check w32api version
         _W32API_MAJOR_VERSION=`echo $W32API_VERSION | $AWK -F\. '{ print $1 }'`
         _W32API_MINOR_VERSION=`echo $W32API_VERSION | $AWK -F\. '{ print $2 }'`
         AC_MSG_CHECKING([for w32api version >= $W32API_VERSION])
         AC_TRY_COMPILE([#include <w32api.h>],
             #if (__W32API_MAJOR_VERSION < $_W32API_MAJOR_VERSION) || \
@@ -841,16 +869,18 @@ AC_SUBST(GNU_AS)
 AC_SUBST(GNU_LD)
 AC_SUBST(GNU_CC)
 AC_SUBST(GNU_CXX)
 AC_SUBST(INTEL_CC)
 AC_SUBST(INTEL_CXX)
 
 AC_SUBST(STL_FLAGS)
 AC_SUBST(WRAP_STL_INCLUDES)
+AC_SUBST(MOZ_MSVC_STL_WRAP__Throw)
+AC_SUBST(MOZ_MSVC_STL_WRAP__RAISE)
 
 dnl ========================================================
 dnl Checks for programs.
 dnl ========================================================
 AC_PROG_INSTALL
 AC_PROG_LN_S
 
 if test -z "$TINDERBOX_SKIP_PERL_VERSION_CHECK"; then
@@ -1968,16 +1998,36 @@ case "$target" in
 # Can't have force w/o an unforce.
 #    # Hack for FreeBSD 2.2
 #    if test -z "$MKSHLIB_FORCE_ALL"; then
 #	MKSHLIB_FORCE_ALL='-Wl,-Bforcearchive'
 #	MKSHLIB_UNFORCE_ALL=''
 #    fi
     ;; 
 
+ia64*-hpux*)
+    DLL_SUFFIX=".so"
+    if test ! "$GNU_CC"; then
+       DSO_LDOPTS='-b'
+       DSO_CFLAGS=""
+       DSO_PIC_CFLAGS=
+       MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_LDOPTS) -o $@'
+       MKCSHLIB='$(CC) $(CFLAGS) $(DSO_LDOPTS) -o $@'
+       CXXFLAGS="$CXXFLAGS -Wc,-ansi_for_scope,on"
+    else
+       DSO_LDOPTS='-b -E'
+       MKSHLIB='$(LD) $(DSO_LDOPTS) -o $@'
+       MKCSHLIB='$(LD) $(DSO_LDOPTS) -o $@'
+    fi
+    MOZ_FIX_LINK_PATHS=
+    SYSTEM_MAKEDEPEND=
+    AC_DEFINE(NSCAP_DISABLE_DEBUG_PTR_TYPES)
+    AC_DEFINE(_LARGEFILE64_SOURCE)
+    ;;
+
 *-hpux*)
     DLL_SUFFIX=".sl"
     if test ! "$GNU_CC"; then
     	DSO_LDOPTS='-b -Wl,+s'
     	DSO_CFLAGS=""
     	DSO_PIC_CFLAGS="+Z"
     	MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_LDOPTS) -L$(LIBXUL_DIST)/bin -o $@'
     	MKCSHLIB='$(LD) -b +s -L$(LIBXUL_DIST)/bin -o $@'
@@ -6564,16 +6614,24 @@ else
     if test "x$ac_cv_sqlite_enable_fts3" = "xno"; then
         AC_MSG_ERROR([System SQLite library is not compiled with SQLITE_ENABLE_FTS3.])
     fi
 fi
 
 AC_SUBST(MOZ_NATIVE_SQLITE)
 
 dnl ========================================================
+dnl = Enable help viewer (off by default)
+dnl ========================================================
+if test -n "$MOZ_HELP_VIEWER"; then
+     dnl Do this if defined in confvars.sh
+     AC_DEFINE(MOZ_HELP_VIEWER)
+fi
+
+dnl ========================================================
 dnl = Enable safe browsing (anti-phishing)
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(safe-browsing,
 [  --enable-safe-browsing        Enable safe browsing (anti-phishing) implementation],
     MOZ_SAFE_BROWSING=1,
     MOZ_SAFE_BROWSING= )
 if test -n "$MOZ_SAFE_BROWSING"; then
     AC_DEFINE(MOZ_SAFE_BROWSING)
new file mode 100644
--- /dev/null
+++ b/content/base/crashtests/558973.html
@@ -0,0 +1,17 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+<script type="text/javascript">
+
+var child = document.createTextNode("a");
+
+var attr = document.createAttribute("a");
+try {
+    attr.appendChild(child);
+}
+catch (e) {
+}
+
+</script>
+</head>
+</html>
--- a/content/base/crashtests/crashtests.list
+++ b/content/base/crashtests/crashtests.list
@@ -56,8 +56,9 @@ load 472593-1.html
 load 474041-1.svg
 load 483818-1.html
 load 493281-1.html
 load 493281-2.html
 load 490760-1.xhtml
 load 494810-1.html
 load 529670.html
 load 554230-1.xhtml
+load 558973.html
--- a/content/base/public/Makefile.in
+++ b/content/base/public/Makefile.in
@@ -48,16 +48,17 @@ GRE_MODULE	= 1
 EXPORTS		= \
 mozFlushType.h \
 nsIContent.h \
 nsIAttribute.h \
 nsIContentIterator.h \
 nsContentErrors.h \
 nsContentPolicyUtils.h \
 nsContentUtils.h \
+nsIContentUtils.h \
 nsIDocument.h \
 nsIDocumentObserver.h \
 nsIMutationObserver.h \
 nsINameSpaceManager.h \
 nsINode.h \
 nsINodeInfo.h \
 nsINodeList.h \
 nsIRange.h \
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -578,18 +578,20 @@ public:
   static nsAdoptingString GetLocalizedStringPref(const char *aPref);
   static nsAdoptingString GetStringPref(const char *aPref);
   static void RegisterPrefCallback(const char *aPref,
                                    PrefChangedFunc aCallback,
                                    void * aClosure);
   static void UnregisterPrefCallback(const char *aPref,
                                      PrefChangedFunc aCallback,
                                      void * aClosure);
-  static void AddBoolPrefVarCache(const char* aPref, PRBool* aVariable);
-  static void AddIntPrefVarCache(const char* aPref, PRInt32* aVariable);
+  static void AddBoolPrefVarCache(const char* aPref, PRBool* aVariable,
+                                  PRBool aDefault = PR_FALSE);
+  static void AddIntPrefVarCache(const char* aPref, PRInt32* aVariable,
+                                 PRInt32 aDefault = 0);
   static nsIPrefBranch2 *GetPrefBranch()
   {
     return sPrefBranch;
   }
 
   static nsILineBreaker* LineBreaker()
   {
     return sLineBreaker;
new file mode 100644
--- /dev/null
+++ b/content/base/public/nsIContentUtils.h
@@ -0,0 +1,56 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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
+ * Mozilla Foundation.
+ * 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 of 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 nsIContentUtils_h__
+#define nsIContentUtils_h__
+
+// C4EA618E-A3D9-4524-8EEA-E92F26FC44DB
+#define NS_ICONTENTUTILS_IID \
+{ 0xC4EA618E, 0xA3D9, 0x4524, \
+  { 0x8E, 0xEA, 0xE9, 0x2F, 0x26, 0xFC, 0x44, 0xDB } }
+
+class nsIContentUtils : public nsISupports
+{
+public:
+    NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICONTENTUTILS_IID)
+    NS_DECL_ISUPPORTS
+
+    virtual PRBool IsSafeToRunScript();
+};
+
+NS_DEFINE_STATIC_IID_ACCESSOR(nsIContentUtils, NS_ICONTENTUTILS_IID)
+
+#endif /* nsIContentUtils_h__ */
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -53,31 +53,31 @@
 #include "nsTObserverArray.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
 #include "nsNodeInfoManager.h"
 #include "nsIStreamListener.h"
 #include "nsIObserver.h"
 #include "nsGkAtoms.h"
 #include "nsAutoPtr.h"
+#include "nsPIDOMWindow.h"
 #ifdef MOZ_SMIL
 #include "nsSMILAnimationController.h"
 #endif // MOZ_SMIL
 
 class nsIContent;
 class nsPresContext;
 class nsIPresShell;
 class nsIDocShell;
 class nsStyleSet;
 class nsIStyleSheet;
 class nsIStyleRule;
 class nsICSSStyleSheet;
 class nsIViewManager;
 class nsIScriptGlobalObject;
-class nsPIDOMWindow;
 class nsIDOMEvent;
 class nsIDOMEventTarget;
 class nsIDeviceContext;
 class nsIParser;
 class nsIDOMNode;
 class nsIDOMElement;
 class nsIDOMDocumentFragment;
 class nsILineBreaker;
@@ -110,18 +110,18 @@ class Loader;
 } // namespace css
 
 namespace dom {
 class Link;
 } // namespace dom
 } // namespace mozilla
 
 #define NS_IDOCUMENT_IID      \
-{ 0x4a0c9bfa, 0xef60, 0x4bb2, \
-  { 0x87, 0x5e, 0xac, 0xdb, 0xe8, 0xfe, 0xa1, 0xb5 } }
+{ 0x56d981ce, 0x7f03, 0x4d90, \
+  { 0xb2, 0x40, 0x72, 0x08, 0xb6, 0x28, 0x73, 0x06 } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Document states
 
 // RTL locale: specific to the XUL localedir attribute
 #define NS_DOCUMENT_STATE_RTL_LOCALE              (1 << 0)
@@ -628,17 +628,20 @@ public:
    * document is truly gone. Use this object when you're trying to find a
    * content wrapper in XPConnect.
    */
   virtual nsIScriptGlobalObject* GetScopeObject() = 0;
 
   /**
    * Return the window containing the document (the outer window).
    */
-  virtual nsPIDOMWindow *GetWindow() = 0;
+  nsPIDOMWindow *GetWindow()
+  {
+    return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
+  }
 
   /**
    * Return the inner window used as the script compilation scope for
    * this document. If you're not absolutely sure you need this, use
    * GetWindow().
    */
   nsPIDOMWindow* GetInnerWindow()
   {
@@ -1343,16 +1346,19 @@ protected:
     // XXX The cleanup of mNodeInfoManager (calling DropDocumentReference and
     //     releasing it) happens in the nsDocument destructor. We'd prefer to
     //     do it here but nsNodeInfoManager is a concrete class that we don't
     //     want to expose to users of the nsIDocument API outside of Gecko.
   }
 
   nsPropertyTable* GetExtraPropertyTable(PRUint16 aCategory);
 
+  // Never ever call this. Only call GetWindow!
+  virtual nsPIDOMWindow *GetWindowInternal() = 0;
+
   // Never ever call this. Only call GetInnerWindow!
   virtual nsPIDOMWindow *GetInnerWindowInternal() = 0;
 
   /**
    * These methods should be called before and after dispatching
    * a mutation event.
    * To make this easy and painless, use the mozAutoSubtreeModified helper class.
    */
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -415,16 +415,20 @@ public:
     return InsertBefore(aNewChild, nsnull, aReturn);
   }
   nsresult RemoveChild(nsINode *aOldChild)
   {
     if (!aOldChild) {
       return NS_ERROR_NULL_POINTER;
     }
 
+    if (IsNodeOfType(eDATA_NODE)) {
+      return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
+    }
+
     PRInt32 index = IndexOf(aOldChild);
     if (index == -1) {
       // aOldChild isn't one of our children.
       return NS_ERROR_DOM_NOT_FOUND_ERR;
     }
 
     return RemoveChildAt(index, PR_TRUE);
   }
--- a/content/base/public/nsISelection.idl
+++ b/content/base/public/nsISelection.idl
@@ -42,20 +42,20 @@
 interface nsIDOMNode;
 interface nsIDOMRange;
 
 /**
  * Interface for manipulating and querying the current selected range
  * of nodes within the document.
  *
  * @status FROZEN
- * @version 1.0
+ * @version 1.1
  */
 
-[scriptable, uuid(B2C7ED59-8634-4352-9E37-5484C8B6E4E1)]
+[scriptable, uuid(24bb8c1c-407c-4a97-b652-af767d847716)]
 interface nsISelection : nsISupports
 {
     /**
      * Returns the node in which the selection begins.
      */
     readonly attribute nsIDOMNode anchorNode;
 
     /**
@@ -151,16 +151,37 @@ interface nsISelection : nsISupports
     void removeAllRanges();
 
     /**
      * Deletes this selection from document the nodes belong to.
      */
     void deleteFromDocument();
 
     /**
+     * Modifies the selection.  Note that the parameters are case-insensitive.
+     *
+     * @param alter can be one of { "move", "extend" }
+     *   - "move" collapses the selection to the end of the selection and
+     *      applies the movement direction/granularity to the collapsed
+     *      selection.
+     *   - "extend" leaves the start of the selection unchanged, and applies
+     *      movement direction/granularity to the end of the selection.
+     * @param direction can be one of { "forward", "backward", "left", "right" }
+     * @param granularity can be one of { "character", "word",
+     *                                    "line", "lineboundary" }
+     *
+     * @returns NS_ERROR_NOT_IMPLEMENTED if the granularity is "sentence",
+     * "sentenceboundary", "paragraph", "paragraphboundary", or
+     * "documentboundary".  Returns NS_ERROR_INVALID_ARG if alter, direction,
+     * or granularity has an unrecognized value.
+     */
+    void modify(in DOMString alter, in DOMString direction,
+                in DOMString granularity);
+
+    /**
      * Modifies the cursor Bidi level after a change in keyboard direction
      * @param langRTL is PR_TRUE if the new language is right-to-left or
      *                PR_FALSE if the new language is left-to-right.
      */
     void selectionLanguageChange(in boolean langRTL);
 
     /**
      * Returns the whole selection into a plain text string.
--- a/content/base/src/Makefile.in
+++ b/content/base/src/Makefile.in
@@ -92,16 +92,17 @@ CPPSRCS		= \
 		nsDOMAttributeMap.cpp \
 		nsDOMDocumentType.cpp \
 		nsDOMFile.cpp \
 		nsDOMFileReader.cpp \
 		nsDOMLists.cpp \
 		nsDOMParser.cpp \
 		nsDOMSerializer.cpp \
 		nsDOMTokenList.cpp \
+		nsDOMSettableTokenList.cpp \
 		nsDocument.cpp \
 		nsDocumentEncoder.cpp \
 		nsDocumentFragment.cpp \
 		nsFrameLoader.cpp \
 		nsFormData.cpp \
 		nsGenConImageContent.cpp \
 		nsGenericDOMDataNode.cpp \
 		nsGenericElement.cpp \
--- a/content/base/src/nsAttrValue.cpp
+++ b/content/base/src/nsAttrValue.cpp
@@ -383,34 +383,17 @@ nsAttrValue::ToString(nsAString& aResult
     {
       NS_NOTREACHED("color attribute without string data");
       aResult.Truncate();
       break;
     }
 #endif
     case eEnum:
     {
-      PRInt16 val = GetEnumValue();
-      PRUint32 allEnumBits =
-        cont ? cont->mEnumValue : static_cast<PRUint32>(GetIntInternal());
-      const EnumTable* table = sEnumTableArray->
-        ElementAt(allEnumBits & NS_ATTRVALUE_ENUMTABLEINDEX_MASK);
-      while (table->tag) {
-        if (table->value == val) {
-          aResult.AssignASCII(table->tag);
-          if (allEnumBits & NS_ATTRVALUE_ENUMTABLE_VALUE_NEEDS_TO_UPPER) {
-            ToUpperCase(aResult);
-          }
-          return;
-        }
-        table++;
-      }
-
-      NS_NOTREACHED("couldn't find value in EnumTable");
-
+      GetEnumString(aResult, PR_FALSE);
       break;
     }
     case ePercent:
     {
       nsAutoString intStr;
       intStr.AppendInt(cont ? cont->mPercent : GetIntInternal());
       aResult = intStr + NS_LITERAL_STRING("%");
 
@@ -465,16 +448,42 @@ nsAttrValue::GetColorValue(nscolor& aCol
     NS_ASSERTION(Type() == eString, "unexpected type for color-valued attr");
     return PR_FALSE;
   }
 
   aColor = GetMiscContainer()->mColor;
   return PR_TRUE;
 }
 
+void
+nsAttrValue::GetEnumString(nsAString& aResult, PRBool aRealTag) const
+{
+  NS_PRECONDITION(Type() == eEnum, "wrong type");
+
+  PRUint32 allEnumBits =
+    (BaseType() == eIntegerBase) ? static_cast<PRUint32>(GetIntInternal())
+                                   : GetMiscContainer()->mEnumValue;
+  PRInt16 val = allEnumBits >> NS_ATTRVALUE_ENUMTABLEINDEX_BITS;
+  const EnumTable* table = sEnumTableArray->
+    ElementAt(allEnumBits & NS_ATTRVALUE_ENUMTABLEINDEX_MASK);
+
+  while (table->tag) {
+    if (table->value == val) {
+      aResult.AssignASCII(table->tag);
+      if (!aRealTag && allEnumBits & NS_ATTRVALUE_ENUMTABLE_VALUE_NEEDS_TO_UPPER) {
+        ToUpperCase(aResult);
+      }
+      return;
+    }
+    table++;
+  }
+
+  NS_NOTREACHED("couldn't find value in EnumTable");
+}
+
 PRInt32
 nsAttrValue::GetAtomCount() const
 {
   ValueType type = Type();
 
   if (type == eAtom) {
     return 1;
   }
@@ -953,56 +962,68 @@ nsAttrValue::SetIntValueAndType(PRInt32 
     }
   } else {
     NS_ASSERTION(!mBits, "Reset before calling SetIntValueAndType!");
     mBits = (aValue * NS_ATTRVALUE_INTEGERTYPE_MULTIPLIER) | aType;
   }
 }
 
 PRBool
+nsAttrValue::GetEnumTableIndex(const EnumTable* aTable, PRInt16& aResult)
+{
+  PRInt16 index = sEnumTableArray->IndexOf(aTable);
+  if (index < 0) {
+    index = sEnumTableArray->Length();
+    NS_ASSERTION(index <= NS_ATTRVALUE_ENUMTABLEINDEX_MAXVALUE,
+        "too many enum tables");
+    if (!sEnumTableArray->AppendElement(aTable)) {
+      return PR_FALSE;
+    }
+  }
+
+  aResult = index;
+
+  return PR_TRUE;
+}
+
+PRBool
 nsAttrValue::ParseEnumValue(const nsAString& aValue,
                             const EnumTable* aTable,
                             PRBool aCaseSensitive)
 {
   ResetIfSet();
-
-  while (aTable->tag) {
-    if (aCaseSensitive ? aValue.EqualsASCII(aTable->tag) :
-                         aValue.LowerCaseEqualsASCII(aTable->tag)) {
+  const EnumTable* tableEntry = aTable;
 
-      // Find index of EnumTable
-      PRInt16 index = sEnumTableArray->IndexOf(aTable);
-      if (index < 0) {
-        index = sEnumTableArray->Length();
-        NS_ASSERTION(index <= NS_ATTRVALUE_ENUMTABLEINDEX_MAXVALUE,
-                     "too many enum tables");
-        if (!sEnumTableArray->AppendElement(aTable)) {
-          return PR_FALSE;
-        }
+  while (tableEntry->tag) {
+    if (aCaseSensitive ? aValue.EqualsASCII(tableEntry->tag) :
+                         aValue.LowerCaseEqualsASCII(tableEntry->tag)) {
+      PRInt16 index;
+      if (!GetEnumTableIndex(aTable, index)) {
+        return PR_FALSE;
       }
 
-      PRInt32 value = (aTable->value << NS_ATTRVALUE_ENUMTABLEINDEX_BITS) +
+      PRInt32 value = (tableEntry->value << NS_ATTRVALUE_ENUMTABLEINDEX_BITS) +
                       index;
 
-      PRBool equals = aCaseSensitive || aValue.EqualsASCII(aTable->tag);
+      PRBool equals = aCaseSensitive || aValue.EqualsASCII(tableEntry->tag);
       if (!equals) {
         nsAutoString tag;
-        tag.AssignASCII(aTable->tag);
+        tag.AssignASCII(tableEntry->tag);
         ToUpperCase(tag);
         if ((equals = tag.Equals(aValue))) {
           value |= NS_ATTRVALUE_ENUMTABLE_VALUE_NEEDS_TO_UPPER;
         }
       }
       SetIntValueAndType(value, eEnum, equals ? nsnull : &aValue);
-      NS_ASSERTION(GetEnumValue() == aTable->value,
+      NS_ASSERTION(GetEnumValue() == tableEntry->value,
                    "failed to store enum properly");
 
       return PR_TRUE;
     }
-    aTable++;
+    tableEntry++;
   }
 
   return PR_FALSE;
 }
 
 PRBool
 nsAttrValue::ParseSpecialIntValue(const nsAString& aString,
                                   PRBool aCanBePercent)
--- a/content/base/src/nsAttrValue.h
+++ b/content/base/src/nsAttrValue.h
@@ -149,16 +149,24 @@ public:
   inline float GetPercentValue() const;
   inline nsCOMArray<nsIAtom>* GetAtomArrayValue() const;
   inline nsICSSStyleRule* GetCSSStyleRuleValue() const;
 #ifdef MOZ_SVG
   inline nsISVGValue* GetSVGValue() const;
 #endif
   inline float GetFloatValue() const;
 
+  /**
+   * Returns the string corresponding to the stored enum value.
+   *
+   * @param aResult   the string representing the enum tag
+   * @param aRealTag  wheter we want to have the real tag or the saved one
+   */
+  void GetEnumString(nsAString& aResult, PRBool aRealTag) const;
+
   // Methods to get access to atoms we may have
   // Returns the number of atoms we have; 0 if we have none.  It's OK
   // to call this without checking the type first; it handles that.
   PRInt32 GetAtomCount() const;
   // Returns the atom at aIndex (0-based).  Do not call this with
   // aIndex >= GetAtomCount().
   nsIAtom* AtomAt(PRInt32 aIndex) const;
 
@@ -194,22 +202,22 @@ public:
     PRInt16 value;
   };
 
   /**
    * Parse into an enum value.
    *
    * @param aValue the string to find the value for
    * @param aTable the enumeration to map with
-   * @param aResult the enum mapping [OUT]
+   * @param aCaseSensitive specify if the parsing has to be case sensitive
    * @return whether the enum value was found or not
    */
   PRBool ParseEnumValue(const nsAString& aValue,
                         const EnumTable* aTable,
-                        PRBool aCaseSensitive = PR_FALSE);
+                        PRBool aCaseSensitive);
 
   /**
    * Parse a string into an integer. Can optionally parse percent (n%).
    * This method explicitly sets a lower bound of zero on the element,
    * whether it be percent or raw integer.
    *
    * @param aString the string to parse
    * @param aCanBePercent PR_TRUE if it can be a percent value (%)
@@ -301,16 +309,27 @@ private:
       nsISVGValue* mSVGValue;
 #endif
       float mFloatValue;
     };
   };
 
   inline ValueBaseType BaseType() const;
 
+  /**
+   * Get the index of an EnumTable in the sEnumTableArray.
+   * If the EnumTable is not in the sEnumTableArray, it is added.
+   * If there is no more space in sEnumTableArray, it returns PR_FALSE.
+   *
+   * @param aTable   the EnumTable to get the index of.
+   * @param aResult  the index of the EnumTable.
+   * @return         whether the index has been found or inserted.
+   */
+  PRBool GetEnumTableIndex(const EnumTable* aTable, PRInt16& aResult);
+
   inline void SetPtrValueAndType(void* aValue, ValueBaseType aType);
   void SetIntValueAndType(PRInt32 aValue, ValueType aType,
                           const nsAString* aStringValue);
   void SetColorValue(nscolor aColor, const nsAString& aString);
   void SetMiscAtomOrString(const nsAString* aValue);
   void ResetMiscAtomOrString();
   inline void ResetIfSet();
 
--- a/content/base/src/nsContentAreaDragDrop.cpp
+++ b/content/base/src/nsContentAreaDragDrop.cpp
@@ -432,17 +432,18 @@ DragDataProducer::Produce(nsDOMDataTrans
   // aCanDrag to false however, as we still want to allow the drag.
   nsCOMPtr<nsIContent> findFormNode = mSelectionTargetNode;
   nsIContent* findFormParent = findFormNode->GetParent();
   while (findFormParent) {
     nsCOMPtr<nsIFormControl> form(do_QueryInterface(findFormParent));
     if (form && form->GetType() != NS_FORM_OBJECT &&
                 form->GetType() != NS_FORM_FIELDSET &&
                 form->GetType() != NS_FORM_LEGEND &&
-                form->GetType() != NS_FORM_LABEL)
+                form->GetType() != NS_FORM_LABEL &&
+                form->GetType() != NS_FORM_OUTPUT)
       return NS_OK;
     findFormParent = findFormParent->GetParent();
   }
     
   // if set, serialize the content under this node
   nsCOMPtr<nsIContent> nodeToSerialize;
   *aDragSelection = PR_FALSE;
 
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -98,16 +98,17 @@
 #include "nsPIDOMWindow.h"
 #include "mozAutoDocUpdate.h"
 #include "nsIWebNavigation.h"
 #include "nsIDocumentLoader.h"
 #include "nsICachingChannel.h"
 #include "nsICacheEntryDescriptor.h"
 #include "nsGenericHTMLElement.h"
 #include "nsHTMLDNSPrefetch.h"
+#include "nsISupportsPrimitives.h"
 
 PRLogModuleInfo* gContentSinkLogModuleInfo;
 
 class nsScriptLoaderObserverProxy : public nsIScriptLoaderObserver
 {
 public:
   nsScriptLoaderObserverProxy(nsIScriptLoaderObserver* aInner)
     : mInner(do_GetWeakReference(aInner))
@@ -211,16 +212,70 @@ nsContentSink::~nsContentSink()
 {
   if (mDocument) {
     // Remove ourselves just to be safe, though we really should have
     // been removed in DidBuildModel if everything worked right.
     mDocument->RemoveObserver(this);
   }
 }
 
+PRBool  nsContentSink::sNotifyOnTimer;
+PRInt32 nsContentSink::sBackoffCount;
+PRInt32 nsContentSink::sNotificationInterval;
+PRInt32 nsContentSink::sInteractiveDeflectCount;
+PRInt32 nsContentSink::sPerfDeflectCount;
+PRInt32 nsContentSink::sPendingEventMode;
+PRInt32 nsContentSink::sEventProbeRate;
+PRInt32 nsContentSink::sInteractiveParseTime;
+PRInt32 nsContentSink::sPerfParseTime;
+PRInt32 nsContentSink::sInteractiveTime;
+PRInt32 nsContentSink::sInitialPerfTime;
+PRInt32 nsContentSink::sEnablePerfMode;
+PRBool  nsContentSink::sCanInterruptParser;
+
+void
+nsContentSink::InitializeStatics()
+{
+  nsContentUtils::AddBoolPrefVarCache("content.notify.ontimer",
+                                      &sNotifyOnTimer);
+  // -1 means never.
+  nsContentUtils::AddIntPrefVarCache("content.notify.backoffcount",
+                                     &sBackoffCount, -1);
+  // The gNotificationInterval has a dramatic effect on how long it
+  // takes to initially display content for slow connections.
+  // The current value provides good
+  // incremental display of content without causing an increase
+  // in page load time. If this value is set below 1/10 of second
+  // it starts to impact page load performance.
+  // see bugzilla bug 72138 for more info.
+  nsContentUtils::AddIntPrefVarCache("content.notify.interval",
+                                     &sNotificationInterval,
+                                     120000);
+  nsContentUtils::AddIntPrefVarCache("content.sink.interactive_deflect_count",
+                                     &sInteractiveDeflectCount, 0);
+  nsContentUtils::AddIntPrefVarCache("content.sink.perf_deflect_count",
+                                     &sPerfDeflectCount, 200);
+  nsContentUtils::AddIntPrefVarCache("content.sink.pending_event_mode",
+                                     &sPendingEventMode, 1);
+  nsContentUtils::AddIntPrefVarCache("content.sink.event_probe_rate",
+                                     &sEventProbeRate, 1);
+  nsContentUtils::AddIntPrefVarCache("content.sink.interactive_parse_time",
+                                     &sInteractiveParseTime, 3000);
+  nsContentUtils::AddIntPrefVarCache("content.sink.perf_parse_time",
+                                     &sPerfParseTime, 360000);
+  nsContentUtils::AddIntPrefVarCache("content.sink.interactive_time",
+                                     &sInteractiveTime, 750000);
+  nsContentUtils::AddIntPrefVarCache("content.sink.initial_perf_time",
+                                     &sInitialPerfTime, 2000000);
+  nsContentUtils::AddIntPrefVarCache("content.sink.enable_perf_mode",
+                                     &sEnablePerfMode, 0);
+  nsContentUtils::AddBoolPrefVarCache("content.interrupt.parsing",
+                                      &sCanInterruptParser, PR_TRUE);
+}
+
 nsresult
 nsContentSink::Init(nsIDocument* aDoc,
                     nsIURI* aURI,
                     nsISupports* aContainer,
                     nsIChannel* aChannel)
 {
   NS_PRECONDITION(aDoc, "null ptr");
   NS_PRECONDITION(aURI, "null ptr");
@@ -249,59 +304,24 @@ nsContentSink::Init(nsIDocument* aDoc,
   mScriptLoader->AddObserver(proxy);
 
   mCSSLoader = aDoc->CSSLoader();
 
   ProcessHTTPHeaders(aChannel);
 
   mNodeInfoManager = aDoc->NodeInfoManager();
 
-  mNotifyOnTimer =
-    nsContentUtils::GetBoolPref("content.notify.ontimer", PR_TRUE);
-
-  // -1 means never
-  mBackoffCount =
-    nsContentUtils::GetIntPref("content.notify.backoffcount", -1);
-
-  // The mNotificationInterval has a dramatic effect on how long it
-  // takes to initially display content for slow connections.
-  // The current value provides good
-  // incremental display of content without causing an increase
-  // in page load time. If this value is set below 1/10 of second
-  // it starts to impact page load performance.
-  // see bugzilla bug 72138 for more info.
-  mNotificationInterval =
-    nsContentUtils::GetIntPref("content.notify.interval", 120000);
+  mBackoffCount = sBackoffCount;
 
-  mInteractiveDeflectCount =
-    nsContentUtils::GetIntPref("content.sink.interactive_deflect_count", 0);
-  mPerfDeflectCount =
-    nsContentUtils::GetIntPref("content.sink.perf_deflect_count", 200);
-  mPendingEventMode =
-    nsContentUtils::GetIntPref("content.sink.pending_event_mode", 1);
-  mEventProbeRate =
-    nsContentUtils::GetIntPref("content.sink.event_probe_rate", 1);
-  mInteractiveParseTime =
-    nsContentUtils::GetIntPref("content.sink.interactive_parse_time", 3000);
-  mPerfParseTime =
-    nsContentUtils::GetIntPref("content.sink.perf_parse_time", 360000);
-  mInteractiveTime =
-    nsContentUtils::GetIntPref("content.sink.interactive_time", 750000);
-  mInitialPerfTime =
-    nsContentUtils::GetIntPref("content.sink.initial_perf_time", 2000000);
-  mEnablePerfMode =
-    nsContentUtils::GetIntPref("content.sink.enable_perf_mode", 0);
-
-  if (mEnablePerfMode != 0) {
-    mDynamicLowerValue = mEnablePerfMode == 1;
+  if (sEnablePerfMode != 0) {
+    mDynamicLowerValue = sEnablePerfMode == 1;
     FavorPerformanceHint(!mDynamicLowerValue, 0);
   }
 
-  mCanInterruptParser =
-    nsContentUtils::GetBoolPref("content.interrupt.parsing", PR_TRUE);
+  mCanInterruptParser = sCanInterruptParser;
 
   return NS_OK;
 
 }
 
 NS_IMETHODIMP
 nsContentSink::StyleSheetLoaded(nsICSSStyleSheet* aSheet,
                                 PRBool aWasAlternate,
@@ -390,17 +410,17 @@ nsContentSink::ScriptAvailable(nsresult 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsContentSink::ScriptEvaluated(nsresult aResult,
                                nsIScriptElement *aElement,
                                PRBool aIsInline)
 {
-  mDeflectedCount = mPerfDeflectCount;
+  mDeflectedCount = sPerfDeflectCount;
 
   // Check if this is the element we were waiting for
   PRInt32 count = mScriptElements.Count();
   if (count == 0 || aElement != mScriptElements[count - 1]) {
     return NS_OK;
   }
 
   NS_ASSERTION(!aElement->GetScriptDeferred(), "defer script was in mScriptElements");
@@ -926,24 +946,25 @@ nsresult
 nsContentSink::GetChannelCacheKey(nsIChannel* aChannel, nsACString& aCacheKey)
 {
   aCacheKey.Truncate();
 
   nsresult rv;
   nsCOMPtr<nsICachingChannel> cachingChannel = do_QueryInterface(aChannel, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<nsISupports> token;
-  rv = cachingChannel->GetCacheToken(getter_AddRefs(token));
+  nsCOMPtr<nsISupports> cacheKey;
+  rv = cachingChannel->GetCacheKey(getter_AddRefs(cacheKey));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<nsICacheEntryDescriptor> descriptor = do_QueryInterface(token, &rv);
+  nsCOMPtr<nsISupportsCString> cacheKeyString = 
+        do_QueryInterface(cacheKey, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  rv = descriptor->GetKey(aCacheKey);
+  rv = cacheKeyString->GetData(aCacheKey);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 nsresult
 nsContentSink::SelectDocAppCache(nsIApplicationCache *aLoadApplicationCache,
                                  nsIURI *aManifestURI,
@@ -1396,17 +1417,17 @@ nsContentSink::Notify(nsITimer *timer)
 
   mNotificationTimer = nsnull;
   return NS_OK;
 }
 
 PRBool
 nsContentSink::IsTimeToNotify()
 {
-  if (!mNotifyOnTimer || !mLayoutStarted || !mBackoffCount ||
+  if (!sNotifyOnTimer || !mLayoutStarted || !mBackoffCount ||
       mInMonolithicContainer) {
     return PR_FALSE;
   }
 
   if (WaitForPendingSheets()) {
     mDeferredFlushTags = PR_TRUE;
     return PR_FALSE;
   }
@@ -1430,17 +1451,17 @@ nsContentSink::WillInterruptImpl()
 {
   nsresult result = NS_OK;
 
   SINK_TRACE(gContentSinkLogModuleInfo, SINK_TRACE_CALLS,
              ("nsContentSink::WillInterrupt: this=%p", this));
 #ifndef SINK_NO_INCREMENTAL
   if (WaitForPendingSheets()) {
     mDeferredFlushTags = PR_TRUE;
-  } else if (mNotifyOnTimer && mLayoutStarted) {
+  } else if (sNotifyOnTimer && mLayoutStarted) {
     if (mBackoffCount && !mInMonolithicContainer) {
       PRInt64 now = PR_Now();
       PRInt64 interval = GetNotificationInterval();
       PRInt64 diff = now - mLastNotificationTime;
 
       // If it's already time for us to have a notification
       if (diff > interval || mDroppedTimer) {
         mBackoffCount--;
@@ -1509,37 +1530,37 @@ nsContentSink::DidProcessATokenImpl()
   // Get the current user event time
   nsIPresShell *shell = mDocument->GetPrimaryShell();
   if (!shell) {
     // If there's no pres shell in the document, return early since
     // we're not laying anything out here.
     return NS_OK;
   }
 
-  // Increase before comparing to mEventProbeRate
+  // Increase before comparing to gEventProbeRate
   ++mDeflectedCount;
 
   // Check if there's a pending event
-  if (mPendingEventMode != 0 && !mHasPendingEvent &&
-      (mDeflectedCount % mEventProbeRate) == 0) {
+  if (sPendingEventMode != 0 && !mHasPendingEvent &&
+      (mDeflectedCount % sEventProbeRate) == 0) {
     nsIViewManager* vm = shell->GetViewManager();
     NS_ENSURE_TRUE(vm, NS_ERROR_FAILURE);
     nsCOMPtr<nsIWidget> widget;
     vm->GetRootWidget(getter_AddRefs(widget));
     mHasPendingEvent = widget && widget->HasPendingInputEvent();
   }
 
-  if (mHasPendingEvent && mPendingEventMode == 2) {
+  if (mHasPendingEvent && sPendingEventMode == 2) {
     return NS_ERROR_HTMLPARSER_INTERRUPTED;
   }
 
   // Have we processed enough tokens to check time?
   if (!mHasPendingEvent &&
-      mDeflectedCount < (mDynamicLowerValue ? mInteractiveDeflectCount :
-                                              mPerfDeflectCount)) {
+      mDeflectedCount < PRUint32(mDynamicLowerValue ? sInteractiveDeflectCount :
+                                                      sPerfDeflectCount)) {
     return NS_OK;
   }
 
   mDeflectedCount = 0;
 
   // Check if it's time to return to the main event loop
   if (PR_IntervalToMicroseconds(PR_IntervalNow()) > mCurrentParseEndTime) {
     return NS_ERROR_HTMLPARSER_INTERRUPTED;
@@ -1677,37 +1698,37 @@ nsContentSink::WillParseImpl(void)
 
   nsIPresShell *shell = mDocument->GetPrimaryShell();
   if (!shell) {
     return NS_OK;
   }
 
   PRUint32 currentTime = PR_IntervalToMicroseconds(PR_IntervalNow());
 
-  if (mEnablePerfMode == 0) {
+  if (sEnablePerfMode == 0) {
     nsIViewManager* vm = shell->GetViewManager();
     NS_ENSURE_TRUE(vm, NS_ERROR_FAILURE);
     PRUint32 lastEventTime;
     vm->GetLastUserEventTime(lastEventTime);
 
     PRBool newDynLower =
-      (currentTime - mBeginLoadTime) > mInitialPerfTime &&
-      (currentTime - lastEventTime) < mInteractiveTime;
+      (currentTime - mBeginLoadTime) > PRUint32(sInitialPerfTime) &&
+      (currentTime - lastEventTime) < PRUint32(sInteractiveTime);
     
     if (mDynamicLowerValue != newDynLower) {
       FavorPerformanceHint(!newDynLower, 0);
       mDynamicLowerValue = newDynLower;
     }
   }
   
   mDeflectedCount = 0;
   mHasPendingEvent = PR_FALSE;
 
   mCurrentParseEndTime = currentTime +
-    (mDynamicLowerValue ? mInteractiveParseTime : mPerfParseTime);
+    (mDynamicLowerValue ? sInteractiveParseTime : sPerfParseTime);
 
   return NS_OK;
 }
 
 void
 nsContentSink::WillBuildModelImpl()
 {
   if (mCanInterruptParser) {
--- a/content/base/src/nsContentSink.h
+++ b/content/base/src/nsContentSink.h
@@ -147,16 +147,18 @@ class nsContentSink : public nsICSSLoade
   // nsIDocumentObserver
   virtual void BeginUpdate(nsIDocument *aDocument, nsUpdateType aUpdateType);
   virtual void EndUpdate(nsIDocument *aDocument, nsUpdateType aUpdateType);
 
   virtual void UpdateChildCounts() = 0;
 
   PRBool IsTimeToNotify();
 
+  static void InitializeStatics();
+
 protected:
   nsContentSink();
   virtual ~nsContentSink();
 
   enum CacheSelectionAction {
     // There is no offline cache manifest specified by the document,
     // or the document was loaded from a cache other than the one it
     // specifies via its manifest attribute and IS NOT a top-level
@@ -273,17 +275,17 @@ protected:
   FavorPerformanceHint(PRBool perfOverStarvation, PRUint32 starvationDelay);
 
   inline PRInt32 GetNotificationInterval()
   {
     if (mDynamicLowerValue) {
       return 1000;
     }
 
-    return mNotificationInterval;
+    return sNotificationInterval;
   }
 
   // Overridable hooks into script evaluation
   virtual void PreEvaluateScript()                            {return;}
   virtual void PostEvaluateScript(nsIScriptElement *aElement) {return;}
 
   virtual nsresult FlushTags() = 0;
 
@@ -313,29 +315,23 @@ protected:
 
   nsCOMArray<nsIScriptElement> mScriptElements;
 
   nsCString mRef; // ScrollTo #ref
 
   // back off timer notification after count
   PRInt32 mBackoffCount;
 
-  // Notification interval in microseconds
-  PRInt32 mNotificationInterval;
-
   // Time of last notification
   // Note: mLastNotificationTime is only valid once mLayoutStarted is true.
   PRTime mLastNotificationTime;
 
   // Timer used for notification
   nsCOMPtr<nsITimer> mNotificationTimer;
 
-  // Do we notify based on time?
-  PRPackedBool mNotifyOnTimer;
-
   // Have we already called BeginUpdate for this set of content changes?
   PRUint8 mBeganUpdate : 1;
   PRUint8 mLayoutStarted : 1;
   PRUint8 mScrolledToRefAlready : 1;
   PRUint8 mCanInterruptParser : 1;
   PRUint8 mDynamicLowerValue : 1;
   PRUint8 mParsing : 1;
   PRUint8 mDroppedTimer : 1;
@@ -352,61 +348,63 @@ protected:
   //
   // -- Can interrupt parsing members --
   //
 
   // The number of tokens that have been processed since we measured
   // if it's time to return to the main event loop.
   PRUint32 mDeflectedCount;
 
-  // How many times to deflect in interactive/perf modes
-  PRUint32 mInteractiveDeflectCount;
-  PRUint32 mPerfDeflectCount;
-
-  // 0 = don't check for pending events
-  // 1 = don't deflect if there are pending events
-  // 2 = bail if there are pending events
-  PRUint32 mPendingEventMode;
-
-  // How often to probe for pending events. 1=every token
-  PRUint32 mEventProbeRate;
-
   // Is there currently a pending event?
   PRBool mHasPendingEvent;
 
   // When to return to the main event loop
   PRUint32 mCurrentParseEndTime;
 
-  // How long to stay off the event loop in interactive/perf modes
-  PRUint32 mInteractiveParseTime;
-  PRUint32 mPerfParseTime;
-
-  // How long to be in interactive mode after an event
-  PRUint32 mInteractiveTime;
-  // How long to stay in perf mode after initial loading
-  PRUint32 mInitialPerfTime;
-
-  // Should we switch between perf-mode and interactive-mode
-  PRBool mEnablePerfMode;
-
   PRInt32 mBeginLoadTime;
 
   // Last mouse event or keyboard event time sampled by the content
   // sink
   PRUint32 mLastSampledUserEventTime;
 
   PRInt32 mInMonolithicContainer;
 
   PRInt32 mInNotification;
   PRUint32 mUpdatesInNotification;
 
   PRUint32 mPendingSheetCount;
 
   nsRevocableEventPtr<nsRunnableMethod<nsContentSink, void, false> >
     mProcessLinkHeaderEvent;
+
+  // Do we notify based on time?
+  static PRBool sNotifyOnTimer;
+  // Back off timer notification after count.
+  static PRInt32 sBackoffCount;
+  // Notification interval in microseconds
+  static PRInt32 sNotificationInterval;
+  // How many times to deflect in interactive/perf modes
+  static PRInt32 sInteractiveDeflectCount;
+  static PRInt32 sPerfDeflectCount;
+  // 0 = don't check for pending events
+  // 1 = don't deflect if there are pending events
+  // 2 = bail if there are pending events
+  static PRInt32 sPendingEventMode;
+  // How often to probe for pending events. 1=every token
+  static PRInt32 sEventProbeRate;
+  // How long to stay off the event loop in interactive/perf modes
+  static PRInt32 sInteractiveParseTime;
+  static PRInt32 sPerfParseTime;
+  // How long to be in interactive mode after an event
+  static PRInt32 sInteractiveTime;
+  // How long to stay in perf mode after initial loading
+  static PRInt32 sInitialPerfTime;
+  // Should we switch between perf-mode and interactive-mode
+  static PRInt32 sEnablePerfMode;
+  static PRBool sCanInterruptParser;
 };
 
 // sanitizing content sink whitelists
 extern PRBool IsAttrURI(nsIAtom *aName);
 extern nsIAtom** const kDefaultAllowedTags [];
 extern nsIAtom** const kDefaultAllowedAttributes [];
 
 #endif // _nsContentSink_h_
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -53,16 +53,17 @@
 #include "nsIPrefBranch2.h"
 #include "nsIPrefLocalizedString.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptContext.h"
 #include "nsIDOMScriptObjectFactory.h"
 #include "nsDOMCID.h"
 #include "nsContentUtils.h"
+#include "nsIContentUtils.h"
 #include "nsIXPConnect.h"
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsINodeInfo.h"
 #include "nsReadableUtils.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMNodeList.h"
 #include "nsIDOMNode.h"
@@ -326,26 +327,38 @@ nsPrefOldCallback::Observe(nsISupports  
 {
   NS_ASSERTION(!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID),
                "invalid topic");
   mCallback(NS_LossyConvertUTF16toASCII(aData).get(), mClosure);
 
   return NS_OK;
 }
 
+struct PrefCacheData {
+  void* cacheLocation;
+  union {
+    PRBool defaultValueBool;
+    PRInt32 defaultValueInt;
+  };
+};
+
+nsTArray<nsAutoPtr<PrefCacheData> >* sPrefCacheData = nsnull;
+
 // static
 nsresult
 nsContentUtils::Init()
 {
   if (sInitialized) {
     NS_WARNING("Init() called twice");
 
     return NS_OK;
   }
 
+  sPrefCacheData = new nsTArray<nsAutoPtr<PrefCacheData> >();
+
   nsresult rv = CallGetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID,
                                &sSecurityManager);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // It's ok to not have a pref service.
   CallGetService(NS_PREFSERVICE_CONTRACTID, &sPrefBranch);
 
   rv = NS_GetNameSpaceManager(&sNameSpaceManager);
@@ -949,16 +962,19 @@ nsContentUtils::Shutdown()
       if (sPrefBranch)
         sPrefBranch->RemoveObserver(callback->mPref.get(), callback);
       sPrefCallbackList->RemoveObject(callback);
     }
     delete sPrefCallbackList;
     sPrefCallbackList = nsnull;
   }
 
+  delete sPrefCacheData;
+  sPrefCacheData = nsnull;
+
   NS_IF_RELEASE(sStringBundleService);
   NS_IF_RELEASE(sConsoleService);
   NS_IF_RELEASE(sDOMScriptObjectFactory);
   if (sJSGCThingRootCount == 0 && sXPConnect)
     NS_RELEASE(sXPConnect);
   NS_IF_RELEASE(sSecurityManager);
   NS_IF_RELEASE(sThreadJSContextStack);
   NS_IF_RELEASE(sNameSpaceManager);
@@ -2691,45 +2707,57 @@ nsContentUtils::UnregisterPrefCallback(c
       }
     }
   }
 }
 
 static int
 BoolVarChanged(const char *aPref, void *aClosure)
 {
-  PRBool* cache = static_cast<PRBool*>(aClosure);
-  *cache = nsContentUtils::GetBoolPref(aPref, PR_FALSE);
+  PrefCacheData* cache = static_cast<PrefCacheData*>(aClosure);
+  *((PRBool*)cache->cacheLocation) =
+    nsContentUtils::GetBoolPref(aPref, cache->defaultValueBool);
   
   return 0;
 }
 
 void
 nsContentUtils::AddBoolPrefVarCache(const char *aPref,
-                                    PRBool* aCache)
-{
-  *aCache = GetBoolPref(aPref, PR_FALSE);
-  RegisterPrefCallback(aPref, BoolVarChanged, aCache);
+                                    PRBool* aCache,
+                                    PRBool aDefault)
+{
+  *aCache = GetBoolPref(aPref, aDefault);
+  PrefCacheData* data = new PrefCacheData;
+  data->cacheLocation = aCache;
+  data->defaultValueBool = aDefault;
+  sPrefCacheData->AppendElement(data);
+  RegisterPrefCallback(aPref, BoolVarChanged, data);
 }
 
 static int
 IntVarChanged(const char *aPref, void *aClosure)
 {
-  PRInt32* cache = static_cast<PRInt32*>(aClosure);
-  *cache = nsContentUtils::GetIntPref(aPref, 0);
+  PrefCacheData* cache = static_cast<PrefCacheData*>(aClosure);
+  *((PRInt32*)cache->cacheLocation) =
+    nsContentUtils::GetIntPref(aPref, cache->defaultValueInt);
   
   return 0;
 }
 
 void
 nsContentUtils::AddIntPrefVarCache(const char *aPref,
-                                   PRInt32* aCache)
-{
-  *aCache = GetIntPref(aPref, PR_FALSE);
-  RegisterPrefCallback(aPref, IntVarChanged, aCache);
+                                   PRInt32* aCache,
+                                   PRInt32 aDefault)
+{
+  *aCache = GetIntPref(aPref, aDefault);
+  PrefCacheData* data = new PrefCacheData;
+  data->cacheLocation = aCache;
+  data->defaultValueInt = aDefault;
+  sPrefCacheData->AppendElement(data);
+  RegisterPrefCallback(aPref, IntVarChanged, data);
 }
 
 static const char *gEventNames[] = {"event"};
 static const char *gSVGEventNames[] = {"evt"};
 // for b/w compat, the first name to onerror is still 'event', even though it
 // is actually the error message.  (pre this code, the other 2 were not avail.)
 // XXXmarkh - a quick lxr shows no affected code - should we correct this?
 static const char *gOnErrorNames[] = {"event", "source", "lineno"};
@@ -5398,17 +5426,17 @@ nsContentUtils::StripNullChars(const nsA
     if (*start != '\0')
       aOutStr.Append(*start);
     ++start;
   }
 }
 
 namespace {
 
-const int kCloneStackFrameStackSize = 20;
+const unsigned int kCloneStackFrameStackSize = 20;
 
 class CloneStackFrame
 {
   friend class CloneStack;
 
 public:
   // These three jsvals must all stick together as they're treated as a jsval
   // array!
@@ -5608,35 +5636,24 @@ CloneSimpleValues(JSContext* cx,
       return NS_ERROR_FAILURE;
     }
     return SetPropertyOnValueOrObject(cx, val, rval, robj, rid);
   }
 
   NS_ASSERTION(JSVAL_IS_OBJECT(val), "Not an object!");
   JSObject* obj = JSVAL_TO_OBJECT(val);
 
-  // See if this JSObject is backed by some C++ object. If it is then we assume
-  // that it is inappropriate to clone.
-  nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
-  nsContentUtils::XPConnect()->
-    GetWrappedNativeOfJSObject(cx, obj, getter_AddRefs(wrapper));
-  if (wrapper) {
-    return SetPropertyOnValueOrObject(cx, JSVAL_NULL, rval, robj, rid);
-  }
-
-  // Security wrapped objects are auto-nulled as well.
-  JSClass* clasp = JS_GET_CLASS(cx, obj);
-  if ((clasp->flags & JSCLASS_IS_EXTENDED) &&
-      ((JSExtendedClass*)clasp)->wrappedObject) {
-    return SetPropertyOnValueOrObject(cx, JSVAL_NULL, rval, robj, rid);
-  }
-
-  // Function objects don't get cloned.
-  if (JS_ObjectIsFunction(cx, obj)) {
-    return SetPropertyOnValueOrObject(cx, JSVAL_NULL, rval, robj, rid);
+  // Dense arrays of primitives can be cloned quickly.
+  JSObject* newArray;
+  if (!js_CloneDensePrimitiveArray(cx, obj, &newArray)) {
+    return NS_ERROR_FAILURE;
+  }
+  if (newArray) {
+    return SetPropertyOnValueOrObject(cx, OBJECT_TO_JSVAL(newArray), rval, robj,
+                                      rid);
   }
 
   // Date objects.
   if (js_DateIsValid(cx, obj)) {
     jsdouble msec = js_DateGetMsecSinceEpoch(cx, obj);
     JSObject* newDate;
     if (!(msec  && (newDate = js_NewDateObjectMsec(cx, msec)))) {
       return NS_ERROR_OUT_OF_MEMORY;
@@ -5683,16 +5700,37 @@ CloneSimpleValues(JSContext* cx,
     return SetPropertyOnValueOrObject(cx, OBJECT_TO_JSVAL(newBuffer), rval,
                                       robj, rid);
   }
 
   // Do we support File?
   // Do we support Blob?
   // Do we support FileList?
 
+  // Function objects don't get cloned.
+  if (JS_ObjectIsFunction(cx, obj)) {
+    return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
+  }
+
+  // Security wrapped objects are not allowed either.
+  JSClass* clasp = JS_GET_CLASS(cx, obj);
+  if ((clasp->flags & JSCLASS_IS_EXTENDED) &&
+      ((JSExtendedClass*)clasp)->wrappedObject) {
+    return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
+  }
+
+  // See if this JSObject is backed by some C++ object. If it is then we assume
+  // that it is inappropriate to clone.
+  nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
+  nsContentUtils::XPConnect()->
+    GetWrappedNativeOfJSObject(cx, obj, getter_AddRefs(wrapper));
+  if (wrapper) {
+    return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
+  }
+
   *wasCloned = PR_FALSE;
   return NS_OK;
 }
 
 } // anonymous namespace
 
 // static
 nsresult
@@ -5827,16 +5865,23 @@ nsContentUtils::ReparentClonedObjectToSc
       // Fix the prototype and parent first.
       JSObject* proto;
       if (!js_GetClassPrototype(cx, scope, key, &proto) ||
           !JS_SetPrototype(cx, data.obj, proto) ||
           !JS_SetParent(cx, data.obj, scope)) {
         return NS_ERROR_FAILURE;
       }
 
+      // Primitive arrays don't need to be enumerated either but the proto and
+      // parent needed to be fixed above. Now we can just move on.
+      if (js_IsDensePrimitiveArray(data.obj)) {
+        objectData.RemoveElementAt(objectData.Length() - 1);
+        continue;
+      }
+
       // And now enumerate the object's properties.
       if (!(data.ids = JS_Enumerate(cx, data.obj))) {
         return NS_ERROR_FAILURE;
       }
     }
 
     // If we've gone through all the object's properties then we're done with
     // this frame.
@@ -5984,8 +6029,15 @@ void nsContentUtils::PlatformToDOMLineBr
                              NS_LITERAL_STRING("\n").get());
 
     // Mac linebreaks: Map any remaining CR to LF:
     aString.ReplaceSubstring(NS_LITERAL_STRING("\r").get(),
                              NS_LITERAL_STRING("\n").get());
   }
 }
 
+NS_IMPL_ISUPPORTS1(nsIContentUtils, nsIContentUtils)
+
+PRBool
+nsIContentUtils::IsSafeToRunScript()
+{
+  return nsContentUtils::IsSafeToRunScript();
+}
--- a/content/base/src/nsDOMAttribute.cpp
+++ b/content/base/src/nsDOMAttribute.cpp
@@ -370,35 +370,35 @@ nsDOMAttribute::GetAttributes(nsIDOMName
 
   *aAttributes = nsnull;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMAttribute::InsertBefore(nsIDOMNode* aNewChild, nsIDOMNode* aRefChild, nsIDOMNode** aReturn)
 {
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return ReplaceOrInsertBefore(PR_FALSE, aNewChild, aRefChild, aReturn);
 }
 
 NS_IMETHODIMP
 nsDOMAttribute::ReplaceChild(nsIDOMNode* aNewChild, nsIDOMNode* aOldChild, nsIDOMNode** aReturn)
 {
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return ReplaceOrInsertBefore(PR_TRUE, aNewChild, aOldChild, aReturn);
 }
 
 NS_IMETHODIMP
 nsDOMAttribute::RemoveChild(nsIDOMNode* aOldChild, nsIDOMNode** aReturn)
 {
   return nsINode::RemoveChild(aOldChild, aReturn);
 }
 
 NS_IMETHODIMP
 nsDOMAttribute::AppendChild(nsIDOMNode* aNewChild, nsIDOMNode** aReturn)
 {
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return InsertBefore(aNewChild, nsnull, aReturn);
 }
 
 nsresult
 nsDOMAttribute::Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const
 {
   nsAutoString value;
   const_cast<nsDOMAttribute*>(this)->GetValue(value);
 
new file mode 100644
--- /dev/null
+++ b/content/base/src/nsDOMSettableTokenList.cpp
@@ -0,0 +1,80 @@
+/* ***** 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 Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Mounir Lamouri <mounir.lamouri@mozilla.com> (original author)
+ *
+ * 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 ***** */
+
+/*
+ * Implementation of nsIDOMDOMSettableTokenList specified by HTML5.
+ */
+
+#include "nsDOMSettableTokenList.h"
+
+
+nsDOMSettableTokenList::nsDOMSettableTokenList(nsGenericElement *aElement, nsIAtom* aAttrAtom)
+  : nsDOMTokenList(aElement, aAttrAtom)
+{
+}
+
+nsDOMSettableTokenList::~nsDOMSettableTokenList()
+{
+}
+
+DOMCI_DATA(DOMSettableTokenList, nsDOMSettableTokenList)
+
+NS_INTERFACE_TABLE_HEAD(nsDOMSettableTokenList)
+  NS_INTERFACE_TABLE1(nsDOMSettableTokenList,
+                      nsIDOMDOMSettableTokenList)
+  NS_INTERFACE_TABLE_TO_MAP_SEGUE
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(DOMSettableTokenList)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMTokenList)
+
+NS_IMPL_ADDREF_INHERITED(nsDOMSettableTokenList, nsDOMTokenList)
+NS_IMPL_RELEASE_INHERITED(nsDOMSettableTokenList, nsDOMTokenList)
+
+NS_IMETHODIMP
+nsDOMSettableTokenList::GetValue(nsAString& aResult)
+{
+  return ToString(aResult);
+}
+
+NS_IMETHODIMP
+nsDOMSettableTokenList::SetValue(const nsAString& aValue)
+{
+  if (!mElement) {
+    return NS_OK;
+  }
+
+  return mElement->SetAttr(kNameSpaceID_None, mAttrAtom, aValue, PR_TRUE);
+}
+
new file mode 100644
--- /dev/null
+++ b/content/base/src/nsDOMSettableTokenList.h
@@ -0,0 +1,67 @@
+/* ***** 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 Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Mounir Lamouri <mounir.lamouri@mozilla.com> (original author)
+ *
+ * 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 ***** */
+
+/*
+ * Implementation of nsIDOMDOMSettableTokenList specified by HTML5.
+ */
+
+#ifndef nsDOMSettableTokenList_h___
+#define nsDOMSettableTokenList_h___
+
+#include "nsIDOMDOMSettableTokenList.h"
+#include "nsDOMTokenList.h"
+
+
+class nsGenericElement;
+class nsIAtom;
+
+class nsDOMSettableTokenList : public nsDOMTokenList,
+                               public nsIDOMDOMSettableTokenList
+{
+public:
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_NSIDOMDOMSETTABLETOKENLIST
+
+  NS_FORWARD_NSIDOMDOMTOKENLIST(nsDOMTokenList::);
+
+  nsDOMSettableTokenList(nsGenericElement* aElement, nsIAtom* aAttrAtom);
+
+protected:
+  virtual ~nsDOMSettableTokenList();
+};
+
+#endif // nsDOMSettableTokenList_h___
+
--- a/content/base/src/nsDOMTokenList.h
+++ b/content/base/src/nsDOMTokenList.h
@@ -51,17 +51,17 @@ class nsDOMTokenList : public nsIDOMDOMT
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMDOMTOKENLIST
 
   nsDOMTokenList(nsGenericElement* aElement, nsIAtom* aAttrAtom);
 
   void DropReference();
 
-private:
+protected:
   ~nsDOMTokenList();
 
   const nsAttrValue* GetParsedAttr() {
     if (!mElement) {
       return nsnull;
     }
     return mElement->GetParsedAttr(mAttrAtom);
   }
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -3812,21 +3812,19 @@ nsDocument::SetScriptHandlingObject(nsIS
   NS_ASSERTION(!win || win->IsInnerWindow(), "Should have inner window here!");
   mScopeObject = mScriptObject = do_GetWeakReference(aScriptObject);
   if (aScriptObject) {
     mHasHadScriptHandlingObject = PR_TRUE;
   }
 }
 
 nsPIDOMWindow *
-nsDocument::GetWindow()
-{
-  if (mWindow) {
-    return mWindow->GetOuterWindow();
-  }
+nsDocument::GetWindowInternal()
+{
+  NS_ASSERTION(!mWindow, "This should not be called when mWindow is not null!");
 
   nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(GetScriptGlobalObject()));
 
   if (!win) {
     return nsnull;
   }
 
   return win->GetOuterWindow();
@@ -7168,53 +7166,72 @@ nsDocument::EnsureOnloadBlocker()
 
       // Not in the loadgroup, so add it.
       loadGroup->AddRequest(mOnloadBlocker, nsnull);
     }
   }
 }
 
 void
+nsDocument::AsyncBlockOnload()
+{
+  while (mAsyncOnloadBlockCount) {
+    --mAsyncOnloadBlockCount;
+    BlockOnload();
+  }
+}
+
+void
 nsDocument::BlockOnload()
 {
   if (mDisplayDocument) {
     mDisplayDocument->BlockOnload();
     return;
   }
   
   // If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
   // -- it's not ours.
   if (mOnloadBlockCount == 0 && mScriptGlobalObject) {
+    if (!nsContentUtils::IsSafeToRunScript()) {
+      // Because AddRequest may lead to OnStateChange calls in chrome,
+      // block onload only when there are no script blockers.
+      ++mAsyncOnloadBlockCount;
+      if (mAsyncOnloadBlockCount == 1) {
+        nsContentUtils::AddScriptRunner(
+          NS_NewRunnableMethod(this, &nsDocument::AsyncBlockOnload));
+      }
+      return;
+    }
     nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
     if (loadGroup) {
       loadGroup->AddRequest(mOnloadBlocker, nsnull);
     }
   }
   ++mOnloadBlockCount;      
 }
 
 void
 nsDocument::UnblockOnload(PRBool aFireSync)
 {
   if (mDisplayDocument) {
     mDisplayDocument->UnblockOnload(aFireSync);
     return;
   }
 
-  if (mOnloadBlockCount == 0) {
+  if (mOnloadBlockCount == 0 && mAsyncOnloadBlockCount == 0) {
     NS_NOTREACHED("More UnblockOnload() calls than BlockOnload() calls; dropping call");
     return;
   }
 
   --mOnloadBlockCount;
 
   // If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
   // -- it's not ours.
   if (mOnloadBlockCount == 0 && mScriptGlobalObject) {
-    if (aFireSync) {
+    if (aFireSync && mAsyncOnloadBlockCount == 0) {
       // Increment mOnloadBlockCount, since DoUnblockOnload will decrement it
       ++mOnloadBlockCount;
       DoUnblockOnload();
     } else {
       PostUnblockOnloadEvent();
     }
   }
 }
@@ -7255,16 +7272,21 @@ nsDocument::DoUnblockOnload()
   --mOnloadBlockCount;
 
   if (mOnloadBlockCount != 0) {
     // We blocked again after the last unblock.  Nothing to do here.  We'll
     // post a new event when we unblock again.
     return;
   }
 
+  if (mAsyncOnloadBlockCount != 0) {
+    // We need to wait until the async onload block has been handled.
+    PostUnblockOnloadEvent();
+  }
+
   // If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
   // -- it's not ours.
   if (mScriptGlobalObject) {
     nsCOMPtr<nsILoadGroup> loadGroup = GetDocumentLoadGroup();
     if (loadGroup) {
       loadGroup->RemoveRequest(mOnloadBlocker, nsnull, NS_OK);
     }
   }
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -645,21 +645,16 @@ public:
 
   virtual nsIScriptGlobalObject*
     GetScriptHandlingObject(PRBool& aHasHadScriptHandlingObject) const;
   virtual void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
 
   virtual nsIScriptGlobalObject* GetScopeObject();
 
   /**
-   * Return the window containing the document (the outer window).
-   */
-  virtual nsPIDOMWindow *GetWindow();
-
-  /**
    * Get the script loader for this document
    */
   virtual nsScriptLoader* ScriptLoader();
 
   /**
    * Add a new observer of document change notifications. Whenever
    * content is changed, appended, inserted or removed the observers are
    * informed.
@@ -939,16 +934,19 @@ public:
                                        nsICSSStyleSheet** sheet);
 
   virtual nsISupports* GetCurrentContentSink();
 
   virtual PRInt32 GetDocumentState();
 
   virtual void RegisterFileDataUri(nsACString& aUri);
 
+  // Only BlockOnload should call this!
+  void AsyncBlockOnload();
+
 protected:
   friend class nsNodeUtils;
   void RegisterNamedItems(nsIContent *aContent);
   void UnregisterNamedItems(nsIContent *aContent);
   void UpdateNameTableEntry(nsIContent *aContent);
   void UpdateIdTableEntry(nsIContent *aContent);
   void RemoveFromNameTable(nsIContent *aContent);
   void RemoveFromIdTable(nsIContent *aContent);
@@ -1003,16 +1001,17 @@ protected:
   {
     return kNameSpaceID_None;
   }
 
   void DispatchPageTransition(nsPIDOMEventTarget* aDispatchTarget,
                               const nsAString& aType,
                               PRBool aPersisted);
 
+  virtual nsPIDOMWindow *GetWindowInternal();
   virtual nsPIDOMWindow *GetInnerWindowInternal();
 
   // nsContentList match functions for GetElementsByClassName
   static PRBool MatchClassNames(nsIContent* aContent, PRInt32 aNamespaceID,
                                 nsIAtom* aAtom, void* aData);
 
   static void DestroyClassNameArray(void* aData);
 
@@ -1169,17 +1168,20 @@ private:
   nsCOMPtr<nsISupports> mXPathEvaluatorTearoff;
 
   // The layout history state that should be used by nodes in this
   // document.  We only actually store a pointer to it when:
   // 1)  We have no script global object.
   // 2)  We haven't had Destroy() called on us yet.
   nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
 
+  // Currently active onload blockers
   PRUint32 mOnloadBlockCount;
+  // Onload blockers which haven't been activated yet
+  PRUint32 mAsyncOnloadBlockCount;
   nsCOMPtr<nsIRequest> mOnloadBlocker;
   ReadyState mReadyState;
 
   // A hashtable of styled links keyed by address pointer.
   nsTHashtable<nsPtrHashKey<mozilla::dom::Link> > mStyledLinks;
 #ifdef DEBUG
   // Indicates whether mStyledLinks was cleared or not.  This is used to track
   // state so we can provide useful assertions to consumers of ForgetLink and
--- a/content/base/src/nsGenericDOMDataNode.h
+++ b/content/base/src/nsGenericDOMDataNode.h
@@ -105,47 +105,30 @@ public:
   {
     NS_ENSURE_ARG_POINTER(aHasAttributes);
     *aHasAttributes = PR_FALSE;
     return NS_OK;
   }
   nsresult InsertBefore(nsIDOMNode* aNewChild, nsIDOMNode* aRefChild,
                         nsIDOMNode** aReturn)
   {
-    NS_ENSURE_ARG_POINTER(aReturn);
-    *aReturn = nsnull;
-    return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
+    return ReplaceOrInsertBefore(PR_FALSE, aNewChild, aRefChild, aReturn);
   }
   nsresult ReplaceChild(nsIDOMNode* aNewChild, nsIDOMNode* aOldChild,
                         nsIDOMNode** aReturn)
   {
-    NS_ENSURE_ARG_POINTER(aReturn);
-    *aReturn = nsnull;
-
-    /*
-     * Data nodes can't have children.
-     */
-    return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
+    return ReplaceOrInsertBefore(PR_TRUE, aNewChild, aOldChild, aReturn);
   }
   nsresult RemoveChild(nsIDOMNode* aOldChild, nsIDOMNode** aReturn)
   {
-    NS_ENSURE_ARG_POINTER(aReturn);
-    *aReturn = nsnull;
-
-    /*
-     * Data nodes can't have children, i.e. aOldChild can't be a child of
-     * this node.
-     */
-    return NS_ERROR_DOM_NOT_FOUND_ERR;
+    return nsINode::RemoveChild(aOldChild, aReturn);
   }
   nsresult AppendChild(nsIDOMNode* aNewChild, nsIDOMNode** aReturn)
   {
-    NS_ENSURE_ARG_POINTER(aReturn);
-    *aReturn = nsnull;
-    return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
+    return InsertBefore(aNewChild, nsnull, aReturn);
   }
   nsresult GetNamespaceURI(nsAString& aNamespaceURI);
   nsresult GetLocalName(nsAString& aLocalName);
   nsresult GetPrefix(nsAString& aPrefix);
   nsresult SetPrefix(const nsAString& aPrefix);
   nsresult Normalize();
   nsresult IsSupported(const nsAString& aFeature,
                        const nsAString& aVersion,
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -3746,16 +3746,24 @@ PRBool IsAllowedAsChild(nsIContent* aNew
 nsresult
 nsINode::ReplaceOrInsertBefore(PRBool aReplace, nsINode* aNewChild,
                                nsINode* aRefChild)
 {
   if (!aNewChild || (aReplace && !aRefChild)) {
     return NS_ERROR_NULL_POINTER;
   }
 
+  if (IsNodeOfType(eDATA_NODE)) {
+    return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
+  }
+
+  if (IsNodeOfType(eATTRIBUTE)) {
+    return NS_ERROR_NOT_IMPLEMENTED;
+  }
+
   nsIContent* refContent;
   nsresult res = NS_OK;
   PRInt32 insPos;
 
   // Figure out which index to insert at
   if (aRefChild) {
     insPos = IndexOf(aRefChild);
     if (insPos < 0) {
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -1276,23 +1276,26 @@ GK_ATOM(z, "z")
 GK_ATOM(zoomAndPan, "zoomAndPan")
 #endif
 
 #ifdef MOZ_SMIL
 GK_ATOM(accumulate, "accumulate")
 GK_ATOM(additive, "additive")
 GK_ATOM(attributeName, "attributeName")
 GK_ATOM(attributeType, "attributeType")
+GK_ATOM(auto_reverse, "auto-reverse")
 GK_ATOM(begin, "begin")
 GK_ATOM(by, "by")
 GK_ATOM(calcMode, "calcMode")
 GK_ATOM(css, "CSS")
 GK_ATOM(dur, "dur")
+GK_ATOM(keyPoints, "keyPoints")
 GK_ATOM(keySplines, "keySplines")
 GK_ATOM(keyTimes, "keyTimes")
+GK_ATOM(mozAnimateMotionDummyAttr, "_mozAnimateMotionDummyAttr")
 GK_ATOM(repeatCount, "repeatCount")
 GK_ATOM(repeatDur, "repeatDur")
 GK_ATOM(restart, "restart")
 GK_ATOM(to, "to")
 GK_ATOM(XML, "XML")
 #endif
 
 #ifdef MOZ_MATHML
--- a/content/base/src/nsNodeUtils.cpp
+++ b/content/base/src/nsNodeUtils.cpp
@@ -352,29 +352,33 @@ nsNodeUtils::GetUserData(nsINode *aNode,
   return NS_OK;
 }
 
 struct NS_STACK_CLASS nsHandlerData
 {
   PRUint16 mOperation;
   nsCOMPtr<nsIDOMNode> mSource;
   nsCOMPtr<nsIDOMNode> mDest;
+  nsCxPusher mPusher;
 };
 
 static void
 CallHandler(void *aObject, nsIAtom *aKey, void *aHandler, void *aData)
 {
   nsHandlerData *handlerData = static_cast<nsHandlerData*>(aData);
   nsCOMPtr<nsIDOMUserDataHandler> handler =
     static_cast<nsIDOMUserDataHandler*>(aHandler);
   nsINode *node = static_cast<nsINode*>(aObject);
   nsCOMPtr<nsIVariant> data =
     static_cast<nsIVariant*>(node->GetProperty(DOM_USER_DATA, aKey));
   NS_ASSERTION(data, "Handler without data?");
 
+  if (!handlerData->mPusher.RePush(node)) {
+    return;
+  }
   nsAutoString key;
   aKey->ToString(key);
   handler->Handle(handlerData->mOperation, key, data, handlerData->mSource,
                   handlerData->mDest);
 }
 
 /* static */
 nsresult
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -2066,28 +2066,30 @@ static nsresult GetPartialTextRect(nsLay
                                    nsIContent* aContent, PRInt32 aStartOffset, PRInt32 aEndOffset)
 {
   nsIFrame* frame = aContent->GetPrimaryFrame();
   if (frame && frame->GetType() == nsGkAtoms::textFrame) {
     nsTextFrame* textFrame = static_cast<nsTextFrame*>(frame);
     nsIFrame* relativeTo = nsLayoutUtils::GetContainingBlockForClientRect(textFrame);
     for (nsTextFrame* f = textFrame; f; f = static_cast<nsTextFrame*>(f->GetNextContinuation())) {
       PRInt32 fstart = f->GetContentOffset(), fend = f->GetContentEnd();
-      PRBool rtl = f->GetTextRun()->IsRightToLeft();
       if (fend <= aStartOffset || fstart >= aEndOffset)
         continue;
 
-      //overlaping with the offset we want
+      // overlapping with the offset we want
+      f->EnsureTextRun();
+      NS_ENSURE_TRUE(f->GetTextRun(), NS_ERROR_OUT_OF_MEMORY);
+      PRBool rtl = f->GetTextRun()->IsRightToLeft();
       nsRect r(f->GetOffsetTo(relativeTo), f->GetSize());
       if (fstart < aStartOffset) {
-        //aStartOffset is within this frame
+        // aStartOffset is within this frame
         ExtractRectFromOffset(f, relativeTo, aStartOffset, &r, rtl);
       }
       if (fend > aEndOffset) {
-        //aEndOffset is in the middle of this frame
+        // aEndOffset is in the middle of this frame
         ExtractRectFromOffset(f, relativeTo, aEndOffset, &r, !rtl);
       }
       aCallback->AddRect(r);
     }
   }
   return NS_OK;
 }
 
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -373,16 +373,18 @@ include $(topsrcdir)/config/rules.mk
 		test_bug558726.html \
 		test_bug557892.html \
 		file_bug557892.html \
 		test_bug559526.html \
 		test_csp_redirects.html \
 		file_csp_redirects_page.sjs \
 		file_csp_redirects_main.html \
 		file_csp_redirects_resource.sjs \
+		test_bug346485.html \
+		test_bug560780.html \
 		$(NULL)
 
 # This test fails on the Mac for some reason
 ifneq (,$(filter gtk2 windows,$(MOZ_WIDGET_TOOLKIT)))
 _TEST_FILES += 	test_copyimage.html \
 		$(NULL)
 endif
 
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug346485.html
@@ -0,0 +1,77 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=346485
+-->
+<head>
+  <title>Test for Bug 346485</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=346485">Mozilla Bug 346485</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  <input id='a'>
+  <input id='b'>
+  <output id='o' for='a b'></output>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 346485 **/
+
+/**
+ * This test is testing DOMSettableTokenList used by the output element.
+ */
+
+var o = document.getElementById('o');
+
+is(o.htmlFor, 'a b',
+  "htmlFor IDL attribute should reflect for content attribute");
+
+is(o.htmlFor.value, 'a b',
+  "value should return the underlying string");
+
+is(o.htmlFor.length, 2, "Size should be '2'");
+
+ok(o.htmlFor.contains('a'), "It should contain 'a' token'");
+ok(!o.htmlFor.contains('c'), "It should not contain 'c' token");
+
+is(o.htmlFor.item(0), 'a', "First item is 'a' token'");
+is(o.htmlFor.item(42), null, "Out-of-range should return null");
+
+o.htmlFor.add('c');
+is(o.htmlFor, 'a b c', "'c' token should have been added");
+is(o.htmlFor.length, 3, "Size should be '3'");
+
+o.htmlFor.add('a');
+is(o.htmlFor, 'a b c', "Nothing should have changed");
+is(o.htmlFor.length, 3, "Size should be '3'");
+
+o.htmlFor.remove('a');
+is(o.htmlFor, 'b c', "'a' token should have been removed");
+is(o.htmlFor.length, 2, "Size should be '2'");
+
+o.htmlFor.remove('d');
+is(o.htmlFor, 'b c', "Nothing should have been removed");
+is(o.htmlFor.length, 2, "Size should be '2'");
+
+o.htmlFor.toggle('a');
+is(o.htmlFor, 'b c a', "'a' token should have been added");
+is(o.htmlFor.length, 3, "Size should be '3'");
+
+o.htmlFor.toggle('b');
+is(o.htmlFor, 'c a', "Nothing should have changed");
+is(o.htmlFor.length, 2, "Size should be '2'");
+
+o.htmlFor.value = "foo bar";
+is(o.htmlFor, 'foo bar', "The underlying string should have changed");
+is(o.htmlFor.length, 2, "Size should be '2'");
+ok(o.htmlFor.contains('foo'), "It should contain 'foo'");
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/base/test/test_bug515401.html
+++ b/content/base/test/test_bug515401.html
@@ -1,9 +1,9 @@
-<<!DOCTYPE HTML>
+<!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=515401
 -->
 <head>
   <title>Test for Bug 515401</title>
   <script type="text/javascript" src="/MochiKit/packed.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
@@ -91,17 +91,17 @@ verifyBase("base5/", "set href on existi
 // Unset href on second
 basehref2.removeAttribute("href");
 verifyBase("base5/", "unset href on second");
 
 // Insert base with href before existing
 var basehref0 = document.createElement("base");
 basehref0.href = "base6/";
 verifyBase("base5/", "nothing modified");
-head.insertBefore(basehref0, head.firstChild.nextElementSibling);
+head.insertBefore(basehref0, head.firstChild);
 verifyBase("base6/", "insert base with href before existing");
 
 // Insert base as grandchild of head
 var baseerr = document.createElement("base");
 baseerr.href = "baseerr/";
 var tmp = document.createElement("head");
 tmp.appendChild(baseerr);
 head.insertBefore(tmp, head.firstChild);
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug560780.html
@@ -0,0 +1,100 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=560780
+-->
+<head>
+  <title>Test for Bug 560780</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+
+<script  type="text/javascript">
+function init() {
+  var elem = document.getElementById('body');
+  elem.addEventListener('mousedown', mousedown, true);
+}
+var seen_mousedown = 0;
+function mousedown(event) {
+  var doc = event.target.ownerDocument;
+  var win = doc.defaultView;
+  var elem = doc.getElementById('body');
+  var selection = win.getSelection();
+  if (selection.rangeCount>0) {
+    var ragne = selection.getRangeAt(0);
+    var rect = ragne.getBoundingClientRect();
+    var p = elem.parentNode.appendChild(doc.createElement('p'));
+    p.textContent = "width: " + (rect.right -rect.left);
+  }
+  ++seen_mousedown;
+}
+</script>
+
+</head>
+<body id="body">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=560780">Mozilla Bug 560780</a>
+<p id="display" style="margin:0;padding:0;border:0"><a id="testlink" href="#aaaaaaaaaaaaaaaaaaaaaa">abcdefghijklmnabcdefghijklmn</a></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+  1.Start Minefield with New Profile.
+  2.Select texts by alt + mouse dragging horizontaly from 'd' in the link above to far right of window.
+  3.Click on the selected text
+  4.Click empty area of page
+  5.Repeat STEP 2 to 4 till browser crashes. (at least 5 times)
+
+<script type="application/javascript">
+
+/** Test for Bug 560780 **/
+
+function selectByMouseThenClick(elm,startx,starty) {
+  // select some text
+  var ctrl = navigator.platform.indexOf("Linux") ? true : false;
+  var alt  = true;
+  var x = startx;
+  synthesizeMouse(elm, x,        starty, { type:"mousedown", ctrlKey:ctrl, altKey:alt }); 
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x += 100, starty, { type:"mousemove", ctrlKey:ctrl, altKey:alt });
+  synthesizeMouse(elm, x,        starty, { type:"mouseup",   ctrlKey:ctrl, altKey:alt });
+
+  // click on the selection
+  synthesizeMouse(elm, startx + 10, starty + 1, {}); 
+
+  // click empty area of the page
+  synthesizeMouse(document.getElementById('body'), 800, 800, {}); 
+}
+
+function runTest() {
+  var e = document.getElementById('testlink');
+  selectByMouseThenClick(e,110,5);
+  selectByMouseThenClick(e,90,5);
+  selectByMouseThenClick(e,70,5);
+  selectByMouseThenClick(e,50,5);
+  selectByMouseThenClick(e,30,5);
+  selectByMouseThenClick(e,10,5);
+  is(seen_mousedown, 12, "got the mousedown events");
+  SimpleTest.finish();
+}
+
+function doTest() {
+  init();
+  runTest();
+}
+
+SimpleTest.waitForFocus(doTest, window);
+SimpleTest.waitForExplicitFinish();
+
+
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/canvas/src/WebGLContextNotSupported.cpp
+++ b/content/canvas/src/WebGLContextNotSupported.cpp
@@ -33,20 +33,29 @@
  * 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 ***** */
 
 #include "nsICanvasRenderingContextWebGL.h"
 #include "WebGLArray.h"
+#include "nsDOMClassInfoID.h"
 
 #define DUMMY(func,rtype)  nsresult func (rtype ** aResult) { return NS_ERROR_FAILURE; }
 
 DUMMY(NS_NewCanvasRenderingContextWebGL, nsICanvasRenderingContextWebGL)
 DUMMY(NS_NewWebGLFloatArray, nsISupports)
 DUMMY(NS_NewWebGLByteArray, nsISupports)
 DUMMY(NS_NewWebGLUnsignedByteArray, nsISupports)
 DUMMY(NS_NewWebGLShortArray, nsISupports)
 DUMMY(NS_NewWebGLUnsignedShortArray, nsISupports)
 DUMMY(NS_NewWebGLIntArray, nsISupports)
 DUMMY(NS_NewWebGLUnsignedIntArray, nsISupports)
 DUMMY(NS_NewWebGLArrayBuffer, nsISupports)
+
+DOMCI_DATA(CanvasRenderingContextWebGL, void)
+DOMCI_DATA(WebGLBuffer, void)
+DOMCI_DATA(WebGLTexture, void)
+DOMCI_DATA(WebGLProgram, void)
+DOMCI_DATA(WebGLShader, void)
+DOMCI_DATA(WebGLFramebuffer, void)
+DOMCI_DATA(WebGLRenderbuffer, void)
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -4277,17 +4277,17 @@ nsEventStateManager::SetContentState(nsI
   return PR_TRUE;
 }
 
 NS_IMETHODIMP
 nsEventStateManager::ContentRemoved(nsIDocument* aDocument, nsIContent* aContent)
 {
   // inform the focus manager that the content is being removed. If this
   // content is focused, the focus will be removed without firing events.
-  nsIFocusManager* fm = nsFocusManager::GetFocusManager();
+  nsFocusManager* fm = nsFocusManager::GetFocusManager();
   if (fm)
     fm->ContentRemoved(aDocument, aContent);
 
   if (mHoverContent &&
       nsContentUtils::ContentIsDescendantOf(mHoverContent, aContent)) {
     // Since hover is hierarchical, set the current hover to the
     // content's parent node.
     mHoverContent = aContent->GetParent();
--- a/content/html/content/public/nsIFormControl.h
+++ b/content/html/content/public/nsIFormControl.h
@@ -57,20 +57,21 @@ class nsFormSubmission;
 #define NS_FORM_INPUT_IMAGE    10
 #define NS_FORM_INPUT_PASSWORD 11
 #define NS_FORM_INPUT_RADIO    12
 #define NS_FORM_INPUT_SUBMIT   13
 #define NS_FORM_INPUT_TEXT     14
 #define NS_FORM_LABEL          15
 #define NS_FORM_OPTION         16
 #define NS_FORM_OPTGROUP       17
-#define NS_FORM_LEGEND         18
-#define NS_FORM_SELECT         19
-#define NS_FORM_TEXTAREA       20
-#define NS_FORM_OBJECT         21
+#define NS_FORM_OUTPUT         18
+#define NS_FORM_LEGEND         19
+#define NS_FORM_SELECT         20
+#define NS_FORM_TEXTAREA       21
+#define NS_FORM_OBJECT         22
 
 #define NS_IFORMCONTROL_IID   \
 { 0x52dc1f0d, 0x1683, 0x4dd7, \
  { 0xae, 0x0a, 0xc4, 0x76, 0x10, 0x64, 0x2f, 0xa8 } }
 
 /**
  * Interface which all form controls (e.g. buttons, checkboxes, text,
  * radio buttons, select, etc) implement in addition to their dom specific
--- a/content/html/content/src/Makefile.in
+++ b/content/html/content/src/Makefile.in
@@ -82,16 +82,17 @@ CPPSRCS		= \
 		nsHTMLLinkElement.cpp \
 		nsHTMLMapElement.cpp \
 		nsHTMLMetaElement.cpp \
 		nsHTMLObjectElement.cpp \
 		nsHTMLOListElement.cpp \
 		nsHTMLSharedObjectElement.cpp \
 		nsHTMLOptionElement.cpp \
 		nsHTMLOptGroupElement.cpp \
+		nsHTMLOutputElement.cpp \
 		nsHTMLParagraphElement.cpp \
 		nsHTMLPreElement.cpp \
 		nsHTMLScriptElement.cpp \
 		nsHTMLSelectElement.cpp \
 		nsHTMLSharedElement.cpp \
 		nsHTMLSpanElement.cpp \
 		nsHTMLStyleElement.cpp \
 		nsHTMLTableElement.cpp \
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -1157,17 +1157,17 @@ nsGenericHTMLElement::IsNodeOfType(PRUin
 PRBool
 nsGenericHTMLElement::ParseAttribute(PRInt32 aNamespaceID,
                                      nsIAtom* aAttribute,
                                      const nsAString& aValue,
                                      nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::dir) {
-      return aResult.ParseEnumValue(aValue, kDirTable);
+      return aResult.ParseEnumValue(aValue, kDirTable, PR_FALSE);
     }
   
     if (aAttribute == nsGkAtoms::tabindex) {
       return aResult.ParseIntWithBounds(aValue, -32768, 32767);
     }
 
     if (aAttribute == nsGkAtoms::name && !aValue.IsEmpty()) {
       // Store name as an atom.  name="" means that the element has no name,
@@ -1406,17 +1406,17 @@ static const nsAttrValue::EnumTable kTab
   { "baseline",NS_STYLE_VERTICAL_ALIGN_BASELINE },
   { 0 }
 };
 
 PRBool
 nsGenericHTMLElement::ParseAlignValue(const nsAString& aString,
                                       nsAttrValue& aResult)
 {
-  return aResult.ParseEnumValue(aString, kAlignTable);
+  return aResult.ParseEnumValue(aString, kAlignTable, PR_FALSE);
 }
 
 //----------------------------------------
 
 // Vanilla table as defined by the html4 spec...
 static const nsAttrValue::EnumTable kTableHAlignTable[] = {
   { "left",   NS_STYLE_TEXT_ALIGN_LEFT },
   { "right",  NS_STYLE_TEXT_ALIGN_RIGHT },
@@ -1439,19 +1439,19 @@ static const nsAttrValue::EnumTable kCom
   { 0 }
 };
 
 PRBool
 nsGenericHTMLElement::ParseTableHAlignValue(const nsAString& aString,
                                             nsAttrValue& aResult) const
 {
   if (InNavQuirksMode(GetOwnerDoc())) {
-    return aResult.ParseEnumValue(aString, kCompatTableHAlignTable);
+    return aResult.ParseEnumValue(aString, kCompatTableHAlignTable, PR_FALSE);
   }
-  return aResult.ParseEnumValue(aString, kTableHAlignTable);
+  return aResult.ParseEnumValue(aString, kTableHAlignTable, PR_FALSE);
 }
 
 //----------------------------------------
 
 // These tables are used for TD,TH,TR, etc (but not TABLE)
 static const nsAttrValue::EnumTable kTableCellHAlignTable[] = {
   { "left",   NS_STYLE_TEXT_ALIGN_MOZ_LEFT },
   { "right",  NS_STYLE_TEXT_ALIGN_MOZ_RIGHT },
@@ -1477,35 +1477,35 @@ static const nsAttrValue::EnumTable kCom
   { 0 }
 };
 
 PRBool
 nsGenericHTMLElement::ParseTableCellHAlignValue(const nsAString& aString,
                                                 nsAttrValue& aResult) const
 {
   if (InNavQuirksMode(GetOwnerDoc())) {
-    return aResult.ParseEnumValue(aString, kCompatTableCellHAlignTable);
+    return aResult.ParseEnumValue(aString, kCompatTableCellHAlignTable, PR_FALSE);
   }
-  return aResult.ParseEnumValue(aString, kTableCellHAlignTable);
+  return aResult.ParseEnumValue(aString, kTableCellHAlignTable, PR_FALSE);
 }
 
 //----------------------------------------
 
 PRBool
 nsGenericHTMLElement::ParseTableVAlignValue(const nsAString& aString,
                                             nsAttrValue& aResult)
 {
-  return aResult.ParseEnumValue(aString, kTableVAlignTable);
+  return aResult.ParseEnumValue(aString, kTableVAlignTable, PR_FALSE);
 }
 
-PRBool
+PRBool 
 nsGenericHTMLElement::ParseDivAlignValue(const nsAString& aString,
                                          nsAttrValue& aResult) const
 {
-  return aResult.ParseEnumValue(aString, kDivAlignTable);
+  return aResult.ParseEnumValue(aString, kDivAlignTable, PR_FALSE);
 }
 
 PRBool
 nsGenericHTMLElement::ParseImageAttribute(nsIAtom* aAttribute,
                                           const nsAString& aString,
                                           nsAttrValue& aResult)
 {
   if ((aAttribute == nsGkAtoms::width) ||
@@ -1519,24 +1519,24 @@ nsGenericHTMLElement::ParseImageAttribut
   }
   return PR_FALSE;
 }
 
 PRBool
 nsGenericHTMLElement::ParseFrameborderValue(const nsAString& aString,
                                             nsAttrValue& aResult)
 {
-  return aResult.ParseEnumValue(aString, kFrameborderTable);
+  return aResult.ParseEnumValue(aString, kFrameborderTable, PR_FALSE);
 }
 
 PRBool
 nsGenericHTMLElement::ParseScrollingValue(const nsAString& aString,
                                           nsAttrValue& aResult)
 {
-  return aResult.ParseEnumValue(aString, kScrollingTable);
+  return aResult.ParseEnumValue(aString, kScrollingTable, PR_FALSE);
 }
 
 /**
  * Handle attributes common to all html elements
  */
 void
 nsGenericHTMLElement::MapCommonAttributesInto(const nsMappedAttributes* aAttributes,
                                               nsRuleData* aData)
@@ -2134,16 +2134,34 @@ nsGenericHTMLElement::GetURIListAttr(nsI
         break;
     }
   }
 
   return NS_OK;
 }
 
 nsresult
+nsGenericHTMLElement::GetEnumAttr(nsIAtom* aAttr,
+                                  const char* aDefault,
+                                  nsAString& aResult)
+{
+  const nsAttrValue* attrVal = mAttrsAndChildren.GetAttr(aAttr);
+
+  aResult.Truncate();
+
+  if (attrVal && attrVal->Type() == nsAttrValue::eEnum) {
+    attrVal->GetEnumString(aResult, PR_TRUE);
+  } else {
+    AppendASCIItoUTF16(nsDependentCString(aDefault), aResult);
+  }
+
+  return NS_OK;
+}
+
+nsresult
 nsGenericHTMLElement::GetContentEditable(nsAString& aContentEditable)
 {
   ContentEditableTristate value = GetContentEditableValue();
 
   if (value == eTrue) {
     aContentEditable.AssignLiteral("true");
   }
   else if (value == eFalse) {
@@ -2547,17 +2565,18 @@ PRBool
 nsGenericHTMLFormElement::CanBeDisabled() const
 {
   PRInt32 type = GetType();
   // It's easier to test the types that _cannot_ be disabled
   return
     type != NS_FORM_LABEL &&
     type != NS_FORM_LEGEND &&
     type != NS_FORM_FIELDSET &&
-    type != NS_FORM_OBJECT;
+    type != NS_FORM_OBJECT &&
+    type != NS_FORM_OUTPUT;
 }
 
 PRBool
 nsGenericHTMLFormElement::IsSubmitControl() const
 {
   PRInt32 type = GetType();
   return type == NS_FORM_INPUT_SUBMIT ||
          type == NS_FORM_BUTTON_SUBMIT ||
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -658,16 +658,29 @@ protected:
    * attributes in null namespace.
    *
    * @param aAttr    name of attribute.
    * @param aResult  result value [out]
    */
   NS_HIDDEN_(nsresult) GetURIListAttr(nsIAtom* aAttr, nsAString& aResult);
 
   /**
+   * Helper method for NS_IMPL_ENUM_ATTR_DEFAULT_VALUE.
+   * Gets the enum value string of an attribute and using a default value if
+   * the attribute is missing or the string is an invalid enum value.
+   *
+   * @param aType     the name of the attribute.
+   * @param aDefault  the default value if the attribute is missing or invalid.
+   * @param aResult   string corresponding to the value [out].
+   */
+  NS_HIDDEN_(nsresult) GetEnumAttr(nsIAtom* aAttr,
+                                   const char* aDefault,
+                                   nsAString& aResult);
+
+  /**
    * Locates the nsIEditor associated with this node.  In general this is
    * equivalent to GetEditorInternal(), but for designmode or contenteditable,
    * this may need to get an editor that's not actually on this element's
    * associated TextControlFrame.  This is used by the spellchecking routines
    * to get the editor affected by changing the spellcheck attribute on this
    * node.
    */
   virtual already_AddRefed<nsIEditor> GetAssociatedEditor();
@@ -1059,16 +1072,33 @@ NS_NewHTML##_elementName##Element(nsINod
   {                                                                       \
     if (aValue < 0) {                                                     \
       return NS_ERROR_DOM_INDEX_SIZE_ERR;                                 \
     }                                                                     \
     return SetIntAttr(nsGkAtoms::_atom, aValue);                          \
   }
 
 /**
+ * A macro to implement the getter and setter for a given content
+ * property that needs to set an enumerated string. The method
+ * uses a specific GetEnumAttr and the generic SetAttrHelper methods.
+ */
+#define NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(_class, _method, _atom, _default) \
+  NS_IMETHODIMP                                                           \
+  _class::Get##_method(nsAString& aValue)                                 \
+  {                                                                       \
+    return GetEnumAttr(nsGkAtoms::_atom, _default, aValue);               \
+  }                                                                       \
+  NS_IMETHODIMP                                                           \
+  _class::Set##_method(const nsAString& aValue)                           \
+  {                                                                       \
+    return SetAttrHelper(nsGkAtoms::_atom, aValue);                       \
+  }
+
+/**
  * QueryInterface() implementation helper macros
  */
 
 #define NS_HTML_CONTENT_INTERFACE_TABLE_AMBIGUOUS_BEGIN(_class, _base)        \
   NS_NODE_OFFSET_AND_INTERFACE_TABLE_BEGIN(_class)                            \
     NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMNode, _base)             \
     NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMElement, _base)          \
     NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMHTMLElement, _base)
@@ -1241,16 +1271,17 @@ NS_DECLARE_NS_NEW_HTML_ELEMENT(LI)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Label)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Legend)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Link)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Map)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Meta)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Object)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(OptGroup)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Option)
+NS_DECLARE_NS_NEW_HTML_ELEMENT(Output)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Paragraph)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Pre)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Script)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Select)
 #if defined(MOZ_MEDIA)
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Source)
 #endif
 NS_DECLARE_NS_NEW_HTML_ELEMENT(Span)
--- a/content/html/content/src/nsHTMLBRElement.cpp
+++ b/content/html/content/src/nsHTMLBRElement.cpp
@@ -115,17 +115,17 @@ static const nsAttrValue::EnumTable kCle
 
 PRBool
 nsHTMLBRElement::ParseAttribute(PRInt32 aNamespaceID,
                                 nsIAtom* aAttribute,
                                 const nsAString& aValue,
                                 nsAttrValue& aResult)
 {
   if (aAttribute == nsGkAtoms::clear && aNamespaceID == kNameSpaceID_None) {
-    return aResult.ParseEnumValue(aValue, kClearTable);
+    return aResult.ParseEnumValue(aValue, kClearTable, PR_FALSE);
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
 static void
 MapAttributesIntoRule(const nsMappedAttributes* aAttributes,
--- a/content/html/content/src/nsHTMLButtonElement.cpp
+++ b/content/html/content/src/nsHTMLButtonElement.cpp
@@ -61,16 +61,26 @@
 #include "nsPresState.h"
 #include "nsLayoutErrors.h"
 #include "nsFocusManager.h"
 #include "nsHTMLFormElement.h"
 
 #define NS_IN_SUBMIT_CLICK      (1 << 0)
 #define NS_OUTER_ACTIVATE_EVENT (1 << 1)
 
+static const nsAttrValue::EnumTable kButtonTypeTable[] = {
+  { "button", NS_FORM_BUTTON_BUTTON },
+  { "reset", NS_FORM_BUTTON_RESET },
+  { "submit", NS_FORM_BUTTON_SUBMIT },
+  { 0 }
+};
+
+// Default type is 'submit'.
+static const nsAttrValue::EnumTable* kButtonDefaultType = &kButtonTypeTable[2];
+
 class nsHTMLButtonElement : public nsGenericHTMLFormElement,
                             public nsIDOMHTMLButtonElement,
                             public nsIDOMNSHTMLButtonElement
 {
 public:
   nsHTMLButtonElement(nsINodeInfo *aNodeInfo);
   virtual ~nsHTMLButtonElement();
 
@@ -105,16 +115,21 @@ public:
   NS_IMETHOD SaveState();
   PRBool RestoreState(nsPresState* aState);
 
   /**
    * Called when an attribute is about to be changed
    */
   virtual nsresult BeforeSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                                  const nsAString* aValue, PRBool aNotify);
+  /**
+   * Called when an attribute has just been changed
+   */
+  nsresult AfterSetAttr(PRInt32 aNamespaceID, nsIAtom* aName,
+                        const nsAString* aValue, PRBool aNotify);
   
   // nsIContent overrides...
   virtual PRBool IsHTMLFocusable(PRBool *aIsFocusable, PRInt32 *aTabIndex);
   virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
                                 nsIAtom* aAttribute,
                                 const nsAString& aValue,
                                 nsAttrValue& aResult);
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
@@ -139,17 +154,17 @@ private:
 // Construction, destruction
 
 
 NS_IMPL_NS_NEW_HTML_ELEMENT(Button)
 
 
 nsHTMLButtonElement::nsHTMLButtonElement(nsINodeInfo *aNodeInfo)
   : nsGenericHTMLFormElement(aNodeInfo),
-    mType(NS_FORM_BUTTON_SUBMIT),  // default
+    mType(kButtonDefaultType->value),
     mHandlingClick(PR_FALSE),
     mDisabledChanged(PR_FALSE),
     mInInternalActivate(PR_FALSE)
 {
 }
 
 nsHTMLButtonElement::~nsHTMLButtonElement()
 {
@@ -186,17 +201,18 @@ nsHTMLButtonElement::GetForm(nsIDOMHTMLF
   return nsGenericHTMLFormElement::GetForm(aForm);
 }
 
 NS_IMPL_STRING_ATTR(nsHTMLButtonElement, AccessKey, accesskey)
 NS_IMPL_BOOL_ATTR(nsHTMLButtonElement, Disabled, disabled)
 NS_IMPL_STRING_ATTR(nsHTMLButtonElement, Name, name)
 NS_IMPL_INT_ATTR_DEFAULT_VALUE(nsHTMLButtonElement, TabIndex, tabindex, 0)
 NS_IMPL_STRING_ATTR(nsHTMLButtonElement, Value, value)
-NS_IMPL_STRING_ATTR_DEFAULT_VALUE(nsHTMLButtonElement, Type, type, "submit")
+NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLButtonElement, Type, type,
+                                kButtonDefaultType->tag)
 
 NS_IMETHODIMP
 nsHTMLButtonElement::Blur()
 {
   return nsGenericHTMLElement::Blur();
 }
 
 NS_IMETHODIMP
@@ -250,37 +266,33 @@ nsHTMLButtonElement::IsHTMLFocusable(PRB
     *aTabIndex = -1;
   }
 
   *aIsFocusable = !HasAttr(kNameSpaceID_None, nsGkAtoms::disabled);
 
   return PR_FALSE;
 }
 
-static const nsAttrValue::EnumTable kButtonTypeTable[] = {
-  { "button", NS_FORM_BUTTON_BUTTON },
-  { "reset", NS_FORM_BUTTON_RESET },
-  { "submit", NS_FORM_BUTTON_SUBMIT },
-  { 0 }
-};
-
 PRBool
 nsHTMLButtonElement::ParseAttribute(PRInt32 aNamespaceID,
                                     nsIAtom* aAttribute,
                                     const nsAString& aValue,
                                     nsAttrValue& aResult)
 {
   if (aAttribute == nsGkAtoms::type && kNameSpaceID_None == aNamespaceID) {
     // XXX ARG!! This is major evilness. ParseAttribute
     // shouldn't set members. Override SetAttr instead
-    PRBool res = aResult.ParseEnumValue(aValue, kButtonTypeTable);
-    if (res) {
+    PRBool success = aResult.ParseEnumValue(aValue, kButtonTypeTable, PR_FALSE);
+    if (success) {
       mType = aResult.GetEnumValue();
+    } else {
+      mType = kButtonDefaultType->value;
     }
-    return res;
+
+    return success;
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
 nsresult
 nsHTMLButtonElement::PreHandleEvent(nsEventChainPreVisitor& aVisitor)
@@ -569,16 +581,29 @@ nsHTMLButtonElement::BeforeSetAttr(PRInt
       aNameSpaceID == kNameSpaceID_None) {
     mDisabledChanged = PR_TRUE;
   }
 
   return nsGenericHTMLFormElement::BeforeSetAttr(aNameSpaceID, aName,
                                                  aValue, aNotify);
 }
 
+nsresult
+nsHTMLButtonElement::AfterSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
+                                  const nsAString* aValue, PRBool aNotify)
+{
+  if (!aValue && aNameSpaceID == kNameSpaceID_None &&
+    aName == nsGkAtoms::type) {
+    mType = kButtonDefaultType->value;
+  }
+
+  return nsGenericHTMLFormElement::AfterSetAttr(aNameSpaceID, aName,
+                                                aValue, aNotify);
+}
+
 NS_IMETHODIMP
 nsHTMLButtonElement::SaveState()
 {
   if (!mDisabledChanged) {
     return NS_OK;
   }
   
   nsPresState *state = nsnull;
--- a/content/html/content/src/nsHTMLFontElement.cpp
+++ b/content/html/content/src/nsHTMLFontElement.cpp
@@ -146,17 +146,17 @@ nsHTMLFontElement::ParseAttribute(PRInt3
                                   nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::size) {
       nsAutoString tmp(aValue);
       tmp.CompressWhitespace(PR_TRUE, PR_TRUE);
       PRUnichar ch = tmp.IsEmpty() ? 0 : tmp.First();
       if ((ch == '+' || ch == '-') &&
-          aResult.ParseEnumValue(aValue, kRelFontSizeTable)) {
+          aResult.ParseEnumValue(aValue, kRelFontSizeTable, PR_FALSE)) {
         return PR_TRUE;
       }
 
       return aResult.ParseIntValue(aValue);
     }
     if (aAttribute == nsGkAtoms::pointSize ||
         aAttribute == nsGkAtoms::fontWeight) {
       return aResult.ParseIntValue(aValue);
--- a/content/html/content/src/nsHTMLFormElement.cpp
+++ b/content/html/content/src/nsHTMLFormElement.cpp
@@ -186,16 +186,17 @@ ShouldBeInElements(nsIFormControl* aForm
   case NS_FORM_INPUT_PASSWORD :
   case NS_FORM_INPUT_RADIO :
   case NS_FORM_INPUT_SUBMIT :
   case NS_FORM_INPUT_TEXT :
   case NS_FORM_SELECT :
   case NS_FORM_TEXTAREA :
   case NS_FORM_FIELDSET :
   case NS_FORM_OBJECT :
+  case NS_FORM_OUTPUT :
     return PR_TRUE;
   }
 
   // These form control types are not supposed to end up in the
   // form.elements array
   //
   // NS_FORM_INPUT_IMAGE
   // NS_FORM_LABEL
@@ -431,20 +432,20 @@ static const nsAttrValue::EnumTable kFor
 PRBool
 nsHTMLFormElement::ParseAttribute(PRInt32 aNamespaceID,
                                   nsIAtom* aAttribute,
                                   const nsAString& aValue,
                                   nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::method) {
-      return aResult.ParseEnumValue(aValue, kFormMethodTable);
+      return aResult.ParseEnumValue(aValue, kFormMethodTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::enctype) {
-      return aResult.ParseEnumValue(aValue, kFormEnctypeTable);
+      return aResult.ParseEnumValue(aValue, kFormEnctypeTable, PR_FALSE);
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
 nsresult
--- a/content/html/content/src/nsHTMLHRElement.cpp
+++ b/content/html/content/src/nsHTMLHRElement.cpp
@@ -134,17 +134,17 @@ nsHTMLHRElement::ParseAttribute(PRInt32 
   if (aNamespaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::width) {
       return aResult.ParseSpecialIntValue(aValue, PR_TRUE);
     }
     if (aAttribute == nsGkAtoms::size) {
       return aResult.ParseIntWithBounds(aValue, 1, 1000);
     }
     if (aAttribute == nsGkAtoms::align) {
-      return aResult.ParseEnumValue(aValue, kAlignTable);
+      return aResult.ParseEnumValue(aValue, kAlignTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::color) {
       return aResult.ParseColor(aValue, GetOwnerDoc());
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -148,16 +148,33 @@ static NS_DEFINE_CID(kLookAndFeelCID, NS
   NS_ORIGINAL_INDETERMINATE_VALUE))
 
 static const char kWhitespace[] = "\n\r\t\b";
 
 // whether textfields should be selected once focused:
 //  -1: no, 1: yes, 0: uninitialized
 static PRInt32 gSelectTextFieldOnFocus;
 
+static const nsAttrValue::EnumTable kInputTypeTable[] = {
+  { "button", NS_FORM_INPUT_BUTTON },
+  { "checkbox", NS_FORM_INPUT_CHECKBOX },
+  { "file", NS_FORM_INPUT_FILE },
+  { "hidden", NS_FORM_INPUT_HIDDEN },
+  { "reset", NS_FORM_INPUT_RESET },
+  { "image", NS_FORM_INPUT_IMAGE },
+  { "password", NS_FORM_INPUT_PASSWORD },
+  { "radio", NS_FORM_INPUT_RADIO },
+  { "submit", NS_FORM_INPUT_SUBMIT },
+  { "text", NS_FORM_INPUT_TEXT },
+  { 0 }
+};
+
+// Default type is 'text'.
+static const nsAttrValue::EnumTable* kInputDefaultType = &kInputTypeTable[9];
+
 #define NS_INPUT_ELEMENT_STATE_IID                 \
 { /* dc3b3d14-23e2-4479-b513-7b369343e3a0 */       \
   0xdc3b3d14,                                      \
   0x23e2,                                          \
   0x4479,                                          \
   {0xb5, 0x13, 0x7b, 0x36, 0x93, 0x43, 0xe3, 0xa0} \
 }
 
@@ -473,17 +490,17 @@ static nsresult FireEventForAccessibilit
 // construction, destruction
 //
 
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Input)
 
 nsHTMLInputElement::nsHTMLInputElement(nsINodeInfo *aNodeInfo,
                                        PRBool aFromParser)
   : nsGenericHTMLFormElement(aNodeInfo),
-    mType(NS_FORM_INPUT_TEXT), // default value
+    mType(kInputDefaultType->value),
     mBitField(0),
     mValue(nsnull)
 {
   SET_BOOLBIT(mBitField, BF_PARSER_CREATING, aFromParser);
 }
 
 nsHTMLInputElement::~nsHTMLInputElement()
 {
@@ -671,17 +688,17 @@ nsHTMLInputElement::AfterSetAttr(PRInt32
       MOZ_AUTO_DOC_UPDATE(document, UPDATE_CONTENT_STATE, aNotify);
 
       UpdateEditableState();
 
       if (!aValue) {
         // We're now a text input.  Note that we have to handle this manually,
         // since removing an attribute (which is what happened, since aValue is
         // null) doesn't call ParseAttribute.
-        mType = NS_FORM_INPUT_TEXT;
+        mType = kInputDefaultType->value;
       }
     
       // If we are changing type from File/Text/Passwd to other input types
       // we need save the mValue into value attribute
       if (mValue &&
           mType != NS_FORM_INPUT_TEXT &&
           mType != NS_FORM_INPUT_PASSWORD &&
           mType != NS_FORM_INPUT_FILE) {
@@ -768,18 +785,19 @@ NS_IMPL_BOOL_ATTR(nsHTMLInputElement, Mu
 NS_IMPL_NON_NEGATIVE_INT_ATTR(nsHTMLInputElement, MaxLength, maxlength)
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, Name, name)
 NS_IMPL_BOOL_ATTR(nsHTMLInputElement, ReadOnly, readonly)
 NS_IMPL_URI_ATTR(nsHTMLInputElement, Src, src)
 NS_IMPL_INT_ATTR_DEFAULT_VALUE(nsHTMLInputElement, TabIndex, tabindex, 0)
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, UseMap, usemap)
 //NS_IMPL_STRING_ATTR(nsHTMLInputElement, Value, value)
 //NS_IMPL_INT_ATTR_DEFAULT_VALUE(nsHTMLInputElement, Size, size, 0)
-//NS_IMPL_STRING_ATTR_DEFAULT_VALUE(nsHTMLInputElement, Type, type, "text")
 NS_IMPL_STRING_ATTR(nsHTMLInputElement, Placeholder, placeholder)
+NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLInputElement, Type, type,
+                                kInputDefaultType->tag)
 
 NS_IMETHODIMP
 nsHTMLInputElement::GetDefaultValue(nsAString& aValue)
 {
   GetAttrHelper(nsGkAtoms::value, aValue);
 
   if (mType != NS_FORM_INPUT_HIDDEN) {
     // Bug 114997: trim \n, etc. for non-hidden inputs
@@ -2204,46 +2222,32 @@ nsHTMLInputElement::UnbindFromTree(PRBoo
   // have a form
   if (!mForm && mType == NS_FORM_INPUT_RADIO) {
     WillRemoveFromRadioGroup();
   }
 
   nsGenericHTMLFormElement::UnbindFromTree(aDeep, aNullParent);
 }
 
-static const nsAttrValue::EnumTable kInputTypeTable[] = {
-  { "button", NS_FORM_INPUT_BUTTON },
-  { "checkbox", NS_FORM_INPUT_CHECKBOX },
-  { "file", NS_FORM_INPUT_FILE },
-  { "hidden", NS_FORM_INPUT_HIDDEN },
-  { "reset", NS_FORM_INPUT_RESET },
-  { "image", NS_FORM_INPUT_IMAGE },
-  { "password", NS_FORM_INPUT_PASSWORD },
-  { "radio", NS_FORM_INPUT_RADIO },
-  { "submit", NS_FORM_INPUT_SUBMIT },
-  { "text", NS_FORM_INPUT_TEXT },
-  { 0 }
-};
-
 PRBool
 nsHTMLInputElement::ParseAttribute(PRInt32 aNamespaceID,
                                    nsIAtom* aAttribute,
                                    const nsAString& aValue,
                                    nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::type) {
       // XXX ARG!! This is major evilness. ParseAttribute
       // shouldn't set members. Override SetAttr instead
       PRInt32 newType;
-      PRBool success;
-      if ((success = aResult.ParseEnumValue(aValue, kInputTypeTable))) {
+      PRBool success = aResult.ParseEnumValue(aValue, kInputTypeTable, PR_FALSE);
+      if (success) {
         newType = aResult.GetEnumValue();
       } else {
-        newType = NS_FORM_INPUT_TEXT;
+        newType = kInputDefaultType->value;
       }
 
       if (newType != mType) {
         // Make sure to do the check for newType being NS_FORM_INPUT_FILE and
         // the corresponding SetValueInternal() call _before_ we set mType.
         // That way the logic in SetValueInternal() will work right (that logic
         // makes assumptions about our frame based on mType, but we won't have
         // had time to recreate frames yet -- that happens later in the
@@ -2286,44 +2290,16 @@ nsHTMLInputElement::ParseAttribute(PRInt
       return PR_TRUE;
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
-NS_IMETHODIMP
-nsHTMLInputElement::GetType(nsAString& aValue)
-{
-  const nsAttrValue::EnumTable *table = kInputTypeTable;
-
-  while (table->tag) {
-    if (mType == table->value) {
-      CopyUTF8toUTF16(table->tag, aValue);
-
-      return NS_OK;
-    }
-
-    ++table;
-  }
-
-  NS_ERROR("Shouldn't get here!");
-
-  aValue.Truncate();
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLInputElement::SetType(const nsAString& aValue)
-{
-  return SetAttrHelper(nsGkAtoms::type, aValue);
-}
-
 static void
 MapAttributesIntoRule(const nsMappedAttributes* aAttributes,
                       nsRuleData* aData)
 {
   const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::type);
   if (value && value->Type() == nsAttrValue::eEnum &&
       value->GetEnumValue() == NS_FORM_INPUT_IMAGE) {
     nsGenericHTMLFormElement::MapImageBorderAttributeInto(aAttributes, aData);
--- a/content/html/content/src/nsHTMLLIElement.cpp
+++ b/content/html/content/src/nsHTMLLIElement.cpp
@@ -130,17 +130,17 @@ nsHTMLLIElement::ParseAttribute(PRInt32 
                                 nsIAtom* aAttribute,
                                 const nsAString& aValue,
                                 nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::type) {
       return aResult.ParseEnumValue(aValue, kOrderedListItemTypeTable,
                                     PR_TRUE) ||
-             aResult.ParseEnumValue(aValue, kUnorderedListItemTypeTable);
+             aResult.ParseEnumValue(aValue, kUnorderedListItemTypeTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::value) {
       return aResult.ParseIntWithBounds(aValue, 0);
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
--- a/content/html/content/src/nsHTMLLegendElement.cpp
+++ b/content/html/content/src/nsHTMLLegendElement.cpp
@@ -164,17 +164,17 @@ static const nsAttrValue::EnumTable kAli
 
 PRBool
 nsHTMLLegendElement::ParseAttribute(PRInt32 aNamespaceID,
                                     nsIAtom* aAttribute,
                                     const nsAString& aValue,
                                     nsAttrValue& aResult)
 {
   if (aAttribute == nsGkAtoms::align && aNamespaceID == kNameSpaceID_None) {
-    return aResult.ParseEnumValue(aValue, kAlignTable);
+    return aResult.ParseEnumValue(aValue, kAlignTable, PR_FALSE);
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
 nsChangeHint
 nsHTMLLegendElement::GetAttributeChangeHint(const nsIAtom* aAttribute,
--- a/content/html/content/src/nsHTMLOListElement.cpp
+++ b/content/html/content/src/nsHTMLOListElement.cpp
@@ -159,17 +159,17 @@ nsHTMLSharedListElement::ParseAttribute(
                                         nsIAtom* aAttribute,
                                         const nsAString& aValue,
                                         nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
     if (mNodeInfo->Equals(nsGkAtoms::ol) ||
         mNodeInfo->Equals(nsGkAtoms::ul)) {
       if (aAttribute == nsGkAtoms::type) {
-        return aResult.ParseEnumValue(aValue, kListTypeTable) ||
+        return aResult.ParseEnumValue(aValue, kListTypeTable, PR_FALSE) ||
                aResult.ParseEnumValue(aValue, kOldListTypeTable, PR_TRUE);
       }
       if (aAttribute == nsGkAtoms::start) {
         return aResult.ParseIntValue(aValue);
       }
     }
   }
 
--- a/content/html/content/src/nsHTMLObjectElement.cpp
+++ b/content/html/content/src/nsHTMLObjectElement.cpp
@@ -355,17 +355,17 @@ NS_IMPL_URI_ATTR_WITH_BASE(nsHTMLObjectE
 NS_IMPL_URI_ATTR(nsHTMLObjectElement, CodeBase, codebase)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, CodeType, codetype)
 NS_IMPL_URI_ATTR_WITH_BASE(nsHTMLObjectElement, Data, data, codebase)
 NS_IMPL_BOOL_ATTR(nsHTMLObjectElement, Declare, declare)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, Height, height)
 NS_IMPL_INT_ATTR(nsHTMLObjectElement, Hspace, hspace)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, Name, name)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, Standby, standby)
-NS_IMPL_INT_ATTR(nsHTMLObjectElement, TabIndex, tabindex)
+NS_IMPL_INT_ATTR_DEFAULT_VALUE(nsHTMLObjectElement, TabIndex, tabindex, 0)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, Type, type)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, UseMap, usemap)
 NS_IMPL_INT_ATTR(nsHTMLObjectElement, Vspace, vspace)
 NS_IMPL_STRING_ATTR(nsHTMLObjectElement, Width, width)
 
 NS_IMETHODIMP
 nsHTMLObjectElement::GetContentDocument(nsIDOMDocument **aContentDocument)
 {
new file mode 100644
--- /dev/null
+++ b/content/html/content/src/nsHTMLOutputElement.cpp
@@ -0,0 +1,278 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Mounir Lamouri <mounir.lamouri@mozilla.com> (original author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of 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 ***** */
+
+#include "nsIDOMHTMLOutputElement.h"
+#include "nsGenericHTMLElement.h"
+#include "nsIFormSubmission.h"
+#include "nsDOMSettableTokenList.h"
+#include "nsStubMutationObserver.h"
+
+
+class nsHTMLOutputElement : public nsGenericHTMLFormElement,
+                            public nsIDOMHTMLOutputElement,
+                            public nsStubMutationObserver
+{
+public:
+  nsHTMLOutputElement(nsINodeInfo *aNodeInfo);
+  virtual ~nsHTMLOutputElement();
+
+  // nsISupports
+  NS_DECL_ISUPPORTS_INHERITED
+
+  // nsIDOMNode
+  NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
+
+  // nsIDOMElement
+  NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLFormElement::)
+
+  // nsIDOMHTMLElement
+  NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLFormElement::)
+
+  // nsIDOMHTMLOutputElement
+  NS_DECL_NSIDOMHTMLOUTPUTELEMENT
+
+  // nsIFormControl
+  NS_IMETHOD_(PRInt32) GetType() const { return NS_FORM_OUTPUT; }
+  NS_IMETHOD Reset();
+  NS_IMETHOD SubmitNamesValues(nsFormSubmission* aFormSubmission,
+                               nsIContent* aSubmitElement);
+
+  nsresult Clone(nsINodeInfo* aNodeInfo, nsINode** aResult) const;
+
+  PRBool ParseAttribute(PRInt32 aNamespaceID, nsIAtom* aAttribute,
+                        const nsAString& aValue, nsAttrValue& aResult);
+
+  // This function is called when a callback function from nsIMutationObserver
+  // has to be used to update the defaultValue attribute.
+  void DescendantsChanged();
+
+  // nsIMutationObserver
+  void CharacterDataChanged(nsIDocument* aDocument,
+                            nsIContent* aContent,
+                            CharacterDataChangeInfo* aInfo);
+  void ContentAppended     (nsIDocument* aDocument,
+                            nsIContent* aContainer,
+                            PRInt32 aNewIndexInContainer);
+  void ContentInserted     (nsIDocument* aDocument,
+                            nsIContent* aContainer,
+                            nsIContent* aChild,
+                            PRInt32 aIndexInContainer);
+  void ContentRemoved      (nsIDocument* aDocument,
+                            nsIContent* aContainer,
+                            nsIContent* aChild,
+                            PRInt32 aIndexInContainer);
+
+
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED_NO_UNLINK(nsHTMLOutputElement,
+                                                     nsGenericHTMLFormElement)
+
+protected:
+  enum ValueModeFlag {
+    eModeDefault,
+    eModeValue
+  };
+
+  ValueModeFlag                     mValueModeFlag;
+  nsString                          mDefaultValue;
+  nsRefPtr<nsDOMSettableTokenList>  mTokenList;
+};
+
+
+NS_IMPL_NS_NEW_HTML_ELEMENT(Output)
+
+
+nsHTMLOutputElement::nsHTMLOutputElement(nsINodeInfo *aNodeInfo)
+  : nsGenericHTMLFormElement(aNodeInfo)
+  , mValueModeFlag(eModeDefault)
+{
+  AddMutationObserver(this);
+}
+
+nsHTMLOutputElement::~nsHTMLOutputElement()
+{
+  if (mTokenList) {
+    mTokenList->DropReference();
+  }
+}
+
+
+NS_IMPL_ADDREF_INHERITED(nsHTMLOutputElement, nsGenericElement)
+NS_IMPL_RELEASE_INHERITED(nsHTMLOutputElement, nsGenericElement)
+
+DOMCI_DATA(HTMLOutputElement, nsHTMLOutputElement)
+
+NS_INTERFACE_TABLE_HEAD(nsHTMLOutputElement)
+  NS_HTML_CONTENT_INTERFACE_TABLE2(nsHTMLOutputElement,
+                                   nsIDOMHTMLOutputElement,
+                                   nsIMutationObserver)
+  NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLOutputElement,
+                                               nsGenericHTMLFormElement)
+NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLOutputElement)
+
+NS_IMPL_ELEMENT_CLONE(nsHTMLOutputElement)
+
+
+NS_IMPL_STRING_ATTR(nsHTMLOutputElement, Name, name)
+
+NS_IMETHODIMP
+nsHTMLOutputElement::Reset()
+{
+  mValueModeFlag = eModeDefault;
+  nsresult rv = nsContentUtils::SetNodeTextContent(this, mDefaultValue,
+                                                   PR_TRUE);
+  return rv;
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::SubmitNamesValues(nsFormSubmission* aFormSubmission,
+                                       nsIContent* aSubmitElement)
+{
+  // The output element is not submittable.
+  return NS_OK;
+}
+
+PRBool
+nsHTMLOutputElement::ParseAttribute(PRInt32 aNamespaceID, nsIAtom* aAttribute,
+                                    const nsAString& aValue, nsAttrValue& aResult)
+{
+  if (aNamespaceID == kNameSpaceID_None) {
+    if (aAttribute == nsGkAtoms::_for) {
+      aResult.ParseAtomArray(aValue);
+      return PR_TRUE;
+    }
+  }
+
+  return nsGenericHTMLFormElement::ParseAttribute(aNamespaceID, aAttribute,
+                                                  aValue, aResult);
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::GetForm(nsIDOMHTMLFormElement** aForm)
+{
+  return nsGenericHTMLFormElement::GetForm(aForm);
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::GetType(nsAString& aType)
+{
+  aType.AssignLiteral("output");
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::GetValue(nsAString& aValue)
+{
+  nsContentUtils::GetNodeTextContent(this, PR_TRUE, aValue);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::SetValue(const nsAString& aValue)
+{
+  mValueModeFlag = eModeValue;
+  return nsContentUtils::SetNodeTextContent(this, aValue, PR_TRUE);
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::GetDefaultValue(nsAString& aDefaultValue)
+{
+  aDefaultValue = mDefaultValue;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::SetDefaultValue(const nsAString& aDefaultValue)
+{
+  mDefaultValue = aDefaultValue;
+  if (mValueModeFlag == eModeDefault) {
+    return nsContentUtils::SetNodeTextContent(this, mDefaultValue, PR_TRUE);
+  }
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHTMLOutputElement::GetHtmlFor(nsIDOMDOMSettableTokenList** aResult)
+{
+  if (!mTokenList) {
+    mTokenList = new nsDOMSettableTokenList(this, nsGkAtoms::_for);
+  }
+
+  NS_ADDREF(*aResult = mTokenList);
+
+  return NS_OK;
+}
+
+void nsHTMLOutputElement::DescendantsChanged()
+{
+  if (mValueModeFlag == eModeDefault) {
+    nsContentUtils::GetNodeTextContent(this, PR_TRUE, mDefaultValue);
+  }
+}
+
+// nsIMutationObserver
+
+void nsHTMLOutputElement::CharacterDataChanged(nsIDocument* aDocument,
+                                               nsIContent* aContent,
+                                               CharacterDataChangeInfo* aInfo)
+{
+  DescendantsChanged();
+}
+
+void nsHTMLOutputElement::ContentAppended(nsIDocument* aDocument,
+                                          nsIContent* aContainer,
+                                          PRInt32 aNewIndexInContainer)
+{
+  DescendantsChanged();
+}
+
+void nsHTMLOutputElement::ContentInserted(nsIDocument* aDocument,
+                                          nsIContent* aContainer,
+                                          nsIContent* aChild,
+                                          PRInt32 aIndexInContainer)
+{
+  DescendantsChanged();
+}
+
+void nsHTMLOutputElement::ContentRemoved(nsIDocument* aDocument,
+                                         nsIContent* aContainer,
+                                         nsIContent* aChild,
+                                         PRInt32 aIndexInContainer)
+{
+  DescendantsChanged();
+}
+
--- a/content/html/content/src/nsHTMLSharedElement.cpp
+++ b/content/html/content/src/nsHTMLSharedElement.cpp
@@ -258,17 +258,17 @@ nsHTMLSharedElement::ParseAttribute(PRIn
       if (aAttribute == nsGkAtoms::width ||
           aAttribute == nsGkAtoms::height) {
         return aResult.ParseSpecialIntValue(aValue, PR_TRUE);
       }
     }
     else if (mNodeInfo->Equals(nsGkAtoms::dir) ||
              mNodeInfo->Equals(nsGkAtoms::menu)) {
       if (aAttribute == nsGkAtoms::type) {
-        return aResult.ParseEnumValue(aValue, kListTypeTable);
+        return aResult.ParseEnumValue(aValue, kListTypeTable, PR_FALSE);
       }
       if (aAttribute == nsGkAtoms::start) {
         return aResult.ParseIntWithBounds(aValue, 1);
       }
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
--- a/content/html/content/src/nsHTMLTableCaptionElement.cpp
+++ b/content/html/content/src/nsHTMLTableCaptionElement.cpp
@@ -119,17 +119,17 @@ static const nsAttrValue::EnumTable kCap
 
 PRBool
 nsHTMLTableCaptionElement::ParseAttribute(PRInt32 aNamespaceID,
                                           nsIAtom* aAttribute,
                                           const nsAString& aValue,
                                           nsAttrValue& aResult)
 {
   if (aAttribute == nsGkAtoms::align && aNamespaceID == kNameSpaceID_None) {
-    return aResult.ParseEnumValue(aValue, kCaptionAlignTable);
+    return aResult.ParseEnumValue(aValue, kCaptionAlignTable, PR_FALSE);
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
 static 
 void MapAttributesIntoRule(const nsMappedAttributes* aAttributes, nsRuleData* aData)
--- a/content/html/content/src/nsHTMLTableCellElement.cpp
+++ b/content/html/content/src/nsHTMLTableCellElement.cpp
@@ -311,17 +311,17 @@ nsHTMLTableCellElement::ParseAttribute(P
     }
     if (aAttribute == nsGkAtoms::align) {
       return ParseTableCellHAlignValue(aValue, aResult);
     }
     if (aAttribute == nsGkAtoms::bgcolor) {
       return aResult.ParseColor(aValue, GetOwnerDoc());
     }
     if (aAttribute == nsGkAtoms::scope) {
-      return aResult.ParseEnumValue(aValue, kCellScopeTable);
+      return aResult.ParseEnumValue(aValue, kCellScopeTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::valign) {
       return ParseTableVAlignValue(aValue, aResult);
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
--- a/content/html/content/src/nsHTMLTableElement.cpp
+++ b/content/html/content/src/nsHTMLTableElement.cpp
@@ -1008,23 +1008,23 @@ nsHTMLTableElement::ParseAttribute(PRInt
     if (aAttribute == nsGkAtoms::align) {
       return ParseTableHAlignValue(aValue, aResult);
     }
     if (aAttribute == nsGkAtoms::bgcolor ||
         aAttribute == nsGkAtoms::bordercolor) {
       return aResult.ParseColor(aValue, GetOwnerDoc());
     }
     if (aAttribute == nsGkAtoms::frame) {
-      return aResult.ParseEnumValue(aValue, kFrameTable);
+      return aResult.ParseEnumValue(aValue, kFrameTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::layout) {
-      return aResult.ParseEnumValue(aValue, kLayoutTable);
+      return aResult.ParseEnumValue(aValue, kLayoutTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::rules) {
-      return aResult.ParseEnumValue(aValue, kRulesTable);
+      return aResult.ParseEnumValue(aValue, kRulesTable, PR_FALSE);
     }
     if (aAttribute == nsGkAtoms::hspace ||
         aAttribute == nsGkAtoms::vspace) {
       return aResult.ParseIntWithBounds(aValue, 0);
     }
   }
 
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -153,13 +153,16 @@ include $(topsrcdir)/config/rules.mk
 		test_bug529819.html \
 		test_bug529859.html \
 		test_bug535043.html \
 		test_bug547850.html \
 		test_bug457800.html \
 		test_bug536891.html \
 		test_bug536895.html \
 		test_bug458037.xhtml \
+		test_bug556645.html \
 		test_bug559284.html \
+        test_bug551670.html \
+        test_bug346485.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
--- a/content/html/content/test/file_bug209275_3.html
+++ b/content/html/content/test/file_bug209275_3.html
@@ -6,18 +6,18 @@
 <body onload="load();">
 Initial state
 
 <script>
 function load() {
   // Nuke and rebuild the page.  If document.open() clears the <base> properly,
   // our new <base> will take precedence and the test will pass.
   document.open();
-  document.write("<html><body><a id='link' href='/'>A</a>" +
-                 "<base href='http://mochi.test:8888' /></body></html>");
+  document.write("<html><base href='http://mochi.test:8888' /><body>" + 
+                 "<a id='link' href='/'>A</a></body></html>");
 
   // Tell our parent to have a look at us.
   parent.gGen.next();
 }
 </script>
 
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug346485.html
@@ -0,0 +1,179 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=346485
+-->
+<head>
+  <title>Test for Bug 346485</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=346485">Mozilla Bug 346485</a>
+<p id="display"></p>
+<iframe name="submit_frame" onload="checkFormSubmission();" style="visibility: hidden;"></iframe>
+<div id="content" style="display: none">
+  <form id='f' method='get' target='submit_frame' action='foo'>
+    <input name='a' id='a'>
+    <input name='b' id='b'>
+    <output id='o' for='a b' name='output-name'>tulip</output>
+  </form>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 346485 **/
+
+function checkNameAttribute(element)
+{
+  function nameAttributeEquals(element, expectedValue)
+  {
+    is(element.name, expectedValue, "Output name IDL attribute is not correct");
+    is(element.getAttribute('name'), expectedValue,
+      "Output name content attribute is not correct");
+  }
+
+  nameAttributeEquals(element, "output-name");
+
+  element.name = "new-name";
+  nameAttributeEquals(element, "new-name");
+
+  element.setAttribute('name', 'new-name-2');
+  nameAttributeEquals(element, "new-name-2");
+}
+
+function checkValueAndDefaultValueIDLAttribute(element)
+{
+  is(element.value, element.textContent,
+    "The value IDL attribute should act like the textContent IDL attribute");
+
+  element.value = "foo";
+  is(element.value, "foo", "Value should be 'foo'");
+
+  is(element.defaultValue, "", "Default defaultValue is ''");
+
+  element.defaultValue = "bar";
+  is(element.defaultValue, "bar", "defaultValue should be 'bar'");
+
+  // More complex situation.
+  element.textContent = 'foo';
+  var b = document.createElement('b');
+  b.textContent = 'bar'
+  element.appendChild(b);
+  is(element.value, element.textContent,
+    "The value IDL attribute should act like the textContent IDL attribute");
+}
+
+function checkValueModeFlag(element)
+{
+  /**
+   * The value mode flag is the flag used to know if value should represent the
+   * textContent or the default value.
+   */
+  // value mode flag should be 'value'
+  isnot(element.defaultValue, element.value,
+    "When value is set, defaultValue keeps its value");
+
+  var f = document.getElementById('f');
+  f.reset();
+  // value mode flag should be 'default'
+  is(element.defaultValue, element.value, "When reset, defaultValue=value");
+  is(element.textContent, element.defaultValue,
+    "textContent should contain the defaultValue");
+}
+
+function checkDescendantChanged(element)
+{
+  /**
+   * Whenever a descendant is changed if the value mode flag is value,
+   * the default value should be the textContent value.
+   */
+  element.defaultValue = 'tulip';
+  element.value = 'foo';
+
+  // set value mode flag to 'default'
+  var f = document.getElementById('f');
+  f.reset();
+
+  is(element.textContent, element.defaultValue,
+    "textContent should contain the defaultValue");
+  element.textContent = "bar";
+  is(element.textContent, element.defaultValue,
+    "textContent should contain the defaultValue");
+}
+
+function checkFormIDLAttribute(element)
+{
+  is(element.form, document.getElementById('f'),
+    "form IDL attribute is invalid");
+}
+
+function checkHtmlForIDLAttribute(element)
+{
+  is(element.htmlFor, 'a b',
+    "htmlFor IDL attribute should reflect the for content attribute");
+
+  // DOMSettableTokenList is tested in another bug so we just test assignation
+  element.htmlFor.value = 'a b c';
+  is(element.htmlFor, 'a b c', "htmlFor shoud have changed");
+}
+
+function submitForm()
+{
+  // Setting the values for the submit.
+  document.getElementById('o').value = 'foo';
+  document.getElementById('a').value = 'afield';
+  document.getElementById('b').value = 'bfield';
+
+  // This will call checkFormSubmission() which is going to call ST.finish().
+  document.getElementById('f').submit();
+}
+
+function checkFormSubmission()
+{
+  /**
+   * All elements values have been set just before the submission.
+   * The input elements values should be in the submit url but the ouput
+   * element value should not appear.
+   */
+
+  is(frames['submit_frame'].location.href,
+    'http://mochi.test:8888/tests/content/html/content/test/foo?a=afield&b=bfield',
+     "The output element value should not be submitted");
+  SimpleTest.finish();
+}
+
+SimpleTest.waitForExplicitFinish();
+
+var o = document.getElementsByTagName('output');
+is(o.length, 1, "There should be one output element");
+
+o = o[0];
+ok(o instanceof HTMLOutputElement,
+  "The output should be instance of HTMLOutputElement");
+
+o = document.getElementById('o');
+ok(o instanceof HTMLOutputElement,
+  "The output should be instance of HTMLOutputElement");
+
+is(o.type, "output", "Output type IDL attribute should be 'output'");
+
+checkNameAttribute(o);
+
+checkValueAndDefaultValueIDLAttribute(o);
+
+checkValueModeFlag(o);
+
+checkDescendantChanged(o);
+
+checkFormIDLAttribute(o);
+
+checkHtmlForIDLAttribute(o);
+
+submitForm();
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/content/test/test_bug430351.html
+++ b/content/html/content/test/test_bug430351.html
@@ -136,16 +136,17 @@ var focusableElements = [
     "<input type=\"submit\" contenteditable=\"true\">",
 
     "<input type=\"text\">",
     "<input type=\"text\" tabindex=\"-1\">",
     "<input type=\"text\" tabindex=\"0\">",
     "<input type=\"text\" tabindex=\"1\">",
     "<input type=\"text\" contenteditable=\"true\">",
 
+    "<object></object>",
     "<object tabindex=\"-1\"></object>",
     "<object tabindex=\"0\"></object>",
     "<object tabindex=\"1\"></object>",
     "<object contenteditable=\"true\"></object>",
 
     "<object classid=\"java:a\"></object>",
     "<object classid=\"java:a\" tabindex=\"-1\"></object>",
     "<object classid=\"java:a\" tabindex=\"0\"></object>",
@@ -235,17 +236,16 @@ var nonFocusableElements = [
     "<input type=\"reset\" disabled>",
 
     "<input type=\"submit\" tabindex=\"0\" disabled>",
     "<input type=\"submit\" disabled>",
 
     "<input type=\"text\" tabindex=\"0\" disabled>",
     "<input type=\"text\" disabled>",
 
-    "<object></object>",
     "<object tabindex=\"0\" disabled></object>",
     "<object disabled></object>",
 
     "<select tabindex=\"0\" disabled></select>",
     "<select disabled></select>"
 ];
 
 var focusableInContentEditable = [
@@ -343,19 +343,22 @@ var focusableInContentEditable = [
     "<input type=\"submit\" contenteditable=\"true\">",
 
     "<input type=\"text\">",
     "<input type=\"text\" tabindex=\"-1\">",
     "<input type=\"text\" tabindex=\"0\">",
     "<input type=\"text\" tabindex=\"1\">",
     "<input type=\"text\" contenteditable=\"true\">",
 
+    "<object></object>",
     "<object tabindex=\"-1\"></object>",
     "<object tabindex=\"0\"></object>",
     "<object tabindex=\"1\"></object>",
+    "<object contenteditable=\"true\"></object>",
+
     "<select></select>",
     "<select tabindex=\"-1\"></select>",
     "<select tabindex=\"0\"></select>",
     "<select tabindex=\"1\"></select>",
     "<select contenteditable=\"true\"></select>"
 ];
 
 var focusableInDesignMode = [
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug551670.html
@@ -0,0 +1,98 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=551670
+-->
+<head>
+  <title>Test for Bug 551670</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=551670">Mozilla Bug 551670</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  <button type='badtype' id='b1'></button>
+  <button id='b2'></button>
+  <input type='badtype' id='i1'>
+  <input id='i2'>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 551670 **/
+
+function checkType(e1, e2, defaultType, otherType, wrongType)
+{
+  // When accessing to the type attribute from the IDL,
+  // it should reflect the state of the button.
+
+  defaultType = defaultType.toLowerCase();
+  otherType = otherType.toLowerCase();
+
+  is(e1.type, defaultType,
+    "When the initial type attribute value is not valid, the state should be '" +
+    defaultType + "'");
+  is(e2.type, defaultType,
+    "When the type attribute is not set, the state should be '" +
+    defaultType + "'");
+
+  e1.type = otherType;
+  e1.setAttribute('type', '');
+  is(e1.type, defaultType,
+    "When type attribute is set to an empty string, the state should be '" +
+    defaultType + "'");
+
+  e1.type = otherType;
+  e1.type = '';
+  is(e1.type, defaultType,
+    "When type attribute is set to an empty string, the state should be '" +
+    defaultType + "'");
+
+  e1.type = otherType;
+  e1.setAttribute('type', wrongType);
+  is(e1.type, defaultType,
+    "When type attribute is set to an invalid value, the state should be '" +
+    defaultType + "'");
+  is(e1.getAttribute('type'), wrongType,
+    "Type attribute content should not be changed");
+
+  e1.type = otherType;
+  e1.type = wrongType;
+  is(e1.type, defaultType,
+    "When type attribute is set to an invalid value, the state should be '" +
+    defaultType + "'");
+  is(e1.getAttribute('type'), wrongType,
+    "Type attribute content should not be changed");
+
+  e1.type = otherType.toUpperCase();
+  is(e1.type, otherType, "Type attribute should be case insensitive");
+
+  e1.removeAttribute('type');
+  is(e1.type, defaultType,
+    "When type attribute is set to an empty string, the state should be '" +
+    defaultType + "'");
+}
+
+var wrongType = 'this-is-probably-a-wrong-type';
+
+// button types
+checkType(document.getElementById('b1'), document.getElementById('b2'), 'submit', 'button', wrongType);
+checkType(document.getElementById('b1'), document.getElementById('b2'), 'submit', 'reset', wrongType);
+
+// input types
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'button', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'checkbox', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'file', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'hidden', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'reset', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'image', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'password', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'radio', wrongType);
+checkType(document.getElementById('i1'), document.getElementById('i2'), 'text', 'submit', wrongType);
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug556645.html
@@ -0,0 +1,50 @@
+<html>
+<head>
+  <title>Test for Bug 556645</title>
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <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 onload="runTest()">
+<script>
+SimpleTest.waitForExplicitFinish();
+
+function runTest()
+{
+  var obj = document.getElementById("obj");
+  var childDoc = obj.contentDocument;
+  var body = childDoc.body;
+  is(document.activeElement, document.body, "focus in parent before");
+  is(childDoc.activeElement, body, "focus in child before");
+
+  var button = childDoc.getElementsByTagName("button")[0];
+  button.focus();
+  childDoc.defaultView.focus();
+  is(document.activeElement, obj, "focus in parent after focus()");
+  is(childDoc.activeElement, button, "focus in child after focus()");
+
+  button.blur();
+  var pbutton = document.getElementById("pbutton");
+  pbutton.focus();
+
+  synthesizeKey("VK_TAB", { });
+  is(document.activeElement, obj, "focus in parent after tab");
+  is(childDoc.activeElement, childDoc.documentElement, "focus in child after tab");
+
+  synthesizeKey("VK_TAB", { });
+  is(document.activeElement, obj, "focus in parent after tab 2");
+  is(childDoc.activeElement, button, "focus in child after tab 2");
+
+  SimpleTest.finish();
+}
+
+</script>
+
+<button id="pbutton">Parent</button>
+<object id="obj" type="text/html"
+        data="data:text/html,%3Cbody%3E%3Cbutton%3EChild%3C/button%3E%3C/body%3E"
+        width="200" height="200"></object>
+
+</body>
+</html>
--- a/content/html/document/test/test_bug255820.html
+++ b/content/html/document/test/test_bug255820.html
@@ -64,16 +64,21 @@ function f3Continue() {
                  'is(doc.defaultView.getComputedStyle(doc.body, "").color, ' +
                  '   "rgb(0, 180, 0)",' +
                  '   "Wrong color after reload");' +
                  "charsetTestFinished('f1', this.contentDocument, 'UTF-8')");
   $("f3").contentWindow.location.reload();
 }
 
 function runTest() {
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
+    .getService(Components.interfaces.nsIPrefBranch);
+  var html5enabled = prefs.getBoolPref("html5.enable");
+
   var doc = $("f1").contentDocument;
   is(doc.characterSet, "UTF-8",
      "Unexpected initial character set for first frame");
   doc.open();
   doc.write('<html></html>');
   doc.close();
   is(doc.characterSet, "UTF-8",
      "Unexpected character set for first frame after write");
@@ -90,20 +95,27 @@ function runTest() {
   str += '<script src="data:application/javascript,"><'+'/script>';
   str += '<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">';
   str += '</head><body>';
   str += '</body></html>';
   doc.write(str);
   doc.close();
   is(doc.characterSet, "UTF-8",
      "Unexpected character set for second frame after write");
-  $("f2").
-    setAttribute("onload",
-                 "charsetTestFinished('f2', this.contentDocument, 'us-ascii');" +
-                 "f2Continue()");
+  if (html5enabled) {
+    $("f2").
+      setAttribute("onload",
+        "charsetTestFinished('f2', this.contentDocument, 'UTF-8');" +
+        "f2Continue()");
+  } else {
+    $("f2").
+      setAttribute("onload",
+        "charsetTestFinished('f2', this.contentDocument, 'us-ascii');" +
+        "f2Continue()");
+  }
 
   doc = $("f3").contentDocument;
   is(doc.characterSet, "UTF-8",
      "Unexpected initial character set for first frame");
   doc.open();
   var str = '<html><head>';
   str += '<style>body { color: rgb(255, 0, 0) }</style>';
   str += '<link type="text/css" rel="stylesheet" href="data:text/css, body { color: rgb(0, 180, 0) }">';
--- a/content/media/Makefile.in
+++ b/content/media/Makefile.in
@@ -44,22 +44,25 @@ include $(DEPTH)/config/autoconf.mk
 MODULE = content
 LIBRARY_NAME = gkconmedia_s
 LIBXUL_LIBRARY = 1
 
 EXPORTS = \
   nsMediaDecoder.h \
   nsMediaStream.h \
   nsMediaCache.h \
+  nsBuiltinDecoder.h \
+  VideoUtils.h \
   $(NULL)
 
 CPPSRCS = \
   nsMediaDecoder.cpp \
   nsMediaCache.cpp \
   nsMediaStream.cpp \
+  nsBuiltinDecoder.cpp \
   $(NULL)
 
 ifdef MOZ_SYDNEYAUDIO
 EXPORTS += \
   nsAudioStream.h \
   $(NULL)
 CPPSRCS += \
   nsAudioStream.cpp \
rename from content/media/ogg/nsOggHacks.h
rename to content/media/VideoUtils.h
--- a/content/media/ogg/nsOggHacks.h
+++ b/content/media/VideoUtils.h
@@ -31,18 +31,20 @@
  * 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