Merging from cvs-trunk-mirror to mozilla-central.
authorjorendorff@mozilla.com
Mon, 19 Nov 2007 15:25:08 -0600
changeset 8097 74d4f075ce54b6e8a77a88dfaaa1d0bf2f665c58
parent 7266 da56edb3eb5b0d0517a5d9a4d5179967909164e1 (current diff)
parent 8096 f9cdde7fd181b7428d15a13df3d366f133857b95 (diff)
child 8341 9aa744529b957527bc1f4cfe53e6b84872b18719
push id1
push userbsmedberg@mozilla.com
push dateThu, 20 Mar 2008 16:49:24 +0000
treeherdermozilla-central@61007906a1f8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone1.9b2pre
Merging from cvs-trunk-mirror to mozilla-central.
browser/components/bookmarks/Makefile.in
browser/components/bookmarks/content/addBookmark.js
browser/components/bookmarks/content/addBookmark.xul
browser/components/bookmarks/content/addBookmark2.js
browser/components/bookmarks/content/addBookmark2.xul
browser/components/bookmarks/content/bookmarks.css
browser/components/bookmarks/content/bookmarks.js
browser/components/bookmarks/content/bookmarksManager.js
browser/components/bookmarks/content/bookmarksManager.xul
browser/components/bookmarks/content/bookmarksMenu.js
browser/components/bookmarks/content/bookmarksPanel.js
browser/components/bookmarks/content/bookmarksPanel.xul
browser/components/bookmarks/content/bookmarksProperties.js
browser/components/bookmarks/content/bookmarksProperties.xul
browser/components/bookmarks/content/bookmarksTree.xml
browser/components/bookmarks/content/microsummaryPicker.js
browser/components/bookmarks/content/selectBookmark.js
browser/components/bookmarks/content/selectBookmark.xul
browser/components/bookmarks/jar.mn
browser/components/bookmarks/public/Makefile.in
browser/components/bookmarks/public/nsIBookmarkTransactionManager.idl
browser/components/bookmarks/public/nsIBookmarksService.idl
browser/components/bookmarks/src/Makefile.in
browser/components/bookmarks/src/nsBookmarkTransactionManager.js
browser/components/bookmarks/src/nsBookmarksFeedHandler.cpp
browser/components/bookmarks/src/nsBookmarksService.cpp
browser/components/bookmarks/src/nsBookmarksService.h
browser/components/bookmarks/src/nsForwardProxyDataSource.cpp
browser/components/bookmarks/src/nsForwardProxyDataSource.h
browser/locales/en-US/chrome/browser/bookmarks/addBookmark.dtd
browser/locales/en-US/chrome/browser/bookmarks/bookmarks.dtd
browser/locales/en-US/chrome/browser/bookmarks/bookmarks.properties
browser/locales/en-US/chrome/browser/bookmarks/bookmarksProperties.dtd
browser/themes/gnomestripe/browser/Bookmarks-folder.png
browser/themes/gnomestripe/browser/Go-arrow.png
browser/themes/gnomestripe/browser/endcap-bkgnd-hover.png
browser/themes/gnomestripe/browser/endcap-bkgnd.png
browser/themes/gnomestripe/browser/feeds/feedIcon.png
browser/themes/gnomestripe/browser/feeds/feedIcon16.png
browser/themes/gnomestripe/browser/monitor.png
browser/themes/gnomestripe/browser/places/bookmarkProperties.css
browser/themes/gnomestripe/browser/places/bookmarksMenu.png
browser/themes/gnomestripe/browser/places/folderDragOver.png
browser/themes/gnomestripe/browser/places/livemark-item-rtl.png
browser/themes/gnomestripe/browser/places/livemarkItem.png
browser/themes/gnomestripe/browser/places/places.css
browser/themes/gnomestripe/browser/places/query.png
browser/themes/gnomestripe/browser/places/tag.png
browser/themes/gnomestripe/browser/places/toolbarDropMarker.png
browser/themes/gnomestripe/browser/places/wrench.png
browser/themes/gnomestripe/browser/tabbrowser/tab-arrow-end.png
browser/themes/gnomestripe/browser/tabbrowser/tab-arrow-start.png
browser/themes/gnomestripe/browser/tabbrowser/tabDragIndicator.png
client.mk
config/rules.mk
configure.in
js/src/Makefile.in
js/src/js.cpp
js/src/jsapi.cpp
js/src/jsatom.cpp
js/src/jscntxt.cpp
js/src/jsdate.cpp
js/src/jsdbgapi.cpp
js/src/jsemit.cpp
js/src/jsfun.cpp
js/src/jsgc.cpp
js/src/jsinterp.cpp
js/src/jsobj.cpp
js/src/jsopcode.cpp
js/src/jsparse.cpp
js/src/jsregexp.cpp
js/src/jsscan.cpp
js/src/jsscope.cpp
js/src/jsscript.cpp
js/src/jsstr.cpp
js/src/jsxml.cpp
js/src/prmjtime.cpp
js/tests/ecma_3/Date/15.9.5.5-02.js
js/tests/ecma_3/LexicalConventions/7.9.1.js
js/tests/ecma_3/extensions/7.9.1.js
js/tests/js1_5/Regress/regress-383682.js
layout/base/tests/test_bug399951.html
modules/libimg/png/pnggccrd.c
modules/libimg/png/pngvcrd.c
modules/plugin/samples/default/mac/DefaultPlugin.pbproj/project.pbxproj
modules/plugin/samples/default/mac/DefaultPlugin.xcode/project.pbxproj
security/manager/locales/en-US/chrome/pippki/newserver.dtd
security/manager/locales/en-US/chrome/pippki/newserver.properties
security/manager/pki/resources/content/domainMismatch.js
security/manager/pki/resources/content/domainMismatch.xul
security/manager/pki/resources/content/newserver.js
security/manager/pki/resources/content/newserver.xul
security/manager/pki/resources/content/serverCertExpired.js
security/manager/pki/resources/content/serverCertExpired.xul
widget/public/nsIMenuListener.h
xpcom/io/nsIObservableInputStream.idl
xpcom/io/nsIObservableOutputStream.idl
xpcom/reflect/xptcall/src/md/unix/xptcinvoke_nto_shle.cpp
xpcom/reflect/xptcall/src/md/unix/xptcstubs_asm_shle.py
xpcom/reflect/xptcall/src/md/unix/xptcstubs_asm_shle.s
xpcom/reflect/xptcall/src/md/unix/xptcstubs_nto_shle.cpp
--- a/accessible/public/ia2/Makefile.in
+++ b/accessible/public/ia2/Makefile.in
@@ -100,17 +100,16 @@ MIDL_GENERATED_FILES = \
   $(NULL)
 
 EMBED_MANIFEST_AT = 2
 
 include $(topsrcdir)/config/rules.mk
 
 OS_LIBS = \
   kernel32.lib \
-  rpcndr.lib \
   rpcns4.lib \
   rpcrt4.lib \
   ole32.lib \
   oleaut32.lib \
   $(NULL)
 
 $(MIDL_GENERATED_FILES): $(addprefix $(IA2DIR)/,$(MIDL_INTERFACES) $(MIDL_ENUMS))
 	for idl in $^; do \
--- a/accessible/public/msaa/Makefile.in
+++ b/accessible/public/msaa/Makefile.in
@@ -82,17 +82,16 @@ MIDL_GENERATED_FILES = \
 	ISimpleDOMText_p.c \
 	ISimpleDOMText_i.c \
 	$(NULL)
 
 SRCDIR_CSRCS	= $(addprefix $(srcdir)/,$(CSRCS))
 
 OS_LIBS = \
 	kernel32.lib \
-	rpcndr.lib \
 	rpcns4.lib \
 	rpcrt4.lib \
 	oleaut32.lib \
 	$(NULL)
 
 $(MIDL_GENERATED_FILES): done_gen
 
 done_gen: ISimpleDOMNode.idl \
--- a/accessible/public/nsIAccessible.idl
+++ b/accessible/public/nsIAccessible.idl
@@ -181,17 +181,18 @@ interface nsIAccessible : nsISupports
    */
   readonly attribute nsIPersistentProperties attributes;
 
   /**
    * Returns grouping information. Used for tree items, list items, tab panel
    * labels, radio buttons, etc. Also used for collectons of non-text objects.
    *
    * @param groupLevel - 1-based, similar to ARIA 'level' property
-   * @param similarItemsInGroup - 1-based, similar to ARIA 'setsize' property
+   * @param similarItemsInGroup - 1-based, similar to ARIA 'setsize' property,
+   *                              inclusive of the current item
    * @param positionInGroup - 1-based, similar to ARIA 'posinset' property
    */
   void groupPosition(out long aGroupLevel, out long aSimilarItemsInGroup,
                      out long aPositionInGroup);
 
   /**
    * Accessible child which contains the coordinate at (x, y) in screen pixels.
    * If the point is in the current accessible but not in a child, the
--- a/accessible/public/nsIAccessibleRole.idl
+++ b/accessible/public/nsIAccessibleRole.idl
@@ -736,22 +736,37 @@ interface nsIAccessibleRole : nsISupport
   /**
    * A list of items that is shown by combobox.
    */
   const unsigned long ROLE_COMBOBOX_LIST = 114;
 
   /**
    * A item of list that is shown by combobox;
    */
-  const unsigned long ROLE_COMBOBOX_LISTITEM = 115;
+  const unsigned long ROLE_COMBOBOX_OPTION = 115;
 
   /**
    * An image map -- has child links representing the areas
    */
   const unsigned long ROLE_IMAGE_MAP = 116;
   
   /**
+   * An option in a listbox
+   */
+  const unsigned long ROLE_OPTION = 117;
+  
+  /**
+   * A rich option in a listbox, it can have other widgets as children
+   */
+  const unsigned long ROLE_RICH_OPTION = 118;
+  
+  /**
+   * A list of options
+   */
+  const unsigned long ROLE_LISTBOX = 119;
+
+  /**
    * It's not role actually. This contanst is important to help ensure
    * nsRoleMap's are synchronized.
    */
-  const unsigned long ROLE_LAST_ENTRY = 117;
+  const unsigned long ROLE_LAST_ENTRY = 120;
 };
 
--- a/accessible/public/nsPIAccessible.idl
+++ b/accessible/public/nsPIAccessible.idl
@@ -35,18 +35,22 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
 interface nsIAccessible;
 interface nsIAccessibleEvent;
+%{C++
+   struct nsRoleMapEntry;
+%}
+[ptr] native nsRoleMapEntryPtr(nsRoleMapEntry);
 
-[uuid(af05f83c-6fd2-48c1-b1c3-811857472421)]
+[uuid(2d552ed0-3f38-4c7f-94c1-419de4d693ed)]
 interface nsPIAccessible : nsISupports
 {
   /**
    * Set accessible parent.
    */
   void setParent(in nsIAccessible aAccParent);
 
   /**
@@ -102,10 +106,18 @@ interface nsPIAccessible : nsISupports
   void testChildCache(in nsIAccessible aCachedChild);
 
   /**
    * Returns text of accessible if accessible has text role otherwise empty
    * string.
    */
   void appendTextTo(out AString aString, in unsigned long aStartOffset,
                     in unsigned long aLength);
+                    
+  /**
+   * Set the ARIA role map entry for a new accessible.
+   * For a newly created accessible, specify which role map entry should be used.
+   * @param aRoleMapEntry The ARIA nsRoleMapEntry* for the accessible, or 
+   *                      nsnull if none.
+   */
+   void setRoleMapEntry(in nsRoleMapEntryPtr aRoleMapEntry);
 };
 
--- a/accessible/src/atk/nsRoleMap.h
+++ b/accessible/src/atk/nsRoleMap.h
@@ -156,13 +156,16 @@ static const PRUint32 atkRoleMap[] = {
     ATK_ROLE_SECTION,             // nsIAccessibleRole::ROLE_SECTION              107
     ATK_ROLE_REDUNDANT_OBJECT,    // nsIAccessibleRole::ROLE_REDUNDANT_OBJECT     108
     ATK_ROLE_FORM,                // nsIAccessibleRole::ROLE_FORM                 109
     ATK_ROLE_INPUT_METHOD_WINDOW, // nsIAccessibleRole::ROLE_IME                  110
     ATK_ROLE_APPLICATION,         // nsIAccessibleRole::ROLE_APP_ROOT             111
     ATK_ROLE_MENU,                // nsIAccessibleRole::ROLE_PARENT_MENUITEM      112
     ATK_ROLE_CALENDAR,            // nsIAccessibleRole::ROLE_CALENDAR             113
     ATK_ROLE_MENU,                // nsIAccessibleRole::ROLE_COMBOBOX_LIST        114
-    ATK_ROLE_MENU_ITEM,           // nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM    115
+    ATK_ROLE_MENU_ITEM,           // nsIAccessibleRole::ROLE_COMBOBOX_OPTION      115
     ATK_ROLE_IMAGE,               // nsIAccessibleRole::ROLE_IMAGE_MAP            116
+    ATK_ROLE_LIST_ITEM,           // nsIAccessibleRole::ROLE_OPTION               117
+    ATK_ROLE_LIST_ITEM,           // nsIAccessibleRole::ROLE_RICH_OPTION          118
+    ATK_ROLE_LIST,                // nsIAccessibleRole::ROLE_LISTBOX              119
     kROLE_ATK_LAST_ENTRY          // nsIAccessibleRole::ROLE_LAST_ENTRY
 };
 
--- a/accessible/src/base/nsARIAMap.cpp
+++ b/accessible/src/base/nsARIAMap.cpp
@@ -113,17 +113,17 @@ nsRoleMapEntry nsARIAMap::gWAIRoleMap[] 
   {"heading", nsIAccessibleRole::ROLE_HEADING, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"img", nsIAccessibleRole::ROLE_GRAPHIC, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"label", nsIAccessibleRole::ROLE_LABEL, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"link", nsIAccessibleRole::ROLE_LINK, eNameOkFromChildren, eNoValue, nsIAccessibleStates::STATE_LINKED,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"list", nsIAccessibleRole::ROLE_LIST, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
             {eAria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
-  {"listbox", nsIAccessibleRole::ROLE_LIST, eNameLabelOrTitle, eNoValue, kNoReqStates,
+  {"listbox", nsIAccessibleRole::ROLE_LISTBOX, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
             {eAria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
   {"listitem", nsIAccessibleRole::ROLE_LISTITEM, eNameOkFromChildren, eNoValue, kNoReqStates,
             {eAria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {eAria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
             {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
             {eAria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
@@ -139,23 +139,24 @@ nsRoleMapEntry nsARIAMap::gWAIRoleMap[] 
             {eAria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE}, kEndEntry},
   {"menuitemcheckbox", nsIAccessibleRole::ROLE_CHECK_MENU_ITEM, eNameOkFromChildren, eNoValue, nsIAccessibleStates::STATE_CHECKABLE,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED },
             {eAria_checked, "mixed", nsIAccessibleStates::STATE_MIXED}, kEndEntry},
   {"menuitemradio", nsIAccessibleRole::ROLE_RADIO_MENU_ITEM, eNameOkFromChildren, eNoValue, nsIAccessibleStates::STATE_CHECKABLE,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED }, kEndEntry},
-  {"option", nsIAccessibleRole::ROLE_LISTITEM, eNameOkFromChildren, eNoValue, kNoReqStates,
+  {"option", nsIAccessibleRole::ROLE_OPTION, eNameOkFromChildren, eNoValue, kNoReqStates,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {eAria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {eAria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
             {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
             {eAria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
             {eAria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE}, kEndEntry},
+  {"presentation", nsIAccessibleRole::ROLE_NOTHING, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"progressbar", nsIAccessibleRole::ROLE_PROGRESSBAR, eNameLabelOrTitle, eHasValueMinMax, nsIAccessibleStates::STATE_READONLY,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"radio", nsIAccessibleRole::ROLE_RADIOBUTTON, eNameOkFromChildren, eNoValue, kNoReqStates,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED}, kEndEntry},
   {"radiogroup", nsIAccessibleRole::ROLE_GROUPING, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"region", nsIAccessibleRole::ROLE_PANE, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
@@ -206,17 +207,27 @@ nsRoleMapEntry nsARIAMap::gWAIRoleMap[] 
             {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {eAria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {eAria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
             {eAria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
             {eAria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED},
             {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
             {eAria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
             {eAria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE},},
-  {nsnull, nsIAccessibleRole::ROLE_NOTHING, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry} // Last item
+};
+
+PRUint32 nsARIAMap::gWAIRoleMapLength = NS_ARRAY_LENGTH(nsARIAMap::gWAIRoleMap);
+
+nsRoleMapEntry nsARIAMap::gLandmarkRoleMap = {
+  "",
+  nsIAccessibleRole::ROLE_NOTHING,
+  eNameLabelOrTitle,
+  eNoValue,
+  kNoReqStates,
+  kEndEntry
 };
 
 /**
  * Universal states:
  * The following state rules are applied to any accessible element,
  * whether there is an ARIA role or not:
  */
 nsStateMapEntry nsARIAMap::gWAIUnivStateMap[] = {
--- a/accessible/src/base/nsARIAMap.h
+++ b/accessible/src/base/nsARIAMap.h
@@ -129,12 +129,14 @@ struct nsRoleMapEntry
  *  and provide the mappings for WAI-ARIA roles and properties using the 
  *  structs defined in this file.
  */
 struct nsARIAMap
 {
   static nsIAtom** gAriaAtomPtrsNS[eAria_none];
   static nsIAtom** gAriaAtomPtrsHyphenated[eAria_none];
   static nsRoleMapEntry gWAIRoleMap[];
+  static PRUint32 gWAIRoleMapLength;
+  static nsRoleMapEntry gLandmarkRoleMap;
   static nsStateMapEntry gWAIUnivStateMap[];
 };
 
 #endif
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -42,17 +42,16 @@
 #include "nsHashtable.h"
 #include "nsIAccessibilityService.h"
 #include "nsIAccessibleDocument.h"
 #include "nsPIAccessibleDocument.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIDocumentViewer.h"
-#include "nsIDOM3Node.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"
@@ -839,71 +838,15 @@ nsAccessNode::GetLanguage(nsAString& aLa
   return NS_OK;
 }
 
 PRBool
 nsAccessNode::GetARIARole(nsIContent *aContent, nsString& aRole)
 {
   aRole.Truncate();
 
-  PRBool allowPrefixLookup = PR_TRUE;
-
   if (aContent->IsNodeOfType(nsINode::eHTML)) {
     // Allow non-namespaced role attribute in HTML
-    if (!aContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::role, aRole)) {
-      return PR_FALSE;
-    }
-    nsCOMPtr<nsIDOMNSDocument> doc(do_QueryInterface(aContent->GetDocument()));
-    if (doc) {
-      nsAutoString mimeType;
-      doc->GetContentType(mimeType);
-      if (mimeType.EqualsLiteral("text/html")) {
-        allowPrefixLookup = PR_FALSE;
-      }
-    }
+    return aContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::role, aRole);
   }
   // In non-HTML content, use XHTML namespaced-role attribute
-  else if (!aContent->GetAttr(kNameSpaceID_XHTML, nsAccessibilityAtoms::role, aRole)) {
-    return PR_FALSE;
-  }
-
-  PRBool hasPrefix = (aRole.Find(":") >= 0);
-
-  if (!hasPrefix) {
-    // * No prefix* -- not a QName
-    // Just return entire string as long as prefix is not currently required
-    return PR_TRUE;
-  }
-
-  // Has prefix -- is a QName (role="prefix:rolename")
-
-  // Check hardcoded 'wairole:' prefix
-  NS_NAMED_LITERAL_STRING(hardcodedWairolePrefix, "wairole:");
-  if (StringBeginsWith(aRole, hardcodedWairolePrefix)) {
-    // The exact prefix "wairole:" is reserved to 
-    // always indicate that we are using WAI roles.
-    aRole.Cut(0, hardcodedWairolePrefix.Length());
-    return PR_TRUE;
-  }
-
-  // Check for prefix mapped with xmlns:prefixname=""
-  nsAutoString prefix;
-  if (allowPrefixLookup) {  // Not text/html, so we will try to find the WAIRole prefix
-    // QI to nsIDOM3Node causes some overhead. Unfortunately we need to do this each
-    // time there is a prefixed role attribute, because the prefix to namespace mappings
-    // can change within any subtree via the xmlns attribute
-    nsCOMPtr<nsIDOM3Node> dom3Node(do_QueryInterface(aContent));
-    if (dom3Node) {
-      // Look up exact prefix name for WAI Roles
-      NS_NAMED_LITERAL_STRING(kWAIRoles_Namespace, "http://www.w3.org/2005/01/wai-rdf/GUIRoleTaxonomy#");
-      dom3Node->LookupPrefix(kWAIRoles_Namespace, prefix);
-      prefix += ':';
-      PRUint32 length = prefix.Length();
-      if (length > 1 && StringBeginsWith(aRole, prefix)) {
-        // Is a QName (role="prefix:rolename"), and prefix matches WAI Role prefix
-        // Trim the WAI Role prefix off
-        aRole.Cut(0, length);
-      }
-    }
-  }
-
-  return PR_TRUE;
+  return aContent->GetAttr(kNameSpaceID_XHTML, nsAccessibilityAtoms::role, aRole);
 }
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -121,16 +121,17 @@ ACCESSIBILITY_ATOM(object, "object")
 ACCESSIBILITY_ATOM(ol, "ol")
 ACCESSIBILITY_ATOM(optgroup, "optgroup")
 ACCESSIBILITY_ATOM(option, "option")
 ACCESSIBILITY_ATOM(q, "q")
 ACCESSIBILITY_ATOM(select, "select")
 ACCESSIBILITY_ATOM(select1, "select1") // XForms
 ACCESSIBILITY_ATOM(svg, "svg")
 ACCESSIBILITY_ATOM(table, "table")
+ACCESSIBILITY_ATOM(tabpanels, "tabpanels") // XUL
 ACCESSIBILITY_ATOM(tbody, "tbody")
 ACCESSIBILITY_ATOM(td, "td")
 ACCESSIBILITY_ATOM(th, "th")
 ACCESSIBILITY_ATOM(tfoot, "tfoot")
 ACCESSIBILITY_ATOM(thead, "thead")
 ACCESSIBILITY_ATOM(textarea, "textarea") // XForms
 ACCESSIBILITY_ATOM(textbox, "textbox")   // XUL
 ACCESSIBILITY_ATOM(toolbaritem, "toolbaritem")   // XUL
@@ -153,16 +154,17 @@ ACCESSIBILITY_ATOM(curpos, "curpos") // 
 ACCESSIBILITY_ATOM(data, "data")
 ACCESSIBILITY_ATOM(droppable, "droppable")   // XUL combo box
 ACCESSIBILITY_ATOM(editable, "editable")
 ACCESSIBILITY_ATOM(_for, "for")
 ACCESSIBILITY_ATOM(hidden, "hidden")   // XUL tree columns
 ACCESSIBILITY_ATOM(href, "href")
 ACCESSIBILITY_ATOM(increment, "increment") // XUL
 ACCESSIBILITY_ATOM(lang, "lang")
+ACCESSIBILITY_ATOM(linkedPanel, "linkedpanel") // XUL
 ACCESSIBILITY_ATOM(maxpos, "maxpos") // XUL
 ACCESSIBILITY_ATOM(minpos, "minpos") // XUL
 ACCESSIBILITY_ATOM(name, "name")
 ACCESSIBILITY_ATOM(onclick, "onclick")
 ACCESSIBILITY_ATOM(src, "src")
 ACCESSIBILITY_ATOM(summary, "summary")
 ACCESSIBILITY_ATOM(tabindex, "tabindex")
 ACCESSIBILITY_ATOM(title, "title")
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.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 "nsAccessibilityAtoms.h"
 #include "nsAccessibilityService.h"
 #include "nsAccessibilityUtils.h"
+#include "nsARIAMap.h"
 #include "nsCURILoader.h"
 #include "nsDocAccessible.h"
 #include "nsHTMLImageAccessibleWrap.h"
 #include "nsHTMLLinkAccessible.h"
 #include "nsHTMLSelectAccessible.h"
 #include "nsHTMLTableAccessibleWrap.h"
 #include "nsHTMLTextAccessible.h"
 #include "nsHyperTextAccessibleWrap.h"
@@ -1170,27 +1171,31 @@ NS_IMETHODIMP nsAccessibilityService::Ge
   nsCOMPtr<nsIPresShell> presShell(do_QueryReferent(aWeakShell));
   nsIFrame *outFrameUnused = NULL;
   PRBool isHiddenUnused = false;
   return GetAccessible(aNode, presShell, aWeakShell, 
                        &outFrameUnused, &isHiddenUnused, aAccessible);
 }
 
 nsresult nsAccessibilityService::InitAccessible(nsIAccessible *aAccessibleIn,
-                                                nsIAccessible **aAccessibleOut)
+                                                nsIAccessible **aAccessibleOut,
+                                                nsRoleMapEntry *aRoleMapEntry)
 {
   if (!aAccessibleIn) {
     return NS_ERROR_FAILURE; // No accessible to init
   }
   NS_ASSERTION(aAccessibleOut && !*aAccessibleOut, "Out param should already be cleared out");
 
   nsCOMPtr<nsPIAccessNode> privateAccessNode = do_QueryInterface(aAccessibleIn);
   NS_ASSERTION(privateAccessNode, "All accessibles must support nsPIAccessNode");
   nsresult rv = privateAccessNode->Init(); // Add to cache, etc.
   if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsPIAccessible> privateAccessible =
+      do_QueryInterface(privateAccessNode);
+    privateAccessible->SetRoleMapEntry(aRoleMapEntry);
     NS_ADDREF(*aAccessibleOut = aAccessibleIn);
   }
   return rv;
 }
 
 NS_IMETHODIMP nsAccessibilityService::GetAccessible(nsIDOMNode *aNode,
                                                     nsIPresShell *aPresShell,
                                                     nsIWeakReference *aWeakShell,
@@ -1345,22 +1350,23 @@ NS_IMETHODIMP nsAccessibilityService::Ge
    */
   if (content->IsNodeOfType(nsINode::eTEXT)) {
     // --- Create HTML for visible text frames ---
     if (frame->IsEmpty()) {
       *aIsHidden = PR_TRUE;
       return NS_OK;
     }
     frame->GetAccessible(getter_AddRefs(newAcc));
-    return InitAccessible(newAcc, aAccessible);
+    return InitAccessible(newAcc, aAccessible, nsnull);
   }
 
-  nsAutoString role;
-  if (nsAccessNode::GetARIARole(content, role) && role.EqualsLiteral("presentation") && !content->IsFocusable()) {
-    // Only create accessible for role=":presentation" if it is focusable --
+  nsRoleMapEntry *roleMapEntry = nsAccUtils::GetRoleMapEntry(aNode);
+  if (roleMapEntry && !nsCRT::strcmp(roleMapEntry->roleString, "presentation") &&
+      !content->IsFocusable()) { // For presentation only
+    // Only create accessible for role of "presentation" if it is focusable --
     // in that case we need an accessible in case it gets focused, we
     // don't want focus ever to be 'lost'
     return NS_OK;
   }
 
   // Elements may implement nsIAccessibleProvider via XBL. This allows them to
   // say what kind of accessible to create.
   nsresult rv = GetAccessibleByType(aNode, getter_AddRefs(newAcc));
@@ -1444,31 +1450,31 @@ NS_IMETHODIMP nsAccessibilityService::Ge
 
   // If no accessible, see if we need to create a generic accessible because
   // of some property that makes this object interesting
   // We don't do this for <body>, <html>, <window>, <dialog> etc. which 
   // correspond to the doc accessible and will be created in any case
   if (!newAcc && content->Tag() != nsAccessibilityAtoms::body && content->GetParent() && 
       (content->IsFocusable() ||
       (isHTML && nsAccUtils::HasListener(content, NS_LITERAL_STRING("click"))) ||
-       HasUniversalAriaProperty(content, aWeakShell) || !role.IsEmpty())) {
+       HasUniversalAriaProperty(content, aWeakShell) || roleMapEntry)) {
     // This content is focusable or has an interesting dynamic content accessibility property.
     // If it's interesting we need it in the accessibility hierarchy so that events or
     // other accessibles can point to it, or so that it can hold a state, etc.
     if (isHTML) {
       // Interesting HTML container which may have selectable text and/or embedded objects
       CreateHyperTextAccessible(frame, getter_AddRefs(newAcc));
     }
     else {  // XUL, SVG, MathML etc.
       // Interesting generic non-HTML container
       newAcc = new nsAccessibleWrap(aNode, aWeakShell);
     }
   }
 
-  return InitAccessible(newAcc, aAccessible);
+  return InitAccessible(newAcc, aAccessible, roleMapEntry);
 }
 
 PRBool
 nsAccessibilityService::HasUniversalAriaProperty(nsIContent *aContent,
                                                  nsIWeakReference *aWeakShell)
 {
   nsCOMPtr<nsIAccessibleDocument> docAccessible =
     nsAccessNode::GetDocAccessibleFor(aWeakShell);
@@ -1914,15 +1920,28 @@ nsAccessibilityService::GetAccessibleFor
   if (content) {
     frame = shell->GetPrimaryFrameFor(content);
   }
 
   if (frame && (frame->GetType() == nsAccessibilityAtoms::boxFrame ||
                 frame->GetType() == nsAccessibilityAtoms::scrollFrame)) { 
     parentFrame = frame->GetParent();
     if (parentFrame && parentFrame->GetType() == nsAccessibilityAtoms::deckFrame) {
-      *aAccessible = new nsEnumRoleAccessible(aNode, weakShell, nsIAccessibleRole::ROLE_PROPERTYPAGE);
+      // If deck frame is for xul:tabpanels element then the given node has
+      // tabpanel accessible.
+      nsCOMPtr<nsIContent> parentContent = parentFrame->GetContent();
+      if (parentContent->NodeInfo()->Equals(nsAccessibilityAtoms::tabpanels,
+                                            kNameSpaceID_XUL)) {
+        *aAccessible = new nsXULTabpanelAccessible(aNode, weakShell);
+      } else {
+        *aAccessible =
+          new nsEnumRoleAccessible(aNode, weakShell,
+                                   nsIAccessibleRole::ROLE_PROPERTYPAGE);
+      }
+
+      NS_ENSURE_TRUE(*aAccessible, NS_ERROR_OUT_OF_MEMORY);
+
       NS_ADDREF(*aAccessible);
     }
   }
 
   return NS_OK;
 }
--- a/accessible/src/base/nsAccessibilityService.h
+++ b/accessible/src/base/nsAccessibilityService.h
@@ -46,16 +46,17 @@
 
 class nsIFrame;
 class nsIWeakReference;
 class nsIDOMNode;
 class nsObjectFrame;
 class nsIDocShell;
 class nsIPresShell;
 class nsIContent;
+struct nsRoleMapEntry;
 
 class nsAccessibilityService : public nsIAccessibilityService,
                                public nsIObserver,
                                public nsIWebProgressListener,
                                public nsSupportsWeakReference
 {
 public:
   nsAccessibilityService();
@@ -94,18 +95,23 @@ private:
                    nsIWeakReference **aShell,
                    nsIDOMNode **aContent);
 
   /**
    * Initialize an accessible and cache it. The method should be called for
    * every created accessible.
    *
    * @param aAccessibleIn - accessible to initialize.
+   * @param aAcccessibleOut - set to the same thing as aAccessibleIn, unless there was
+   *                          an error initializing the accessible, in which case
+   *                          it is set to nsnull
+   * @param aRoleMapEntry - The role map entry role the ARIA role or nsnull if none
    */
-  nsresult InitAccessible(nsIAccessible *aAccessibleIn, nsIAccessible **aAccessibleOut);
+  nsresult InitAccessible(nsIAccessible *aAccessibleIn, nsIAccessible **aAccessibleOut,
+                          nsRoleMapEntry *aRoleMapEntry = nsnull);
 
   /**
    * Return accessible object for elements implementing nsIAccessibleProvider
    * interface.
    *
    * @param aNode - DOM node that accessible is returned for.
    */
   nsresult GetAccessibleByType(nsIDOMNode *aNode, nsIAccessible **aAccessible);
@@ -246,17 +252,17 @@ static const char kRoleNames[][20] = {
   "section",             //ROLE_SECTION
   "redundant object",    //ROLE_REDUNDANT_OBJECT
   "form",                //ROLE_FORM
   "ime",                 //ROLE_IME
   "app root",            //ROLE_APP_ROOT
   "parent menuitem",     //ROLE_PARENT_MENUITEM
   "calendar",            //ROLE_CALENDAR
   "combobox list",       //ROLE_COMBOBOX_LIST
-  "combobox listitem",   //ROLE_COMBOBOX_LISTITEM
+  "combobox option",     //ROLE_COMBOBOX_OPTION
   "image map"            //ROLE_IMAGE_MAP
 };
 
 /**
  * Map nsIAccessibleEvents constants to strings. Used by
  * nsIAccessibleRetrieval::getStringEventType() method.
  */
 static const char kEventTypeNames[][40] = {
--- a/accessible/src/base/nsAccessibilityUtils.cpp
+++ b/accessible/src/base/nsAccessibilityUtils.cpp
@@ -43,16 +43,17 @@
 #include "nsPIAccessible.h"
 #include "nsPIAccessNode.h"
 #include "nsAccessibleEventData.h"
 
 #include "nsAccessible.h"
 #include "nsARIAMap.h"
 #include "nsIDocument.h"
 #include "nsIDOMAbstractView.h"
+#include "nsIDOM3Node.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentView.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsIDOMNodeList.h"
 #include "nsIDOMRange.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMWindowInternal.h"
@@ -62,16 +63,17 @@
 #include "nsIScrollableFrame.h"
 #include "nsIEventStateManager.h"
 #include "nsISelection2.h"
 #include "nsISelectionController.h"
 
 #include "nsContentCID.h"
 #include "nsComponentManagerUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
+#include "nsWhitespaceTokenizer.h"
 
 static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
 void
 nsAccUtils::GetAccAttr(nsIPersistentProperties *aAttributes, nsIAtom *aAttrName,
                        nsAString& aAttrValue)
 {
   aAttrValue.Truncate();
@@ -189,17 +191,17 @@ nsAccUtils::SetAccAttrsForXULSelectContr
     nsCOMPtr<nsIDOMNode> currNode(do_QueryInterface(currItem));
 
     nsCOMPtr<nsIAccessible> itemAcc;
     nsAccessNode::GetAccService()->GetAccessibleFor(currNode,
                                                     getter_AddRefs(itemAcc));
     if (!itemAcc ||
         nsAccessible::State(itemAcc) & nsIAccessibleStates::STATE_INVISIBLE) {
       setSize--;
-      if (index < indexOf)
+      if (index < static_cast<PRUint32>(indexOf))
         posInSet--;
     }
   }
 
   SetAccGroupAttrs(aAttributes, 0, posInSet + 1, setSize);
 }
 
 PRBool
@@ -750,8 +752,82 @@ nsAccUtils::FindDescendantPointingToIDIm
       if (labelContent) {
         return labelContent;
       }
     }
   }
   return nsnull;
 }
 
+const char *
+nsAccUtils::TrimmedRole(const char *aRole, nsIContent *aContent)
+{  
+  const char kWaiRolePrefix[] = "wairole:";
+  const PRUint32 kWaiRolePrefixLen = NS_ARRAY_LENGTH(kWaiRolePrefix) - 1;
+
+  if (!PL_strncmp(aRole, kWaiRolePrefix, kWaiRolePrefixLen)) {
+    return aRole + kWaiRolePrefixLen;
+  }
+//#ifdef ALLOW_PREFIX_LOOKUP
+  // Check if prefix was mapped via xmlns:[prefix] to the official WAI role namespace
+  char *colon = PL_strchr(aRole, ':');
+  if (colon) {
+    nsCOMPtr<nsIDOM3Node> dom3Node = do_QueryInterface(aContent);
+    if (dom3Node) {
+      // Look up exact prefix name for WAI Roles
+      nsAutoString prefix;
+      NS_NAMED_LITERAL_STRING(kWAIRoles_Namespace, "http://www.w3.org/2005/01/wai-rdf/GUIRoleTaxonomy#");
+      dom3Node->LookupPrefix(kWAIRoles_Namespace, prefix);
+      prefix += ':';
+      PRUint32 prefixLength = colon - aRole + 1;
+
+      if (!PL_strncmp(aRole, NS_LossyConvertUTF16toASCII(prefix).get(), prefixLength)) {
+        // Is a QName (role="prefix:rolename"), and prefix is mapped to WAI Role namespace
+        // Trim the prefix off
+        return aRole + prefixLength;
+      }
+    }
+  }
+
+  return aRole;
+}
+
+nsRoleMapEntry*
+nsAccUtils::GetRoleMapEntry(nsIDOMNode *aNode)
+{
+  nsIContent *content = nsAccessible::GetRoleContent(aNode);
+  if (!content) {
+    return nsnull;
+  }
+  nsAutoString roleString;
+  if (!nsAccessNode::GetARIARole(content, roleString)) {
+    return nsnull;
+  }
+
+  nsWhitespaceTokenizer tokenizer(roleString);
+  while (tokenizer.hasMoreTokens()) {
+    // Do a binary search through table for the next role in role list
+    const char *rawRole = NS_LossyConvertUTF16toASCII(tokenizer.nextToken()).get();
+    const char *trimmedRole = TrimmedRole(rawRole, content);
+//#endif
+    PRInt32 low = 0;
+    PRInt32 high = nsARIAMap::gWAIRoleMapLength;
+    while (low <= high) {
+      PRInt32 index = low + ((high - low) / 2);
+      PRInt32 compare = PL_strcmp(trimmedRole, nsARIAMap::gWAIRoleMap[index].roleString);
+      if (compare == 0) {
+        // The  role attribute maps to an entry in the role table
+        return &nsARIAMap::gWAIRoleMap[index];
+      }
+      if (compare < 0) {
+        high = index - 1;
+      }
+      else {
+        low = index + 1;
+      }
+    }
+  }
+
+  // Always use some entry if there is a role string
+  // To ensure an accessible object is created
+  return &nsARIAMap::gLandmarkRoleMap;
+}
+
--- a/accessible/src/base/nsAccessibilityUtils.h
+++ b/accessible/src/base/nsAccessibilityUtils.h
@@ -268,16 +268,33 @@ public:
    *  @param aAriaPropTypes  A bitflag for the property types to check for (namespaced, hyphenated or both), if known by caller
    *  @return             PR_TRUE if the property is defined
    */
   static PRBool GetAriaProperty(nsIContent *aContent, nsIWeakReference *aWeakShell,
                                 EAriaProperty aProperty, nsAString& aValue, 
                                 PRUint32 aCheckFlags = 0);
 
   /**
+   * Given a role string, return the role with any WAI role prefix trimmed off
+   * @param aRole  The role to start with
+   * @param aContent  What content nodes the role is set on
+   * @return          The entire role if there is no prefix that is a WAI role prefix,
+   *                  or the role without the prefix, if it was mapped to WAI roles
+   */
+  static const char *TrimmedRole(const char *aRole, nsIContent *aContent);  
+
+  /**
+   * Get the role map entry for a given DOM node. This will use the first
+   * ARIA role if the role attribute provides a space delimited list of roles.
+   * @param aNode  The DOM node to get the role map entry for
+   * @return       A pointer to the role map entry for the ARIA role, or nsnull if none
+   */
+   static nsRoleMapEntry* GetRoleMapEntry(nsIDOMNode *aNode);
+
+  /**
    * 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.
    *
    * @param aAriaProperty - the ARIA property to search for or eAria_none, if aRelationAttr is passed in
    * @param aForNode - the given element the search is performed for
    * @param aTagName - tag name of searched element, or nsnull for any -- ignored if aAriaProperty passed in
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -80,16 +80,17 @@
 #include "nsIAtom.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsIURI.h"
 #include "nsITimer.h"
 #include "nsIMutableArray.h"
 #include "nsIObserverService.h"
 #include "nsIServiceManager.h"
+#include "nsWhitespaceTokenizer.h"
 
 #ifdef NS_DEBUG
 #include "nsIFrameDebug.h"
 #include "nsIDOMCharacterData.h"
 #endif
 
 /**
  * nsAccessibleDOMStringList implementation
@@ -267,16 +268,22 @@ nsAccessible::nsAccessible(nsIDOMNode* a
 
 //-----------------------------------------------------
 // destruction
 //-----------------------------------------------------
 nsAccessible::~nsAccessible()
 {
 }
 
+NS_IMETHODIMP nsAccessible::SetRoleMapEntry(nsRoleMapEntry* aRoleMapEntry)
+{
+  mRoleMapEntry = aRoleMapEntry;
+  return NS_OK;
+}
+
 NS_IMETHODIMP nsAccessible::GetName(nsAString& aName)
 {
   aName.Truncate();
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (!content) {
     return NS_ERROR_FAILURE;  // Node shut down
   }
 
@@ -445,74 +452,44 @@ nsAccessible::GetKeyboardShortcut(nsAStr
   }
 
   aAccessKey = accesskey;
   return NS_OK;
 }
 
 NS_IMETHODIMP nsAccessible::SetParent(nsIAccessible *aParent)
 {
-#ifdef DEBUG
-  if (aParent && aParent != mParent) {
-    nsCOMPtr<nsPIAccessible> privParent = do_QueryInterface(mParent);
-    if (privParent) {
-      nsCOMPtr<nsIAccessible> firstChild;
-      privParent->GetCachedFirstChild(getter_AddRefs(firstChild));
-      NS_ASSERTION(firstChild != this, "Reparenting other node's first child!");
+  if (mParent != aParent) {
+    // Adopt a child -- we allow this now. the new parent
+    // may be a dom node which wasn't previously accessible but now is.
+    // The old parent's children now need to be invalidated, since 
+    // it no longer owns the child, the new parent does
+    nsCOMPtr<nsPIAccessible> privOldParent = do_QueryInterface(mParent);
+    if (privOldParent) {
+      privOldParent->InvalidateChildren();
     }
   }
-#endif
+
   mParent = aParent;
   return NS_OK;
 }
 
 NS_IMETHODIMP nsAccessible::SetFirstChild(nsIAccessible *aFirstChild)
 {
-#ifdef DEBUG
-  // If there's parent of this child already, make sure it's us!
-  nsCOMPtr<nsPIAccessible> privChild = do_QueryInterface(aFirstChild);
-  if (privChild) {
-    nsCOMPtr<nsIAccessible> parent;
-    privChild->GetCachedParent(getter_AddRefs(parent));
-    NS_ASSERTION(!parent || parent == this, "Stealing child!");
-  }
-#endif
-
   mFirstChild = aFirstChild;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsAccessible::SetNextSibling(nsIAccessible *aNextSibling)
 {
   mNextSibling = aNextSibling? aNextSibling: DEAD_END_ACCESSIBLE;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsAccessible::Init()
-{
-  nsIContent *content = GetRoleContent(mDOMNode);
-  nsAutoString roleString;
-  if (content && GetARIARole(content, roleString)) {
-    nsCString utf8Role = NS_ConvertUTF16toUTF8(roleString); // For easy comparison
-    ToLowerCase(utf8Role);
-    PRUint32 index;
-    for (index = 0; nsARIAMap::gWAIRoleMap[index].roleString; index ++) {
-      if (utf8Role.Equals(nsARIAMap::gWAIRoleMap[index].roleString)) {
-        break; // The dynamic role attribute maps to an entry in our table
-      }
-    }
-    // Always use some entry if there is a role string
-    // If no match, we use the last entry which maps to ROLE_NOTHING
-    mRoleMapEntry = &nsARIAMap::gWAIRoleMap[index];
-  }
-
-  return nsAccessNodeWrap::Init();
-}
-
 nsIContent *nsAccessible::GetRoleContent(nsIDOMNode *aDOMNode)
 {
   // Given the DOM node for an acessible, return content node that
   // we should look at role string from
   // For non-document accessibles, this is the associated content node.
   // For doc accessibles, first try the <body> if it's HTML and there is
   // a role attribute used there.
   // For any other doc accessible , this is the document element.
@@ -564,17 +541,21 @@ NS_IMETHODIMP nsAccessible::InvalidateCh
 {
   // Document has transformed, reset our invalid children and child count
 
   // Reset the sibling pointers, they will be set up again the next time
   // CacheChildren() is called.
   // Note: we don't want to start creating accessibles at this point,
   // so don't use GetNextSibling() here. (bug 387252)
   nsAccessible* child = static_cast<nsAccessible*>(mFirstChild);
-  while (child && child->mNextSibling != DEAD_END_ACCESSIBLE) {
+  while (child) {
+    child->mParent = nsnull;
+    if (child->mNextSibling == DEAD_END_ACCESSIBLE) {
+      break;
+    }
     nsIAccessible *next = child->mNextSibling;
     child->mNextSibling = nsnull;
     child = static_cast<nsAccessible*>(next);
   }
 
   mAccChildCount = eChildCountUninitialized;
   mFirstChild = nsnull;
   return NS_OK;
@@ -904,16 +885,19 @@ nsresult nsAccessible::GetFullKeyName(co
 
 PRBool nsAccessible::IsVisible(PRBool *aIsOffscreen) 
 {
   // We need to know if at least a kMinPixels around the object is visible
   // Otherwise it will be marked nsIAccessibleStates::STATE_OFFSCREEN
   // The STATE_INVISIBLE flag is for elements which are programmatically hidden
   
   *aIsOffscreen = PR_TRUE;
+  if (!mDOMNode) {
+    return PR_FALSE; // Defunct object
+  }
 
   const PRUint16 kMinPixels  = 12;
    // Set up the variables we need, return false if we can't get at them all
   nsCOMPtr<nsIPresShell> shell(GetPresShell());
   if (!shell) 
     return PR_FALSE;
 
   nsIViewManager* viewManager = shell->GetViewManager();
@@ -973,18 +957,21 @@ PRBool nsAccessible::IsVisible(PRBool *a
       PRInt32 x, y, width, height;
       GetBounds(&x, &y, &width, &height);
       if (width > 0 && height > 0) {
         rectVisibility = nsRectVisibility_kVisible;    
       }
     }
   }
 
-  if (rectVisibility == nsRectVisibility_kZeroAreaRect || !mDOMNode) {
-    return PR_FALSE;   // Hidden element
+  if (rectVisibility == nsRectVisibility_kZeroAreaRect && frame && 
+      0 == (frame->GetStateBits() & NS_FRAME_OUT_OF_FLOW)) {
+    // Consider zero area objects hidden unless they are absoultely positioned
+    // or floating and may have descendants that have a non-zero size
+    return PR_FALSE;
   }
   
   // Currently one of:
   // nsRectVisibility_kVisible, 
   // nsRectVisibility_kAboveViewport, 
   // nsRectVisibility_kBelowViewport, 
   // nsRectVisibility_kLeftOfViewport, 
   // nsRectVisibility_kRightOfViewport
@@ -1003,24 +990,26 @@ PRBool nsAccessible::IsVisible(PRBool *a
   return isVisible;
 }
 
 nsresult
 nsAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   *aState = 0;
 
+  if (!mDOMNode) {
+    if (aExtraState) {
+      *aExtraState = nsIAccessibleStates::EXT_STATE_DEFUNCT;
+    }
+    return NS_OK; // Node shut down
+  }
+
   if (aExtraState)
     *aExtraState = 0;
 
-  if (!mDOMNode && aExtraState) {
-    *aExtraState = nsIAccessibleStates::EXT_STATE_DEFUNCT;
-    return NS_OK; // Node shut down
-  }
-
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (!content) {
     return NS_OK;  // On document, this is not an error
   }
 
   // Set STATE_UNAVAILABLE state based on disabled attribute
   // The disabled attribute is mostly used in XUL elements and HTML forms, but
   // if someone sets it on another attribute, 
@@ -1557,19 +1546,23 @@ nsresult nsAccessible::AppendFlatStringF
           if (!aFlatString->IsEmpty()) {
             aFlatString->Append(PRUnichar(' '));
           }
         }
       }
     }
     if (aContent->TextLength() > 0) {
       nsIFrame *frame = shell->GetPrimaryFrameFor(aContent);
-      NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
-      nsresult rv = frame->GetRenderedText(aFlatString);
-      NS_ENSURE_SUCCESS(rv, rv);
+      if (frame) {
+        nsresult rv = frame->GetRenderedText(aFlatString);
+        NS_ENSURE_SUCCESS(rv, rv);
+      } else {
+        //if aContent is an object that is display: none, we have no a frame
+        aContent->AppendTextTo(*aFlatString);
+      }
       if (isHTMLBlock && !aFlatString->IsEmpty()) {
         aFlatString->Append(PRUnichar(' '));
       }
     }
     return NS_OK;
   }
 
   nsAutoString textEquivalent;
@@ -1995,17 +1988,32 @@ NS_IMETHODIMP nsAccessible::GetFinalRole
           if (nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_haspopup, haspopup) &&
               haspopup.EqualsLiteral("true")) {
             // For button with aaa:haspopup="true"
             *aRole = nsIAccessibleRole::ROLE_BUTTONMENU;
           }
         }
       }
     }
-  
+    else if (*aRole == nsIAccessibleRole::ROLE_LISTBOX) {
+      // A listbox inside of a combo box needs a special role because of ATK mapping to menu
+      nsCOMPtr<nsIAccessible> parent;
+      GetParent(getter_AddRefs(parent));
+      if (parent && Role(parent) == nsIAccessibleRole::ROLE_COMBOBOX) {
+        *aRole = nsIAccessibleRole::ROLE_COMBOBOX_LIST;
+      }
+    }
+    else if (*aRole == nsIAccessibleRole::ROLE_OPTION) {
+      nsCOMPtr<nsIAccessible> parent;
+      GetParent(getter_AddRefs(parent));
+      if (parent && Role(parent) == nsIAccessibleRole::ROLE_COMBOBOX_LIST) {
+        *aRole = nsIAccessibleRole::ROLE_COMBOBOX_OPTION;
+      }
+    }
+
     if (*aRole != nsIAccessibleRole::ROLE_NOTHING) {
       return NS_OK;
     }
   }
   return mDOMNode ? GetRole(aRole) : NS_ERROR_FAILURE;  // Node already shut down
 }
 
 NS_IMETHODIMP
@@ -2031,17 +2039,33 @@ nsAccessible::GetAttributes(nsIPersisten
   if (content && nsAccUtils::GetID(content, id)) {
     attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, oldValueUnused);
   }
 
   // XXX In the future we may need to expose the dynamic content role inheritance chain
   // through this attribute
   nsAutoString xmlRole;
   if (GetARIARole(content, xmlRole)) {
-    attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"), xmlRole, oldValueUnused);          
+    nsWhitespaceTokenizer tokenizer(xmlRole);
+    nsAutoString trimmedRoles;
+    while (tokenizer.hasMoreTokens()) {
+      // Trim off prefixes for WAI roles so they are easier for ATs to recognize --
+      // they will always appear the same, and the AT need not understand prefixes
+      const char *rawRole = NS_LossyConvertUTF16toASCII(tokenizer.nextToken()).get();
+      const char *trimmedRole = nsAccUtils::TrimmedRole(rawRole, content);
+      if (*trimmedRole) {
+        if (!trimmedRoles.IsEmpty()) {
+          trimmedRoles.AppendLiteral(" ");
+        }
+        trimmedRoles.Append(NS_ConvertASCIItoUTF16(trimmedRole));
+      }
+    } 
+    if (!trimmedRoles.IsEmpty()) {
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"),  trimmedRoles, oldValueUnused);          
+    }
   }
 
   // Make sure to keep these two arrays in sync
   PRUint32 ariaPropTypes = nsAccUtils::GetAriaPropTypes(content, mWeakShell);
   char *ariaPropertyString[] = { "live", "channel", "atomic", "relevant", "datatype", "level",
                              "posinset", "setsize", "sort", "grab", "dropeffect"};
   EAriaProperty ariaPropertyEnum[] = { eAria_live, eAria_channel, eAria_atomic, eAria_relevant,
                                      eAria_datatype, eAria_level, eAria_posinset, eAria_setsize,
@@ -2193,17 +2217,17 @@ nsAccessible::GroupPosition(PRInt32 *aGr
   nsAccUtils::GetAccGroupAttrs(attributes, &level, &posInSet, &setSize);
 
   if (!posInSet && !setSize)
     return NS_OK;
 
   *aGroupLevel = level;
 
   *aPositionInGroup = posInSet;
-  *aSimilarItemsInGroup = setSize - 1;
+  *aSimilarItemsInGroup = setSize;
 
   return NS_OK;
 }
 
 PRBool nsAccessible::MappedAttrState(nsIContent *aContent, PRUint32 *aStateInOut,
                                      nsStateMapEntry *aStateMapEntry)
 {
   // Return true if we should continue
@@ -2573,17 +2597,17 @@ NS_IMETHODIMP nsAccessible::GetAccessibl
 /* nsIAccessible getAccessibleBelow(); */
 NS_IMETHODIMP nsAccessible::GetAccessibleBelow(nsIAccessible **_retval)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 nsIDOMNode* nsAccessible::GetAtomicRegion()
 {
-  nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
+  nsCOMPtr<nsIContent> content = GetRoleContent(mDOMNode);
   nsIContent *loopContent = content;
   nsAutoString atomic;
   PRUint32 ariaPropTypes = nsAccUtils::GetAriaPropTypes(content, mWeakShell);
 
   while (loopContent && !nsAccUtils::GetAriaProperty(loopContent, mWeakShell,
                                                      eAria_atomic, atomic,
                                                      ariaPropTypes)) {
     loopContent = loopContent->GetParent();
@@ -2926,17 +2950,18 @@ nsAccessible::GetNextWithState(nsIAccess
     current->GetFirstChild(getter_AddRefs(look));
     while (!look) {
       if (current == this) {
         return nsnull; // At top of subtree
       }
       current->GetNextSibling(getter_AddRefs(look));
       if (!look) {
         current->GetParent(getter_AddRefs(look));
-        current.swap(look);
+        current = look;
+        look = nsnull;
         continue;
       }
     }
     current.swap(look);
     state = State(current);
   }
 
   nsIAccessible *returnAccessible = nsnull;
@@ -3251,16 +3276,19 @@ PRBool nsAccessible::CheckVisibilityInPa
       view = view->GetParent();
     }
 
     nsIDocument* parentDoc = document->GetParentDocument();
     if (parentDoc != nsnull) {
       nsIContent* content = parentDoc->FindContentForSubDocument(document);
       if (content != nsnull) {
         nsIPresShell* shell = parentDoc->GetPrimaryShell();
+        if (!shell) {
+          return PR_FALSE;
+        }
         nsIFrame* frame = shell->GetPrimaryFrameFor(content);
         while (frame != nsnull && !frame->HasView()) {
           frame = frame->GetParent();
         }
 
         if (frame != nsnull) {
           view = frame->GetViewExternal();
         }
@@ -3295,16 +3323,18 @@ nsAccessible::GetAttrValue(EAriaProperty
 
   return result;
 }
 
 PRBool nsAccessible::MustPrune(nsIAccessible *aAccessible)
 { 
   PRUint32 role = Role(aAccessible);
   return role == nsIAccessibleRole::ROLE_MENUITEM || 
+         role == nsIAccessibleRole::ROLE_COMBOBOX_OPTION ||
+         role == nsIAccessibleRole::ROLE_OPTION ||
          role == nsIAccessibleRole::ROLE_ENTRY ||
          role == nsIAccessibleRole::ROLE_PASSWORD_TEXT ||
          role == nsIAccessibleRole::ROLE_PUSHBUTTON ||
          role == nsIAccessibleRole::ROLE_TOGGLE_BUTTON ||
          role == nsIAccessibleRole::ROLE_GRAPHIC ||
          role == nsIAccessibleRole::ROLE_SLIDER ||
          role == nsIAccessibleRole::ROLE_PROGRESSBAR ||
          role == nsIAccessibleRole::ROLE_SEPARATOR;
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -1,9 +1,9 @@
- /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* -*- 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/
  *
@@ -109,17 +109,16 @@ public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLE
   NS_DECL_NSPIACCESSIBLE
   NS_DECL_NSIACCESSIBLEHYPERLINK
   NS_DECL_NSIACCESSIBLESELECTABLE
   NS_DECL_NSIACCESSIBLEVALUE
 
   // nsIAccessNode
-  NS_IMETHOD Init();
   NS_IMETHOD Shutdown();
 
   /**
    * Return the state of accessible that doesn't take into account ARIA states.
    * Use nsIAccessible::finalState() to get all states for accessible. If
    * second argument is omitted then second bit field of accessible state won't
    * be calculated.
    */
@@ -156,16 +155,25 @@ public:
   static PRBool MustPrune(nsIAccessible *aAccessible);
   
   already_AddRefed<nsIAccessible> GetParent() {
     nsIAccessible *parent = nsnull;
     GetParent(&parent);
     return parent;
   }
   
+  /**
+   *  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.
+   *  @param aDOMNode   The DOM node for the accessible that may be affected by ARIA
+   *  @return The nsIContent which may have ARIA markup
+   */
+  static nsIContent *GetRoleContent(nsIDOMNode *aDOMNode);
+
 protected:
   PRBool MappedAttrState(nsIContent *aContent, PRUint32 *aStateInOut, nsStateMapEntry *aStateMapEntry);
   virtual nsIFrame* GetBoundsFrame();
   virtual void GetBoundsRect(nsRect& aRect, nsIFrame** aRelativeFrame);
   PRBool IsVisible(PRBool *aIsOffscreen); 
 
   // Relation helpers
 
@@ -176,17 +184,16 @@ protected:
    * @param aIDProperty  The ARIA relationship property to get the text for
    * @param aName        Where to put the text
    * @return error or success code
    */
   nsresult GetTextFromRelationID(EAriaProperty aIDProperty, nsString &aName);
 
   static nsIContent *GetHTMLLabelContent(nsIContent *aForNode);
   static nsIContent *GetLabelContent(nsIContent *aForNode);
-  static nsIContent *GetRoleContent(nsIDOMNode *aDOMNode);
 
   // Name helpers
   nsresult GetHTMLName(nsAString& _retval, PRBool aCanAggregateSubtree = PR_TRUE);
   nsresult GetXULName(nsAString& aName, PRBool aCanAggregateSubtree = PR_TRUE);
   // For accessibles that are not lists of choices, the name of the subtree should be the 
   // sum of names in the subtree
   nsresult AppendFlatStringFromSubtree(nsIContent *aContent, nsAString *aFlatString);
   nsresult AppendNameFromAccessibleFor(nsIContent *aContent, nsAString *aFlatString,
--- a/accessible/src/base/nsAccessibleEventData.cpp
+++ b/accessible/src/base/nsAccessibleEventData.cpp
@@ -44,16 +44,17 @@
 #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"
 
 PRBool nsAccEvent::gLastEventFromUserInput = PR_FALSE;
 nsIDOMNode* nsAccEvent::gLastEventNodeWeak = 0;
 
 NS_IMPL_ISUPPORTS1(nsAccEvent, nsIAccessibleEvent)
@@ -119,16 +120,20 @@ void nsAccEvent::PrepareForEvent(nsIAcce
   PRBool isFromUserInput;
   aEvent->GetIsFromUserInput(&isFromUserInput);
   PrepareForEvent(eventNode, isFromUserInput);
 }
 
 void nsAccEvent::PrepareForEvent(nsIDOMNode *aEventNode,
                                  PRBool aForceIsFromUserInput)
 {
+  if (!aEventNode) {
+    return;
+  }
+
   gLastEventNodeWeak = aEventNode;
   if (aForceIsFromUserInput) {
     gLastEventFromUserInput = PR_TRUE;
     return;
   }
 
   nsCOMPtr<nsIDOMDocument> domDoc;
   aEventNode->GetOwnerDocument(getter_AddRefs(domDoc));
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -116,16 +116,18 @@ NS_IMETHODIMP nsLinkableAccessible::Take
 }
 
 /* long GetState (); */
 NS_IMETHODIMP
 nsLinkableAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsHyperTextAccessibleWrap::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   if (mIsLink) {
     *aState |= nsIAccessibleStates::STATE_LINKED;
     nsCOMPtr<nsILink> link = do_QueryInterface(mActionContent);
     if (link) {
       nsLinkState linkState;
       link->GetLinkState(linkState);
       if (linkState == eLinkState_Visited) {
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -230,16 +230,18 @@ nsDocAccessible::GetDescription(nsAStrin
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // nsAccessible::GetState() always fail for document accessible.
   nsAccessible::GetState(aState, aExtraState);
+  if (!mDOMNode)
+    return NS_OK;
 
 #ifdef MOZ_XUL
   nsCOMPtr<nsIXULDocument> xulDoc(do_QueryInterface(mDocument));
   if (!xulDoc)
 #endif
   {
     // XXX Need to invent better check to see if doc is focusable,
     // which it should be if it is scrollable. A XUL document could be focusable.
@@ -1801,16 +1803,20 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
   nsCOMPtr<nsIAccessNode> childAccessNode;
   GetCachedAccessNode(childNode, getter_AddRefs(childAccessNode));
   nsCOMPtr<nsIAccessible> childAccessible = do_QueryInterface(childAccessNode);
   if (!childAccessible && !isHiding) {
     // If not about to hide it, make sure there's an accessible so we can fire an
     // event for it
     GetAccService()->GetAttachedAccessibleFor(childNode,
                                               getter_AddRefs(childAccessible));
+    if (childAccessible) {
+      // New accessible created -- to make sure to adopt the children from the old parent.
+      AdoptChildren(childAccessible);
+    }
   }
 
 #ifdef DEBUG_A11Y
   nsAutoString localName;
   childNode->GetLocalName(localName);
   const char *hasAccessible = childAccessible ? " (acc)" : "";
   if (aChangeEventType == nsIAccessibleEvent::EVENT_ASYNCH_HIDE) {
     printf("[Hide %s %s]\n", NS_ConvertUTF16toUTF8(localName).get(), hasAccessible);
@@ -1928,16 +1934,23 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
       NS_ENSURE_TRUE(reorderEvent, NS_ERROR_OUT_OF_MEMORY);
       FireDelayedAccessibleEvent(reorderEvent, eCoalesceFromSameSubtree, isAsynch);
     }
   }
 
   return NS_OK;
 }
 
+void nsDocAccessible::AdoptChildren(nsIAccessible *aAccessible)
+{
+  PRInt32 childCountUnused;
+  // Force CacheChildren()
+  aAccessible->GetChildCount(&childCountUnused);
+}
+
 NS_IMETHODIMP
 nsDocAccessible::GetAccessibleInParentChain(nsIDOMNode *aNode,
                                             PRBool aCanCreate,
                                             nsIAccessible **aAccessible)
 {
   // Find accessible in parent chain of DOM nodes, or return null
   *aAccessible = nsnull;
   nsCOMPtr<nsIDOMNode> currentNode(aNode), parentNode;
@@ -1954,24 +1967,27 @@ nsDocAccessible::GetAccessibleInParentCh
       *aAccessible = this;
       break;
     }
 
     nsCOMPtr<nsIDOMNode> relevantNode;
     if (NS_SUCCEEDED(accService->GetRelevantContentNodeFor(currentNode, getter_AddRefs(relevantNode))) && relevantNode) {
       currentNode = relevantNode;
     }
-    if (aCanCreate) {
-      accService->GetAccessibleInWeakShell(currentNode, mWeakShell, aAccessible);
+    // Try cached accessible
+    nsCOMPtr<nsIAccessNode> accessNode;
+    GetCachedAccessNode(currentNode, getter_AddRefs(accessNode)); // AddRefs
+    if (accessNode) {
+      CallQueryInterface(accessNode, aAccessible); // AddRefs
     }
-    else { // Only return cached accessibles, don't create anything
-      nsCOMPtr<nsIAccessNode> accessNode;
-      GetCachedAccessNode(currentNode, getter_AddRefs(accessNode)); // AddRefs
-      if (accessNode) {
-        CallQueryInterface(accessNode, aAccessible); // AddRefs
+    if (!*aAccessible && aCanCreate) {
+      accService->GetAccessibleInWeakShell(currentNode, mWeakShell, aAccessible);
+      if (*aAccessible) {
+        // New accessible created -- to make sure to adopt the children from the old parent.
+        AdoptChildren(*aAccessible);
       }
     }
   } while (!*aAccessible);
 
   return NS_OK;
 }
 
 nsresult
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -199,16 +199,24 @@ class nsDocAccessible : public nsHyperTe
      * @param aDOMNode               the given node
      * @param aEventType             event type to fire an event
      * @param aDelay                 whether to fire the event on a delay
      * @param aForceIsFromUserInput  the event is known to be from user input
      */
     nsresult FireShowHideEvents(nsIDOMNode *aDOMNode, PRUint32 aEventType,
                                 PRBool aDelay, PRBool aForceIsFromUserInput);
 
+    /**
+     * For a new accessible that is created because of a DOM mutation,
+     * make sure that any children it has, which were already children
+     * of the parent should be assigned to it
+     * @param aAccessible The new accessible
+     */
+    void AdoptChildren(nsIAccessible *aAccessible);
+
     nsAccessNodeHashtable mAccessNodeCache;
     void *mWnd;
     nsCOMPtr<nsIDocument> mDocument;
     nsCOMPtr<nsITimer> mScrollWatchTimer;
     nsCOMPtr<nsITimer> mFireEventTimer;
     PRUint16 mScrollPositionChangedTicks; // Used for tracking scroll events
     PRPackedBool mIsContentLoaded;
     nsCOMArray<nsIAccessibleEvent> mEventsToFire;
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -207,16 +207,18 @@ PRUint32 nsRootAccessible::GetChromeFlag
 }
 #endif
 
 NS_IMETHODIMP
 nsRootAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsDocAccessibleWrap::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
 #ifdef MOZ_XUL
   PRUint32 chromeFlags = GetChromeFlags();
   if (chromeFlags & nsIWebBrowserChrome::CHROME_WINDOW_RESIZE) {
     *aState |= nsIAccessibleStates::STATE_SIZEABLE;
   }
   if (chromeFlags & nsIWebBrowserChrome::CHROME_TITLEBAR) {
     // If it has a titlebar it's movable
@@ -487,20 +489,24 @@ PRBool nsRootAccessible::FireAccessibleF
 
   gLastFocusedAccessiblesState = State(finalFocusAccessible);
   PRUint32 role = Role(finalFocusAccessible);
   if (role == nsIAccessibleRole::ROLE_MENUITEM) {
     if (!mCurrentARIAMenubar) {  // Entering menus
       PRUint32 naturalRole; // The natural role is the role that this type of element normally has
       finalFocusAccessible->GetRole(&naturalRole);
       if (role != naturalRole) { // Must be a DHTML menuitem
-        mCurrentARIAMenubar =
+        nsCOMPtr<nsIAccessible> menuBarAccessible =
           nsAccUtils::GetAncestorWithRole(finalFocusAccessible, nsIAccessibleRole::ROLE_MENUBAR);
-        if (mCurrentARIAMenubar) {
-          nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENU_START, mCurrentARIAMenubar);
+        nsCOMPtr<nsIAccessNode> menuBarAccessNode = do_QueryInterface(menuBarAccessible);
+        if (menuBarAccessNode) {
+          menuBarAccessNode->GetDOMNode(getter_AddRefs(mCurrentARIAMenubar));
+          if (mCurrentARIAMenubar) {
+            nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENU_START, menuBarAccessible);
+          }
         }
       }
     }
   }
   else if (mCurrentARIAMenubar) {
     nsCOMPtr<nsIAccessibleEvent> menuEndEvent =
       new nsAccEvent(nsIAccessibleEvent::EVENT_MENU_END, mCurrentARIAMenubar, nsnull, PR_FALSE);
     if (menuEndEvent) {
--- a/accessible/src/base/nsRootAccessible.h
+++ b/accessible/src/base/nsRootAccessible.h
@@ -120,14 +120,14 @@ class nsRootAccessible : public nsDocAcc
     void FireCurrentFocusEvent();
     void GetChromeEventHandler(nsIDOMEventTarget **aChromeTarget);
 #ifdef MOZ_XUL
     PRUint32 GetChromeFlags();
 #endif
     already_AddRefed<nsIDocShellTreeItem>
            GetContentDocShell(nsIDocShellTreeItem *aStart);
     nsRefPtr<nsCaretAccessible> mCaretAccessible;
-    nsCOMPtr<nsIAccessible> mCurrentARIAMenubar;
+    nsCOMPtr<nsIDOMNode> mCurrentARIAMenubar;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsRootAccessible, NS_ROOTACCESSIBLE_IMPL_CID)
 
 #endif  
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -368,16 +368,18 @@ nsHTML4ButtonAccessible::GetState(PRUint
 
 // --- textfield -----
 
 nsHTMLTextFieldAccessible::nsHTMLTextFieldAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell):
 nsHyperTextAccessibleWrap(aNode, aShell)
 {
 }
 
+NS_IMPL_ISUPPORTS_INHERITED3(nsHTMLTextFieldAccessible, nsAccessible, nsHyperTextAccessible, nsIAccessibleText, nsIAccessibleEditableText)
+
 NS_IMETHODIMP nsHTMLTextFieldAccessible::GetRole(PRUint32 *aRole)
 {
   *aRole = nsIAccessibleRole::ROLE_ENTRY;
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (content &&
       content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::type,
                            nsAccessibilityAtoms::password, eIgnoreCase)) {
     *aRole = nsIAccessibleRole::ROLE_PASSWORD_TEXT;
--- a/accessible/src/html/nsHTMLFormControlAccessible.h
+++ b/accessible/src/html/nsHTMLFormControlAccessible.h
@@ -99,16 +99,18 @@ public:
 class nsHTMLTextFieldAccessible : public nsHyperTextAccessibleWrap
 {
 
 public:
   enum { eAction_Click = 0 };
 
   nsHTMLTextFieldAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
 
+  NS_DECL_ISUPPORTS_INHERITED
+
   NS_IMETHOD GetRole(PRUint32 *_retval); 
   NS_IMETHOD GetName(nsAString& aName); 
   NS_IMETHOD GetValue(nsAString& _retval); 
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 index);
 
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -79,26 +79,28 @@ nsLinkableAccessible(aDOMNode, aShell), 
   }
 
   if (mMapElement) {
     mAccessNodeCache = new nsAccessNodeHashtable();
     mAccessNodeCache->Init(kDefaultImageCacheSize);
   }
 }
 
-NS_IMPL_ISUPPORTS_INHERITED1(nsHTMLImageAccessible, nsLinkableAccessible, nsIAccessibleImage)
+NS_IMPL_ISUPPORTS_INHERITED1(nsHTMLImageAccessible, nsAccessible, nsIAccessibleImage)
 
 NS_IMETHODIMP
 nsHTMLImageAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // The state is a bitfield, get our inherited state, then logically OR it with
   // STATE_ANIMATED if this is an animated image.
 
   nsresult rv = nsLinkableAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsCOMPtr<nsIImageLoadingContent> content(do_QueryInterface(mDOMNode));
   nsCOMPtr<imgIRequest> imageRequest;
 
   if (content)
     content->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                         getter_AddRefs(imageRequest));
 
--- a/accessible/src/html/nsHTMLLinkAccessible.cpp
+++ b/accessible/src/html/nsHTMLLinkAccessible.cpp
@@ -65,16 +65,18 @@ NS_IMETHODIMP nsHTMLLinkAccessible::GetR
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLLinkAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsLinkableAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   *aState  &= ~nsIAccessibleStates::STATE_READONLY;
 
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (content && content->HasAttr(kNameSpaceID_None,
                                   nsAccessibilityAtoms::name)) {
     // This is how we indicate it is a named anchor
     // In other words, this anchor can be selected as a location :)
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -325,19 +325,31 @@ nsHTMLSelectListAccessible::nsHTMLSelect
   *     nsIAccessibleStates::STATE_MULTISELECTABLE
   *     nsIAccessibleStates::STATE_EXTSELECTABLE
   */
 NS_IMETHODIMP
 nsHTMLSelectListAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsHTMLSelectableAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsCOMPtr<nsIDOMHTMLSelectElement> select (do_QueryInterface(mDOMNode));
   if (select) {
+    if (*aState | nsIAccessibleStates::STATE_FOCUSED) {
+      // Treat first focusable option node as actual focus, in order
+      // to avoid confusing JAWS, which needs focus on the option
+      nsCOMPtr<nsIDOMNode> focusedOption;
+      nsHTMLSelectOptionAccessible::GetFocusedOptionNode(mDOMNode, 
+                                                         getter_AddRefs(focusedOption));
+      if (focusedOption) { // Clear focused state since it is on option
+        *aState &= ~nsIAccessibleStates::STATE_FOCUSED;
+      }
+    }
     PRBool multiple;
     select->GetMultiple(&multiple);
     if ( multiple )
       *aState |= nsIAccessibleStates::STATE_MULTISELECTABLE |
                  nsIAccessibleStates::STATE_EXTSELECTABLE;
   }
 
   return NS_OK;
@@ -480,20 +492,20 @@ nsHyperTextAccessibleWrap(aDOMNode, aShe
   }
   SetParent(parentAccessible);
 }
 
 /** We are a ListItem */
 NS_IMETHODIMP nsHTMLSelectOptionAccessible::GetRole(PRUint32 *aRole)
 {
   if (mParent && Role(mParent) == nsIAccessibleRole::ROLE_COMBOBOX_LIST) {
-    *aRole = nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM;
+    *aRole = nsIAccessibleRole::ROLE_COMBOBOX_OPTION;
   }
   else {
-    *aRole = nsIAccessibleRole::ROLE_LISTITEM;
+    *aRole = nsIAccessibleRole::ROLE_OPTION;
   }
   return NS_OK;
 }
 
 /**
   * Get our Name from our Content's subtree
   */
 NS_IMETHODIMP nsHTMLSelectOptionAccessible::GetName(nsAString& aName)
@@ -599,34 +611,46 @@ nsIFrame* nsHTMLSelectOptionAccessible::
   *     STATE_OFFSCREEN
   */
 NS_IMETHODIMP
 nsHTMLSelectOptionAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Upcall to nsAccessible, but skip nsHyperTextAccessible impl
   // because we don't want EXT_STATE_EDITABLE or EXT_STATE_SELECTABLE_TEXT
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
+  NS_ENSURE_TRUE(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   PRUint32 selectState, selectExtState;
   nsCOMPtr<nsIContent> selectContent = GetSelectState(&selectState,
                                                       &selectExtState);
   if (selectState & nsIAccessibleStates::STATE_INVISIBLE) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIDOMNode> selectNode = do_QueryInterface(selectContent); 
   NS_ENSURE_TRUE(selectNode, NS_ERROR_FAILURE);
 
   // Is disabled?
   if (0 == (*aState & nsIAccessibleStates::STATE_UNAVAILABLE)) {
     *aState |= (nsIAccessibleStates::STATE_FOCUSABLE |
                 nsIAccessibleStates::STATE_SELECTABLE);
+    // When the list is focused but no option is actually focused,
+    // Firefox draws a focus ring around the first non-disabled option.
+    // We need to indicated STATE_FOCUSED in that case, because it
+    // prevents JAWS from ignoring the list
+    // GetFocusedOptionNode() ensures that an option node is 
+    // returned in this case, as long as some focusable option exists
+    // in the listbox
+    nsCOMPtr<nsIDOMNode> focusedOptionNode;
+    GetFocusedOptionNode(selectNode, getter_AddRefs(focusedOptionNode));
+    if (focusedOptionNode == mDOMNode) {
+      *aState |= nsIAccessibleStates::STATE_FOCUSED;
+    }
   }
 
   // Are we selected?
   PRBool isSelected = PR_FALSE;
   nsCOMPtr<nsIDOMHTMLOptionElement> option (do_QueryInterface(mDOMNode));
   if (option) {
     option->GetSelected(&isSelected);
     if ( isSelected ) 
@@ -783,16 +807,32 @@ nsresult nsHTMLSelectOptionAccessible::G
     nsIListControlFrame *listFrame = nsnull;
     frame->QueryInterface(NS_GET_IID(nsIListControlFrame), (void**)&listFrame);
     if (listFrame) {
       // Get what's focused in listbox by asking frame for "selected item". 
       // Can't use dom interface for this, because it will always return the first selected item
       // when there is more than 1 item selected. We need the focused item, not
       // the first selected item.
       focusedOptionIndex = listFrame->GetSelectedIndex();
+      if (focusedOptionIndex == -1) {
+        nsCOMPtr<nsIDOMNode> nextOption;
+        while (PR_TRUE) {
+          ++ focusedOptionIndex;
+          options->Item(focusedOptionIndex, getter_AddRefs(nextOption));
+          nsCOMPtr<nsIDOMHTMLOptionElement> optionElement = do_QueryInterface(nextOption);
+          if (!optionElement) {
+            break;
+          }
+          PRBool disabled;
+          optionElement->GetDisabled(&disabled);
+          if (!disabled) {
+            break;
+          }
+        }
+      }
     }
     else  // Combo boxes can only have 1 selected option, so they can use the dom interface for this
       rv = selectElement->GetSelectedIndex(&focusedOptionIndex);
   }
 
   // Either use options and focused index, or default return null
   if (NS_SUCCEEDED(rv) && options && focusedOptionIndex >= 0) {  // Something is focused
     rv = options->Item(focusedOptionIndex, aFocusedOptionNode);
@@ -1032,16 +1072,18 @@ NS_IMETHODIMP nsHTMLComboboxAccessible::
   *     STATE_COLLAPSED
   */
 NS_IMETHODIMP
 nsHTMLComboboxAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsIFrame *frame = GetBoundsFrame();
   nsIComboboxControlFrame *comboFrame = nsnull;
   if (frame) {
     frame->QueryInterface(NS_GET_IID(nsIComboboxControlFrame), (void**)&comboFrame);
   }
 
   if (comboFrame && comboFrame->IsDroppedDown()) {
@@ -1350,16 +1392,18 @@ NS_IMETHODIMP nsHTMLComboboxButtonAccess
   *     STATE_INVISIBLE
   */
 NS_IMETHODIMP
 nsHTMLComboboxButtonAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsIFrame *boundsFrame = GetBoundsFrame();
   nsIComboboxControlFrame* comboFrame = nsnull;
   if (boundsFrame)
     boundsFrame->QueryInterface(NS_GET_IID(nsIComboboxControlFrame), (void**)&comboFrame);
 
   if (!comboFrame) {
     *aState |= nsIAccessibleStates::STATE_INVISIBLE;
@@ -1407,16 +1451,18 @@ nsIFrame *nsHTMLComboboxListAccessible::
   *     STATE_FLOATING
   */
 NS_IMETHODIMP
 nsHTMLComboboxListAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsIFrame *boundsFrame = GetBoundsFrame();
   nsIComboboxControlFrame* comboFrame = nsnull;
   if (boundsFrame)
     boundsFrame->QueryInterface(NS_GET_IID(nsIComboboxControlFrame), (void**)&comboFrame);
 
   if (comboFrame && comboFrame->IsDroppedDown())
     *aState |= nsIAccessibleStates::STATE_FLOATING;
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -69,28 +69,16 @@ nsHyperTextAccessibleWrap(aDomNode, aShe
 
 /* unsigned long getRole (); */
 NS_IMETHODIMP nsHTMLTableCellAccessible::GetRole(PRUint32 *aResult)
 {
   *aResult = nsIAccessibleRole::ROLE_CELL;
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsHTMLTableCellAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
-{
-  nsresult rv = nsAccessible::GetState(aState, aExtraState);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Inherit all states except focusable state since table cells cannot be
-  // focused.
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
-  return NS_OK;
-}
-
 NS_IMPL_ISUPPORTS_INHERITED1(nsHTMLTableAccessible, nsAccessible, nsIAccessibleTable)
 
 nsHTMLTableAccessible::nsHTMLTableAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell):
 nsAccessibleWrap(aDomNode, aShell)
 { 
 }
 
 void nsHTMLTableAccessible::CacheChildren()
@@ -141,20 +129,17 @@ NS_IMETHODIMP nsHTMLTableAccessible::Get
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLTableAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv= nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
   *aState |= nsIAccessibleStates::STATE_READONLY;
-  // Inherit all states except focusable state since tables cannot be focused.
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
   return NS_OK;
 }
 
 NS_IMETHODIMP nsHTMLTableAccessible::GetName(nsAString& aName)
 {
   aName.Truncate();  // Default name is blank
 
   nsAccessible::GetName(aName);
--- a/accessible/src/html/nsHTMLTableAccessible.h
+++ b/accessible/src/html/nsHTMLTableAccessible.h
@@ -44,25 +44,24 @@
 
 class nsHTMLTableCellAccessible : public nsHyperTextAccessibleWrap
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
 
   nsHTMLTableCellAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *aResult); 
-  NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
 };
 
 class nsITableLayout;
 
-// XXX For now debugging descriptions are always on via SHOW_LAYOUT_HEURISTIC
-// This will allow release trunk builds to be used by testers to refine the algorithm
-// Change to |#define SHOW_LAYOUT_HEURISTIC DEBUG| before final release
-#define SHOW_LAYOUT_HEURISTIC
+// To turn on table debugging descriptions define SHOW_LAYOUT_HEURISTIC
+// This allow release trunk builds to be used by testers to refine the
+// data vs. layout heuristic
+// #define SHOW_LAYOUT_HEURISTIC
 
 class nsHTMLTableAccessible : public nsAccessibleWrap,
                               public nsIAccessibleTable
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLETABLE
 
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -72,16 +72,18 @@ NS_IMETHODIMP nsHTMLTextAccessible::GetR
   return nsTextAccessible::GetRole(aRole);
 }
 
 NS_IMETHODIMP
 nsHTMLTextAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsTextAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsCOMPtr<nsIAccessible> docAccessible = 
     do_QueryInterface(nsCOMPtr<nsIAccessibleDocument>(GetDocAccessible()));
   if (docAccessible) {
      PRUint32 state, extState;
      docAccessible->GetFinalState(&state, &extState);
      if (0 == (extState & nsIAccessibleStates::EXT_STATE_EDITABLE)) {
        *aState |= nsIAccessibleStates::STATE_READONLY; // Links not focusable in editor
@@ -115,41 +117,34 @@ nsLeafAccessible(aDomNode, aShell)
 }
 
 NS_IMETHODIMP nsHTMLHRAccessible::GetRole(PRUint32 *aRole)
 {
   *aRole = nsIAccessibleRole::ROLE_SEPARATOR;
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsHTMLHRAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
-{
-  nsresult rv = nsLeafAccessible::GetState(aState, aExtraState);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
-  return NS_OK;
-}
-
 nsHTMLBRAccessible::nsHTMLBRAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell):
 nsLeafAccessible(aDomNode, aShell)
 { 
 }
 
 NS_IMETHODIMP nsHTMLBRAccessible::GetRole(PRUint32 *aRole)
 {
   *aRole = nsIAccessibleRole::ROLE_WHITESPACE;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLBRAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   *aState = nsIAccessibleStates::STATE_READONLY;
+  if (aExtraState) {
+    *aExtraState = mDOMNode ? 0 : nsIAccessibleStates::EXT_STATE_DEFUNCT;
+  }
   return NS_OK;
 }
 
 NS_IMETHODIMP nsHTMLBRAccessible::GetName(nsAString& aName)
 {
   aName = static_cast<PRUnichar>('\n');    // Newline char
   return NS_OK;
 }
@@ -183,19 +178,20 @@ NS_IMETHODIMP nsHTMLLabelAccessible::Get
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLLabelAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsTextAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= (nsIAccessibleStates::STATE_LINKED |
-              nsIAccessibleStates::STATE_TRAVERSED);  // Only use link states
+  if (mDOMNode) {
+    *aState &= (nsIAccessibleStates::STATE_LINKED |
+                nsIAccessibleStates::STATE_TRAVERSED); // Only use link states
+  }
   return NS_OK;
 }
 
 NS_IMETHODIMP nsHTMLLabelAccessible::GetFirstChild(nsIAccessible **aFirstChild) 
 {  
   // A <label> is not necessarily a leaf!
   return nsAccessible::GetFirstChild(aFirstChild);
 }
--- a/accessible/src/html/nsHTMLTextAccessible.h
+++ b/accessible/src/html/nsHTMLTextAccessible.h
@@ -58,17 +58,16 @@ public:
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
 };
 
 class nsHTMLHRAccessible : public nsLeafAccessible
 {
 public:
   nsHTMLHRAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *aRole); 
-  NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
 };
 
 class nsHTMLBRAccessible : public nsLeafAccessible
 {
 public:
   nsHTMLBRAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *aRole); 
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -86,39 +86,30 @@ nsresult nsHyperTextAccessible::QueryInt
     // return nsDocAccessible to inherit from nsAccessibleWrap.
 
     if (aIID.Equals(NS_GET_IID(nsHyperTextAccessible))) {
       *aInstancePtr = static_cast<nsHyperTextAccessible*>(this);
       NS_ADDREF_THIS();
       return NS_OK;
     }
 
-    PRUint32 role = Role(this);
-    if (role == nsIAccessibleRole::ROLE_GRAPHIC ||
-        role == nsIAccessibleRole::ROLE_IMAGE_MAP ||
-        role == nsIAccessibleRole::ROLE_TEXT_LEAF) {
+    if (mRoleMapEntry &&
+        (mRoleMapEntry->role == nsIAccessibleRole::ROLE_GRAPHIC ||
+         mRoleMapEntry->role == nsIAccessibleRole::ROLE_IMAGE_MAP)) {
+      // ARIA roles that these interfaces are not appropriate for
       return nsAccessible::QueryInterface(aIID, aInstancePtr);
     }
 
     if (aIID.Equals(NS_GET_IID(nsIAccessibleText))) {
       *aInstancePtr = static_cast<nsIAccessibleText*>(this);
       NS_ADDREF_THIS();
       return NS_OK;
     }
 
     if (aIID.Equals(NS_GET_IID(nsIAccessibleHyperText))) {
-      if (role == nsIAccessibleRole::ROLE_ENTRY ||
-          role == nsIAccessibleRole::ROLE_PASSWORD_TEXT) {
-        nsCOMPtr<nsIEditor> editor;
-        GetAssociatedEditor(getter_AddRefs(editor));
-        nsCOMPtr<nsIPlaintextEditor> peditor(do_QueryInterface(editor));
-        if (peditor) {
-          return NS_ERROR_NO_INTERFACE; // No embedded objects ever in plain text
-        }
-      }
       *aInstancePtr = static_cast<nsIAccessibleHyperText*>(this);
       NS_ADDREF_THIS();
       return NS_OK;
     }
 
     if (aIID.Equals(NS_GET_IID(nsIAccessibleEditableText))) {
       *aInstancePtr = static_cast<nsIAccessibleEditableText*>(this);
       NS_ADDREF_THIS();
@@ -170,18 +161,17 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHyperTextAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsAccessibleWrap::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  if (!aExtraState)
+  if (!mDOMNode || !aExtraState)
     return NS_OK;
 
   nsCOMPtr<nsIEditor> editor;
   GetAssociatedEditor(getter_AddRefs(editor));
   if (editor) {
     PRUint32 flags;
     editor->GetFlags(&flags);
     if (0 == (flags & nsIPlaintextEditor::eEditorReadonlyMask)) {
--- a/accessible/src/mac/nsRoleMap.h
+++ b/accessible/src/mac/nsRoleMap.h
@@ -152,12 +152,15 @@ static const NSString* AXRoles [] = {
   NSAccessibilityGroupRole,                     // ROLE_SECTION
   NSAccessibilityUnknownRole,                   // ROLE_REDUNDANT_OBJECT
   NSAccessibilityGroupRole,                     // ROLE_FORM
   NSAccessibilityUnknownRole,                   // ROLE_IME
   NSAccessibilityUnknownRole,                   // ROLE_APP_ROOT. unused on OS X
   NSAccessibilityMenuItemRole,                  // ROLE_PARENT_MENUITEM
   NSAccessibilityGroupRole,                     // ROLE_CALENDAR
   NSAccessibilityMenuRole,                      // ROLE_COMBOBOX_LIST
-  NSAccessibilityMenuItemRole,                  // ROLE_COMBOBOX_LISTITEM
+  NSAccessibilityMenuItemRole,                  // ROLE_COMBOBOX_OPTION
   NSAccessibilityImageRole,                     // ROLE_IMAGE_MAP
+  NSAccessibilityRowRole,                       // ROLE_OPTION
+  NSAccessibilityRowRole,                       // ROLE_RICH_OPTION
+  NSAccessibilityListRole,                      // ROLE_LISTBOX
   @"ROLE_LAST_ENTRY"                            // ROLE_LAST_ENTRY. bogus role that will never be shown (just marks the end of this array)!
 };
--- a/accessible/src/msaa/nsAccessNodeWrap.h
+++ b/accessible/src/msaa/nsAccessNodeWrap.h
@@ -31,34 +31,37 @@
  * 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 ***** */
 
-/* For documentation of the accessibility architecture, 
+/* For documentation of the accessibility architecture,
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 #ifndef _nsAccessNodeWrap_H_
 #define _nsAccessNodeWrap_H_
 
 #include "nsCOMPtr.h"
 #include "nsIAccessible.h"
 #include "nsIAccessibleEvent.h"
 #include "nsIWinAccessNode.h"
 #include "ISimpleDOMNode.h"
 #include "nsIDOMElement.h"
 #include "nsIContent.h"
 #include "nsAccessNode.h"
 #include "OLEIDL.H"
 #include "OLEACC.H"
-#include "winable.h"
+#include <winuser.h>
+#ifndef WINABLEAPI
+#include <winable.h>
+#endif
 #undef ERROR /// Otherwise we can't include nsIDOMNSEvent.h if we include this
 
 typedef LRESULT (STDAPICALLTYPE *LPFNNOTIFYWINEVENT)(DWORD event,HWND hwnd,LONG idObjectType,LONG idObject);
 typedef LRESULT (STDAPICALLTYPE *LPFNGETGUITHREADINFO)(DWORD idThread, GUITHREADINFO* pgui);
 
 class nsAccessNodeWrap :  public nsAccessNode,
                           public nsIWinAccessNode,
                           public ISimpleDOMNode,
--- a/accessible/src/msaa/nsEventMap.h
+++ b/accessible/src/msaa/nsEventMap.h
@@ -33,17 +33,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
  * 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 "winable.h"
+#include <winuser.h>
+#ifndef WINABLEAPI
+#include <winable.h>
+#endif
 #include "AccessibleEventId.h"
 
 const PRUint32 kEVENT_WIN_UNKNOWN = 0x00000000;
 const PRUint32 kEVENT_LAST_ENTRY  = 0xffffffff;
 
 static const PRUint32 gWinEventMap[] = {
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent doesn't have 0 constant
   EVENT_OBJECT_SHOW,                                 // nsIAccessibleEvent::EVENT_DOM_CREATE
--- a/accessible/src/msaa/nsRoleMap.h
+++ b/accessible/src/msaa/nsRoleMap.h
@@ -414,18 +414,27 @@ static const WindowsRoleMapItem gWindows
   { ROLE_SYSTEM_MENUITEM, ROLE_SYSTEM_MENUITEM },
 
   // nsIAccessibleRole::ROLE_CALENDAR
   { ROLE_SYSTEM_CLIENT, ROLE_SYSTEM_CLIENT },
 
   // nsIAccessibleRole::ROLE_COMBOBOX_LIST
   { ROLE_SYSTEM_LIST, ROLE_SYSTEM_LIST },
 
-  // nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM
+  // nsIAccessibleRole::ROLE_COMBOBOX_OPTION
   { ROLE_SYSTEM_LISTITEM, ROLE_SYSTEM_LISTITEM },
 
   // nsIAccessibleRole::ROLE_IMAGE_MAP
   { ROLE_SYSTEM_GRAPHIC, ROLE_SYSTEM_GRAPHIC },
 
+  // nsIAccessibleRole::ROLE_OPTION 
+  { ROLE_SYSTEM_LISTITEM, ROLE_SYSTEM_LISTITEM },
+  
+  // nsIAccessibleRole::ROLE_RICH_OPTION
+  { ROLE_SYSTEM_LIST, ROLE_SYSTEM_LIST },
+  
+  // nsIAccessibleRole::ROLE_LISTBOX
+  { ROLE_SYSTEM_LIST, ROLE_SYSTEM_LIST },
+  
   // nsIAccessibleRole::ROLE_LAST_ENTRY
   { ROLE_WINDOWS_LAST_ENTRY, ROLE_WINDOWS_LAST_ENTRY }
 };
 
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -170,16 +170,24 @@ nsXFormsAccessible::GetValue(nsAString& 
   return sXFormsService->GetValue(mDOMNode, aValue);
 }
 
 NS_IMETHODIMP
 nsXFormsAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
   *aState = 0;
+  if (!mDOMNode) {
+    if (aExtraState) {
+      *aExtraState = nsIAccessibleStates::EXT_STATE_DEFUNCT;
+    }
+    return NS_OK;
+  }
+  if (aExtraState)
+    *aExtraState = 0;
 
   NS_ENSURE_TRUE(sXFormsService, NS_ERROR_FAILURE);
 
   PRBool isRelevant = PR_FALSE;
   nsresult rv = sXFormsService->IsRelevant(mDOMNode, &isRelevant);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool isReadonly = PR_FALSE;
@@ -303,18 +311,17 @@ nsXFormsEditableAccessible::
 
 NS_IMETHODIMP
 nsXFormsEditableAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
 
   nsresult rv = nsXFormsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  if (!aExtraState)
+  if (!mDOMNode || !aExtraState)
     return NS_OK;
 
   PRBool isReadonly = PR_FALSE;
   rv = sXFormsService->IsReadonly(mDOMNode, &isReadonly);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!isReadonly) {
     PRBool isRelevant = PR_FALSE;
--- a/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
@@ -145,16 +145,18 @@ nsXFormsTriggerAccessible::DoAction(PRUi
 // nsXFormsInputAccessible
 
 nsXFormsInputAccessible::
   nsXFormsInputAccessible(nsIDOMNode *aNode, nsIWeakReference *aShell):
   nsXFormsEditableAccessible(aNode, aShell)
 {
 }
 
+NS_IMPL_ISUPPORTS_INHERITED3(nsXFormsInputAccessible, nsAccessible, nsHyperTextAccessible, nsIAccessibleText, nsIAccessibleEditableText)
+
 NS_IMETHODIMP
 nsXFormsInputAccessible::GetRole(PRUint32 *aRole)
 {
   NS_ENSURE_ARG_POINTER(aRole);
 
   *aRole = nsIAccessibleRole::ROLE_ENTRY;
   return NS_OK;
 }
@@ -204,16 +206,18 @@ nsXFormsInputBooleanAccessible::GetRole(
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsInputBooleanAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   nsAutoString value;
   rv = sXFormsService->GetValue(mDOMNode, value);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (value.EqualsLiteral("true"))
     *aState |= nsIAccessibleStates::STATE_CHECKED;
 
@@ -290,16 +294,18 @@ nsXFormsSecretAccessible::GetRole(PRUint
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsSecretAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsInputAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   *aState |= nsIAccessibleStates::STATE_PROTECTED;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsSecretAccessible::GetValue(nsAString& aValue)
 {
@@ -324,16 +330,18 @@ nsXFormsRangeAccessible::GetRole(PRUint3
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsRangeAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   PRUint32 isInRange = nsIXFormsUtilityService::STATE_NOT_A_RANGE;
   rv = sXFormsService->IsInRange(mDOMNode, &isInRange);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (isInRange == nsIXFormsUtilityService::STATE_OUT_OF_RANGE)
     *aState |= nsIAccessibleStates::STATE_INVALID;
 
@@ -405,16 +413,18 @@ nsXFormsSelectAccessible::
 {
 }
 
 NS_IMETHODIMP
 nsXFormsSelectAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsContainerAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   PRUint32 isInRange = nsIXFormsUtilityService::STATE_NOT_A_RANGE;
   rv = sXFormsService->IsInRange(mDOMNode, &isInRange);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (isInRange == nsIXFormsUtilityService::STATE_OUT_OF_RANGE)
     *aState |= nsIAccessibleStates::STATE_INVALID;
 
@@ -496,16 +506,18 @@ nsXFormsItemCheckgroupAccessible::GetRol
 }
 
 NS_IMETHODIMP
 nsXFormsItemCheckgroupAccessible::GetState(PRUint32 *aState,
                                            PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsSelectableItemAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   if (IsItemSelected())
     *aState |= nsIAccessibleStates::STATE_CHECKED;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -541,16 +553,18 @@ nsXFormsItemRadiogroupAccessible::GetRol
 }
 
 NS_IMETHODIMP
 nsXFormsItemRadiogroupAccessible::GetState(PRUint32 *aState,
                                            PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsSelectableItemAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   if (IsItemSelected())
     *aState |= nsIAccessibleStates::STATE_CHECKED;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -582,16 +596,18 @@ nsXFormsSelectComboboxAccessible::GetRol
 }
 
 NS_IMETHODIMP
 nsXFormsSelectComboboxAccessible::GetState(PRUint32 *aState,
                                            PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsSelectableAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   PRBool isOpen = PR_FALSE;
   rv = sXFormsService->IsDropmarkerOpen(mDOMNode, &isOpen);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (isOpen)
     *aState = nsIAccessibleStates::STATE_EXPANDED;
   else
@@ -630,18 +646,17 @@ nsXFormsItemComboboxAccessible::GetRole(
 }
 
 NS_IMETHODIMP
 nsXFormsItemComboboxAccessible::GetState(PRUint32 *aState,
                                          PRUint32 *aExtraState)
 {
   nsresult rv = nsXFormsSelectableItemAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  if (*aState & nsIAccessibleStates::STATE_UNAVAILABLE)
+  if (!mDOMNode || (*aState & nsIAccessibleStates::STATE_UNAVAILABLE))
     return NS_OK;
 
   *aState |= nsIAccessibleStates::STATE_SELECTABLE;
   if (IsItemSelected())
     *aState |= nsIAccessibleStates::STATE_SELECTED;
 
   return NS_OK;
 }
--- a/accessible/src/xforms/nsXFormsFormControlsAccessible.h
+++ b/accessible/src/xforms/nsXFormsFormControlsAccessible.h
@@ -88,16 +88,18 @@ public:
  * Accessible object for xforms:input and xforms:textarea.
  */
 
 class nsXFormsInputAccessible : public nsXFormsEditableAccessible
 {
 public:
   nsXFormsInputAccessible(nsIDOMNode *aNode, nsIWeakReference *aShell);
 
+  NS_DECL_ISUPPORTS_INHERITED
+
   NS_IMETHOD GetRole(PRUint32 *aRole);
   NS_IMETHOD GetNumActions(PRUint8 *aCount);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 aIndex);
 };
 
 /**
  * Accessible object for xforms:input[type="xsd:boolean"].
--- a/accessible/src/xforms/nsXFormsWidgetsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsWidgetsAccessible.cpp
@@ -55,18 +55,24 @@ nsXFormsDropmarkerWidgetAccessible::GetR
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsDropmarkerWidgetAccessible::GetState(PRUint32 *aState,
                                              PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
+  *aState = 0;
+  if (!mDOMNode) {
+    if (aExtraState) {
+      *aExtraState = nsIAccessibleStates::EXT_STATE_DEFUNCT;
+    }
+    return NS_OK;
+  }
 
-  *aState = 0;
   if (aExtraState)
     *aExtraState = 0;
 
   PRBool isOpen = PR_FALSE;
   nsresult rv = sXFormsService->IsDropmarkerOpen(mDOMNode, &isOpen);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (isOpen)
@@ -151,16 +157,18 @@ nsXFormsComboboxPopupWidgetAccessible::G
 NS_IMETHODIMP
 nsXFormsComboboxPopupWidgetAccessible::GetState(PRUint32 *aState,
                                                 PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
 
   nsresult rv = nsXFormsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   PRBool isOpen = PR_FALSE;
   rv = sXFormsService->IsDropmarkerOpen(mDOMNode, &isOpen);
   NS_ENSURE_SUCCESS(rv, rv);
 
   *aState |= nsIAccessibleStates::STATE_FOCUSABLE;
 
   if (isOpen)
--- a/accessible/src/xul/nsXULAlertAccessible.cpp
+++ b/accessible/src/xul/nsXULAlertAccessible.cpp
@@ -53,14 +53,14 @@ NS_IMETHODIMP nsXULAlertAccessible::GetR
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULAlertAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
-  *aState |= nsIAccessibleStates::STATE_ALERT_MEDIUM; // XUL has no markup for low, medium or high
+  if (mDOMNode) {
+    *aState |= nsIAccessibleStates::STATE_ALERT_MEDIUM; // XUL has no markup for low, medium or high
+  }
   return NS_OK;
 }
 
--- a/accessible/src/xul/nsXULColorPickerAccessible.cpp
+++ b/accessible/src/xul/nsXULColorPickerAccessible.cpp
@@ -66,16 +66,18 @@ NS_IMETHODIMP nsXULColorPickerTileAccess
   * Possible states: focused, focusable, selected
   */
 NS_IMETHODIMP
 nsXULColorPickerTileAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // get focus and disable status from base class
   nsresult rv = nsFormControlAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   *aState |= nsIAccessibleStates::STATE_FOCUSABLE;
 
   // Focused?
   nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
   NS_ASSERTION(element, "No XUL Element for colorpicker");
   PRBool isFocused = PR_FALSE;
   element->HasAttribute(NS_LITERAL_STRING("hover"), &isFocused);
@@ -121,16 +123,18 @@ nsXULColorPickerTileAccessible(aNode, aS
   * Possible states: focused, focusable, unavailable(disabled)
   */
 NS_IMETHODIMP
 nsXULColorPickerAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // get focus and disable status from base class
   nsresult rv = nsFormControlAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   *aState |= nsIAccessibleStates::STATE_FOCUSABLE |
              nsIAccessibleStates::STATE_HASPOPUP;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsXULColorPickerAccessible::GetRole(PRUint32 *_retval)
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -115,16 +115,18 @@ NS_IMETHODIMP nsXULButtonAccessible::Get
   * Possible states: focused, focusable, unavailable(disabled)
   */
 NS_IMETHODIMP
 nsXULButtonAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // get focus and disable status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   PRBool disabled = PR_FALSE;
   nsCOMPtr<nsIDOMXULControlElement> xulFormElement(do_QueryInterface(mDOMNode));
   if (xulFormElement) {
     xulFormElement->GetDisabled(&disabled);
     if (disabled)
       *aState |= nsIAccessibleStates::STATE_UNAVAILABLE;
     else 
@@ -288,16 +290,22 @@ NS_IMETHODIMP nsXULDropmarkerAccessible:
   *aResult = nsIAccessibleRole::ROLE_PUSHBUTTON;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULDropmarkerAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   *aState = 0;
+  if (!mDOMNode) {
+    if (aExtraState) {
+      *aExtraState = nsIAccessibleStates::EXT_STATE_DEFUNCT;
+    }
+    return NS_OK;
+  }
   if (aExtraState)
     *aExtraState = 0;
 
   if (DropmarkerOpen(PR_FALSE))
     *aState = nsIAccessibleStates::STATE_PRESSED;
 
   return NS_OK;
 }
@@ -367,16 +375,18 @@ NS_IMETHODIMP nsXULCheckboxAccessible::D
   * Possible states: focused, focusable, unavailable(disabled), checked
   */
 NS_IMETHODIMP
 nsXULCheckboxAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus and disable status from base class
   nsresult rv = nsFormControlAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
   
   *aState |= nsIAccessibleStates::STATE_CHECKABLE;
   
   // Determine Checked state
   nsCOMPtr<nsIDOMXULCheckboxElement> xulCheckboxElement(do_QueryInterface(mDOMNode));
   if (xulCheckboxElement) {
     PRBool checked = PR_FALSE;
     xulCheckboxElement->GetChecked(&checked);
@@ -468,26 +478,16 @@ nsFormControlAccessible(aNode, aShell)
 }
 
 NS_IMETHODIMP nsXULProgressMeterAccessible::GetRole(PRUint32 *_retval)
 {
   *_retval = nsIAccessibleRole::ROLE_PROGRESSBAR;
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
-{
-  nsresult rv = nsAccessible::GetState(aState, aExtraState);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE; // Progress meters are not focusable
-  return NS_OK;
-}
-
 NS_IMETHODIMP nsXULProgressMeterAccessible::GetValue(nsAString& aValue)
 {
   aValue.Truncate();
   nsAccessible::GetValue(aValue);
   if (!aValue.IsEmpty()) {
     return NS_OK;
   }
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
@@ -552,16 +552,18 @@ nsRadioButtonAccessible(aNode, aShell)
 }
 
 /** We are Focusable and can be Checked and focused */
 NS_IMETHODIMP
 nsXULRadioButtonAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsFormControlAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode)
+    return NS_OK;
 
   *aState |= nsIAccessibleStates::STATE_CHECKABLE;
   
   PRBool selected = PR_FALSE;   // Radio buttons can be selected
 
   nsCOMPtr<nsIDOMXULSelectControlItemElement> radioButton(do_QueryInterface(mDOMNode));
   if (radioButton) {
     radioButton->GetSelected(&selected);
@@ -611,19 +613,20 @@ NS_IMETHODIMP nsXULRadioGroupAccessible:
 NS_IMETHODIMP
 nsXULRadioGroupAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // The radio group is not focusable.
   // Sometimes the focus controller will report that it is focused.
   // That means that the actual selected radio button should be considered focused
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= ~(nsIAccessibleStates::STATE_FOCUSABLE |
-               nsIAccessibleStates::STATE_FOCUSED);
+  if (mDOMNode) {
+    *aState &= ~(nsIAccessibleStates::STATE_FOCUSABLE |
+                 nsIAccessibleStates::STATE_FOCUSED);
+  }
 
   return NS_OK;
 }
 /**
   * XUL StatusBar: can contain arbitrary HTML content
   */
 
 /**
@@ -714,26 +717,16 @@ nsAccessibleWrap(aNode, aShell)
 }
 
 NS_IMETHODIMP nsXULToolbarAccessible::GetRole(PRUint32 *_retval)
 {
   *_retval = nsIAccessibleRole::ROLE_TOOLBAR;
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsXULToolbarAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
-{
-  nsresult rv = nsAccessible::GetState(aState, aExtraState);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;  // toolbar is not focusable
-  return NS_OK;
-}
-
 /**
   * XUL Toolbar Separator
   */
 
 nsXULToolbarSeparatorAccessible::nsXULToolbarSeparatorAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell):
 nsLeafAccessible(aNode, aShell)
 { 
 }
@@ -744,31 +737,33 @@ NS_IMETHODIMP nsXULToolbarSeparatorAcces
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULToolbarSeparatorAccessible::GetState(PRUint32 *aState,
                                           PRUint32 *aExtraState)
 {
   *aState = 0;  // no special state flags for toolbar separator
-  if (aExtraState)
-    *aExtraState = 0;
-
+  if (aExtraState) {
+    *aExtraState = mDOMNode ? 0 : nsIAccessibleStates::EXT_STATE_DEFUNCT;
+  }
   return NS_OK;
 }
 
 /**
   * XUL Textfield
   */
 
 nsXULTextFieldAccessible::nsXULTextFieldAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell) :
  nsHyperTextAccessibleWrap(aNode, aShell)
 {
 }
 
+NS_IMPL_ISUPPORTS_INHERITED3(nsXULTextFieldAccessible, nsAccessible, nsHyperTextAccessible, nsIAccessibleText, nsIAccessibleEditableText)
+
 NS_IMETHODIMP nsXULTextFieldAccessible::GetValue(nsAString& aValue)
 {
   PRUint32 state;
   GetState(&state, nsnull);
   if (state & nsIAccessibleStates::STATE_PROTECTED)    // Don't return password text!
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMXULTextBoxElement> textBox(do_QueryInterface(mDOMNode));
--- a/accessible/src/xul/nsXULFormControlAccessible.h
+++ b/accessible/src/xul/nsXULFormControlAccessible.h
@@ -99,17 +99,16 @@ public:
 class nsXULProgressMeterAccessible : public nsFormControlAccessible
 {
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLEVALUE
 
 public:
   nsXULProgressMeterAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *aRole); 
-  NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   NS_IMETHOD GetValue(nsAString &aValue);
 };
 
 class nsXULRadioButtonAccessible : public nsRadioButtonAccessible
 {
 
 public:
   nsXULRadioButtonAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
@@ -140,17 +139,16 @@ public:
   static PRBool IsSeparator(nsIAccessible *aAccessible);
 };
 
 class nsXULToolbarAccessible : public nsAccessibleWrap
 {
 public:
   nsXULToolbarAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *_retval); 
-  NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
 };
 
 class nsXULToolbarSeparatorAccessible : public nsLeafAccessible
 {
 public:
   nsXULToolbarSeparatorAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *_retval); 
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
@@ -158,16 +156,18 @@ public:
 
 class nsXULTextFieldAccessible : public nsHyperTextAccessibleWrap
 {
 public:
   enum { eAction_Click = 0 };
 
   nsXULTextFieldAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
 
+  NS_DECL_ISUPPORTS_INHERITED
+
   NS_IMETHOD GetValue(nsAString& aValue);
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   NS_IMETHOD GetRole(PRUint32 *aRole);
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 index);
   NS_IMETHOD GetAllowsAnonChildAccessibles(PRBool *aAllowsAnonChildren);
 
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -270,16 +270,19 @@ NS_IMETHODIMP nsXULMenuitemAccessible::I
   return rv;
 }
 
 NS_IMETHODIMP
 nsXULMenuitemAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
 
   // Focused?
   nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
   if (!element)
     return NS_ERROR_FAILURE;
   PRBool isFocused = PR_FALSE;
   element->HasAttribute(NS_LITERAL_STRING("_moz-menuactive"), &isFocused); 
   if (isFocused)
@@ -313,17 +316,17 @@ nsXULMenuitemAccessible::GetState(PRUint
     nsAutoString checkValue;
     element->GetAttribute(NS_LITERAL_STRING("checked"), checkValue);
     if (checkValue.EqualsLiteral("true")) {
       *aState |= nsIAccessibleStates::STATE_CHECKED;
     }
   }
 
   // Combo box listitem
-  if (Role(this) == nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM) {
+  if (Role(this) == nsIAccessibleRole::ROLE_COMBOBOX_OPTION) {
     // Is selected?
     PRBool isSelected = PR_FALSE;
     nsCOMPtr<nsIDOMXULSelectControlItemElement>
       item(do_QueryInterface(mDOMNode));
     NS_ENSURE_TRUE(item, NS_ERROR_FAILURE);
     item->GetSelected(&isSelected);
 
     // Is collapsed?
@@ -358,17 +361,17 @@ nsXULMenuitemAccessible::GetState(PRUint
         *aState |= grandParentState & nsIAccessibleStates::STATE_OFFSCREEN |
                    grandParentState & nsIAccessibleStates::STATE_INVISIBLE;
         if (aExtraState) {
           *aExtraState |=
             grandParentExtState & nsIAccessibleStates::EXT_STATE_OPAQUE;
         }
       } // isCollapsed
     } // isSelected
-  } // ROLE_COMBOBOX_LISTITEM
+  } // ROLE_COMBOBOX_OPTION
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsXULMenuitemAccessible::GetName(nsAString& _retval)
 {
   nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
   if (!element) {
@@ -456,17 +459,17 @@ nsXULMenuitemAccessible::GetDefaultKeyBi
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsXULMenuitemAccessible::GetRole(PRUint32 *aRole)
 {
   *aRole = nsIAccessibleRole::ROLE_MENUITEM;
   if (mParent && Role(mParent) == nsIAccessibleRole::ROLE_COMBOBOX_LIST) {
-    *aRole = nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM;
+    *aRole = nsIAccessibleRole::ROLE_COMBOBOX_OPTION;
     return NS_OK;
   }
   nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
   if (!element)
     return NS_ERROR_FAILURE;
   nsAutoString menuItemType;
   element->GetAttribute(NS_LITERAL_STRING("type"), menuItemType);
   if (menuItemType.EqualsIgnoreCase("radio"))
@@ -544,16 +547,19 @@ nsXULMenuitemAccessible(aDOMNode, aShell
 }
 
 NS_IMETHODIMP
 nsXULMenuSeparatorAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Isn't focusable, but can be offscreen/invisible -- only copy those states
   nsresult rv = nsXULMenuitemAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
 
   *aState &= (nsIAccessibleStates::STATE_OFFSCREEN | 
               nsIAccessibleStates::STATE_INVISIBLE);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsXULMenuSeparatorAccessible::GetName(nsAString& _retval)
@@ -593,16 +599,19 @@ nsXULMenupopupAccessible::nsXULMenupopup
   mSelectControl = do_QueryInterface(parentNode);
 }
 
 NS_IMETHODIMP
 nsXULMenupopupAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
 
 #ifdef DEBUG_A11Y
   // We are onscreen if our parent is active
   PRBool isActive = PR_FALSE;
 
   nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
   element->HasAttribute(NS_LITERAL_STRING("menuactive"), &isActive);
   if (!isActive) {
@@ -707,16 +716,19 @@ nsXULMenubarAccessible::nsXULMenubarAcce
 { 
 }
 
 NS_IMETHODIMP
 nsXULMenubarAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
 
   // Menu bar iteself is not actually focusable
   *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
   return rv;
 }
 
 
 NS_IMETHODIMP nsXULMenubarAccessible::GetName(nsAString& _retval)
--- a/accessible/src/xul/nsXULSelectAccessible.cpp
+++ b/accessible/src/xul/nsXULSelectAccessible.cpp
@@ -65,21 +65,20 @@ nsXULColumnsAccessible::GetRole(PRUint32
   *aRole = nsIAccessibleRole::ROLE_LIST;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULColumnsAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
-
-  if (aExtraState)
-    *aExtraState = 0;
-
   *aState = nsIAccessibleStates::STATE_READONLY;
+  if (aExtraState) {
+    *aExtraState = mDOMNode ? 0 : nsIAccessibleStates::EXT_STATE_DEFUNCT ;
+  }
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColumnItemAccessible
 
 nsXULColumnItemAccessible::
   nsXULColumnItemAccessible(nsIDOMNode *aDOMNode, nsIWeakReference *aShell) :
@@ -95,21 +94,20 @@ nsXULColumnItemAccessible::GetRole(PRUin
   *aRole = nsIAccessibleRole::ROLE_COLUMNHEADER;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULColumnItemAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
-
-  if (aExtraState)
-    *aExtraState = 0;
-
   *aState = nsIAccessibleStates::STATE_READONLY;
+  if (aExtraState) {
+    *aExtraState = mDOMNode ? 0 : nsIAccessibleStates::EXT_STATE_DEFUNCT ;
+  }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULColumnItemAccessible::GetName(nsAString& aName)
 {
   return GetXULName(aName);
 }
@@ -158,16 +156,19 @@ nsXULSelectableAccessible(aDOMNode, aShe
   *     nsIAccessibleStates::STATE_FOCUSABLE
   */
 NS_IMETHODIMP
 nsXULListboxAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
 
 // see if we are multiple select if so set ourselves as such
   nsCOMPtr<nsIDOMElement> element (do_QueryInterface(mDOMNode));
   if (element) {
     nsAutoString selType;
     element->GetAttribute(NS_LITERAL_STRING("seltype"), selType);
     if (!selType.IsEmpty() && selType.EqualsLiteral("multiple"))
       *aState |= nsIAccessibleStates::STATE_MULTISELECTABLE |
@@ -245,30 +246,39 @@ NS_IMETHODIMP nsXULListitemAccessible::G
 /**
   *
   */
 NS_IMETHODIMP nsXULListitemAccessible::GetRole(PRUint32 *aRole)
 {
   if (mIsCheckbox)
     *aRole = nsIAccessibleRole::ROLE_CHECKBUTTON;
   else
-    *aRole = nsIAccessibleRole::ROLE_LISTITEM;
+    *aRole = nsIAccessibleRole::ROLE_RICH_OPTION;
   return NS_OK;
 }
 
 /**
   *
   */
 NS_IMETHODIMP
 nsXULListitemAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   if (mIsCheckbox) {
-    nsXULMenuitemAccessible::GetState(aState, aExtraState);
+    return nsXULMenuitemAccessible::GetState(aState, aExtraState);
+  }
+
+  *aState = 0;
+  if (!mDOMNode) {
+    if (aExtraState) {
+      *aExtraState = nsIAccessibleStates::EXT_STATE_DEFUNCT;
+    }
     return NS_OK;
   }
+  if (aExtraState)
+    *aExtraState = 0;
 
   *aState = nsIAccessibleStates::STATE_FOCUSABLE |
             nsIAccessibleStates::STATE_SELECTABLE;
   nsCOMPtr<nsIDOMXULSelectControlItemElement> listItem (do_QueryInterface(mDOMNode));
   if (listItem) {
     PRBool isSelected;
     listItem->GetSelected(&isSelected);
     if (isSelected)
@@ -352,16 +362,19 @@ NS_IMETHODIMP nsXULComboboxAccessible::G
   *     STATE_COLLAPSED
   */
 NS_IMETHODIMP
 nsXULComboboxAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
 
   nsCOMPtr<nsIDOMXULMenuListElement> menuList(do_QueryInterface(mDOMNode));
   if (menuList) {
     PRBool isOpen;
     menuList->GetOpen(&isOpen);
     if (isOpen) {
       *aState |= nsIAccessibleStates::STATE_EXPANDED;
     }
--- a/accessible/src/xul/nsXULTabAccessible.cpp
+++ b/accessible/src/xul/nsXULTabAccessible.cpp
@@ -96,16 +96,19 @@ NS_IMETHODIMP nsXULTabAccessible::GetRol
 /**
   * Possible states: focused, focusable, unavailable(disabled), offscreen
   */
 NS_IMETHODIMP
 nsXULTabAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // get focus and disable status from base class
   nsresult rv = nsLeafAccessible::GetState(aState, aExtraState);
+  if (!mDOMNode) {
+    return NS_OK;
+  }
   NS_ENSURE_SUCCESS(rv, rv);
 
   // In the past, tabs have been focusable in classic theme
   // They may be again in the future
   // Check style for -moz-user-focus: normal to see if it's focusable
   *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   nsCOMPtr<nsIPresShell> presShell(do_QueryReferent(mWeakShell));
@@ -124,16 +127,108 @@ nsXULTabAccessible::GetState(PRUint32 *a
   if (tab) {
     PRBool selected = PR_FALSE;
     if (NS_SUCCEEDED(tab->GetSelected(&selected)) && selected)
       *aState |= nsIAccessibleStates::STATE_SELECTED;
   }
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsXULTabAccessible::GetAccessibleRelated(PRUint32 aRelationType,
+                                         nsIAccessible **aRelatedAccessible)
+{
+  NS_ENSURE_ARG_POINTER(aRelatedAccessible);
+  *aRelatedAccessible = nsnull;
+
+  if (!mDOMNode)
+    return NS_ERROR_FAILURE;
+
+  nsresult rv = nsLeafAccessible::GetAccessibleRelated(aRelationType,
+                                                       aRelatedAccessible);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (*aRelatedAccessible ||
+      aRelationType != nsIAccessibleRelation::RELATION_LABEL_FOR)
+    return NS_OK;
+
+  // Expose 'LABEL_FOR' relation on tab accessible for tabpanel accessible.
+  // XXX: It makes sense to require the interface from xul:tab to get linked
+  // tabpanel element.
+  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+
+  // Check whether tab and tabpanel are related by 'linkedPanel' attribute on
+  // xul:tab element.
+  nsAutoString linkedPanelID;
+  content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::linkedPanel,
+                   linkedPanelID);
+
+  if (!linkedPanelID.IsEmpty()) {
+    nsCOMPtr<nsIDOMDocument> document;
+    mDOMNode->GetOwnerDocument(getter_AddRefs(document));
+    NS_ENSURE_TRUE(document, NS_ERROR_FAILURE);
+
+    nsCOMPtr<nsIDOMElement> linkedPanel;
+    document->GetElementById(linkedPanelID, getter_AddRefs(linkedPanel));
+    if (linkedPanel) {
+      nsCOMPtr<nsIDOMNode> linkedPanelNode(do_QueryInterface(linkedPanel));
+      GetAccService()->GetAccessibleInWeakShell(linkedPanelNode, mWeakShell,
+                                                aRelatedAccessible);
+      return NS_OK;
+    }
+  }
+
+  // If there is no 'linkedPanel' attribute on xul:tab element then we
+  // assume tab and tabpanels are related 1 to 1. We follow algorithm from
+  // the setter 'selectedIndex' of tabbox.xml#tabs binding.
+
+  nsCOMPtr<nsIAccessible> tabsAcc = GetParent();
+  NS_ENSURE_TRUE(tabsAcc && Role(tabsAcc) == nsIAccessibleRole::ROLE_PAGETABLIST,
+                 NS_ERROR_FAILURE);
+
+  PRInt32 tabIndex = -1;
+
+  nsCOMPtr<nsIAccessible> childAcc;
+  tabsAcc->GetFirstChild(getter_AddRefs(childAcc));
+  while (childAcc) {
+    if (Role(childAcc) == nsIAccessibleRole::ROLE_PAGETAB)
+      tabIndex++;
+
+    if (childAcc == this)
+      break;
+
+    nsCOMPtr<nsIAccessible> acc;
+    childAcc->GetNextSibling(getter_AddRefs(acc));
+    childAcc.swap(acc);
+  }
+
+  nsCOMPtr<nsIAccessible> tabBoxAcc;
+  tabsAcc->GetParent(getter_AddRefs(tabBoxAcc));
+  NS_ENSURE_TRUE(tabBoxAcc && Role(tabBoxAcc) == nsIAccessibleRole::ROLE_PANE,
+                 NS_ERROR_FAILURE);
+
+  tabBoxAcc->GetFirstChild(getter_AddRefs(childAcc));
+  while (childAcc) {
+    if (Role(childAcc) == nsIAccessibleRole::ROLE_PROPERTYPAGE) {
+      if (tabIndex == 0) {
+        NS_ADDREF(*aRelatedAccessible = childAcc);
+        return NS_OK;
+      }
+
+      tabIndex--;
+    }
+
+    nsCOMPtr<nsIAccessible> acc;
+    childAcc->GetNextSibling(getter_AddRefs(acc));
+    childAcc.swap(acc);
+  }
+
+  return NS_OK;
+}
+
 nsresult
 nsXULTabAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
 {
   NS_ENSURE_ARG_POINTER(aAttributes);
   NS_ENSURE_TRUE(mDOMNode, NS_ERROR_FAILURE);
 
   nsresult rv = nsLeafAccessible::GetAttributesInternal(aAttributes);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -157,27 +252,16 @@ nsAccessibleWrap(aNode, aShell)
 
 /** We are a window*/
 NS_IMETHODIMP nsXULTabBoxAccessible::GetRole(PRUint32 *_retval)
 {
   *_retval = nsIAccessibleRole::ROLE_PANE;
   return NS_OK;
 }
 
-/** Possible states: normal */
-NS_IMETHODIMP
-nsXULTabBoxAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
-{
-  nsresult rv = nsAccessible::GetState(aState, aExtraState);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
-  return NS_OK;
-}
-
 #ifdef NEVER
 /** 2 children, tabs, tabpanels */
 NS_IMETHODIMP nsXULTabBoxAccessible::GetChildCount(PRInt32 *_retval)
 {
   *_retval = 2;
   return NS_OK;
 }
 #endif
@@ -201,27 +285,128 @@ NS_IMETHODIMP nsXULTabsAccessible::GetRo
 
 /** no actions */
 NS_IMETHODIMP nsXULTabsAccessible::GetNumActions(PRUint8 *_retval)
 {
   *_retval = 0;
   return NS_OK;
 }
 
-/** no state -- normal */
-NS_IMETHODIMP
-nsXULTabsAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
-{
-  return nsAccessible::GetState(aState, aExtraState);
-}
-
 /** no value */
 NS_IMETHODIMP nsXULTabsAccessible::GetValue(nsAString& _retval)
 {
   return NS_OK;
 }
 
 /** no name*/
 NS_IMETHODIMP nsXULTabsAccessible::GetName(nsAString& _retval)
 {
   _retval.Truncate();
   return NS_OK;
 }
+
+////////////////////////////////////////////////////////////////////////////////
+// nsXULTabpanelAccessible
+
+nsXULTabpanelAccessible::
+  nsXULTabpanelAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell):
+  nsAccessibleWrap(aNode, aShell)
+{
+}
+
+NS_IMETHODIMP
+nsXULTabpanelAccessible::GetRole(PRUint32 *aRole)
+{
+  NS_ENSURE_ARG_POINTER(aRole);
+
+  *aRole = nsIAccessibleRole::ROLE_PROPERTYPAGE;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsXULTabpanelAccessible::GetAccessibleRelated(PRUint32 aRelationType,
+                                              nsIAccessible **aRelatedAccessible)
+{
+  NS_ENSURE_ARG_POINTER(aRelatedAccessible);
+  *aRelatedAccessible = nsnull;
+
+  if (!mDOMNode)
+    return NS_ERROR_FAILURE;
+
+  nsresult rv = nsAccessibleWrap::GetAccessibleRelated(aRelationType,
+                                                       aRelatedAccessible);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (*aRelatedAccessible ||
+      aRelationType != nsIAccessibleRelation::RELATION_LABELLED_BY)
+    return NS_OK;
+
+  // Expose 'LABELLED_BY' relation on tabpanel accessible for tab accessible.
+  nsCOMPtr<nsIAccessible> tabBoxAcc;
+  GetParent(getter_AddRefs(tabBoxAcc));
+  NS_ENSURE_TRUE(tabBoxAcc && Role(tabBoxAcc) == nsIAccessibleRole::ROLE_PANE,
+                 NS_ERROR_FAILURE);
+
+  PRInt32 tabpanelIndex = -1;
+  nsCOMPtr<nsIAccessible> tabsAcc;
+
+  PRBool isTabpanelFound = PR_FALSE;
+  nsCOMPtr<nsIAccessible> childAcc;
+  tabBoxAcc->GetFirstChild(getter_AddRefs(childAcc));
+  while (childAcc && (!tabsAcc || !isTabpanelFound)) {
+    if (Role(childAcc) == nsIAccessibleRole::ROLE_PAGETABLIST)
+      tabsAcc = childAcc;
+
+    if (!isTabpanelFound &&
+        Role(childAcc) == nsIAccessibleRole::ROLE_PROPERTYPAGE)
+      tabpanelIndex++;
+
+    if (childAcc == this)
+      isTabpanelFound = PR_TRUE;
+
+    nsCOMPtr<nsIAccessible> acc;
+    childAcc->GetNextSibling(getter_AddRefs(acc));
+    childAcc.swap(acc);
+  }
+
+  if (!tabsAcc || tabpanelIndex == -1)
+    return NS_OK;
+
+  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+  nsIAtom *atomID = content->GetID();
+
+  nsCOMPtr<nsIAccessible> foundTabAcc;
+  tabsAcc->GetFirstChild(getter_AddRefs(childAcc));
+  while (childAcc) {
+    if (Role(childAcc) == nsIAccessibleRole::ROLE_PAGETAB) {
+      if (atomID) {
+        nsCOMPtr<nsIAccessNode> tabAccNode(do_QueryInterface(childAcc));
+        nsCOMPtr<nsIDOMNode> tabNode;
+        tabAccNode->GetDOMNode(getter_AddRefs(tabNode));
+        nsCOMPtr<nsIContent> tabContent(do_QueryInterface(tabNode));
+        NS_ENSURE_TRUE(tabContent, NS_ERROR_FAILURE);
+
+        if (tabContent->AttrValueIs(kNameSpaceID_None,
+                                    nsAccessibilityAtoms::linkedPanel, atomID,
+                                    eCaseMatters)) {
+          NS_ADDREF(*aRelatedAccessible = childAcc);
+          return NS_OK;
+        }
+      }
+
+      if (tabpanelIndex == 0) {
+        foundTabAcc = childAcc;
+        if (!atomID)
+          break;
+      }
+
+      tabpanelIndex--;
+    }
+
+    nsCOMPtr<nsIAccessible> acc;
+    childAcc->GetNextSibling(getter_AddRefs(acc));
+    childAcc.swap(acc);
+  }
+
+  NS_IF_ADDREF(*aRelatedAccessible = foundTabAcc);
+  return NS_OK;
+}
+
--- a/accessible/src/xul/nsXULTabAccessible.h
+++ b/accessible/src/xul/nsXULTabAccessible.h
@@ -38,50 +38,75 @@
 
 #ifndef _nsXULTabAccessible_H_
 #define _nsXULTabAccessible_H_
 
 // NOTE: alphabetically ordered
 #include "nsBaseWidgetAccessible.h"
 #include "nsXULSelectAccessible.h"
 
-/** An individual tab */
+/**
+ * An individual tab, xul:tab element
+ */
 class nsXULTabAccessible : public nsLeafAccessible
 {
 public:
   enum { eAction_Switch = 0 };
 
   nsXULTabAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
+
+  // nsIAccessible
   NS_IMETHOD GetRole(PRUint32 *_retval); 
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 index);
+  NS_IMETHOD GetAccessibleRelated(PRUint32 aRelationType,
+                                  nsIAccessible **aRelatedAccessible);
+
+  // nsAccessible
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
 };
 
 /** 
   * Contains a tabs object and a tabPanels object. A complete
   *    entity with relationships between tabs and content to
   *    be displayed in the tabpanels object
   */
 class nsXULTabBoxAccessible : public nsAccessibleWrap
 {
 public:
   nsXULTabBoxAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *_retval); 
-  NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
-  //NS_IMETHOD GetChildCount(PRInt32 *_retval); // aaronl remove this?
 };
 
-/** merely a container of tab obejcts */
+/**
+ * A container of tab obejcts, xul:tabs element.
+ */
 class nsXULTabsAccessible : public nsXULSelectableAccessible
 {
 public:
   nsXULTabsAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
   NS_IMETHOD GetRole(PRUint32 *_retval);
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
-  NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   NS_IMETHOD GetValue(nsAString& _retval);
   NS_IMETHOD GetName(nsAString& _retval);
 };
 
+/**
+ * A tabpanel object, child elements of xul:tabpanels element. Note,the object
+ * is created from nsAccessibilityService::GetAccessibleForDeckChildren()
+ * method and we do not use nsIAccessibleProvider interface here because
+ * all children of xul:tabpanels element acts as xul:tabpanel element.
+ */
+class nsXULTabpanelAccessible : public nsAccessibleWrap
+{
+public:
+  nsXULTabpanelAccessible(nsIDOMNode *aNode, nsIWeakReference *aShell);
+
+  // nsIAccessible
+  NS_IMETHOD GetRole(PRUint32 *aRole);
+  NS_IMETHOD GetAccessibleRelated(PRUint32 aRelationType,
+                                  nsIAccessible **aRelatedAccessible);
+};
+
 #endif
+
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -172,17 +172,19 @@ void nsXULTreeAccessible::GetTreeBoxObje
 }
 
 NS_IMETHODIMP
 nsXULTreeAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // Get focus status from base class
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
-
+  if (!mDOMNode)
+    return NS_OK;
+  
   // see if we are multiple select if so set ourselves as such
   nsCOMPtr<nsIDOMElement> element (do_QueryInterface(mDOMNode));
   if (element) {
     // the default selection type is multiple
     nsAutoString selType;
     element->GetAttribute(NS_LITERAL_STRING("seltype"), selType);
     if (selType.IsEmpty() || !selType.EqualsLiteral("single"))
       *aState |= nsIAccessibleStates::STATE_MULTISELECTABLE;
@@ -595,17 +597,21 @@ NS_IMETHODIMP nsXULTreeitemAccessible::S
   return nsLeafAccessible::Shutdown();
 }
 
 NS_IMETHODIMP nsXULTreeitemAccessible::GetName(nsAString& aName)
 {
   NS_ENSURE_TRUE(mTree && mTreeView, NS_ERROR_FAILURE);
   mTreeView->GetCellText(mRow, mColumn, aName);
   
-  // if still no name try cell value
+  // If there is still no name try the cell value:
+  // This is for graphical cells. We need tree/table view implementors to implement
+  // FooView::GetCellValue to return a meaningful string for cases where there is
+  // something shown in the cell (non-text) such as a star icon; in which case
+  // GetCellValue for that cell would return "starred" or "flagged" for example.
   if (aName.IsEmpty()) {
     mTreeView->GetCellValue(mRow, mColumn, aName);
   }
   
   return NS_OK;
 }
 
 NS_IMETHODIMP nsXULTreeitemAccessible::GetUniqueID(void **aUniqueID)
--- a/browser/app/module.ver
+++ b/browser/app/module.ver
@@ -1,8 +1,8 @@
 WIN32_MODULE_COMPANYNAME=Mozilla Corporation
 WIN32_MODULE_COPYRIGHT=©Firefox and Mozilla Developers, according to the MPL 1.1/GPL 2.0/LGPL 2.1 licenses, as applicable.
 WIN32_MODULE_PRODUCTVERSION=3,0,0,0
-WIN32_MODULE_PRODUCTVERSION_STRING=3.0a9pre
+WIN32_MODULE_PRODUCTVERSION_STRING=3.0b2pre
 WIN32_MODULE_TRADEMARKS=Firefox is a Trademark of The Mozilla Foundation.
 WIN32_MODULE_DESCRIPTION=Firefox
 WIN32_MODULE_PRODUCTNAME=Firefox
 WIN32_MODULE_NAME=Firefox
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -246,16 +246,17 @@ pref("browser.microsummary.updateGenerat
 
 // enable search suggestions by default
 pref("browser.search.suggest.enabled", true);
 
 pref("browser.history.grouping", "day");
 pref("browser.history.showSessions", false);
 pref("browser.sessionhistory.max_entries", 50);
 pref("browser.history_expire_days", 180);
+pref("browser.history_expire_visits", 20000);
 
 // handle external links
 // 0=default window, 1=current window/tab, 2=new window, 3=new tab in most recent window
 pref("browser.link.open_external", 3);
 
 // handle links targeting new windows
 pref("browser.link.open_newwindow", 3);
 
@@ -287,16 +288,20 @@ pref("browser.tabs.closeButtons", 1);
 // true   return to the tab that opened this tab (its owner)
 // false  return to the adjacent tab (old default)
 pref("browser.tabs.selectOwnerOnClose", true);
 
 // Default bookmark sorting
 pref("browser.bookmarks.sort.direction", "descending");
 pref("browser.bookmarks.sort.resource", "rdf:http://home.netscape.com/NC-rdf#Name");
 
+// By default, do not overwrite bookmarks.html in the profile directory
+// See bug #381216 for details
+pref("browser.bookmarks.overwrite",               false);
+
 // Scripts & Windows prefs
 pref("dom.disable_open_during_load",              true);
 #ifdef DEBUG
 pref("javascript.options.showInConsole",          true);
 pref("general.warnOnAboutConfig",                 false);
 #else
 pref("javascript.options.showInConsole",          false);
 #endif
--- a/browser/base/content/browser-context.inc
+++ b/browser/base/content/browser-context.inc
@@ -221,17 +221,17 @@
       <menuitem id="context-viewpartialsource-mathml"
                 label="&viewPartialSourceForMathMLCmd.label;"
                 accesskey="&viewPartialSourceCmd.accesskey;"
                 oncommand="gContextMenu.viewPartialSource('mathml');"
                 observes="isImage"/>
       <menuitem id="context-viewsource"
                 label="&viewPageSourceCmd.label;"
                 accesskey="&viewPageSourceCmd.accesskey;"
-                oncommand="BrowserViewSourceOfDocument(content.document);"
+                oncommand="BrowserViewSourceOfDocument(gContextMenu.browser.contentDocument);"
                 observes="isImage"/>
       <menuitem id="context-viewinfo"
                 label="&viewPageInfoCmd.label;"
                 accesskey="&viewPageInfoCmd.accesskey;"
                 oncommand="gContextMenu.viewInfo();"/>
       <menuitem id="context-metadata"
                 label="&metadataCmd.label;"
                 accesskey="&metadataCmd.accesskey;"
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -47,16 +47,19 @@ var PlacesCommandHook = {
 
     throw Cr.NS_NOINTERFACE;
   },
 
   // Edit-bookmark panel
   get panel() {
     delete this.panel;
     var element = document.getElementById("editBookmarkPanel");
+    // initially the panel is hidden
+    // to avoid impacting startup / new window performance
+    element.hidden = false;
     element.addEventListener("popuphiding", this, false);
     element.addEventListener("keypress", this, true);
     return this.panel = element;
   },
 
   // list of command elements (by id) to disable when the panel is opened
   _blockedCommands: ["cmd_close", "cmd_closeWindow"],
 
@@ -159,23 +162,18 @@ var PlacesCommandHook = {
    *
    * @param aBrowser
    *        a <browser> element.
    * @param [optional] aParent
    *        The folder in which to create a new bookmark if the page loaded in
    *        aBrowser isn't bookmarked yet, defaults to the unfiled root.
    * @param [optional] aShowEditUI
    *        whether or not to show the edit-bookmark UI for the bookmark item
-   * @param [optional] aAnchorElement
-   *        required if aShowEditUI is set, see popup's openPopup.
-   * @param [optional] aPosition
-   *        required if aShowEditUI is set, see popup's openPopup.
    */  
-  bookmarkPage: function PCH_bookmarkPage(aBrowser, aParent, aShowEditUI,
-                                          aAnchorElement, aPosition) {
+  bookmarkPage: function PCH_bookmarkPage(aBrowser, aParent, aShowEditUI) {
     var uri = aBrowser.currentURI;
     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     if (itemId == -1) {
       // Copied over from addBookmarkForBrowser:
       // Bug 52536: We obtain the URL and title from the nsIWebNavigation
       // associated with a <browser/> rather than from a DOMWindow.
       // This is because when a full page plugin is loaded, there is
       // no DOMWindow (?) but information about the loaded document
@@ -194,35 +192,35 @@ var PlacesCommandHook = {
       var descAnno = { name: DESCRIPTION_ANNO, value: description };
       var txn = PlacesUtils.ptm.createItem(uri, parent, -1,
                                            title, null, [descAnno]);
       PlacesUtils.ptm.commitTransaction(txn);
       if (aShowEditUI)
         itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     }
 
-    if (aShowEditUI)
-      this.showEditBookmarkPopup(itemId, aAnchorElement, aPosition);
+    if (aShowEditUI) {
+      // dock the panel to the star icon when possible, otherwise dock
+      // it to the content area
+      if (aBrowser.contentWindow == window.content) {
+        var starIcon = aBrowser.ownerDocument.getElementById("star-button");
+        if (starIcon && isElementVisible(starIcon)) {
+          this.showEditBookmarkPopup(itemId, starIcon, "after_start");
+          return;
+        }
+      }
+      this.showEditBookmarkPopup(itemId, aBrowser, "overlap");
+    }
   },
 
   /**
    * Adds a bookmark to the page loaded in the current tab. 
    */
   bookmarkCurrentPage: function PCH_bookmarkCurrentPage(aShowEditUI, aParent) {
-    // dock the panel to the star icon if it is visible, otherwise dock
-    // it to the content area
-    var starIcon = document.getElementById("star-button");
-    if (starIcon && isElementVisible(starIcon)) {
-      this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI,
-                        starIcon, "after_start");
-    }
-    else {
-      this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI,
-                        getBrowser(), "overlap");
-    }
+    this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI);
   },
 
   /**
    * Adds a bookmark to the page targeted by a link.
    * @param aParent
    *        The folder in which to create a new bookmark if aURL isn't
    *        bookmarked.
    * @param aURL (string)
@@ -234,17 +232,17 @@ var PlacesCommandHook = {
     var linkURI = IO.newURI(aURL)
     var itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
     if (itemId == -1) {
       var txn = PlacesUtils.ptm.createItem(linkURI, aParent, -1, aTitle);
       PlacesUtils.ptm.commitTransaction(txn);
       itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
     }
 
-    PlacesCommandHook.showEditBookmarkPopup(itemId, getBrowser(), "overlap");
+    this.showEditBookmarkPopup(itemId, getBrowser(), "overlap");
   },
 
   /**
    * This function returns a list of nsIURI objects characterizing the
    * tabs currently open in the browser.  The URIs will appear in the
    * list in the order in which their corresponding tabs appeared.  However,
    * only the first instance of each URI will be returned.
    *
--- a/browser/base/content/browser-textZoom.js
+++ b/browser/base/content/browser-textZoom.js
@@ -227,16 +227,21 @@ var FullZoom = {
     if (typeof this.globalValue != "undefined")
       ZoomManager.fullZoom = this.globalValue;
     else
       ZoomManager.reset();
 
     this._removePref();
   },
 
+  setSettingValue: function () {
+    var value = this._cps.getPref(gBrowser.currentURI, this.name);
+    this._applyPrefToSetting(value);
+  },
+
   /**
    * Set the zoom level for the current tab.
    *
    * Per DocumentViewerImpl::SetFullZoom in nsDocumentViewer.cpp, it looks
    * like we can set the zoom to its current value without significant impact
    * on performance, as the setting is only applied if it differs from the
    * current setting.
    *
@@ -245,30 +250,36 @@ var FullZoom = {
    * may have a different zoom under unusual circumstances, and it implies
    * that those child zooms should get updated when the parent zoom gets set.
    *
    * So when we apply new zoom values to the browser, we simply set the zoom.
    * We don't check first to see if the new value is the same as the current
    * one.
    **/
   _applyPrefToSetting: function (aValue) {
+    if (gInPrintPreviewMode)
+      return;
+
     // Bug 375918 means this will sometimes throw, so we catch it
     // and don't do anything in those cases.
     try {
       if (typeof aValue != "undefined")
         ZoomManager.fullZoom = this._ensureValid(aValue);
       else if (typeof this.globalValue != "undefined")
         ZoomManager.fullZoom = this.globalValue;
       else
         ZoomManager.reset();
     }
     catch(ex) {}
   },
 
   _applySettingToPref: function () {
+    if (gInPrintPreviewMode)
+      return;
+
     var fullZoom = ZoomManager.fullZoom;
     this._cps.setPref(gBrowser.currentURI, this.name, fullZoom);
   },
 
   _removePref: function () {
     this._cps.removePref(gBrowser.currentURI, this.name);
   },
 
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -19,16 +19,20 @@ toolbar[printpreview="true"] {
 menuitem.spell-suggestion {
   font-weight: bold;
 }
 
 #sidebar-box toolbarbutton.tabs-closebutton {
   -moz-user-focus: normal;
 }
 
+.verifiedDomain > #identity-icon-label {
+  display: none;
+}
+
 /* apply Fitts' law to the notification bar's close button */
 window[sizemode="maximized"] #content .notification-inner {
   border-right: 0px !important;
 }
 
 tabbrowser {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser");
 }
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -93,16 +93,17 @@ var gLastValidURLStr = "";
 var gMustLoadSidebar = false;
 var gProgressMeterPanel = null;
 var gProgressCollapseTimer = null;
 var gPrefService = null;
 var appCore = null;
 var gBrowser = null;
 var gNavToolbox = null;
 var gSidebarCommand = "";
+var gInPrintPreviewMode = false;
 
 // Global variable that holds the nsContextMenu instance.
 var gContextMenu = null;
 
 var gChromeState = null; // chrome state before we went into print preview
 
 var gSanitizeListener = null;
 
@@ -258,18 +259,17 @@ function SetClickAndHoldHandlers()
 
 function BookmarkThisTab()
 {
   var tab = getBrowser().mContextTab;
   if (tab.localName != "tab")
     tab = getBrowser().mCurrentTab;
 
   PlacesCommandHook.bookmarkPage(tab.linkedBrowser,
-                                 PlacesUtils.bookmarksRootId,
-                                 true, getBrowser(), "overlap");
+                                 PlacesUtils.bookmarksRootId, true);
 }
 
 /**
  * Global bookmarks observer for browser-window specific stuff
  */
 var gBookmarksObserver = {
   QueryInterface: function G_BO_QueryInterface(aIID) {
     if (aIID.equals(Ci.nsINavBookmarkObserver) ||
@@ -1067,16 +1067,18 @@ function delayedStartup()
   Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
 
   if (gMustLoadSidebar) {
     var sidebar = document.getElementById("sidebar");
     var sidebarBox = document.getElementById("sidebar-box");
     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
   }
 
+  UpdateUrlbarSearchSplitterState();
+
   initPlacesDefaultQueries();
   initBookmarksToolbar();
   PlacesUtils.bookmarks.addObserver(gBookmarksObserver, false);
   PlacesStarButton.init();
 
   // called when we go into full screen, even if it is
   // initiated by a web page script
   window.addEventListener("fullscreen", onFullScreen, true);
@@ -1199,16 +1201,22 @@ function delayedStartup()
       ss.init(window);
     } catch(ex) {
       dump("nsSessionStore could not be initialized: " + ex + "\n");
     }
   }
 
   // bookmark-all-tabs command
   gBookmarkAllTabsHandler = new BookmarkAllTabsHandler();
+
+  // Attach a listener to watch for "command" events bubbling up from error
+  // pages.  This lets us fix bugs like 401575 which require error page UI to
+  // do privileged things, without letting error pages have any privilege
+  // themselves.
+  gBrowser.addEventListener("command", BrowserOnCommand, false);
 }
 
 function BrowserShutdown()
 {
   try {
     FullZoom.destroy();
     ContentPrefSink.destroy();
   }
@@ -1951,21 +1959,22 @@ function BrowserViewSourceOfDocument(aDo
     // If no page descriptor is available, just use the view-source URL...
   }
 
   ViewSourceOfURL(webNav.currentURI.spec, pageCookie, aDocument);
 }
 
 function ViewSourceOfURL(aURL, aPageDescriptor, aDocument)
 {
+  var utils = window.top.gViewSourceUtils;
   if (getBoolPref("view_source.editor.external", false)) {
-    gViewSourceUtils.openInExternalEditor(aURL, aPageDescriptor, aDocument);
+    utils.openInExternalEditor(aURL, aPageDescriptor, aDocument);
   }
   else {
-    gViewSourceUtils.openInInternalViewer(aURL, aPageDescriptor, aDocument);
+    utils.openInInternalViewer(aURL, aPageDescriptor, aDocument);
   }
 }
 
 // doc - document to use for source, or null for this window's document
 // initialTab - name of the initial tab to display, or null for the first tab
 function BrowserPageInfo(doc, initialTab)
 {
   var args = {doc: doc, initialTab: initialTab};
@@ -2149,16 +2158,42 @@ function canonizeUrl(aTriggeringEvent, a
   }
 
   gURLBar.value = getShortcutOrURI(url, aPostDataRef);
 
   // Also update this so the browser display keeps the new value (bug 310651)
   gBrowser.userTypedValue = gURLBar.value;
 }
 
+function UpdateUrlbarSearchSplitterState()
+{
+  var splitter = document.getElementById("urlbar-search-splitter");
+
+  var urlbar = document.getElementById("urlbar-container");
+  var searchbar = document.getElementById("search-container");
+  var ibefore = null;
+  if (urlbar.nextSibling == searchbar)
+    ibefore = searchbar;
+  else if (searchbar.nextSibling == urlbar)
+    ibefore = urlbar;
+  else if (splitter)
+    splitter.parentNode.removeChild(splitter);
+
+  if (ibefore) {
+    if (!splitter) {
+      splitter = document.createElement("splitter");
+      splitter.id = "urlbar-search-splitter";
+      splitter.setAttribute("resizebefore", "flex");
+      splitter.setAttribute("resizeafter", "flex");
+      splitter.className = "chromeclass-toolbar-additional";
+    }
+    urlbar.parentNode.insertBefore(splitter, ibefore);
+  }
+}
+
 function UpdatePageProxyState()
 {
   if (gURLBar && gURLBar.value != gLastValidURLStr)
     SetPageProxyState("invalid");
 }
 
 function SetPageProxyState(aState)
 {
@@ -2214,26 +2249,18 @@ function PageProxyDragGesture(aEvent)
     nsDragAndDrop.startDrag(aEvent, proxyIconDNDObserver);
     return true;
   }
   return false;
 }
 
 function PageProxyClickHandler(aEvent)
 {
-  switch (aEvent.button) {
-    case 0:
-      gURLBar.select();
-      break;
-    case 1:
-      if (gPrefService.getBoolPref("middlemouse.paste"))
-        middleMousePaste(aEvent);
-      break;
-  }
-  return true;
+  if (aEvent.button == 1 && gPrefService.getBoolPref("middlemouse.paste"))
+    middleMousePaste(aEvent);
 }
 
 function URLBarOnInput(evt)
 {
   gBrowser.userTypedValue = gURLBar.value;
   
   // If the user is interacting with the url bar, get rid of the identity popup
   var ih = getIdentityHandler();
@@ -2274,19 +2301,22 @@ var urlbarObserver = {
           handleURLBarCommand();
         } catch (ex) {}
       }
     },
   getSupportedFlavours: function ()
     {
       var flavourSet = new FlavourSet();
 
-      // Plain text drops are often misidentified as "text/x-moz-url", so favor plain text.
+      // Favor text/x-moz-url since text/unicode coming from Win32 1.8 branch
+      // drops contains URL\ntext.  The previous comment here said that
+      // plain text drops often come with text/x-moz-url flavor, but I
+      // haven't seen that, so hopefully that behavior has changed.
+      flavourSet.appendFlavour("text/x-moz-url");
       flavourSet.appendFlavour("text/unicode");
-      flavourSet.appendFlavour("text/x-moz-url");
       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
       return flavourSet;
     }
 }
 
 function BrowserImport()
 {
 #ifdef XP_MACOSX
@@ -2300,16 +2330,60 @@ function BrowserImport()
                       "migration", "centerscreen,chrome,resizable=no");
   }
 #else
   window.openDialog("chrome://browser/content/migration/migration.xul",
                     "migration", "modal,centerscreen,chrome,resizable=no");
 #endif
 }
 
+/**
+ * Handle command events bubbling up from error page content
+ */
+function BrowserOnCommand(event) {
+    
+    // Don't trust synthetic events
+    if (!event.isTrusted)
+      return;
+    
+    // If the event came from an ssl error page, it is probably either the "Add
+    // Exception…" or "Get me out of here!" button
+    if (/^about:neterror\?e=nssBadCert/.test(event.originalTarget.ownerDocument.documentURI)) {
+      var ot = event.originalTarget;
+      var errorDoc = ot.ownerDocument;
+      
+      if (ot == errorDoc.getElementById('exceptionDialogButton')) {
+        var params = { location : content.location.href,
+                       exceptionAdded : false };
+        window.openDialog('chrome://pippki/content/exceptionDialog.xul',
+                          '','chrome,centerscreen,modal', params);
+        
+        // If the user added the exception cert, attempt to reload the page
+        if (params.exceptionAdded)
+          content.location.reload();
+      }
+      else if (ot == errorDoc.getElementById('getMeOutOfHereButton')) {
+        // Redirect them to a known-functioning page, default start page
+        var prefs = Cc["@mozilla.org/preferences-service;1"]
+                    .getService(Ci.nsIPrefService).getDefaultBranch(null);
+        var url = "about:blank";
+        try {
+          url = prefs.getComplexValue("browser.startup.homepage",
+                                      Ci.nsIPrefLocalizedString).data;
+          // If url is a pipe-delimited set of pages, just take the first one.
+          if (url.indexOf("|") != -1)
+            url = url.split("|")[0];
+        } catch(e) {
+          Components.utils.reportError("Couldn't get homepage pref: " + e);
+        }
+        content.location = url;
+      }
+    }
+  }
+
 function BrowserFullScreen()
 {
   window.fullScreen = !window.fullScreen;
 }
 
 function onFullScreen()
 {
   FullScreen.toggle();
@@ -2399,22 +2473,25 @@ function toggleAffectedChrome(aHide)
   }
 
   if (gChromeState.sidebarOpen)
     toggleSidebar(gSidebarCommand);
 }
 
 function onEnterPrintPreview()
 {
+  gInPrintPreviewMode = true;
   toggleAffectedChrome(true);
 }
 
 function onExitPrintPreview()
 {
   // restore chrome to original state
+  gInPrintPreviewMode = false;
+  FullZoom.setSettingValue();
   toggleAffectedChrome(false);
 }
 
 function getPPBrowser()
 {
   return getBrowser();
 }
 
@@ -3159,16 +3236,20 @@ function BrowserCustomizeToolbar()
   // Disable the toolbar context menu items
   var menubar = document.getElementById("main-menubar");
   for (var i = 0; i < menubar.childNodes.length; ++i)
     menubar.childNodes[i].setAttribute("disabled", true);
 
   var cmd = document.getElementById("cmd_CustomizeToolbars");
   cmd.setAttribute("disabled", "true");
 
+  var splitter = document.getElementById("urlbar-search-splitter");
+  if (splitter)
+    splitter.parentNode.removeChild(splitter);
+
 #ifdef TOOLBAR_CUSTOMIZATION_SHEET
   var sheetFrame = document.getElementById("customizeToolbarSheetIFrame");
   sheetFrame.hidden = false;
   // XXXmano: there's apparently no better way to get this when the iframe is
   // hidden
   var sheetWidth = sheetFrame.style.width.match(/([0-9]+)px/)[1];
   document.getElementById("customizeToolbarSheetPopup")
           .openPopup(getNavToolbox(), "after_start", (window.innerWidth - sheetWidth) / 2, 0);
@@ -3192,16 +3273,18 @@ function BrowserToolboxCustomizeDone(aTo
     gURLBar = document.getElementById("urlbar");
     gProxyButton = document.getElementById("page-proxy-button");
     gProxyFavIcon = document.getElementById("page-proxy-favicon");
     gProxyDeck = document.getElementById("page-proxy-deck");
     gHomeButton.updateTooltip();
     window.XULBrowserWindow.init();
   }
 
+  UpdateUrlbarSearchSplitterState();
+
   // Update the urlbar
   var url = getWebNavigation().currentURI.spec;
   if (gURLBar) {
     gURLBar.value = url == "about:blank" ? "" : url;
     SetPageProxyState("valid");
     XULBrowserWindow.asyncUpdateUI();
     PlacesStarButton.updateState();
   }
@@ -5809,16 +5892,18 @@ IdentityHandler.prototype = {
     this._identityPopupContentSupp.textContent = supplemental;
     this._identityPopupContentVerif.textContent = verifier;
   },
   
   /**
    * Click handler for the identity-box element in primary chrome.  
    */
   handleIdentityClick : function(event) {
+    event.stopPropagation();
+
     if (event.button != 0)
       return; // We only want left-clicks
         
     // Make sure that the display:none style we set in xul is removed now that
     // the popup is actually needed
     this._identityPopup.hidden = false;
     
     // Tell the popup to consume dismiss clicks, to avoid bug 395314
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -94,19 +94,19 @@
            onclick="checkForMiddleClick(this, event);"/>
     <popup id="forwardMenu"
            position="after_start"
            onpopupshowing="return BrowserForwardMenu(event);"
            oncommand="gotoHistoryIndex(event);"
            onclick="checkForMiddleClick(this, event);"/>
     <tooltip id="aHTMLTooltip" onpopupshowing="return FillInHTMLTooltip(document.tooltipNode);"/>
 
-    <panel type="autocomplete" chromedir="&locale.dir;" id="PopupAutoComplete" noautofocus="true"/>
+    <panel type="autocomplete" chromedir="&locale.dir;" id="PopupAutoComplete" noautofocus="true" hidden="true"/>
 
-    <panel id="editBookmarkPanel" orient="vertical">
+    <panel id="editBookmarkPanel" orient="vertical" hidden="true">
       <vbox id="editBookmarkPanelContent" flex="1"/>
       <hbox flex="1">
         <spacer flex="1"/>
         <button id="editBookmarkPanelDeleteButton"
                 label="&editBookmark.delete.label;"
                 oncommand="PlacesCommandHook.deleteButtonOnCommand();"/>
         <button id="editBookmarkPanelDoneButton"
                 label="&editBookmark.done.label;"
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -1135,23 +1135,22 @@ nsContextMenu.prototype = {
 
     var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
     var where = newWindowPref == 3 ? "tab" : "window";
 
     openUILinkIn(uri, where);
   },
 
   bookmarkThisPage: function CM_bookmarkThisPage() {
-    PlacesCommandHook.bookmarkPage(this.browser, PlacesUtils.bookmarksRootId,
-                                   true, this.browser, "overlap");
+    window.top.PlacesCommandHook.bookmarkPage(this.browser, PlacesUtils.bookmarksRootId, true);
   },
 
   bookmarkLink: function CM_bookmarkLink() {
-    PlacesCommandHook.bookmarkLink(PlacesUtils.bookmarksRootId, this.linkURL,
-                                   this.linkText());
+    window.top.PlacesCommandHook.bookmarkLink(PlacesUtils.bookmarksRootId, this.linkURL,
+                                              this.linkText());
   },
 
   addBookmarkForFrame: function CM_addBookmarkForFrame() {
     var doc = this.target.ownerDocument;
     var uri = doc.documentURIObject;
 
     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     if (itemId == -1) {
@@ -1160,17 +1159,17 @@ nsContextMenu.prototype = {
 
       var descAnno = { name: DESCRIPTION_ANNO, value: description };
       var txn = PlacesUtils.ptm.createItem(uri, PlacesUtils.bookmarksRootId, -1,
                                            title, null, [descAnno]);
       PlacesUtils.ptm.commitTransaction(txn);
       itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     }
 
-    PlacesCommandHook.showEditBookmarkPopup(itemId, this.browser, "overlap");
+    window.top.PlacesCommandHook.showEditBookmarkPopup(itemId, this.browser, "overlap");
   },
 
   savePageAs: function CM_savePageAs() {
     saveDocument(this.browser.contentDocument);
   },
 
   sendPage: function CM_sendPage() {
     MailIntegration.sendLinkForWindow(this.browser.contentWindow);  
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -277,17 +277,16 @@ var onUnloadRegistry = [ ];
  */
 function onLoadPageInfo()
 {
   gBundle = document.getElementById("pageinfobundle");
   gStrings.unknown = gBundle.getString("unknown");
   gStrings.notSet = gBundle.getString("notset");
   gStrings.mediaImg = gBundle.getString("mediaImg");
   gStrings.mediaBGImg = gBundle.getString("mediaBGImg");
-  gStrings.mediaApplet = gBundle.getString("mediaApplet");
   gStrings.mediaObject = gBundle.getString("mediaObject");
   gStrings.mediaEmbed = gBundle.getString("mediaEmbed");
   gStrings.mediaLink = gBundle.getString("mediaLink");
   gStrings.mediaInput = gBundle.getString("mediaInput");
 
   if ("arguments" in window && window.arguments.length >= 1 &&
        window.arguments[0] && window.arguments[0].doc) {
     gDocument = window.arguments[0].doc;
@@ -434,16 +433,19 @@ function makeGeneralTab()
   document.getElementById("titletext").value = title;
 
   var url = gDocument.location.toString();
   setItemValue("urltext", url);
 
   var referrer = ("referrer" in gDocument && gDocument.referrer);
   setItemValue("refertext", referrer);
 
+  var mode = ("compatMode" in gDocument && gDocument.compatMode == "BackCompat") ? "generalQuirksMode" : "generalStrictMode";
+  document.getElementById("modetext").value = gBundle.getString(mode);
+
   // find out the mime type
   var mimeType = gDocument.contentType;
   setItemValue("typetext", mimeType);
 
   // get the document characterset
   var encoding = gDocument.characterSet;
   document.getElementById("encodingtext").value = encoding;
 
@@ -611,24 +613,16 @@ function grabAll(elem)
     if (elem.rel && /\bicon\b/i.test(elem.rel))
       addImage(elem.href, gStrings.mediaLink, "", elem, false);
   }
   else if (elem instanceof HTMLInputElement || elem instanceof HTMLButtonElement) {
     if (elem.type.toLowerCase() == "image")
       addImage(elem.src, gStrings.mediaInput,
                (elem.hasAttribute("alt")) ? elem.alt : gStrings.notSet, elem, false);
   }
-  else if (elem instanceof HTMLAppletElement) {
-    //XXX When Java is enabled, the DOM model for <APPLET> is broken. Bug #59686.
-    // Also, some reports of a crash with Java in Media tab (bug 136535), and mixed
-    // content from two hosts (bug 136539) so just drop applets from Page Info when
-    // Java is on. For the 1.0.1 branch; get a real fix on the trunk.
-    if (!navigator.javaEnabled())
-      addImage(elem.code || elem.object, gStrings.mediaApplet, "", elem, false);
-  }
   else if (elem instanceof HTMLObjectElement)
     addImage(elem.data, gStrings.mediaObject, getValueText(elem), elem, false);
   else if (elem instanceof HTMLEmbedElement)
     addImage(elem.src, gStrings.mediaEmbed, "", elem, false);
 
   onProcessElement.forEach(function(func) { func(elem); });
 
   return NodeFilter.FILTER_ACCEPT;
--- a/browser/base/content/pageinfo/pageInfo.xul
+++ b/browser/base/content/pageinfo/pageInfo.xul
@@ -149,16 +149,21 @@
             <separator class="thin"/>
           </row>
           <row>
             <label control="typetext" value="&generalType;"/>
             <separator/>
             <textbox readonly="true" id="typetext"/>
           </row>
           <row>
+            <label control="modetext" value="&generalMode;"/>
+            <separator/>
+            <textbox readonly="true" crop="end" id="modetext"/>
+          </row>
+          <row>
             <label control="encodingtext" value="&generalEncoding;"/>
             <separator/>
             <textbox readonly="true" id="encodingtext"/>
           </row>
           <row>
             <label control="sizetext" value="&generalSize;"/>
             <separator/>
             <textbox readonly="true" id="sizetext"/>
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -58,34 +58,29 @@ var security = {
 
     var hName = null;
     try {
       hName = gWindow.location.host;
     }
     catch (exception) { }
 
     var ui = security._getSecurityUI();
-    var status = null;
-    var sp = null;
-    var isBroken = false;
-    if (ui) {
-      isBroken = (ui.state == Components.interfaces.nsIWebProgressListener.STATE_IS_BROKEN);
-      sp = ui.QueryInterface(nsISSLStatusProvider);
-      if (sp)
-        status = sp.SSLStatus;
-    }
+    if (!ui)
+      return null;
+
+    var isBroken =
+      (ui.state == Components.interfaces.nsIWebProgressListener.STATE_IS_BROKEN);
+    ui.QueryInterface(nsISSLStatusProvider);
+    var status = ui.SSLStatus;
+
     if (status) {
-      status = status.QueryInterface(nsISSLStatus);
-    }
-    if (status) {
+      status.QueryInterface(nsISSLStatus);
       var cert = status.serverCert;
-      var issuerName;
-
-      issuerName = this.mapIssuerOrganization(cert.issuerOrganization);
-      if (!issuerName) issuerName = cert.issuerName;
+      var issuerName =
+        this.mapIssuerOrganization(cert.issuerOrganization) || cert.issuerName;
 
       return {
         hostName : hName,
         cAName : issuerName,
         encryptionAlgorithm : status.cipherName,
         encryptionStrength : status.secretKeyLength,
         isBroken : isBroken,
         cert : cert,
@@ -101,17 +96,17 @@ var security = {
         cert : null,
         fullLocation : gWindow.location        
       };
     }
   },
 
   // Find the secureBrowserUI object (if present)
   _getSecurityUI : function() {
-    if ("gBrowser" in window.opener)
+    if (window.opener.gBrowser)
       return window.opener.gBrowser.securityUI;
     return null;
   },
 
   // Interface for mapping a certificate issuer organization to
   // the value to be displayed.
   // Bug 82017 - this implementation should be moved to pipnss C++ code
   mapIssuerOrganization: function(name) {
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -216,16 +216,29 @@
     <handlers>
       <handler event="focus" phase="capturing" action="this._hideURLTooltip();"/>
     </handlers>
 
   </binding>
 
   <binding id="urlbar-result-popup" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete-result-popup">
     <implementation>
+      <method name="openAutocompletePopup">
+        <parameter name="aInput"/>
+        <parameter name="aElement"/>
+        <body><![CDATA[
+          // initially the panel is hidden
+          // to avoid impacting startup / new window performance
+          aInput.popup.hidden = false;
+
+          // this method is defined on the base binding
+          this._openAutocompletePopup(aInput, aElement);
+        ]]></body>
+      </method>
+
       <method name="onPopupClick">
         <parameter name="aEvent"/>
         <body><![CDATA[
           var controller = this.view.QueryInterface(Components.interfaces.nsIAutoCompleteController);
 
           // default action on unmodified left-click
           if (aEvent.button == 0 && !aEvent.shiftKey && !aEvent.ctrlKey &&
               !aEvent.altKey && !aEvent.metaKey) {
--- a/browser/base/content/web-panels.xul
+++ b/browser/base/content/web-panels.xul
@@ -58,16 +58,20 @@
   <script type="application/x-javascript" src="chrome://global/content/inlineSpellCheckUI.js"/>
   <script type="application/x-javascript" src="chrome://browser/content/nsContextMenu.js"/>
   <script type="application/x-javascript" src="chrome://browser/content/web-panels.js"/>
 
   <stringbundleset id="stringbundleset"> 
     <stringbundle id="bundle_browser" src="chrome://browser/locale/browser.properties"/>
   </stringbundleset>
 
+  <broadcasterset id="mainBroadcasterSet">
+    <broadcaster id="isFrameImage"/>
+  </broadcasterset>
+
   <commandset id="mainCommandset">
     <command id="Browser:Back"
              oncommand="getPanelBrowser().webNavigation.goBack();"
              disabled="true"/>
     <command id="Browser:Forward"
              oncommand="getPanelBrowser().webNavigation.goForward();"
              disabled="true"/>
     <command id="Browser:Stop" oncommand="PanelBrowserStop();"/>
--- a/browser/branding/unofficial/branding.nsi
+++ b/browser/branding/unofficial/branding.nsi
@@ -29,22 +29,27 @@
 # 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 *****
 
-# NSIS defines for nightly builds.
-# The release build branding.nsi is located in other-license/branding/firefox/
+# NSIS branding defines for unofficial builds.
+# The official release build branding.nsi is located in other-license/branding/firefox/
+# The nightly build branding.nsi is located in browser/installer/windows/nsis/
 !define BrandShortName        "Gran Paradiso"
-!define BrandFullName         "Gran Paradiso"
-# BrandFullNameInternal is used for some registry and file system values that
-# should not contain release that may be in the BrandFullName (e.g. Beta 1, etc.)
+# BrandFullNameInternal is used for some registry and file system values
+# instead of BrandFullName and typically should not be modified.
 !define BrandFullNameInternal "Gran Paradiso"
 !define CompanyName           "mozilla.org"
 !define URLInfoAbout          "http://www.mozilla.org"
 !define URLUpdateInfo         "http://www.mozilla.org/projects/firefox"
 !define SurveyURL             "https://survey.mozilla.com/1/Mozilla%20Firefox/${AppVersion}/${AB_CD}/exit.html"
 
-# Percentage of new "Standard" installs to enable talkback for
-!define RandomPercent         "50"
+# Everything below this line may be modified for Alpha / Beta releases.
+!define BrandFullName         "Gran Paradiso"
+
+# Add !define NO_INSTDIR_FROM_REG to prevent finding a non-default installation
+# directory in the registry and using that as the default. This prevents
+# Beta releases built with official branding from finding an existing install
+# of an official release and defaulting to its installation directory.
deleted file mode 100644
--- a/browser/components/bookmarks/Makefile.in
+++ /dev/null
@@ -1,52 +0,0 @@
-#
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-DEPTH		= ../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-DIRS		= public
-
-ifndef MOZ_PLACES_BOOKMARKS
-DIRS		+= src
-endif
-
-include $(topsrcdir)/config/rules.mk
-
deleted file mode 100644
--- a/browser/components/bookmarks/content/addBookmark.js
+++ /dev/null
@@ -1,263 +0,0 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# ***** 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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Ben Goodger <ben@netscape.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 *****
-
-/**
- * Add Bookmark Dialog. 
- * ====================
- * 
- * This is a generic bookmark dialog that allows for bookmark addition
- * and folder selection. It can be opened with various parameters that 
- * result in appearance/purpose differences and initial state. 
- * 
- * Use: Open with 'openDialog', with the flags 
- *        'centerscreen,chrome,dialog=no,resizable=yes'
- * 
- * Parameters: 
- *   Apart from the standard openDialog parameters, this dialog can 
- *   be passed additional information, which gets mapped to the 
- *   window.arguments array:
- * 
- *   window.arguments[0]: Bookmark Name. The value to be prefilled
- *                        into the "Name: " field (if visible).
- *   window.arguments[1]: Bookmark URL: The location of the bookmark.
- *                        The value to be filled in the "Location: "
- *                        field (if visible).
- *   window.arguments[2]: Bookmark Folder. The RDF Resource URI of the
- *                        folder that this bookmark should be created in.
- *   window.arguments[3]: Bookmark Charset. The charset that should be
- *                        used when adding a bookmark to the specified
- *                        URL. (Usually the charset of the current 
- *                        document when launching this window). 
- *   window.arguments[4]: The mode of operation. See notes for details.
- *   window.arguments[6]: If the bookmark should become a web panel.
- *
- * Mode of Operation Notes:
- * ------------------------
- * This dialog can be opened in four different ways by using a parameter
- * passed through the call to openDialog. The 'mode' of operation
- * of the window is expressed in window.arguments[4]. The valid modes are:
- *
- * 1) <default> (no fifth open parameter).
- *      Opens this dialog with the bookmark Name, URL and folder selection
- *      components visible. 
- * 2) "newBookmark" (fifth open parameter = String("newBookmark"))
- *      Opens the dialog as in (1) above except the folder selection tree
- *      is hidden. This type of mode is useful when the creation folder 
- *      is pre-determined.
- * 3) "selectFolder" (fifth open parameter = String("selectFolder"))
- *      Opens the dialog as in (1) above except the Name/Location section
- *      is hidden, and the dialog takes on the utility of a Folder chooser.
- *      Used when the user must select a Folder for some purpose. 
- */
-
-var gFld_Name   = null;
-var gFld_URL    = null; 
-var gFolderTree = null;
-
-var gBookmarkCharset = null;
-
-var gSelectItemObserver = null;
-
-var gCreateInFolder = "NC:NewBookmarkFolder";
-
-function Startup()
-{
-  initServices();
-  initBMService();
-  gFld_Name = document.getElementById("name");
-  gFld_URL = document.getElementById("url");
-  var bookmarkView = document.getElementById("bookmarks-view");
-
-  var shouldSetOKButton = true;
-  if ("arguments" in window) {
-    var ind;
-    var folderItem = null;
-    var arg;
-    if (window.arguments.length < 5)
-      arg = null;
-    else
-      arg = window.arguments[4];
-    switch (arg) {
-    case "selectFolder":
-      // If we're being opened as a folder selection window
-      document.getElementById("bookmarknamegrid").setAttribute("hidden", "true");
-      document.getElementById("createinseparator").setAttribute("hidden", "true");
-      document.getElementById("nameseparator").setAttribute("hidden", "true");
-      document.title = document.documentElement.getAttribute("title-selectFolder");
-      shouldSetOKButton = false;
-      if (window.arguments[2])
-        folderItem = RDF.GetResource(window.arguments[2]);
-      if (folderItem) {
-        ind = bookmarkView.treeBuilder.getIndexOfResource(folderItem);
-        bookmarkView.treeBoxObject.view.selection.select(ind);
-      }
-      break;
-    case "newBookmark":
-      setupFields();
-      if (window.arguments[2])
-        gCreateInFolder = window.arguments[2];
-      document.getElementById("folderbox").setAttribute("hidden", "true");
-      sizeToFit();
-      break;
-    default:
-      // Regular Add Bookmark
-      setupFields();
-      if (window.arguments[2]) {
-        gCreateInFolder = window.arguments[2];
-        folderItem = bookmarkView.rdf.GetResource(gCreateInFolder);
-        if (folderItem) {
-          ind = bookmarkView.treeBuilder.getIndexOfResource(folderItem);
-          bookmarkView.treeBoxObject.view.selection.select(ind);
-        }
-      }
-    }
-  }
-  
-  if (shouldSetOKButton)
-    onFieldInput();
-  if (document.getElementById("bookmarknamegrid").hasAttribute("hidden")) {
-    bookmarkView.tree.focus();
-    if (bookmarkView.currentIndex == -1)
-      bookmarkView.treeBoxObject.view.selection.select(0);
-  }
-  else {
-    gFld_Name.select();
-    gFld_Name.focus();
-  }
-} 
-
-function sizeToFit()
-{
-  var dialogElement = document.documentElement;
-  dialogElement.removeAttribute("persist");
-  dialogElement.removeAttribute("height");
-  dialogElement.removeAttribute("width");
-  dialogElement.setAttribute("style", dialogElement.getAttribute("style"));
-  sizeToContent();
-}
-
-function setupFields()
-{
-  // New bookmark in predetermined folder. 
-  gFld_Name.value = window.arguments[0] || "";
-  gFld_URL.value = window.arguments[1] || "";
-  onFieldInput();
-  gFld_Name.select();
-  gFld_Name.focus();
-  gBookmarkCharset = window.arguments[3] || null;
-}
-
-function onFieldInput()
-{
-  const ok = document.documentElement.getButton("accept");
-  ok.disabled = gFld_URL.value == "" ||
-                gFld_Name.value == "";
-}    
-
-function onOK()
-{
-  if (!document.getElementById("folderbox").hasAttribute("hidden")) {
-    var bookmarkView = document.getElementById("bookmarks-view");
-    var currentIndex = bookmarkView.currentIndex;
-    if (currentIndex != -1)
-      gCreateInFolder = bookmarkView.treeBuilder.getResourceAtIndex(currentIndex).Value;
-  }
-  // In Select Folder Mode, do nothing but tell our caller what
-  // folder was selected. 
-  if (window.arguments.length > 4 && window.arguments[4] == "selectFolder")
-    window.arguments[5].target = BookmarksUtils.getTargetFromFolder(bookmarkView.treeBuilder.getResourceAtIndex(currentIndex));
-  else {
-    // Otherwise add a bookmark to the selected folder. 
-    var rFolder = RDF.GetResource(gCreateInFolder);
-    try {
-      RDFC.Init(BMDS, rFolder);
-    }
-    catch (e) {
-      // No "NC:NewBookmarkFolder" exists, just append to the root.
-      rFolder = RDF.GetResource("NC:BookmarksRoot");
-      RDFC.Init(BMDS, rFolder);
-    }
-
-    // if no URL was provided, do nothing
-    if (!gFld_URL.value)
-      return;
-
-    var url, rSource;
-   
-    url = getNormalizedURL(gFld_URL.value);
-    rSource = BMDS.createBookmark(gFld_Name.value, url, null, null, gBookmarkCharset, false, "");
-    if (window.arguments.length > 4 && window.arguments[4] == "newBookmark") {
-      window.arguments[5].newBookmark = rSource;
-    }    
-    var selection = BookmarksUtils.getSelectionFromResource(rSource);
-    var target    = BookmarksUtils.getTargetFromFolder(rFolder);
-    BookmarksUtils.insertAndCheckSelection("newbookmark", selection, target);
-  }
-}
-
-function getNormalizedURL(url)
-{
-  // Check to see if the item is a local directory path, and if so, convert
-  // to a file URL so that aggregation with rdf:files works
-  try {
-    const kLF = Components.classes["@mozilla.org/file/local;1"]
-                          .createInstance(Components.interfaces.nsILocalFile);
-    kLF.initWithPath(url);
-    if (kLF.exists()) {
-      var ioService = Components.classes["@mozilla.org/network/io-service;1"]
-                                .getService(Components.interfaces.nsIIOService);
-      var fileHandler = ioService.getProtocolHandler("file")
-                                 .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
-
-      url = fileHandler.getURLSpecFromFile(kLF);
-    }
-  }
-  catch (e) {
-  }
-
-  return url;
-}
-
-function createNewFolder ()
-{
-  var bookmarksView = document.getElementById("bookmarks-view");
-  var resource = bookmarksView.treeBuilder.getResourceAtIndex(bookmarksView.currentIndex);
-  var target = BookmarksUtils.getTargetFromFolder(resource);
-  BookmarksCommand.createNewFolder(target);
-}
-
deleted file mode 100644
--- a/browser/components/bookmarks/content/addBookmark.xul
+++ /dev/null
@@ -1,111 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- -*- Mode: HTML; indent-tabs-mode: nil; -*- -->
-<!--
-
- ***** 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
- Netscape Communications Corporation.
- Portions created by the Initial Developer are Copyright (C) 1998
- the Initial Developer. All Rights Reserved.
-
- Contributor(s):
-   Ben Goodger <ben@netscape.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 ***** -->
-
-<?xml-stylesheet href="chrome://browser/skin/"?>
-<?xml-stylesheet href="chrome://browser/content/bookmarks/bookmarks.css"?>
-
-<!DOCTYPE dialog SYSTEM "chrome://browser/locale/bookmarks/addBookmark.dtd">
-
-<dialog id="newBookmarkDialog" style="width: 36em; height: 18em;"
-        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        ondialogaccept="return onOK(event)"
-        title="&newBookmark.title;" title-selectFolder="&selectFolder.label;"
-        onload="Startup();"
-        persist="screenX screenY width height"
-        screenX="24" screenY="24">
-   
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/addBookmark.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/bookmarks.js"/>
-
-  <broadcaster id="showaddgroup" hidden="true"/>
-
-  <separator id="nameseparator" class="thin"/>
-  
-  <grid id="bookmarknamegrid">
-    <columns>
-      <column/>
-      <column flex="5"/>
-      <column flex="1"/>
-    </columns>
-    <rows>
-      <row align="center">
-        <label value="&name.label;" accesskey="&name.accesskey;" control="name"/>
-        <textbox id="name" oninput="onFieldInput();"/>
-        <spacer/>
-      </row>
-      <row>
-        <separator class="thin"/>
-        <separator class="thin"/>
-        <spacer/>
-      </row>
-      <row align="center">
-        <label value="&url.label;" accesskey="&url.accesskey;" control="url"/>
-        <textbox id="url" oninput="onFieldInput();"/>
-        <spacer/>
-      </row>
-      <row observes="showaddgroup">
-        <separator class="thin"/>
-        <separator class="thin"/>
-        <spacer/>
-      </row>
-    </rows>
-  </grid>
-
-  <separator id="createinseparator"/>
-
-  <vbox id="folderbox" flex="1">
-    <separator/>
-    <hbox flex="1">
-      <label id="movetolabel" value="&moveto.label;"/>
-      <hbox flex="1">
-        <bookmarks-tree id="bookmarks-view" flex="1" type="folders"/>
-        <vbox>
-          <button label="&button.newfolder.label;" accesskey="&button.newfolder.accesskey;"
-                  oncommand="createNewFolder();" icon="open"/>
-        </vbox>
-      </hbox>
-    </hbox>
-  </vbox>
-
-  <separator/>
-
-</dialog>
deleted file mode 100644
--- a/browser/components/bookmarks/content/addBookmark2.js
+++ /dev/null
@@ -1,379 +0,0 @@
-# -*- Mode: Java; 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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Ben Goodger <ben@netscape.com> (Original Author)
-#   David Hyatt <hyatt@mozilla.org>
-#   Myk Melez <myk@mozilla.org>
-#
-# 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 *****
-
-/**
- * Add Bookmark Dialog. 
- * ====================
- * 
- * This is a generic bookmark dialog that allows for bookmark addition
- * and folder selection. It can be opened with various parameters that 
- * result in appearance/purpose differences and initial state. 
- * 
- * Use: Open with 'openDialog', with the flags 
- *        'centerscreen,chrome,dialog=no,resizable=yes'
- * 
- * Parameters: 
- *   Apart from the standard openDialog parameters, this dialog can 
- *   be passed additional information, which is contained in the 
- *   wArg object:
- *  
- *   wArg.name              : Bookmark Name. The value to be prefilled
- *                            into the "Name: " field (if visible).
- *   wArg.description       : Bookmark description. The value to be added
- *                          : to the boomarks description field.
- *   wArg.url               : Bookmark URL: The location of the bookmark.
- *                            The value to be filled in the "Location: "
- *                            field (if visible).
- *   wArg.folderURI         : Bookmark Folder. The RDF Resource URI of the
- *                            folder that this bookmark should be created in.
- *   wArg.charset           : Bookmark Charset. The charset that should be
- *                            used when adding a bookmark to the specified
- *                            URL. (Usually the charset of the current 
- *                            document when launching this window).
- *   wArg.bBookmarkAllTabs  : True if "Bookmark All Tabs" option is chosen,
- *                            false otherwise.
- *   wArg.objGroup[]        : If adding a group of tabs, this is an array
- *                            of wArg objects with name, URL and charset
- *                            properties, one for each group member.
- *   wArg.bWebPanel         : If the bookmark should become a web panel.
- *   wArg.keyword           : A suggested keyword for the bookmark. If this
- *                            argument is supplied, the keyword row is made
- *                            visible.
- *   wArg.bNeedKeyword      : Whether or not a keyword is required to add
- *                            the bookmark.
- *   wArg.postData          : PostData to be saved with this bookmark, 
- *                            in the format a string of name=value pairs
- *                            separated by CRLFs.
- *   wArg.feedURL           : feed URL for Livemarks (turns bookmark
- *                            into Livemark)
- */
-
-var gSelectedFolder;
-var gName;
-var gKeyword;
-var gKeywordRow;
-var gExpander;
-var gMenulist;
-var gBookmarksTree;
-var gKeywordRequired;
-var gSuggestedKeyword;
-var gRequiredFields = [];
-var gPostData;
-var gArg = window.arguments[0];
-var gResource;
-
-# on windows, sizeToContent is buggy (see bug 227951), we''ll use resizeTo
-# instead and cache the bookmarks tree view size.
-var WSucks;
-
-function Startup()
-{
-  initServices();
-  initBMService();
-  gName = document.getElementById("name");
-  gKeywordRow = document.getElementById("keywordRow");
-  gKeyword = document.getElementById("keyword");
-  gExpander = document.getElementById("expander");
-  gMenulist = document.getElementById("select-menu");
-  gBookmarksTree = document.getElementById("folder-tree");
-  gName.value = gArg.name;
-  gName.select();
-  gName.focus();
-  gSuggestedKeyword = gArg.keyword;
-  gKeywordRequired = gArg.bNeedKeyword;
-  if (!gSuggestedKeyword && !gKeywordRequired) {
-    gKeywordRow.hidden = true;
-  } else {
-    if (gSuggestedKeyword)
-      gKeyword.value = gSuggestedKeyword;
-    if (gKeywordRequired)
-      gRequiredFields.push(gKeyword);
-  }
-  sizeToContent();
-  onFieldInput();
-  initTitle();
-  gExpander.setAttribute("tooltiptext", gExpander.getAttribute("tooltiptextdown"));
-  gPostData = gArg.postData;
-  
-  if ("feedURL" in gArg) {
-    var strings = document.getElementById("bookmarksBundle");
-    document.title = strings.getString("addLiveBookmarkTitle");
-  }
-
-# read the persisted attribute. If it is not present, set a default height.
-  WSucks = parseInt(gBookmarksTree.getAttribute("height"));
-  if (!WSucks)
-    WSucks = 150;
-
-  // fix no more persisted class attribute in old profiles
-  var localStore = RDF.GetDataSource("rdf:local-store");
-  var rAttribute = RDF.GetResource("class");
-  var rElement   = RDF.GetResource("chrome://browser/content/bookmarks/addBookmark2.xul#expander");
-  var rDialog    = RDF.GetResource("chrome://browser/content/bookmarks/addBookmark2.xul");
-  var rPersist   = RDF.GetResource(gNC_NS+"persist");
-  
-  var rOldValue = localStore.GetTarget(rElement, rAttribute, true);
-  if (rOldValue) {
-    localStore.Unassert(rElement, rAttribute, rOldValue, true);
-    localStore.Unassert(rDialog, rPersist, rElement, true);
-    gExpander.setAttribute("class", "down");
-  }
-
-  // Select the specified folder after the window is made visible
-  function initMenulist() {
-    if ("folderURI" in gArg) {
-      var folderItem = document.getElementById(gArg.folderURI);
-      if (folderItem)
-        gMenulist.selectedItem = folderItem;
-    }
-    gSelectedFolder = RDF.GetResource(gMenulist.selectedItem.id);
-  }
-  setTimeout(initMenulist, 0);
-
-  // Reset the |id| attribute on the toolbar folder attribute to the URI of the
-  // Bookmarks toolbar folder. 
-  var btfMenuItem = document.getElementById("btfMenuItem");
-  btfMenuItem.id = BMSVC.getBookmarksToolbarFolder().Value;
-
-  if (MicrosummaryPicker.enabled)
-    MicrosummaryPicker.init();
-} 
-
-function initTitle()
-{
-  if(gArg.bBookmarkAllTabs)
-    document.title = document.getElementById("bookmarksBundle").getString("bookmarkAllTabsTitle");
-  else
-    document.title = document.getElementById("bookmarksBundle").getString("bookmarkCurTabTitle");
-}
-
-function onFieldInput()
-{
-  var ok = document.documentElement.getButton("accept");
-  ok.disabled = false;
-  for (var i = 0; i < gRequiredFields.length; ++i) {
-    if (gRequiredFields[i].value == "") {
-      ok.disabled = true;
-      return;
-    }
-  }
-}
-
-function onOK()
-{
-  RDFC.Init(BMDS, gSelectedFolder);
-  
-  var url;
-  var livemarkFeed = gArg.feedURL;
-  if (gArg.bBookmarkAllTabs) {
-    gResource = BMDS.createFolder(gName.value);
-    const groups = gArg.objGroup;
-    for (var i = 0; i < groups.length; ++i) {
-      url = getNormalizedURL(groups[i].url);
-      BMDS.createBookmarkInContainer(groups[i].name, url, gKeyword.value, 
-                                     groups[i].description, groups[i].charset, 
-                                     gPostData, gResource, -1);
-    }
-  } else if (livemarkFeed != null) {
-    url = getNormalizedURL(gArg.url);
-    gResource = BMDS.createLivemark(gName.value, url, livemarkFeed, 
-                                    gArg.description);
-  } else {
-    url = getNormalizedURL(gArg.url);
-
-    var name = gName.value;
-
-    // If the microsummary picker is enabled, the value of the name field
-    // won't necessarily contain the user-entered name for the bookmark.
-    // But the first item in the microsummary drop-down menu will always
-    // contain the user-entered name, so get the name from there instead.
-    if (MicrosummaryPicker.enabled) {
-      var menuPopup = document.getElementById("microsummaryMenuPopup");
-      name = menuPopup.childNodes[0].getAttribute("label");
-    }
-
-    gResource = BMDS.createBookmark(name, url, gKeyword.value, 
-                                    gArg.description, gArg.charset, 
-                                    gPostData);
-  }
-
-  var selection = BookmarksUtils.getSelectionFromResource(gResource);
-  var target    = BookmarksUtils.getTargetFromFolder(gSelectedFolder);
-  BookmarksUtils.insertAndCheckSelection("newbookmark", selection, target);
-
-  if (MicrosummaryPicker.enabled) {
-    MicrosummaryPicker.commit();
-    MicrosummaryPicker.destroy();
-  }
-
-  if (gArg.bWebPanel && gResource) {
-    // Assert that we're a web panel.
-    BMDS.Assert(gResource, RDF.GetResource(gNC_NS+"WebPanel"),
-                RDF.GetLiteral("true"), true);
-  }
-  
-  // in insertSelection, the ds flush is delayed. It will never be performed,
-  // since this dialog is destroyed before.
-  // We have to flush manually
-  var remoteDS = BMDS.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
-  remoteDS.Flush();
-}
-
-function onCancel()
-{
-  // Destroy the microsummary picker controller to prevent memory leaks,
-  // catching exceptions so we don't prevent the dialog from closing.
-  try {
-    if (MicrosummaryPicker.enabled)
-      MicrosummaryPicker.destroy();
-  }
-  catch(e) {
-    Components.utils.reportError(e);
-  }
-
-  return true;
-}
-
-function getNormalizedURL(url)
-{
-  // Check to see if the item is a local directory path, and if so, convert
-  // to a file URL so that aggregation with rdf:files works
-  try {
-    const kLF = Components.classes["@mozilla.org/file/local;1"]
-                          .createInstance(Components.interfaces.nsILocalFile);
-    kLF.initWithPath(url);
-    if (kLF.exists()) {
-      var ioService = Components.classes["@mozilla.org/network/io-service;1"]
-                                .getService(Components.interfaces.nsIIOService);
-      var fileHandler = ioService.getProtocolHandler("file")
-                                 .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
-
-      url = fileHandler.getURLSpecFromFile(kLF);
-    }
-  }
-  catch (e) {
-  }
-
-  return url;
-}
-
-function selectMenulistFolder(aEvent)
-{
-  gSelectedFolder = RDF.GetResource(aEvent.target.id);
-  if (!gBookmarksTree.collapsed)
-    selectFolder(gSelectedFolder);
-}
-
-function selectTreeFolder()
-{
-  // If no item is selected, we obviously can't do anything with the selection.
-  // This happens when the bookmarks tree rebuilds, since the rebuild starts
-  // by removing all items from the tree, including the currently selected item,
-  // and removing the selection also triggers the "select" handler which calls
-  // this function.
-  if (gBookmarksTree.currentIndex == -1)
-    return;
-
-  var resource = gBookmarksTree.currentResource;
-  if (resource == gSelectedFolder)
-    return;
-  gSelectedFolder = resource;
-  var menuitem = document.getElementById(gSelectedFolder.Value);
-  gMenulist.selectedItem = menuitem;
-  if (!menuitem) {
-    gMenulist.removeItemAt(gMenulist.firstChild.childNodes.length-1);
-    var newItem = gMenulist.appendItem(BookmarksUtils.getProperty(gSelectedFolder, gNC_NS+"Name"), gSelectedFolder.Value);
-    newItem.setAttribute("class", "menuitem-iconic folder-icon");
-    newItem.setAttribute("id", gSelectedFolder.Value);
-    gMenulist.selectedItem = newItem;
-  }
-}
-
-function selectFolder(aFolder)
-{
-  gBookmarksTree.treeBoxObject.view.selection.selectEventsSuppressed = true;
-  gBookmarksTree.treeBoxObject.view.selection.clearSelection();
-  gBookmarksTree.selectResource(aFolder);
-  var index = gBookmarksTree.currentIndex;
-  gBookmarksTree.treeBoxObject.ensureRowIsVisible(index);
-  gBookmarksTree.treeBoxObject.view.selection.selectEventsSuppressed = false;
-# triggers a select event that will provoke a call to selectTreeFolder()
-}
-
-function expandTree()
-{
-  setFolderTreeHeight();
-  var willCollapse = !gBookmarksTree.collapsed;
-  gExpander.setAttribute("class",willCollapse?"down":"up");
-  gExpander.setAttribute("tooltiptext", gExpander.getAttribute("tooltiptext"+(willCollapse?"down":"up")));
-  if (willCollapse) {
-    document.documentElement.buttons = "accept,cancel";
-    WSucks = gBookmarksTree.boxObject.height;
-  } else {
-    document.documentElement.buttons = "accept,cancel,extra2";
-#   always open the bookmark root folder
-    if (!gBookmarksTree.treeBoxObject.view.isContainerOpen(0))
-      gBookmarksTree.treeBoxObject.view.toggleOpenState(0);
-    selectFolder(gSelectedFolder);
-    gBookmarksTree.focus();
-  }
-  gBookmarksTree.collapsed = willCollapse;
-  resizeTo(window.outerWidth, window.outerHeight+(willCollapse?-WSucks:+WSucks));
-}
-
-function setFolderTreeHeight()
-{
-  var isCollapsed = gBookmarksTree.collapsed;
-  if (!isCollapsed)
-    gBookmarksTree.setAttribute("height", gBookmarksTree.boxObject.height);
-}
-
-function newFolder()
-{
-  gBookmarksTree.focus();
-  // we should use goDoCommand, but the current way of inserting
-  // resources do not insert in folders.
-  //goDoCommand("cmd_bm_newfolder");
-  var target = BookmarksUtils.getTargetFromFolder(gSelectedFolder);
-  var folder = BookmarksCommand.createNewFolder(target);
-  if (!BMSVC.isBookmarkedResource(folder))
-    return; // new folder cancelled
-  selectFolder(folder);
-}
deleted file mode 100644
--- a/browser/components/bookmarks/content/addBookmark2.xul
+++ /dev/null
@@ -1,139 +0,0 @@
-<?xml version="1.0"?>
-
-# -*- Mode: HTML; indent-tabs-mode: nil; -*- -->
-# ***** 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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Ben Goodger <ben@netscape.com> (Original Author)
-#   Myk Melez <myk@mozilla.org>
-#
-# 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 *****
-
-<?xml-stylesheet href="chrome://global/skin/"?>
-<?xml-stylesheet href="chrome://global/skin/arrow.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/content/bookmarks/bookmarks.css"?>
-<?xml-stylesheet href="chrome://browser/skin/bookmarks/addBookmark.css"?>
-
-<!DOCTYPE dialog [
-<!ENTITY % addBookmarkDTD SYSTEM "chrome://browser/locale/bookmarks/addBookmark.dtd">
-%addBookmarkDTD;
-<!ENTITY % bookmarksDTD SYSTEM "chrome://browser/locale/bookmarks/bookmarks.dtd">
-%bookmarksDTD;
-]>
-
-<dialog id="addBookmarkDialog"
-        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-        ondialogextra2="newFolder()"
-        ondialogaccept="return onOK(event)"
-        ondialogcancel="return onCancel(event)"
-        buttons="accept,cancel" 
-        buttonlabelextra2="&button.newfolder.label;" buttonaccesskeyextra2="&button.newfolder.accesskey;"
-#ifdef XP_UNIX
-        buttonlabelaccept="&acceptButton.label;"
-#endif
-        buttoniconaccept="add"
-        buttoniconextra2="open"
-        title-selectFolder="&selectFolder.label;"
-        onload="Startup();"
-        onunload="setFolderTreeHeight();"
-        persist="screenX screenY width">
-   
-  <script type="application/x-javascript" src="chrome://global/content/globalOverlay.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/bookmarks.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/microsummaryPicker.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/addBookmark2.js"/>
-
-  <stringbundle id="bookmarksBundle" 
-                src="chrome://browser/locale/bookmarks/bookmarks.properties"/>
-
-  <separator id="nameseparator" class="thin"/>
-  
-  <grid>
-    <columns>
-      <column/>
-      <column flex="1"/>
-      <column/>
-    </columns>
-    <rows>
-      <row align="center">
-        <label value="&name.label;" accesskey="&name.accesskey;" control="name"/>
-        <menulist id="name" editable="true" droppable="false"
-                  oninput="onFieldInput(); MicrosummaryPicker.onInput(event);">
-          <menupopup id="microsummaryMenuPopup">
-            <menuitem id="userEnteredNameItem"/>
-            <menuitem disabled="true">
-              <menuseparator flex="1"/>
-              <label value="&microsummary.label;"/>
-            </menuitem>
-          </menupopup>
-        </menulist>
-      </row>
-      <row align="center" id="keywordRow">
-        <label value="&keyword.label;" accesskey="&keyword.accesskey;" control="keyword"/>
-        <textbox id="keyword" oninput="onFieldInput();"/>
-      </row>
-      <row align="center">
-        <label id="createinlabel" value="&createin.label;" accesskey="&createin.accesskey;" control="select-menu"/>
-        <menulist id="select-menu" class="folder-icon"
-                  oncommand="selectMenulistFolder(event);">
-          <menupopup datasources="rdf:bookmarks" ref="NC:LastModifiedFoldersRoot">
-            <menuitem class="menuitem-iconic folder-icon"
-                      label="&bookmarksRoot.label;"
-                      id="NC:BookmarksRoot"/>
-            <menuitem class="menuitem-iconic folder-icon"
-                      label="&bookmarksToolbar.label;"
-                      id="btfMenuItem"/>
-            <menuseparator/>
-            <template>
-              <!-- this parent="menupopup" here seems to prevent the template builder from recursing. -->
-              <rule parent="menupopup">
-                <menuitem uri="rdf:*" class="menuitem-iconic folder-icon"
-                          label="rdf:http://home.netscape.com/NC-rdf#Name"/>
-              </rule>
-            </template>
-          </menupopup>
-        </menulist>
-        <button id="expander" class="down" oncommand="expandTree();"
-                 tooltiptextdown="&expanderDown.tooltip;"
-                 tooltiptextup="&expanderUp.tooltip;"/>
-      </row>
-    </rows>
-  </grid>
-
-  <separator class="thin"/>
-
-  <bookmarks-tree id="folder-tree" flex="1" type="folders" collapsed="true"
-                  seltype="single" persist="height" rows="6"
-                  onselect="selectTreeFolder();"/>
-</dialog>
deleted file mode 100644
--- a/browser/components/bookmarks/content/bookmarks.css
+++ /dev/null
@@ -1,16 +0,0 @@
-bookmarks-tree, bookmarks-tree[type="multi-column"] {
-  -moz-binding: url("chrome://browser/content/bookmarks/bookmarksTree.xml#bookmarks-tree-full");
-}
-  
-bookmarks-tree[type="single-column"] {
-  -moz-binding: url("chrome://browser/content/bookmarks/bookmarksTree.xml#bookmarks-tree-name");
-}
-
-bookmarks-tree[type="folders"] {
-  -moz-binding: url("chrome://browser/content/bookmarks/bookmarksTree.xml#bookmarks-tree-folders");
-}
-
-treechildren::-moz-tree-image(Name) {
-  width:16px;
-  height:16px;
-}
deleted file mode 100644
--- a/browser/components/bookmarks/content/bookmarks.js
+++ /dev/null
@@ -1,2310 +0,0 @@
-# -*- Mode: javascript; 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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Ben Goodger <ben@netscape.com> (Original Author)
-#   Joey Minta <jminta@gmail.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-#ifdef XP_MACOSX
-const ADD_BM_DIALOG_FEATURES = "centerscreen,chrome,dialog,resizable,modal";
-#else
-const ADD_BM_DIALOG_FEATURES = "centerscreen,chrome,dialog,resizable,dependent";
-#endif
-
-const kBATCH_LIMIT = 4;
-
-var gNC_NS, gWEB_NS, gRDF_NS, gXUL_NS, gNC_NS_CMD;
-
-// definition of the services frequently used for bookmarks
-var kRDFContractID;
-var kRDFSVCIID;
-var kRDFRSCIID;
-var kRDFLITIID;
-var RDF;
-
-var kRDFCContractID;
-var kRDFCIID;
-var RDFC;
-
-var kRDFCUContractID;
-var kRDFCUIID;
-var RDFCU;
-
-var BMDS;
-var kBMSVCIID;
-var BMSVC;
-
-var kPREFContractID;
-var kPREFIID;
-var PREF;
-
-var kSOUNDContractID;
-var kSOUNDIID;
-var SOUND;
-
-var kWINDOWContractID;
-var kWINDOWIID;
-var WINDOWSVC;
-
-var kDSContractID;
-var kDSIID;
-var DS;
-
-var kIOContractID;
-var kIOIID;
-var IOSVC;
-
-var kMICSUMContractID;
-var kMICSUMIID;
-var MICSUMSVC;
-
-var gBmProperties;
-var gBkmkTxnSvc;
-
-// should be moved in a separate file
-function initServices()
-{
-  gNC_NS     = "http://home.netscape.com/NC-rdf#";
-  gWEB_NS    = "http://home.netscape.com/WEB-rdf#";
-  gRDF_NS    = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
-  gXUL_NS    = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
-  gNC_NS_CMD = gNC_NS + "command?cmd=";
-
-  kRDFContractID   = "@mozilla.org/rdf/rdf-service;1";
-  kRDFSVCIID       = Components.interfaces.nsIRDFService;
-  kRDFRSCIID       = Components.interfaces.nsIRDFResource;
-  kRDFLITIID       = Components.interfaces.nsIRDFLiteral;
-  RDF              = Components.classes[kRDFContractID].getService(kRDFSVCIID);
-
-  kRDFCContractID  = "@mozilla.org/rdf/container;1";
-  kRDFCIID         = Components.interfaces.nsIRDFContainer;
-  RDFC             = Components.classes[kRDFCContractID].createInstance(kRDFCIID);
-
-  kRDFCUContractID = "@mozilla.org/rdf/container-utils;1";
-  kRDFCUIID        = Components.interfaces.nsIRDFContainerUtils;
-  RDFCU            = Components.classes[kRDFCUContractID].getService(kRDFCUIID);
-
-  kPREFContractID  = "@mozilla.org/preferences-service;1";
-  kPREFIID         = Components.interfaces.nsIPrefService;
-  PREF             = Components.classes[kPREFContractID].getService(kPREFIID)
-                               .getBranch(null);
-
-  kSOUNDContractID = "@mozilla.org/sound;1";
-  kSOUNDIID        = Components.interfaces.nsISound;
-  SOUND            = Components.classes[kSOUNDContractID].createInstance(kSOUNDIID);
-
-  kWINDOWContractID = "@mozilla.org/appshell/window-mediator;1";
-  kWINDOWIID        = Components.interfaces.nsIWindowMediator;
-  WINDOWSVC         = Components.classes[kWINDOWContractID].getService(kWINDOWIID);
-
-  kDSContractID     = "@mozilla.org/widget/dragservice;1";
-  kDSIID            = Components.interfaces.nsIDragService;
-  DS                = Components.classes[kDSContractID].getService(kDSIID);
-
-  kIOContractID     = "@mozilla.org/network/io-service;1";
-  kIOIID            = Components.interfaces.nsIIOService;
-  IOSVC             = Components.classes[kIOContractID].getService(kIOIID);
-  
-  kMICSUMContractID = "@mozilla.org/microsummary/service;1";
-  kMICSUMIID        = Components.interfaces.nsIMicrosummaryService;
-  MICSUMSVC         = Components.classes[kMICSUMContractID].getService(kMICSUMIID);
-  
-  gBmProperties     = [RDF.GetResource(gNC_NS+"Name"),
-                       RDF.GetResource(gNC_NS+"URL"),
-                       RDF.GetResource(gNC_NS+"ShortcutURL"),
-                       RDF.GetResource(gNC_NS+"Description"),
-                       RDF.GetResource(gNC_NS+"WebPanel"),
-                       RDF.GetResource(gNC_NS+"FeedURL"),
-                       RDF.GetResource(gNC_NS+"MicsumGenURI"),
-                       RDF.GetResource(gNC_NS+"MicsumExpiration"),
-                       RDF.GetResource(gNC_NS+"GeneratedTitle")];
-  gBkmkTxnSvc = Components.classes["@mozilla.org/bookmarks/transactionmanager;1"]
-                          .getService(Components.interfaces.nsIBookmarkTransactionManager);
-}
-
-function initBMService()
-{
-  kBMSVCIID = Components.interfaces.nsIBookmarksService;
-  BMDS  = RDF.GetDataSource("rdf:bookmarks");
-  BMSVC = BMDS.QueryInterface(kBMSVCIID);
-}
-
-/**
- * XXX - 24 Jul 04
- * If you add a command that needs to run from the main browser window,
- * it needs to be added to browser/base/content/browser-sets.inc as well!
- *
- * XXX - 04/16/01
- *  ACK! massive command name collision problems are causing big issues
- *  in getting this stuff to work in the Navigator window. For sanity's 
- *  sake, we need to rename all the commands to be of the form cmd_bm_*
- *  otherwise there'll continue to be problems. For now, we're just 
- *  renaming those that affect the personal toolbar (edit operations,
- *  which were clashing with the textfield controller)
- *
- * There are also several places that need to be updated if you need
- * to change a command name. 
- *   1) the controller...
- *      - in bookmarksTree.xml if the command is tree-specifc
- *      - in bookmarksMenu.js if the command is DOM-specific
- *      - in bookmarks.js otherwise
- *   2) the command nodes in the overlay or xul file
- *   3) the command human-readable name key in bookmarks.properties
- *   4) the function 'getCommands' in bookmarks.js
- */
-
-var BookmarksCommand = {
-
-  /////////////////////////////////////////////////////////////////////////////
-  // This method constructs a menuitem for a context menu for the given command.
-  // This is implemented by the client so that it can intercept menuitem naming
-  // as appropriate.
-  createMenuItem: function (aDisplayName, aAccessKey, aCommandName, aSelection)
-  {
-    var xulElement = document.createElementNS(gXUL_NS, "menuitem");
-    xulElement.setAttribute("cmd", aCommandName);
-    var cmd = "cmd_" + aCommandName.substring(gNC_NS_CMD.length);
-    xulElement.setAttribute("command", cmd);
-    xulElement.setAttribute("label", aDisplayName);
-    xulElement.setAttribute("accesskey", aAccessKey);
-    return xulElement;
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // Fill a context menu popup with menuitems that are appropriate for the current
-  // selection.
-  createContextMenu: function (aEvent, aSelection, aDS)
-  {
-    if (aSelection == undefined) {
-      aEvent.preventDefault();
-      return;
-    }
-
-    var popup = aEvent.target;
-    // clear out the old context menu contents (if any)
-    while (popup.hasChildNodes()) 
-      popup.removeChild(popup.firstChild);
-        
-    var commonCommands = [];
-    for (var i = 0; i < aSelection.length; ++i) {
-      var commands = this.getCommands(aSelection.item[i], aSelection.parent[i], aDS);
-      if (!commands) {
-        aEvent.preventDefault();
-        return;
-      }
-      commands = this.flattenEnumerator(commands);
-      if (!commonCommands.length) commonCommands = commands;
-      commonCommands = this.findCommonNodes(commands, commonCommands);
-    }
-
-    if (!commonCommands.length) {
-      aEvent.preventDefault();
-      return;
-    }
-    
-    // Now that we should have generated a list of commands that is valid
-    // for the entire selection, build a context menu.
-    for (i = 0; i < commonCommands.length; ++i) {
-      var currCommand = commonCommands[i].QueryInterface(kRDFRSCIID).Value;
-      var element = null;
-      if (currCommand != gNC_NS_CMD + "bm_separator") {
-        var commandName = this.getCommandName(currCommand);
-        var accessKey = this.getAccessKey(currCommand);
-        element = this.createMenuItem(commandName, accessKey, currCommand, aSelection);
-      }
-      else if (i != 0 && i < commonCommands.length-1) {
-        // Never append a separator as the first or last element in a context
-        // menu.
-        element = document.createElementNS(gXUL_NS, "menuseparator");
-      }
-      if (element) 
-        popup.appendChild(element);
-    }
-
-    if (popup.firstChild.getAttribute("command") == "cmd_bm_open")
-      popup.firstChild.setAttribute("default", "true");
-  },
-  
-  /////////////////////////////////////////////////////////////////////////////
-  // Given two unique arrays, return an array that contains only the elements
-  // common to both. 
-  findCommonNodes: function (aNewArray, aOldArray)
-  {
-    var common = [];
-    for (var i = 0; i < aNewArray.length; ++i) {
-      for (var j = 0; j < aOldArray.length; ++j) {
-        if (common.length > 0 && common[common.length-1] == aNewArray[i])
-          continue;
-        if (aNewArray[i] == aOldArray[j])
-          common.push(aNewArray[i]);
-      }
-    }
-    return common;
-  },
-
-  flattenEnumerator: function (aEnumerator)
-  {
-    if ("_index" in aEnumerator)
-      return aEnumerator._inner;
-    
-    var temp = [];
-    while (aEnumerator.hasMoreElements()) 
-      temp.push(aEnumerator.getNext());
-    return temp;
-  },
-  
-  /////////////////////////////////////////////////////////////////////////////
-  // For a given URI (a unique identifier of a resource in the graph) return 
-  // an enumeration of applicable commands for that URI. 
-  getCommands: function (aNodeID, aParent, aDS)
-  {
-    var type = BookmarksUtils.resolveType(aNodeID, aDS);
-    if (!type)
-      return null;
-
-    var ptype = null;
-    aParent =  (aParent != null) ? aParent : BMSVC.getParent(aNodeID);
-    if (aParent) {
-      ptype = BookmarksUtils.resolveType(aParent, aDS);
-      if (ptype == "Livemark") {
-        type = "LivemarkBookmark";
-      }
-    }
-
-    var commands = [];
-    // menu order:
-    // 
-    // bm_open, bm_openfolder
-    // bm_openinnewwindow
-    // bm_openinnewtab
-    // ---------------------
-    // bm_newfolder
-    // ---------------------
-    // cut
-    // copy
-    // paste
-    // ---------------------
-    // delete
-    // ---------------------
-    // bm_refreshlivemark
-    // bm_refreshmicrosummary
-    // bm_sortbyname
-    // ---------------------
-    // bm_properties
-    switch (type) {
-    case "BookmarkSeparator":
-      commands = ["bm_newbookmark", "bm_newfolder", "bm_newseparator", "bm_separator",
-                  "cut", "copy", "paste", "bm_separator",
-                  "delete", "bm_separator",
-                  "bm_sortbyname", "bm_separator",
-                  "bm_properties"];
-      break;
-    case "Bookmark":
-      commands = ["bm_open", "bm_openinnewwindow", "bm_openinnewtab", "bm_separator",
-                  "bm_newbookmark", "bm_newfolder", "bm_newseparator", "bm_separator",
-                  "cut", "copy", "paste", "bm_separator",
-                  "delete", "bm_separator",
-                  "bm_sortbyname", "bm_separator",
-                  "bm_properties"];
-      // If this bookmark has a microsummary, add a command for refreshing it
-      // right before the "sort by name" (bm_sortbyname) command.
-      if (MICSUMSVC.hasMicrosummary(aNodeID))
-        commands.splice(14, 0, "bm_refreshmicrosummary");
-      break;
-    case "Folder":
-    case "PersonalToolbarFolder":
-      commands = ["bm_openfolder", "bm_separator", "bm_newbookmark", 
-                  "bm_newfolder", "bm_newseparator", "bm_separator",
-                  "cut", "copy", "paste", "bm_separator",
-                  "delete", "bm_separator",
-                  "bm_sortbyname", "bm_separator",
-                  "bm_properties"];
-      break;
-    case "IEFavoriteFolder":
-      commands = ["bm_separator", "delete"];
-      break;
-    case "IEFavorite":
-      commands = ["bm_open", "bm_openinnewwindow", "bm_openinnewtab", "bm_separator",
-                  "copy"];
-      break;
-    case "FileSystemObject":
-      commands = ["bm_open", "bm_openinnewwindow", "bm_openinnewtab", "bm_separator",
-                  "copy"];
-      break;
-    case "Livemark":
-      commands = ["bm_openfolder", "bm_separator",
-                  "cut", "copy", "bm_separator",
-                  "delete", "bm_separator",
-                  "bm_refreshlivemark", "bm_sortbyname", "bm_separator",
-                  "bm_properties"];
-      break;
-    case "LivemarkBookmark":
-      commands = ["bm_open", "bm_openinnewwindow", "bm_openinnewtab", "bm_separator",
-                  "copy"];
-      break;
-    case "ImmutableBookmark":
-      commands = ["bm_open", "bm_openinnewwindow", "bm_openinnewtab"];
-      break;
-    default: 
-      commands = [];
-    }
-
-    return new CommandArrayEnumerator(commands);
-  },
-  
-  /////////////////////////////////////////////////////////////////////////////
-  // Retrieve the human-readable name for a particular command. Used when 
-  // manufacturing a UI to invoke commands.
-  getCommandName: function (aCommand) 
-  {
-    var cmdName = aCommand.substring(gNC_NS_CMD.length);
-    return BookmarksUtils.getLocaleString ("cmd_" + cmdName);
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // Retrieve the access key for a particular command. Used when 
-  // manufacturing a UI to invoke commands.
-  getAccessKey: function (aCommand) 
-  {
-    var cmdName = aCommand.substring(gNC_NS_CMD.length);
-    return BookmarksUtils.getLocaleString ("cmd_" + cmdName + "_accesskey");
-  },
-  
-  ///////////////////////////////////////////////////////////////////////////
-  // Execute a command with the given source and arguments
-  doBookmarksCommand: function (aSource, aCommand, aArgumentsArray)
-  {
-    var rCommand = RDF.GetResource(aCommand);
-  
-    var kSuppArrayContractID = "@mozilla.org/supports-array;1";
-    var kSuppArrayIID = Components.interfaces.nsISupportsArray;
-    var sourcesArray = Components.classes[kSuppArrayContractID].createInstance(kSuppArrayIID);
-    if (aSource) {
-      sourcesArray.AppendElement(aSource);
-    }
-  
-    var argsArray = Components.classes[kSuppArrayContractID].createInstance(kSuppArrayIID);
-    var length = aArgumentsArray?aArgumentsArray.length:0;
-    for (var i = 0; i < length; ++i) {
-      var rArc = RDF.GetResource(aArgumentsArray[i].property);
-      argsArray.AppendElement(rArc);
-      var rValue = null;
-      if ("resource" in aArgumentsArray[i]) { 
-        rValue = RDF.GetResource(aArgumentsArray[i].resource);
-      }
-      else
-        rValue = RDF.GetLiteral(aArgumentsArray[i].literal);
-      argsArray.AppendElement(rValue);
-    }
-
-    // Exec the command in the Bookmarks datasource. 
-    BMDS.DoCommand(sourcesArray, rCommand, argsArray);
-  },
-
-  undoBookmarkTransaction: function ()
-  {
-    gBkmkTxnSvc.undo();
-    BookmarksUtils.refreshSearch();
-    BookmarksUtils.flushDataSource();
-  },
-
-  redoBookmarkTransaction: function ()
-  {
-    gBkmkTxnSvc.redo();
-    BookmarksUtils.refreshSearch();
-    BookmarksUtils.flushDataSource();
-  },
-
-  manageFolder: function (aSelection)
-  {
-    openDialog("chrome://browser/content/bookmarks/bookmarksManager.xul", 
-               "", "chrome,all,dialog=no", aSelection.item[0].Value);
-  },
-  
-  cutBookmark: function (aSelection)
-  {
-    this.copyBookmark(aSelection);
-    BookmarksUtils.removeAndCheckSelection("cut", aSelection);
-  },
-
-  copyBookmark: function (aSelection)
-  {
-    const kSuppArrayContractID = "@mozilla.org/supports-array;1";
-    const kSuppArrayIID = Components.interfaces.nsISupportsArray;
-    var itemArray = Components.classes[kSuppArrayContractID].createInstance(kSuppArrayIID);
-
-    const kSuppWStringContractID = "@mozilla.org/supports-string;1";
-    const kSuppWStringIID = Components.interfaces.nsISupportsString;
-    var bmstring = Components.classes[kSuppWStringContractID].createInstance(kSuppWStringIID);
-    var unicodestring = Components.classes[kSuppWStringContractID].createInstance(kSuppWStringIID);
-    var htmlstring = Components.classes[kSuppWStringContractID].createInstance(kSuppWStringIID);
-  
-    var sBookmarkItem = ""; var sTextUnicode = ""; var sTextHTML = ""; var tmpBmItem = [];
-    for (var i = 0; i < aSelection.length; ++i) {
-      sBookmarkItem += aSelection.item[i].Value + "\n";
-
-      // save the selection property into text string that we will use later in paste function
-      // and in INSERT tranasactions
-      // (if the selection is folder or livemark save all childs property)
-      var aType = BookmarksUtils.resolveType(aSelection.item[i]);
-      if (aType == "Livemark") {
-        sBookmarkItem += "\n\n\n\n\n\n\n\n\n"; // don't change livemark properties
-      } else {
-         for (var j = 0; j < gBmProperties.length; ++j) {
-            var itemValue = BMDS.GetTarget(aSelection.item[i], gBmProperties[j], true);
-            if (itemValue)
-                sBookmarkItem += itemValue.QueryInterface(kRDFLITIID).Value + "\n";
-            else
-                sBookmarkItem += "\n";
-         }
-      }
-      var childCount = 1;
-      if (aType == "Folder" || aType == "Livemark") {
-         var propArray = [];
-         BookmarksUtils.getAllChildren(aSelection.item[i], propArray);
-         for (var k = 0; k < propArray.length; ++k) {
-            for (var j = 0; j < gBmProperties.length + 1; ++j) {
-               if (propArray[k][j])
-                   sBookmarkItem += propArray[k][j].Value + "\n";
-               else
-                   sBookmarkItem += "\n";
-            }
-         }
-         childCount += propArray.length;
-      }
-      tmpBmItem.push(childCount +  "\n" + sBookmarkItem);
-      sBookmarkItem = "";
-
-      var url;
-      if (aType == "Livemark")
-        url = BookmarksUtils.getProperty(aSelection.item[i], gNC_NS+"FeedURL");
-      else
-        url = BookmarksUtils.getProperty(aSelection.item[i], gNC_NS+"URL");
-
-      var name = BookmarksUtils.getProperty(aSelection.item[i], gNC_NS+"Name");
-
-      sTextUnicode += url + "\n";
-      sTextHTML += "<A HREF=\"" + url + "\">" + name + "</A>";
-    }
-    sTextUnicode = sTextUnicode.replace(/\n$/,"");
-    
-    // generate unique separator and combine the array to one string 
-    var bmSeparator = "]-[", extrarSeparator = "@";
-    for (var i = 0; i < tmpBmItem.length; ++i) {
-        while (tmpBmItem[i].indexOf(bmSeparator)>-1)
-           bmSeparator += extrarSeparator;
-    }
-    for (var i = 0; i < tmpBmItem.length; ++i) {
-      sBookmarkItem += tmpBmItem[i] + bmSeparator;
-    }
-    // insert the separator to sBookmarkItem so we can extract it in pasteBookmark
-    sBookmarkItem = bmSeparator + "\n" + sBookmarkItem;
-    
-    const kXferableContractID = "@mozilla.org/widget/transferable;1";
-    const kXferableIID = Components.interfaces.nsITransferable;
-    var xferable = Components.classes[kXferableContractID].createInstance(kXferableIID);
-
-    xferable.addDataFlavor("moz/bookmarkclipboarditem");
-    bmstring.data = sBookmarkItem;
-    xferable.setTransferData("moz/bookmarkclipboarditem", bmstring, sBookmarkItem.length*2);
-    
-    xferable.addDataFlavor("text/html");
-    htmlstring.data = sTextHTML;
-    xferable.setTransferData("text/html", htmlstring, sTextHTML.length*2);
-    
-    xferable.addDataFlavor("text/unicode");
-    unicodestring.data = sTextUnicode;
-    xferable.setTransferData("text/unicode", unicodestring, sTextUnicode.length*2);
-    
-    const kClipboardContractID = "@mozilla.org/widget/clipboard;1";
-    const kClipboardIID = Components.interfaces.nsIClipboard;
-    var clipboard = Components.classes[kClipboardContractID].getService(kClipboardIID);
-    clipboard.setData(xferable, null, kClipboardIID.kGlobalClipboard);
-  },
-
-  pasteBookmark: function (aTarget)
-  {
-    const kXferableContractID = "@mozilla.org/widget/transferable;1";
-    const kXferableIID = Components.interfaces.nsITransferable;
-    var xferable = Components.classes[kXferableContractID].createInstance(kXferableIID);
-    xferable.addDataFlavor("moz/bookmarkclipboarditem");
-    xferable.addDataFlavor("text/x-moz-url");
-    xferable.addDataFlavor("text/unicode");
-
-    const kClipboardContractID = "@mozilla.org/widget/clipboard;1";
-    const kClipboardIID = Components.interfaces.nsIClipboard;
-    var clipboard = Components.classes[kClipboardContractID].getService(kClipboardIID);
-    clipboard.getData(xferable, kClipboardIID.kGlobalClipboard);
-    
-    var flavour = { };
-    var data    = { };
-    var length  = { };
-    xferable.getAnyTransferData(flavour, data, length);
-    var items, name, url, childs, removedProps = [];
-    data = data.value.QueryInterface(Components.interfaces.nsISupportsString).data;
-    switch (flavour.value) {
-    case "moz/bookmarkclipboarditem":
-      var tmpItem = data.split("\n");
-      var sep = tmpItem.shift();
-      data = tmpItem.join("\n");
-      items = data.split(sep);
-      // since data are ended by separator, remove the last empty node
-      items.pop(); 
-      // convert propery from text string to array
-      var p = gBmProperties.length+1;
-      for (var i = 0; i < items.length; ++i) {
-        childs = items[i].split("\n");
-        childs.pop();
-        var childCount = childs.shift();
-        items[i] = RDF.GetResource(childs[0]);
-        var propArray = [];
-        for (var k = 0; k < childCount; ++k) {
-          for (var j = 1; j < p; ++j) {
-             var prop = childs[p*k+j];
-             if (prop)
-                 propArray.push(RDF.GetLiteral(prop));
-             else
-                 propArray.push(null);
-          }
-        }
-        removedProps.push(propArray);
-      }
-      break;
-    case "text/x-moz-url":
-      // there should be only one item in this case
-      var ix = data.indexOf("\n");
-      items = data.substring(0, ix != -1 ? ix : data.length);
-      name  = data.substring(ix);
-      // XXX: we should infer the best charset
-      var createdBookmarkResource = BookmarksUtils.createBookmark(null, items, null, name, null);
-      items = [createdBookmarkResource];
-      break;
-    default: 
-      return;
-    }
-   
-    var selection = {item: items, parent:Array(items.length), length: items.length, prop: removedProps};
-    BookmarksUtils.checkSelection(selection);
-    BookmarksUtils.insertAndCheckSelection("paste", selection, aTarget, -1);
-  },
-  
-  deleteBookmark: function (aSelection)
-  {
-    // call checkSelection here to update the immutable and other
-    // flags on the selection; when new resources get created,
-    // they're temporarily not valid because they're not in a
-    // bookmark container.  So, they can't be removed until that's
-    // fixed.
-    BookmarksUtils.checkSelection(aSelection);
-    BookmarksUtils.removeAndCheckSelection("delete", aSelection);
-  },
-
-  moveBookmark: function (aSelection)
-  {
-    var rv = { selectedFolder: null };      
-    openDialog("chrome://browser/content/bookmarks/addBookmark.xul", "", 
-               "centerscreen,chrome,modal=yes,dialog=yes,resizable=yes", null, 
-               null, null, null, "selectFolder", rv);
-    if (!rv.target)
-      return;
-    BookmarksUtils.moveAndCheckSelection("move", aSelection, rv.target);
-  },
-
-  openBookmark: function (aSelection, aTargetBrowser, aDS) 
-  {
-    if (!aTargetBrowser)
-      return;
-
-    // in this case, we can just use |aSelection.length| as "Open in Tabs"
-    // is only available when you are only selecting multiple bookmarks
-    // if you selected a folder of bookmarks, we check the number of tabs in
-    // openGroupBookmark()
-    if (aTargetBrowser == "tab" && !this._confirmOpenTabs(aSelection.length))
-      return;
-
-    for (var i=0; i<aSelection.length; ++i) {
-      var type = aSelection.type[i];
-      if (aTargetBrowser == "save") {
-        this.saveBookmark(aSelection.item[i].Value, aDS);
-      }
-      else if (type == "Bookmark" || type == "ImmutableBookmark") {
-        var webPanel = BMDS.GetTarget(aSelection.item[i],
-                                      RDF.GetResource(gNC_NS + "WebPanel"),
-                                      true);
-        if (webPanel && aTargetBrowser == "current")
-          this.openWebPanel(aSelection.item[i].Value, aDS);
-        else
-          this.openOneBookmark(aSelection.item[i].Value, aTargetBrowser, aDS);
-      }
-      else if (type == "Folder" || type == "PersonalToolbarFolder" || type == "Livemark")
-        this.openGroupBookmark(aSelection.item[i].Value, aTargetBrowser);
-    }
-  },
-  
-  openBookmarkProperties: function (aSelection) 
-  {
-    // Bookmark Properties dialog is only ever opened with one selection 
-    // (command is disabled otherwise)
-    var bookmark = aSelection.item[0].Value;
-    var value = {};
-    openDialog("chrome://browser/content/bookmarks/bookmarksProperties.xul", "", "centerscreen,chrome,modal,resizable=no", bookmark, value);
-    return value.ok;
-  },
-
-  // requires utilityOverlay.js if opening in new window for getTopWin()
-  openWebPanel: function(aResource, aDS)
-  {
-    var url = BookmarksUtils.getProperty(aResource, gNC_NS+"URL", aDS);
-    // Ignore "NC:" and empty urls.
-    if (url == "")
-      return;
-    var w = getTopWin();
-    if (!w) {
-      openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no", url);
-      return;
-    }
-    w.openWebPanel(BookmarksUtils.getProperty(aResource,  gNC_NS+"Name"), url);
-  },
-
-  // requires contentAreaUtils.js because it calls saveURL
-  saveBookmark: function(aResource, aDS)
-  {
-    var url = BookmarksUtils.getProperty(aResource, gNC_NS+"URL", aDS);
-    // Ignore "NC:" and empty urls.
-    if (url == "")
-      return;
-    var fileName = BookmarksUtils.getProperty(aResource, gNC_NS+"Name", aDS);
-
-    saveURL(url, fileName, null, true); 
-  },
-
-  // requires utilityOverlay.js because it calls openUILinkIn
-  openOneBookmark: function (aURI, aTargetBrowser, aDS)
-  {
-    var url = BookmarksUtils.getProperty(aURI, gNC_NS+"URL", aDS);
-    // Ignore "NC:" and empty urls.
-    if (url == "")
-      return;
-
-    openUILinkIn(url, aTargetBrowser, false);
-  },
-
-  _confirmOpenTabs: function(numTabsToOpen) 
-  {
-    var reallyOpen = true;
-
-    const kWarnOnOpenPref = "browser.tabs.warnOnOpen";
-    if (PREF.getBoolPref(kWarnOnOpenPref))
-    {
-      if (numTabsToOpen >= PREF.getIntPref("browser.tabs.maxOpenBeforeWarn"))
-      {
-        var promptService = 
-            Components.classes["@mozilla.org/embedcomp/prompt-service;1"].
-            getService(Components.interfaces.nsIPromptService);
- 
-        // default to true: if it were false, we wouldn't get this far
-        var warnOnOpen = { value: true };
- 
-        var messageKey = "tabs.openWarningMultipleBranded";
-        var openKey = "tabs.openButtonMultiple";
-
-        var buttonPressed = promptService.confirmEx(window,
-            BookmarksUtils.getLocaleString("tabs.openWarningTitle"),
-            BookmarksUtils.getLocaleString(messageKey, 
-              [numTabsToOpen, BookmarksUtils._brandShortName]),
-            (promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0)
-            + (promptService.BUTTON_TITLE_CANCEL * promptService.BUTTON_POS_1),
-            BookmarksUtils.getLocaleString(openKey),
-            null, null,
-            BookmarksUtils.getLocaleString("tabs.openWarningPromptMeBranded",
-               [BookmarksUtils._brandShortName]),
-            warnOnOpen);
-
-         reallyOpen = (buttonPressed == 0);
-         // don't set the pref unless they press OK and it's false
-         if (reallyOpen && !warnOnOpen.value)
-           PREF.setBoolPref(kWarnOnOpenPref, false);
-       }
-    }
-    return reallyOpen;
-  },
-
-  openGroupBookmark: function (aURI, aTargetBrowser)
-  {
-    var w = getTopWin();
-    if (!w)
-      // no browser window is open, we have to open the group into a new window
-      aTargetBrowser = "window";
-
-    var resource = RDF.GetResource(aURI);
-    var urlArc   = RDF.GetResource(gNC_NS+"URL");
-    RDFC.Init(BMDS, resource);
-    var containerChildren = RDFC.GetElements();
-    var numTabsToOpen = 0;
-
-    // we can't just use |RDFC.GetCount()| as that might include
-    // folders, separators, deleted bookmarks, etc.
-    while (containerChildren.hasMoreElements()) {
-      var res = containerChildren.getNext().QueryInterface(kRDFRSCIID);
-      var type = BookmarksUtils.resolveType(res);
-      // these are the types in getCommands() that support the 
-      // "bm_openinnewwindow" and "bm_openinnewtab" commands
-      if (type == "Bookmark" || type == "LivemarkBookmark" || 
-          type == "ImmutableBookmark" || type == "IEFavorite" ||
-          type == "FileSystemObject")
-        numTabsToOpen++;
-    }
-
-    if (!this._confirmOpenTabs(numTabsToOpen))
-      return;
-
-    // counting the number of tabs to open modified the 
-    // containerChildren enumerator, so we need to reset it.
-    containerChildren = RDFC.GetElements();
-    if (aTargetBrowser == "current" || aTargetBrowser == "tab") {
-      var browser  = w.document.getElementById("content");
-      var tabPanels = browser.browsers;
-      var tabs = browser.mTabContainer.childNodes;
-      var tabCount  = tabPanels.length;
-      var doReplace = PREF.getBoolPref("browser.tabs.loadFolderAndReplace");
-      var loadInBackground = PREF.getBoolPref("browser.tabs.loadBookmarksInBackground");
-      var index0;
-      if (doReplace)
-        index0 = 0;
-      else {
-        for (index0=tabCount-1; index0>=0; --index0) {
-          var tab = tabPanels[index0];
-          if (tab.webNavigation.currentURI.spec != "about:blank" ||
-              tab.webProgress.isLoadingDocument)
-            break;
-        }
-        ++index0;
-      }
-
-      var index = index0;
-      while (containerChildren.hasMoreElements()) {
-        var res = containerChildren.getNext().QueryInterface(kRDFRSCIID);
-        var target = BMDS.GetTarget(res, urlArc, true);
-        if (target) {
-          var uri = target.QueryInterface(kRDFLITIID).Value;
-          if (index < tabCount)
-            tabPanels[index].loadURI(uri);
-          else {
-            // This is not a modal sub-action of a given tab/document within a window
-            // since opening a bookmarks group replaces all existing tabs in the window,
-            // closing extras. If this ever changes to be augmentative, this code will
-            // have to change to probably just use <tabbrowser>.loadTabs() which figures
-            // out whether or not owner should be set. 
-            browser.addTab(uri);
-          }
-          ++index;
-        }
-      }
-
-      // If the bookmark group was completely invalid, just bail.
-      if (index == index0)
-        return;
-
-      // focus the first tab if prefs say to
-      if (!loadInBackground || doReplace) {
-        // Select the first tab in the group.
-        // Set newly selected tab after quick timeout, otherwise hideous focus problems
-        // can occur because new presshell is not ready to handle events
-        function selectNewForegroundTab(browser, tab) {
-          browser.selectedTab = tab;
-        }
-        setTimeout(selectNewForegroundTab, 0, browser, tabs[index0]);
-      }
-
-      // Close any remaining open tabs that are left over.
-      // (Always skipped when we append tabs)
-      for (var i = tabCount-1; i >= index; --i)
-        browser.removeTab(tabs[i]);
-
-      // and focus the content
-      w.content.focus();
-
-    } else if (aTargetBrowser == "window") {
-      var URIs = [];
-
-      while (containerChildren.hasMoreElements()) {
-        var res = containerChildren.getNext().QueryInterface(kRDFRSCIID);
-        var target = BMDS.GetTarget(res, urlArc, true);
-        if (target)
-          URIs.push(target.QueryInterface(kRDFLITIID).Value);
-      }
-
-      openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no", URIs.join("|"));
-    }
-  },
-
-  createNewBookmark: function (aTarget)
-  {
-    var name     = BookmarksUtils.getLocaleString("ile_newbookmark");
-    var resource = BMSVC.createBookmark(name, "", "", "", "", null);
-    this.createNewResource(resource, aTarget, "newbookmark");
-  },
-
-  createNewLivemark: function (aTarget)
-  {
-    var name     = BookmarksUtils.getLocaleString("ile_newlivemark");
-    var resource = BMSVC.createLivemark(name, "", "", null);
-    this.createNewResource(resource, aTarget, "newlivemark");
-  },
-
-  createNewFolder: function (aTarget)
-  {
-    var name     = BookmarksUtils.getLocaleString("ile_newfolder");
-    var resource = BMSVC.createFolder(name);
-    this.createNewResource(resource, aTarget, "newfolder");
-    // temporary hack...
-    return resource;
-  },
-
-  createNewSeparator: function (aTarget)
-  {
-    var resource = BMSVC.createSeparator();
-    this.createNewResource(resource, aTarget, "newseparator");
-  },
-
-  createNewResource: function(aResource, aTarget, aTxnType)
-  {
-    var selection = BookmarksUtils.getSelectionFromResource(aResource, aTarget.parent);
-    var ok        = BookmarksUtils.insertAndCheckSelection(aTxnType, selection, aTarget, -1);
-    if (ok && aTxnType != "newseparator") {
-      ok = this.openBookmarkProperties(selection);
-      if (!ok)
-        BookmarksCommand.deleteBookmark(selection);
-    }
-  },
-
-  importBookmarks: function ()
-  {
-      // XXX: ifdef it to be non-modal (non-"sheet") on mac (see bug 259039)
-      var features = "modal,centerscreen,chrome,resizable=no";
-      window.fromFile = false;
-      window.openDialog("chrome://browser/content/migration/migration.xul", "migration", features, "bookmarks");
-      if(window.fromFile)
-      {
-        this.importBookmarksFromFile();
-      }
-  },
-
-  importBookmarksFromFile: function ()
-  {
-    ///transaction...
-    try {
-      const kFilePickerContractID = "@mozilla.org/filepicker;1";
-      const kFilePickerIID = Components.interfaces.nsIFilePicker;
-      const kFilePicker = Components.classes[kFilePickerContractID].createInstance(kFilePickerIID);
-    
-      const kTitle = BookmarksUtils.getLocaleString("SelectImport");
-      kFilePicker.init(window, kTitle, kFilePickerIID["modeOpen"]);
-      kFilePicker.appendFilters(kFilePickerIID.filterHTML | kFilePickerIID.filterAll);
-      var fileName;
-      if (kFilePicker.show() != kFilePickerIID.returnCancel) {
-        fileName = kFilePicker.file.path;
-        if (!fileName) return;
-      }
-      else return;
-    }
-    catch (e) {
-      return;
-    }
-    rTarget = RDF.GetResource("NC:BookmarksRoot");
-    RDFC.Init(BMDS, rTarget);
-    var countBefore = parseInt(BookmarksUtils.getProperty(rTarget, gRDF_NS+"nextVal"));
-    var args = [{ property: gNC_NS+"URL", literal: fileName}];
-    this.doBookmarksCommand(rTarget, gNC_NS_CMD+"import", args);
-    var countAfter = parseInt(BookmarksUtils.getProperty(rTarget, gRDF_NS+"nextVal"));
-
-    if (countAfter - countBefore > 1)
-      gBkmkTxnSvc.startBatch();
-    for (var index = countBefore; index < countAfter; index++) {
-      var nChildArc = RDFCU.IndexToOrdinalResource(index);
-      var rChild    = BMDS.GetTarget(rTarget, nChildArc, true);
-      gBkmkTxnSvc.createAndCommitTxn(gBkmkTxnSvc.IMPORT, "IMPORT", rChild, index,
-                                    rTarget, 0, null);
-    }
-    if (countAfter - countBefore > 1)
-      gBkmkTxnSvc.endBatch();
-
-    BookmarksUtils.flushDataSource();
-  },
-
-  exportBookmarks: function ()
-  {
-    try {
-      const kFilePickerContractID = "@mozilla.org/filepicker;1";
-      const kFilePickerIID = Components.interfaces.nsIFilePicker;
-      const kFilePicker = Components.classes[kFilePickerContractID].createInstance(kFilePickerIID);
-      
-      const kTitle = BookmarksUtils.getLocaleString("EnterExport");
-      kFilePicker.init(window, kTitle, kFilePickerIID["modeSave"]);
-      kFilePicker.appendFilters(kFilePickerIID.filterHTML | kFilePickerIID.filterAll);
-      kFilePicker.defaultString = "bookmarks.html";
-      var fileName;
-      if (kFilePicker.show() != kFilePickerIID.returnCancel) {
-        fileName = kFilePicker.file.path;
-        if (!fileName) return;
-      }
-      else return;
-
-      var file = Components.classes["@mozilla.org/file/local;1"]
-                           .createInstance(Components.interfaces.nsILocalFile);
-      if (!file)
-        return;
-      file.initWithPath(fileName);
-      if (!file.exists()) {
-        file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644);
-      }
-    }
-    catch (e) {
-      return;
-    }
-    var selection = RDF.GetResource("NC:BookmarksRoot");
-    var args = [{ property: gNC_NS+"URL", literal: fileName}];
-    this.doBookmarksCommand(selection, gNC_NS_CMD+"export", args);
-  },
-
-  refreshLivemark: function (aSelection)
-  {
-    var exp = RDF.GetResource(gNC_NS+"LivemarkExpiration");
-    for (var i = 0; i < aSelection.length; i++) {
-      rsrc = RDF.GetResource(aSelection.item[i].Value);
-      oldtgt = BMDS.GetTarget(rsrc, exp, true);
-      if (oldtgt) {
-        BMDS.Unassert(rsrc, exp, oldtgt);
-      }
-    }
-  },
-
-  refreshMicrosummary: function (aSelection)
-  {
-    for (var i = 0; i < aSelection.length; i++) {
-      rsrc = RDF.GetResource(aSelection.item[i].Value);
-      MICSUMSVC.refreshMicrosummary(rsrc);
-    }
-  },
-
-  sortByName: function (aSelection)
-  {
-    // do the real sorting in a timeout, to make sure that
-    // if we sort from a menu that the menu gets torn down
-    // before we sort.  the template builder really doesn't
-    // like it if we move things around; the menu code also
-    // doesn't like it if we move the menuparent while a
-    // popup is open.
-    setTimeout(function () { BookmarksCommand.realSortByName(aSelection); }, 0);
-  },
-
-  realSortByName: function (aSelection)
-  {
-    var theFolder;
-
-    if (aSelection.length != 1)
-      return;
-
-    var selType = BookmarksUtils.resolveType(aSelection.item[0]);
-    if (selType == "Folder" || selType == "Bookmark" ||
-        selType == "PersonalToolbarFolder" || selType == "Livemark")
-    {
-      theFolder = aSelection.parent[0];
-    } else {
-      // we're not going to try to sort ImmutableBookmark siblings or
-      // any other such thing, since it'll probably just get us into
-      // trouble
-      return;
-    }
-
-    var toSort = [];
-    RDFC.Init(BMDS, theFolder);
-    var folderContents = RDFC.GetElements();
-    while (folderContents.hasMoreElements()) {
-        var rsrc = folderContents.getNext().QueryInterface(kRDFRSCIID);
-        var rtype = BookmarksUtils.resolveType(rsrc);
-        if (rtype == "BookmarkSeparator")
-          continue;
-        toSort.push(rsrc);
-    }
-
-    const kName = RDF.GetResource(gNC_NS+"Name");
-
-    var localeService = Components.classes["@mozilla.org/intl/nslocaleservice;1"]
-                                  .getService(Components.interfaces.nsILocaleService);
-    var collationFactory = Components.classes["@mozilla.org/intl/collation-factory;1"]
-                                     .getService(Components.interfaces.nsICollationFactory);
-    var collation = collationFactory.CreateCollation(localeService.getApplicationLocale());
-
-    toSort.sort (function (a, b) {
-                   var atype = BookmarksUtils.resolveType(a);
-                   var btype = BookmarksUtils.resolveType(b);
-
-                   var aisfolder = (atype == "Folder") || (atype == "PersonalToolbarFolder");
-                   var bisfolder = (btype == "Folder") || (btype == "PersonalToolbarFolder");
-
-                   // folders above bookmarks
-                   if (aisfolder && !bisfolder)
-                     return -1;
-                   if (bisfolder && !aisfolder)
-                     return 1;
-
-                   // then sort by name
-                   var aname = BMDS.GetTarget(a, kName, true).QueryInterface(kRDFLITIID).Value;
-                   var bname = BMDS.GetTarget(b, kName, true).QueryInterface(kRDFLITIID).Value;
-
-                   return collation.compareString(0, aname, bname);
-                 });
-
-    // we now have the resources here sorted by name
-    BMDS.beginUpdateBatch();
-
-    RDFC.Init(BMDS, theFolder);
-
-    // remove existing elements
-    var folderContents = RDFC.GetElements();
-    while (folderContents.hasMoreElements()) {
-      RDFC.RemoveElement (folderContents.getNext(), false);
-    }
-
-    // and add our elements back
-    for (var i = 0; i < toSort.length; i++) {
-      RDFC.InsertElementAt (toSort[i], i+1, true);
-    }
-
-    BMDS.endUpdateBatch();
-  }
-
-}
-
-  /////////////////////////////////////////////////////////////////////////////
-  // Command handling & Updating.
-var BookmarksController = {
-
-  supportsCommand: function (aCommand)
-  {
-    var isCommandSupported;
-    switch(aCommand) {
-    case "cmd_undo":
-    case "cmd_redo":
-    case "cmd_bm_undo":
-    case "cmd_bm_redo":
-    case "cmd_cut":
-    case "cmd_copy":
-    case "cmd_paste":
-    case "cmd_delete":
-    case "cmd_selectAll":
-    case "cmd_bm_open":
-    case "cmd_bm_openinnewwindow":
-    case "cmd_bm_openinnewtab":
-    case "cmd_bm_openfolder":
-    case "cmd_bm_managefolder":
-    case "cmd_bm_newbookmark":
-    case "cmd_bm_newlivemark":
-    case "cmd_bm_newfolder":
-    case "cmd_bm_newseparator":
-    case "cmd_bm_properties":
-    case "cmd_bm_rename":
-    case "cmd_bm_setnewbookmarkfolder":
-    case "cmd_bm_setpersonaltoolbarfolder":
-    case "cmd_bm_setnewsearchfolder":
-    case "cmd_bm_import":
-    case "cmd_bm_export":
-    case "cmd_bm_movebookmark":
-    case "cmd_bm_refreshlivemark":
-    case "cmd_bm_refreshmicrosummary":
-    case "cmd_bm_sortbyname":
-      isCommandSupported = true;
-      break;
-    default:
-      isCommandSupported = false;
-    }
-    //if (!isCommandSupported)
-    //  dump("Bookmark command '"+aCommand+"' is not supported!\n");
-    return isCommandSupported;
-  },
-
-  isCommandEnabled: function (aCommand, aSelection, aTarget)
-  {
-    var item0, type0, junk, parent0, ptype0;
-    var length = 0;
-    if (aSelection && aSelection.length != 0) {
-      length = aSelection.length;
-      item0 = aSelection.item[0].Value;
-      type0 = aSelection.type[0];
-      parent0 =  (aSelection.parent[0] != null) ? aSelection.parent[0] : BMSVC.getParent(aSelection.item[0]);
-      ptype0 = BookmarksUtils.resolveType(parent0);
-    }
-    var i;
-
-    switch(aCommand) {
-    case "cmd_undo":
-    case "cmd_bm_undo":
-      return gBkmkTxnSvc.canUndo();
-    case "cmd_redo":
-    case "cmd_bm_redo":
-      return gBkmkTxnSvc.canRedo();
-    case "cmd_paste":
-      if (ptype0 == "Livemark" || (aTarget && !BookmarksUtils.isValidTargetContainer(aTarget.parent)))
-        return false;
-      const kClipboardContractID = "@mozilla.org/widget/clipboard;1";
-      const kClipboardIID = Components.interfaces.nsIClipboard;
-      var clipboard = Components.classes[kClipboardContractID].getService(kClipboardIID);
-      const kSuppArrayContractID = "@mozilla.org/supports-array;1";
-      const kSuppArrayIID = Components.interfaces.nsISupportsArray;
-      var flavourArray = Components.classes[kSuppArrayContractID].createInstance(kSuppArrayIID);
-      const kSuppStringContractID = "@mozilla.org/supports-cstring;1";
-      const kSuppStringIID = Components.interfaces.nsISupportsCString;
-    
-      var flavours = ["moz/bookmarkclipboarditem", "text/x-moz-url"];
-      for (i = 0; i < flavours.length; ++i) {
-        const kSuppString = Components.classes[kSuppStringContractID].createInstance(kSuppStringIID);
-        kSuppString.data = flavours[i];
-        flavourArray.AppendElement(kSuppString);
-      }
-      var hasFlavours = clipboard.hasDataMatchingFlavors(flavourArray, kClipboardIID.kGlobalClipboard);
-      return hasFlavours;
-    case "cmd_copy":
-      return length > 0;
-    case "cmd_cut":
-    case "cmd_delete":
-      return length > 0 && !aSelection.containsImmutable && ptype0 != "Livemark" && !aSelection.containsPTF;
-    case "cmd_selectAll":
-      return true;
-    case "cmd_bm_open":
-    case "cmd_bm_managefolder":
-      return length == 1;
-    case "cmd_bm_openinnewwindow":
-    case "cmd_bm_openinnewtab":
-      return true;
-    case "cmd_bm_openfolder":
-      for (i=0; i<length; ++i) {
-        if (aSelection.type[i] == "ImmutableBookmark" ||
-            aSelection.type[i] == "ImmutableFolder" ||
-            aSelection.type[i] == "Bookmark" ||
-            aSelection.type[i] == "BookmarkSeparator")
-          return false;
-        RDFC.Init(BMDS, aSelection.item[i]);
-        var children = RDFC.GetElements();
-        while (children.hasMoreElements()) {
-          var childType = BookmarksUtils.resolveType(children.getNext());
-          if (childType == "Bookmark" || childType == "LivemarkBookmark")
-            return true;
-        }
-      }
-      return false;
-    case "cmd_bm_import":
-    case "cmd_bm_export":
-      return true;
-    case "cmd_bm_newbookmark":
-    case "cmd_bm_newlivemark":
-    case "cmd_bm_newfolder":
-    case "cmd_bm_newseparator":
-      return (ptype0 != "Livemark" && ((type0 == "PersonalToolbarFolder") ||
-              (aTarget && BookmarksUtils.isValidTargetContainer(aTarget.parent))));
-    case "cmd_bm_properties":
-    case "cmd_bm_rename":
-      if (length != 1 ||
-          aSelection.item[0].Value == "NC:BookmarksRoot" ||
-          ptype0 == "Livemark")
-        return false;
-      return true;
-    case "cmd_bm_setpersonaltoolbarfolder":
-      if (length != 1 || type0 == "Livemark")
-        return false;
-      return item0 != BMSVC.getBookmarksToolbarFolder().Value && 
-             item0 != "NC:BookmarksRoot" && type0 == "Folder";
-    case "cmd_bm_movebookmark":
-      return length > 0 && !aSelection.containsImmutable && ptype0 != "Livemark";
-    case "cmd_bm_refreshlivemark":
-      for (i=0; i<length; ++i) {
-        if (aSelection.type[i] != "Livemark")
-          return false;
-      }
-      return length > 0;
-    case "cmd_bm_refreshmicrosummary":
-      for (i=0; i<length; ++i) {
-        if (!MICSUMSVC.hasMicrosummary(aSelection.item[i]))
-          return false;
-      }
-      return length > 0;
-    case "cmd_bm_sortbyname":
-      if (length == 1 && (aSelection.type[0] == "Folder" ||
-                          aSelection.type[0] == "Bookmark" ||
-                          aSelection.type[0] == "PersonalToolbarFolder" ||
-                          aSelection.type[0] == "Livemark"))
-        return true;
-      return false;
-    default:
-      return false;
-    }
-  },
-
-  doCommand: function (aCommand, aSelection, aTarget, aDS)
-  {
-    var resource0, type0, realTarget;
-    if (aSelection && aSelection.length == 1) {
-      resource0 = aSelection.item[0];
-      type0 = aSelection.type[0];
-    }
-
-    if (type0 == "PersonalToolbarFolder" && aTarget == null)
-      realTarget = { parent: resource0, index: -1 };
-    else
-      realTarget = aTarget;
-
-    switch (aCommand) {
-    case "cmd_undo":
-    case "cmd_bm_undo":
-      BookmarksCommand.undoBookmarkTransaction();
-      break;
-    case "cmd_redo":
-    case "cmd_bm_redo":
-      BookmarksCommand.redoBookmarkTransaction();
-      break;
-    case "cmd_bm_open":
-      BookmarksCommand.openBookmark(aSelection, "current", aDS);
-      break;
-    case "cmd_bm_openinnewwindow":
-      BookmarksCommand.openBookmark(aSelection, "window", aDS);
-      break;
-    case "cmd_bm_openinnewtab":
-      BookmarksCommand.openBookmark(aSelection, "tab", aDS);
-      break;
-    case "cmd_bm_openfolder":
-      BookmarksCommand.openBookmark(aSelection, "current", aDS);
-      break;
-    case "cmd_bm_managefolder":
-      BookmarksCommand.manageFolder(aSelection);
-      break;
-    case "cmd_bm_setnewbookmarkfolder":
-    case "cmd_bm_setpersonaltoolbarfolder":
-    case "cmd_bm_setnewsearchfolder":
-      BookmarksCommand.doBookmarksCommand(aSelection.item[0], gNC_NS_CMD+aCommand.substring("cmd_bm_".length), []);
-      break;
-    case "cmd_bm_rename":
-    case "cmd_bm_properties":
-      junk = BookmarksCommand.openBookmarkProperties(aSelection);
-      break;
-    case "cmd_cut":
-      BookmarksCommand.cutBookmark(aSelection);
-      break;
-    case "cmd_copy":
-      BookmarksCommand.copyBookmark(aSelection);
-      break;
-    case "cmd_paste":
-      BookmarksCommand.pasteBookmark(realTarget);
-      break;
-    case "cmd_delete":
-      BookmarksCommand.deleteBookmark(aSelection);
-      break;
-    case "cmd_bm_movebookmark":
-      BookmarksCommand.moveBookmark(aSelection);
-      break;
-    case "cmd_bm_newbookmark":
-      BookmarksCommand.createNewBookmark(realTarget);
-      break;
-    case "cmd_bm_newlivemark":
-      BookmarksCommand.createNewLivemark(realTarget);
-      break;
-    case "cmd_bm_newfolder":
-      BookmarksCommand.createNewFolder(realTarget);
-      break;
-    case "cmd_bm_newseparator":
-      BookmarksCommand.createNewSeparator(realTarget);
-      break;
-    case "cmd_bm_import":
-      BookmarksCommand.importBookmarks();
-      break;
-    case "cmd_bm_export":
-      BookmarksCommand.exportBookmarks();
-      break;
-    case "cmd_bm_refreshlivemark":
-      BookmarksCommand.refreshLivemark(aSelection);
-      break;
-    case "cmd_bm_refreshmicrosummary":
-      BookmarksCommand.refreshMicrosummary(aSelection);
-      break;
-    case "cmd_bm_sortbyname":
-      BookmarksCommand.sortByName(aSelection);
-      break;
-    default: 
-      dump("Bookmark command "+aCommand+" not handled!\n");
-    }
-
-  },
-
-  onCommandUpdate: function (aSelection, aTarget)
-  {
-    var commands = ["cmd_bm_newbookmark", "cmd_bm_newlivemark", "cmd_bm_newfolder", "cmd_bm_newseparator",
-                    "cmd_undo", "cmd_redo", "cmd_bm_properties", "cmd_bm_rename", 
-                    "cmd_copy", "cmd_paste", "cmd_cut", "cmd_delete",
-                    "cmd_bm_setpersonaltoolbarfolder", "cmd_bm_movebookmark",
-                    "cmd_bm_openfolder", "cmd_bm_managefolder", "cmd_bm_refreshlivemark",
-                    "cmd_bm_refreshmicrosummary", "cmd_bm_sortbyname"];
-    for (var i = 0; i < commands.length; ++i) {
-      var enabled = this.isCommandEnabled(commands[i], aSelection, aTarget);
-      var commandNode = document.getElementById(commands[i]);
-     if (commandNode) { 
-        if (enabled) 
-          commandNode.removeAttribute("disabled");
-        else 
-          commandNode.setAttribute("disabled", "true");
-      }
-    }
-  }
-}
-
-function CommandArrayEnumerator (aCommandArray)
-{
-  this._inner = [];
-  for (var i = 0; i < aCommandArray.length; ++i)
-    this._inner.push(RDF.GetResource(gNC_NS_CMD + aCommandArray[i]));
-    
-  this._index = 0;
-}
-
-CommandArrayEnumerator.prototype = {
-  getNext: function () 
-  {
-    return this._inner[this._index];
-  },
-  
-  hasMoreElements: function ()
-  {
-    return this._index < this._inner.length;
-  }
-};
-
-var BookmarksUtils = {
-
-  DROP_BEFORE: Components.interfaces.nsITreeView.DROP_BEFORE,
-  DROP_ON    : Components.interfaces.nsITreeView.DROP_ON,
-  DROP_AFTER : Components.interfaces.nsITreeView.DROP_AFTER,
-
-  _bundle        : null,
-  _brandShortName: null,
-
-  /////////////////////////////////////////////////////////////////////////////////////
-  // returns a property from chrome://browser/locale/bookmarks/bookmarks.properties
-  getLocaleString: function (aStringKey, aReplaceString)
-  {
-    if (!this._bundle) {
-      // for those who would xblify Bookmarks.js, there is a need to create string bundle 
-      // manually instead of using <xul:stringbundle/> see bug 63370 for details
-      var LOCALESVC = Components.classes["@mozilla.org/intl/nslocaleservice;1"]
-                                .getService(Components.interfaces.nsILocaleService);
-      var BUNDLESVC = Components.classes["@mozilla.org/intl/stringbundle;1"]
-                                .getService(Components.interfaces.nsIStringBundleService);
-      var bookmarksBundle  = "chrome://browser/locale/bookmarks/bookmarks.properties";
-      this._bundle         = BUNDLESVC.createBundle(bookmarksBundle, LOCALESVC.getApplicationLocale());
-      var brandBundle      = "chrome://branding/locale/brand.properties";
-      this._brandShortName = BUNDLESVC.createBundle(brandBundle,     LOCALESVC.getApplicationLocale())
-                                      .GetStringFromName("brandShortName");
-    }
-   
-    var bundle;
-    try {
-      if (!aReplaceString)
-        bundle = this._bundle.GetStringFromName(aStringKey);
-      else if (typeof(aReplaceString) == "string")
-        bundle = this._bundle.formatStringFromName(aStringKey, [aReplaceString], 1);
-      else
-        bundle = this._bundle.formatStringFromName(aStringKey, aReplaceString, aReplaceString.length);
-    } catch (e) {
-      dump("Bookmark bundle "+aStringKey+" not found!\n");
-      bundle = "";
-    }
-
-    bundle = bundle.replace(/%brandShortName%/, this._brandShortName);
-    return bundle;
-  },
-    
-  /////////////////////////////////////////////////////////////////////////////
-  // returns the literal targeted by the URI aArcURI for a resource or uri
-  getProperty: function (aInput, aArcURI, aDS)
-  {
-    var node;
-    var arc  = RDF.GetResource(aArcURI);
-    if (typeof(aInput) == "string") 
-      aInput = RDF.GetResource(aInput);
-    if (!aDS)
-      node = BMDS.GetTarget(aInput, arc, true);
-    else
-      node = aDS .GetTarget(aInput, arc, true);
-    try {
-      return node.QueryInterface(kRDFRSCIID).Value;
-    }
-    catch (e) {
-      return node? node.QueryInterface(kRDFLITIID).Value : "";
-    }    
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // Determine the rdf:type property for the given resource.
-  resolveType: function (aResource, aDS)
-  {
-    var type = this.getProperty(aResource, gRDF_NS+"type", aDS);
-    if (type != "")
-      type = type.split("#")[1];
-    if (type == "Folder") {
-      if (aResource == BMSVC.getBookmarksToolbarFolder())
-        type = "PersonalToolbarFolder";
-    }
-    // Treat microsummary bookmarks like regular bookmarks, since they behave
-    // like regular bookmarks in almost every regard.
-    if (type == "MicsumBookmark")
-      type = "Bookmark";
-
-    if (type == "") {
-      // we're not sure what type it is.  figure out if it's a container.
-      var child = this.getProperty(aResource, gNC_NS+"child", aDS);
-      if (child || RDFCU.IsContainer(aDS?aDS:BMDS, RDF.GetResource(aResource)))
-        return "ImmutableFolder";
-
-      // not a container; make sure it has at least a URL
-      if (this.getProperty(aResource, gNC_NS+"URL") != null)
-        return "ImmutableBookmark";
-    }
-
-    return type;
-  },
-
-  
-  /////////////////////////////////////////////////////////////////////////////
-  // Caches frequently used informations about the selection
-  checkSelection: function (aSelection)
-  {
-    if (aSelection.length == 0)
-      return;
-
-    aSelection.type        = new Array(aSelection.length);
-    aSelection.isContainer = new Array(aSelection.length);
-    aSelection.containsPTF = false;
-    aSelection.containsImmutable = false;
-    var index, item, parent, type, ptype, protocol, isContainer, isImmutable;
-    for (var i=0; i<aSelection.length; ++i) {
-      item        = aSelection.item[i];
-      parent      = aSelection.parent[i];
-      type        = BookmarksUtils.resolveType(item);
-      protocol    = item.Value.split(":")[0];
-      isContainer = RDFCU.IsContainer(BMDS, item) ||
-                    protocol == "find" || protocol == "file";
-      isImmutable = false;
-      if (item.Value == "NC:BookmarksRoot") {
-        isImmutable = true;
-      }
-      else if (type != "Bookmark" && type != "BookmarkSeparator" && 
-               type != "Folder"   && type != "PersonalToolbarFolder" &&
-               type != "Livemark")
-        isImmutable = true;
-      else if (parent) {
-        var ptype = BookmarksUtils.resolveType(parent);
-        if (ptype == "Livemark")
-          isImmutable = true;
-        var parentProtocol = parent.Value.split(":")[0];
-        if (parentProtocol == "find" || parentProtocol == "file")
-          aSelection.parent[i] = null;
-      }
-      if (isImmutable)
-        aSelection.containsImmutable = true;
-
-      aSelection.type       [i] = type;
-      aSelection.isContainer[i] = isContainer;
-    }
-    if (this.isContainerChildOrSelf(BMSVC.getBookmarksToolbarFolder(), aSelection))
-      aSelection.containsPTF = true;
-  },
-
-  isSelectionValidForInsertion: function (aSelection, aTarget)
-  {
-    return BookmarksUtils.isValidTargetContainer(aTarget.parent, aSelection)
-  },
-
-  isSelectionValidForDeletion: function (aSelection)
-  {
-    return !aSelection.containsImmutable && !aSelection.containsPTF;
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // Returns true is aContainer is a member or a child of the selection
-  isContainerChildOrSelf: function (aContainer, aSelection)
-  {
-    var folder = aContainer;
-    do {
-      for (var i=0; i<aSelection.length; ++i) {
-        if (aSelection.isContainer[i] && aSelection.item[i].Value == folder.Value)
-          return true;
-      }
-      folder = BMSVC.getParent(folder);
-      if (!folder)
-        return false; // sanity check
-    } while (folder.Value != "NC:BookmarksRoot")
-    return false;
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // Returns true if aSelection can be inserted in aFolder
-  isValidTargetContainer: function (aFolder, aSelection)
-  {
-    if (!aFolder)
-      return false;
-    if (aFolder.Value == "NC:BookmarksTopRoot")
-      return false;
-    if (aFolder.Value == "NC:BookmarksRoot")
-      return true;
-
-    // don't insert items in an invalid container
-    // 'file:' and 'find:' items have a 'Bookmark' type
-    var type = BookmarksUtils.resolveType(aFolder);
-    if (type != "Folder" && type != "PersonalToolbarFolder")
-      return false;
-
-    // bail if we just check the container
-    if (!aSelection)
-      return true;
-
-    // check that the selected folder is not the selected item nor its child
-    if (this.isContainerChildOrSelf(aFolder, aSelection))
-      return false;
-
-    return true;
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  removeAndCheckSelection: function (aAction, aSelection)
-  {
-    var isValid = BookmarksUtils.isSelectionValidForDeletion(aSelection);
-    if (!isValid) {
-      SOUND.beep();
-      return false;
-    }
-    this.removeSelection(aAction, aSelection);
-    BookmarksUtils.flushDataSource();
-    BookmarksUtils.refreshSearch();
-    return true;
-  },
-
-  removeSelection: function (aAction, aSelection)
-  {
-    if (aSelection.length > 1)
-      gBkmkTxnSvc.startBatch();
-    if (aSelection.length > kBATCH_LIMIT && aAction != "move")
-      BMDS.beginUpdateBatch();
-
-    for (var i = 0; i < aSelection.length; ++i) {
-      // try to put back aSelection.parent[i] if it's null, so we can delete after searching
-      if (aSelection.parent[i] == null)
-          aSelection.parent[i] = BMDS.getParent(aSelection.item[i]);
-
-      if (aSelection.parent[i]) {
-        RDFC.Init(BMDS, aSelection.parent[i]);
-
-        // save the selection property into array that is used later in
-        // when performing the REMOVE transaction
-        // (if the selection is folder save all childs property)
-        var propArray;
-        if (aAction != "move") {
-            propArray = new Array(gBmProperties.length);
-            var aType = BookmarksUtils.resolveType(aSelection.item[i]);            
-            if (aType != "Livemark") {// don't change livemark properties
-               for (var j = 0; j < gBmProperties.length; ++j) {
-                  var oldValue = BMDS.GetTarget(aSelection.item[i], gBmProperties[j], true);
-                  if (oldValue)
-                      propArray[j] = oldValue.QueryInterface(kRDFLITIID);
-               }
-            }
-            if (aType == "Folder" || aType == "Livemark")
-                BookmarksUtils.getAllChildren(aSelection.item[i], propArray);
-        }
-
-        var proplength = propArray ? propArray.length : 0;
-        gBkmkTxnSvc.createAndCommitTxn(gBkmkTxnSvc.REMOVE, aAction, 
-                                       aSelection.item[i], 
-                                       RDFC.IndexOf(aSelection.item[i]),
-                                       aSelection.parent[i], 
-                                       proplength, propArray);
-      }
-    }
-    if (aSelection.length > 1)
-      gBkmkTxnSvc.endBatch();
-    if (aSelection.length > kBATCH_LIMIT && aAction != "move")
-      BMDS.endUpdateBatch();
-    return true;
-  },
-
-  //  this recursive function return array of all childrens properties for given folder
-  getAllChildren: function (folder, propArray)
-  {
-    var container = Components.classes[kRDFCContractID].createInstance(kRDFCIID);
-    container.Init(BMDS, folder);
-    var children = container.GetElements();
-    while (children.hasMoreElements()){
-      var child = children.getNext() ;
-      if (child instanceof Components.interfaces.nsIRDFResource){
-         var aType = BookmarksUtils.resolveType(child);
-         var childResource = child.QueryInterface(kRDFRSCIID);
-         var props = new Array(gBmProperties.length);
-         // don't change livemark properties
-         if (aType != "Livemark") {
-            for (var j = 0; j < gBmProperties.length; ++j) {
-               var oldValue = BMDS.GetTarget(childResource, gBmProperties[j], true);
-               if (oldValue)
-                   props[(j)] = oldValue.QueryInterface(kRDFLITIID);
-            }
-         }
-         propArray.push(props);
-         if (aType == "Folder" || aType == "Livemark")
-             BookmarksUtils.getAllChildren(child, propArray);
-      }
-    }
-  },
-
-  // if we are in search mode i.e. "find:" is in ref attribute we refresh the Search
-  refreshSearch: function ()
-  {
-   var bmTree, bmView = document.getElementById("bookmarks-view");
-   if (bmView) bmTree = bmView.tree;
-   else return;
-   var aRef = bmTree.getAttribute("ref");
-   var aProtocol = aRef.split(":")[0];
-   if (aProtocol == "find"){
-      bmTree.setAttribute("ref", "");
-      bmTree.setAttribute("ref", aRef);
-   }
-  },
-        
-  insertAndCheckSelection: function (aAction, aSelection, aTarget, aTargetIndex)
-  {
-    var isValid = BookmarksUtils.isSelectionValidForInsertion(aSelection, aTarget);
-    if (!isValid) {
-      SOUND.beep();
-      return false;
-    }
-    this.insertSelection(aAction, aSelection, aTarget, aTargetIndex);
-    BookmarksUtils.flushDataSource();
-    BookmarksUtils.refreshSearch();
-    return true;
-  },
-
-  insertSelection: function (aAction, aSelection, aTarget, aTargetIndex)
-  {
-    var item, removedProps;
-    var index = aTarget.index;
-    var brokenIndex = aTarget.index;
-
-    if (aSelection.length > 1)
-      gBkmkTxnSvc.startBatch();
-    if (aSelection.length > kBATCH_LIMIT && aAction != "move")
-      BMDS.beginUpdateBatch();
-
-    for (var i=0; i<aSelection.length; ++i) {
-      var rSource = aSelection.item[i];
-      if (BMSVC.isBookmarkedResource(rSource))
-        rSource = BMSVC.cloneResource(rSource);
-      item = rSource;
-      // we only have aSelection.prop if insertSelection call by paste action we don't use it for move
-      removedProps = aSelection.prop ? aSelection.prop[i] : null;
-      // Broken Insert Code attempts to always insert items in the
-      // right place (i.e. after the selected item).  However, because
-      // of RDF Container suckyness, this code gets very confused, due
-      // to rdf container indexes not matching up to number of items,
-      // and because we can't trust GetCount to return a real count.
-      // The -1 is there to handle inserting into the persontal toolbar
-      // folder via right-click on the PTF.
-      if (aTarget.index == -1) {
-        index = -1;
-      } else {
-#ifdef BROKEN_INSERT_CODE
-        if (aTargetIndex == -1)
-          index = (++brokenIndex);
-        else
-          index = (brokenIndex++);
-#else
-      index = brokenIndex++;
-#endif
-      }
-      var proplength = removedProps ? removedProps.length : 0;
-      gBkmkTxnSvc.createAndCommitTxn(gBkmkTxnSvc.INSERT, aAction, item, index,
-                                     aTarget.parent, proplength, removedProps);
-    }
-    if (aSelection.length > 1)
-      gBkmkTxnSvc.endBatch();
-    if (aSelection.length > kBATCH_LIMIT && aAction != "move")
-      BMDS.endUpdateBatch();
-  },
-
-  moveAndCheckSelection: function (aAction, aSelection, aTarget)
-  {
-    var isValid = BookmarksUtils.isSelectionValidForDeletion(aSelection) &&
-                  BookmarksUtils.isSelectionValidForInsertion(aSelection, aTarget);
-    if (!isValid) {
-      SOUND.beep();
-      return false;
-    }
-    this.moveSelection(aAction, aSelection, aTarget);
-    BookmarksUtils.flushDataSource();
-    return true;
-  },
-
-  moveSelection: function (aAction, aSelection, aTarget)
-  {
-    if (aSelection.length > kBATCH_LIMIT)
-      BMDS.beginUpdateBatch();
-
-    gBkmkTxnSvc.startBatch();
-    BookmarksUtils.removeSelection("move", aSelection);
-    BookmarksUtils.insertSelection("move", aSelection, aTarget);
-    gBkmkTxnSvc.endBatch();
-    if (aSelection.length > kBATCH_LIMIT)
-      BMDS.endUpdateBatch();
-  }, 
-
-  // returns true if this selection should be copied instead of moved,
-  // if a move was originally requested
-  shouldCopySelection: function (aAction, aSelection)
-  {
-    for (var i = 0; i < aSelection.length; i++) {
-      var parentType = BookmarksUtils.resolveType(aSelection.parent[i]);
-      if (aSelection.type[i] == "ImmutableBookmark" ||
-          aSelection.type[i] == "ImmutableFolder" ||
-          aSelection.parent[i] == null ||
-          (aSelection.type[i] == "Bookmark" && parentType == "Livemark"))
-      {
-        return true;            // if any of these are found
-      }
-    }
-
-    return false;
-  },
-
-  getXferDataFromSelection: function (aSelection)
-  {
-    if (aSelection.length == 0)
-      return null;
-    var dataSet = new TransferDataSet();
-    var data, item, itemUrl, itemName, parent, name;
-    for (var i=0; i<aSelection.length; ++i) {
-      data     = new TransferData();
-      item     = aSelection.item[i].Value;
-      itemUrl  = this.getProperty(item, gNC_NS+"URL");
-      itemName = this.getProperty(item, gNC_NS+"Name");
-      parent   = aSelection.parent[i].Value;
-      data.addDataForFlavour("moz/rdfitem",    item+"\n"+(parent?parent:""));
-      data.addDataForFlavour("text/x-moz-url", itemUrl+"\n"+itemName);
-      data.addDataForFlavour("text/html",      "<A HREF='"+itemUrl+"'>"+itemName+"</A>");
-      data.addDataForFlavour("text/unicode",   itemUrl);
-      dataSet.push(data);
-    }
-    return dataSet;
-  },
-
-  getSelectionFromXferData: function (aDragSession)
-  {
-    var selection    = {};
-    selection.item   = [];
-    selection.parent = [];
-    var trans = Components.classes["@mozilla.org/widget/transferable;1"]
-                          .createInstance(Components.interfaces.nsITransferable);
-    trans.addDataFlavor("moz/rdfitem");
-    trans.addDataFlavor("text/x-moz-url");
-    trans.addDataFlavor("text/unicode");
-    var uri, extra, rSource, rParent, parent;
-    for (var i = 0; i < aDragSession.numDropItems; ++i) {
-      var bestFlavour = {}, dataObj = {}, len = {};
-      aDragSession.getData(trans, i);
-      trans.getAnyTransferData(bestFlavour, dataObj, len);
-      dataObj = dataObj.value.QueryInterface(Components.interfaces.nsISupportsString);
-      if (!dataObj)
-        continue;
-      dataObj = dataObj.data.substring(0, len.value).split("\n");
-      uri     = dataObj[0];
-      if (dataObj.length > 1 && dataObj[1] != "")
-        extra = dataObj[1];
-      else
-        extra = null;
-      switch (bestFlavour.value) {
-      case "moz/rdfitem":
-        rSource = RDF.GetResource(uri);
-        parent  = extra;
-        break;
-      case "text/x-moz-url":
-      case "text/unicode":
-        rSource = BookmarksUtils.createBookmark(null, uri, null, extra, null);
-        parent = null;
-        break;
-      }
-      selection.item.push(rSource);
-      if (parent)
-        rParent = RDF.GetResource(parent);
-      else
-        rParent = null;
-      selection.parent.push(rParent);
-    }
-    selection.length = selection.item.length;
-    BookmarksUtils.checkSelection(selection);
-    return selection;
-  },
-
-  getTargetFromFolder: function(aResource)
-  {
-    var index = parseInt(this.getProperty(aResource, gRDF_NS+"nextVal"));
-    if (isNaN(index))
-      return {parent: null, index: -1};
-    else
-      return {parent: aResource, index: index};
-  },
-
-  getSelectionFromResource: function (aItem, aParent)
-  {
-    var selection    = {};
-    selection.length = 1;
-    selection.item   = [aItem  ];
-    selection.parent = [aParent];
-    this.checkSelection(selection);
-    return selection;
-  },
-
-  getTitleForURLFromHistory: function(aURL, aDefaultName)
-  {
-#ifndef MOZ_PLACES
-    // look up in the history ds to retrieve the name
-    var rSource = RDF.GetResource(aURL);
-    var HISTDS  = RDF.GetDataSource("rdf:history");
-    var nameArc = RDF.GetResource(gNC_NS+"Name");
-    var rName   = HISTDS.GetTarget(rSource, nameArc, true);
-    return (rName ? rName.QueryInterface(kRDFLITIID).Value : aDefaultName);
-#else
-    var histsvc = 
-      Components.classes["@mozilla.org/browser/nav-history-service;1"]
-                .getService(Components.interfaces.nsINavHistoryService);
-
-    // query for the URL
-    var options = histsvc.getNewQueryOptions();
-    options.resultType = options.RESULTS_AS_URI;
-    var query = histsvc.getNewQuery();
-    query.uri = IOSVC.newURI(aURL, null, null);
-    var result = histsvc.executeQuery(query, options);
-    var root = result.root;
-    root.containerOpen = true;
-    var cc = root.childCount;
-    for (var i=0; i < cc; ++i) { 
-      var node = root.getChild(i);
-      if (node.title)
-        return node.title;
-    }
-
-    return (aDefaultName ? aDefaultName : aURL);
-#endif
-  },
-
-  createBookmark: function (aName, aURL, aCharSet, aDefaultName)
-  {
-    if (!aName)
-      aName = this.getTitleForURLFromHistory(aURL, aDefaultName);
-
-    if (!aCharSet) {
-      var fw = document.commandDispatcher.focusedWindow;
-      if (fw)
-        aCharSet = fw.document.characterSet;
-    }
-    return BMSVC.createBookmark(aName, aURL, null, null, aCharSet, null);
-  },
-
-  flushDataSource: function ()
-  {
-    var remoteDS = BMDS.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
-    setTimeout(function () {remoteDS.Flush()}, 100);
-  },
-
-  addBookmark: function (aURL, aTitle, aCharset, aIsWebPanel, aDescription)
-  {
-    var dArgs = {
-      name: aTitle,
-      url: aURL,
-      charset: aCharset,
-      bWebPanel: aIsWebPanel,
-      description: aDescription
-    }
-    openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "",
-               ADD_BM_DIALOG_FEATURES, dArgs);
-  },
- 
-  addLivemark: function (aURL, aFeedURL, aTitle, aDescription)
-  {
-    var dArgs = {
-      name: aTitle,
-      url: aURL,
-      bWebPanel: false,
-      feedURL: aFeedURL,
-      description: aDescription
-    };
-    try {
-      var toolbarFolderURI = BMDS.getBookmarksToolbarFolder().Value;
-      dArgs.folderURI = toolbarFolderURI;
-    }
-    catch (e) { 
-    }
-    openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "",
-               ADD_BM_DIALOG_FEATURES, dArgs);
-  },
- 
-  getDescriptionFromDocument: function (aDocument) {
-    var metaElements = aDocument.getElementsByTagName('META');
-    for (var m = 0; m < metaElements.length; m++) {
-      if (metaElements[m].name.toLowerCase() == 'description' || metaElements[m].httpEquiv.toLowerCase() == 'description')
-        return metaElements[m].content;
-    }
-    return '';
-  },
- 
-  loadFavIcon: function (aURL, aFavIconURL) {
-    if (!RDF || !BMSVC)
-      return;
- 
-    var urlLiteral = RDF.GetLiteral(aURL);
-    // don't do anything if this URI isn't bookmarked
-    var bmResources = BMSVC.GetSources(RDF.GetResource(gNC_NS+"URL"), urlLiteral, true);
-    var toUpdate = 0;
-
-    while (bmResources.hasMoreElements()) {
-      var bmResource = bmResources.getNext();
- 
-      // don't flag this as needing update if it already has a data: icon url set
-      var oldIcon = BMDS.GetTarget(bmResource, RDF.GetResource(gNC_NS+"Icon"), true);
-      if (oldIcon && (oldIcon.QueryInterface(kRDFLITIID).Value.substring(0,5) == "data:"))
-        continue;
-
-      toUpdate++;
-    }
-
-    if (toUpdate == 0)
-      return;
-
-    var chan = IOSVC.newChannel(aFavIconURL, null, null);
-    var listener = new bookmarksFavIconLoadListener (aURL, aFavIconURL, chan);
-    chan.notificationCallbacks = listener;
-    chan.asyncOpen(listener, null);
-  }
-}
-
-var BookmarkEditMenuTxnListener =
-{
-  didDo: function (aTxmgr, aTxn)
-  {
-    this.updateMenuItem(aTxmgr, aTxn);
-  },
-
-  didUndo: function (aTxmgr, aTxn)
-  {
-    this.updateMenuItem(aTxmgr, aTxn);
-  },
-
-  didRedo: function (aTxmgr, aTxn)
-  {
-    this.updateMenuItem(aTxmgr, aTxn);
-  },
-
-  didMerge       : function (aTxmgr, aTxn) {},
-  didBeginBatch  : function (aTxmgr, aTxn) {},
-  didEndBatch    : function (aTxmgr, aTxn) {
-    this.updateMenuItem(aTxmgr, aTxn);
-  },
-  willDo         : function (aTxmgr, aTxn) {},
-  willUndo       : function (aTxmgr, aTxn) {},
-  willRedo       : function (aTxmgr, aTxn) {},
-  willMerge      : function (aTxmgr, aTxn) {},
-  willBeginBatch : function (aTxmgr, aTxn) {},
-  willEndBatch   : function (aTxmgr, aTxn) {},
-
-  updateMenuItem: function bkmkMenuListenerUpdate(aTxmgr, aTxn) {
-    var node, transactionNumber, transactionList, transactionLabel, action, item;
-    node = document.getElementById("cmd_undo");
-    transactionNumber = aTxmgr.numberOfUndoItems;
-    dump("N UNDO: "+transactionNumber+"\n");
-    if (transactionNumber == 0) {
-      transactionLabel = BookmarksUtils.getLocaleString("cmd_bm_undo");
-    } else {
-      transactionList  = aTxmgr.getUndoList();
-      if (!transactionList.itemIsBatch(transactionNumber-1)) {
-        item = transactionList.getItem(transactionNumber-1);
-        action = item.wrappedJSObject.action;
-      } else {
-        var childList = transactionList.getChildListForItem(transactionNumber-1);
-        item = childList.getItem(0);
-        action = item.wrappedJSObject.action;
-      }
-      transactionLabel = BookmarksUtils.getLocaleString("cmd_bm_"+action+"_undo");
-    }
-    node.setAttribute("label", transactionLabel);
-      
-    node = document.getElementById("cmd_redo");
-    transactionNumber = aTxmgr.numberOfRedoItems;
-    dump("N REDO: "+transactionNumber+"\n");
-    if (transactionNumber == 0) {
-      transactionLabel = BookmarksUtils.getLocaleString("cmd_bm_redo");
-    } else {
-      transactionList  = aTxmgr.getRedoList();
-      if (!transactionList.itemIsBatch(transactionNumber-1)) {
-        item = transactionList.getItem(transactionNumber-1);
-        action = item.wrappedJSObject.action;
-      } else {
-        var childList = transactionList.getChildListForItem(transactionNumber-1);
-        item = childList.getItem(0);
-        action = item.wrappedJSObject.action;
-      }
-      transactionLabel = BookmarksUtils.getLocaleString("cmd_bm_"+action+"_redo");
-    }
-    node.setAttribute("label", transactionLabel);
-  }
-}
-
-// favicon loaders
-
-function bookmarksFavIconLoadListener(uri, faviconurl, channel) {
-  this.mURI = uri;
-  this.mFavIconURL = faviconurl;
-  this.mCountRead = 0;
-  this.mChannel = channel;
-}
-
-bookmarksFavIconLoadListener.prototype = {
-  mURI : null,
-  mFavIconURL : null,
-  mCountRead : null,
-  mChannel : null,
-  mBytes : Array(),
-  mStream : null,
-
-  QueryInterface: function (iid) {
-    if (!iid.equals(Components.interfaces.nsISupports) &&
-        !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
-        !iid.equals(Components.interfaces.nsIRequestObserver) &&
-        !iid.equals(Components.interfaces.nsIChannelEventSink) &&
-        !iid.equals(Components.interfaces.nsIProgressEventSink) && // see below
-        !iid.equals(Components.interfaces.nsIStreamListener)) {
-      throw Components.results.NS_ERROR_NO_INTERFACE;
-    }
-    return this;
-  },
-
-  // nsIInterfaceRequestor
-  getInterface: function (iid) {
-    try {
-      return this.QueryInterface(iid);
-    } catch (e) {
-      throw Components.results.NS_NOINTERFACE;
-    }
-  },
-
-  // nsIRequestObserver
-  onStartRequest : function (aRequest, aContext) {
-    this.mStream = Components.classes['@mozilla.org/binaryinputstream;1'].createInstance(Components.interfaces.nsIBinaryInputStream);
-  },
-
-  onStopRequest : function (aRequest, aContext, aStatusCode) {
-    var httpChannel = this.mChannel.QueryInterface(Components.interfaces.nsIHttpChannel);
-    if ((httpChannel && httpChannel.requestSucceeded) &&
-        Components.isSuccessCode(aStatusCode) &&
-        this.mCountRead > 0)
-    {
-      var dataurl;
-      // XXX - arbitrary size beyond which we won't store a favicon.  This is /extremely/
-      // generous, and is probably too high.
-      if (this.mCountRead > 16384) {
-        dataurl = "data:";      // hack meaning "pretend this doesn't exist"
-      } else {
-        // get us a mime type for this
-        var mimeType = null;
-
-        const nsICategoryManager = Components.interfaces.nsICategoryManager;
-        const nsIContentSniffer = Components.interfaces.nsIContentSniffer;
-
-        var catMgr = Components.classes["@mozilla.org/categorymanager;1"].getService(nsICategoryManager);
-        var sniffers = catMgr.enumerateCategory("content-sniffing-services");
-        while (mimeType == null && sniffers.hasMoreElements()) {
-          var snifferCID = sniffers.getNext().QueryInterface(Components.interfaces.nsISupportsCString).toString();
-          var sniffer = Components.classes[snifferCID].getService(nsIContentSniffer);
-
-          try {
-            mimeType = sniffer.getMIMETypeFromContent (aRequest, this.mBytes, this.mCountRead);
-          } catch (e) {
-            mimeType = null;
-            // ignore
-          }
-        }
-      }
-
-      if (mimeType == null) {
-        BMSVC.updateBookmarkIcon(this.mURI, null, null, 0);
-      } else {
-        BMSVC.updateBookmarkIcon(this.mURI, mimeType, this.mBytes, this.mCountRead);
-      }
-    }
-
-    this.mChannel = null;
-  },
-
-  // nsIStreamObserver
-  onDataAvailable : function (aRequest, aContext, aInputStream, aOffset, aCount) {
-    // we could get a different aInputStream, so we don't save this;
-    // it's unlikely we'll get more than one onDataAvailable for a
-    // favicon anyway
-    this.mStream.setInputStream(aInputStream);
-
-    var chunk = this.mStream.readByteArray(aCount);
-    this.mBytes = this.mBytes.concat(chunk);
-    this.mCountRead += aCount;
-  },
-
-  // nsIChannelEventSink
-  onChannelRedirect : function (aOldChannel, aNewChannel, aFlags) {
-    this.mChannel = aNewChannel;
-  },
-
-  // nsIProgressEventSink: the only reason we support
-  // nsIProgressEventSink is to shut up a whole slew of xpconnect
-  // warnings in debug builds.  (see bug #253127)
-  onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
-  onStatus : function (aRequest, aContext, aStatus, aStatusArg) { }
-}
-
-#ifdef 0
-
-var _dumpTIME;
-function dumpTIME(aString)
-{
-  var now=Date.now();
-  dump(aString);
-  if (_dumpTIME)
-    dump(now-_dumpTIME+'ms\n');
-  else
-    _dumpTIME = now;
-}
-
-function dumpOBJ (aObj) 
-{
-  if (!aObj)
-    dump("*** null object\n");
-  for (var i in aObj) {
-    dump("*** aObj[" + i + "] = ");
-    try {
-      dump(aObj[i] + "\n");
-    } catch (e) { 
-      dump("*** not available\n")
-    }
-  }
-}
-
-function dumpDOM (aElement, aIndent)
-{
-  if (!aElement)
-    return;
-  if (typeof(aElement) == "string")
-    aElement = document.getElementById(aElement);
-
-  if (!aIndent)
-    aIndent = 0;
-  for (var i=0; i<aIndent*2; ++i)
-    dump("-");
-  dump("-> ");
-  dump(aElement.localName+ " ("+aElement.id+') "'+aElement.getAttribute("class")+'"\n');
-  var element = aElement.firstChild;
-  while (element) {
-    dumpDOM(element,++aIndent);
-    --aIndent;
-    element = element.nextSibling;
-  }
-}
-
-function dumpRDF (aDS, aRDFNode)
-{
-  dumpRDFOut(aDS, aRDFNode);
-  dump("\n");
-  dumpRDFIn (aDS, aRDFNode);
-}
-
-function dumpRDFOut (aDS, aRDFNode)
-{
-  dump("Arcs Out for "+aRDFNode.Value+"\n");
-  var arcsout=aDS.ArcLabelsOut(aRDFNode);
-  while (arcsout.hasMoreElements()) {
-    var arc = arcsout.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
-    var targets = aDS.GetTargets(aRDFNode, arc, true);
-    while (targets.hasMoreElements()) {
-      var target = targets.getNext();
-      try {
-        target = target.QueryInterface(Components.interfaces.nsIRDFResource).Value;
-      } catch (e) {
-        try {
-          target = target.QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
-        } catch (e) {}
-      }
-      dump("=>"+arc.Value+"=>"+target+"\n");
-    }
-  }
-}
-function dumpRDFIn (aDS, aRDFNode)
-{
-  dump("Arcs In for "+aRDFNode.Value+"\n");
-  var arcs=aDS.ArcLabelsIn(aRDFNode);
-  while (arcs.hasMoreElements()) {
-    var arc = arcs.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
-    var sources = aDS.GetSources(arc, aRDFNode, true);
-    while (sources.hasMoreElements()) {
-      var source = sources.getNext();
-      try {
-        source = source.QueryInterface(Components.interfaces.nsIRDFResource).Value;
-      } catch (e) {
-        try {
-          source = source.QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
-        } catch (e) {}
-      }
-      dump("<="+arc.Value+"<="+source+"\n");
-    }
-  }
-}
-
-function dumpTXN(aTxn)
-{
-  aTxn = aTxn.wrappedJSObject;
-  dump(aTxn.type+", "+aTxn.action+"\n");
-  if (aTxn.type == "insert" || aTxn.type == "remove") {
-    for (var i=0; i<aTxn.item.length; ++i) {
-      dump(i+": "+aTxn.item[i].Value+" in "+BookmarksUtils.getProperty(aTxn.parent[i], gNC_NS+"Name")+", i:"+aTxn.index[i]+"\n");
-    }
-  }
-}
-#endif
deleted file mode 100644
--- a/browser/components/bookmarks/content/bookmarksManager.js
+++ /dev/null
@@ -1,274 +0,0 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- 
-# 
-# ***** 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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Ben Goodger <ben@netscape.com> (Original Author, v3.0)
-#   Pierre Chanial <chanial@noos.fr>
-#
-# 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 *****
-
-var gSearchBox;
-
-////////////////////////////////////////////////////////////////////////////////
-// Initialize the command controllers, set focus, tree root, 
-// window title state, etc. 
-function Startup()
-{
-  const windowNode = document.getElementById("bookmark-window");
-  const bookmarksView = document.getElementById("bookmarks-view");
-  const bookmarksFolder = document.getElementById("bookmark-folders-view");
-
-  var titleString;
-
-  // If we've been opened with a parameter, root the tree on it.
-  if ("arguments" in window && window.arguments[0]) {
-    var title;
-    var uri = window.arguments[0];
-    bookmarksView.tree.setAttribute("ref", uri);
-    bookmarksFolder.setAttribute("hidden","true")
-    document.getElementById("bookmarks-search").setAttribute("hidden","true")
-    document.getElementById("bookmark-views-splitter").setAttribute("hidden","true")    
-    if (uri.substring(0,5) == "find:") {
-      title = BookmarksUtils.getLocaleString("search_results_title");
-      // Update the windowtype so that future searches are directed 
-      // there and the window is not re-used for bookmarks. 
-      windowNode.setAttribute("windowtype", "bookmarks:searchresults");
-    }
-    else
-      title = BookmarksUtils.getProperty(window.arguments[0], gNC_NS+"Name");
-    
-    titleString = BookmarksUtils.getLocaleString("window_title", title);
-  }
-  else {
-    titleString = BookmarksUtils.getLocaleString("bookmarks_title", title);
-    // always open the bookmark root folder
-    if (!bookmarksFolder.treeBoxObject.view.isContainerOpen(0))
-      bookmarksFolder.treeBoxObject.view.toggleOpenState(0);
-    bookmarksFolder.treeBoxObject.view.selection.select(0);
-  }
-
-  bookmarksView.treeBoxObject.view.selection.select(0);
-
-  document.title = titleString;
-
-  document.getElementById("CommandUpdate_Bookmarks").setAttribute("commandupdater","true");
-  bookmarksView.focus();
-
-  var bkmkTxnSvc = Components.classes["@mozilla.org/bookmarks/transactionmanager;1"]
-                             .getService(Components.interfaces.nsIBookmarkTransactionManager);
-  bkmkTxnSvc.transactionManager.AddListener(BookmarkEditMenuTxnListener);
-
-}
-
-function Shutdown()
-{
-  var bkmkTxnSvc = Components.classes["@mozilla.org/bookmarks/transactionmanager;1"]
-                             .getService(Components.interfaces.nsIBookmarkTransactionManager);
-  bkmkTxnSvc.transactionManager.RemoveListener(BookmarkEditMenuTxnListener);
-  // Store current window position and size in window attributes (for persistence).
-  var win = document.getElementById("bookmark-window");
-  win.setAttribute("x", screenX);
-  win.setAttribute("y", screenY);
-  win.setAttribute("height", outerHeight);
-  win.setAttribute("width", outerWidth);
-}
-
-var gConstructedViewMenuSortItems = false;
-function fillViewMenu(aEvent)
-{
-  var adjacentElement = document.getElementById("fill-before-this-node");
-  var popupElement = aEvent.target;
-  
-  var bookmarksView = document.getElementById("bookmarks-view");
-  var columns = bookmarksView.columns;
-
-  if (!gConstructedViewMenuSortItems) {
-    const kViewMenuSortedPrefix = "view.sortBy.";
-    for (var i = 0; i < columns.length; ++i) {
-      var menuitem  = document.createElement("menuitem");
-      var accesskey = BookmarksUtils.getLocaleString(kViewMenuSortedPrefix +
-                                                     columns[i].id + ".accesskey");
-      var label     = BookmarksUtils.getLocaleString(kViewMenuSortedPrefix +
-                                                     columns[i].id + ".label");
-      menuitem.setAttribute("label", label);
-      menuitem.setAttribute("accesskey", accesskey);
-      menuitem.setAttribute("resource", columns[i].resource);
-      menuitem.setAttribute("id", "sortMenuItem:" + columns[i].resource);
-      menuitem.setAttribute("checked", columns[i].sortActive);
-      menuitem.setAttribute("name", "sortSet");
-      menuitem.setAttribute("type", "radio");
-      
-      popupElement.insertBefore(menuitem, adjacentElement);
-    }
-    
-    gConstructedViewMenuSortItems = true;
-  }  
-
-  const kPrefSvcContractID = "@mozilla.org/preferences-service;1";
-  const kPrefSvcIID = Components.interfaces.nsIPrefService;
-  var prefSvc = Components.classes[kPrefSvcContractID].getService(kPrefSvcIID);
-  var bookmarksSortPrefs = prefSvc.getBranch("browser.bookmarks.sort.");
-
-  if (gConstructedViewMenuSortItems) {
-    var resource = bookmarksSortPrefs.getCharPref("resource");
-    var element = document.getElementById("sortMenuItem:" + resource);
-    if (element)
-      element.setAttribute("checked", "true");
-  }  
-
-  var sortAscendingMenu = document.getElementById("ascending");
-  var sortDescendingMenu = document.getElementById("descending");
-  var noSortMenu = document.getElementById("natural");
-  
-  sortAscendingMenu.setAttribute("checked", "false");
-  sortDescendingMenu.setAttribute("checked", "false");
-  noSortMenu.setAttribute("checked", "false");
-  var direction = bookmarksSortPrefs.getCharPref("direction");
-  if (direction == "natural")
-    sortAscendingMenu.setAttribute("checked", "true");
-  else if (direction == "ascending") 
-    sortDescendingMenu.setAttribute("checked", "true");
-  else
-    noSortMenu.setAttribute("checked", "true");
-}
-
-function onViewMenuSortItemSelected(aEvent)
-{
-  var resource = aEvent.target.getAttribute("resource");
-  
-  const kPrefSvcContractID = "@mozilla.org/preferences-service;1";
-  const kPrefSvcIID = Components.interfaces.nsIPrefService;
-  var prefSvc = Components.classes[kPrefSvcContractID].getService(kPrefSvcIID);
-  var bookmarksSortPrefs = prefSvc.getBranch("browser.bookmarks.sort.");
-
-  switch (resource) {
-  case "":
-    break;
-  case "direction":
-    var dirn = bookmarksSortPrefs.getCharPref("direction");
-    if (aEvent.target.id == "ascending")
-      bookmarksSortPrefs.setCharPref("direction", "natural");
-    else if (aEvent.target.id == "descending")
-      bookmarksSortPrefs.setCharPref("direction", "ascending");
-    else
-      bookmarksSortPrefs.setCharPref("direction", "descending");
-    break;
-  default:
-    bookmarksSortPrefs.setCharPref("resource", resource);
-    var direction = bookmarksSortPrefs.getCharPref("direction");
-    if (direction == "descending")
-      bookmarksSortPrefs.setCharPref("direction", "natural");
-    break;
-  }
-
-  aEvent.stopPropagation();
-}  
-
-var gConstructedColumnsMenuItems = false;
-function fillColumnsMenu(aEvent) 
-{
-  var bookmarksView = document.getElementById("bookmarks-view");
-  var columns = bookmarksView.columns;
-  var i;
-
-  if (!gConstructedColumnsMenuItems) {
-    for (i = 0; i < columns.length; ++i) {
-      var menuitem = document.createElement("menuitem");
-      menuitem.setAttribute("label", columns[i].label);
-      menuitem.setAttribute("resource", columns[i].resource);
-      menuitem.setAttribute("id", "columnMenuItem:" + columns[i].resource);
-      menuitem.setAttribute("type", "checkbox");
-      menuitem.setAttribute("checked", columns[i].hidden != "true");
-      aEvent.target.appendChild(menuitem);
-    }
-
-    gConstructedColumnsMenuItems = true;
-  }
-  else {
-    for (i = 0; i < columns.length; ++i) {
-      var element = document.getElementById("columnMenuItem:" + columns[i].resource);
-      if (element && columns[i].hidden != "true")
-        element.setAttribute("checked", "true");
-    }
-  }
-  
-  aEvent.stopPropagation();
-}
-
-function onViewMenuColumnItemSelected(aEvent)
-{
-  var resource = aEvent.target.getAttribute("resource");
-  if (resource != "") {
-    var bookmarksView = document.getElementById("bookmarks-view");
-    bookmarksView.toggleColumnVisibility(resource);
-  }  
-
-  aEvent.stopPropagation();
-}
-
-function onViewSelected(aEvent)
-{
-  var statusBar = document.getElementById("statusbar-text");
-  var displayValue;
-  var selection = aEvent.target.getTreeSelection();
-  var bookmarksView = document.getElementById("bookmarks-view");
-
-  if (selection.length == 0)
-      return;
-
-  if (aEvent.target.id == "bookmark-folders-view" && selection)
-    bookmarksView.tree.setAttribute("ref",selection.item[0].Value);
-      
-  if (statusBar && selection.length == 1) {
-    //protocol broken since we have unique ID...
-    //var protocol = selection.protocol[0];
-    if (selection.isContainer[0]) {// && protocol != "find" && protocol != "file") {
-      RDFC.Init(aEvent.target.db, selection.item[0]);
-      var count = 0;
-      var children = RDFC.GetElements();
-      while (children.hasMoreElements()) {
-        if (BookmarksUtils.resolveType(children.getNext()) != "BookmarkSeparator")
-          count++;
-      }
-
-      displayValue = BookmarksUtils.getLocaleString("status_foldercount", String(count));
-    }
-    else if (selection.type[0] == "Bookmark")
-      displayValue = BookmarksUtils.getProperty(selection.item[0], gNC_NS+"URL", aEvent.target.db)
-    else
-      displayValue = "";
-    statusBar.label = displayValue;
-  }
-}
-
deleted file mode 100644
--- a/browser/components/bookmarks/content/bookmarksManager.xul
+++ /dev/null
@@ -1,253 +0,0 @@
-<?xml version="1.0"?>
-
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Ben Goodger <ben@netscape.com>
-#   Blake Ross <blaker@netscape.com>
-#   Dean Tessman <dean_tessman@hotmail.com>
-#   Pierre Chanial <chanial@noos.fr>
-#
-# 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 *****
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/skin/bookmarks/bookmarksManager.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/content/bookmarks/bookmarks.css" type="text/css"?>
-<?xul-overlay href="chrome://global/content/editMenuOverlay.xul"?>
-<?xul-overlay href="chrome://browser/content/baseMenuOverlay.xul"?>
-<!DOCTYPE window SYSTEM "chrome://browser/locale/bookmarks/bookmarks.dtd">
-
-<window id="bookmark-window" windowtype="bookmarks:manager"
-        title="&bookmarksWindowTitle.label;"
-        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-        xmlns:web="http://home.netscape.com/WEB-rdf#"
-        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        width="630" height="400" screenX="20" screenY="20"
-        persist="width height screenX screenY sizemode"
-        onload="Startup();" onunload="Shutdown();"
-        onclose="return closeWindow(false);">
-
-  <script type="application/x-javascript" src="chrome://global/content/globalOverlay.js"/>
-  <script type="application/x-javascript" src="chrome://global/content/nsDragAndDrop.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/utilityOverlay.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/bookmarks.js"/>
-  <script type="application/x-javascript" src="chrome://browser/content/bookmarks/bookmarksManager.js"/>
-
-  <stringbundleset id="stringbundleset"/>
-
-  <commandset id="editMenuCommands"/>
-  <commandset id="CommandUpdate_Bookmarks"
-              events="focus,tree-select"
-              oncommandupdate="document.getElementById('bookmarks-view').onCommandUpdate();">
-  </commandset>
-
-  <command id="cmd_close" oncommand="closeWindow(true);"/>
-  <command id="cmd_bm_open"                      oncommand="goDoCommand('cmd_bm_open');"/>
-  <command id="cmd_bm_openinnewwindow"           oncommand="goDoCommand('cmd_bm_openinnewwindow');"/>
-  <command id="cmd_bm_openinnewtab"              oncommand="goDoCommand('cmd_bm_openinnewtab');"/>
-  <command id="cmd_bm_openfolder"                oncommand="goDoCommand('cmd_bm_openfolder');"/>
-  <command id="cmd_bm_managefolder"              oncommand="goDoCommand('cmd_bm_managefolder');"/>
-  <command id="cmd_bm_newfolder"                 oncommand="goDoCommand('cmd_bm_newfolder');"/>
-  <command id="cmd_bm_newbookmark"               oncommand="goDoCommand('cmd_bm_newbookmark');"/>
-  <command id="cmd_bm_newlivemark"               oncommand="goDoCommand('cmd_bm_newlivemark');"/>
-  <command id="cmd_bm_newseparator"              oncommand="goDoCommand('cmd_bm_newseparator');"/>
-  <command id="cmd_bm_find"                      oncommand="goDoCommand('cmd_bm_find');"/>
-  <command id="cmd_bm_setnewbookmarkfolder"      oncommand="goDoCommand('cmd_bm_setnewbookmarkfolder');"/>
-  <command id="cmd_bm_setpersonaltoolbarfolder"  oncommand="goDoCommand('cmd_bm_setpersonaltoolbarfolder');"/>
-  <command id="cmd_bm_setnewsearchfolder"        oncommand="goDoCommand('cmd_bm_setnewsearchfolder');"/>
-  <command id="cmd_bm_refreshlivemark"           oncommand="goDoCommand('cmd_bm_refreshlivemark');"/>
-  <command id="cmd_bm_refreshmicrosummary"       oncommand="goDoCommand('cmd_bm_refreshmicrosummary');"/>
-  <command id="cmd_bm_properties"                oncommand="goDoCommand('cmd_bm_properties');"/>
-  <command id="cmd_bm_rename"                    oncommand="goDoCommand('cmd_bm_rename');"/>
-  <command id="cmd_bm_import"                    oncommand="goDoCommand('cmd_bm_import');"/>
-  <command id="cmd_bm_export"                    oncommand="goDoCommand('cmd_bm_export');"/>
-  <command id="cmd_bm_movebookmark"              oncommand="goDoCommand('cmd_bm_movebookmark');"/>
-  <command id="cmd_bm_sortbyname"                oncommand="goDoCommand('cmd_bm_sortbyname');"/>
-
-  <keyset id="editMenuKeys"/>
-  <keyset id="bookmarksManagerKeys">
-    <key id="key_close" key="&closeCmd.commandkey;" modifiers="accel" command="cmd_close"/>
-    <key keycode="VK_ESCAPE" command="cmd_close"/>
-    <key id="bm_key_find" key="&edit.find.keybinding;" modifiers="accel" command="cmd_bm_find"/>
-    <key id="bm_key_properties" key="&edit.properties.keybinding;" modifiers="accel" command="cmd_bm_properties"/>
-#ifdef XP_MACOSX
-    <key id="key_delete2" keycode="VK_BACK" command="cmd_delete"/>
-#endif
-  </keyset>
-
-  <commandset id="baseMenuCommandSet" />
-  <keyset id="baseMenuKeyset" />
-
-  <toolbox id="bookmarks-toolbox">
-    <menubar id="main-menubar">
-      <menu label="&fileMenu.label;" accesskey="&fileMenu.accesskey;">
-        <menupopup>
-          <menuitem label="&menuitem.newBookmark.label;" 
-                    accesskey="&menuitem.newBookmark.accesskey;"
-                    command="cmd_bm_newbookmark"/>
-          <menuitem label="&menuitem.newLivemark.label;" 
-                    accesskey="&menuitem.newLivemark.accesskey;"
-                    command="cmd_bm_newlivemark"/>
-          <menuitem label="&menuitem.newFolder.label;" 
-                    accesskey="&menuitem.newFolder.accesskey;"
-                    command="cmd_bm_newfolder"/>
-          <menuitem label="&menuitem.newSeparator.label;"
-                    accesskey="&menuitem.newSeparator.accesskey;"
-                    command="cmd_bm_newseparator"/>
-          <menuseparator/>
-          <menuitem label="&menuitem.import.label;"
-                    accesskey="&menuitem.import.accesskey;"
-                    command="cmd_bm_import"/>
-          <menuitem label="&menuitem.export.label;"
-                    accesskey="&menuitem.export.accesskey;"
-                    command="cmd_bm_export"/>
-          <menuseparator/>
-          <menuitem label="&closeCmd.label;" command="cmd_close"
-                    key="key_close" accesskey="&closeCmd.accesskey;"/>
-        </menupopup>
-      </menu>
-
-      <menu id="menu_edit">
-        <menupopup>
-          <menuitem id="menu_undo"/>
-          <menuitem id="menu_redo"/>
-          <menuseparator/>
-          <menuitem id="menu_cut"/>
-          <menuitem id="menu_copy"/>
-          <menuitem id="menu_paste"/>
-          <menuitem id="menu_delete"/>
-          <menuseparator/>
-          <menuitem id="menu_selectAll"/>
-          <menuseparator/>
-          <menuitem label="&command.moveBookmark.label;"
-                    accesskey="&command.moveBookmark.accesskey;"
-                    command="cmd_bm_movebookmark"/>
-          <menuitem label="&menuitem.personaltoolbarfolder.label;"
-                    command="cmd_bm_setpersonaltoolbarfolder"
-                    accesskey="&menuitem.personaltoolbarfolder.accesskey;"/>
-          <menuseparator/>
-          <menuitem label="&command.refreshLivemark.label;"
-                    accesskey="&command.refreshLivemark.accesskey;"
-                    command="cmd_bm_refreshlivemark"/>
-          <menuseparator/>
-          <menuitem label="&command.properties.label;"
-                    key="bm_key_properties" accesskey="&command.properties.accesskey;"
-                    command="cmd_bm_properties"/>
-        </menupopup>
-      </menu>
-  
-      <menu label="&viewMenu.label;" accesskey="&viewMenu.accesskey;">
-        <menupopup onpopupshowing="fillViewMenu(event)"
-                   oncommand="onViewMenuSortItemSelected(event);">
-          <menuitem id="viewCommandToolbar" type="checkbox" class="menuitem-iconic"
-                    label="&menuitem.view.command.toolbar.label;"
-                    accesskey="&menuitem.view.command.toolbar.accesskey;"
-                    oncommand="goToggleToolbar('command-toolbar', 'viewCommandToolbar'); event.stopPropagation();"
-                    checked="true"/>
-          <menu id="descending" label="&menuitem.view.show_columns.label;"
-                accesskey="&menuitem.view.show_columns.accesskey;">
-            <menupopup id="columnsPopup" onpopupshowing="fillColumnsMenu(event);"
-                       oncommand="onViewMenuColumnItemSelected(event);"/>
-          </menu>
-          <menuseparator id="fill-after-this-node"/>
-          <menuitem id="natural" label="&menuitem.view.unsorted.label;"
-                    accesskey="&menuitem.view.unsorted.accesskey;"
-                    type="radio"
-                    resource="direction" name="sortSet"/>
-          <menuseparator id="fill-before-this-node"/>
-          <menuitem id="ascending" label="&sortAscending.label;"
-                    accesskey="&sortAscending.accesskey;"
-                    type="radio"
-                    resource="direction" name="sortDirectionSet"/>
-          <menuitem id="descending" label="&sortDescending.label;"
-                    accesskey="&sortDescending.accesskey;"
-                    type="radio"
-                    resource="direction" name="sortDirectionSet"/>
-        </menupopup>
-      </menu>
-#ifdef XP_MACOSX
-      <menu id="windowMenu"/>
-      <menupopup id="menu_ToolsPopup"/>
-#endif
-      <menu id="helpMenu"/>
-    </menubar>
-
-    <toolbar id="command-toolbar" class="chromeclass-toolbar">
-      <toolbarbutton id="newbookmark" label="&menuitem.newBookmark.label;"
-                     accesskey="&menuitem.newBookmark.accesskey;"
-                     command="cmd_bm_newbookmark"/>
-      <toolbarbutton id="newfolder" label="&menuitem.newFolder.label;"
-                     accesskey="&menuitem.newFolder.accesskey;"
-                     command="cmd_bm_newfolder"/>
-      <toolbarbutton id="newseparator" label="&menuitem.newSeparator.label;" 
-                     accesskey="&menuitem.newSeparator.accesskey;"
-                     command="cmd_bm_newseparator"/>
-      <toolbarseparator/>
-      <toolbarbutton id="moveBookmark" label="&command.moveBookmarkShort.label;"
-                     accesskey="&command.moveBookmark.accesskey;"
-                     command="cmd_bm_movebookmark"/>
-      <toolbarseparator/>
-      <toolbarbutton id="properties" label="&command.properties.label;"
-                     accesskey="&command.properties.accesskey;"
-                     command="cmd_bm_properties"/>
-      <toolbarbutton id="rename" label="&command.rename.label;"
-                     accesskey="&command.rename.accesskey;"
-                     command="cmd_bm_rename"/>
-      <toolbarbutton id="delete" label="&command.delete.label;"
-                     accesskey="&command.delete.accesskey;"
-                     command="cmd_delete"/>
-    </toolbar>
-
-    <toolbar id="bookmarks-search" align="center" pack="center">
-      <label value="&search.label;" accesskey="&search.accesskey;" control="search-box"/>
-      <textbox id="search-box" flex="1"
-               type="timed" timeout="500"
-               oncommand="document.getElementById('bookmarks-view').searchBookmarks(this.value)"/>
-    </toolbar>
-  </toolbox>
-
-  <hbox flex="1">
-    <bookmarks-tree id="bookmark-folders-view" type="folders" flex="1" 
-                    persist="width" onselect="onViewSelected(event);"/>
-    <splitter id="bookmark-views-splitter" collapse="before" persist="state">
-      <grippy/>
-    </splitter>
-    <bookmarks-tree id="bookmarks-view" flex="4" persist="width" 
-                    onselect="onViewSelected(event);"/>
-  </hbox>
-  <statusbar id="statusbar">
-    <statusbarpanel id="statusbar-text" flex="1"/>
-  </statusbar>
-
-</window>
-
deleted file mode 100644
--- a/browser/components/bookmarks/content/bookmarksMenu.js
+++ /dev/null
@@ -1,1096 +0,0 @@
-# -*- Mode: Java; 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
-# Pierre Chanial <chanial@noos.fr>.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   David Hyatt <hyatt@apple.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-var BookmarksMenu = {
-  _selection:null,
-  _target:null,
-  _orientation:null,
-
-  /////////////////////////////////////////////////////////////////////////////
-  // prepare the bookmarks menu for display
-  onShowMenu: function (aTarget)
-  {
-    this.showOpenInTabsMenuItem(aTarget);
-    this.showEmptyItem(aTarget);
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // remove arbitary elements created in this.onShowMenu()
-  onHideMenu: function (aTarget)
-  {
-    this.hideOpenInTabsMenuItem(aTarget);
-    this.hideEmptyItem(aTarget);
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // shows the 'Open All in Tabs' menu item if validOpenInTabsMenuItem is true -->
-  showOpenInTabsMenuItem: function (aTarget)
-  {
-    if (!this.validOpenInTabsMenuItem(aTarget) ||
-        aTarget.lastChild.getAttribute("class") == "openintabs-menuitem")
-      return;
-    var element = document.createElementNS(gXUL_NS, "menuseparator");
-    element.setAttribute("class", "openintabs-menuseparator");
-    aTarget.appendChild(element);
-    element = document.createElementNS(gXUL_NS, "menuitem");
-    element.setAttribute("class", "openintabs-menuitem");
-    element.setAttribute("label", BookmarksUtils.getLocaleString("cmd_bm_openfolder"));
-    element.setAttribute("accesskey", BookmarksUtils.getLocaleString("cmd_bm_openfolder_accesskey"));
-    aTarget.appendChild(element);
-  },
-
-  realHideOpenInTabsMenuItem: function (aParent)
-  {
-    if (!aParent.hasChildNodes())
-      return;
-    var child = aParent.lastChild;
-    var removed = 0;
-    while (child) {
-      var cclass = child.getAttribute("class");
-      if (cclass == "openintabs-menuitem" || cclass == "openintabs-menuseparator") {
-        var prevchild = child.previousSibling;
-        aParent.removeChild(child);
-        child = prevchild;
-        removed++;
-        if (removed == 2)
-          break;
-      } else {
-        child = child.previousSibling;
-      }
-    }
-  },
-
-#ifdef XP_MACOSX
-  // FIXME: Work around a Mac menu bug with onpopuphidden.  onpopuphiding/hidden on mac fire
-  // before oncommand executes on a menuitem.  For now we're applying a XUL workaround
-  // since it's too late to fix this in the Mac widget code for 1.5.
-  hideOpenInTabsMenuItem: function (aTarget)
-  {
-    setTimeout(function() { BookmarksMenu.realHideOpenInTabsMenuItem(aTarget); }, 0);
-  },
-#else
-  /////////////////////////////////////////////////////////////////////////////
-  // hides the 'Open All in Tabs' on popuphidden so that we won't duplicate it -->
-  hideOpenInTabsMenuItem: function (aTarget)
-  {
-    BookmarksMenu.realHideOpenInTabsMenuItem(aTarget);
-  },
-#endif
-
-  /////////////////////////////////////////////////////////////////////////////
-  // returns false if...
-  // - the parent is the bookmark menu or the chevron
-  // - the menupopup contains ony one bookmark
-  validOpenInTabsMenuItem: function (aTarget)
-  {
-    var rParent = RDF.GetResource(aTarget.parentNode.id)
-    var type = BookmarksUtils.resolveType(rParent);
-    if (type != "Folder" && type != "PersonalToolbarFolder" && type != "Livemark")
-      return false;
-    var count = 0;
-    if (!aTarget.hasChildNodes())
-      return false;
-    var curr = aTarget.firstChild;
-    do {
-      type = BookmarksUtils.resolveType(curr.id);
-      if (type == "Bookmark" && ++count == 2)
-        return true;
-      curr = curr.nextSibling;
-    } while (curr);
-    return false;
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // show an empty item if the menu is empty
-  showEmptyItem: function (aTarget)
-  {
-    if(aTarget.hasChildNodes())
-      return;
-
-    var EmptyMsg = BookmarksUtils.getLocaleString("emptyFolder");
-    var emptyElement = document.createElementNS(gXUL_NS, "menuitem");
-    emptyElement.setAttribute("id", "empty-menuitem");
-    emptyElement.setAttribute("label", EmptyMsg);
-    emptyElement.setAttribute("disabled", "true");
-
-    aTarget.appendChild(emptyElement);
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // remove the empty element
-  hideEmptyItem: function (aTarget)
-  {
-    if (!aTarget.hasChildNodes())
-      return;
-
-    // if the user drags to the menu while it's open (i.e. on the toolbar),
-    // the bookmark gets added either before or after the Empty menu item
-    // before the menu is hidden.  So we need to test both first and last.
-    if (aTarget.firstChild.id == "empty-menuitem")
-      aTarget.removeChild(aTarget.firstChild);
-    else if (aTarget.lastChild.id == "empty-menuitem")
-      aTarget.removeChild(aTarget.lastChild);
-  },
-
-  //////////////////////////////////////////////////////////////////////////
-  // Fill a context menu popup with menuitems appropriate for the current
-  // selection.
-  createContextMenu: function (aEvent)
-  {
-    var target = document.popupNode;
-
-    if (!this.isBTBookmark(target.id)) {
-      target.removeAttribute("open");
-      return false;
-    }
-
-    var targettype = BookmarksUtils.resolveType(target.id);
-
-    if (targettype == "ImmutableFolder") {
-      // no context; see bug#... (popups getting stuck because "open"
-      // attribute doesn't get removed)
-      target.removeAttribute("open");
-      return false;
-    }
-
-    // -moz-user-focus: ignore; is set on toolbars
-    document.getElementById("PersonalToolbar").focus();
-
-    this._selection   = this.getBTSelection(target);
-    this._orientation = this.getBTOrientation(aEvent, target);
-    if (targettype != "ImmutableBookmark")
-      this._target = this.getBTTarget(target, this._orientation);
-
-    // walk up the tree until we find a database node
-    var p = target;
-    while (p && !p.database)
-      p = p.parentNode;
-    if (p)
-      this._db = p.database;
-
-    BookmarksCommand.createContextMenu(aEvent, this._selection, this._db);
-    this.onCommandUpdate();
-    aEvent.target.addEventListener("mousemove", BookmarksMenuController.onMouseMove, false);
-    return true;
-  },
-
-  /////////////////////////////////////////////////////////////////////////
-  // Clean up after closing the context menu popup
-  destroyContextMenu: function (aEvent)
-  {
-    // note that this method is called after doCommand.
-    // let's focus the content and dismiss the popup chain (needed when the user
-    // type escape or if he/she clicks outside the context menu)
-    if (content)
-      content.focus();
-    // XXXpch: see bug 210910, it should be done properly in the backend
-    BookmarksMenuDNDObserver.mCurrentDragOverTarget = null;
-    BookmarksMenuDNDObserver.onDragCloseTarget();
-
-    // if the user types escape, we need to remove the feedback
-    BookmarksMenuDNDObserver.onDragRemoveFeedBack(document.popupNode);
-
-    aEvent.target.removeEventListener("mousemove", BookmarksMenuController.onMouseMove, false);
-
-    this._target = null;
-    this._selection = null;
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // returns the formatted selection from aNode
-  getBTSelection: function (aNode)
-  {
-    var item;
-    switch (aNode.id) {
-    case "bookmarks-ptf":
-      item = BMSVC.getBookmarksToolbarFolder().Value;
-      break;
-    case "bookmarks-menu":
-      item = "NC:BookmarksRoot";
-      break;
-    default:
-      item = aNode.id;
-      if (!this.isBTBookmark(item))
-        return {length:0};
-    }
-    var parent           = this.getBTContainer(aNode);
-    var isExpanded       = aNode.hasAttribute("open") && aNode.open;
-    var selection        = {};
-    selection.item       = [RDF.GetResource(item)];
-    selection.parent     = [RDF.GetResource(parent)];
-    selection.isExpanded = [isExpanded];
-    selection.length     = selection.item.length;
-    BookmarksUtils.checkSelection(selection);
-    return selection;
-  },
-
-  /////////////////////////////////////////////////////////////////////////
-  // returns the insertion target from aNode
-  getBTTarget: function (aNode, aOrientation)
-  {
-    var item, parent, index;
-    switch (aNode.id) {
-    case "bookmarks-ptf":
-      parent = BMSVC.getBookmarksToolbarFolder().Value;
-      item = BookmarksToolbar.getLastVisibleBookmark();
-      break;
-    case "bookmarks-menu":
-      parent = "NC:BookmarksRoot";
-      break;
-    case "bookmarks-chevron":
-      parent = BMSVC.getBookmarksToolbarFolder().Value;
-      break;
-    default:
-      if (aOrientation == BookmarksUtils.DROP_ON)
-        parent = aNode.id
-      else {
-        parent = this.getBTContainer(aNode);
-        item = aNode;
-      }
-    }
-
-    parent = RDF.GetResource(parent);
-    if (aOrientation == BookmarksUtils.DROP_ON)
-      return BookmarksUtils.getTargetFromFolder(parent);
-
-    item = RDF.GetResource(item.id);
-    RDFC.Init(BMDS, parent);
-    index = RDFC.IndexOf(item);
-    if (aOrientation == BookmarksUtils.DROP_AFTER)
-      ++index;
-
-    return { parent: parent, index: index };
-  },
-
-  /////////////////////////////////////////////////////////////////////////
-  // returns the parent resource of a node in the personal toolbar.
-  // this is determined by inspecting the source element and walking up the 
-  // DOM tree to find the appropriate containing node.
-  getBTContainer: function (aNode)
-  {
-    var parent;
-    var item = aNode.id;
-    if (!this.isBTBookmark(item))
-      return "NC:BookmarksRoot"
-    parent = aNode.parentNode.parentNode;
-    parent = parent.id;
-    switch (parent) {
-    case "bookmarks-chevron":
-    case "bookmarks-stack":
-    case "bookmarks-toolbar":
-      return BMSVC.getBookmarksToolbarFolder().Value;
-    case "bookmarks-menu":
-      return "NC:BookmarksRoot";
-    default:
-      return parent;
-    }
-  },
-
-  ///////////////////////////////////////////////////////////////////////////
-  // returns true if the node is a bookmark, a folder or a bookmark separator
-  isBTBookmark: function (aURI)
-  {
-    if (!aURI || aURI == "bookmarkAllCmd")
-      return false;
-    var type = BookmarksUtils.resolveType(aURI);
-    return (type == "BookmarkSeparator"     ||
-            type == "Bookmark"              ||
-            type == "Folder"                ||
-            type == "PersonalToolbarFolder" ||
-            type == "Livemark"              ||
-            type == "ImmutableBookmark"     ||
-            type == "ImmutableFolder"       ||
-            aURI == "bookmarks-ptf")
-  },
-
-  /////////////////////////////////////////////////////////////////////////
-  // returns true if the node is a container. -->
-  isBTContainer: function (aTarget)
-  {
-    return  aTarget.localName == "menu" || (aTarget.localName == "toolbarbutton" &&
-           (aTarget.getAttribute("container") == "true"));
-  },
-
-  /////////////////////////////////////////////////////////////////////////
-  // returns BookmarksUtils.DROP_BEFORE, DROP_ON or DROP_AFTER accordingly
-  // to the event coordinates. Skin authors could break us, we'll cross that 
-  // bridge when they turn us 90degrees.  -->
-  getBTOrientation: function (aEvent, aTarget)
-  {
-    var target
-    if (!aTarget)
-      target = aEvent.target;
-    else
-      target = aTarget;
-    if (target.localName == "menu"                 &&
-        target.parentNode.localName != "menupopup" ||
-        target.id == "bookmarks-chevron")
-      return BookmarksUtils.DROP_ON;
-    if (target.id == "bookmarks-ptf") {
-      return target.hasChildNodes()?
-             BookmarksUtils.DROP_AFTER:BookmarksUtils.DROP_ON;
-    }
-
-    var overButtonBoxObject = target.boxObject.QueryInterface(Components.interfaces.nsIBoxObject);
-    var overParentBoxObject = target.parentNode.boxObject.QueryInterface(Components.interfaces.nsIBoxObject);
-
-    var size, border;
-    var coordValue, clientCoordValue;
-    switch (target.localName) {
-      case "toolbarseparator":
-      case "toolbarbutton":
-        size = overButtonBoxObject.width;
-        coordValue = overButtonBoxObject.x;
-        clientCoordValue = aEvent.clientX;
-        break;
-      case "menuseparator": 
-      case "menu":
-      case "menuitem":
-        size = overButtonBoxObject.height;
-        coordValue = overButtonBoxObject.screenY;
-        clientCoordValue = aEvent.screenY;
-        break;
-      default: return BookmarksUtils.DROP_ON;
-    }
-    if (this.isBTContainer(target))
-      if (target.localName == "toolbarbutton") {
-        // the DROP_BEFORE area excludes the label
-        var iconNode = document.getAnonymousElementByAttribute(target, "class", "toolbarbutton-icon");
-        border = parseInt(document.defaultView.getComputedStyle(target,"").getPropertyValue("padding-left")) +
-                 parseInt(document.defaultView.getComputedStyle(iconNode     ,"").getPropertyValue("width"));
-        border = Math.min(size/5,Math.max(border,4));
-      } else
-        border = size/5;
-    else
-      border = size/2;
-
-    // in the first region?
-    if (clientCoordValue-coordValue < border)
-      return BookmarksUtils.DROP_BEFORE;
-    // in the last region?
-    else if (clientCoordValue-coordValue >= size-border)
-      return BookmarksUtils.DROP_AFTER;
-    else // must be in the middle somewhere
-      return BookmarksUtils.DROP_ON;
-  },
-
-  /////////////////////////////////////////////////////////////////////////
-  // expand the folder targeted by the context menu.
-  expandBTFolder: function ()
-  {
-    var target = document.popupNode.lastChild;
-    if (document.popupNode.open)
-      target.hidePopup();
-    else
-      target.showPopup(document.popupNode);
-  },
-
-  onCommandUpdate: function ()
-  {
-    var selection = this._selection;
-    var target    = this._target;
-    BookmarksController.onCommandUpdate(selection, target);
-    if (document.popupNode.id == "bookmarks-ptf") {
-      // disabling 'cut' and 'copy' on the empty area of the personal toolbar
-      var commandNode = document.getElementById("cmd_cut");
-      commandNode.setAttribute("disabled", "true");
-      commandNode = document.getElementById("cmd_copy");
-      commandNode.setAttribute("disabled", "true");
-    }
-  },
-
-  ///////////////////////////////////////////////////////////////
-  // Load a bookmark in menus or toolbar buttons
-  // aTarget may not the aEvent target (see Open all in tabs command)
-  loadBookmark: function (aEvent, aTarget, aDS)
-  {
-    if (aTarget.getAttribute("class") == "openintabs-menuitem")
-      aTarget = aTarget.parentNode.parentNode;
-      
-    // Check for invalid bookmarks (most likely a static menu item like "Manage Bookmarks")
-    if (!this.isBTBookmark(aTarget.id))
-      return;
-    var rSource   = RDF.GetResource(aTarget.id);
-    var selection = BookmarksUtils.getSelectionFromResource(rSource);
-    var browserTarget = whereToOpenLink(aEvent);
-    BookmarksCommand.openBookmark(selection, browserTarget, aDS);
-    aEvent.stopPropagation();
-  },
-
-  ////////////////////////////////////////////////
-  // loads a bookmark with the mouse middle button
-  loadBookmarkMiddleClick: function (aEvent, aDS)
-  {
-    if (aEvent.button != 1)
-      return;
-    // unlike for command events, we have to close the menus manually
-    BookmarksMenuDNDObserver.mCurrentDragOverTarget = null;
-    BookmarksMenuDNDObserver.onDragCloseTarget();
-    this.loadBookmark(aEvent, aEvent.target, aDS);
-  }
-}
-
-var BookmarksMenuController = {
-
-  supportsCommand: BookmarksController.supportsCommand,
-
-  isCommandEnabled: function (aCommand)
-  {
-    var selection = BookmarksMenu._selection;
-    var target    = BookmarksMenu._target;
-    if (selection)
-      return BookmarksController.isCommandEnabled(aCommand, selection, target);
-    return false;
-  },
-
-  doCommand: function (aCommand)
-  {
-    // we needed to focus the element that has the bm command controller
-    // to get here. Now, let's focus the content before performing the command:
-    // if a modal dialog is called from now, the content will be focused again
-    // automatically after dismissing the dialog
-    if (content)
-      content.focus();
-    BookmarksMenuDNDObserver.onDragRemoveFeedBack(document.popupNode);
-
-    // if a dialog opens, the "open" attribute of a menuitem-container
-    // clicked on won't be removed. We do it manually.
-    var element = document.popupNode.firstChild;
-    if (element && element.localName == "menupopup")
-      element.hidePopup();
-
-    var selection = BookmarksMenu._selection;
-    var target    = BookmarksMenu._target;
-    var db        = BookmarksMenu._db;
-    switch (aCommand) {
-    case "cmd_bm_expandfolder":
-      BookmarksMenu.expandBTFolder();
-      break;
-    default:
-      BookmarksController.doCommand(aCommand, selection, target, db);
-    }
-  },
-
-  onMouseMove: function (aEvent)
-  {
-    var command = aEvent.target.getAttribute("command");
-    var isDisabled = aEvent.target.getAttribute("disabled")
-    if (isDisabled != "true" && (command == "cmd_bm_newfolder" || command == "cmd_paste")) {
-      BookmarksMenuDNDObserver.onDragSetFeedBack(document.popupNode, BookmarksMenu._orientation);
-    } else {
-      BookmarksMenuDNDObserver.onDragRemoveFeedBack(document.popupNode);
-    }
-  }
-}
-
-var BookmarksMenuDNDObserver = {
-
-  ////////////////////
-  // Public methods //
-  ////////////////////
-
-  onDragStart: function (aEvent, aXferData, aDragAction)
-  {
-    var target = aEvent.target;
-
-    // Prevent dragging from invalid regions
-
-    // can't drag from the empty areas
-    if (target.id == "bookmarks-menu" ||
-        target.id == "bookmarks-chevron" ||
-        target.id == "bookmarks-ptf")
-      return false;
-
-    if (!BookmarksMenu.isBTBookmark(target.id))
-      return false;
-
-    // Prevent dragging out of menupopups on non Win32 platforms. 
-    // a) on Mac drag from menus is generally regarded as being satanic
-    // b) on Linux, this causes an X-server crash, (bug 151336)
-    // c) on Windows, there is no hang or crash associated with this, so we'll leave 
-    // the functionality there. 
-    if (navigator.platform != "Win32" && target.localName != "toolbarbutton")
-      return false;
-
-    // a drag start is fired when leaving an open toolbarbutton(type=menu) 
-    // (see bug 143031)
-    if (this.isContainer(target)) {
-      if (this.isPlatformNotSupported) 
-        return false;
-      if (!aEvent.shiftKey && !aEvent.altKey && !aEvent.ctrlKey)
-        return false;
-      // menus open on mouse down
-      target.firstChild.hidePopup();
-    }
-    var selection  = BookmarksMenu.getBTSelection(target);
-    aXferData.data = BookmarksUtils.getXferDataFromSelection(selection);
-    return true;
-  },
-
-  onDragOver: function(aEvent, aFlavour, aDragSession) 
-  {
-    var orientation = BookmarksMenu.getBTOrientation(aEvent)
-    if (aDragSession.canDrop)
-      this.onDragSetFeedBack(aEvent.target, orientation);
-    if (orientation != this.mCurrentDropPosition) {
-      // emulating onDragExit and onDragEnter events since the drop region
-      // has changed on the target.
-      this.onDragExit(aEvent, aDragSession);
-      this.onDragEnter(aEvent, aDragSession);
-    }
-    if (this.isPlatformNotSupported)
-      return;
-    if (this.isTimerSupported || !aDragSession.sourceNode)
-      return;
-    this.onDragOverCheckTimers();
-  },
-
-  onDragEnter: function (aEvent, aDragSession)
-  {
-    var target = aEvent.target;
-    var orientation = BookmarksMenu.getBTOrientation(aEvent);
-    if (target.localName == "menupopup" || target.id == "bookmarks-ptf")
-      target = target.parentNode;
-    if (aDragSession.canDrop) {
-      this.onDragSetFeedBack(target, orientation);
-      this.onDragEnterSetTimer(target, aDragSession);
-    }
-    this.mCurrentDragOverTarget = target;
-    this.mCurrentDropPosition   = orientation;
-  },
-
-  onDragExit: function (aEvent, aDragSession)
-  {
-    var target = aEvent.target;
-    if (target.localName == "menupopup" || target.id == "bookmarks-ptf")
-      target = target.parentNode;
-    this.onDragRemoveFeedBack(target);
-    this.onDragExitSetTimer(target, aDragSession);
-    this.mCurrentDragOverTarget = null;
-    this.mCurrentDropPosition = null;
-  },
-
-  onDrop: function (aEvent, aXferData, aDragSession)
-  {
-    var target = aEvent.target;
-    this.onDragRemoveFeedBack(target);
-
-    var selection = BookmarksUtils.getSelectionFromXferData(aDragSession);
-
-    var orientation = BookmarksMenu.getBTOrientation(aEvent);
-
-    // For RTL PersonalBar bookmarks buttons, orientation should be inverted (only in drop case)
-    var PBStyle = window.getComputedStyle(document.getElementById("PersonalToolbar"),'');
-    var isHorizontal = (target.localName == "toolbarbutton");
-    if ((PBStyle.direction == 'rtl') && isHorizontal) {
-      if (orientation == BookmarksUtils.DROP_AFTER)
-        orientation = BookmarksUtils.DROP_BEFORE;
-      else if (orientation == BookmarksUtils.DROP_BEFORE)
-        orientation = BookmarksUtils.DROP_AFTER;
-    }
-
-    var selTarget   = BookmarksMenu.getBTTarget(target, orientation);
-
-    // we can only test for kCopyAction if the source is a bookmark
-    var checkCopy = aDragSession.isDataFlavorSupported("moz/rdfitem");
-
-    const kDSIID      = Components.interfaces.nsIDragService;
-    const kCopyAction = kDSIID.DRAGDROP_ACTION_COPY + kDSIID.DRAGDROP_ACTION_LINK;
-
-    // hide the 'open in tab' menuseparator because bookmarks
-    // can be inserted after it if they are dropped after the last bookmark
-    // a more comprehensive fix would be in the menupopup template builder
-    var menuSeparator = null;
-    var menuTarget = (target.localName == "toolbarbutton" ||
-                      target.localName == "menu")         && 
-                     orientation == BookmarksUtils.DROP_ON?
-                     target.lastChild:target.parentNode;
-    if (menuTarget.hasChildNodes() &&
-        menuTarget.lastChild.getAttribute("class") == "openintabs-menuitem") {
-      menuSeparator = menuTarget.lastChild.previousSibling;
-      menuTarget.removeChild(menuSeparator);
-    }
-
-    // doCopy defaults to true; check if we should make it false.
-    // we make it false only if all the selection items have valid parent
-    // bookmark DS containers (i.e. aren't generated via aggregation)
-    var doCopy = true;
-    if (checkCopy && !(aDragSession.dragAction & kCopyAction))
-      doCopy = BookmarksUtils.shouldCopySelection("drag", selection);
-
-    if (doCopy)
-      BookmarksUtils.insertAndCheckSelection("drag", selection, selTarget);
-    else
-      BookmarksUtils.moveAndCheckSelection("drag", selection, selTarget);
-
-    // show again the menuseparator
-    if (menuSeparator)
-      menuTarget.insertBefore(menuSeparator, menuTarget.lastChild);
-
-  },
-
-  canDrop: function (aEvent, aDragSession)
-  {
-    var target = aEvent.target;
-    if (!BookmarksMenu.isBTBookmark(target.id))
-      return false;
-
-    var btype = BookmarksUtils.resolveType(target.id);
-
-    return target.id == "bookmarks-menu"               ||
-           target.id == "bookmarks-chevron"            ||
-           target.id == "bookmarks-ptf" ||
-          (target.id != "NC:SystemBookmarksStaticRoot" &&
-           btype == "Folder" ||
-           btype == "Bookmark");
-  },
-
-  canHandleMultipleItems: true,
-
-  getSupportedFlavours: function () 
-  {
-    var flavourSet = new FlavourSet();
-    flavourSet.appendFlavour("moz/rdfitem");
-    flavourSet.appendFlavour("text/x-moz-url");
-    flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
-    flavourSet.appendFlavour("text/unicode");
-    return flavourSet;
-  }, 
-  
-
-  ////////////////////////////////////
-  // Private methods and properties //
-  ////////////////////////////////////
-
-  springLoadedMenuDelay: 350, // milliseconds
-  isPlatformNotSupported: navigator.platform.indexOf("Mac") != -1, // see bug 136524
-  // Needs to be dynamically overridden (to |true|) in the case of an external drag: see bug 232795.
-  isTimerSupported: navigator.platform.indexOf("Win") == -1,
-
-  mCurrentDragOverTarget: null,
-  mCurrentDropPosition: null,
-  loadTimer  : null,
-  closeTimer : null,
-  loadTarget : null,
-  closeTarget: null,
-
-  _observers : null,
-  get mObservers ()
-  {
-    if (!this._observers) {
-      this._observers = [
-        document.getElementById("bookmarks-ptf"),
-        // menubar menus haven't an "open" attribute: we can take the child
-        document.getElementById("bookmarks-menu").firstChild,
-        document.getElementById("bookmarks-chevron").parentNode
-      ]
-    }
-    return this._observers;
-  },
-
-  getObserverForNode: function (aNode)
-  {
-    if (!aNode)
-      return null;
-    var node = aNode;
-    var observer;
-    while (node) {
-      for (var i=0; i < this.mObservers.length; i++) {
-        observer = this.mObservers[i];
-        if (observer == node)
-          return observer;
-      }
-      node = node.parentNode;
-    }
-    return null;
-  },
-
-  onDragCloseMenu: function (aNode)
-  {
-    var children = aNode.childNodes;
-    for (var i = 0; i < children.length; i++) {
-      if (this.isContainer(children[i]) && 
-          children[i].getAttribute("open") == "true") {
-        this.onDragCloseMenu(children[i].lastChild);
-        if (children[i] != this.mCurrentDragOverTarget || this.mCurrentDropPosition != BookmarksUtils.DROP_ON)
-          children[i].lastChild.hidePopup();
-      }
-    } 
-  },
-
-  onDragCloseTarget: function ()
-  {
-    var currentObserver = this.getObserverForNode(this.mCurrentDragOverTarget);
-    // close all the menus not hovered by the mouse
-    for (var i=0; i < this.mObservers.length; i++) {
-      if (currentObserver != this.mObservers[i]) {
-        this.onDragCloseMenu(this.mObservers[i]);
-        if (this.mObservers[i].parentNode.id == "bookmarks-menu")
-          this.mObservers[i].hidePopup();
-      } else
-        this.onDragCloseMenu(this.mCurrentDragOverTarget.parentNode);
-    }
-  },
-
-  onDragLoadTarget: function (aTarget) 
-  {
-    if (!this.mCurrentDragOverTarget)
-      return;
-    // Load the current menu
-    if (this.mCurrentDropPosition == BookmarksUtils.DROP_ON && 
-        this.isContainer(aTarget))
-      aTarget.lastChild.showPopup(aTarget);
-  },
-
-  onDragOverCheckTimers: function ()
-  {
-    var now = new Date().getTime();
-    if (this.closeTimer && now-this.springLoadedMenuDelay>this.closeTimer) {
-      this.onDragCloseTarget();
-      this.closeTimer = null;
-    }
-    if (this.loadTimer && (now-this.springLoadedMenuDelay>this.loadTimer)) {
-      this.onDragLoadTarget(this.loadTarget);
-      this.loadTimer = null;
-    }
-  },
-
-  onDragEnterSetTimer: function (aTarget, aDragSession)
-  {
-    if (this.isPlatformNotSupported)
-      return;
-    if (this.isTimerSupported || !aDragSession.sourceNode) {
-      var targetToBeLoaded = aTarget;
-      clearTimeout(this.loadTimer);
-      if (aTarget == aDragSession.sourceNode)
-        return;
-      var This = this;
-      this.loadTimer=setTimeout(function () {This.onDragLoadTarget(targetToBeLoaded)}, This.springLoadedMenuDelay);
-    } else {
-      var now = new Date().getTime();
-      this.loadTimer  = now;
-      this.loadTarget = aTarget;
-    }
-  },
-
-  onDragExitSetTimer: function (aTarget, aDragSession)
-  {
-    if (this.isPlatformNotSupported)
-      return;
-    var This = this;
-    if (this.isTimerSupported || !aDragSession.sourceNode) {
-      clearTimeout(this.closeTimer)
-      this.closeTimer=setTimeout(function () {This.onDragCloseTarget()}, This.springLoadedMenuDelay);
-    } else {
-      var now = new Date().getTime();
-      this.closeTimer  = now;
-      this.closeTarget = aTarget;
-      this.loadTimer = null;
-
-      // If the user isn't rearranging within the menu, close it
-      // To do so, we exploit a Mac bug: timeout set during
-      // drag and drop on Windows and Mac are fired only after that the drop is released.
-      // timeouts will pile up, we may have a better approach but for the moment, this one
-      // correctly close the menus after a drop/cancel outside the personal toolbar.
-      // The if statement in the function has been introduced to deal with rare but reproducible
-      // missing Exit events.
-      if (aDragSession.sourceNode.localName != "menuitem" && aDragSession.sourceNode.localName != "menu")
-        setTimeout(function () { if (This.mCurrentDragOverTarget) {This.onDragRemoveFeedBack(This.mCurrentDragOverTarget); This.mCurrentDragOverTarget=null} This.loadTimer=null; This.onDragCloseTarget() }, 0);
-    }
-  },
-
-  onDragSetFeedBack: function (aTarget, aOrientation)
-  {
-   switch (aTarget.localName) {
-      case "toolbarseparator":
-      case "toolbarbutton":
-        switch (aOrientation) {
-          case BookmarksUtils.DROP_BEFORE: 
-            aTarget.setAttribute("dragover-left", "true");
-            break;
-          case BookmarksUtils.DROP_AFTER:
-            aTarget.setAttribute("dragover-right", "true");
-            break;
-          case BookmarksUtils.DROP_ON:
-            aTarget.setAttribute("dragover-top"   , "true");
-            aTarget.setAttribute("dragover-bottom", "true");
-            aTarget.setAttribute("dragover-left"  , "true");
-            aTarget.setAttribute("dragover-right" , "true");
-            break;
-        }
-        break;
-      case "menuseparator": 
-      case "menu":
-      case "menuitem":
-        switch (aOrientation) {
-          case BookmarksUtils.DROP_BEFORE: 
-            aTarget.setAttribute("dragover-top", "true");
-            break;
-          case BookmarksUtils.DROP_AFTER:
-            aTarget.setAttribute("dragover-bottom", "true");
-            break;
-          case BookmarksUtils.DROP_ON:
-            break;
-        }
-        break;
-      case "hbox"     : 
-        // hit between the last visible bookmark and the chevron
-        var newTarget = BookmarksToolbar.getLastVisibleBookmark();
-        if (newTarget)
-          newTarget.setAttribute("dragover-right", "true");
-        break;
-      case "stack"    :
-      case "menupopup": break; 
-     default: dump("No feedback for: "+aTarget.localName+"\n");
-    }
-  },
-
-  onDragRemoveFeedBack: function (aTarget)
-  { 
-    var newTarget;
-    var bt;
-    if (aTarget.id == "bookmarks-ptf") { 
-      // hit when dropping in the bt or between the last visible bookmark 
-      // and the chevron
-      newTarget = BookmarksToolbar.getLastVisibleBookmark();
-      if (newTarget)
-        newTarget.removeAttribute("dragover-right");
-    } else if (aTarget.id == "bookmarks-stack") {
-      newTarget = BookmarksToolbar.getLastVisibleBookmark();
-      newTarget.removeAttribute("dragover-right");
-    } else {
-      aTarget.removeAttribute("dragover-left");
-      aTarget.removeAttribute("dragover-right");
-      aTarget.removeAttribute("dragover-top");
-      aTarget.removeAttribute("dragover-bottom");
-    }
-  },
-
-  onDropSetFeedBack: function (aTarget)
-  {
-    //XXX Not yet...
-  },
-
-  isContainer: function (aTarget)
-  {
-    return aTarget.localName == "menu"          || 
-           aTarget.localName == "toolbarbutton" &&
-           aTarget.getAttribute("type") == "menu";
-  }
-}
-
-var BookmarksToolbar = 
-{
-  /////////////////////////////////////////////////////////////////////////////
-  // make bookmarks toolbar act like menus
-  openedMenuButton:null,
-  autoOpenMenu: function (aEvent)
-  {
-    var target = aEvent.target;
-    if (BookmarksToolbar.openedMenuButton != target &&
-        target.nodeName == "toolbarbutton" &&
-        target.type == "menu") {
-      BookmarksToolbar.openedMenuButton.open = false;
-      target.open = true;
-    }
-  },
-  setOpenedMenu: function (aEvent)
-  {
-    if (aEvent.target.parentNode.localName == 'toolbarbutton') {
-      if (!this.openedMenuButton)
-        aEvent.currentTarget.addEventListener("mouseover", this.autoOpenMenu, true);
-      this.openedMenuButton = aEvent.target.parentNode;
-    }
-  },
-  unsetOpenedMenu: function (aEvent)
-  {
-    if (aEvent.target.parentNode.localName == 'toolbarbutton') {
-      aEvent.currentTarget.removeEventListener("mouseover", this.autoOpenMenu, true);
-      this.openedMenuButton = null;
-    }
-  },
-
-  /////////////////////////////////////////////////////////////////////////////
-  // returns the node of the last visible bookmark on the toolbar -->
-  getLastVisibleBookmark: function ()
-  {
-    var buttons = document.getElementById("bookmarks-ptf");
-    var button = buttons.firstChild;
-    if (!button)
-      return null; // empty bookmarks toolbar
-    do {
-      if (button.collapsed)
-        return button.previousSibling;
-      button = button.nextSibling;
-    } while (button)
-    return buttons.lastChild;
-  },
-
-  updateOverflowMenu: function (aMenuPopup)
-  {
-    var hbox = document.getElementById("bookmarks-ptf");
-    for (var i = 0; i < hbox.childNodes.length; i++) {
-      var button = hbox.childNodes[i];
-      var menu = aMenuPopup.childNodes[i];
-      if (menu.collapsed == button.collapsed)
-        menu.collapsed = !menu.collapsed;
-    }
-  },
-
-  resizeFunc: function(event) 
-  { 
-    BookmarksToolbarRDFObserver._overflowTimerInEffect = false;
-    if (event && event.type == 'focus') 
-      window.removeEventListener('focus', BookmarksToolbar.resizeFunc, false); // hack for bug 266737
-    var buttons = document.getElementById("bookmarks-ptf");
-    if (!buttons)
-      return;
-    var chevron = document.getElementById("bookmarks-chevron");
-    var myToolbarItem = buttons.parentNode.parentNode;
-    
-    var width = myToolbarItem.boxObject.width;
-    if (width <= 0) {  // hack for bug 266737
-      window.addEventListener('focus', BookmarksToolbar.resizeFunc, false);
-      return;
-    }
-
-    if (buttons.childNodes.length == 0) {
-      chevron.collapsed = true;
-      return;
-    }
-
-    var chevronWidth = 0;
-    chevron.collapsed = false;
-    chevronWidth = chevron.boxObject.width;
-    chevron.collapsed = true;
-    var overflowed = false;
-
-    // This 3 is to account for the 'padding-left: 3px;' in browser.xul.
-    var usedWidth = 3;
-    for (var i=0; i<buttons.childNodes.length; i++) {
-      var button = buttons.childNodes[i];
-      button.collapsed = overflowed;
-      
-      if (i == buttons.childNodes.length - 1) // last ptf item...
-        chevronWidth = 0;
-      if (usedWidth + button.boxObject.width + chevronWidth > width) {
-         overflowed = true;
-        // This button doesn't fit. Show it in the menu. Hide it in the toolbar.
-        if (!button.collapsed)
-          button.collapsed = true;
-        if (chevron.collapsed) {
-          chevron.collapsed = false;
-          var overflowPadder = document.getElementById("overflow-padder");
-          overflowPadder.width = width - chevron.boxObject.width;
-        }
-      }
-      usedWidth += button.boxObject.width;
-    }
-  },
-
-  // Fill in tooltips for personal toolbar
-  fillInBTTooltip: function (tipElement)
-  {