Merge from cvs-trunk-mirror to mozilla-central.
authorjorendorff@mozilla.com
Thu, 13 Dec 2007 13:15:17 -0600
changeset 9013 baffecf28c7e683c42631ed395c591c866a97df7
parent 8619 cf917177abad33b185de640447801fa340219712 (current diff)
parent 9012 8bfe999bed946737fbd8bf1cce2f1e6aec290440 (diff)
child 9014 5603fa93e575d0c274fedfbf3eac4c768f49a412
push idunknown
push userunknown
push dateunknown
milestone1.9b3pre
Merge from cvs-trunk-mirror to mozilla-central.
accessible/src/base/nsARIAPropertyList.h
client.mk
config/rules.mk
configure.in
content/svg/content/src/nsSVGTextPathElement.h
js/src/js.cpp
js/src/jsapi.cpp
js/src/jsarray.cpp
js/src/jsbool.cpp
js/src/jscntxt.cpp
js/src/jsdate.cpp
js/src/jsemit.cpp
js/src/jsexn.cpp
js/src/jsfile.cpp
js/src/jsfun.cpp
js/src/jsinterp.cpp
js/src/jsiter.cpp
js/src/jsmath.cpp
js/src/jsnum.cpp
js/src/jsobj.cpp
js/src/jsopcode.cpp
js/src/jsparse.cpp
js/src/jsprf.cpp
js/src/jsregexp.cpp
js/src/jsscan.cpp
js/src/jsstr.cpp
js/src/jsxdrapi.cpp
js/src/jsxml.cpp
js/tests/ecma_3/Expressions/11.10-03.js
js/tests/ecma_3/extensions/regress-368516.js
js/tests/js1_5/Regress/regress-398609.js
js/tests/js1_5/Regress/regress-404755.js
js/tests/js1_5/Regress/regress-407024.js
js/tests/js1_5/extensions/regress-371636.js
js/tests/js1_8/extensions/regress-353116.js
js/tests/process-logs.sh
layout/reftests/bugs/404553-1-ref.html
layout/reftests/bugs/404553-1.html
--- a/accessible/public/nsIAccessibleDocument.idl
+++ b/accessible/public/nsIAccessibleDocument.idl
@@ -53,17 +53,17 @@ interface nsIDOMWindow;
  * You can QueryInterface to nsIAccessibleDocument from
  * the nsIAccessible or nsIAccessNode for the root node
  * of a document. You can also get one from 
  * nsIAccessNode::GetAccessibleDocument() or 
  * nsIAccessibleEvent::GetAccessibleDocument()
  *
  * @status UNDER_REVIEW
  */
-[scriptable, uuid(81ddd75f-adbd-4a1c-b87c-6522bcea0596)]
+[scriptable, uuid(b7ae45bd-21e9-4ed5-a67e-86448b25d56b)]
 interface nsIAccessibleDocument : nsISupports
 {
   /**
    * The URL of the document
    */
   readonly attribute AString URL;
 
   /**
@@ -117,32 +117,9 @@ interface nsIAccessibleDocument : nsISup
    * @param aDOMNode The DOM node we need an accessible for.
    * @param aCanCreate Can accessibles be created or must it be the first 
    *                   cached accessible in the parent chain?
    * @return An first nsIAccessible found by crawling up the DOM node
    *         to the document root.
    */
   nsIAccessible getAccessibleInParentChain(in nsIDOMNode aDOMNode,
                                            in boolean aCanCreate);
-
-  /**
-   * A bit flag representing the type of ARIA properties which should be
-   * checked in this document:
-   * either eUnknownPropType, eCheckNamespaced, eCheckHyphenated or eCheckAny
-   */
-  readonly attribute unsigned long ariaPropTypes;
-  
-  /**
-   * Check attributes in the form of:
-   * [someprefix]:[propname]  (e.g. aria:live) where ancestor defines: 
-   * xmlns:[someprefix]="http://www.w3.org/2005/07/aaa"
-   */
-  const unsigned long eCheckNamespaced = 1;
-  
-  /**
-   * Check hyphenated attributes in the form of aria-[propname].
-   * This is the default in text/html documents.
-   * Can be combined with eCheckNamespaced flag. This may
-   * change during the life of the document, if setAttributeNS()
-   * is used to set an ARIA property.
-   */
-  const unsigned long eCheckHyphenated = 2;
 };
--- a/accessible/public/nsIAccessibleRole.idl
+++ b/accessible/public/nsIAccessibleRole.idl
@@ -56,17 +56,17 @@ interface nsIAccessibleRole : nsISupport
    * Represents a title or caption bar for a window. It is used by MSAA only,
    * supported automatically by MS Windows.
    */
   const unsigned long ROLE_TITLEBAR = 1;
 
   /**
    * Represents the menu bar (positioned beneath the title bar of a window)
    * from which menus are selected by the user. The role is used by
-   * xul:menubar or role="wairole:menubar".
+   * xul:menubar or role="menubar".
    */
   const unsigned long ROLE_MENUBAR = 2;
 
   /**
    * Represents a vertical or horizontal scroll bar, which is part of the client
    * area or used in a control.
    */
   const unsigned long ROLE_SCROLLBAR = 3;
@@ -93,17 +93,17 @@ interface nsIAccessibleRole : nsISupport
    */
   const unsigned long ROLE_CARET = 7;
 
   /**
    * Represents an alert or a condition that a user should be notified about.
    * Assistive Technologies typically respond to the role by reading the entire
    * onscreen contents of containers advertising this role. Should be used for
    * warning dialogs, etc. The role is used by xul:browsermessage,
-   * role="wairole:alert", xforms:message.
+   * role="alert", xforms:message.
    */
   const unsigned long ROLE_ALERT = 8;
 
   /**
    * Represents the window frame, which contains child objects such as
    * a title bar, client, and other objects contained in a window. The role
    * is supported automatically by MS Windows.
    */
@@ -111,41 +111,41 @@ interface nsIAccessibleRole : nsISupport
 
   /**
    * XXX: document this.
    */
   const unsigned long ROLE_CLIENT = 10;
 
   /**
    * Represents a menu, which presents a list of options from which the user can
-   * make a selection to perform an action. It is used for role="wairole:menu".
+   * make a selection to perform an action. It is used for role="menu".
    */
   const unsigned long ROLE_MENUPOPUP = 11;
 
   /**
    * Represents a menu item, which is an entry in a menu that a user can choose
    * to carry out a command, select an option. It is used for xul:menuitem,
-   * role="wairole:menuitem".
+   * role="menuitem".
    */
   const unsigned long ROLE_MENUITEM = 12;
 
   /**
    * Represents a ToolTip that provides helpful hints.
    */
   const unsigned long ROLE_TOOLTIP = 13;
 
   /**
    * Represents a main window for an application. It is used for
-   * role="wairole:application". Also refer to ROLE_APP_ROOT
+   * role="application". Also refer to ROLE_APP_ROOT
    */
   const unsigned long ROLE_APPLICATION = 14;
 
   /**
    * Represents a document window. A document window is always contained within
-   * an application window. It is used for role="wairole:document".
+   * an application window. It is used for role="document".
    */
   const unsigned long ROLE_DOCUMENT = 15;
 
   /**
    * Represents a pane within a frame or document window. Users can navigate
    * between panes and within the contents of the current pane, but cannot
    * navigate between items in different panes. Thus, panes represent a level
    * of grouping lower than frame windows or documents, but above individual
@@ -155,88 +155,88 @@ interface nsIAccessibleRole : nsISupport
 
   /**
    * Represents a graphical image used to represent data.
    */
   const unsigned long ROLE_CHART = 17;
 
   /**
    * Represents a dialog box or message box. It is used for xul:dialog, 
-   * role="wairole:dialog".
+   * role="dialog".
    */
   const unsigned long ROLE_DIALOG = 18;
 
   /**
    * Represents a window border.
    */
   const unsigned long ROLE_BORDER = 19;
 
   /**
    * Logically groups other objects. There is not always a parent-child
    * relationship between the grouping object and the objects it contains. It
-   * is used for html:textfield, xul:groupbox, role="wairole:group".
+   * is used for html:textfield, xul:groupbox, role="group".
    */
   const unsigned long ROLE_GROUPING = 20;
 
   /**
    * Used to visually divide a space into two regions, such as a separator menu
    * item or a bar that divides split panes within a window. It is used for
-   * xul:separator, html:hr, role="wairole:separator".
+   * xul:separator, html:hr, role="separator".
    */
   const unsigned long ROLE_SEPARATOR = 21;
 
   /**
    * Represents a toolbar, which is a grouping of controls (push buttons or
    * toggle buttons) that provides easy access to frequently used features. It
-   * is used for xul:toolbar, role="wairole:toolbar".
+   * is used for xul:toolbar, role="toolbar".
    */
   const unsigned long ROLE_TOOLBAR = 22;
 
   /**
    * Represents a status bar, which is an area at the bottom of a window that
    * displays information about the current operation, state of the application,
    * or selected object. The status bar has multiple fields, which display
    * different kinds of information. It is used for xul:statusbar.
    */
   const unsigned long ROLE_STATUSBAR = 23;
 
   /**
    * Represents a table that contains rows and columns of cells, and optionally,
    * row headers and column headers. It is used for html:table,
-   * role="wairole:grid". Also refer to the following roles: ROLE_COLUMNHEADER,
+   * role="grid". Also refer to the following roles: ROLE_COLUMNHEADER,
    * ROLE_ROWHEADER, ROLE_COLUMN, ROLE_ROW, ROLE_CELL.
    */
   const unsigned long ROLE_TABLE = 24;
 
   /**
    * Represents a column header, providing a visual label for a column in
    * a table. It is used for XUL tree column headers, html:th,
-   * role="wairole:colheader". Also refer to ROLE_TABLE.
+   * role="colheader". Also refer to ROLE_TABLE.
    */
   const unsigned long ROLE_COLUMNHEADER = 25;
 
   /**
    * Represents a row header, which provides a visual label for a table row.
-   * It is used for role="wairole:rowheader". Also, see ROLE_TABLE.
+   * It is used for role="rowheader". Also, see ROLE_TABLE.
    */
   const unsigned long ROLE_ROWHEADER = 26;
 
   /**
    * Represents a column of cells within a table. Also, see ROLE_TABLE.
    */
   const unsigned long ROLE_COLUMN = 27;
 
   /**
    * Represents a row of cells within a table. Also, see ROLE_TABLE.
    */
   const unsigned long ROLE_ROW = 28;
 
   /**
    * Represents a cell within a table. Is is used for html:td,
-   * role="wairole:gridcell". Also, see ROLE_TABLE.
+   * role="gridcell". Also, see ROLE_TABLE.
    */
   const unsigned long ROLE_CELL = 29;
 
   /**
    * Represents a link to something else. This object might look like text or
    * a graphic, but it acts like a button. It is used for
    * xul:label@class="text-link", html:a, html:area,
    * xforms:trigger@appearance="minimal".
@@ -251,48 +251,48 @@ interface nsIAccessibleRole : nsISupport
   /**
    * Represents a cartoon-like graphic object, such as Microsoft Office
    * Assistant, which is displayed to provide help to users of an application.
    */
   const unsigned long ROLE_CHARACTER = 32;
 
   /**
    * Represents a list box, allowing the user to select one or more items. It
-   * is used for xul:listbox, html:select@size, role="wairole:list". See also
+   * is used for xul:listbox, html:select@size, role="list". See also
    * ROLE_LIST_ITEM.
    */
   const unsigned long ROLE_LIST = 33;
 
   /**
    * Represents an item in a list. See also ROLE_LIST.
    */
   const unsigned long ROLE_LISTITEM = 34;
 
   /**
    * Represents an outline or tree structure, such as a tree view control,
    * that displays a hierarchical list and allows the user to expand and
-   * collapse branches. Is is used for role="wairole:tree".
+   * collapse branches. Is is used for role="tree".
    */
   const unsigned long ROLE_OUTLINE = 35;
 
   /**
    * Represents an item in an outline or tree structure. It is used for
-   * role="wairole:treeitem".
+   * role="treeitem".
    */
   const unsigned long ROLE_OUTLINEITEM = 36;
 
   /**
    * Represents a page tab, it is a child of a page tab list. It is used for
-   * xul:tab, role="wairole:treeitem". Also refer to ROLE_PAGETABLIST.
+   * xul:tab, role="treeitem". Also refer to ROLE_PAGETABLIST.
    */
   const unsigned long ROLE_PAGETAB = 37;
 
   /**
    * Represents a property sheet. It is used for xul:tabpanel,
-   * role="wairole:tabpanel".
+   * role="tabpanel".
    */
   const unsigned long ROLE_PROPERTYPAGE = 38;
 
   /**
    * Represents an indicator, such as a pointer graphic, that points to the
    * current item.
    */
   const unsigned long ROLE_INDICATOR = 39;
@@ -301,62 +301,62 @@ interface nsIAccessibleRole : nsISupport
    * Represents a picture. Is is used for xul:image, html:img.
    */
   const unsigned long ROLE_GRAPHIC = 40;
 
   /**
    * Represents read-only text, such as labels for other controls or
    * instructions in a dialog box. Static text cannot be modified or selected.
    * Is is used for xul:label, xul:description, html:lablel,
-   * role="wairole:label" or role="wairole:description", xforms:output.
+   * role="label" or role="description", xforms:output.
    */
   const unsigned long ROLE_STATICTEXT = 41;
 
   /**
    * Represents selectable text that allows edits or is designated read-only.
    */
   const unsigned long ROLE_TEXT_LEAF = 42;
 
   /**
    * Represents a push button control. It is used for xul:button, html:button,
-   * role="wairole:button", xforms:trigger, xforms:submit.
+   * role="button", xforms:trigger, xforms:submit.
    */
   const unsigned long ROLE_PUSHBUTTON = 43;
 
   /**
    * Represents a check box control. It is used for xul:checkbox,
-   * html:input@type="checkbox", role="wairole:checkbox", boolean xforms:input.
+   * html:input@type="checkbox", role="checkbox", boolean xforms:input.
    */
   const unsigned long ROLE_CHECKBUTTON = 44;
 
   /**
    * Represents an option button, also called a radio button. It is one of a
    * group of mutually exclusive options. All objects sharing a single parent
    * that have this attribute are assumed to be part of single mutually
    * exclusive group. It is used for xul:radio, html:input@type="radio",
-   * role="wairole:radio".
+   * role="radio".
    */
   const unsigned long ROLE_RADIOBUTTON = 45;
 
   /**
    * Represents a combo box; an edit control with an associated list box that
    * provides a set of predefined choices. It is used for html:select,
-   * xul:menulist, role="wairole:combobox".
+   * xul:menulist, role="combobox".
    */
   const unsigned long ROLE_COMBOBOX = 46;
 
   /**
    * Represents the calendar control. It is used for date xforms:input.
    */
   const unsigned long ROLE_DROPLIST = 47;
 
   /**
    * Represents a progress bar, dynamically showing the user the percent
    * complete of an operation in progress. It is used for xul:progressmeter,
-   * role="wairole:progressbar".
+   * role="progressbar".
    */
   const unsigned long ROLE_PROGRESSBAR = 48;
 
   /**
    * Represents a dial or knob whose purpose is to allow a user to set a value.
    */
   const unsigned long ROLE_DIAL = 49;
 
@@ -364,17 +364,17 @@ interface nsIAccessibleRole : nsISupport
    * Represents a hot-key field that allows the user to enter a combination or
    * sequence of keystrokes.
    */
   const unsigned long ROLE_HOTKEYFIELD = 50;
 
   /**
    * Represents a slider, which allows the user to adjust a setting in given
    * increments between minimum and maximum values. It is used by xul:scale,
-   * role="wairole:slider", xforms:range.
+   * role="slider", xforms:range.
    */
   const unsigned long ROLE_SLIDER = 51;
 
   /**
    * Represents a spin box, which is a control that allows the user to increment
    * or decrement the value displayed in a separate "buddy" control associated
    * with the spin box. It is used for xul:spinbuttons.
    */
@@ -413,17 +413,17 @@ interface nsIAccessibleRole : nsISupport
 
   /**
    * Represents blank space between other objects.
    */
   const unsigned long ROLE_WHITESPACE = 59;
 
   /**
    * Represents a container of page tab controls. Is it used for xul:tabs,
-   * DHTML: role="wairole:tabs". Also refer to ROLE_PAGETAB.
+   * DHTML: role="tabs". Also refer to ROLE_PAGETAB.
    */
   const unsigned long ROLE_PAGETABLIST = 60;
 
   /**
    * Represents a control that displays time.
    */
   const unsigned long ROLE_CLOCK = 61;
 
--- a/accessible/public/nsIAccessibleText.idl
+++ b/accessible/public/nsIAccessibleText.idl
@@ -43,16 +43,22 @@
 
 typedef long nsAccessibleTextBoundary;
 
 interface nsIAccessible;
 
 [scriptable, uuid(caa4f543-070e-4705-8428-2e53575c41bb)]
 interface nsIAccessibleText : nsISupports
 {
+  // In parameters for character offsets:
+  //  -1 will be treated as the equal to the end of the text
+  //  -2 will be treated as the caret position
+  const PRInt32 TEXT_OFFSET_END_OF_TEXT = -1;
+  const PRInt32 TEXT_OFFSET_CARET       = -2;
+
   const nsAccessibleTextBoundary BOUNDARY_CHAR = 0;
   const nsAccessibleTextBoundary BOUNDARY_WORD_START = 1;
   const nsAccessibleTextBoundary BOUNDARY_WORD_END = 2;
   const nsAccessibleTextBoundary BOUNDARY_SENTENCE_START = 3; // don't use, deprecated
   const nsAccessibleTextBoundary BOUNDARY_SENTENCE_END = 4;  // don't use, deprecated
   const nsAccessibleTextBoundary BOUNDARY_LINE_START = 5;
   const nsAccessibleTextBoundary BOUNDARY_LINE_END = 6;
   const nsAccessibleTextBoundary BOUNDARY_ATTRIBUTE_RANGE = 7;
@@ -161,17 +167,16 @@ interface nsIAccessibleText : nsISupport
                          in unsigned long coordType);
 
   void getSelectionBounds (in long selectionNum,
                            out long startOffset,
                            out long endOffset);
 
   /**
    * Set the bounds for the given selection range
-   * Offsets < 0 will be treated as the equal to the end of the text
    */
   void setSelectionBounds (in long selectionNum,
                            in long startOffset,
                            in long endOffset);
 
   void addSelection (in long startOffset, in long endOffset);
 
   void removeSelection (in long selectionNum);
--- a/accessible/public/nsIAccessibleTreeCache.idl
+++ b/accessible/public/nsIAccessibleTreeCache.idl
@@ -32,22 +32,39 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 #include "nsITreeColumns.idl"
 
 interface nsIAccessible;
+
 /**
  * A cross-platform interface that supports cache for tree item 
  *
  * @status UNDER_REVIEW
  */
-[scriptable, uuid(CC742DA2-9C25-4D04-96CD-DA407D676C6D)]
+[uuid(7cdad914-948b-4bbc-9c47-ee5e1ae6b148)]
 interface nsIAccessibleTreeCache : nsISupports
 {
   /**
-   * Get tree item from cache according to row and column, create if doesn't exist in cache
-   * "aColumn" can be nsnull
+   * Get tree item from cache according to row and column, create if doesn't
+   * exist in cache.
+   *
+   * @param aRow     the given row index
+   * @param aColumn  the given column object. If is is nsnull then primary
+   *                 column is used. It makes sense for ATK only.
    */
-  [noscript] nsIAccessible getCachedTreeitemAccessible(in PRInt32 aRow, in nsITreeColumn aColumn);
+  nsIAccessible getCachedTreeitemAccessible(in long aRow,
+                                            in nsITreeColumn aColumn);
+
+  /**
+   * Invalidates the number of cached treeitem accessibles.
+   *
+   * @param aRow    row index the invalidation starts from
+   * @param aCount  the number of treeitem accessibles to invalidate,
+   *                the number sign specifies whether rows have been
+   *                inserted (plus) or removed (minus)
+   */
+  void invalidateCache(in long aRow, in long aCount);
 };
+
--- a/accessible/src/atk/nsMaiInterfaceTable.cpp
+++ b/accessible/src/atk/nsMaiInterfaceTable.cpp
@@ -338,17 +338,20 @@ getRowHeaderCB(AtkTable *aTable, gint aR
     NS_ENSURE_TRUE(accHeader, nsnull);
 
     return nsAccessibleWrap::GetAtkObject(accHeader);
 }
 
 AtkObject*
 getSummaryCB(AtkTable *aTable)
 {
-    /* ??? in nsIAccessibleTable, it returns a nsAString */
+    // Neither html:table nor xul:tree nor ARIA grid/tree have an ability to
+    // link an accessible object to specify a summary. There is closes method
+    // in nsIAccessibleTable::summary to get a summary as a string which is not
+    // mapped directly to ATK.
     return nsnull;
 }
 
 gint
 getSelectedColumnsCB(AtkTable *aTable, gint **aSelected)
 {
     nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable));
     if (!accWrap)
--- a/accessible/src/atk/nsXULTreeAccessibleWrap.cpp
+++ b/accessible/src/atk/nsXULTreeAccessibleWrap.cpp
@@ -442,17 +442,17 @@ NS_IMETHODIMP nsXULTreeAccessibleWrap::C
 
 NS_IMETHODIMP nsXULTreeAccessibleWrap::IsProbablyForLayout(PRBool *aIsProbablyForLayout)
 {
   *aIsProbablyForLayout = PR_FALSE;
   return NS_OK;
 }
 
 // --------------------------------------------------------
-// nsXULTreeAccessibleWrap Accessible
+// nsXULTreeColumnsAccessibleWrap Accessible
 // --------------------------------------------------------
 NS_IMPL_ISUPPORTS_INHERITED1(nsXULTreeColumnsAccessibleWrap, nsXULTreeColumnsAccessible, nsIAccessibleTable)
 
 nsXULTreeColumnsAccessibleWrap::nsXULTreeColumnsAccessibleWrap(nsIDOMNode *aDOMNode, nsIWeakReference *aShell):
 nsXULTreeColumnsAccessible(aDOMNode, aShell)
 {
 }
 
--- a/accessible/src/atk/nsXULTreeAccessibleWrap.h
+++ b/accessible/src/atk/nsXULTreeAccessibleWrap.h
@@ -50,18 +50,22 @@ class nsXULTreeAccessibleWrap : public n
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLETABLE
 
   nsXULTreeAccessibleWrap(nsIDOMNode* aDOMNode, nsIWeakReference* aShell);
   virtual ~nsXULTreeAccessibleWrap() {}
 
+  // nsIAccessible
   NS_IMETHOD GetChildCount(PRInt32 *_retval);
-  NS_IMETHOD ChangeSelection(PRInt32 aIndex, PRUint8 aMethod, PRBool *aSelState);
+
+protected:
+  NS_IMETHOD ChangeSelection(PRInt32 aIndex, PRUint8 aMethod,
+                             PRBool *aSelState);
 };
 
 class nsXULTreeColumnsAccessibleWrap : public nsXULTreeColumnsAccessible,
                                        public nsIAccessibleTable
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLETABLE
--- a/accessible/src/base/nsARIAMap.cpp
+++ b/accessible/src/base/nsARIAMap.cpp
@@ -36,187 +36,175 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsARIAMap.h"
 #include "nsIAccessibleRole.h"
 #include "nsIAccessibleStates.h"
 
-#define ARIA_PROPERTY(atom) &nsAccessibilityAtoms::atom,
-nsIAtom** nsARIAMap::gAriaAtomPtrsNS[eAria_none] = {
-#include "nsARIAPropertyList.h"
-};
-#undef ARIA_PROPERTY
-
-#define ARIA_PROPERTY(atom) &nsAccessibilityAtoms::aria_##atom,
-nsIAtom** nsARIAMap::gAriaAtomPtrsHyphenated[eAria_none] = {
-#include "nsARIAPropertyList.h"
-};
-#undef ARIA_PROPERTY
-
 /**
  *  This list of WAI-defined roles are currently hardcoded.
  *  Eventually we will most likely be loading an RDF resource that contains this information
  *  Using RDF will also allow for role extensibility. See bug 280138.
  *
  *  Definition of nsRoleMapEntry and nsStateMapEntry contains comments explaining this table.
  *
  *  When no nsIAccessibleRole enum mapping exists for an ARIA role, the
  *  role will be exposed via the object attribute "xml-roles".
  *  In addition, in MSAA, the unmapped role will also be exposed as a BSTR string role.
  *
  *  There are no nsIAccessibleRole enums for the following landmark roles:
  *    banner, contentinfo, main, navigation, note, search, secondary, seealso, breadcrumbs
  */ 
 
-static const nsStateMapEntry kEndEntry = {eAria_none, 0, 0};  // To fill in array of state mappings
+static const nsStateMapEntry kEndEntry = {nsnull, 0, 0};  // To fill in array of state mappings
 
 nsRoleMapEntry nsARIAMap::gWAIRoleMap[] = 
 {
   {"alert", nsIAccessibleRole::ROLE_ALERT, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"alertdialog", nsIAccessibleRole::ROLE_ALERT, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"application", nsIAccessibleRole::ROLE_APPLICATION, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"button", nsIAccessibleRole::ROLE_PUSHBUTTON, eNameOkFromChildren, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_pressed, kBoolState, nsIAccessibleStates::STATE_PRESSED},
-            {eAria_pressed, "mixed", nsIAccessibleStates::STATE_MIXED}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_pressed, kBoolState, nsIAccessibleStates::STATE_PRESSED},
+            {&nsAccessibilityAtoms::aria_pressed, "mixed", nsIAccessibleStates::STATE_MIXED}, kEndEntry},
   {"checkbox", nsIAccessibleRole::ROLE_CHECKBUTTON, eNameOkFromChildren, eNoValue, nsIAccessibleStates::STATE_CHECKABLE,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED},
-            {eAria_checked, "mixed", nsIAccessibleStates::STATE_MIXED},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED},
+            {&nsAccessibilityAtoms::aria_checked, "mixed", nsIAccessibleStates::STATE_MIXED},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"columnheader", nsIAccessibleRole::ROLE_COLUMNHEADER, 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_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"combobox", nsIAccessibleRole::ROLE_COMBOBOX, eNameLabelOrTitle, eHasValueMinMax,
                nsIAccessibleStates::STATE_COLLAPSED | nsIAccessibleStates::STATE_HASPOPUP,
-            // Manually map EXT_STATE_SUPPORTS_AUTOCOMPLETION aaa:autocomplete
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
-            {eAria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED}, kEndEntry},
+            // Manually map EXT_STATE_SUPPORTS_AUTOCOMPLETION aria-autocomplete
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
+            {&nsAccessibilityAtoms::aria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED}, kEndEntry},
   {"description", nsIAccessibleRole::ROLE_TEXT_CONTAINER, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"dialog", nsIAccessibleRole::ROLE_DIALOG, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"document", nsIAccessibleRole::ROLE_DOCUMENT, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"grid", nsIAccessibleRole::ROLE_TABLE, eNameLabelOrTitle, eNoValue, nsIAccessibleStates::STATE_FOCUSABLE,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"gridcell", nsIAccessibleRole::ROLE_CELL, eNameOkFromChildren, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
-            {eAria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED},
-            {eAria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
-            {eAria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
+            {&nsAccessibilityAtoms::aria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"group", nsIAccessibleRole::ROLE_GROUPING, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"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},
+            {&nsAccessibilityAtoms::aria_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},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
+            {&nsAccessibilityAtoms::aria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
   {"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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
+            {&nsAccessibilityAtoms::aria_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},
-            {eAria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE}, kEndEntry},
   {"menu", nsIAccessibleRole::ROLE_MENUPOPUP, eNameLabelOrTitle, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"menubar", nsIAccessibleRole::ROLE_MENUBAR, eNameLabelOrTitle, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"menuitem", nsIAccessibleRole::ROLE_MENUITEM, eNameOkFromChildren, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED },
+            {&nsAccessibilityAtoms::aria_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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED }, kEndEntry},
   {"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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_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},
+            {&nsAccessibilityAtoms::aria_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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED}, kEndEntry},
   {"radiogroup", nsIAccessibleRole::ROLE_GROUPING, eNameLabelOrTitle, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"region", nsIAccessibleRole::ROLE_PANE, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"row", nsIAccessibleRole::ROLE_ROW, 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_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
-            {eAria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
+            {&nsAccessibilityAtoms::aria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED}, kEndEntry},
   {"rowheader", nsIAccessibleRole::ROLE_ROWHEADER, 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_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"section", nsIAccessibleRole::ROLE_SECTION, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"separator", nsIAccessibleRole::ROLE_SEPARATOR, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"slider", nsIAccessibleRole::ROLE_SLIDER, eNameLabelOrTitle, eHasValueMinMax, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"spinbutton", nsIAccessibleRole::ROLE_SPINBUTTON, eNameLabelOrTitle, eHasValueMinMax, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"status", nsIAccessibleRole::ROLE_STATUSBAR, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"tab", nsIAccessibleRole::ROLE_PAGETAB, eNameOkFromChildren, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"tablist", nsIAccessibleRole::ROLE_PAGETABLIST, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"tabpanel", nsIAccessibleRole::ROLE_PROPERTYPAGE, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"textbox", nsIAccessibleRole::ROLE_ENTRY, eNameLabelOrTitle, eNoValue, kNoReqStates,
-            // Manually map EXT_STATE_SINGLE_LINE and EXT_STATE_MULTI_LINE FROM aaa:multiline
-            // Manually map EXT_STATE_SUPPORTS_AUTOCOMPLETION aaa:autocomplete
-            {eAria_autocomplete, "list", nsIAccessibleStates::STATE_HASPOPUP},
-            {eAria_autocomplete, "both", nsIAccessibleStates::STATE_HASPOPUP},
-            {eAria_secret, kBoolState, nsIAccessibleStates::STATE_PROTECTED},
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
-            {eAria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
+            // Manually map EXT_STATE_SINGLE_LINE and EXT_STATE_MULTI_LINE FROM aria-multiline
+            // Manually map EXT_STATE_SUPPORTS_AUTOCOMPLETION aria-autocomplete
+            {&nsAccessibilityAtoms::aria_autocomplete, "list", nsIAccessibleStates::STATE_HASPOPUP},
+            {&nsAccessibilityAtoms::aria_autocomplete, "both", nsIAccessibleStates::STATE_HASPOPUP},
+            {&nsAccessibilityAtoms::aria_secret, kBoolState, nsIAccessibleStates::STATE_PROTECTED},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"toolbar", nsIAccessibleRole::ROLE_TOOLBAR, eNameLabelOrTitle, eNoValue, kNoReqStates,
-            {eAria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"tooltip", nsIAccessibleRole::ROLE_TOOLTIP, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"tree", nsIAccessibleRole::ROLE_OUTLINE, 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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
+            {&nsAccessibilityAtoms::aria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
   {"treegrid", nsIAccessibleRole::ROLE_TREE_TABLE, 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},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_readonly, kBoolState, nsIAccessibleStates::STATE_READONLY},
+            {&nsAccessibilityAtoms::aria_multiselectable, kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
   {"treeitem", nsIAccessibleRole::ROLE_OUTLINEITEM, 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_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},},
+            {&nsAccessibilityAtoms::aria_disabled, kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
+            {&nsAccessibilityAtoms::aria_selected, kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_selected, "false", nsIAccessibleStates::STATE_SELECTABLE},
+            {&nsAccessibilityAtoms::aria_expanded, kBoolState, nsIAccessibleStates::STATE_EXPANDED},
+            {&nsAccessibilityAtoms::aria_expanded, "false", nsIAccessibleStates::STATE_COLLAPSED},
+            {&nsAccessibilityAtoms::aria_checked, kBoolState, nsIAccessibleStates::STATE_CHECKED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_checked, "mixed", nsIAccessibleStates::STATE_MIXED | nsIAccessibleStates::STATE_CHECKABLE},
+            {&nsAccessibilityAtoms::aria_checked, "false", nsIAccessibleStates::STATE_CHECKABLE},},
 };
 
 PRUint32 nsARIAMap::gWAIRoleMapLength = NS_ARRAY_LENGTH(nsARIAMap::gWAIRoleMap);
 
 nsRoleMapEntry nsARIAMap::gLandmarkRoleMap = {
   "",
   nsIAccessibleRole::ROLE_NOTHING,
   eNameLabelOrTitle,
@@ -226,16 +214,16 @@ nsRoleMapEntry nsARIAMap::gLandmarkRoleM
 };
 
 /**
  * Universal states:
  * The following state rules are applied to any accessible element,
  * whether there is an ARIA role or not:
  */
 nsStateMapEntry nsARIAMap::gWAIUnivStateMap[] = {
-  {eAria_required, kBoolState, nsIAccessibleStates::STATE_REQUIRED},
-  {eAria_invalid,  kBoolState, nsIAccessibleStates::STATE_INVALID},
-  {eAria_haspopup, kBoolState, nsIAccessibleStates::STATE_HASPOPUP},
-  {eAria_busy,     "true",     nsIAccessibleStates::STATE_BUSY},
-  {eAria_busy,     "error",    nsIAccessibleStates::STATE_INVALID},
+  {&nsAccessibilityAtoms::aria_required, kBoolState, nsIAccessibleStates::STATE_REQUIRED},
+  {&nsAccessibilityAtoms::aria_invalid,  kBoolState, nsIAccessibleStates::STATE_INVALID},
+  {&nsAccessibilityAtoms::aria_haspopup, kBoolState, nsIAccessibleStates::STATE_HASPOPUP},
+  {&nsAccessibilityAtoms::aria_busy,     "true",     nsIAccessibleStates::STATE_BUSY},
+  {&nsAccessibilityAtoms::aria_busy,     "error",    nsIAccessibleStates::STATE_INVALID},
   kEndEntry
 };
 
--- a/accessible/src/base/nsARIAMap.h
+++ b/accessible/src/base/nsARIAMap.h
@@ -38,22 +38,16 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsARIAMap_H_
 #define _nsARIAMap_H_
 
 #include "prtypes.h"
 #include "nsAccessibilityAtoms.h"
 
-#define ARIA_PROPERTY(atom) eAria_##atom,
-enum EAriaProperty {
-#include "nsARIAPropertyList.h"
-  eAria_none };
-#undef ARIA_PROPERTY
-
 // Name mapping rule: can the name be computed from descendants?
 enum ENameRule
 {
   // eNameLabelOrTitle:
   // Collect name from:
   //   1) The content subtrees pointed to by labelledby
   //      which contains the IDs for the label content, or if unspecified
   //   2) The title attribute if specified
@@ -68,30 +62,30 @@ enum ENameRule
   //   3) The title attribute if specified
   eNameOkFromChildren
 };
 
 // Is nsIAccessible value supported for this role or not?
 enum EValueRule
 {
   eNoValue,
-  eHasValueMinMax    // Supports value, min and max from aaa:valuenow, valuemin and valuemax
+  eHasValueMinMax    // Supports value, min and max from aria-valuenow, aria-valuemin and aria-valuemax
 };
 
 // Used for an nsStateMapEntry if a given state attribute supports "true" and "false"
 #define kBoolState 0
 
 // Used in nsRoleMapEntry.state if no nsIAccessibleStates are automatic for a given role
 #define kNoReqStates 0
 
 // For this name and value pair, what is the nsIAccessibleStates mapping.
 // nsStateMapEntry.state
 struct nsStateMapEntry
 {
-  EAriaProperty attributeName;  // eARIA_none indicates last entry in map
+  nsIAtom** attributeName;  // nsnull indicates last entry in map
   const char* attributeValue; // magic value of kBoolState (0) means supports "true" and "false"
   PRUint32 state;             // If match, this is the nsIAccessibleStates to map to
 };
 
 // For each ARIA role, this maps the nsIAccessible information
 struct nsRoleMapEntry
 {
   // ARIA role: string representation such as "button"
@@ -105,17 +99,17 @@ struct nsRoleMapEntry
   
   // Value mapping rule: how to compute nsIAccessible value
   EValueRule valueRule;
   
   // Automatic state mapping rule: always include in nsIAccessibleStates
   PRUint32 state;   // or kNoReqStates if no nsIAccessibleStates are automatic for this role.
   
   // ARIA properties supported for this role
-  // (in other words, the aaa:foo attribute to nsIAccessibleStates mapping rules)
+  // (in other words, the aria-foo attribute to nsIAccessibleStates mapping rules)
   // Currently you cannot have unlimited mappings, because
   // a variable sized array would not allow the use of
   // C++'s struct initialization feature.
   nsStateMapEntry attributeMap1;
   nsStateMapEntry attributeMap2;
   nsStateMapEntry attributeMap3;
   nsStateMapEntry attributeMap4;
   nsStateMapEntry attributeMap5;
@@ -126,17 +120,15 @@ struct nsRoleMapEntry
 
 /**
  *  These are currently initialized (hardcoded) in nsARIAMap.cpp, 
  *  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
deleted file mode 100644
--- a/accessible/src/base/nsARIAPropertyList.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:expandtab:shiftwidth=2:tabstop=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 IBM Corporation
- * Portions created by the Initial Developer are Copyright (C)2007
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Aaron Leventhal <aleventh@us.ibm.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 ***** */
-
-  // ARIA properties
-ARIA_PROPERTY(activedescendant)
-ARIA_PROPERTY(atomic)
-ARIA_PROPERTY(autocomplete)
-ARIA_PROPERTY(busy)
-ARIA_PROPERTY(channel)
-ARIA_PROPERTY(checked)
-ARIA_PROPERTY(controls)
-ARIA_PROPERTY(datatype)
-ARIA_PROPERTY(describedby)
-ARIA_PROPERTY(disabled)
-ARIA_PROPERTY(dropeffect)
-ARIA_PROPERTY(expanded)
-ARIA_PROPERTY(flowto)
-ARIA_PROPERTY(grab)
-ARIA_PROPERTY(haspopup)
-ARIA_PROPERTY(invalid)
-ARIA_PROPERTY(labelledby)
-ARIA_PROPERTY(level)
-ARIA_PROPERTY(live)
-ARIA_PROPERTY(multiline)
-ARIA_PROPERTY(multiselectable)
-ARIA_PROPERTY(owns)
-ARIA_PROPERTY(posinset)
-ARIA_PROPERTY(pressed)
-ARIA_PROPERTY(readonly)
-ARIA_PROPERTY(relevant)
-ARIA_PROPERTY(required)
-ARIA_PROPERTY(secret)
-ARIA_PROPERTY(selected)
-ARIA_PROPERTY(setsize)
-ARIA_PROPERTY(sort)
-ARIA_PROPERTY(valuenow)
-ARIA_PROPERTY(valuemin)
-ARIA_PROPERTY(valuemax)
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -874,20 +874,8 @@ nsAccessNode::GetLanguage(nsAString& aLa
     if (doc) {
       doc->GetHeaderData(nsAccessibilityAtoms::headerContentLanguage, aLanguage);
     }
   }
  
   return NS_OK;
 }
 
-PRBool
-nsAccessNode::GetARIARole(nsIContent *aContent, nsString& aRole)
-{
-  aRole.Truncate();
-
-  if (aContent->IsNodeOfType(nsINode::eHTML)) {
-    // Allow non-namespaced role attribute in HTML
-    return aContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::role, aRole);
-  }
-  // In non-HTML content, use XHTML namespaced-role attribute
-  return aContent->GetAttr(kNameSpaceID_XHTML, nsAccessibilityAtoms::role, aRole);
-}
--- a/accessible/src/base/nsAccessNode.h
+++ b/accessible/src/base/nsAccessNode.h
@@ -67,26 +67,16 @@ class nsApplicationAccessibleWrap;
 class nsIDocShellTreeItem;
 
 #define ACCESSIBLE_BUNDLE_URL "chrome://global-platform/locale/accessible.properties"
 #define PLATFORM_KEYS_BUNDLE_URL "chrome://global-platform/locale/platformKeys.properties"
 
 typedef nsInterfaceHashtable<nsVoidPtrHashKey, nsIAccessNode>
         nsAccessNodeHashtable;
 
-/**
- * Does the current content have this ARIA role? 
- * Implemented as a compiler macro so that length can be computed at compile time.
- * @param aContent  Node to get role string from
- * @param aRoleName Role string to compare with -- literal const char*
- * @return PR_TRUE if there is a match
- */
-#define ARIARoleEquals(aContent, aRoleName) \
-  nsAccessNode::ARIARoleEqualsImpl(aContent, aRoleName, NS_ARRAY_LENGTH(aRoleName) - 1)
-
 class nsAccessNode: public nsIAccessNode, public nsPIAccessNode
 {
   public: // construction, destruction
     nsAccessNode(nsIDOMNode *, nsIWeakReference* aShell);
     virtual ~nsAccessNode();
 
     NS_DECL_ISUPPORTS
     NS_DECL_NSIACCESSNODE
@@ -113,35 +103,16 @@ class nsAccessNode: public nsIAccessNode
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIDocument *aDocument);
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIWeakReference *aWeakShell);
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIDocShellTreeItem *aContainer, PRBool aCanCreate = PR_FALSE);
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIDOMNode *aNode);
 
     static already_AddRefed<nsIDOMNode> GetDOMNodeForContainer(nsISupports *aContainer);
     static already_AddRefed<nsIPresShell> GetPresShellFor(nsIDOMNode *aStartNode);
     
-    // Return PR_TRUE if there is a role attribute
-    static PRBool HasRoleAttribute(nsIContent *aContent)
-    {
-      return (aContent->IsNodeOfType(nsINode::eHTML) && aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::role)) ||
-              aContent->HasAttr(kNameSpaceID_XHTML, nsAccessibilityAtoms::role) ||
-              aContent->HasAttr(kNameSpaceID_XHTML2_Unofficial, nsAccessibilityAtoms::role);
-    }
-
-    /**
-     * Provide the role string if there is one
-     * @param aContent Node to get role string from
-     * @param aRole String to fill role into
-     * @return PR_TRUE if there is a role attribute, and fill it into aRole
-     */
-    static PRBool GetARIARole(nsIContent *aContent, nsString& aRole);
-
-    static PRBool ARIARoleEqualsImpl(nsIContent* aContent, const char* aRoleName, PRUint32 aLen)
-      { nsAutoString role; return GetARIARole(aContent, role) && role.EqualsASCII(aRoleName, aLen); }
-
     static void GetComputedStyleDeclaration(const nsAString& aPseudoElt,
                                             nsIDOMElement *aElement,
                                             nsIDOMCSSStyleDeclaration **aCssDecl);
 
     already_AddRefed<nsRootAccessible> GetRootAccessible();
 
     static nsIDOMNode *gLastFocusedNode;
     static nsIAccessibilityService* GetAccService();
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -83,16 +83,17 @@ ACCESSIBILITY_ATOM(tableCaptionFrame, "T
 ACCESSIBILITY_ATOM(tableCellFrame, "TableCellFrame")
 ACCESSIBILITY_ATOM(tableOuterFrame, "TableOuterFrame")
 
   // Alphabetical list of tag names
 ACCESSIBILITY_ATOM(a, "a")
 ACCESSIBILITY_ATOM(abbr, "abbr")
 ACCESSIBILITY_ATOM(acronym, "acronym")
 ACCESSIBILITY_ATOM(area, "area")
+ACCESSIBILITY_ATOM(autocomplete, "autocomplete")
 ACCESSIBILITY_ATOM(blockquote, "blockquote")
 ACCESSIBILITY_ATOM(br, "br")
 ACCESSIBILITY_ATOM(body, "body")
 ACCESSIBILITY_ATOM(caption, "caption") // XUL
 ACCESSIBILITY_ATOM(choices, "choices") // XForms
 ACCESSIBILITY_ATOM(description, "description")    // XUL
 ACCESSIBILITY_ATOM(dd, "dd")
 ACCESSIBILITY_ATOM(div, "div")
@@ -144,49 +145,85 @@ ACCESSIBILITY_ATOM(ul, "ul")
 
   // Alphabetical list of attributes
 ACCESSIBILITY_ATOM(acceltext, "acceltext")
 ACCESSIBILITY_ATOM(accesskey, "accesskey")
 ACCESSIBILITY_ATOM(alt, "alt")
 ACCESSIBILITY_ATOM(anonid, "anonid") // Used for ID's in XBL
 ACCESSIBILITY_ATOM(contenteditable, "contenteditable")
 ACCESSIBILITY_ATOM(control, "control")
+ACCESSIBILITY_ATOM(disabled, "disabled")
 ACCESSIBILITY_ATOM(cycles, "cycles") // used for XUL cycler attribute
 ACCESSIBILITY_ATOM(curpos, "curpos") // XUL
 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(multiline, "multiline") // XUL
 ACCESSIBILITY_ATOM(name, "name")
 ACCESSIBILITY_ATOM(onclick, "onclick")
+ACCESSIBILITY_ATOM(readonly, "readonly")
 ACCESSIBILITY_ATOM(src, "src")
+ACCESSIBILITY_ATOM(selected, "selected")
 ACCESSIBILITY_ATOM(summary, "summary")
 ACCESSIBILITY_ATOM(tabindex, "tabindex")
 ACCESSIBILITY_ATOM(title, "title")
 ACCESSIBILITY_ATOM(tooltiptext, "tooltiptext")
 ACCESSIBILITY_ATOM(type, "type")
 ACCESSIBILITY_ATOM(value, "value")
 
   // ARIA (DHTML accessibility) attributes
   // Also add to nsARIAMap.cpp and nsARIAMap.h
   // ARIA role attribute
 ACCESSIBILITY_ATOM(role, "role")
-
-  // ARIA properties
-#define ARIA_PROPERTY(atom) ACCESSIBILITY_ATOM(atom, #atom)
-#include "nsARIAPropertyList.h"
-#undef ARIA_PROPERTY
-
-#define ARIA_PROPERTY(atom) ACCESSIBILITY_ATOM(aria_##atom, "aria-"#atom)
-#include "nsARIAPropertyList.h"
-#undef ARIA_PROPERTY
+ACCESSIBILITY_ATOM(aria_activedescendant, "aria-activedescendant")
+ACCESSIBILITY_ATOM(aria_atomic, "aria-atomic")
+ACCESSIBILITY_ATOM(aria_autocomplete, "aria-autocomplete")
+ACCESSIBILITY_ATOM(aria_busy, "aria-busy")
+ACCESSIBILITY_ATOM(aria_channel, "aria-channel")
+ACCESSIBILITY_ATOM(aria_checked, "aria-checked")
+ACCESSIBILITY_ATOM(aria_controls, "aria-controls")
+ACCESSIBILITY_ATOM(aria_datatype, "aria-datatype")
+ACCESSIBILITY_ATOM(aria_describedby, "aria-describedby")
+ACCESSIBILITY_ATOM(aria_droppable, "aria-droppable")
+ACCESSIBILITY_ATOM(aria_disabled, "aria-disabled")
+ACCESSIBILITY_ATOM(aria_dropeffect, "aria-dropeffect")
+ACCESSIBILITY_ATOM(aria_expanded, "aria-expanded")
+ACCESSIBILITY_ATOM(aria_flowto, "aria-flowto")
+ACCESSIBILITY_ATOM(aria_grab, "aria-grab")
+ACCESSIBILITY_ATOM(aria_haspopup, "aria-haspopup")
+ACCESSIBILITY_ATOM(aria_invalid, "aria-invalid")
+ACCESSIBILITY_ATOM(aria_labelledby, "aria-labelledby")
+ACCESSIBILITY_ATOM(aria_level, "aria-level")
+ACCESSIBILITY_ATOM(aria_live, "aria-live")
+ACCESSIBILITY_ATOM(aria_multiline, "aria-multiline")
+ACCESSIBILITY_ATOM(aria_multiselectable, "aria-multiselectable")
+ACCESSIBILITY_ATOM(aria_owns, "aria-owns")
+ACCESSIBILITY_ATOM(aria_posinset, "aria-posinset")
+ACCESSIBILITY_ATOM(aria_pressed, "aria-pressed")
+ACCESSIBILITY_ATOM(aria_readonly, "aria-readonly")
+ACCESSIBILITY_ATOM(aria_relevant, "aria-relevant")
+ACCESSIBILITY_ATOM(aria_required, "aria-required")
+ACCESSIBILITY_ATOM(aria_secret, "aria-secret")
+ACCESSIBILITY_ATOM(aria_selected, "aria-selected")
+ACCESSIBILITY_ATOM(aria_setsize, "aria-setsize")
+ACCESSIBILITY_ATOM(aria_sort, "aria-sort")
+ACCESSIBILITY_ATOM(aria_valuenow, "aria-valuenow")
+ACCESSIBILITY_ATOM(aria_valuemin, "aria-valuemin")
+ACCESSIBILITY_ATOM(aria_valuemax, "aria-valuemax")
 
   // misc atoms
 // a form property used to obtain the default label
 // of an HTML button from the button frame
 ACCESSIBILITY_ATOM(defaultLabel, "defaultLabel")
+
+// Object attributes
+ACCESSIBILITY_ATOM(level, "level")
+ACCESSIBILITY_ATOM(posinset, "posinset") 
+ACCESSIBILITY_ATOM(setsize, "setsize")
+ACCESSIBILITY_ATOM(lineNumber, "line-number")
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -1396,22 +1396,35 @@ NS_IMETHODIMP nsAccessibilityService::Ge
           tag == nsAccessibilityAtoms::tr ||
           tag == nsAccessibilityAtoms::tbody ||
           tag == nsAccessibilityAtoms::tfoot ||
           tag == nsAccessibilityAtoms::thead) {
         nsIContent *tableContent = content;
         nsAutoString tableRole;
         while ((tableContent = tableContent->GetParent()) != nsnull) {
           if (tableContent->Tag() == nsAccessibilityAtoms::table) {
-            nsIFrame *tableFrame = aPresShell->GetPrimaryFrameFor(tableContent);
-            if (!tableFrame || tableFrame->GetType() != nsAccessibilityAtoms::tableOuterFrame ||
-                nsAccessNode::HasRoleAttribute(tableContent)) {
-              // Table that we're a descendant of is not styled as a table,
-              // and has no table accessible for an ancestor, or
-              // table that we're a descendant of is presentational
+            // Table that we're a descendant of is not styled as a table,
+            // and has no table accessible for an ancestor, or
+            // table that we're a descendant of is presentational
+
+            nsCOMPtr<nsIDOMNode> tableNode(do_QueryInterface(tableContent));
+            if (tableNode) {
+              nsRoleMapEntry *tableRoleMapEntry =
+                nsAccUtils::GetRoleMapEntry(tableNode);
+              if (tableRoleMapEntry &&
+                  tableRoleMapEntry != &nsARIAMap::gLandmarkRoleMap) {
+                tryTagNameOrFrame = PR_FALSE;
+                break;
+              }
+            }
+
+            nsIFrame *tableFrame =
+              aPresShell->GetPrimaryFrameFor(tableContent);
+            if (!tableFrame ||
+                tableFrame->GetType() != nsAccessibilityAtoms::tableOuterFrame) {
               tryTagNameOrFrame = PR_FALSE;
             }
             break;
           }
         }
       }
     }
 
@@ -1471,43 +1484,33 @@ NS_IMETHODIMP nsAccessibilityService::Ge
 
   return InitAccessible(newAcc, aAccessible, roleMapEntry);
 }
 
 PRBool
 nsAccessibilityService::HasUniversalAriaProperty(nsIContent *aContent,
                                                  nsIWeakReference *aWeakShell)
 {
-  nsCOMPtr<nsIAccessibleDocument> docAccessible =
-    nsAccessNode::GetDocAccessibleFor(aWeakShell);
-  if (!docAccessible) {
-    return PR_FALSE;
-  }
-
-  // Precalculate |ariaPropTypes| so that HasAriaProperty() doesn't have to do that each time
-  PRUint32 ariaPropTypes;
-  docAccessible->GetAriaPropTypes(&ariaPropTypes);
-
-  return nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_atomic, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_busy, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_channel, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_controls, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_datatype, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_describedby, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_dropeffect, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_flowto, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_grab, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_haspopup, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_invalid, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_labelledby, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_live, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_owns, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_relevant, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_required, ariaPropTypes) ||
-         nsAccUtils::HasAriaProperty(aContent, aWeakShell, eAria_sort, ariaPropTypes);
+  return aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_atomic) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_busy) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_channel) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_controls) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_datatype) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_describedby) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_dropeffect) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_flowto) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_grab) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_haspopup) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_invalid) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_labelledby) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_live) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_owns) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_relevant) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_required) ||
+         aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_sort);
 }
 
 NS_IMETHODIMP
 nsAccessibilityService::GetRelevantContentNodeFor(nsIDOMNode *aNode,
                                                   nsIDOMNode **aRelevantNode)
 {
   // The method returns node that is relevant for attached accessible check.
   // Sometimes element that is XBL widget hasn't accessible children in
--- a/accessible/src/base/nsAccessibilityUtils.cpp
+++ b/accessible/src/base/nsAccessibilityUtils.cpp
@@ -576,88 +576,22 @@ nsAccUtils::GetDocShellTreeItemFor(nsIDO
 
 PRBool
 nsAccUtils::GetID(nsIContent *aContent, nsAString& aID)
 {
   nsIAtom *idAttribute = aContent->GetIDAttributeName();
   return idAttribute ? aContent->GetAttr(kNameSpaceID_None, idAttribute, aID) : PR_FALSE;
 }
 
-PRUint32
-nsAccUtils::GetAriaPropTypes(nsIContent *aContent, nsIWeakReference *aWeakShell)
-{
-  NS_ENSURE_ARG_POINTER(aContent);
-
-  PRUint32 ariaPropTypes = 0;
-
-  // Get the doc accessible using the optimsal methodology
-  nsCOMPtr<nsIAccessibleDocument> docAccessible;
-  if (aWeakShell) {
-    docAccessible = nsAccessNode::GetDocAccessibleFor(aWeakShell);
-  }
-  else {
-      nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aContent);
-    if (node) {
-      docAccessible = nsAccessNode::GetDocAccessibleFor(node);
-    }
-  }
-  if (docAccessible) {
-    docAccessible->GetAriaPropTypes(&ariaPropTypes);
-  }
-  return ariaPropTypes;
-}
-
-PRBool
-nsAccUtils::HasAriaProperty(nsIContent *aContent, nsIWeakReference *aWeakShell,
-                            EAriaProperty aProperty, PRUint32 aAriaPropTypes)
-{
-  if (!aAriaPropTypes) {
-    // The property types to check for is unknown, get it from the doc accessible
-    aAriaPropTypes = GetAriaPropTypes(aContent, aWeakShell);
-  }
-
-  return ((aAriaPropTypes & nsIAccessibleDocument::eCheckNamespaced) &&
-          aContent->HasAttr(kNameSpaceID_WAIProperties,
-                            *nsARIAMap::gAriaAtomPtrsNS[aProperty])) ||
-         ((aAriaPropTypes & nsIAccessibleDocument::eCheckHyphenated) &&
-          aContent->HasAttr(kNameSpaceID_None,
-                            *nsARIAMap::gAriaAtomPtrsHyphenated[aProperty]));
-}
-
-PRBool
-nsAccUtils::GetAriaProperty(nsIContent *aContent, nsIWeakReference *aWeakShell,
-                            EAriaProperty aProperty, nsAString& aValue,
-                            PRUint32 aAriaPropTypes)
-{
-  aValue.Truncate();
-  if (!aAriaPropTypes) {
-    // The property types to check for is unknown, get it from the doc accessible
-    aAriaPropTypes = GetAriaPropTypes(aContent, aWeakShell);
-  }
-  return ((aAriaPropTypes & nsIAccessibleDocument::eCheckNamespaced) &&
-          aContent->GetAttr(kNameSpaceID_WAIProperties,
-                            *nsARIAMap::gAriaAtomPtrsNS[aProperty],
-                            aValue)) ||
-         ((aAriaPropTypes & nsIAccessibleDocument::eCheckHyphenated) &&
-          aContent->GetAttr(kNameSpaceID_None,
-                            *nsARIAMap::gAriaAtomPtrsHyphenated[aProperty],
-                            aValue));
-}
-
 nsIContent*
 nsAccUtils::FindNeighbourPointingToNode(nsIContent *aForNode, 
-                                        EAriaProperty aAriaProperty, 
+                                        nsIAtom *aRelationAttr,
                                         nsIAtom *aTagName,
-                                        nsIAtom *aRelationAttr,
                                         PRUint32 aAncestorLevelsToSearch)
 {
-  NS_ASSERTION(aAriaProperty == eAria_none || !aRelationAttr,
-               "Cannot pass in both an ARIA relation property and an atom relation. Choose one");
-  NS_ASSERTION(aAriaProperty == eAria_none || !aTagName,
-               "Cannot use aTagName with ARIA relation property, because ARIA relations apply to any tag");
   nsCOMPtr<nsIContent> binding;
   nsAutoString controlID;
   if (!nsAccUtils::GetID(aForNode, controlID)) {
     binding = aForNode->GetBindingParent();
     if (binding == aForNode)
       return nsnull;
 
     aForNode->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::anonid, controlID);
@@ -698,171 +632,113 @@ nsAccUtils::FindNeighbourPointingToNode(
         if (NS_FAILED(rv))
           return nsnull;
 
         nsCOMPtr<nsIContent> content = do_QueryInterface(node);
         if (!content)
           return nsnull;
 
         if (content != prevSearched) {
-          labelContent = FindDescendantPointingToID(&controlID, content, aAriaProperty,
+          labelContent = FindDescendantPointingToID(&controlID, content,
                                                     aRelationAttr, nsnull, aTagName);
         }
       }
       break;
     }
 
-    labelContent = FindDescendantPointingToID(&controlID, aForNode, aAriaProperty,
+    labelContent = FindDescendantPointingToID(&controlID, aForNode,
                                               aRelationAttr, prevSearched, aTagName);
     prevSearched = aForNode;
   }
 
   return labelContent;
 }
 
 // Pass in aAriaProperty = null and aRelationAttr == nsnull if any <label> will do
 nsIContent*
 nsAccUtils::FindDescendantPointingToID(const nsString *aId,
                                        nsIContent *aLookContent,
-                                       EAriaProperty aAriaProperty,
                                        nsIAtom *aRelationAttr,
                                        nsIContent *aExcludeContent,
                                        nsIAtom *aTagType)
 {
   // Surround id with spaces for search
   nsCAutoString idWithSpaces(' ');
   LossyAppendUTF16toASCII(*aId, idWithSpaces);
   idWithSpaces += ' ';
-  PRUint32 ariaPropTypes = (aAriaProperty == eAria_none) ? 0 :
-                            nsAccUtils::GetAriaPropTypes(aLookContent);
   return FindDescendantPointingToIDImpl(idWithSpaces, aLookContent,
-                                        aAriaProperty, ariaPropTypes,
                                         aRelationAttr, aExcludeContent, aTagType);
 }
 
 nsIContent*
 nsAccUtils::FindDescendantPointingToIDImpl(nsCString& aIdWithSpaces,
                                            nsIContent *aLookContent,
-                                           EAriaProperty aAriaProperty,
-                                           PRUint32 aAriaPropTypes,
                                            nsIAtom *aRelationAttr,
                                            nsIContent *aExcludeContent,
                                            nsIAtom *aTagType)
 {
-  if (aAriaProperty != eAria_none) {  // Tag ignored for ARIA properties, which can apply to anything
+  NS_ENSURE_TRUE(aLookContent, nsnull);
+  NS_ENSURE_TRUE(aRelationAttr, nsnull);
+
+  if (!aTagType || aLookContent->Tag() == aTagType) {
+    // Tag matches
+    // Check for ID in the attribute aRelationAttr, which can be a list
     nsAutoString idList;
-    if (nsAccUtils::GetAriaProperty(aLookContent, nsnull, aAriaProperty,
-                                    idList, aAriaPropTypes)) {
+    if (aLookContent->GetAttr(kNameSpaceID_None, aRelationAttr, idList)) {
       idList.Insert(' ', 0);  // Surround idlist with spaces for search
       idList.Append(' ');
       // idList is now a set of id's with spaces around each,
       // and id also has spaces around it.
       // If id is a substring of idList then we have a match
       if (idList.Find(aIdWithSpaces) != -1) {
         return aLookContent;
       }
     }
-  }
-  else if (!aTagType || aLookContent->Tag() == aTagType) {
-    // Tag matches
-    if (aRelationAttr) {
-      // Check for ID in the attribute aRelationAttr, which can be a list
-      nsAutoString idList;
-      if (aLookContent->GetAttr(kNameSpaceID_None, aRelationAttr, idList)) {
-        idList.Insert(' ', 0);  // Surround idlist with spaces for search
-        idList.Append(' ');
-        // idList is now a set of id's with spaces around each,
-        // and id also has spaces around it.
-        // If id is a substring of idList then we have a match
-        if (idList.Find(aIdWithSpaces) != -1) {
-          return aLookContent;
-        }
-      }
-    }
     if (aTagType) {
       // Don't bother to search descendants of an element with matching tag.
       // That would be like looking for a nested <label> or <description>
       return nsnull;
     }
   }
 
   // Recursively search descendants for match
   PRUint32 count  = 0;
   nsIContent *child;
   nsIContent *labelContent = nsnull;
 
   while ((child = aLookContent->GetChildAt(count++)) != nsnull) {
     if (child != aExcludeContent) {
       labelContent = FindDescendantPointingToIDImpl(aIdWithSpaces, child,
-                                                    aAriaProperty, aAriaPropTypes,
                                                     aRelationAttr, aExcludeContent, aTagType);
       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)) {
+  if (!content || !content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::role, 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
+    const char *role = NS_LossyConvertUTF16toASCII(tokenizer.nextToken()).get();
     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);
+      PRInt32 compare = PL_strcmp(role, 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 {
--- a/accessible/src/base/nsAccessibilityUtils.h
+++ b/accessible/src/base/nsAccessibilityUtils.h
@@ -260,113 +260,61 @@ public:
    * Get the ID for an element, in some types of XML this may not be the ID attribute
    * @param aContent  Node to get the ID for
    * @param aID       Where to put ID string
    * @return          PR_TRUE if there is an ID set for this node
    */
   static PRBool GetID(nsIContent *aContent, nsAString& aID);
 
   /**
-   * Find out what kinds of properties are checked for this content node's document
-   * @param aContent     The content node we're going to look for ARIA properties on
-   * @param aWeakShell   The presshell for the document we're looking for ARIA properties on (optional optimization)
-   * @return             The types of properties checked
-   */
-  static PRUint32 GetAriaPropTypes(nsIContent *aContent, nsIWeakReference *aWeakShell = nsnull);
-
-  /**
-   *  Check for the relevant ARIA property. Can check either for a properly namespaced property,
-   *  or a fake hyphenated namespace using "aria-" as a prefix in HTML. Is optimized to only
-   *  check for each type when it is possible to exist on a given node.
-   *  @param aContent     Node to check for property on
-   *  @param aWeakShell   The current pres shell if known (as an optimization), or nsnull if not known by caller
-   *  @param aProperty    An enumeration indicating which ARIA property we are checking
-   *  @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 HasAriaProperty(nsIContent *aContent, nsIWeakReference *aWeakShell,
-                                EAriaProperty aProperty,
-                                PRUint32 aCheckFlags = 0);
-
-  /**
-   *  Get the relevant ARIA property. Can check either for a properly namespaced property,
-   *  or a fake hyphenated namespace using "aria-" as a prefix in HTML. Is optimized to only
-   *  check for each type when it is possible to exist on a given node.
-   *  @param aContent     Node to check for property on
-   *  @param aWeakShell   The current pres shell if known (as an optimization), or nsnull if not known by caller
-   *  @param aProperty    An enumeration indicating which ARIA property we are checking
-   *  @param aValue       Where to store the property value
-   *  @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 aRelationAttr - attribute name of searched element, ignored if aAriaProperty passed in
    * @param aTagName - tag name of searched element, or nsnull for any -- ignored if aAriaProperty passed in
-   * @param aRelationAttr - attribute name of searched element, ignored if aAriaProperty passed in
    * @param aAncestorLevelsToSearch - points how is the neighborhood of the
    *                                  given element big.
    */
   static nsIContent *FindNeighbourPointingToNode(nsIContent *aForNode,
-                                                 EAriaProperty aAriaProperty,
+                                                 nsIAtom *aRelationAttr,
                                                  nsIAtom *aTagName = nsnull,
-                                                 nsIAtom *aRelationAttr = nsnull,
                                                  PRUint32 aAncestorLevelsToSearch = 5);
 
   /**
    * Search for element that satisfies the requirements in subtree of the given
    * element. The requirements are tag name, attribute name and value of
    * attribute.
    *
    * @param aId - value of searched attribute
    * @param aLookContent - element that search is performed inside
-   * @param aAriaProperty - the ARIA property to search for or eAria_none, if aRelationAttr is passed in
-   * @param aRelationAttr - searched attribute-- ignored if aAriaProperty passed in
+   * @param aRelationAttr - searched attribute
    * @param                 if both aAriaProperty and aRelationAttr are null, then any element with aTagType will do
    * @param aExcludeContent - element that is skiped for search
    * @param aTagType - tag name of searched element, by default it is 'label' --
    *                   ignored if aAriaProperty passed in
    */
   static nsIContent *FindDescendantPointingToID(const nsString *aId,
                                                 nsIContent *aLookContent,
-                                                EAriaProperty aAriaProperty,
-                                                nsIAtom *aRelationAttr = nsnull,
+                                                nsIAtom *aRelationAttr,
                                                 nsIContent *aExcludeContent = nsnull,
                                                 nsIAtom *aTagType = nsAccessibilityAtoms::label);
 
   // Helper for FindDescendantPointingToID(), same args
   static nsIContent *FindDescendantPointingToIDImpl(nsCString& aIdWithSpaces,
                                                     nsIContent *aLookContent,
-                                                    EAriaProperty aAriaProperty,
-                                                    PRUint32 aAriaPropTypes,
-                                                    nsIAtom *aRelationAttr = nsnull,
+                                                    nsIAtom *aRelationAttrs,
                                                     nsIContent *aExcludeContent = nsnull,
                                                     nsIAtom *aTagType = nsAccessibilityAtoms::label);
 };
 
 #endif
 
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -178,17 +178,17 @@ PRBool nsAccessible::IsTextInterfaceSupp
   }
   return PR_TRUE; 
 }
 #endif
 
 nsresult nsAccessible::QueryInterface(REFNSIID aIID, void** aInstancePtr)
 {
   // Custom-built QueryInterface() knows when we support nsIAccessibleSelectable
-  // based on role attribute and waistate:multiselectable
+  // based on role attribute and aria-multiselectable
   *aInstancePtr = nsnull;
   
   if (aIID.Equals(NS_GET_IID(nsIAccessible))) {
     *aInstancePtr = static_cast<nsIAccessible*>(this);
     NS_ADDREF_THIS();
     return NS_OK;
   }
 
@@ -198,25 +198,25 @@ nsresult nsAccessible::QueryInterface(RE
     return NS_OK;
   }
 
   if (aIID.Equals(NS_GET_IID(nsIAccessibleSelectable))) {
     nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
     if (!content) {
       return NS_ERROR_FAILURE; // This accessible has been shut down
     }
-    if (HasRoleAttribute(content)) {
+    if (content->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::role)) {
       // If we have an XHTML role attribute present and the
-      // waistate multiselectable attribute is true, then we need
+      // aria-multiselectable attribute is true, then we need
       // to support nsIAccessibleSelectable
       // If either attribute (role or multiselectable) change, then we'll
       // destroy this accessible so that we can follow COM identity rules.
       nsAutoString multiselectable;
-      if (nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_multiselectable, multiselectable) &&
-          multiselectable.EqualsLiteral("true")) {
+      if (content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::aria_multiselectable,
+                               nsAccessibilityAtoms::_true, eCaseMatters)) {
         *aInstancePtr = static_cast<nsIAccessibleSelectable*>(this);
         NS_ADDREF_THIS();
         return NS_OK;
       }
     }
   }
 
   if (aIID.Equals(NS_GET_IID(nsIAccessibleValue))) {
@@ -309,25 +309,24 @@ NS_IMETHODIMP nsAccessible::GetDescripti
   // 3. it doesn't have an accName; or
   // 4. its title attribute already equals to its accName nsAutoString name; 
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (!content) {
     return NS_ERROR_FAILURE;  // Node shut down
   }
   if (!content->IsNodeOfType(nsINode::eTEXT)) {
     nsAutoString description;
-    nsresult rv = GetTextFromRelationID(eAria_describedby, description);
+    nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_describedby, description);
     if (NS_FAILED(rv)) {
       PRBool isXUL = content->IsNodeOfType(nsINode::eXUL);
       if (isXUL) {
         // Try XUL <description control="[id]">description text</description>
         nsIContent *descriptionContent =
-          nsAccUtils::FindNeighbourPointingToNode(content, eAria_none,
-                                                  nsAccessibilityAtoms::description,
-                                                  nsAccessibilityAtoms::control);
+          nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::control,
+                                                  nsAccessibilityAtoms::description);
 
         if (descriptionContent) {
           // We have a description content node
           AppendFlatStringFromSubtree(descriptionContent, &description);
         }
       }
       if (description.IsEmpty()) {
         nsIAtom *descAtom = isXUL ? nsAccessibilityAtoms::tooltiptext :
@@ -1390,36 +1389,23 @@ NS_IMETHODIMP nsAccessible::SetSelected(
   if (state & nsIAccessibleStates::STATE_SELECTABLE) {
     nsCOMPtr<nsIAccessible> multiSelect = GetMultiSelectFor(mDOMNode);
     if (!multiSelect) {
       return aSelect ? TakeFocus() : NS_ERROR_FAILURE;
     }
     nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
     NS_ASSERTION(content, "Called for dead accessible");
 
-    // For ARIA widgets use WAI namespace or hyphenated property, depending on what doc accepts
-    PRUint32 nameSpaceID = kNameSpaceID_None;  // Default
     if (mRoleMapEntry) {
-      if (0 == (nsAccUtils::GetAriaPropTypes(content, mWeakShell) &
-                nsIAccessibleDocument::eCheckNamespaced)) {
-        // No WAI namespaced properties used in this doc, use hyphenated property
-        if (aSelect) {
-          return content->SetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_selected,
-                                  NS_LITERAL_STRING("true"), PR_TRUE);
-        }
-        return content->UnsetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_selected, PR_TRUE);
+      if (aSelect) {
+        return content->SetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_selected,
+                                NS_LITERAL_STRING("true"), PR_TRUE);
       }
-      nameSpaceID = kNameSpaceID_WAIProperties;
+      return content->UnsetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_selected, PR_TRUE);
     }
-    // Use normal property
-    if (aSelect) {
-      return content->SetAttr(nameSpaceID, nsAccessibilityAtoms::selected,
-                              NS_LITERAL_STRING("true"), PR_TRUE);
-    }
-    return content->UnsetAttr(nameSpaceID, nsAccessibilityAtoms::selected, PR_TRUE);
   }
 
   return NS_ERROR_FAILURE;
 }
 
 /* void takeSelection (); */
 NS_IMETHODIMP nsAccessible::TakeSelection()
 {
@@ -1671,19 +1657,18 @@ nsresult nsAccessible::AppendFlatStringF
     AppendFlatStringFromSubtreeRecurse(aContent->GetChildAt(index), aFlatString);
   }
   return NS_OK;
 }
 
 nsIContent *nsAccessible::GetLabelContent(nsIContent *aForNode)
 {
   if (aForNode->IsNodeOfType(nsINode::eXUL))
-    return nsAccUtils::FindNeighbourPointingToNode(aForNode, eAria_none,
-                                                   nsAccessibilityAtoms::label,
-                                                   nsAccessibilityAtoms::control);
+    return nsAccUtils::FindNeighbourPointingToNode(aForNode, nsAccessibilityAtoms::control,
+                                                   nsAccessibilityAtoms::label);
 
   return GetHTMLLabelContent(aForNode);
 }
 
 nsIContent* nsAccessible::GetHTMLLabelContent(nsIContent *aForNode)
 {
   // Get either <label for="[id]"> element which explictly points to aForNode, or 
   // <label> ancestor which implicitly point to it
@@ -1701,43 +1686,43 @@ nsIContent* nsAccessible::GetHTMLLabelCo
       // There can be a label targeted at this control using the 
       // for="control_id" attribute. To save computing time, only 
       // look for those inside of a form element
       nsAutoString forId;
       if (!nsAccUtils::GetID(aForNode, forId)) {
         break;
       }
       // Actually we'll be walking down the content this time, with a depth first search
-      return nsAccUtils::FindDescendantPointingToID(&forId, walkUpContent, eAria_none,
+      return nsAccUtils::FindDescendantPointingToID(&forId, walkUpContent,
                                                     nsAccessibilityAtoms::_for);
     }
   }
 
   return nsnull;
 }
 
-nsresult nsAccessible::GetTextFromRelationID(EAriaProperty aIDProperty, nsString &aName)
+nsresult nsAccessible::GetTextFromRelationID(nsIAtom *aIDProperty, nsString &aName)
 {
   // Get DHTML name from content subtree pointed to by ID attribute
   aName.Truncate();
   nsCOMPtr<nsIContent> content = GetRoleContent(mDOMNode);
   NS_ASSERTION(content, "Called from shutdown accessible");
 
   nsAutoString ids;
-  if (!nsAccUtils::GetAriaProperty(content, mWeakShell, aIDProperty, ids)) {
+  if (!content->GetAttr(kNameSpaceID_None, aIDProperty, ids)) {
     return NS_ERROR_FAILURE;
   }
   ids.CompressWhitespace(PR_TRUE, PR_TRUE);
 
   nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(content->GetOwnerDoc());
   NS_ENSURE_TRUE(domDoc, NS_ERROR_FAILURE);
   
   nsresult rv = NS_ERROR_FAILURE;
 
-  // Support idlist as in aaa::labelledby="id1 id2 id3"
+  // Support idlist as in aria-labelledby="id1 id2 id3"
   while (!ids.IsEmpty()) {
     nsAutoString id;
     PRInt32 idLength = ids.FindChar(' ');
     NS_ASSERTION(idLength != 0, "Should not be 0 because of CompressWhitespace() call above");
     if (idLength == kNotFound) {
       id = ids;
       ids.Truncate();
     } else {
@@ -1773,17 +1758,17 @@ nsresult nsAccessible::GetHTMLName(nsASt
 {
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (!content) {
     return NS_ERROR_FAILURE;   // Node shut down
   }
 
   // Check for DHTML accessibility labelledby relationship property
   nsAutoString label;
-  nsresult rv = GetTextFromRelationID(eAria_labelledby, label);
+  nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_labelledby, label);
   if (NS_SUCCEEDED(rv)) {
     aLabel = label;
     return rv;
   }
 
   nsIContent *labelContent = GetHTMLLabelContent(content);
   if (labelContent) {
     AppendFlatStringFromSubtree(labelContent, &label);
@@ -1824,17 +1809,17 @@ nsresult nsAccessible::GetHTMLName(nsASt
   */
 nsresult nsAccessible::GetXULName(nsAString& aLabel, PRBool aCanAggregateSubtree)
 {
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   NS_ASSERTION(content, "No nsIContent for DOM node");
 
   // First check for label override via accessibility labelledby relationship
   nsAutoString label;
-  nsresult rv = GetTextFromRelationID(eAria_labelledby, label);
+  nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_labelledby, label);
   if (NS_SUCCEEDED(rv)) {
     aLabel = label;
     return rv;
   }
 
   // CASE #1 (via label attribute) -- great majority of the cases
   nsCOMPtr<nsIDOMXULLabeledControlElement> labeledEl(do_QueryInterface(mDOMNode));
   if (labeledEl) {
@@ -1857,19 +1842,18 @@ nsresult nsAccessible::GetXULName(nsAStr
       }
     }
   }
 
   // CASES #2 and #3 ------ label as a child or <label control="id" ... > </label>
   if (NS_FAILED(rv) || label.IsEmpty()) {
     label.Truncate();
     nsIContent *labelContent =
-      nsAccUtils::FindNeighbourPointingToNode(content, eAria_none,
-                                              nsAccessibilityAtoms::label,
-                                              nsAccessibilityAtoms::control);
+      nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::control,
+                                              nsAccessibilityAtoms::label);
 
     nsCOMPtr<nsIDOMXULLabelElement> xulLabel(do_QueryInterface(labelContent));
     // Check if label's value attribute is used
     if (xulLabel && NS_SUCCEEDED(xulLabel->GetValue(label)) && label.IsEmpty()) {
       // If no value attribute, a non-empty label must contain
       // children that define it's text -- possibly using HTML
       AppendFlatStringFromSubtree(labelContent, &label);
     }
@@ -1956,38 +1940,34 @@ NS_IMETHODIMP nsAccessible::GetFinalRole
 
   if (mRoleMapEntry) {
     *aRole = mRoleMapEntry->role;
 
     // These unfortunate exceptions don't fit into the ARIA table
     // This is where the nsIAccessible role depends on both the role and ARIA state
     if (*aRole == nsIAccessibleRole::ROLE_ENTRY) {
       nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
-      nsAutoString secret;
-      if (content && nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_secret, secret) &&
-          secret.EqualsLiteral("true")) {
-        // For entry field with aaa:secret="true"
+      if (content && content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::aria_secret,
+                                          nsAccessibilityAtoms::_true, eCaseMatters)) {
+        // For entry field with aria-secret="true"
         *aRole = nsIAccessibleRole::ROLE_PASSWORD_TEXT;
       }
     }
     else if (*aRole == nsIAccessibleRole::ROLE_PUSHBUTTON) {
       nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
       if (content) {
-        if (nsAccUtils::HasAriaProperty(content, mWeakShell, eAria_pressed)) {
-          // For aaa:pressed="false" or aaa:pressed="true"
+        if (content->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_pressed)) {
+          // For aria-pressed="false" or aria-pressed="true"
           // For simplicity, any pressed attribute indicates it's a toggle button
           *aRole = nsIAccessibleRole::ROLE_TOGGLE_BUTTON;
         }
-        else {
-          nsAutoString haspopup;
-          if (nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_haspopup, haspopup) &&
-              haspopup.EqualsLiteral("true")) {
-            // For button with aaa:haspopup="true"
-            *aRole = nsIAccessibleRole::ROLE_BUTTONMENU;
-          }
+        else if (content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::aria_secret,
+                                      nsAccessibilityAtoms::_true, eCaseMatters)) {
+          // For button with aria-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) {
@@ -2008,94 +1988,77 @@ NS_IMETHODIMP nsAccessible::GetFinalRole
   }
   return mDOMNode ? GetRole(aRole) : NS_ERROR_FAILURE;  // Node already shut down
 }
 
 NS_IMETHODIMP
 nsAccessible::GetAttributes(nsIPersistentProperties **aAttributes)
 {
   NS_ENSURE_ARG_POINTER(aAttributes);
-
-  if (!mDOMNode)
+  *aAttributes = nsnull;
+
+  nsCOMPtr<nsIContent> content = GetRoleContent(mDOMNode);
+  if (!content) {
     return NS_ERROR_FAILURE;
+  }
 
   nsCOMPtr<nsIPersistentProperties> attributes =
      do_CreateInstance(NS_PERSISTENTPROPERTIES_CONTRACTID);
   NS_ENSURE_TRUE(attributes, NS_ERROR_OUT_OF_MEMORY);
 
   nsAccEvent::GetLastEventAttributes(mDOMNode, attributes);
  
   nsresult rv = GetAttributesInternal(attributes);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<nsIContent> content = GetRoleContent(mDOMNode);
   nsAutoString id;
   nsAutoString oldValueUnused;
-  if (content && nsAccUtils::GetID(content, id)) {
+  if (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)) {
-    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);          
-    }
+  nsAutoString xmlRoles;
+  if (content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::role, xmlRoles)) {
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"),  xmlRoles, 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,
-                                     eAria_sort, eAria_grab, eAria_dropeffect};
+  nsIAtom *ariaPropertyEnum[] = { nsAccessibilityAtoms::aria_live, nsAccessibilityAtoms::aria_channel, nsAccessibilityAtoms::aria_atomic, nsAccessibilityAtoms::aria_relevant,
+                                     nsAccessibilityAtoms::aria_datatype, nsAccessibilityAtoms::aria_level, nsAccessibilityAtoms::aria_posinset, nsAccessibilityAtoms::aria_setsize,
+                                     nsAccessibilityAtoms::aria_sort, nsAccessibilityAtoms::aria_grab, nsAccessibilityAtoms::aria_dropeffect};
   NS_ASSERTION(NS_ARRAY_LENGTH(ariaPropertyString) == NS_ARRAY_LENGTH(ariaPropertyEnum),
                "ARIA attributes and object property name arrays out of sync");
   for (PRUint32 index = 0; index < NS_ARRAY_LENGTH(ariaPropertyString); index ++) {
     nsAutoString value;
-    if (nsAccUtils::GetAriaProperty(content, mWeakShell, ariaPropertyEnum[index], value, ariaPropTypes)) {
+    if (content->GetAttr(kNameSpaceID_None, ariaPropertyEnum[index], value)) {
       ToLowerCase(value);
       attributes->SetStringProperty(nsDependentCString(ariaPropertyString[index]), value, oldValueUnused);    
     }
   }
 
   // Get container-foo computed live region properties based on the closest container with
   // the live region attribute
   nsAutoString atomic, live, relevant, channel, busy;
   while (content) {
     if (relevant.IsEmpty() &&
-        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_relevant, relevant, ariaPropTypes))
+        content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_relevant, relevant))
       attributes->SetStringProperty(NS_LITERAL_CSTRING("container-relevant"), relevant, oldValueUnused);
     if (live.IsEmpty() &&
-        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_live, live, ariaPropTypes))
+        content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_live, live))
       attributes->SetStringProperty(NS_LITERAL_CSTRING("container-live"), live, oldValueUnused);
     if (channel.IsEmpty() &&
-        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_channel, channel, ariaPropTypes))
+        content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_channel, channel))
       attributes->SetStringProperty(NS_LITERAL_CSTRING("container-channel"), channel, oldValueUnused);
     if (atomic.IsEmpty() &&
-        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_atomic, atomic, ariaPropTypes))
+        content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_atomic, atomic))
       attributes->SetStringProperty(NS_LITERAL_CSTRING("container-atomic"), atomic, oldValueUnused);
     if (busy.IsEmpty() &&
-        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_busy, busy, ariaPropTypes))
+        content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_busy, busy))
       attributes->SetStringProperty(NS_LITERAL_CSTRING("container-busy"), busy, oldValueUnused);
     content = content->GetParent();
   }
 
   if (!nsAccUtils::HasAccGroupAttrs(attributes)) {
     // The role of an accessible can be pointed by ARIA attribute but ARIA
     // posinset, level, setsize may be skipped. Therefore we calculate here
     // these properties to map them into description.
@@ -2161,17 +2124,17 @@ nsAccessible::GetAttributes(nsIPersisten
   attributes.swap(*aAttributes);
 
   return NS_OK;
 }
 
 nsresult
 nsAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
 {
-  nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
+  nsCOMPtr<nsIDOMElement> element(do_QueryInterface(GetRoleContent(mDOMNode)));
   NS_ENSURE_TRUE(element, NS_ERROR_UNEXPECTED);
 
   nsAutoString tagName;
   element->GetTagName(tagName);
   if (!tagName.IsEmpty()) {
     nsAutoString oldValueUnused;
     aAttributes->SetStringProperty(NS_LITERAL_CSTRING("tag"), tagName,
                                    oldValueUnused);
@@ -2219,22 +2182,22 @@ nsAccessible::GroupPosition(PRInt32 *aGr
 
   return NS_OK;
 }
 
 PRBool nsAccessible::MappedAttrState(nsIContent *aContent, PRUint32 *aStateInOut,
                                      nsStateMapEntry *aStateMapEntry)
 {
   // Return true if we should continue
-  if (aStateMapEntry->attributeName == eAria_none) {
+  if (!aStateMapEntry->attributeName) {
     return PR_FALSE;  // Stop looking -- no more states
   }
 
   nsAutoString attribValue;
-  if (nsAccUtils::GetAriaProperty(aContent, mWeakShell, aStateMapEntry->attributeName, attribValue)) {
+  if (aContent->GetAttr(kNameSpaceID_None, *aStateMapEntry->attributeName, attribValue)) {
     if (aStateMapEntry->attributeValue == kBoolState) {
       // No attribute value map specified in state map entry indicates state cleared
       if (attribValue.EqualsLiteral("false")) {
         *aStateInOut &= ~aStateMapEntry->state;
       }
       else {
         *aStateInOut |= aStateMapEntry->state;
       }
@@ -2299,45 +2262,61 @@ nsAccessible::GetFinalState(PRUint32 *aS
       // in ARIA expanded combobox because of limitation of nsARIAMap
       // XXX Perhaps we will be able to make this less hacky if 
       // we support extended states in nsARIAMap, e.g. derive
       // COLLAPSED from EXPANDABLE && !EXPANDED
       *aExtraState &= ~nsIAccessibleStates::STATE_COLLAPSED;
     }
   }
 
+  if (mRoleMapEntry) {
+    // If an object has an ancestor with the activedescendant property
+    // pointing at it, we mark it as ACTIVE even if it's not currently focused.
+    // This allows screen reader virtual buffer modes to know which descendant
+    // is the current one that would get focus if the user navigates to the container widget.
+    nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
+    nsAutoString id;
+    if (content && nsAccUtils::GetID(content, id)) {
+      nsIContent *ancestorContent = content;
+      nsAutoString activeID;
+      while ((ancestorContent = ancestorContent->GetParent()) != nsnull) {
+        if (ancestorContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_activedescendant, activeID)) {
+          if (id == activeID) {
+            *aExtraState |= nsIAccessibleStates::EXT_STATE_ACTIVE;
+          }
+          break;
+        }
+      }
+    }
+  }
+
   PRUint32 role;
   rv = GetFinalRole(&role);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (role == nsIAccessibleRole::ROLE_ENTRY ||
       role == nsIAccessibleRole::ROLE_PASSWORD_TEXT ||
       role == nsIAccessibleRole::ROLE_COMBOBOX) {
 
     nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
     NS_ENSURE_STATE(content);
 
     nsAutoString autocomplete;
-    if (nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_autocomplete, autocomplete) &&
+    if (content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_autocomplete, autocomplete) &&
         (autocomplete.EqualsIgnoreCase("inline") ||
          autocomplete.EqualsIgnoreCase("list") ||
          autocomplete.EqualsIgnoreCase("both"))) {
       *aExtraState |= nsIAccessibleStates::EXT_STATE_SUPPORTS_AUTOCOMPLETION;
     }
 
     // XXX We can remove this hack once we support RDF-based role & state maps
     if (mRoleMapEntry && mRoleMapEntry->role == nsIAccessibleRole::ROLE_ENTRY) {
-      nsAutoString multiline;
-      if (nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_multiline, multiline) &&
-          multiline.EqualsLiteral("true")) {
-        *aExtraState |= nsIAccessibleStates::EXT_STATE_MULTI_LINE;
-      }
-      else {
-        *aExtraState |= nsIAccessibleStates::EXT_STATE_SINGLE_LINE;
-      }
+      PRBool isMultiLine = content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::aria_multiline,
+                                                nsAccessibilityAtoms::_true, eCaseMatters);
+      *aExtraState |= isMultiLine ? nsIAccessibleStates::EXT_STATE_MULTI_LINE : nsIAccessibleStates::EXT_STATE_SINGLE_LINE;
     }
   }
 
   // For some reasons DOM node may have not a frame. We tract such accessibles
   // as invisible.
   nsIFrame *frame = GetFrame();
   if (!frame)
     return NS_OK;
@@ -2378,84 +2357,84 @@ nsAccessible::GetARIAState()
   }
 
   if (!mRoleMapEntry)
     return ariaState;
 
   // Once DHTML role is used, we're only readonly if DHTML readonly used
   ariaState &= ~nsIAccessibleStates::STATE_READONLY;
 
-  if (ariaState & nsIAccessibleStates::STATE_UNAVAILABLE) {
-    // Disabled elements are not selectable or focusable, even if disabled
-    // via DHTML accessibility disabled property
-    ariaState &= ~(nsIAccessibleStates::STATE_SELECTABLE |
-                   nsIAccessibleStates::STATE_FOCUSABLE);
-  }
-
   ariaState |= mRoleMapEntry->state;
   if (MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap1) &&
       MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap2) &&
       MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap3) &&
       MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap4) &&
       MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap5) &&
       MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap6) &&
       MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap7)) {
     MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap8);
   }
 
+  if (ariaState & nsIAccessibleStates::STATE_UNAVAILABLE) {
+    // Disabled elements are not selectable or focusable, even if disabled
+    // via DHTML accessibility disabled property
+    ariaState &= ~(nsIAccessibleStates::STATE_SELECTABLE |
+                   nsIAccessibleStates::STATE_FOCUSABLE);
+  }
+
   return ariaState;
 }
 
 // Not implemented by this class
 
 /* DOMString getValue (); */
 NS_IMETHODIMP nsAccessible::GetValue(nsAString& aValue)
 {
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;  // Node already shut down
   }
   if (mRoleMapEntry) {
     if (mRoleMapEntry->valueRule == eNoValue) {
       return NS_OK;
     }
     nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
-    if (content && nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_valuenow, aValue)) {
+    if (content && content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_valuenow, aValue)) {
       return NS_OK;
     }
   }
   return NS_OK;
 }
 
 // nsIAccessibleValue
 NS_IMETHODIMP
 nsAccessible::GetMaximumValue(double *aMaximumValue)
 {
-  return GetAttrValue(eAria_valuemax, aMaximumValue);
+  return GetAttrValue(nsAccessibilityAtoms::aria_valuemax, aMaximumValue);
 }
 
 NS_IMETHODIMP
 nsAccessible::GetMinimumValue(double *aMinimumValue)
 {
-  return GetAttrValue(eAria_valuemin, aMinimumValue);
+  return GetAttrValue(nsAccessibilityAtoms::aria_valuemin, aMinimumValue);
 }
 
 NS_IMETHODIMP
 nsAccessible::GetMinimumIncrement(double *aMinIncrement)
 {
   NS_ENSURE_ARG_POINTER(aMinIncrement);
   *aMinIncrement = 0;
 
   // No mimimum increment in dynamic content spec right now
   return NS_OK_NO_ARIA_VALUE;
 }
 
 NS_IMETHODIMP
 nsAccessible::GetCurrentValue(double *aValue)
 {
-  return GetAttrValue(eAria_valuenow, aValue);
+  return GetAttrValue(nsAccessibilityAtoms::aria_valuenow, aValue);
 }
 
 NS_IMETHODIMP
 nsAccessible::SetCurrentValue(double aValue)
 {
   if (!mDOMNode)
     return NS_ERROR_FAILURE;  // Node already shut down
 
@@ -2476,24 +2455,18 @@ nsAccessible::SetCurrentValue(double aVa
   if (NS_SUCCEEDED(GetMaximumValue(&maxValue)) && aValue > maxValue)
     return NS_ERROR_INVALID_ARG;
 
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   NS_ENSURE_STATE(content);
 
   nsAutoString newValue;
   newValue.AppendFloat(aValue);
-  if (0 == (nsAccUtils::GetAriaPropTypes(content, mWeakShell) &
-            nsIAccessibleDocument::eCheckNamespaced)) {
-    // No WAI namespaced properties used in this doc
-    return content->SetAttr(kNameSpaceID_None,
-                            nsAccessibilityAtoms::aria_valuenow, newValue, PR_TRUE);
-  }
-  return content->SetAttr(kNameSpaceID_WAIProperties,
-                          nsAccessibilityAtoms::valuenow, newValue, PR_TRUE);
+  return content->SetAttr(kNameSpaceID_None,
+                          nsAccessibilityAtoms::aria_valuenow, newValue, PR_TRUE);
 }
 
 /* void setName (in DOMString name); */
 NS_IMETHODIMP nsAccessible::SetName(const nsAString& name)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
@@ -2593,21 +2566,17 @@ NS_IMETHODIMP nsAccessible::GetAccessibl
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 nsIDOMNode* nsAccessible::GetAtomicRegion()
 {
   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)) {
+  while (loopContent && !loopContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_atomic, atomic)) {
     loopContent = loopContent->GetParent();
   }
 
   nsCOMPtr<nsIDOMNode> atomicRegion;
   if (atomic.EqualsLiteral("true")) {
     atomicRegion = do_QueryInterface(loopContent);
   }
   return atomicRegion;
@@ -2637,79 +2606,76 @@ NS_IMETHODIMP nsAccessible::GetAccessibl
     {
       if (content->Tag() == nsAccessibilityAtoms::label) {
         nsIAtom *relatedIDAttr = content->IsNodeOfType(nsINode::eHTML) ?
           nsAccessibilityAtoms::_for : nsAccessibilityAtoms::control;
         content->GetAttr(kNameSpaceID_None, relatedIDAttr, relatedID);
       }
       if (relatedID.IsEmpty()) {
         relatedNode =
-          do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, eAria_labelledby));
+          do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::aria_labelledby));
       }
       break;
     }
   case nsIAccessibleRelation::RELATION_LABELLED_BY:
     {
-      if (!nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_labelledby, relatedID)) {
+      if (!content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_labelledby, relatedID)) {
         relatedNode = do_QueryInterface(GetLabelContent(content));
       }
       break;
     }
   case nsIAccessibleRelation::RELATION_DESCRIBED_BY:
     {
-      if (!nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_describedby, relatedID)) {
+      if (!content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_describedby, relatedID)) {
         relatedNode = do_QueryInterface(
-          nsAccUtils::FindNeighbourPointingToNode(content, eAria_none,
-                                                  nsAccessibilityAtoms::description,
-                                                  nsAccessibilityAtoms::control));
-
+          nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::control, nsAccessibilityAtoms::description));
       }
       break;
     }
   case nsIAccessibleRelation::RELATION_DESCRIPTION_FOR:
     {
       relatedNode =
-        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, eAria_describedby));
+        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::aria_describedby));
 
       if (!relatedNode && content->Tag() == nsAccessibilityAtoms::description &&
           content->IsNodeOfType(nsINode::eXUL)) {
         // This affectively adds an optional control attribute to xul:description,
         // which only affects accessibility, by allowing the description to be
         // tied to a control.
         content->GetAttr(kNameSpaceID_None,
                          nsAccessibilityAtoms::control, relatedID);
       }
       break;
     }
   case nsIAccessibleRelation::RELATION_NODE_CHILD_OF:
     {
       relatedNode =
-        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, eAria_owns));
+        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::aria_owns));
       break;
     }
   case nsIAccessibleRelation::RELATION_CONTROLLED_BY:
     {
       relatedNode =
-        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, eAria_controls));
+        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::aria_controls));
       break;
     }
   case nsIAccessibleRelation::RELATION_CONTROLLER_FOR:
     {
-      nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_controls, relatedID);
+      content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_controls, relatedID);
       break;
     }
   case nsIAccessibleRelation::RELATION_FLOWS_TO:
     {
-      nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_flowto, relatedID);
+      content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_flowto, relatedID);
       break;
     }
   case nsIAccessibleRelation::RELATION_FLOWS_FROM:
     {
       relatedNode =
-        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, eAria_flowto));
+        do_QueryInterface(nsAccUtils::FindNeighbourPointingToNode(content, nsAccessibilityAtoms::aria_flowto));
       break;
     }
   case nsIAccessibleRelation::RELATION_DEFAULT_BUTTON:
     {
       if (content->IsNodeOfType(nsINode::eHTML)) {
         // HTML form controls implements nsIFormControl interface.
         nsCOMPtr<nsIFormControl> control(do_QueryInterface(content));
         if (control) {
@@ -3137,17 +3103,17 @@ NS_IMETHODIMP nsAccessible::GetObject(PR
 
 // nsIAccessibleHyperLink::IsValid()
 NS_IMETHODIMP nsAccessible::IsValid(PRBool *aIsValid)
 {
   PRUint32 state = State(this);
   *aIsValid = (0 == (state & nsIAccessibleStates::STATE_INVALID));
   // XXX In order to implement this we would need to follow every link
   // Perhaps we can get information about invalid links from the cache
-  // In the mean time authors can use role="wairole:link" aaa:invalid="true"
+  // In the mean time authors can use role="link" aria_invalid="true"
   // to force it for links they internally know to be invalid
   return NS_OK;
 }
 
 NS_IMETHODIMP nsAccessible::IsSelected(PRBool *aIsSelected)
 {
   *aIsSelected = (gLastFocusedNode == mDOMNode);
   return NS_OK;
@@ -3290,33 +3256,33 @@ PRBool nsAccessible::CheckVisibilityInPa
 
     document = parentDoc;
   }
 
   return PR_TRUE;
 }
 
 nsresult
-nsAccessible::GetAttrValue(EAriaProperty aProperty, double *aValue)
+nsAccessible::GetAttrValue(nsIAtom *aProperty, double *aValue)
 {
   NS_ENSURE_ARG_POINTER(aValue);
   *aValue = 0;
 
   if (!mDOMNode)
     return NS_ERROR_FAILURE;  // Node already shut down
 
  if (!mRoleMapEntry || mRoleMapEntry->valueRule == eNoValue)
     return NS_OK_NO_ARIA_VALUE;
 
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   NS_ENSURE_STATE(content);
 
   PRInt32 result = NS_OK;
   nsAutoString value;
-  if (nsAccUtils::GetAriaProperty(content, mWeakShell, aProperty, value))
+  if (content->GetAttr(kNameSpaceID_None, aProperty, value))
     *aValue = value.ToFloat(&result);
 
   return result;
 }
 
 PRBool nsAccessible::MustPrune(nsIAccessible *aAccessible)
 { 
   PRUint32 role = Role(aAccessible);
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -180,17 +180,17 @@ protected:
   /**
    * For a given ARIA relation, such as labelledby or describedby, get the collated text
    * for the subtree that's pointed to.
    *
    * @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);
+  nsresult GetTextFromRelationID(nsIAtom *aIDProperty, nsString &aName);
 
   static nsIContent *GetHTMLLabelContent(nsIContent *aForNode);
   static nsIContent *GetLabelContent(nsIContent *aForNode);
 
   // 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 
@@ -233,30 +233,30 @@ protected:
   // For accessibles that have actions
   static void DoCommandCallback(nsITimer *aTimer, void *aClosure);
   nsresult DoCommand(nsIContent *aContent = nsnull);
 
   // Check the visibility across both parent content and chrome
   PRBool CheckVisibilityInParentChain(nsIDocument* aDocument, nsIView* aView);
 
   /**
-   *  Get the container node for an atomic region, defined by aria:atomic="true"
+   *  Get the container node for an atomic region, defined by aria-atomic="true"
    *  @return the container node
    */
   nsIDOMNode* GetAtomicRegion();
 
   /**
    * Get numeric value of the given ARIA attribute.
    *
    * @param aAriaProperty - the ARIA property we're using
    * @param aValue - value of the attribute
    *
    * @return - NS_OK_NO_ARIA_VALUE if there is no setted ARIA attribute
    */
-  nsresult GetAttrValue(EAriaProperty aAriaProperty, double *aValue);
+  nsresult GetAttrValue(nsIAtom *aAriaProperty, double *aValue);
 
   // Data Members
   nsCOMPtr<nsIAccessible> mParent;
   nsIAccessible *mFirstChild, *mNextSibling;
   nsRoleMapEntry *mRoleMapEntry; // Non-null indicates author-supplied role; possibly state & value as well
   PRInt32 mAccChildCount;
 };
 
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -37,16 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsBaseWidgetAccessible.h"
 #include "nsAccessibilityAtoms.h"
 #include "nsIAccessibilityService.h"
 #include "nsIAccessibleDocument.h"
 #include "nsAccessibleWrap.h"
 #include "nsAccessibilityUtils.h"
+#include "nsIDOMNSHTMLElement.h"
 #include "nsGUIEvent.h"
 #include "nsHyperTextAccessibleWrap.h"
 #include "nsILink.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIServiceManager.h"
@@ -104,17 +105,23 @@ nsLinkableAccessible::nsLinkableAccessib
 {
 }
 
 NS_IMPL_ISUPPORTS_INHERITED0(nsLinkableAccessible, nsHyperTextAccessibleWrap)
 
 NS_IMETHODIMP nsLinkableAccessible::TakeFocus()
 { 
   if (mActionContent && mActionContent->IsFocusable()) {
-    mActionContent->SetFocus(nsCOMPtr<nsPresContext>(GetPresContext()));
+    nsCOMPtr<nsIDOMNSHTMLElement> htmlElement(do_QueryInterface(mActionContent));
+    if (htmlElement) {
+      // HTML Elements also set the caret position
+      // in order to affect tabbing order
+      return htmlElement->Focus();
+    }
+    NS_WARNING("Has action content that is not an HTML element");
   }
   
   return NS_OK;
 }
 
 /* long GetState (); */
 NS_IMETHODIMP
 nsLinkableAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -79,47 +79,32 @@
 
 PRUint32 nsDocAccessible::gLastFocusedAccessiblesState = 0;
 
 //-----------------------------------------------------
 // construction
 //-----------------------------------------------------
 nsDocAccessible::nsDocAccessible(nsIDOMNode *aDOMNode, nsIWeakReference* aShell):
   nsHyperTextAccessibleWrap(aDOMNode, aShell), mWnd(nsnull),
-  mScrollPositionChangedTicks(0), mIsContentLoaded(PR_FALSE),
-  mAriaPropTypes(eCheckNamespaced)
+  mScrollPositionChangedTicks(0), mIsContentLoaded(PR_FALSE)
 {
   // For GTK+ native window, we do nothing here.
   if (!mDOMNode)
     return;
 
   // Because of the way document loading happens, the new nsIWidget is created before
   // the old one is removed. Since it creates the nsDocAccessible, for a brief moment
   // there can be 2 nsDocAccessible's for the content area, although for 2 different
   // pres shells.
 
   nsCOMPtr<nsIPresShell> shell(do_QueryReferent(mWeakShell));
   if (shell) {
     // Find mDocument
     mDocument = shell->GetDocument();
-    // Find mAriaPropTypes: the initial type of ARIA properties that should be checked for
-    if (!mDocument) {
-      NS_WARNING("No document!");
-      return;
-    }
     
-    nsCOMPtr<nsIDOMNSHTMLDocument> htmlDoc(do_QueryInterface(mDocument));
-    if (htmlDoc) {
-      nsAutoString mimeType;
-      GetMimeType(mimeType);
-      mAriaPropTypes = eCheckHyphenated;
-      if (! mimeType.EqualsLiteral("text/html")) {
-        mAriaPropTypes |= eCheckNamespaced;
-      }
-    }
     // Find mWnd
     nsIViewManager* vm = shell->GetViewManager();
     if (vm) {
       nsCOMPtr<nsIWidget> widget;
       vm->GetWidget(getter_AddRefs(widget));
       if (widget) {
         mWnd = widget->GetNativeData(NS_NATIVE_WINDOW);
       }
@@ -220,17 +205,17 @@ NS_IMETHODIMP nsDocAccessible::GetValue(
 {
   return GetURL(aValue);
 }
 
 NS_IMETHODIMP 
 nsDocAccessible::GetDescription(nsAString& aDescription)
 {
   nsAutoString description;
-  GetTextFromRelationID(eAria_describedby, description);
+  GetTextFromRelationID(nsAccessibilityAtoms::aria_describedby, description);
   aDescription = description;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // nsAccessible::GetState() always fail for document accessible.
@@ -505,25 +490,16 @@ NS_IMETHODIMP nsDocAccessible::GetParent
         // It should be changed to use GetAccessibleInWeakShell()
         accService->GetAccessibleFor(ownerNode, getter_AddRefs(mParent));
       }
     }
   }
   return mParent ? nsAccessible::GetParent(aParent) : NS_ERROR_FAILURE;
 }
 
-NS_IMETHODIMP
-nsDocAccessible::GetAttributes(nsIPersistentProperties **aAttributes)
-{
-  NS_ENSURE_ARG_POINTER(aAttributes);
-  *aAttributes = nsnull;
-
-  return mDOMNode ? NS_OK : NS_ERROR_FAILURE;
-}
-
 NS_IMETHODIMP nsDocAccessible::Init()
 {
   PutCacheEntry(gGlobalDocAccessibleCache, mDocument, this);
 
   AddEventListeners();
 
   nsresult rv = nsHyperTextAccessibleWrap::Init();
 
@@ -913,23 +889,16 @@ NS_IMETHODIMP nsDocAccessible::Observe(n
       new nsAccStateChangeEvent(this, nsIAccessibleStates::EXT_STATE_EDITABLE,
                                 PR_TRUE, PR_TRUE);
     FireAccessibleEvent(event);
   }
 
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsDocAccessible::GetAriaPropTypes(PRUint32 *aAriaPropTypes) 
-{
-  *aAriaPropTypes = mAriaPropTypes;
-  return NS_OK;
-}
-
   ///////////////////////////////////////////////////////////////////////
 // nsIDocumentObserver
 
 NS_IMPL_NSIDOCUMENTOBSERVER_CORE_STUB(nsDocAccessible)
 NS_IMPL_NSIDOCUMENTOBSERVER_LOAD_STUB(nsDocAccessible)
 NS_IMPL_NSIDOCUMENTOBSERVER_STYLE_STUB(nsDocAccessible)
 
 void
@@ -964,23 +933,16 @@ nsDocAccessible::AttributeChangedImpl(ns
   // Otherwise it may just be a state change, for example an object changing
   // its visibility
 
   nsCOMPtr<nsISupports> container = mDocument->GetContainer();
   nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(container);
   if (!docShell) {
     return;
   }
-  if (aNameSpaceID == kNameSpaceID_WAIProperties) {
-    // Using setAttributeNS() in HTML to set namespaced ARIA properties.
-    // From this point forward, check namespaced properties, which
-    // take precedence over hyphenated properties, since in text/html
-    // that can only be set dynamically.
-    mAriaPropTypes |= eCheckNamespaced;
-  }
 
   PRUint32 busyFlags;
   docShell->GetBusyFlags(&busyFlags);
   if (busyFlags) {
     return; // Still loading, ignore setting of initial attributes
   }
 
   nsCOMPtr<nsIPresShell> shell = GetPresShell();
@@ -996,68 +958,60 @@ nsDocAccessible::AttributeChangedImpl(ns
 
   // Since we're in synchronous code, we can store whether the current attribute
   // change is from user input or not. If the attribute change causes an asynchronous
   // layout change, that event can use the last known user input state
   nsAccEvent::PrepareForEvent(targetNode);
 
   // Universal boolean properties that don't require a role.
   if (aAttribute == nsAccessibilityAtoms::disabled ||
-      (aAttribute == nsAccessibilityAtoms::aria_disabled && (mAriaPropTypes & eCheckHyphenated))) {
+      aAttribute == nsAccessibilityAtoms::aria_disabled) {
     // Fire the state change whether disabled attribute is
     // set for XUL, HTML or ARIA namespace.
     // Checking the namespace would not seem to gain us anything, because
     // disabled really is going to mean the same thing in any namespace.
     // We use the attribute instead of the disabled state bit because
-    // ARIA's aaa:disabled does not affect the disabled state bit
+    // ARIA's aria-disabled does not affect the disabled state bit
     nsCOMPtr<nsIAccessibleStateChangeEvent> enabledChangeEvent =
       new nsAccStateChangeEvent(targetNode,
                                 nsIAccessibleStates::EXT_STATE_ENABLED,
                                 PR_TRUE);
     FireDelayedAccessibleEvent(enabledChangeEvent);
     nsCOMPtr<nsIAccessibleStateChangeEvent> sensitiveChangeEvent =
       new nsAccStateChangeEvent(targetNode,
                                 nsIAccessibleStates::EXT_STATE_SENSITIVE,
                                 PR_TRUE);
     FireDelayedAccessibleEvent(sensitiveChangeEvent);
     return;
   }
 
   // Check for namespaced ARIA attribute
-  nsCOMPtr<nsIAtom> ariaAttribute;
-  if (aNameSpaceID == kNameSpaceID_WAIProperties) {
-    ariaAttribute = aAttribute;
-  }
-  else if (mAriaPropTypes & eCheckHyphenated && aNameSpaceID == kNameSpaceID_None) {
+  if (aNameSpaceID == kNameSpaceID_None) {
     // Check for hyphenated aria-foo property?
     const char* attributeName;
     aAttribute->GetUTF8String(&attributeName);
     if (!PL_strncmp("aria-", attributeName, 5)) {
-      // Convert to WAI property atom attribute
-      ariaAttribute = do_GetAtom(attributeName + 5);
+      ARIAAttributeChanged(aContent, aAttribute);
     }
   }
-  if (ariaAttribute) {  // We have an ARIA attribute
-    ARIAAttributeChanged(aContent, ariaAttribute);
-    return;
-  }
 
   if (aAttribute == nsAccessibilityAtoms::role ||
       aAttribute == nsAccessibilityAtoms::href ||
       aAttribute == nsAccessibilityAtoms::onclick ||
-      aAttribute == nsAccessibilityAtoms::droppable) {
+      aAttribute == nsAccessibilityAtoms::aria_droppable) {
     // Not worth the expense to ensure which namespace these are in
     // It doesn't kill use to recreate the accessible even if the attribute was used
     // in the wrong namespace or an element that doesn't support it
     InvalidateCacheSubtree(aContent, nsIAccessibleEvent::EVENT_DOM_SIGNIFICANT_CHANGE);
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::selected) {
-    // DHTML or XUL selection
+  if (aAttribute == nsAccessibilityAtoms::selected ||
+      aAttribute == nsAccessibilityAtoms::aria_selected) {
+    // ARIA or XUL selection
     nsCOMPtr<nsIAccessible> multiSelect = GetMultiSelectFor(targetNode);
     // Multi selects use selection_add and selection_remove
     // Single select widgets just mirror event_selection for
     // whatever gets event_focus, which is done in
     // nsRootAccessible::FireAccessibleFocusEvent()
     // So right here we make sure only to deal with multi selects
     if (multiSelect) {
       // Need to find the right event to use here, SELECTION_WITHIN would
@@ -1067,21 +1021,18 @@ nsDocAccessible::AttributeChangedImpl(ns
       nsCOMPtr<nsIDOMNode> multiSelectDOMNode;
       multiSelectAccessNode->GetDOMNode(getter_AddRefs(multiSelectDOMNode));
       NS_ASSERTION(multiSelectDOMNode, "A new accessible without a DOM node!");
       FireDelayedToolkitEvent(nsIAccessibleEvent::EVENT_SELECTION_WITHIN,
                               multiSelectDOMNode, nsnull, eAllowDupes);
 
       static nsIContent::AttrValuesArray strings[] =
         {&nsAccessibilityAtoms::_empty, &nsAccessibilityAtoms::_false, nsnull};
-      if (aContent->FindAttrValueIn(kNameSpaceID_None,
-                                    nsAccessibilityAtoms::selected,
-                                    strings, eCaseMatters) !=
-          nsIContent::ATTR_VALUE_NO_MATCH) {
-
+      if (aContent->FindAttrValueIn(kNameSpaceID_None, aAttribute,
+                                    strings, eCaseMatters) >= 0) {
         FireDelayedToolkitEvent(nsIAccessibleEvent::EVENT_SELECTION_REMOVE,
                                 targetNode, nsnull);
         return;
       }
 
       FireDelayedToolkitEvent(nsIAccessibleEvent::EVENT_SELECTION_ADD,
                                                   targetNode, nsnull);
     }
@@ -1099,66 +1050,67 @@ nsDocAccessible::AttributeChangedImpl(ns
 
 void
 nsDocAccessible::ARIAAttributeChanged(nsIContent* aContent, nsIAtom* aAttribute)
 {
   nsCOMPtr<nsIDOMNode> targetNode(do_QueryInterface(aContent));
   if (!targetNode)
     return;
 
-  if (aAttribute == nsAccessibilityAtoms::required) {
+  if (aAttribute == nsAccessibilityAtoms::aria_required) {
     nsCOMPtr<nsIAccessibleStateChangeEvent> event =
       new nsAccStateChangeEvent(targetNode,
                                 nsIAccessibleStates::STATE_REQUIRED,
                                 PR_FALSE);
     FireDelayedAccessibleEvent(event);
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::invalid) {
+  if (aAttribute == nsAccessibilityAtoms::aria_invalid) {
     nsCOMPtr<nsIAccessibleStateChangeEvent> event =
       new nsAccStateChangeEvent(targetNode,
                                 nsIAccessibleStates::STATE_INVALID,
                                 PR_FALSE);
     FireDelayedAccessibleEvent(event);
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::activedescendant) {
+  if (aAttribute == nsAccessibilityAtoms::aria_activedescendant) {
     // The activedescendant universal property redirects accessible focus events
     // to the element with the id that activedescendant points to
     nsCOMPtr<nsIDOMNode> currentFocus = GetCurrentFocus();
     if (currentFocus == targetNode) {
       nsRefPtr<nsRootAccessible> rootAcc = GetRootAccessible();
       if (rootAcc)
         rootAcc->FireAccessibleFocusEvent(nsnull, currentFocus, nsnull, PR_TRUE);
     }
     return;
   }
 
-  if (!HasRoleAttribute(aContent)) {
+  if (!aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::role)) {
     // We don't care about these other ARIA attribute changes unless there is
     // an ARIA role set for the element
     // XXX: we should check the role map to see if the changed property is
     // relevant for that particular role.
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::checked ||
-      aAttribute == nsAccessibilityAtoms::pressed) {
-    const PRUint32 kState = (aAttribute == nsAccessibilityAtoms::checked) ?
+  // The following ARIA attributes only take affect when dynamic content role is present
+  if (aAttribute == nsAccessibilityAtoms::aria_checked ||
+      aAttribute == nsAccessibilityAtoms::aria_pressed) {
+    const PRUint32 kState = (aAttribute == nsAccessibilityAtoms::aria_checked) ?
                             nsIAccessibleStates::STATE_CHECKED : 
                             nsIAccessibleStates::STATE_PRESSED;
     nsCOMPtr<nsIAccessibleStateChangeEvent> event =
       new nsAccStateChangeEvent(targetNode, kState, PR_FALSE);
     FireDelayedAccessibleEvent(event);
     if (targetNode == gLastFocusedNode) {
       // State changes for MIXED state currently only supported for focused item, because
       // otherwise we would need access to the old attribute value in this listener.
-      // This is because we don't know if the previous value of aaa:checked or aaa:pressed was "mixed"
+      // This is because we don't know if the previous value of aria-checked or aria-pressed was "mixed"
       // without caching that info.
       nsCOMPtr<nsIAccessible> accessible;
       event->GetAccessible(getter_AddRefs(accessible));
       if (accessible) {
         PRBool wasMixed = (gLastFocusedAccessiblesState & nsIAccessibleStates::STATE_MIXED) != 0;
         PRBool isMixed  = (State(accessible) & nsIAccessibleStates::STATE_MIXED) != 0;
         if (wasMixed != isMixed) {
           nsCOMPtr<nsIAccessibleStateChangeEvent> event =
@@ -1167,49 +1119,46 @@ nsDocAccessible::ARIAAttributeChanged(ns
                                       PR_FALSE, isMixed);
           FireDelayedAccessibleEvent(event);
         }
       }
     }
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::expanded) {
+  if (aAttribute == nsAccessibilityAtoms::aria_expanded) {
     nsCOMPtr<nsIAccessibleStateChangeEvent> event =
       new nsAccStateChangeEvent(targetNode,
                                 nsIAccessibleStates::STATE_EXPANDED,
                                 PR_FALSE);
     FireDelayedAccessibleEvent(event);
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::readonly) {
+  if (aAttribute == nsAccessibilityAtoms::aria_readonly) {
     nsCOMPtr<nsIAccessibleStateChangeEvent> event =
       new nsAccStateChangeEvent(targetNode,
                                 nsIAccessibleStates::STATE_READONLY,
                                 PR_FALSE);
     FireDelayedAccessibleEvent(event);
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::valuenow) {
+  if (aAttribute == nsAccessibilityAtoms::aria_valuenow) {
     FireDelayedToolkitEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE,
                             targetNode, nsnull);
     return;
   }
 
-  if (aAttribute == nsAccessibilityAtoms::multiselectable) {
+  if (aAttribute == nsAccessibilityAtoms::aria_multiselectable &&
+      aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::role)) {
     // This affects whether the accessible supports nsIAccessibleSelectable.
     // COM says we cannot change what interfaces are supported on-the-fly,
     // so invalidate this object. A new one will be created on demand.
-    if (HasRoleAttribute(aContent)) {
-      // The multiselectable and other waistate attributes only take affect
-      // when dynamic content role is present
-      InvalidateCacheSubtree(aContent, nsIAccessibleEvent::EVENT_DOM_SIGNIFICANT_CHANGE);
-    }
+    InvalidateCacheSubtree(aContent, nsIAccessibleEvent::EVENT_DOM_SIGNIFICANT_CHANGE);
   }
 }
 
 void nsDocAccessible::ContentAppended(nsIDocument *aDocument,
                                       nsIContent* aContainer,
                                       PRInt32 aNewIndexInContainer)
 {
   if ((!mIsContentLoaded || !mDocument) && mAccessNodeCache.Count() <= 1) {
@@ -1601,16 +1550,23 @@ NS_IMETHODIMP nsDocAccessible::FlushPend
         nsCOMPtr<nsIAccessibleText> accessibleText = do_QueryInterface(accessible);
         PRInt32 caretOffset;
         if (accessibleText && NS_SUCCEEDED(accessibleText->GetCaretOffset(&caretOffset))) {
 #ifdef DEBUG_A11Y
           PRUnichar chAtOffset;
           accessibleText->GetCharacterAtOffset(caretOffset, &chAtOffset);
           printf("\nCaret moved to %d with char %c", caretOffset, chAtOffset);
 #endif
+#ifdef DEBUG_CARET
+          // Test caret line # -- fire an EVENT_ALERT on the focused node so we can watch the
+          // line-number object attribute on it
+          nsCOMPtr<nsIAccessible> accForFocus;
+          GetAccService()->GetAccessibleFor(gLastFocusedNode, getter_AddRefs(accForFocus));
+          nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_ALERT, accForFocus);
+#endif
           nsCOMPtr<nsIAccessibleCaretMoveEvent> caretMoveEvent =
             new nsAccCaretMoveEvent(accessible, caretOffset);
           NS_ENSURE_TRUE(caretMoveEvent, NS_ERROR_OUT_OF_MEMORY);
 
           FireAccessibleEvent(caretMoveEvent);
 
           PRInt32 selectionCount;
           accessibleText->GetSelectionCount(&selectionCount);
@@ -1751,31 +1707,32 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
   // Invalidate cache subtree
   // We have to check for accessibles for each dom node by traversing DOM tree
   // instead of just the accessible tree, although that would be faster
   // Otherwise we might miss the nsAccessNode's that are not nsAccessible's.
 
   NS_ENSURE_TRUE(mDOMNode, NS_ERROR_FAILURE);
   nsCOMPtr<nsIDOMNode> childNode = aChild ? do_QueryInterface(aChild) : mDOMNode;
 
+  nsCOMPtr<nsIPresShell> presShell = GetPresShell();
+  NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
+  
   if (!mIsContentLoaded) {
     // Still loading document
     if (mAccessNodeCache.Count() <= 1) {
       // Still loading and no accessibles has yet been created other than this
       // doc accessible. In this case we optimize
       // by not firing SHOW/HIDE/REORDER events for every document mutation
       // caused by page load, since AT is not going to want to grab the
       // document and listen to these changes until after the page is first loaded
       // Leave early, and ensure mAccChildCount stays uninitialized instead of 0,
       // which it is if anyone asks for its children right now.
       return InvalidateChildren();
     }
     if (aChangeEventType == nsIAccessibleEvent::EVENT_DOM_CREATE) {
-      nsCOMPtr<nsIPresShell> presShell = GetPresShell();
-      NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
       nsIEventStateManager *esm = presShell->GetPresContext()->EventStateManager();
       NS_ENSURE_TRUE(esm, NS_ERROR_FAILURE);
       if (!esm->IsHandlingUserInputExternal()) {
         // Adding content during page load, but not caused by user input
         // Just invalidate accessible hierarchy and return,
         // otherwise the page load time slows down way too much
         nsCOMPtr<nsIAccessible> containerAccessible;
         GetAccessibleInParentChain(childNode, PR_FALSE, getter_AddRefs(containerAccessible));
@@ -1829,19 +1786,18 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
   nsCOMPtr<nsIAccessible> containerAccessible;
   GetAccessibleInParentChain(childNode, PR_TRUE, getter_AddRefs(containerAccessible));
   if (!containerAccessible) {
     containerAccessible = this;
   }
 
   if (!isShowing) {
     // Fire EVENT_ASYNCH_HIDE or EVENT_DOM_DESTROY
-    nsCOMPtr<nsIContent> content(do_QueryInterface(childNode));
     if (isHiding) {
-      nsCOMPtr<nsIPresShell> presShell = GetPresShell();
+      nsCOMPtr<nsIContent> content(do_QueryInterface(childNode));
       if (content) {
         nsIFrame *frame = presShell->GetPrimaryFrameFor(content);
         if (frame) {
           nsIFrame *frameParent = frame->GetParent();
           if (!frameParent || !frameParent->GetStyleVisibility()->IsVisible()) {
             // Ancestor already hidden or being hidden at the same time:
             // don't process redundant hide event
             // This often happens when visibility is cleared for node,
@@ -1889,31 +1845,37 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
     // the assistive technology may receive the event and then retrieve
     // nsIAccessibleStates::STATE_INVISIBLE for the event's accessible object.
     PRUint32 additionEvent = isAsynch ? nsIAccessibleEvent::EVENT_ASYNCH_SHOW :
                                         nsIAccessibleEvent::EVENT_DOM_CREATE;
     FireDelayedToolkitEvent(additionEvent, childNode, nsnull,
                             eCoalesceFromSameSubtree, isAsynch);
 
     // Check to see change occured in an ARIA menu, and fire an EVENT_MENUPOPUP_START if it did
-    if (ARIARoleEquals(aChild, "menu")) {
+    nsRoleMapEntry *roleMapEntry = nsAccUtils::GetRoleMapEntry(childNode);
+    if (roleMapEntry && roleMapEntry->role == nsIAccessibleRole::ROLE_MENUPOPUP) {
       FireDelayedToolkitEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_START,
                               childNode, nsnull, eAllowDupes, isAsynch);
     }
 
     // Check to see if change occured inside an alert, and fire an EVENT_ALERT if it did
     nsIContent *ancestor = aChild;
-    while (ancestor) {
-      if (ARIARoleEquals(ancestor, "alert")) {
+    while (PR_TRUE) {
+      if (roleMapEntry && roleMapEntry->role == nsIAccessibleRole::ROLE_ALERT) {
         nsCOMPtr<nsIDOMNode> alertNode(do_QueryInterface(ancestor));
         FireDelayedToolkitEvent(nsIAccessibleEvent::EVENT_ALERT, alertNode, nsnull,
                                 eRemoveDupes, isAsynch);
         break;
       }
       ancestor = ancestor->GetParent();
+      nsCOMPtr<nsIDOMNode> ancestorNode = do_QueryInterface(ancestor);
+      if (!ancestorNode) {
+        break;
+      }
+      roleMapEntry = nsAccUtils::GetRoleMapEntry(ancestorNode);
     }
   }
 
   if (!isShowing) {
     // Fire an event so the assistive technology knows the children have changed
     // This is only used by older MSAA clients. Newer ones should derive this
     // from SHOW and HIDE so that they don't fetch extra objects
     if (childAccessible) {
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -75,17 +75,16 @@ class nsDocAccessible : public nsHyperTe
 
     NS_IMETHOD GetRole(PRUint32 *aRole);
     NS_IMETHOD GetName(nsAString& aName);
     NS_IMETHOD GetValue(nsAString& aValue);
     NS_IMETHOD GetDescription(nsAString& aDescription);
     NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
     NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
     NS_IMETHOD GetParent(nsIAccessible **aParent);
-    NS_IMETHOD GetAttributes(nsIPersistentProperties **aAttributes);
     NS_IMETHOD TakeFocus(void);
 
     // ----- nsIScrollPositionListener ---------------------------
     NS_IMETHOD ScrollPositionWillChange(nsIScrollableView *aView, nscoord aX, nscoord aY);
     NS_IMETHOD ScrollPositionDidChange(nsIScrollableView *aView, nscoord aX, nscoord aY);
 
     // nsIDocumentObserver
     NS_DECL_NSIDOCUMENTOBSERVER
@@ -211,17 +210,16 @@ class nsDocAccessible : public nsHyperTe
     nsCOMPtr<nsITimer> mFireEventTimer;
     PRUint16 mScrollPositionChangedTicks; // Used for tracking scroll events
     PRPackedBool mIsContentLoaded;
     nsCOMArray<nsIAccessibleEvent> mEventsToFire;
 
 protected:
     PRBool mIsAnchor;
     PRBool mIsAnchorJumped;
-    PRUint32 mAriaPropTypes;
     static PRUint32 gLastFocusedAccessiblesState;
 
 private:
     static void DocLoadCallback(nsITimer *aTimer, void *aClosure);
     nsCOMPtr<nsITimer> mDocLoadTimer;
 };
 
 #endif  
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -48,16 +48,17 @@
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMEventListener.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMHTMLAnchorElement.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLSelectElement.h"
+#include "nsIDOMDataContainerEvent.h"
 #include "nsIDOMNSEvent.h"
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULPopupElement.h"
 #include "nsIDocument.h"
 #include "nsIEventListenerManager.h"
 #include "nsIFocusController.h"
@@ -265,28 +266,34 @@ nsRootAccessible::GetChromeEventHandler(
 
   nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(chromeEventHandler));
 
   *aChromeTarget = target;
   NS_IF_ADDREF(*aChromeTarget);
 }
 
 const char* const docEvents[] = {
+#ifdef DEBUG
+  // Capture mouse over events and fire fake DRAGDROPSTART event to simplify
+  // debugging a11y objects with event viewers
+  "mouseover",
+#endif
   // capture DOM focus events 
   "focus",
   // capture Form change events 
   "select",
   // capture NameChange events (fired whenever name changes, immediately after, whether focus moves or not)
   "NameChange",
   // capture ValueChange events (fired whenever value changes, immediately after, whether focus moves or not)
   "ValueChange",
   // capture AlertActive events (fired whenever alert pops up)
   "AlertActive",
   // add ourself as a TreeViewChanged listener (custom event fired in nsTreeBodyFrame.cpp)
   "TreeViewChanged",
+  "TreeRowCountChanged",
   // add ourself as a OpenStateChange listener (custom event fired in tree.xml)
   "OpenStateChange",
   // add ourself as a CheckboxStateChange listener (custom event fired in nsHTMLInputElement.cpp)
   "CheckboxStateChange",
   // add ourself as a RadioStateChange Listener ( custom event fired in in nsHTMLInputElement.cpp  & radio.xml)
   "RadioStateChange",
   "popupshown",
   "popuphiding",
@@ -453,23 +460,23 @@ PRBool nsRootAccessible::FireAccessibleF
         realFocusedNode = aNode;
       }
       if (realFocusedNode) {
         mCaretAccessible->SetControlSelectionListener(realFocusedNode);
       }
     }
   }
 
-  // Check for aaa:activedescendant, which changes which element has focus
+  // Check for aria-activedescendant, which changes which element has focus
   nsCOMPtr<nsIDOMNode> finalFocusNode = aNode;
   nsCOMPtr<nsIAccessible> finalFocusAccessible = aAccessible;
   nsCOMPtr<nsIContent> finalFocusContent  = do_QueryInterface(aNode);
   if (finalFocusContent) {
     nsAutoString id;
-    if (nsAccUtils::GetAriaProperty(finalFocusContent, nsnull, eAria_activedescendant, id)) {
+    if (finalFocusContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_activedescendant, id)) {
       nsCOMPtr<nsIDOMDocument> domDoc;
       aNode->GetOwnerDocument(getter_AddRefs(domDoc));
       if (!domDoc) {
         return PR_FALSE;
       }
       nsCOMPtr<nsIDOMElement> relatedEl;
       domDoc->GetElementById(id, getter_AddRefs(relatedEl));
       finalFocusNode = do_QueryInterface(relatedEl);
@@ -631,30 +638,59 @@ nsresult nsRootAccessible::HandleEventWi
     // Don't create the doc accessible until load scripts have a chance to set
     // role attribute for <body> or <html> element, because the value of 
     // role attribute will be cached when the doc accessible is Init()'d
     TryFireEarlyLoadEvent(aTargetNode);
     return NS_OK;
   }
 
   if (eventType.EqualsLiteral("TreeViewChanged")) { // Always asynch, always from user input
-    NS_ENSURE_TRUE(localName.EqualsLiteral("tree"), NS_OK);
+    if (!localName.EqualsLiteral("tree"))
+      return NS_OK;
+
     nsCOMPtr<nsIContent> treeContent = do_QueryInterface(aTargetNode);
     nsAccEvent::PrepareForEvent(aTargetNode, PR_TRUE);
     return accService->InvalidateSubtreeFor(eventShell, treeContent,
                                             nsIAccessibleEvent::EVENT_ASYNCH_SIGNIFICANT_CHANGE);
   }
 
   nsCOMPtr<nsIAccessible> accessible;
   accService->GetAccessibleInShell(aTargetNode, eventShell,
                                    getter_AddRefs(accessible));
   nsCOMPtr<nsPIAccessible> privAcc(do_QueryInterface(accessible));
   if (!privAcc)
     return NS_OK;
 
+  if (eventType.EqualsLiteral("TreeRowCountChanged")) {
+    if (!localName.EqualsLiteral("tree"))
+      return NS_OK;
+
+    nsCOMPtr<nsIDOMDataContainerEvent> dataEvent(do_QueryInterface(aEvent));
+    NS_ENSURE_STATE(dataEvent);
+
+    nsCOMPtr<nsIVariant> indexVariant;
+    dataEvent->GetData(NS_LITERAL_STRING("index"),
+                       getter_AddRefs(indexVariant));
+    NS_ENSURE_STATE(indexVariant);
+
+    nsCOMPtr<nsIVariant> countVariant;
+    dataEvent->GetData(NS_LITERAL_STRING("count"),
+                       getter_AddRefs(countVariant));
+    NS_ENSURE_STATE(countVariant);
+
+    PRInt32 index, count;
+    indexVariant->GetAsInt32(&index);
+    countVariant->GetAsInt32(&count);
+
+    nsCOMPtr<nsIAccessibleTreeCache> treeAccCache(do_QueryInterface(accessible));
+    NS_ENSURE_STATE(treeAccCache);
+
+    return treeAccCache->InvalidateCache(index, count);
+  }
+
   if (eventType.EqualsLiteral("RadioStateChange")) {
     PRUint32 state = State(accessible);
 
     // radiogroup in prefWindow is exposed as a list,
     // and panebutton is exposed as XULListitem in A11y.
     // nsXULListitemAccessible::GetState uses STATE_SELECTED in this case,
     // so we need to check nsIAccessibleStates::STATE_SELECTED also.
     PRBool isEnabled = (state & (nsIAccessibleStates::STATE_CHECKED |
@@ -880,16 +916,21 @@ nsresult nsRootAccessible::HandleEventWi
   else if (eventType.EqualsLiteral("DOMMenuBarInactive")) {  // Always asynch, always from user input
     nsAccEvent::PrepareForEvent(aTargetNode, PR_TRUE);
     nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENU_END, accessible, PR_TRUE);
     FireCurrentFocusEvent();
   }
   else if (eventType.EqualsLiteral("ValueChange")) {
     nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE, accessible);
   }
+#ifdef DEBUG
+  else if (eventType.EqualsLiteral("mouseover")) {
+    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_DRAGDROP_START, accessible);
+  }
+#endif
   return NS_OK;
 }
 
 void nsRootAccessible::GetTargetNode(nsIDOMEvent *aEvent, nsIDOMNode **aTargetNode)
 {
   *aTargetNode = nsnull;
 
   nsCOMPtr<nsIDOMNSEvent> nsevent(do_QueryInterface(aEvent));
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -487,17 +487,17 @@ nsHTMLTextFieldAccessible::GetState(PRUi
                      autocomplete);
 
     if (!autocomplete.LowerCaseEqualsLiteral("off")) {
       nsCOMPtr<nsIDOMHTMLFormElement> form;
       htmlInput->GetForm(getter_AddRefs(form));
       nsCOMPtr<nsIContent> formContent(do_QueryInterface(form));
       if (formContent) {
         formContent->GetAttr(kNameSpaceID_None,
-                     nsAccessibilityAtoms::autocomplete, autocomplete);
+                             nsAccessibilityAtoms::autocomplete, autocomplete);
       }
 
       if (!formContent || !autocomplete.LowerCaseEqualsLiteral("off"))
         *aExtraState |= nsIAccessibleStates::EXT_STATE_SUPPORTS_AUTOCOMPLETION;
     }
   }
 
   return NS_OK;
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -1101,17 +1101,17 @@ nsHTMLComboboxAccessible::GetState(PRUin
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsHTMLComboboxAccessible::GetDescription(nsAString& aDescription)
 {
   aDescription.Truncate();
   // First check to see if combo box itself has a description, perhaps through
-  // tooltip (title attribute) or via aaa:describedby
+  // tooltip (title attribute) or via aria-describedby
   nsAccessible::GetDescription(aDescription);
   if (!aDescription.IsEmpty()) {
     return NS_OK;
   }
   // Use description of currently focused option
   nsCOMPtr<nsIAccessible> optionAccessible = GetFocusedOptionAccessible();
   return optionAccessible ? optionAccessible->GetDescription(aDescription) : NS_OK;
 }
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -978,17 +978,17 @@ NS_IMETHODIMP nsHTMLTableAccessible::IsP
   }
 
   // Check role and role attribute
   PRBool hasNonTableRole = (Role(this) != nsIAccessibleRole::ROLE_TABLE);
   if (hasNonTableRole) {
     RETURN_LAYOUT_ANSWER(PR_FALSE, "Has role attribute");
   }
 
-  if (HasRoleAttribute(content)) {
+  if (content->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::role)) {
     RETURN_LAYOUT_ANSWER(PR_TRUE, "Has role attribute, and role is table");
   }
   
   // Check for legitimate data table elements or attributes
   nsAutoString summary;
   if ((content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::summary, summary) && !summary.IsEmpty()) || 
       HasDescendant("caption", PR_FALSE) || HasDescendant("th") || HasDescendant("thead") ||
       HasDescendant("tfoot")   || HasDescendant("colgroup")) {
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -51,20 +51,23 @@
 #include "nsIDOMDocumentView.h"
 #include "nsIDOMRange.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
 #include "nsIFontMetrics.h"
 #include "nsIFrame.h"
-#include "nsIScrollableFrame.h"
+#include "nsFrameSelection.h"
+#include "nsILineIterator.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPlaintextEditor.h"
+#include "nsIScrollableFrame.h"
 #include "nsISelection2.h"
+#include "nsISelectionPrivate.h"
 #include "nsIServiceManager.h"
 #include "nsTextFragment.h"
 #include "gfxSkipChars.h"
 
 static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
 // ------------
 // nsHyperTextAccessible
@@ -317,22 +320,28 @@ nsIntRect nsHyperTextAccessible::GetBoun
  */
 nsIFrame*
 nsHyperTextAccessible::GetPosAndText(PRInt32& aStartOffset, PRInt32& aEndOffset,
                                      nsAString *aText, nsIFrame **aEndFrame,
                                      nsIntRect *aBoundsRect,
                                      nsIAccessible **aStartAcc,
                                      nsIAccessible **aEndAcc)
 {
-  if (aStartOffset < 0) {
+  if (aStartOffset == nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT) {
     GetCharacterCount(&aStartOffset);
   }
-  if (aEndOffset < 0) {
+  if (aStartOffset == nsIAccessibleText::TEXT_OFFSET_CARET) {
+    GetCaretOffset(&aStartOffset);
+  }
+  if (aEndOffset == nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT) {
     GetCharacterCount(&aEndOffset);
   }
+  if (aEndOffset == nsIAccessibleText::TEXT_OFFSET_CARET) {
+    GetCaretOffset(&aEndOffset);
+  }
 
   PRInt32 startOffset = aStartOffset;
   PRInt32 endOffset = aEndOffset;
 
   // Clear out parameters and set up loop
   if (aText) {
     aText->Truncate();
   }
@@ -837,41 +846,66 @@ nsresult nsHyperTextAccessible::GetTextH
   aText.Truncate();
   *aStartOffset = *aEndOffset = 0;
 
   nsCOMPtr<nsIPresShell> presShell = GetPresShell();
   if (!presShell) {
     return NS_ERROR_FAILURE;
   }
 
-  PRInt32 startOffset = aOffset;
-  PRInt32 endOffset = aOffset;
+  if (aOffset == nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT) {
+    GetCharacterCount(&aOffset);
+  }
+  if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) {
+    GetCaretOffset(&aOffset);
+    if (aOffset > 0 && (aBoundaryType == BOUNDARY_LINE_START ||
+                        aBoundaryType == BOUNDARY_LINE_END)) {
+      // It is the same character offset when the caret is visually at the very end of a line
+      // or the start of a new line. Getting text at the line should provide the line with the visual caret,
+      // otherwise screen readers will announce the wrong line as the user presses up or down arrow and land
+      // at the end of a line.
+      nsCOMPtr<nsISelection> domSel;
+      nsresult rv = GetSelections(nsnull, getter_AddRefs(domSel));
+      nsCOMPtr<nsISelectionPrivate> privateSelection(do_QueryInterface(domSel));
+      nsCOMPtr<nsFrameSelection> frameSelection;
+      rv = privateSelection->GetFrameSelection(getter_AddRefs(frameSelection));
+      NS_ENSURE_SUCCESS(rv, rv);
+      if (frameSelection->GetHint() == nsFrameSelection::HINTLEFT) {
+        -- aOffset;  // We are at the start of a line
+      }
+    }
+  }
+  else if (aOffset < 0) {
+    return NS_ERROR_FAILURE;
+  }
 
-  if (aBoundaryType == BOUNDARY_LINE_END) {
-    // Avoid getting the previous line
-    ++ startOffset;
-    ++ endOffset;
-  }
+  PRInt32 startOffset = aOffset + (aBoundaryType == BOUNDARY_LINE_END);  // Avoid getting the previous line
+  PRInt32 endOffset = startOffset;
+
   // Convert offsets to frame-relative
   nsCOMPtr<nsIAccessible> startAcc;
   nsIFrame *startFrame = GetPosAndText(startOffset, endOffset, nsnull, nsnull,
                                        nsnull, getter_AddRefs(startAcc));
 
   if (!startFrame) {
     PRInt32 textLength;
     GetCharacterCount(&textLength);
     if (aBoundaryType == BOUNDARY_LINE_START && aOffset > 0 && aOffset == textLength) {
       // Asking for start of line, while on last character
       nsCOMPtr<nsPIAccessNode> startAccessNode = do_QueryInterface(startAcc);
       if (startAccessNode) {
         startFrame = startAccessNode->GetFrame();
       }
     }
     if (!startFrame) {
-      return (aOffset < 0 || aOffset > textLength) ? NS_ERROR_FAILURE : NS_OK;
+      return aOffset > textLength ? NS_ERROR_FAILURE : NS_OK;
+    }
+    else {
+      // We're on the last continuation since we're on the last character
+      startFrame = startFrame->GetLastContinuation();
     }
   }
 
   nsSelectionAmount amount;
   PRBool needsStart = PR_FALSE;
   switch (aBoundaryType)
   {
   case BOUNDARY_CHAR:
@@ -940,17 +974,18 @@ nsresult nsHyperTextAccessible::GetTextH
 
   if (aType == eGetBefore) {
     endOffset = aOffset;
   }
   else {
     // Start moving forward from the start so that we don't get 
     // 2 words/lines if the offset occured on whitespace boundary
     // Careful, startOffset and endOffset are passed by reference to GetPosAndText() and changed
-    startOffset = endOffset = finalStartOffset;
+    // For BOUNDARY_LINE_END, make sure we start of this line
+    startOffset = endOffset = finalStartOffset + (aBoundaryType == BOUNDARY_LINE_END);
     nsCOMPtr<nsIAccessible> endAcc;
     nsIFrame *endFrame = GetPosAndText(startOffset, endOffset, nsnull, nsnull,
                                        nsnull, getter_AddRefs(endAcc));
     if (!endFrame) {
       return NS_ERROR_FAILURE;
     }
     finalEndOffset = GetRelativeOffset(presShell, endFrame, endOffset, endAcc,
                                        amount, eDirNext, needsStart);
@@ -1036,17 +1071,17 @@ nsHyperTextAccessible::GetAttributesInte
 {
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;  // Node already shut down
   }
 
   nsresult rv = nsAccessibleWrap::GetAttributesInternal(aAttributes);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+  nsCOMPtr<nsIContent> content(do_QueryInterface(GetRoleContent(mDOMNode)));
   NS_ENSURE_TRUE(content, NS_ERROR_UNEXPECTED);
   nsIAtom *tag = content->Tag();
 
   PRInt32 headLevel = 0;
   if (tag == nsAccessibilityAtoms::h1)
     headLevel = 1;
   else if (tag == nsAccessibilityAtoms::h2)
     headLevel = 2;
@@ -1070,16 +1105,26 @@ nsHyperTextAccessible::GetAttributesInte
   // via formatting: block
   nsIFrame *frame = GetFrame();
   if (frame && frame->GetType() == nsAccessibilityAtoms::blockFrame) {
     nsAutoString oldValueUnused;
     aAttributes->SetStringProperty(NS_LITERAL_CSTRING("formatting"), NS_LITERAL_STRING("block"),
                                    oldValueUnused);
   }
 
+  if (gLastFocusedNode == mDOMNode) {
+    PRInt32 lineNumber = GetCaretLineNumber();
+    if (lineNumber >= 1) {
+      nsAutoString strLineNumber;
+      strLineNumber.AppendInt(lineNumber);
+      nsAccUtils::SetAccAttr(aAttributes, nsAccessibilityAtoms::lineNumber,
+                             strLineNumber);
+    }
+  }
+
   return  NS_OK;
 }
 
 /*
  * Given an offset, the x, y, width, and height values are filled appropriately.
  */
 NS_IMETHODIMP nsHyperTextAccessible::GetCharacterExtents(PRInt32 aOffset, PRInt32 *aX, PRInt32 *aY,
                                                          PRInt32 *aWidth, PRInt32 *aHeight,
@@ -1431,16 +1476,84 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRInt32 caretOffset;
   domSel->GetFocusOffset(&caretOffset);
 
   return DOMPointToHypertextOffset(caretNode, caretOffset, aCaretOffset);
 }
 
+PRInt32 nsHyperTextAccessible::GetCaretLineNumber()
+{
+  // Provide the line number for the caret, relative to the
+  // currently focused node. Use a 1-based index
+  nsCOMPtr<nsISelection> domSel;
+  GetSelections(nsnull, getter_AddRefs(domSel));
+  nsCOMPtr<nsISelectionPrivate> privateSelection(do_QueryInterface(domSel));
+  NS_ENSURE_TRUE(privateSelection, -1);
+  nsCOMPtr<nsFrameSelection> frameSelection;
+  privateSelection->GetFrameSelection(getter_AddRefs(frameSelection));
+  NS_ENSURE_TRUE(frameSelection, -1);
+
+  nsCOMPtr<nsIDOMNode> caretNode;
+  domSel->GetFocusNode(getter_AddRefs(caretNode));
+  nsCOMPtr<nsIContent> caretContent = do_QueryInterface(caretNode);
+  if (!caretContent || !nsAccUtils::IsAncestorOf(mDOMNode, caretNode)) {
+    return -1;
+  }
+
+  PRInt32 caretOffset, returnOffsetUnused;
+  domSel->GetFocusOffset(&caretOffset);
+  nsFrameSelection::HINT hint = frameSelection->GetHint();
+  nsIFrame *caretFrame = frameSelection->GetFrameForNodeOffset(caretContent, caretOffset,
+                                                               hint, &returnOffsetUnused);
+  NS_ENSURE_TRUE(caretFrame, -1);
+
+  PRInt32 lineNumber = 1;
+  nsCOMPtr<nsILineIterator> lineIterForCaret;
+  nsCOMPtr<nsIContent> hyperTextContent = do_QueryInterface(mDOMNode);
+  while (caretFrame) {
+    if (hyperTextContent == caretFrame->GetContent()) {
+      return lineNumber; // Must be in a single line hyper text, there is no line iterator
+    }
+    nsIFrame *parentFrame = caretFrame->GetParent();
+    if (!parentFrame)
+      break;
+
+    // Add lines for the sibling frames before the caret
+    nsIFrame *sibling = parentFrame->GetFirstChild(nsnull);
+    while (sibling && sibling != caretFrame) {
+      nsCOMPtr<nsILineIterator> lineIterForSibling = do_QueryInterface(sibling);
+      if (lineIterForSibling) {
+        PRInt32 addLines;
+        // For the frames before that grab all the lines
+        lineIterForSibling->GetNumLines(&addLines);
+        lineNumber += addLines;
+      }
+      sibling = sibling->GetNextSibling();
+    }
+
+    // Get the line number relative to the container with lines
+    if (!lineIterForCaret) {   // Add the caret line just once
+      lineIterForCaret = do_QueryInterface(parentFrame);
+      if (lineIterForCaret) {
+        // Ancestor of caret
+        PRInt32 addLines;
+        lineIterForCaret->FindLineContaining(caretFrame, &addLines);
+        lineNumber += addLines;
+      }
+    }
+
+    caretFrame = parentFrame;
+  }
+
+  NS_NOTREACHED("DOM ancestry had this hypertext but frame ancestry didn't");
+  return lineNumber;
+}
+
 nsresult nsHyperTextAccessible::GetSelections(nsISelectionController **aSelCon,
                                               nsISelection **aDomSel,
                                               nsCOMArray<nsIDOMRange>* aRanges)
 {
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;
   }
   if (aSelCon) {
--- a/accessible/src/html/nsHyperTextAccessible.h
+++ b/accessible/src/html/nsHyperTextAccessible.h
@@ -217,16 +217,23 @@ protected:
    * @param aDomSel      The selection interface for the current hyper text, or nsnull if not needed
    * @param aRanges      The selected ranges within the current subtree, or nsnull if not needed
    */
   nsresult GetSelections(nsISelectionController **aSelCon,
                          nsISelection **aDomSel = nsnull,
                          nsCOMArray<nsIDOMRange>* aRanges = nsnull);
   nsresult SetSelectionRange(PRInt32 aStartPos, PRInt32 aEndPos);
 
+  /**
+   * Provide the line number for the caret, relative to the
+   * current DOM node.
+   * @return 1-based index for the line number with the caret
+   */
+  PRInt32 GetCaretLineNumber();
+
   // Helpers
   nsresult GetDOMPointByFrameOffset(nsIFrame *aFrame, PRInt32 aOffset,
                                     nsIAccessible *aAccessible,
                                     nsIDOMNode **aNode, PRInt32 *aNodeOffset);
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsHyperTextAccessible,
                               NS_HYPERTEXTACCESSIBLE_IMPL_CID)
--- a/accessible/src/msaa/CAccessibleTable.cpp
+++ b/accessible/src/msaa/CAccessibleTable.cpp
@@ -420,17 +420,22 @@ CAccessibleTable::get_selectedRows(long 
 {
   return GetSelectedItems(aMaxRows, aRows, aNRows, ITEMSTYPE_ROWS);
 }
 
 STDMETHODIMP
 CAccessibleTable::get_summary(IUnknown **aAccessible)
 {
   *aAccessible = NULL;
-  return E_NOTIMPL;
+
+  // Neither html:table nor xul:tree nor ARIA grid/tree have an ability to
+  // link an accessible object to specify a summary. There is closes method
+  // in nsIAccessibleTable::summary to get a summary as a string which is not
+  // mapped directly to IAccessible2.
+  return S_OK;
 }
 
 STDMETHODIMP
 CAccessibleTable::get_isColumnSelected(long aColumn, boolean *aIsSelected)
 {
   nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
   NS_ASSERTION(tableAcc, CANT_QUERY_ASSERTION_MSG);
   if (!tableAcc)
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -471,17 +471,18 @@ STDMETHODIMP nsAccessibleWrap::get_accRo
 
   accessNode->GetDOMNode(getter_AddRefs(domNode));
   nsIContent *content = GetRoleContent(domNode);
   if (!content)
     return E_FAIL;
 
   if (content->IsNodeOfType(nsINode::eELEMENT)) {
     nsAutoString roleString;
-    if (msaaRole != ROLE_SYSTEM_CLIENT && !GetARIARole(content, roleString)) {
+    if (msaaRole != ROLE_SYSTEM_CLIENT &&
+        !content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::role, roleString)) {
       nsINodeInfo *nodeInfo = content->NodeInfo();
       nodeInfo->GetName(roleString);
       nsAutoString nameSpaceURI;
       nodeInfo->GetNamespaceURI(nameSpaceURI);
       if (!nameSpaceURI.IsEmpty()) {
         // Only append name space if different from that of current document
         roleString += NS_LITERAL_STRING(", ") + nameSpaceURI;
       }
@@ -1320,22 +1321,23 @@ nsAccessibleWrap::get_uniqueID(long *uni
     return S_OK;
   }
   return E_FAIL;
 }
 
 STDMETHODIMP
 nsAccessibleWrap::get_windowHandle(HWND *windowHandle)
 {
-  void **handle = nsnull;
-  if (NS_SUCCEEDED(GetOwnerWindow(handle))) {
-    *windowHandle = reinterpret_cast<HWND>(*handle);
-    return S_OK;
-  }
-  return E_FAIL;
+  void *handle = nsnull;
+  nsresult rv = GetOwnerWindow(&handle);
+  if (NS_FAILED(rv))
+    return E_FAIL;
+
+  *windowHandle = reinterpret_cast<HWND>(handle);
+  return S_OK;
 }
 
 STDMETHODIMP
 nsAccessibleWrap::get_indexInParent(long *indexInParent)
 {
   PRInt32 index;
   if (NS_SUCCEEDED(GetIndexInParent(&index))) {
     *indexInParent = index;
--- a/accessible/src/msaa/nsEventMap.h
+++ b/accessible/src/msaa/nsEventMap.h
@@ -33,20 +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 <winuser.h>
-#ifndef WINABLEAPI
-#include <winable.h>
-#endif
+#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
@@ -77,18 +77,18 @@ static const PRUint32 gWinEventMap[] = {
   EVENT_SYSTEM_MENUPOPUPSTART,                       // nsIAccessibleEvent::EVENT_MENUPOPUP_START
   EVENT_SYSTEM_MENUPOPUPEND,                         // nsIAccessibleEvent::EVENT_MENUPOPUP_END
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_CAPTURE_START
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_CAPTURE_END
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_MOVESIZE_START
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_MOVESIZE_END
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_CONTEXT_HELP_START
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_CONTEXT_HELP_END
-  kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_DRAGDROP_START
-  kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_DRAGDROP_END
+  EVENT_SYSTEM_DRAGDROPSTART,                        // nsIAccessibleEvent::EVENT_DRAGDROP_START
+  EVENT_SYSTEM_DRAGDROPEND,                          // nsIAccessibleEvent::EVENT_DRAGDROP_END
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_DIALOG_START
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_DIALOG_END
   EVENT_SYSTEM_SCROLLINGSTART,                       // nsIAccessibleEvent::EVENT_SCROLLING_START
   EVENT_SYSTEM_SCROLLINGEND,                         // nsIAccessibleEvent::EVENT_SCROLLING_END
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_MINIMIZE_START
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_MINIMIZE_END
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_START
   IA2_EVENT_DOCUMENT_LOAD_COMPLETE,                  // nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -220,31 +220,31 @@ nsXFormsAccessible::GetState(PRUint32 *a
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsAccessible::GetName(nsAString& aName)
 {
   nsAutoString name;
-  nsresult rv = GetTextFromRelationID(eAria_labelledby, name);
+  nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_labelledby, name);
   if (NS_SUCCEEDED(rv) && !name.IsEmpty()) {
     aName = name;
     return NS_OK;
   }
 
   // search the xforms:label element
   return GetBoundChildElementValue(NS_LITERAL_STRING("label"), aName);
 }
 
 NS_IMETHODIMP
 nsXFormsAccessible::GetDescription(nsAString& aDescription)
 {
   nsAutoString description;
-  nsresult rv = GetTextFromRelationID(eAria_describedby, description);
+  nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_describedby, description);
 
   if (NS_SUCCEEDED(rv) && !description.IsEmpty()) {
     aDescription = description;
     return NS_OK;
   }
 
   // search the xforms:hint element
   return GetBoundChildElementValue(NS_LITERAL_STRING("hint"), aDescription);
--- a/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
@@ -54,26 +54,26 @@ nsXFormsLabelAccessible::GetRole(PRUint3
   *aRole = nsIAccessibleRole::ROLE_STATICTEXT;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXFormsLabelAccessible::GetName(nsAString& aName)
 {
   nsAutoString name;
-  nsresult rv = GetTextFromRelationID(eAria_labelledby, name);
+  nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_labelledby, name);
   aName = name;
   return rv;
 }
 
 NS_IMETHODIMP
 nsXFormsLabelAccessible::GetDescription(nsAString& aDescription)
 {
   nsAutoString description;
-  nsresult rv = GetTextFromRelationID(eAria_describedby, description);
+  nsresult rv = GetTextFromRelationID(nsAccessibilityAtoms::aria_describedby, description);
   aDescription = description;
   return rv;
 }
 
 // nsXFormsOutputAccessible
 
 nsXFormsOutputAccessible::
   nsXFormsOutputAccessible(nsIDOMNode *aNode, nsIWeakReference *aShell):
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -44,18 +44,16 @@
 #include "nsXULTreeAccessibleWrap.h"
 #include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
 #ifdef MOZ_ACCESSIBILITY_ATK
 #include "nsIAccessibleTable.h"
 #endif
 
-#define kMaxTreeColumns 100
-
 /* static */
 PRBool nsXULTreeAccessible::IsColumnHidden(nsITreeColumn *aColumn)
 {
   nsCOMPtr<nsIDOMElement> element;
   aColumn->GetElement(getter_AddRefs(element));
   nsCOMPtr<nsIContent> content = do_QueryInterface(element);
   return content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::hidden,
                               nsAccessibilityAtoms::_true, eCaseMatters);
@@ -501,16 +499,18 @@ NS_IMETHODIMP nsXULTreeAccessible::Selec
       if (selection)
         selection->SelectAll();
     }
   }
 
   return NS_OK;
 }
 
+// nsIAccessible nsIAccessibleTreeCache::
+//   GetCachedTreeitemAccessible(in long aRow, nsITreeColumn* aColumn)
 NS_IMETHODIMP
 nsXULTreeAccessible::GetCachedTreeitemAccessible(PRInt32 aRow,
                                                  nsITreeColumn* aColumn,
                                                  nsIAccessible** aAccessible)
 {
   NS_ENSURE_ARG_POINTER(aAccessible);
   *aAccessible = nsnull;
 
@@ -549,16 +549,87 @@ nsXULTreeAccessible::GetCachedTreeitemAc
     NS_ENSURE_SUCCESS(rv, rv);
     PutCacheEntry(*mAccessNodeCache, (void*)(aRow * kMaxTreeColumns + columnIndex), accessNode);
   }
   nsCOMPtr<nsIAccessible> accessible(do_QueryInterface(accessNode));
   NS_IF_ADDREF(*aAccessible = accessible);
   return NS_OK;
 }
 
+// void nsIAccessibleTreeCache::
+//   invalidateCache(in PRInt32 aRow, in PRInt32 aCount)
+NS_IMETHODIMP
+nsXULTreeAccessible::InvalidateCache(PRInt32 aRow, PRInt32 aCount)
+{
+  // Do not invalidate the cache if rows have been inserted.
+  if (aCount > 0)
+    return NS_OK;
+
+  nsCOMPtr<nsITreeColumns> cols;
+  nsresult rv = mTree->GetColumns(getter_AddRefs(cols));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+#ifdef MOZ_ACCESSIBILITY_ATK
+  PRInt32 colsCount = 0;
+  rv = cols->GetCount(&colsCount);
+  NS_ENSURE_SUCCESS(rv, rv);
+#else
+  nsCOMPtr<nsITreeColumn> col;
+  rv = cols->GetKeyColumn(getter_AddRefs(col));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRInt32 colIdx = 0;
+  rv = col->GetIndex(&colIdx);
+  NS_ENSURE_SUCCESS(rv, rv);
+#endif
+
+  for (PRInt32 rowIdx = aRow; rowIdx < aRow - aCount; rowIdx++) {
+#ifdef MOZ_ACCESSIBILITY_ATK
+    for (PRInt32 colIdx = 0; colIdx < colsCount; ++colIdx) {
+#else
+    {
+#endif
+
+      void *key = reinterpret_cast<void*>(rowIdx * kMaxTreeColumns + colIdx);
+
+      nsCOMPtr<nsIAccessNode> accessNode;
+      GetCacheEntry(*mAccessNodeCache, key, getter_AddRefs(accessNode));
+
+      if (accessNode) {
+        nsCOMPtr<nsIAccessible> accessible(do_QueryInterface(accessNode));
+        nsCOMPtr<nsIAccessibleEvent> event =
+          new nsAccEvent(nsIAccessibleEvent::EVENT_DOM_DESTROY,
+                         accessible, nsnull, PR_FALSE);
+        FireAccessibleEvent(event);
+
+        mAccessNodeCache->Remove(key);
+      }
+    }
+  }
+
+  PRInt32 newRowCount = 0;
+  rv = mTreeView->GetRowCount(&newRowCount);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRInt32 oldRowCount = newRowCount - aCount;
+
+  for (PRInt32 rowIdx = newRowCount; rowIdx < oldRowCount; ++rowIdx) {
+#ifdef MOZ_ACCESSIBILITY_ATK
+    for (PRInt32 colIdx = 0; colIdx < colsCount; ++colIdx) {
+#else
+    {
+#endif
+      void *key = reinterpret_cast<void*>(rowIdx * kMaxTreeColumns + colIdx);
+      mAccessNodeCache->Remove(key);
+    }
+  }
+
+  return NS_OK;
+}
+
 nsresult nsXULTreeAccessible::GetColumnCount(nsITreeBoxObject* aBoxObject, PRInt32* aCount)
 {
   NS_ENSURE_TRUE(aBoxObject, NS_ERROR_FAILURE);
   nsCOMPtr<nsITreeColumns> treeColumns;
   aBoxObject->GetColumns(getter_AddRefs(treeColumns));
   NS_ENSURE_TRUE(treeColumns, NS_ERROR_FAILURE);
   return treeColumns->GetCount(aCount);
 }
--- a/accessible/src/xul/nsXULTreeAccessible.h
+++ b/accessible/src/xul/nsXULTreeAccessible.h
@@ -39,20 +39,20 @@
 #define __nsXULTreeAccessible_h__
 
 #include "nsITreeBoxObject.h"
 #include "nsITreeView.h"
 #include "nsITreeColumns.h"
 #include "nsXULSelectAccessible.h"
 #include "nsIAccessibleTreeCache.h"
 
-
 /*
  * A class the represents the XUL Tree widget.
  */
+const PRUint32 kMaxTreeColumns = 100;
 const PRUint32 kDefaultTreeCacheSize = 256;
 
 class nsXULTreeAccessible : public nsXULSelectableAccessible,
                             public nsIAccessibleTreeCache
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLESELECTABLE
--- 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.0b2pre
+WIN32_MODULE_PRODUCTVERSION_STRING=3.0b3pre
 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
@@ -253,17 +253,18 @@ 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);
+pref("browser.history_expire_days_min", 90);
+pref("browser.history_expire_sites", 40000);
 
 // 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);
 
@@ -579,16 +580,21 @@ pref("browser.sessionstore.privacy_level
 pref("browser.sessionstore.max_tabs_undo", 10);
 
 // allow META refresh by default
 pref("accessibility.blockautorefresh", false);
 
 // import bookmarks.html into Places bookmarks
 pref("browser.places.importBookmarksHTML", true);
 
-// if false, will add the "Places" folder to the personal toolbar
-pref("browser.places.createdDefaultQueries", false);
+// if false, will add the "Smart Bookmarks" folder to the personal toolbar
+pref("browser.places.createdSmartBookmarks", false);
+
+// If true, will migrate uri post-data annotations to
+// bookmark post-data annotations (bug 398914)
+// XXX to be removed after beta 2 (bug 391419)
+pref("browser.places.migratePostDataAnnotations", true);
 
 // Controls behavior of the "Add Exception" dialog launched from SSL error pages
 // 0 - don't pre-populate anything
 // 1 - pre-populate site URL, but don't fetch certificate
 // 2 - pre-populate site URL and pre-fetch certificate
 pref("browser.ssl_override_behavior", 1);
--- a/browser/base/Makefile.in
+++ b/browser/base/Makefile.in
@@ -69,11 +69,11 @@ libs locale::
 	$(SYSINSTALL) $(IFLAGS1) $(srcdir)/content/browserconfig.properties $(DIST)/bin
 	$(SYSINSTALL) $(IFLAGS1) $(srcdir)/content/old-homepage-default.properties $(DIST)/bin
 
 install::
 	$(SYSINSTALL) $(IFLAGS1) $(srcdir)/content/browserconfig.properties $(DESTDIR)$(mozappdir)
 	$(SYSINSTALL) $(IFLAGS1) $(srcdir)/content/old-homepage-default.properties $(DESTDIR)$(mozappdir)
 endif
 
-ifneq (,$(filter windows mac cocoa, $(MOZ_WIDGET_TOOLKIT)))
+ifneq (,$(filter windows mac cocoa gtk2, $(MOZ_WIDGET_TOOLKIT)))
 DEFINES += -DCONTEXT_COPY_IMAGE_CONTENTS=1
 endif
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -166,17 +166,17 @@
                           command="Browser:Stop"
 #ifdef XP_MACOSX
                           key="key_stop_mac"/>
 #else
                           key="key_stop"/>
 #endif
                 <menuitem label="&reloadCmd.label;" accesskey="&reloadCmd.accesskey;" command="Browser:Reload" key="key_reload"/>
                 <menuseparator/>
-                <menu id="viewFullZoomMenu" label="&fullZoom.label;" accesskey="&fullZoom.accesskey;" observes="isImage">
+                <menu id="viewFullZoomMenu" label="&fullZoom.label;" accesskey="&fullZoom.accesskey;">
                   <menupopup>
                     <menuitem key="key_fullZoomEnlarge" label="&fullZoomEnlargeCmd.label;" accesskey="&fullZoomEnlargeCmd.accesskey;"
                               command="cmd_fullZoomEnlarge"/>
                     <menuitem key="key_fullZoomReduce"  label="&fullZoomReduceCmd.label;"  accesskey="&fullZoomReduceCmd.accesskey;"
                               command="cmd_fullZoomReduce"/>
                     <menuseparator/>
                     <menuitem key="key_fullZoomReset" label="&fullZoomResetCmd.label;" accesskey="&fullZoomResetCmd.accesskey;"
                               command="cmd_fullZoomReset"/>
@@ -412,17 +412,17 @@
               <menuitem id="menu_openDownloads" label="&downloads.label;"
                         accesskey="&downloads.accesskey;"
                         key="key_openDownloads" command="Tools:Downloads"/>
               <menuitem id="menu_openAddons" label="&addons.label;"
                         accesskey="&addons.accesskey;" command="Tools:Addons"/>
               <menuseparator id="devToolsSeparator"/>
               <menuitem id="javascriptConsole" 
                         label="&errorConsoleCmd.label;" accesskey="&errorConsoleCmd.accesskey;" 
-                        oncommand="toJavaScriptConsole();"/>
+                        key="key_errorConsole" oncommand="toJavaScriptConsole();"/>
 #ifdef XP_WIN
               <menuitem accesskey="&pageInfoCmd.accesskey;" label="&pageInfoCmd.label;"   
                         command="View:PageInfo"/>
 #else
               <menuitem accesskey="&pageInfoCmd.accesskey;" label="&pageInfoCmd.label;"   
                         key="key_viewInfo" command="View:PageInfo"/>
 #endif
               <menuseparator id="sanitizeSeparator"/>
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -817,8 +817,42 @@ var PlacesStarButton = {
                                             aIsAnnotationProperty, aValue) {
     if (!this._batching && aProperty == "uri")
       this.updateState();
   },
 
   onItemVisited: function() { },
   onItemMoved: function() { }
 };
+
+/**
+ * Various migration tasks.
+ */
+function placesMigrationTasks() {
+  // bug 398914 - move all post-data annotations from URIs to bookmarks
+  // XXX - REMOVE ME FOR BETA 3 (bug 391419)
+  if (gPrefService.getBoolPref("browser.places.migratePostDataAnnotations")) {
+    const annosvc = PlacesUtils.annotations;
+    const bmsvc = PlacesUtils.bookmarks;
+    const oldPostDataAnno = "URIProperties/POSTData";
+    var pages = annosvc.getPagesWithAnnotation(oldPostDataAnno, {});
+    for (let i = 0; i < pages.length; i++) {
+      try {
+        let uri = pages[i];
+        var postData = annosvc.getPageAnnotation(uri, oldPostDataAnno);
+        // We can't know which URI+keyword combo this postdata was for, but
+        // it's very likely that if this URI is bookmarked and has a keyword
+        // *and* the URI has postdata, then this bookmark was using the
+        // postdata. Propagate the annotation to all bookmarks for this URI
+        // just to be safe.
+        let bookmarks = bmsvc.getBookmarkIdsForURI(uri, {});
+        for (let i = 0; i < bookmarks.length; i++) {
+          var keyword = bmsvc.getKeywordForBookmark(bookmarks[i]);
+          if (keyword)
+            annosvc.setItemAnnotation(bookmarks[i], POST_DATA_ANNO, postData, 0, annosvc.EXPIRE_NEVER); 
+        }
+        // Remove the old annotation.
+        annosvc.removePageAnnotation(uri, oldPostDataAnno);
+      } catch(ex) {}
+    }
+    gPrefService.setBoolPref("browser.places.migratePostDataAnnotations", false);
+  }
+}
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -197,16 +197,17 @@
     <key id="key_search2" key="&searchFocus.commandkey2;" command="Tools:Search" modifiers="accel"/>
 #endif
 #ifdef XP_GNOME
     <key id="key_search2" key="&searchFocusUnix.commandkey;" command="Tools:Search" modifiers="accel"/>
     <key id="key_openDownloads" key="&downloadsUnix.commandkey;" command="Tools:Downloads" modifiers="accel"/>
 #else
     <key id="key_openDownloads" key="&downloads.commandkey;" command="Tools:Downloads" modifiers="accel"/>
 #endif
+    <key id="key_errorConsole" key="&errorConsoleCmd.commandkey;" oncommand="toJavaScriptConsole();" modifiers="accel,shift"/>
     <key id="openFileKb" key="&openFileCmd.commandkey;" command="Browser:OpenFile"  modifiers="accel"/>
     <key id="key_savePage" key="&savePageCmd.commandkey;" command="Browser:SavePage" modifiers="accel"/>
     <key id="printKb" key="&printCmd.commandkey;" command="cmd_print"  modifiers="accel"/>
     <key id="key_close" key="&closeCmd.key;" command="cmd_close" modifiers="accel"/>
     <key id="key_closeWindow" key="&closeCmd.key;" command="cmd_closeWindow" modifiers="accel,shift"/>
     <key id="key_undo"
          key="&undoCmd.key;"
          modifiers="accel"/>
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -23,17 +23,17 @@ toolbar[printpreview="true"] {
 menuitem.spell-suggestion {
   font-weight: bold;
 }
 
 #sidebar-box toolbarbutton.tabs-closebutton {
   -moz-user-focus: normal;
 }
 
-.verifiedDomain > #identity-icon-label {
+.verifiedDomain > hbox > #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;
 }
 
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -907,17 +907,20 @@ function delayedStartup()
 
   if (gMustLoadSidebar) {
     var sidebar = document.getElementById("sidebar");
     var sidebarBox = document.getElementById("sidebar-box");
     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
   }
 
   UpdateUrlbarSearchSplitterState();
-
+  
+  try {
+    placesMigrationTasks();
+  } catch(ex) {}
   initBookmarksToolbar();
   PlacesStarButton.init();
 
   // called when we go into full screen, even if it is
   // initiated by a web page script
   window.addEventListener("fullscreen", onFullScreen, true);
 
   if (gIsLoadingBlank && gURLBar && isElementVisible(gURLBar))
@@ -1656,27 +1659,26 @@ function getShortcutOrURI(aURL, aPostDat
     keyword = aURL.substr(0, offset);
     param = aURL.substr(offset + 1);
   }
 
   var engine = searchService.getEngineByAlias(keyword);
   if (engine)
     return engine.getSubmission(param, null).uri.spec;
 
-  try {
-    var shortcutURI = PlacesUtils.bookmarks.getURIForKeyword(keyword);
-    shortcutURL = shortcutURI.spec;
-    aPostDataRef.value = PlacesUtils.getPostDataForURI(shortcutURI);
-  } catch(ex) {}
+  if (!aPostDataRef)
+    aPostDataRef = {};
+  [shortcutURL, aPostDataRef.value] =
+    PlacesUtils.getURLAndPostDataForKeyword(keyword);
 
   if (!shortcutURL)
     return aURL;
 
   var postData = "";
-  if (aPostDataRef && aPostDataRef.value)
+  if (aPostDataRef.value)
     postData = unescape(aPostDataRef.value);
 
   if (/%s/i.test(shortcutURL) || /%s/i.test(postData)) {
     var charset = "";
     const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
     var matches = shortcutURL.match(re);
     if (matches)
       [, shortcutURL, charset] = matches;
@@ -2037,24 +2039,17 @@ function SetPageProxyState(aState)
 
   if (!gProxyButton)
     gProxyButton = document.getElementById("page-proxy-button");
   if (!gProxyFavIcon)
     gProxyFavIcon = document.getElementById("page-proxy-favicon");
   if (!gProxyDeck)
     gProxyDeck = document.getElementById("page-proxy-deck");
 
-  if (gURLBar.getAttribute("pageproxystate") != aState) {
-    gURLBar.setAttribute("pageproxystate", aState);
-#ifdef MOZ_WIDGET_GTK2
-    // redraw gtk focus ring
-    if (gURLBar.focused)
-      gURLBar.focus();
-#endif
-  }
+  gURLBar.setAttribute("pageproxystate", aState);
   gProxyButton.setAttribute("pageproxystate", aState);
 
   // the page proxy state is set to valid via OnLocationChange, which
   // gets called when we switch tabs.
   if (aState == "valid") {
     gLastValidURLStr = gURLBar.value;
     gURLBar.addEventListener("input", UpdatePageProxyState, false);
 
@@ -2147,28 +2142,28 @@ function BrowserOnCommand(event) {
       if (ot == errorDoc.getElementById('exceptionDialogButton')) {
         var params = { exceptionAdded : false };
         
         try {
           switch (gPrefService.getIntPref("browser.ssl_override_behavior")) {
             case 2 : // Pre-fetch & pre-populate
               params.prefetchCert = true;
             case 1 : // Pre-populate
-              params.location = content.location.href;
+              params.location = errorDoc.location.href;
           }
         } catch (e) {
           Components.utils.reportError("Couldn't get ssl_override pref: " + e);
         }
         
         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();
+          errorDoc.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",
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -260,34 +260,37 @@
                  tabscrolling="true"
                  showcommentcolumn="true"
                  showimagecolumn="true"
                  enablehistory="true"
                  maxrows="10"
                  newlines="stripsurroundingwhitespace"
                  oninput="URLBarOnInput(event);"
                  ontextentered="return handleURLBarCommand(param);"
-                 ontextreverted="return handleURLBarRevert();">
+                 ontextreverted="return handleURLBarRevert();"
+                 pageproxystate="invalid">
           <!-- Use onclick instead of normal popup= syntax since the popup
                code fires onmousedown, and hence eats our favicon drag events -->
-          <box id="identity-box" align="center" 
+          <box id="identity-box"
                onclick="getIdentityHandler().handleIdentityClick(event);">
-            <deck id="page-proxy-deck" onclick="PageProxyClickHandler(event);">
-              <image id="page-proxy-button"
-                     ondraggesture="PageProxyDragGesture(event);"
-                     tooltiptext="&proxyIcon.tooltip;"/>
-              <image id="page-proxy-favicon" validate="never"
-                     ondraggesture="PageProxyDragGesture(event);"
-                     onload="this.parentNode.selectedIndex = 1;
-                             event.stopPropagation();"
-                     onerror="this.removeAttribute('src');
-                              this.parentNode.selectedIndex = 0;"
-                     tooltiptext="&proxyIcon.tooltip;"/>
-            </deck>
-            <label id="identity-icon-label"/>
+            <hbox align="center">
+              <deck id="page-proxy-deck" onclick="PageProxyClickHandler(event);">
+                <image id="page-proxy-button"
+                       ondraggesture="PageProxyDragGesture(event);"
+                       tooltiptext="&proxyIcon.tooltip;"/>
+                <image id="page-proxy-favicon" validate="never"
+                       ondraggesture="PageProxyDragGesture(event);"
+                       onload="this.parentNode.selectedIndex = 1;
+                               event.stopPropagation();"
+                       onerror="this.removeAttribute('src');
+                                this.parentNode.selectedIndex = 0;"
+                       tooltiptext="&proxyIcon.tooltip;"/>
+              </deck>
+              <label id="identity-icon-label"/>
+            </hbox>
           </box>
           <hbox id="urlbar-icons">
             <button type="menu"
                     style="-moz-user-focus: none"
                     class="plain"
                     id="feed-button"
                     chromedir="&locale.dir;"
                     onclick="return FeedHandler.onFeedButtonClick(event);">
--- a/browser/base/content/pageinfo/pageInfo.xul
+++ b/browser/base/content/pageinfo/pageInfo.xul
@@ -54,17 +54,16 @@
 <?xul-overlay href="chrome://browser/content/macBrowserOverlay.xul"?>
 #endif
 
 <window id="main-window"
   xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
   windowtype="Browser:page-info"
   onload="onLoadPageInfo()"
   onunload="onUnloadPageInfo()"
-  xmlns:xhtml="http://www.w3.org/1999/xhtml"
   align="stretch"
   screenX="10" screenY="10"
   width="&pageInfoWindow.width;" height="&pageInfoWindow.height;"
   persist="screenX screenY width height sizemode">
 
   <script type="application/x-javascript" src="chrome://global/content/globalOverlay.js"/>
   <script type="application/x-javascript" src="chrome://global/content/contentAreaUtils.js"/>
   <script type="application/x-javascript" src="chrome://browser/content/pageinfo/pageInfo.js"/>
@@ -325,51 +324,51 @@
         <label value="&permissionsFor;" control="hostText" />
         <textbox id="hostText" class="header" readonly="true"
                  crop="end" flex="1"/>
       </hbox>
 
       <vbox id="permList" flex="1">
         <vbox>
           <label value="&permImage;" control="permImageGroup imageRadioGroup"/>
-          <hbox id="permImageGroup" xhtml:role="group">
+          <hbox id="permImageGroup" role="group">
             <checkbox id="imageDef" command="cmd_imageDef" label="&permUseDefault;"/>
             <spacer flex="1"/>
             <radiogroup id="imageRadioGroup" orient="horizontal">
               <radio id="image#1" command="cmd_imageToggle" label="&permAllow;"/>
               <radio id="image#2" command="cmd_imageToggle" label="&permBlock;"/>
             </radiogroup>
           </hbox>
         </vbox>
         <vbox>
           <label value="&permPopup;" control="permPopupGroup popupRadioGroup"/>
-          <hbox id="permPopupGroup" xhtml:role="group">
+          <hbox id="permPopupGroup" role="group">
             <checkbox id="popupDef" command="cmd_popupDef" label="&permUseDefault;"/>
             <spacer flex="1"/>
             <radiogroup id="popupRadioGroup" orient="horizontal">
               <radio id="popup#1" command="cmd_popupToggle" label="&permAllow;"/>
               <radio id="popup#2" command="cmd_popupToggle" label="&permBlock;"/>
             </radiogroup>
           </hbox>
         </vbox>
         <vbox>
           <label value="&permCookie;" control="permCookieGroup cookieRadioGroup"/>
-          <hbox id="permCookieGroup" xhtml:role="group">
+          <hbox id="permCookieGroup" role="group">
             <checkbox id="cookieDef" command="cmd_cookieDef" label="&permUseDefault;"/>
             <spacer flex="1"/>
             <radiogroup id="cookieRadioGroup" orient="horizontal">
               <radio id="cookie#1" command="cmd_cookieToggle" label="&permAllow;"/>
               <radio id="cookie#8" command="cmd_cookieToggle" label="&permAllowSession;"/>
               <radio id="cookie#2" command="cmd_cookieToggle" label="&permBlock;"/>
             </radiogroup>
           </hbox>
         </vbox>
         <vbox>
           <label value="&permInstall;" control="permInstallGroup installRadioGroup"/>
-          <hbox id="permInstallGroup" xhtml:role="group">
+          <hbox id="permInstallGroup" role="group">
             <checkbox id="installDef" command="cmd_installDef" label="&permUseDefault;"/>
             <spacer flex="1"/>
             <radiogroup id="installRadioGroup" orient="horizontal">
               <radio id="install#1" command="cmd_installToggle" label="&permAllow;"/>
               <radio id="install#2" command="cmd_installToggle" label="&permBlock;"/>
             </radiogroup>
           </hbox>
         </vbox>
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -130,21 +130,27 @@ var security = {
   /**
    * Open the cookie manager window
    */
   viewCookies : function()
   {
     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                        .getService(Components.interfaces.nsIWindowMediator);
     var win = wm.getMostRecentWindow("Browser:Cookies");
-    if (win)
+    var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].
+                      getService(Ci.nsIEffectiveTLDService);
+    var eTLD = eTLDService.getBaseDomainFromHost(this._getSecurityInfo()
+                                                     .hostName);
+    if (win) {
+      win.gCookiesWindow.setFilter(eTLD);
       win.focus();
+    }
     else
       window.openDialog("chrome://browser/content/preferences/cookies.xul",
-                        "Browser:Cookies", "");
+                        "Browser:Cookies", "", {filterString : eTLD});
   },
   
   /**
    * Open the login manager window
    */
   viewPasswords : function()
   {
     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -1787,25 +1787,60 @@
       </method>
 
       <method name="onDrop">
         <parameter name="aEvent"/>
         <parameter name="aXferData"/>
         <parameter name="aDragSession"/>
         <body>
           <![CDATA[
-            if (aDragSession.sourceNode && aDragSession.sourceNode.parentNode == this.mTabContainer) {
+#ifndef XP_MACOSX
+            var accelKeyPressed = aEvent.ctrlKey;
+#else
+            var accelKeyPressed = aEvent.metaKey;
+#endif
+            var draggedTab;
+            if (aDragSession.sourceNode && aDragSession.sourceNode.localName == "tab" &&
+                (aDragSession.sourceNode.parentNode == this.mTabContainer ||
+                 aDragSession.sourceNode.ownerDocument.defaultView instanceof ChromeWindow &&
+                 aDragSession.sourceNode.ownerDocument.documentElement.getAttribute("windowtype") == "navigator:browser"))
+              draggedTab = aDragSession.sourceNode;
+            if (draggedTab && (accelKeyPressed || draggedTab.parentNode == this.mTabContainer)) {
               var newIndex = this.getNewIndex(aEvent);
-              var oldIndex = aDragSession.sourceNode._tPos;
-
-              if (newIndex > oldIndex)
-                newIndex--;
-              if (newIndex != oldIndex)
-                this.moveTabTo(this.mTabs[oldIndex], newIndex);
-            } else {
+              if (accelKeyPressed) {
+                // copy the dropped tab (wherever it's from)
+                var newTab = this.duplicateTab(draggedTab);
+                this.moveTabTo(newTab, newIndex);
+                if (draggedTab.parentNode != this.mTabContainer || aEvent.shiftKey)
+                  this.selectedTab = newTab;
+              }
+              else {
+                // move the dropped tab
+                if (newIndex > draggedTab._tPos)
+                  newIndex--;
+                if (newIndex != draggedTab._tPos)
+                  this.moveTabTo(draggedTab, newIndex);
+              }
+            }
+            else if (draggedTab) {
+              // copy the dropped tab and remove it from the other window
+              // (making it seem to have moved between windows)
+              newIndex = this.getNewIndex(aEvent);
+              newTab = this.duplicateTab(draggedTab);
+              this.moveTabTo(newTab, newIndex);
+              this.selectedTab = newTab;
+              
+              var remoteBrowser = draggedTab.ownerDocument.defaultView.getBrowser();
+              var tabCount = remoteBrowser.tabContainer.childNodes.length;
+              remoteBrowser.removeTab(draggedTab);
+              // close the other window if this was its last tab
+              if (tabCount == 1)
+                draggedTab.ownerDocument.defaultView.close();
+            }
+            else {
               var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
 
               // valid urls don't contain spaces ' '; if we have a space it isn't a valid url.
               // Also disallow dropping javascript: or data: urls--bail out
               if (!url || !url.length || url.indexOf(" ", 0) != -1 ||
                   /^\s*(javascript|data):/.test(url))
                 return;
 
@@ -1815,19 +1850,21 @@
               try {
                 bgLoad = this.mPrefs.getBoolPref("browser.tabs.loadInBackground");
               }
               catch (e) { }
 
               if (aEvent.shiftKey)
                 bgLoad = !bgLoad;
 
-              if (document.getBindingParent(aEvent.originalTarget).localName != "tab") {
+              if (document.getBindingParent(aEvent.originalTarget).localName != "tab" || accelKeyPressed) {
                 // We're adding a new tab.
-                this.loadOneTab(getShortcutOrURI(url), null, null, null, bgLoad, false);
+                newIndex = this.getNewIndex(aEvent);
+                newTab = this.loadOneTab(getShortcutOrURI(url), null, null, null, bgLoad, false);
+                this.moveTabTo(newTab, newIndex);
               }
               else {
                 // Load in an existing tab.
                 var tab = aEvent.target;
                 try {
                   this.getBrowserForTab(tab).loadURI(getShortcutOrURI(url));
                   if (this.mCurrentTab != tab && !bgLoad)
                     this.selectedTab = tab;
@@ -1991,16 +2028,33 @@
                 (direction == "rtl" && aEvent.keyCode == KeyEvent.DOM_VK_LEFT))
               this.moveTabForward();
             else
               this.moveTabBackward();
           ]]>
         </body>
       </method>
 
+      <method name="duplicateTab">
+        <parameter name="aTab"/><!-- can be from a different window as well -->
+        <body>
+          <![CDATA[
+            // try to have SessionStore duplicate the given tab
+            try {
+              var ss = Components.classes["@mozilla.org/browser/sessionstore;1"]
+                                 .getService(Components.interfaces.nsISessionStore);
+              return ss.duplicateTab(window, aTab);
+            } catch (ex) {
+              // fall back to basic URL copying
+              return this.loadOneTab(this.getBrowserForTab(aTab).currentURI.spec);
+            }
+          ]]>
+        </body>
+      </method>
+
       <!-- BEGIN FORWARDED BROWSER PROPERTIES.  IF YOU ADD A PROPERTY TO THE BROWSER ELEMENT
            MAKE SURE TO ADD IT HERE AS WELL. -->
       <property name="canGoBack"
                 onget="return this.mCurrentBrowser.canGoBack;"
                 readonly="true"/>
 
       <property name="canGoForward"
                 onget="return this.mCurrentBrowser.canGoForward;"
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -315,16 +315,22 @@
         </method>
       </implementation>
     </binding>
 
     <binding id="urlbar-rich-result-popup" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete-rich-result-popup">
       <implementation>
       <field name="_maxResults">0</field>
 
+      <field name="_bundle" readonly="true">
+        Cc["@mozilla.org/intl/stringbundle;1"].
+          getService(Ci.nsIStringBundleService).
+          createBundle("chrome://browser/locale/places/places.properties");
+      </field>
+
       <property name="maxResults" readonly="true">
         <getter>
           <![CDATA[
             if (!this._maxResults) {
               var prefService =
                 Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefBranch);
               this._maxResults = prefService.getIntPref("browser.urlbar.maxRichResults");
@@ -370,11 +376,30 @@
               controller.handleEscape();
               // respect the usual clicking subtleties
               openUILink(url, aEvent);
             }
           }
         ]]>
         </body>
       </method>
+
+      <method name="createResultLabel">
+        <parameter name="aTitle"/>
+        <parameter name="aUrl"/>
+        <parameter name="aType"/>
+        <body>
+          <![CDATA[
+            var label = aTitle + " " + aUrl;
+            // convert aType (ex: "ac-result-type-<aType>") to text to be spoke aloud
+            // by screen readers.  convert "tag" and "bookmark" to the localized versions,
+            // but don't do anything for "favicon" (the default)
+            if (aType != "favicon") {
+              label += " " + this._bundle.GetStringFromName(aType + "ResultLabel");
+            }
+            return label;
+          ]]>
+        </body>
+      </method>
+
     </implementation>
   </binding>
 </bindings>
--- a/browser/components/migration/content/migration.xul
+++ b/browser/components/migration/content/migration.xul
@@ -42,18 +42,17 @@
 <wizard id="migrationWizard"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
         windowtype="Browser:MigrationWizard"
         title="&migrationWizard.title;"
         onload="MigrationWizard.init()"
         onunload="MigrationWizard.uninit()"
         style="width: 40em;"
         buttons="accept,cancel"
-        branded="true"
-        xmlns:xhtml="http://www.w3.org/1999/xhtml">
+        branded="true">
 
   <script type="application/x-javascript" src="chrome://browser/content/migration/migration.js"/>
 
   <stringbundle id="bundle" src="chrome://browser/locale/migration/migration.properties"/>
   <stringbundle id="brandBundle" src="chrome://branding/locale/brand.properties"/>
 
   <wizardpage id="importSource" pageid="importSource" next="selectProfile"
               label="&importSource.title;"
@@ -126,18 +125,17 @@
   <wizardpage id="importItems" pageid="importItems" label="&importItems.title;"
               next="homePageImport"
               onpageshow="return MigrationWizard.onImportItemsPageShow();"
               onpagerewound="return MigrationWizard.onImportItemsPageRewound();"
               onpageadvanced="return MigrationWizard.onImportItemsPageAdvanced();"
               oncommand="MigrationWizard.onImportItemCommand();">
     <description control="dataSources">&importItems.label;</description>
 
-    <vbox id="dataSources" style="overflow: auto; -moz-appearance: listbox" align="left" flex="1"
-          xhtml:role="group"/>
+    <vbox id="dataSources" style="overflow: auto; -moz-appearance: listbox" align="left" flex="1" role="group"/>
   </wizardpage>
 
   <wizardpage id="homePageImport" pageid="homePageImport"
               next="migrating"
               onpageshow="return MigrationWizard.onHomePageMigrationPageShow();"
               onpageadvanced="return MigrationWizard.onHomePageMigrationPageAdvanced();">
 
     <description id="homePageImportDesc" control="homePageRadioGroup"/>
@@ -147,20 +145,20 @@
     </radiogroup>
   </wizardpage>
 
   <wizardpage id="migrating" pageid="migrating" label="&migrating.title;"
               next="done"
               onpageshow="MigrationWizard.onMigratingPageShow();">
     <description control="migratingItems">&migrating.label;</description>
 
-    <vbox id="migratingItems" style="overflow: auto;" align="left" xhtml:role="group"/>
+    <vbox id="migratingItems" style="overflow: auto;" align="left" role="group"/>
   </wizardpage>
 
   <wizardpage id="done" pageid="done" label="&done.title;"
               onpageshow="MigrationWizard.onDonePageShow();">
     <description control="doneItems">&done.label;</description>
 
-    <vbox id="doneItems" style="overflow: auto;" align="left" xhtml:role="group"/>
+    <vbox id="doneItems" style="overflow: auto;" align="left" role="group"/>
   </wizardpage>
 
 </wizard>
 
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -410,22 +410,22 @@ BrowserGlue.prototype = {
   {
     this.Sanitizer.sanitize(aParentWindow);
   },
 
   ensurePlacesDefaultQueriesInitialized: function() {
     // bail out if the folder is already created
     var prefBranch = Cc["@mozilla.org/preferences-service;1"].
                      getService(Ci.nsIPrefBranch);
-    var createdDefaultQueries = false;
+    var createdSmartBookmarks = false;
     try {
-      createdDefaultQueries = prefBranch.getBoolPref("browser.places.createdDefaultQueries");
+      createdSmartBookmarks = prefBranch.getBoolPref("browser.places.createdSmartBookmarks");
     } catch(ex) { }
 
-    if (createdDefaultQueries)
+    if (createdSmartBookmarks)
       return;
 
     var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
                 getService(Ci.nsINavBookmarksService);
 
     // XXXmano bug 405497: this should be batched even if we're not called from
     // the import service. However, calling runInBatchedMode from within a
     // RunBatched implementation hangs the browser.
@@ -436,118 +436,84 @@ BrowserGlue.prototype = {
 
       _uri: function(aSpec) {
         return Cc["@mozilla.org/network/io-service;1"].
                getService(Ci.nsIIOService).
                newURI(aSpec, null, null);
       },
 
       runBatched: function() {
-        var placesFolderTitle =
-          this._placesBundle.GetStringFromName("placesFolderTitle");
-        var recentlyCreatedBookmarksTitle =
-          this._placesBundle.GetStringFromName("recentlyCreatedBookmarksTitle");
-        var recentlyVisitedBookmarksTitle =
-          this._placesBundle.GetStringFromName("recentlyVisitedBookmarksTitle");
-        var mostVisitedBookmarksTitle =
-          this._placesBundle.GetStringFromName("mostVisitedBookmarksTitle");
-        var recentlyUsedTagsTitle =
-          this._placesBundle.GetStringFromName("recentlyUsedTagsTitle");
-        var mostUsedTagsTitle =
-          this._placesBundle.GetStringFromName("mostUsedTagsTitle");
-        var mostVisitedSitesTitle =
-          this._placesBundle.GetStringFromName("mostVisitedSitesTitle");
+        var smartBookmarksFolderTitle =
+          this._placesBundle.GetStringFromName("smartBookmarksFolderTitle");
+        var mostVisitedTitle =
+          this._placesBundle.GetStringFromName("mostVisitedTitle");
+        var recentlyBookmarkedTitle =
+          this._placesBundle.GetStringFromName("recentlyBookmarkedTitle");
+        var recentTagsTitle =
+          this._placesBundle.GetStringFromName("recentTagsTitle");
 
         var bookmarksMenuFolder = bmsvc.bookmarksMenuFolder;
         var unfiledBookmarksFolder = bmsvc.unfiledBookmarksFolder;
         var toolbarFolder = bmsvc.toolbarFolder;
         var tagsFolder = bmsvc.tagsFolder;
         var defaultIndex = bmsvc.DEFAULT_INDEX;
 
         // index = 0, make it the first folder
-        var placesFolder = bmsvc.createFolder(toolbarFolder, placesFolderTitle,
+        var placesFolder = bmsvc.createFolder(toolbarFolder, smartBookmarksFolderTitle,
                                               0);
 
         // XXX should this be a pref?  see bug #399268
         var maxResults = 10;
 
-        // exclude queries so that user created "saved searches" 
+        var mostVisitedItem = bmsvc.insertBookmark(placesFolder,
+          this._uri("place:queryType=" +
+              Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY +
+              "&sort=" +
+              Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING +
+              "&maxResults=" + maxResults),
+              defaultIndex, mostVisitedTitle);
+
+        // excludeQueries=1 so that user created "saved searches" 
         // and these queries (added automatically) are excluded
-        var recentlyCreatedBookmarksItem = bmsvc.insertBookmark(placesFolder,
+        var recentlyBookmarkedItem = bmsvc.insertBookmark(placesFolder,
           this._uri("place:folder=" + bookmarksMenuFolder + 
               "&folder=" + unfiledBookmarksFolder +
               "&folder=" + toolbarFolder +
               "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
               "&sort=" +
               Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING +
               "&excludeItemIfParentHasAnnotation=livemark%2FfeedURI" +
               "&maxResults=" + maxResults +
               "&excludeQueries=1"),
-              defaultIndex, recentlyCreatedBookmarksTitle);
-
-        var recentlyVisitedBookmarksItem = bmsvc.insertBookmark(placesFolder,
-          this._uri("place:folder=" + bookmarksMenuFolder + 
-              "&folder=" + unfiledBookmarksFolder +
-              "&folder=" + toolbarFolder +
-              "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
-              "&sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING +
-              "&excludeItemIfParentHasAnnotation=livemark%2FfeedURI" +
-              "&minVisits=1&maxResults=" + maxResults),
-              defaultIndex, recentlyVisitedBookmarksTitle);
+              defaultIndex, recentlyBookmarkedTitle);
 
-        var mostVisitedBookmarksItem = bmsvc.insertBookmark(placesFolder,
-          this._uri("place:folder=" + bookmarksMenuFolder + 
-              "&folder=" + unfiledBookmarksFolder +
-              "&folder=" + toolbarFolder +
-              "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
-              "&sort=" +
-              Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING +
-              "&excludeItemIfParentHasAnnotation=livemark%2FfeedURI" +
-              "&minVisits=1&maxResults=" + maxResults),
-              defaultIndex, mostVisitedBookmarksTitle);
+        var sep =  bmsvc.insertSeparator(placesFolder, defaultIndex);
 
-        var recentlyUsedTagsItem = bmsvc.insertBookmark(placesFolder,
+        var recentTagsItem = bmsvc.insertBookmark(placesFolder,
           this._uri("place:folder=" + tagsFolder +
               "&group=" + Ci.nsINavHistoryQueryOptions.GROUP_BY_FOLDER +
               "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
               "&applyOptionsToContainers=1" +
               "&sort=" +
               Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING +
               "&maxResults=" + maxResults),
-              defaultIndex, recentlyUsedTagsTitle);
-
-        var mostUsedTagsItem = bmsvc.insertBookmark(placesFolder,
-          this._uri("place:folder=" + tagsFolder +
-              "&group=" + Ci.nsINavHistoryQueryOptions.GROUP_BY_FOLDER +
-              "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
-              "&applyOptionsToContainers=1" +
-              "&sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_COUNT_DESCENDING +
-              "&maxResults=" + maxResults),
-              defaultIndex, mostUsedTagsTitle);
-
-        var mostVisitedSitesItem = bmsvc.insertBookmark(placesFolder,
-          this._uri("place:queryType=" +
-              Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY +
-              "&sort=" +
-              Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING +
-              "&maxResults=" + maxResults),
-              defaultIndex, mostVisitedSitesTitle);
+              defaultIndex, recentTagsTitle);
       }
     };
 
     try {
       callback.runBatched();
       // See XXX note above
       // bmsvc.runInBatchMode(callback, null);
     }
     catch(ex) {
       Components.utils.reportError(ex);
     }
     finally {
-      prefBranch.setBoolPref("browser.places.createdDefaultQueries", true);
+      prefBranch.setBoolPref("browser.places.createdSmartBookmarks", true);
       prefBranch.savePrefFile(null);
     }
   },
 
   // for XPCOM
   classDescription: "Firefox Browser Glue Service",
   classID:          Components.ID("{eab9012e-5f74-4cbc-b2b5-a590235513cc}"),
   contractID:       "@mozilla.org/browser/browserglue;1",
--- a/browser/components/places/content/advancedSearch.inc
+++ b/browser/components/places/content/advancedSearch.inc
@@ -148,18 +148,18 @@
               <menuitem value="months"
                         label="&advancedSearch.last_months.label;"/>
             </menupopup>
           </menulist>
 
         </hbox>              
         <button id="advancedSearch0Minus"
                 label="&advancedSearch.minus.label;"
-                class="small"
+                class="small advancedSearchMinus"
                 oncommand="PlacesQueryBuilder.removeRow(event.target.parentNode);"/>
         <button id="advancedSearch0Plus"
                 label="&advancedSearch.plus.label;"
-                class="small"
+                class="small advancedSearchPlus"
                 command="OrganizerCommand_search:moreCriteria"/>
       </row>
     </rows>
   </grid>
 </vbox>
--- a/browser/components/places/content/bookmarkProperties.js
+++ b/browser/components/places/content/bookmarkProperties.js
@@ -84,17 +84,17 @@
  *     - "feedURI"
  *     - "siteURI"
  *     - "folder picker" - hides both the tree and the menu.
  *
  * window.arguments[0].performed is set to true if any transaction has
  * been performed by the dialog.
  */
 
-const LAST_USED_ANNO = "bookmarkPropertiesDialog/lastUsed";
+const LAST_USED_ANNO = "bookmarkPropertiesDialog/folderLastUsed";
 const STATIC_TITLE_ANNO = "bookmarks/staticTitle";
 
 // This doesn't include "static" special folders (first two menu items)
 const MAX_FOLDER_ITEM_IN_MENU_LIST = 5;
 
 const BOOKMARK_ITEM = 0;
 const BOOKMARK_FOLDER = 1;
 const LIVEMARK_CONTAINER = 2;
@@ -108,27 +108,16 @@ var BookmarkPropertiesPanel = {
   __strings: null,
   get _strings() {
     if (!this.__strings) {
       this.__strings = document.getElementById("stringBundle");
     }
     return this.__strings;
   },
 
-  /**
-   * The Microsummary Service for displaying microsummaries.
-   */
-  __mss: null,
-  get _mss() {
-    if (!this.__mss)
-      this.__mss = Cc["@mozilla.org/microsummary/service;1"].
-                  getService(Ci.nsIMicrosummaryService);
-    return this.__mss;
-  },
-
   _action: null,
   _itemType: null,
   _folderId: null,
   _bookmarkId: -1,
   _bookmarkURI: null,
   _loadBookmarkInSidebar: false,
   _itemTitle: "",
   _itemDescription: "",
@@ -386,16 +375,25 @@ var BookmarkPropertiesPanel = {
     folderMenuItem.folderId = aFolderId;
     folderMenuItem.setAttribute("label", folderTitle);
     folderMenuItem.className = "menuitem-iconic folder-icon";
     aMenupopup.appendChild(folderMenuItem);
     return folderMenuItem;
   },
 
   _initFolderMenuList: function BPP__initFolderMenuList() {
+    // Build the static list
+    var bms = PlacesUtils.bookmarks;
+    var bmMenuItem = this._element("bookmarksRootItem");
+    bmMenuItem.label = bms.getItemTitle(PlacesUtils.bookmarksMenuFolderId);
+    bmMenuItem.folderId = PlacesUtils.bookmarksMenuFolderId;
+    var toolbarItem = this._element("toolbarFolderItem");
+    toolbarItem.label = bms.getItemTitle(PlacesUtils.toolbarFolderId);
+    toolbarItem.folderId = PlacesUtils.toolbarFolderId;
+
     // List of recently used folders:
     var annos = PlacesUtils.annotations;
     var folderIds = annos.getItemsWithAnnotation(LAST_USED_ANNO, { });
 
     // Hide the folders-separator if no folder is annotated as recently-used
     if (folderIds.length == 0) {
       this._element("foldersSeparator").hidden = true;
       return;
@@ -424,17 +422,17 @@ var BookmarkPropertiesPanel = {
 
     var numberOfItems = Math.min(MAX_FOLDER_ITEM_IN_MENU_LIST, folders.length);
     var menupopup = this._folderMenuList.menupopup;
     for (i=0; i < numberOfItems; i++) {
       this._appendFolderItemToMenupopup(menupopup, folders[i].folderId);
     }
 
     var defaultItem =
-      this._getFolderMenuItem(this._defaultInsertionPoint.itemId, true);
+      this._getFolderMenuItem(this._defaultInsertionPoint.itemId);
 
     // if we fail to get a menuitem for the default insertion point
     // use the Bookmarks root
     if (!defaultItem)
       defaultItem = this._element("bookmarksRootItem");
 
     this._folderMenuList.selectedItem = defaultItem;
   },
@@ -563,18 +561,19 @@ var BookmarkPropertiesPanel = {
     // Non-bookmark items always use the item-title itself
     if (this._itemType != BOOKMARK_ITEM || !this._bookmarkURI) {
       namePicker.selectedItem = userEnteredNameField;
       return;
     }
 
     var itemToSelect = userEnteredNameField;
     try {
-      this._microsummaries = this._mss.getMicrosummaries(this._bookmarkURI,
-                                                         this._bookmarkId);
+      this._microsummaries =
+        PlacesUtils.microsummaries.getMicrosummaries(this._bookmarkURI,
+                                                     this._bookmarkId);
     }
     catch(ex) {
       // getMicrosummaries will throw an exception if the page to which the URI
       // refers isn't HTML or XML (the only two content types the service knows
       // how to summarize).
       this._microsummaries = null;
     }
     if (this._microsummaries) {
@@ -586,17 +585,18 @@ var BookmarkPropertiesPanel = {
 
         var menupopup = namePicker.menupopup;
         while (enumerator.hasMoreElements()) {
           var microsummary = enumerator.getNext()
                                        .QueryInterface(Ci.nsIMicrosummary);
           var menuItem = this._createMicrosummaryMenuItem(microsummary);
 
           if (this._action == ACTION_EDIT &&
-              this._mss.isMicrosummary(this._bookmarkId, microsummary))
+              PlacesUtils.microsummaries
+                         .isMicrosummary(this._bookmarkId, microsummary))
             itemToSelect = menuItem;
 
           menupopup.appendChild(menuItem);
         }
       }
 
       this._microsummaries.addObserver(this);
     }
@@ -835,19 +835,21 @@ var BookmarkPropertiesPanel = {
       var namePicker = this._element("namePicker");
       var newMicrosummary = namePicker.selectedItem.microsummary;
 
       // Only add a microsummary update to the transaction if the
       // microsummary has actually changed, i.e. the user selected no
       // microsummary, but the bookmark previously had one, or the user
       // selected a microsummary which is not the one the bookmark previously
       // had.
-      if ((newMicrosummary == null && this._mss.hasMicrosummary(itemId)) ||
+      if ((newMicrosummary == null &&
+           PlacesUtils.microsummaries.hasMicrosummary(itemId)) ||
           (newMicrosummary != null &&
-           !this._mss.isMicrosummary(itemId, newMicrosummary))) {
+           !PlacesUtils.microsummaries
+                       .isMicrosummary(itemId, newMicrosummary))) {
         transactions.push(
           PlacesUtils.ptm.editBookmarkMicrosummary(itemId, newMicrosummary));
       }
 
       // load in sidebar
       var loadInSidebarChecked = this._element("loadInSidebarCheckbox").checked;
       if (loadInSidebarChecked != this._loadBookmarkInSidebar) {
         transactions.push(
@@ -924,26 +926,26 @@ var BookmarkPropertiesPanel = {
 
     var childTransactions = [];
     var microsummary = this._element("namePicker").selectedItem.microsummary;
     if (microsummary) {
       childTransactions.push(
         PlacesUtils.ptm.editBookmarkMicrosummary(-1, microsummary));
     }
 
+    if (this._postData) {
+      childTransactions.push(
+        PlacesUtils.ptm.editBookmarkPostData(-1, this._postData));
+    }
+
     var transactions = [PlacesUtils.ptm.createItem(uri, aContainer, aIndex,
                                                    title, keyword,
                                                    annotations,
                                                    childTransactions)];
 
-    if (this._postData) {
-      transactions.push(
-        PlacesUtils.ptm.editURIPostData(uri, this._postData));
-    }
-
     return PlacesUtils.ptm.aggregateTransactions(this._getDialogTitle(), transactions);
   },
 
   /**
    * Returns a childItems-transactions array representing the URIList with
    * which the dialog has been opened.
    */
   _getTransactionsForURIList: function BPP__getTransactionsForURIList() {
@@ -1002,18 +1004,21 @@ var BookmarkPropertiesPanel = {
     var createTxn;
     if (this._itemType == BOOKMARK_FOLDER)
       createTxn = this._getCreateNewFolderTransaction(container, index);
     else if (this._itemType == LIVEMARK_CONTAINER)
       createTxn = this._getCreateNewLivemarkTransaction(container, index);
     else // BOOKMARK_ITEM
       createTxn = this._getCreateNewBookmarkTransaction(container, index);
 
-    // Mark the containing folder as recently-used
-    this._markFolderAsRecentlyUsed(container);
+    // Mark the containing folder as recently-used if it isn't in the static
+    // list
+    if (container != PlacesUtils.toolbarFolderId &&
+        container != PlacesUtils.bookmarksMenuFolderId)
+      this._markFolderAsRecentlyUsed(container);
 
     // perfrom our transaction do via the transaction manager passed by the
     // opener so it can be undone.
     window.arguments[0].performed = true;
     PlacesUtils.ptm.doTransaction(createTxn);
   },
 
   onNamePickerInput: function BPP_onNamePickerInput() {
@@ -1053,58 +1058,39 @@ var BookmarkPropertiesPanel = {
       this._folderTree.focus();
 
       resizeTo(window.outerWidth, window.outerHeight + this._folderTreeHeight);
     }
   },
 
   _getFolderIdFromMenuList:
   function BPP__getFolderIdFromMenuList() {
-    var selectedItem = this._folderMenuList.selectedItem
-    switch (selectedItem.id) {
-      case "bookmarksRootItem":
-        return PlacesUtils.bookmarksMenuFolderId;
-      case "toolbarFolderItem":
-        return PlacesUtils.toolbarFolderId;
-    }
-
+    var selectedItem = this._folderMenuList.selectedItem;
     NS_ASSERT("folderId" in selectedItem,
               "Invalid menuitem in the folders-menulist");
     return selectedItem.folderId;
   },
 
   /**
    * Get the corresponding menu-item in the folder-menu-list for a bookmarks
    * folder if such an item exists. Otherwise, this creates a menu-item for the
    * folder. If the items-count limit (see MAX_FOLDERS_IN_MENU_LIST) is reached,
    * the new item replaces the last menu-item.
    * @param aFolderId
-   *        The identifier of the bookmarks folder
-   * @param aCheckStaticFolderItems
-   *        whether or not to also treat the static items at the top of
-   *        menu-list. Note dynamic items get precedence even if this is set to
-   *        true.
+   *        The identifier of the bookmarks folder.
    */
   _getFolderMenuItem:
-  function BPP__getFolderMenuItem(aFolderId, aCheckStaticFolderItems) {
+  function BPP__getFolderMenuItem(aFolderId) {
     var menupopup = this._folderMenuList.menupopup;
 
-    // 0: Bookmarks root, 1: toolbar folder, 2: separator
-    for (var i=3; i < menupopup.childNodes.length; i++) {
+    for (var i=0; i < menupopup.childNodes.length; i++) {
       if (menupopup.childNodes[i].folderId == aFolderId)
         return menupopup.childNodes[i];
     }
 
-    if (aCheckStaticFolderItems) {
-      if (aFolderId == PlacesUtils.bookmarksMenuFolderId)
-        return this._element("bookmarksRootItem")
-      if (aFolderId == PlacesUtils.toolbarFolderId)
-        return this._element("toolbarFolderItem")
-    }
-
     // 2 special folders + separator + folder-items-count limit
     if (menupopup.childNodes.length == 3 + MAX_FOLDER_ITEM_IN_MENU_LIST)
       menupopup.removeChild(menupopup.lastChild);
 
     return this._appendFolderItemToMenupopup(menupopup, aFolderId);
   },
 
   onMenuListFolderSelect: function BPP_onMenuListFolderSelect(aEvent) {
@@ -1124,17 +1110,17 @@ var BookmarkPropertiesPanel = {
     // already selected
     var oldSelectedItem = this._folderMenuList.selectedItem;
     if ((oldSelectedItem.id == "toolbarFolderItem" &&
          folderId == PlacesUtils.toolbarFolderId) ||
         (oldSelectedItem.id == "bookmarksRootItem" &&
          folderId == PlacesUtils.bookmarksMenuFolderId))
       return;
 
-    var folderItem = this._getFolderMenuItem(folderId, false);
+    var folderItem = this._getFolderMenuItem(folderId);
     this._folderMenuList.selectedItem = folderItem;
   },
 
   _markFolderAsRecentlyUsed:
   function BPP__markFolderAsRecentlyUsed(aFolderId) {
     // We'll figure out when/if to expire the annotation if it turns out
     // we keep this recently-used-folders implementation
     PlacesUtils.annotations
--- a/browser/components/places/content/bookmarkProperties.xul
+++ b/browser/components/places/content/bookmarkProperties.xul
@@ -128,20 +128,18 @@
         <label value="&bookmarks.createIn.label;" accesskey="&bookmarks.createIn.accesskey;"
                control="folderMenuList"/>
         <menulist id="folderMenuList"
                   class="folder-icon"
                   oncommand="BookmarkPropertiesPanel.onMenuListFolderSelect();">
           <menupopup>
             <!-- Static item for special folders -->
             <menuitem id="bookmarksRootItem"
-                      label="&bookmarks.bookmarksFolderItem.label;"
                       class="menuitem-iconic folder-icon"/>
             <menuitem id="toolbarFolderItem"
-                      label="&bookmarks.toolbarFolderItem.label;"
                       class="menuitem-iconic folder-icon"/>
             <menuseparator id="foldersSeparator" hidden="true"/>
           </menupopup>
         </menulist>
         <button id="expander"
                 class="down"
                 tooltiptext="&bookmarks.expanderDown.tooltip;"
                 tooltiptextdown="&bookmarks.expanderDown.tooltip;"
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -273,25 +273,28 @@ PlacesController.prototype = {
    */
   _hasRemovableSelection: function PC__hasRemovableSelection(aIsMoveCommand) {
     if (!this._view.hasSelection)
       return false;
 
     var nodes = this._view.getSelectionNodes();
     var root = this._view.getResultNode();
 
-    var btFolderId = PlacesUtils.toolbarFolderId;
     for (var i = 0; i < nodes.length; ++i) {
-      // Disallow removing the view's root node 
+      // Disallow removing the view's root node
       if (nodes[i] == root)
         return false;
 
-      // Disallow removing the toolbar folder
+      // Disallow removing the toolbar, menu and unfiled-bookmarks folders
+      var nodeItemId = nodes[i].itemId;
       if (!aIsMoveCommand &&
-          PlacesUtils.nodeIsFolder(nodes[i]) && nodes[i].itemId == btFolderId)
+           PlacesUtils.nodeIsFolder(nodes[i]) &&
+           (nodeItemId == PlacesUtils.toolbarFolderId ||
+            nodeItemId == PlacesUtils.unfiledBookmarksFolderId ||
+            nodeItemId == PlacesUtils.bookmarksMenuFolderId))
         return false;
 
       // We don't call nodeIsReadOnly here, because nodeIsReadOnly means that
       // a node has children that cannot be edited, reordered or removed. Here,
       // we don't care if a node's children can't be reordered or edited, just
       // that they're removable. All history results have removable children
       // (based on the principle that any URL in the history table should be
       // removable), but some special bookmark folders may have non-removable
--- a/browser/components/places/content/editBookmarkOverlay.js
+++ b/browser/components/places/content/editBookmarkOverlay.js
@@ -30,39 +30,29 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-const LAST_USED_ANNO = "bookmarkPropertiesDialog/lastUsed";
+const LAST_USED_ANNO = "bookmarkPropertiesDialog/folderLastUsed";
 const STATIC_TITLE_ANNO = "bookmarks/staticTitle";
 const MAX_FOLDER_ITEM_IN_MENU_LIST = 5;
 
 var gEditItemOverlay = {
-  /**
-   * The Microsummary Service for displaying microsummaries.
-   */
-  __mss: null,
-  get _mss() {
-    if (!this.__mss)
-      this.__mss = Cc["@mozilla.org/microsummary/service;1"].
-                  getService(Ci.nsIMicrosummaryService);
-    return this.__mss;
-  },
-
   _uri: null,
   _itemId: -1,
   _itemType: -1,
   _readOnly: false,
   _microsummaries: null,
   _hiddenRows: [],
   _observersAdded: false,
+  _staticFoldersListBuilt: false,
 
   get itemId() {
     return this._itemId;
   },
 
   /**
    * Determines the initial data for the item edited or added by this dialog
    */
@@ -205,24 +195,27 @@ var gEditItemOverlay = {
     while (menupopup.childNodes.length > 4)
       menupopup.removeChild(menupopup.lastChild);
 
     const bms = PlacesUtils.bookmarks;
     const annos = PlacesUtils.annotations;
 
     // Build the static list
     var unfiledItem = this._element("unfiledRootItem");
-    unfiledItem.label = bms.getItemTitle(PlacesUtils.unfiledBookmarksFolderId);
-    // only show "Unfiled Bookmarks" if the url isn't bookmarked somewhere else
-    unfiledItem.hidden = aSelectedFolder != PlacesUtils.unfiledBookmarksFolderId;
-
-    this._element("bmRootItem").label =
-      bms.getItemTitle(PlacesUtils.bookmarksMenuFolderId);
-    this._element("toolbarFolderItem").label =
-      bms.getItemTitle(PlacesUtils.toolbarFolderId);
+    if (!this._staticFoldersListBuilt) {
+      unfiledItem.label = bms.getItemTitle(PlacesUtils.unfiledBookmarksFolderId);
+      unfiledItem.folderId = PlacesUtils.unfiledBookmarksFolderId;
+      var bmMenuItem = this._element("bmRootItem");
+      bmMenuItem.label = bms.getItemTitle(PlacesUtils.bookmarksMenuFolderId);
+      bmMenuItem.folderId = PlacesUtils.bookmarksMenuFolderId;
+      var toolbarItem = this._element("toolbarFolderItem");
+      toolbarItem.label = bms.getItemTitle(PlacesUtils.toolbarFolderId);
+      toolbarItem.folderId = PlacesUtils.toolbarFolderId;
+      this._staticFoldersListBuilt = true;
+    }
 
     // List of recently used folders:
     var folderIds = annos.getItemsWithAnnotation(LAST_USED_ANNO, { });
 
     /**
      * The value of the LAST_USED_ANNO annotation is the time (in the form of
      * Date.getTime) at which the folder has been last used.
      *
@@ -243,17 +236,17 @@ var gEditItemOverlay = {
       return 0;
     });
 
     var numberOfItems = Math.min(MAX_FOLDER_ITEM_IN_MENU_LIST, folders.length);
     for (i=0; i < numberOfItems; i++) {
       this._appendFolderItemToMenupopup(menupopup, folders[i].folderId);
     }
 
-    var defaultItem = this._getFolderMenuItem(aSelectedFolder, true);
+    var defaultItem = this._getFolderMenuItem(aSelectedFolder);
     this._folderMenuList.selectedItem = defaultItem;
 
     // Hide the folders-separator if no folder is annotated as recently-used
     this._element("foldersSeparator").hidden = (menupopup.childNodes.length <= 4);
     this._folderMenuList.disabled = this._readOnly;
   },
 
   QueryInterface: function EIO_QueryInterface(aIID) {
@@ -322,17 +315,18 @@ var gEditItemOverlay = {
       this._microsummaries.removeObserver(this);
       this._microsummaries = null;
     }
 
     var itemToSelect = userEnteredNameField;
     try {
       if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK &&
           !this._readOnly)
-        this._microsummaries = this._mss.getMicrosummaries(this._uri, -1);
+        this._microsummaries = PlacesUtils.microsummaries
+                                          .getMicrosummaries(this._uri, -1);
     }
     catch(ex) {
       // getMicrosummaries will throw an exception in at least two cases:
       // 1. the bookmarked URI contains a scheme that the service won't
       //    download for security reasons (currently it only handles http,
       //    https, and file);
       // 2. the page to which the URI refers isn't HTML or XML (the only two
       //    content types the service knows how to summarize).
@@ -343,18 +337,18 @@ var gEditItemOverlay = {
 
       if (enumerator.hasMoreElements()) {
         // Show the drop marker if there are microsummaries
         droppable = true;
         while (enumerator.hasMoreElements()) {
           var microsummary = enumerator.getNext()
                                        .QueryInterface(Ci.nsIMicrosummary);
           var menuItem = this._createMicrosummaryMenuItem(microsummary);
-          if (this._mss.isMicrosummary(this._itemId, microsummary))
-            itemToSelect = menuItem;
+          if (PlacesUtils.microsummaries
+                         .isMicrosummary(this._itemId, microsummary))
 
           menupopup.appendChild(menuItem);
         }
       }
 
       this._microsummaries.addObserver(this);
     }
 
@@ -484,19 +478,21 @@ var gEditItemOverlay = {
     }
 
     var newMicrosummary = namePicker.selectedItem.microsummary;
 
     // Only add a microsummary update to the transaction if the microsummary
     // has actually changed, i.e. the user selected no microsummary, but the
     // bookmark previously had one, or the user selected a microsummary which
     // is not the one the bookmark previously had
-    if ((newMicrosummary == null && this._mss.hasMicrosummary(this._itemId)) ||
+    if ((newMicrosummary == null &&
+         PlacesUtils.microsummaries.hasMicrosummary(this._itemId)) ||
         (newMicrosummary != null &&
-         !this._mss.isMicrosummary(this._itemId, newMicrosummary))) {
+         !PlacesUtils.microsummaries
+                     .isMicrosummary(this._itemId, newMicrosummary))) {
       txns.push(ptm.editBookmarkMicrosummary(this._itemId, newMicrosummary));
     }
 
     var aggregate = ptm.aggregateTransactions("Edit Item Title", txns);
     ptm.doTransaction(aggregate);
   },
 
   onDescriptionFieldBlur: function EIO_onDescriptionFieldInput() {
@@ -588,80 +584,59 @@ var gEditItemOverlay = {
       var currentFolder = this._getFolderIdFromMenuList();
       this._folderTree.selectItems([currentFolder]);
       this._folderTree.focus();
     }
   },
 
   _getFolderIdFromMenuList:
   function EIO__getFolderIdFromMenuList() {
-    var selectedItem = this._folderMenuList.selectedItem
-    switch (selectedItem.id) {
-      case "editBMPanel_unfiledRootItem":
-        return PlacesUtils.unfiledBookmarksFolderId;
-      case "editBMPanel_bmRootItem":
-        return PlacesUtils.bookmarksMenuFolderId;
-      case "editBMPanel_toolbarFolderItem":
-        return PlacesUtils.toolbarFolderId;
-    }
-
+    var selectedItem = this._folderMenuList.selectedItem;
     NS_ASSERT("folderId" in selectedItem,
               "Invalid menuitem in the folders-menulist");
     return selectedItem.folderId;
   },
 
   /**
    * Get the corresponding menu-item in the folder-menu-list for a bookmarks
    * folder if such an item exists. Otherwise, this creates a menu-item for the
    * folder. If the items-count limit (see MAX_FOLDERS_IN_MENU_LIST) is reached,
    * the new item replaces the last menu-item.
    * @param aFolderId
-   *        The identifier of the bookmarks folder
-   * @param aCheckStaticFolderItems
-   *        whether or not to also treat the static items at the top of
-   *        menu-list. Note dynamic items get precedence even if this is set to
-   *        true.
+   *        The identifier of the bookmarks folder.
    */
   _getFolderMenuItem:
-  function EIO__getFolderMenuItem(aFolderId, aCheckStaticFolderItems) {
+  function EIO__getFolderMenuItem(aFolderId) {
     var menupopup = this._folderMenuList.menupopup;
 
-    // 0: All Bookmarks, 1: Bookmarks root, 2: toolbar folder, 3: separator
-    for (var i=4;  i < menupopup.childNodes.length; i++) {
+    for (var i=0;  i < menupopup.childNodes.length; i++) {
       if (menupopup.childNodes[i].folderId == aFolderId)
         return menupopup.childNodes[i];
     }
 
-    if (aCheckStaticFolderItems) {
-      if (aFolderId == PlacesUtils.unfiledBookmarksFolderId)
-        return this._element("unfiledRootItem");
-      if (aFolderId == PlacesUtils.bookmarksMenuFolderId)
-        return this._element("bmRootItem");
-      if (aFolderId == PlacesUtils.toolbarFolderId)
-        return this._element("toolbarFolderItem");
-    }
-
     // 3 special folders + separator + folder-items-count limit
     if (menupopup.childNodes.length == 4 + MAX_FOLDER_ITEM_IN_MENU_LIST)
       menupopup.removeChild(menupopup.lastChild);
 
     return this._appendFolderItemToMenupopup(menupopup, aFolderId);
   },
 
   onFolderMenuListCommand: function EIO_onFolderMenuListCommand(aEvent) {
     var container = this._getFolderIdFromMenuList();
 
     // Move the item
     if (PlacesUtils.bookmarks.getFolderIdForItem(this._itemId) != container) {
       var txn = PlacesUtils.ptm.moveItem(this._itemId, container, -1);
       PlacesUtils.ptm.doTransaction(txn);
 
-      // Mark the containing folder as recently-used if it isn't the
-      // "All Bookmarks" root
-      if (container != PlacesUtils.unfiledBookmarksFolderId)
+      // Mark the containing folder as recently-used if it isn't in the
+      // static list
+      if (container != PlacesUtils.unfiledBookmarksFolderId &&
+          container != PlacesUtils.toolbarFolderId &&
+          container != PlacesUtils.bookmarksMenuFolderId)
         this._markFolderAsRecentlyUsed(container);
     }
 
     // Update folder-tree selection
     if (!this._folderTree.collapsed) {
       var selectedNode = this._folderTree.selectedNode;
       if (!selectedNode || selectedNode.itemId != container)
         this._folderTree.selectItems([container]);
@@ -672,17 +647,17 @@ var gEditItemOverlay = {
     var selectedNode = this._folderTree.selectedNode;
     if (!selectedNode)
       return;
 
     var folderId = selectedNode.itemId;
     if (this._getFolderIdFromMenuList() == folderId)
       return;
 
-    var folderItem = this._getFolderMenuItem(folderId, false);
+    var folderItem = this._getFolderMenuItem(folderId);
     this._folderMenuList.selectedItem = folderItem;
     folderItem.doCommand();
   },
 
   _markFolderAsRecentlyUsed:
   function EIO__markFolderAsRecentlyUsed(aFolderId) {
     // We'll figure out when/if to expire the annotation if it turns out
     // we keep this recently-used-folders implementation
@@ -838,17 +813,17 @@ var gEditItemOverlay = {
   },
 
   onItemMoved: function EIO_onItemMoved(aItemId, aOldParent, aOldIndex,
                                         aNewParent, aNewIndex) {
     if (aItemId != this._itemId ||
         aNewParent == this._getFolderIdFromMenuList())
       return;
 
-    var folderItem = this._getFolderMenuItem(aNewParent, false);
+    var folderItem = this._getFolderMenuItem(aNewParent);
 
     // just setting selectItem _does not_ trigger oncommand, so we don't
     // recurse
     this._folderMenuList.selectedItem = folderItem;
   },
 
   onBeginUpdateBatch: function() { },
   onEndUpdateBatch: function() { },
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -59,34 +59,38 @@ var PlacesOrganizer = {
     this._content = document.getElementById("placeContent");
     this._initFolderTree();
 
     var leftPaneSelection = "AllBookmarks"; // default to all-bookmarks
     if ("arguments" in window && window.arguments.length > 0)
       leftPaneSelection = window.arguments[0];
 
     this.selectLeftPaneQuery(leftPaneSelection);
+    // clear the back-stack
+    this._backHistory.splice(0);
+    document.getElementById("OrganizerCommand:Back").setAttribute("disabled", true);
 
     var view = this._content.treeBoxObject.view;
     if (view.rowCount > 0)
       view.selection.select(0);
 
     this._content.focus();
 
     // Set up the search UI.
     PlacesSearchBox.init();
 
     // Set up the advanced query builder UI
     PlacesQueryBuilder.init();
 
 #ifdef XP_MACOSX
-    // 1. Make Edit->Find focus the organizer search field
-    var findCommand = document.getElementById("cmd_find");
-    findCommand.setAttribute("oncommand", "PlacesSearchBox.findCurrent();");
-    findCommand.removeAttribute("disabled");
+    // 1. Map Edit->Find command to the organizer's command
+    var findMenuItem = document.getElementById("menu_find");
+    findMenuItem.setAttribute("command", "OrganizerCommand_find:current");
+    var findKey = document.getElementById("key_find");
+    findKey.setAttribute("command", "OrganizerCommand_find:current");
 
     // 2. Disable some keybindings from browser.xul
     var elements = ["cmd_handleBackspace", "cmd_handleShiftBackspace"];
     for (var i=0; i < elements.length; i++) {
       document.getElementById(elements[i]).setAttribute("disabled", "true");
     }
 #endif
   },
@@ -95,25 +99,31 @@ var PlacesOrganizer = {
   },
 
   _location: null,
   get location() {
     return this._location;
   },
 
   set location(aLocation) {
-    LOG("Node URI: " + aLocation);
-
-    if (!aLocation)
+    if (!aLocation || this._location == aLocation)
       return aLocation;
 
-    if (this.location)
+    if (this.location) {
       this._backHistory.unshift(this.location);
+      this._forwardHistory.splice(0);
+    }
 
-    this._content.place = this._location = aLocation;
+    this._location = aLocation;
+    this._places.selectPlaceURI(aLocation);
+
+    if (!this._places.hasSelection) {
+      // If no node was found for the given place: uri, just load it directly
+      this._content.place = aLocation;
+    }
     this.onContentTreeSelect();
 
     // update navigation commands
     if (this._backHistory.length == 0)
       document.getElementById("OrganizerCommand:Back").setAttribute("disabled", true);
     else
       document.getElementById("OrganizerCommand:Back").removeAttribute("disabled");
     if (this._forwardHistory.length == 0)
@@ -121,50 +131,55 @@ var PlacesOrganizer = {
     else
       document.getElementById("OrganizerCommand:Forward").removeAttribute("disabled");
 
     return aLocation;
   },
 
   _backHistory: [],
   _forwardHistory: [],
+
   back: function PO_back() {
     this._forwardHistory.unshift(this.location);
     var historyEntry = this._backHistory.shift();
     this._location = null;
     this.location = historyEntry;
   },
   forward: function PO_forward() {
+    this._backHistory.unshift(this.location);
     var historyEntry = this._forwardHistory.shift();
+    this._location = null;
     this.location = historyEntry;
   },
 
   /**
    * Called when a place folder is selected in the left pane.
    * @param   resetSearchBox
    *          true if the search box should also be reset, false if it should
    *          be left alone.
    */
   onPlaceSelected: function PO_onPlaceSelected(resetSearchBox) {
+    // Don't change the right-hand pane contents when there's no selection
     if (!this._places.hasSelection)
       return;
 
-    var node = asQuery(this._places.selectedNode);
-
-    var queries = node.getQueries({});
+    var node = this._places.selectedNode;
+    var queries = asQuery(node).getQueries({});
 
     // Items are only excluded on the left pane
     var options = node.queryOptions.clone();
     options.excludeItems = false;
+    var placeURI = PlacesUtils.history.queriesToQueryString(queries, queries.length, options);
 
-    // clear forward history
-    this._forwardHistory.splice(0);
+    // update the right-pane contents
+    this._content.place = placeURI;
 
-    // update location
-    this.location = PlacesUtils.history.queriesToQueryString(queries, queries.length, options);
+    // This just updates the back/forward buttons, it doesn't call us back
+    // because node.uri is our current selection.
+    this.location = node.uri;
 
     // Make sure the search UI is hidden.
     PlacesSearchBox.hideSearchUI();
     if (resetSearchBox) {
       var searchFilter = document.getElementById("searchFilter");
       searchFilter.reset();
     }
 
--- a/browser/components/places/content/places.xul
+++ b/browser/components/places/content/places.xul
@@ -60,17 +60,17 @@
 <!DOCTYPE window [
 <!ENTITY % placesDTD SYSTEM "chrome://browser/locale/places/places.dtd">
 %placesDTD;
 <!ENTITY % editMenuOverlayDTD SYSTEM "chrome://global/locale/editMenuOverlay.dtd">
 %editMenuOverlayDTD;
 ]>
 
 <window id="places"
-        title="&places.organizer.title;" 
+        title="&places.library.title;" 
         windowtype="Places:Organizer" 
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
         xmlns:html="http://www.w3.org/1999/xhtml"
         onload="PlacesOrganizer.init();"
         onunload="PlacesOrganizer.destroy();"
         width="700" height="500" screenX="10" screenY="10"
         persist="width height screenX screenY sizemode">
 
--- a/browser/components/places/content/tree.xml
+++ b/browser/components/places/content/tree.xml
@@ -175,97 +175,105 @@
       <!-- 
         Causes a particular node represented by the specified placeURI to be
         selected in the tree. All containers above the node in the hierarchy
         will be opened, so that the node is visible. 
         -->
       <method name="selectPlaceURI">
         <parameter name="placeURI"/>
         <body><![CDATA[
+          // Do nothing if a node matching the given uri is already selected
+          if (this.hasSelection && this.selectedNode.uri == placeURI)
+            return;
+
           function findNode(container, placeURI, nodesURIChecked) {
             var containerURI = container.uri;
             if (containerURI == placeURI)
               return container;
             if (nodesURIChecked.indexOf(containerURI) != -1)
               return null;
 
             // never check the contents of the same query
             nodesURIChecked.push(containerURI);
 
-            container.containerOpen = true;
+            var wasOpen = container.containerOpen;
+            if (!wasOpen)
+              container.containerOpen = true;
             for (var i = 0; i < container.childCount; ++i) {
               var child = container.getChild(i);
               var childURI = child.uri;
               if (childURI == placeURI)
                 return child;
               else if (PlacesUtils.nodeIsContainer(child)) {
                 var nested = findNode(asContainer(child), placeURI, nodesURIChecked);
                 if (nested)
                   return nested;
               }
             }
-            container.containerOpen = false;
+
+            if (!wasOpen)
+              container.containerOpen = false;
 
             return null;
           }
-          
-          var container = this._getRootNode();
+
+          var container = this.getResultNode();
           NS_ASSERT(container, "No result, cannot select place URI!");
           if (!container)
             return;
 
           var child = findNode(container, placeURI, []);
-          container.containerOpen = true;
           if (child)
             this.selectNode(child);
           else {
-            // If the specified child could not be located, just select the first
-            // item in the list. 
-            if (this.view.rowCount)
-              this.view.selection.select(0);
+            // If the specified child could not be located, clear the selection
+            var selection = this.view.selection;
+            selection.clearSelection();
           }
         ]]></body>
       </method>
-      
+
       <!-- 
         Causes a particular node to be selected in the tree, resulting in all 
         containers above the node in the hierarchy to be opened, so that the
         node is visible. 
         -->
       <method name="selectNode">
         <parameter name="node"/>
         <body><![CDATA[ 
+          var view = this.getResultView();
+
           var parent = node.parent;
-          
-          // Build a list of all of the nodes that are the parent of this one 
-          // in the result. 
-          var parents = [];
-          var root = this._getRootNode();
-          while (parent && parent != root) {
-            parents.push(parent);
-            parent = parent.parent;
+          if (parent && !parent.containerOpen) {
+            // Build a list of all of the nodes that are the parent of this one 
+            // in the result. 
+            var parents = [];
+            var root = this.getResultNode();
+            while (parent && parent != root) {
+              parents.push(parent);
+              parent = parent.parent;
+            }
+
+            // Walk the list backwards (opening from the root of the hierarchy)
+            // opening each folder as we go.
+            for (var i = parents.length - 1; i >= 0; --i) {
+              var index = view.treeIndexForNode(parents[i]);
+              if (view.isContainer(index) && !view.isContainerOpen(index)) 
+                view.toggleOpenState(index);
+            }
+            // Select the specified node...
           }
-          
-          // Walk the list backwards (opening from the root of the hierarchy)
-          // opening each folder as we go.
-          var resultview = this.getResultView();
-          var view = this.view;
-          for (var i = parents.length - 1; i >= 0; --i) {
-            var index = resultview.treeIndexForNode(parents[i]);
-            if (view.isContainer(index) && !view.isContainerOpen(index)) 
-              view.toggleOpenState(index);
-          }
-          // Select the specified node...
-          index = resultview.treeIndexForNode(node);
+
+          var index = view.treeIndexForNode(node);
           view.selection.select(index);
           // ... and ensure it's visible, not scrolled off somewhere. 
           this.treeBoxObject.ensureRowIsVisible(index);
         ]]></body>
       </method>
-      
+
       <!-- nsIPlacesView -->
       <method name="getResult">
         <body><![CDATA[
           try {
             return this.view.QueryInterface(Ci.nsINavHistoryResultViewer).result;
           }
           catch (e) {
             return null;
--- a/browser/components/places/content/treeView.js
+++ b/browser/components/places/content/treeView.js
@@ -717,18 +717,18 @@ PlacesTreeView.prototype = {
   },
 
   containerOpened: function PTV_containerOpened(aItem) {
     this.invalidateContainer(aItem);
   },
 
   containerClosed: function PTV_containerClosed(aItem) {
     this.invalidateContainer(aItem);
-  },
-
+  },
+
   invalidateContainer: function PTV_invalidateContainer(aItem) {
     NS_ASSERT(this._result, "Got a notification but have no result!");
     if (!this._tree)
       return; // nothing to do, container is not visible
     var viewIndex = aItem.viewIndex;
     if (viewIndex >= this._visibleElements.length) {
       // be paranoid about visible indices since others can change it
       throw Cr.NS_ERROR_UNEXPECTED;
--- a/browser/components/places/content/utils.js
+++ b/browser/components/places/content/utils.js
@@ -45,17 +45,17 @@ function LOG(str) {
 var Ci = Components.interfaces;
 var Cc = Components.classes;
 var Cr = Components.results;
 
 Components.utils.import("resource://gre/modules/JSON.jsm");
 
 const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
 const DESCRIPTION_ANNO = "bookmarkProperties/description";
-const POST_DATA_ANNO = "URIProperties/POSTData";
+const POST_DATA_ANNO = "bookmarkProperties/POSTData";
 const LMANNO_FEEDURI = "livemark/feedURI";
 const LMANNO_SITEURI = "livemark/siteURI";
 const ORGANIZER_QUERY_ANNO = "PlacesOrganizer/OrganizerQuery";
 
 #ifdef XP_MACOSX
 // On Mac OSX, the transferable system converts "\r\n" to "\n\n", where we
 // really just want "\n".
 const NEWLINE= "\n";
@@ -1441,44 +1441,69 @@ var PlacesUtils = {
   },
 
   get unfiledBookmarksFolderId() {
     delete this.unfiledBookmarksFolderId;
     return this.unfiledBookmarksFolderId = this.bookmarks.unfiledBookmarksFolder;
   },
 
   /**
-   * Set the POST data associated with a URI, if any.
+   * Set the POST data associated with a bookmark, if any.
    * Used by POST keywords.
-   *   @param aURI
+   *   @param aBookmarkId
    *   @returns string of POST data
    */
-  setPostDataForURI: function PU_setPostDataForURI(aURI, aPostData) {
+  setPostDataForBookmark: function PU_setPostDataForBookmark(aBookmarkId, aPostData) {
     const annos = this.annotations;
     if (aPostData)
-      annos.setPageAnnotation(aURI, POST_DATA_ANNO, aPostData, 
+      annos.setItemAnnotation(aBookmarkId, POST_DATA_ANNO, aPostData, 
                               0, Ci.nsIAnnotationService.EXPIRE_NEVER);
-    else if (annos.pageHasAnnotation(aURI, POST_DATA_ANNO))
-      annos.removePageAnnotation(aURI, POST_DATA_ANNO);
+    else if (annos.itemHasAnnotation(aBookmarkId, POST_DATA_ANNO))
+      annos.removeItemAnnotation(aBookmarkId, POST_DATA_ANNO);
   },
 
   /**
    * Get the POST data associated with a bookmark, if any.
-   * @param aURI
-   * @returns string of POST data if set for aURI. null otherwise.
+   * @param aBookmarkId
+   * @returns string of POST data if set for aBookmarkId. null otherwise.
    */
-  getPostDataForURI: function PU_getPostDataForURI(aURI) {
+  getPostDataForBookmark: function PU_getPostDataForBookmark(aBookmarkId) {
     const annos = this.annotations;
-    if (annos.pageHasAnnotation(aURI, POST_DATA_ANNO))
-      return annos.getPageAnnotation(aURI, POST_DATA_ANNO);
+    if (annos.itemHasAnnotation(aBookmarkId, POST_DATA_ANNO))
+      return annos.getItemAnnotation(aBookmarkId, POST_DATA_ANNO);
 
     return null;
   },
 
   /**
+   * Get the URI (and any associated POST data) for a given keyword.
+   * @param aKeyword string keyword
+   * @returns an array containing a string URL and a string of POST data
+   */
+  getURLAndPostDataForKeyword: function PU_getURLAndPostDataForKeyword(aKeyword) {
+    var url = null, postdata = null;
+    try {
+      var uri = this.bookmarks.getURIForKeyword(aKeyword);
+      if (uri) {
+        url = uri.spec;
+        var bookmarks = this.bookmarks.getBookmarkIdsForURI(uri, {});
+        for (let i = 0; i < bookmarks.length; i++) {
+          var bookmark = bookmarks[i];
+          var kw = this.bookmarks.getKeywordForBookmark(bookmark);
+          if (kw == aKeyword) {
+            postdata = this.getPostDataForBookmark(bookmark);
+            break;
+          }
+        }
+      }
+    } catch(ex) {}
+    return [url, postdata];
+  },
+
+  /**
    * Retrieve the description of an item
    * @param aItemId
    *        item identifier
    * @returns the description of the given item, or an empty string if it is
    * not set.
    */
   getItemDescription: function PU_getItemDescription(aItemId) {
     if (this.annotations.itemHasAnnotation(aItemId, DESCRIPTION_ANNO))
@@ -1697,27 +1722,30 @@ var PlacesUtils = {
   // get the folder id for the organizer left-pane folder
   get leftPaneFolderId() {
     var prefs = Cc["@mozilla.org/preferences-service;1"].
                 getService(Ci.nsIPrefBranch2);
     var leftPaneRoot = -1;
     var allBookmarksId;
     try {
       leftPaneRoot = prefs.getIntPref("browser.places.leftPaneFolderId");
-      // Build the leftPaneQueries Map
-      delete this.leftPaneQueries;
-      this.leftPaneQueries = {};
-      var items = this.annotations.getItemsWithAnnotation(ORGANIZER_QUERY_ANNO, { });
-      for (var i=0; i < items.length; i++) {
-        var queryName = this.annotations
-                            .getItemAnnotation(items[i], ORGANIZER_QUERY_ANNO);
-        this.leftPaneQueries[queryName] = items[i];
+      // if the pref is set to -1 then we must create a new root because we have a new places.sqlite
+      if (leftPaneRoot != -1) {
+        // Build the leftPaneQueries Map
+        delete this.leftPaneQueries;
+        this.leftPaneQueries = {};
+        var items = this.annotations.getItemsWithAnnotation(ORGANIZER_QUERY_ANNO, { });
+        for (var i=0; i < items.length; i++) {
+          var queryName = this.annotations
+                              .getItemAnnotation(items[i], ORGANIZER_QUERY_ANNO);
+          this.leftPaneQueries[queryName] = items[i];
+        }
+        delete this.leftPaneFolderId;
+        return this.leftPaneFolderId = leftPaneRoot;
       }
-      delete this.leftPaneFolderId;
-      return this.leftPaneFolderId = leftPaneRoot;
     }
     catch (ex) { }
 
     var self = this;
     const EXPIRE_NEVER = this.annotations.EXPIRE_NEVER;
     var callback = {
       runBatched: function(aUserData) {
         delete self.leftPaneQueries;
--- a/browser/components/places/public/nsIPlacesTransactionsService.idl
+++ b/browser/components/places/public/nsIPlacesTransactionsService.idl
@@ -47,17 +47,17 @@ interface nsITransaction;
 
 /**
  * nsIPlacesTransactionService is a service designed to handle
  * nsITransactions that correspond to changes in Places. It is here as a
  * service so that we can keep the transactions around without holding onto
  * the global scope of a js window.
  */
 
-[scriptable, uuid(939bccbd-ecb1-4742-9c38-a33af91ec872)]
+[scriptable, uuid(89f61a91-c8f7-4abb-b880-895cb9852c35)]
 interface nsIPlacesTransactionsService : nsITransactionManager
 {
   /**
    * Transaction for performing several Places Transactions in a single batch. 
    * 
    * @param aName
    *        title of the aggregate transactions
    * @param aTransactions
@@ -232,30 +232,30 @@ interface nsIPlacesTransactionsService :
    * Transaction for editing a bookmark's keyword.
    *
    * @param id
    *        id of the bookmark to edit
    * @param newKeyword
    *        new keyword for the bookmark
    * @returns nsITransaction object
    */
-  nsITransaction editBookmarkKeyword(in long long id,
-                                           in AString newKeyword);
+  nsITransaction editBookmarkKeyword(in long long aItemId,
+                                     in AString aNewKeyword);
 
   /**
-   * Transaction for editing the post data associated with a URI
+   * Transaction for editing the post data associated with a bookmark.
    *
-   * @param aURI
-   *        uri to edit
+   * @param aItemId
+   *        id of the bookmark to edit
    * @param aPostData
    *        post data
    * @returns nsITransaction object
    */
-  nsITransaction editURIPostData(in nsIURI aURI,
-                                 in AString aPostData);
+  nsITransaction editBookmarkPostData(in long long aItemId,
+                                      in AString aPostData);
 
   /**
    * Transaction for editing a live bookmark's site URI.
    *
    * @param aFolderId
    *        id of the livemark
    * @param aURI
    *        new site uri
--- a/browser/components/places/src/nsPlacesImportExportService.cpp
+++ b/browser/components/places/src/nsPlacesImportExportService.cpp
@@ -122,17 +122,17 @@ static NS_DEFINE_CID(kParserCID, NS_PARS
 #define KEY_NAME_LOWER "name"
 #define KEY_MICSUM_GEN_URI_LOWER "micsum_gen_uri"
 #define KEY_DATE_ADDED_LOWER "add_date"
 #define KEY_LAST_MODIFIED_LOWER "last_modified"
 #define KEY_GENERATED_TITLE_LOWER "generated_title"
 
 #define LOAD_IN_SIDEBAR_ANNO NS_LITERAL_CSTRING("bookmarkProperties/loadInSidebar")
 #define DESCRIPTION_ANNO NS_LITERAL_CSTRING("bookmarkProperties/description")
-#define POST_DATA_ANNO NS_LITERAL_CSTRING("URIProperties/POSTData")
+#define POST_DATA_ANNO NS_LITERAL_CSTRING("bookmarkProperties/POSTData")
 #define LAST_CHARSET_ANNO NS_LITERAL_CSTRING("URIProperties/characterSet")
 #define STATIC_TITLE_ANNO NS_LITERAL_CSTRING("bookmarks/staticTitle")
 
 #define BOOKMARKS_MENU_ICON_URI "chrome://browser/skin/places/bookmarksMenu.png"
 
 // define to get debugging messages on console about import/export
 //#define DEBUG_IMPORT
 //#define DEBUG_EXPORT
@@ -945,17 +945,17 @@ BookmarkContentSink::HandleLinkBegin(con
   }
 
   // save the keyword, ignore errors
   if (!keyword.IsEmpty()) {
     mBookmarksService->SetKeywordForBookmark(frame.mPreviousId, keyword);
 
     // post data
     if (!postData.IsEmpty()) {
-      mAnnotationService->SetPageAnnotationString(frame.mPreviousLink, POST_DATA_ANNO,
+      mAnnotationService->SetItemAnnotationString(frame.mPreviousId, POST_DATA_ANNO,
                                                   postData, 0,
                                                   nsIAnnotationService::EXPIRE_NEVER);
     }
   }
 
   if (webPanel.LowerCaseEqualsLiteral("true")) {
     // set load-in-sidebar annotation for the bookmark
     mAnnotationService->SetItemAnnotationInt32(frame.mPreviousId, LOAD_IN_SIDEBAR_ANNO,
@@ -1850,22 +1850,22 @@ nsPlacesImportExportService::WriteItem(n
   }
 
   // post data
   nsCOMPtr<nsIURI> pageURI;
   rv = NS_NewURI(getter_AddRefs(pageURI), uri, nsnull);
   NS_ENSURE_SUCCESS(rv, rv);
   
   PRBool hasPostData;
-  rv = mAnnotationService->PageHasAnnotation(pageURI, POST_DATA_ANNO,
+  rv = mAnnotationService->ItemHasAnnotation(itemId, POST_DATA_ANNO,
                                              &hasPostData);
   NS_ENSURE_SUCCESS(rv, rv);
   if (hasPostData) {
     nsAutoString postData;
-    rv = mAnnotationService->GetPageAnnotationString(pageURI, POST_DATA_ANNO,
+    rv = mAnnotationService->GetItemAnnotationString(itemId, POST_DATA_ANNO,
                                                      postData);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = aOutput->Write(kPostDataAttribute, sizeof(kPostDataAttribute)-1, &dummy);
     NS_ENSURE_SUCCESS(rv, rv);
     char* escapedPostData = nsEscapeHTML(NS_ConvertUTF16toUTF8(postData).get());
     rv = aOutput->Write(escapedPostData, strlen(escapedPostData), &dummy);
     nsMemory::Free(escapedPostData);
     NS_ENSURE_SUCCESS(rv, rv);
--- a/browser/components/places/src/nsPlacesTransactionsService.js
+++ b/browser/components/places/src/nsPlacesTransactionsService.js
@@ -111,22 +111,22 @@ placesTransactionsService.prototype = {
   setLoadInSidebar: function placesSetLdInSdbar(aBookmarkId, aLoadInSidebar) {
     return new placesSetLoadInSidebarTransactions(aBookmarkId, aLoadInSidebar);
   },
 
   editItemDescription: function placesEditItmDesc(aItemId, aDescription) {
     return new placesEditItemDescriptionTransactions(aItemId, aDescription);
   },
 
-  editBookmarkKeyword: function placesEditBkmkKwd(id, newKeyword) {
-    return new placesEditBookmarkKeywordTransactions(id, newKeyword);
+  editBookmarkKeyword: function placesEditBkmkKwd(aItemId, newKeyword) {
+    return new placesEditBookmarkKeywordTransactions(aItemId, newKeyword);
   },
 
-  editURIPostData: function placesEditURIPdata(aURI, aPostData) {
-    return new placesEditURIPostDataTransactions(aURI, aPostData);
+  editBookmarkPostData: function placesEditBookmarkPostdata(aItemId, aPostData) {
+    return new placesEditBookmarkPostDataTransactions(aItemId, aPostData);
   },
 
   editLivemarkSiteURI: function placesEditLvmkSiteURI(folderId, uri) {
     return new placesEditLivemarkSiteURITransactions(folderId, uri);
   },
 
   editLivemarkFeedURI: function placesEditLvmkFeedURI(folderId, uri) {
     return new placesEditLivemarkFeedURITransactions(folderId, uri);
@@ -201,17 +201,17 @@ function placesBaseTransaction() {
 
 placesBaseTransaction.prototype = {
   // for child-transactions
   get wrappedJSObject() {
     return this;
   },
 
   // nsITransaction
-  redoTransaction: function PIT_redoTransaction() {
+  redoTransaction: function PBT_redoTransaction() {
     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
   },
 
   get isTransient() {
     return false;
   },
 
   merge: function mergeFunc(transaction) {
@@ -635,33 +635,33 @@ placesEditBookmarkKeywordTransactions.pr
     PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._newKeyword);
   },
 
   undoTransaction: function PEBKT_undoTransaction() {
     PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._oldKeyword);
   }
 };
 
-function placesEditURIPostDataTransactions(aURI, aPostData) {
-  this._uri = aURI;
+function placesEditBookmarkPostDataTransactions(aItemId, aPostData) {
+  this.id = aItemId;
   this._newPostData = aPostData;
   this._oldPostData = null;
   this.redoTransaction = this.doTransaction;
 }
 
-placesEditURIPostDataTransactions.prototype = {
+placesEditBookmarkPostDataTransactions.prototype = {
   __proto__: placesBaseTransaction.prototype,
 
   doTransaction: function PEUPDT_doTransaction() {
-    this._oldPostData = PlacesUtils.getPostDataForURI(this._uri);
-    PlacesUtils.setPostDataForURI(this._uri, this._newPostData);
+    this._oldPostData = PlacesUtils.getPostDataForBookmark(this._id);
+    PlacesUtils.setPostDataForBookmark(this.id, this._newPostData);
   },
 
   undoTransaction: function PEUPDT_undoTransaction() {
-    PlacesUtils.setPostDataForURI(this._uri, this._oldPostData);
+    PlacesUtils.setPostDataForBookmark(this.id, this._oldPostData);
   }
 };
 
 function placesEditLivemarkSiteURITransactions(folderId, uri) {
   this._folderId = folderId;
   this._newURI = uri;
   this._oldURI = null;
   this.redoTransaction = this.doTransaction;
--- a/browser/components/places/tests/unit/head_bookmarks.js
+++ b/browser/components/places/tests/unit/head_bookmarks.js
@@ -33,19 +33,19 @@
  * 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 ***** */
 
 const NS_APP_USER_PROFILE_50_DIR = "ProfD";
-const Ci = Components.interfaces;
-const Cc = Components.classes;
-const Cr = Components.results;
+var Ci = Components.interfaces;
+var Cc = Components.classes;
+var Cr = Components.results;
 
 function LOG(aMsg) {
   aMsg = ("*** PLACES TESTS: " + aMsg);
   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).
                                       logStringMessage(aMsg);
   print(aMsg);
 }
 
new file mode 100644
--- /dev/null
+++ b/browser/components/places/tests/unit/test_398914.js
@@ -0,0 +1,189 @@
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* ***** 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.com code.
+ *
+ * The Initial Developer of the Original Code is Mozilla Corp.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *  Dietrich Ayala <dietrich@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+version(170);
+
+var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
+             getService(Ci.mozIJSSubScriptLoader);
+loader.loadSubScript("chrome://global/content/debug.js");
+loader.loadSubScript("chrome://browser/content/places/utils.js");
+
+const bmsvc = PlacesUtils.bookmarks;
+const testFolderId = PlacesUtils.bookmarksMenuFolderId;
+
+// main
+function run_test() {
+  var testURI = uri("http://foo.com");
+
+  /*
+  1. Create a bookmark for a URI, with a keyword and post data.
+  2. Create a bookmark for the same URI, with a different keyword and different post data.
+  3. Confirm that our method for getting a URI+postdata retains bookmark affinity.
+  */
+  var bm1 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm1, "foo");
+  PlacesUtils.setPostDataForBookmark(bm1, "pdata1");
+  var bm2 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm2, "bar");
+  PlacesUtils.setPostDataForBookmark(bm2, "pdata2");
+
+  // check kw, pd for bookmark 1
+  var url, postdata;
+  [url, postdata] = PlacesUtils.getURLAndPostDataForKeyword("foo");
+  do_check_eq(testURI.spec, url);
+  do_check_eq(postdata, "pdata1");
+
+  // check kw, pd for bookmark 2
+  [url, postdata] = PlacesUtils.getURLAndPostDataForKeyword("bar");
+  do_check_eq(testURI.spec, url);
+  do_check_eq(postdata, "pdata2");
+
+  // cleanup
+  bmsvc.removeItem(bm1);
+  bmsvc.removeItem(bm2);
+
+  /*
+  1. Create two bookmarks with the same URI and keyword.
+  2. Confirm that the most recently created one is returned for that keyword.
+  */
+  var bm1 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm1, "foo");
+  PlacesUtils.setPostDataForBookmark(bm1, "pdata1");
+  var bm2 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm2, "foo");
+  PlacesUtils.setPostDataForBookmark(bm2, "pdata2");
+
+  var bm1da = bmsvc.getItemDateAdded(bm1);
+  var bm1lm = bmsvc.getItemLastModified(bm1);
+  LOG("bm1 dateAdded: " + bm1da + ", lastModified: " + bm1lm);
+  var bm2da = bmsvc.getItemDateAdded(bm2);
+  var bm2lm = bmsvc.getItemLastModified(bm2);
+  LOG("bm2 dateAdded: " + bm2da + ", lastModified: " + bm2lm);
+  do_check_true(bm1da <= bm2da);
+  do_check_true(bm1lm <= bm2lm);
+
+  [url, postdata] = PlacesUtils.getURLAndPostDataForKeyword("foo");
+  do_check_eq(testURI.spec, url);
+  do_check_eq(postdata, "pdata2");
+
+  // cleanup
+  bmsvc.removeItem(bm1);
+  bmsvc.removeItem(bm2);
+
+  /*
+  1. Create two bookmarks with the same URI and keyword.
+  2. Modify the first-created bookmark.
+  3. Confirm that the most recently modified one is returned for that keyword.
+  */
+  var bm1 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm1, "foo");
+  PlacesUtils.setPostDataForBookmark(bm1, "pdata1");
+  var bm2 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm2, "foo");
+  PlacesUtils.setPostDataForBookmark(bm2, "pdata2");
+
+  // modify the older bookmark
+  bmsvc.setItemTitle(bm1, "change");
+
+  var bm1da = bmsvc.getItemDateAdded(bm1);
+  var bm1lm = bmsvc.getItemLastModified(bm1);
+  LOG("bm1 dateAdded: " + bm1da + ", lastModified: " + bm1lm);
+  var bm2da = bmsvc.getItemDateAdded(bm2);
+  var bm2lm = bmsvc.getItemLastModified(bm2);
+  LOG("bm2 dateAdded: " + bm2da + ", lastModified: " + bm2lm);
+  do_check_true(bm1da <= bm2da);
+  // the last modified for bm1 should be at least as big as bm2
+  // but could be equal if the test runs faster than our PRNow()
+  // granularity
+  do_check_true(bm1lm >= bm2lm);
+
+  // we need to ensure that bm1 last modified date is greater
+  // that the modified date of bm2, otherwise in case of a "tie"
+  // bm2 will win, as it has a bigger item id
+  if (bm1lm == bm2lm) 
+    bmsvc.setItemLastModified(bm1, bm2lm + 1);
+
+  [url, postdata] = PlacesUtils.getURLAndPostDataForKeyword("foo");
+  do_check_eq(testURI.spec, url);
+  do_check_eq(postdata, "pdata1");
+
+  // cleanup
+  bmsvc.removeItem(bm1);
+  bmsvc.removeItem(bm2);
+
+  /*
+  Test that id breaks ties:
+  1. Create two bookmarks with the same URI and keyword, dateAdded and lastModified.
+  2. Confirm that the most recently created one is returned for that keyword.
+  */
+  var testDate = Date.now() * 1000;
+  var bm1 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm1, "foo");
+  PlacesUtils.setPostDataForBookmark(bm1, "pdata1");
+  bmsvc.setItemDateAdded(bm1, testDate);
+  bmsvc.setItemLastModified(bm1, testDate);
+
+  var bm2 = bmsvc.insertBookmark(testFolderId, testURI, -1, "blah");
+  bmsvc.setKeywordForBookmark(bm2, "foo");
+  PlacesUtils.setPostDataForBookmark(bm2, "pdata2");
+  bmsvc.setItemDateAdded(bm2, testDate);
+  bmsvc.setItemLastModified(bm2, testDate);
+
+  var bm1da = bmsvc.getItemDateAdded(bm1, testDate);
+  var bm1lm = bmsvc.getItemLastModified(bm1);
+  LOG("bm1 dateAdded: " + bm1da + ", lastModified: " + bm1lm);
+  var bm2da = bmsvc.getItemDateAdded(bm2);
+  var bm2lm = bmsvc.getItemLastModified(bm2);
+  LOG("bm2 dateAdded: " + bm2da + ", lastModified: " + bm2lm);
+
+  do_check_eq(bm1da, bm2da);
+  do_check_eq(bm1lm, bm2lm);
+
+
+  var ids = bmsvc.getBookmarkIdsForURI(testURI, {});
+  do_check_eq(ids[0], bm2);
+  do_check_eq(ids[1], bm1);
+
+  [url, postdata] = PlacesUtils.getURLAndPostDataForKeyword("foo");
+  do_check_eq(testURI.spec, url);
+  do_check_eq(postdata, "pdata2");
+
+  // cleanup
+  bmsvc.removeItem(bm1);
+  bmsvc.removeItem(bm2);
+}
--- a/browser/components/places/tests/unit/test_bookmarks_html.js
+++ b/browser/components/places/tests/unit/test_bookmarks_html.js
@@ -76,27 +76,27 @@ try {
   var iosvc = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
 } catch (ex) {
   do_throw("Could not get io service\n");
 }
 
 
 const DESCRIPTION_ANNO = "bookmarkProperties/description";
 const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
-const POST_DATA_ANNO = "URIProperties/POSTData";
+const POST_DATA_ANNO = "bookmarkProperties/POSTData";
 const LAST_CHARSET_ANNO = "URIProperties/characterSet";
 
 // main
 function run_test() {
   // get places import/export service
   var importer = Cc["@mozilla.org/browser/places/import-export-service;1"].getService(Ci.nsIPlacesImportExportService);
 
   // avoid creating the places smart folder during tests
   Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch).
-  setBoolPref("browser.places.createdDefaultQueries", true);
+  setBoolPref("browser.places.createdSmartBookmarks", true);
 
   // file pointer to legacy bookmarks file
   var bookmarksFileOld = do_get_file("browser/components/places/tests/unit/bookmarks.preplaces.html");
   // file pointer to a new places-exported bookmarks file
   var bookmarksFileNew = dirSvc.get("ProfD", Ci.nsILocalFile);
   bookmarksFileNew.append("bookmarks.exported.html");
 
   // create bookmarks.exported.html
@@ -236,21 +236,22 @@ function testCanonicalBookmarks(aFolder)
                                           LOAD_IN_SIDEBAR_ANNO));
   // add date 
   do_check_eq(testBookmark1.dateAdded/1000000, 1177375336);
 
   // last modified
   do_check_eq(testBookmark1.lastModified/1000000, 1177375423);
 
   // post data
-  var pageURI = iosvc.newURI(testBookmark1.uri, "", null);
-  do_check_true(annosvc.pageHasAnnotation(pageURI, POST_DATA_ANNO));
+  do_check_true(annosvc.itemHasAnnotation(testBookmark1.itemId, POST_DATA_ANNO));
   do_check_eq("hidden1%3Dbar&text1%3D%25s",
-              annosvc.getPageAnnotation(pageURI, POST_DATA_ANNO));
+              annosvc.getItemAnnotation(testBookmark1.itemId, POST_DATA_ANNO));
+
   // last charset 
+  var pageURI = iosvc.newURI(testBookmark1.uri, "", null);
   do_check_true(annosvc.pageHasAnnotation(pageURI, LAST_CHARSET_ANNO));
   do_check_eq("ISO-8859-1", annosvc.getPageAnnotation(pageURI,
                                                       LAST_CHARSET_ANNO));
   // description 
   do_check_true(annosvc.itemHasAnnotation(testBookmark1.itemId,
                                           DESCRIPTION_ANNO));
   do_check_eq("item description",
               annosvc.getItemAnnotation(testBookmark1.itemId,
--- a/browser/components/places/tests/unit/test_placesTxn.js
+++ b/browser/components/places/tests/unit/test_placesTxn.js
@@ -376,11 +376,22 @@ function run_test() {
   var txn18 = ptSvc.editBookmarkMicrosummary(bId, tmpMs);
   txn18.doTransaction();
   do_check_eq(observer._itemChangedId, bId);
   do_check_true(mss.hasMicrosummary(bId));
   txn18.undoTransaction();
   do_check_eq(observer._itemChangedId, bId);
   do_check_true(!mss.hasMicrosummary(bId));
 
-  // Testing edit Post Data...
-  // mmm.. cant figure out a good way to test this.
+  // Testing edit Post Data
+  const POST_DATA_ANNO = "bookmarkProperties/POSTData";
+  var postData = "foo";
+  var postDataURI = uri("http://foo.com");
+  ptSvc.doTransaction(
+    ptSvc.createItem(postDataURI, root, -1, "postdata test", null, null, null));
+  var postDataId = (bmsvc.getBookmarkIdsForURI(postDataURI,{}))[0];
+  var postDataTxn = ptSvc.editBookmarkPostData(postDataId, postData);
+  postDataTxn.doTransaction();
+  do_check_true(annotationService.itemHasAnnotation(postDataId, POST_DATA_ANNO))
+  do_check_eq(annotationService.getItemAnnotation(postDataId, POST_DATA_ANNO), postData);
+  postDataTxn.undoTransaction();
+  do_check_false(annotationService.itemHasAnnotation(postDataId, POST_DATA_ANNO))
 }
--- a/browser/components/preferences/advanced.js
+++ b/browser/components/preferences/advanced.js
@@ -394,9 +394,56 @@ var gAdvancedPane = {
    * Displays a dialog from which the user can manage his security devices.
    */
   showSecurityDevices: function ()
   {
     document.documentElement.openWindow("mozilla:devicemanager",
                                         "chrome://pippki/content/device_manager.xul",
                                         "", null);
   }
+#ifdef HAVE_SHELL_SERVICE
+  ,
+
+  // SYSTEM DEFAULTS
+
+  /*
+   * Preferences:
+   *
+   * browser.shell.checkDefault
+   * - true if a default-browser check (and prompt to make it so if necessary)
+   *   occurs at startup, false otherwise
+   */
+
+  /**
+   * Checks whether the browser is currently registered with the operating
+   * system as the default browser.  If the browser is not currently the
+   * default browser, the user is given the option of making it the default;
+   * otherwise, the user is informed that this browser already is the browser.
+   */
+  checkNow: function ()
+  {
+    var shellSvc = Components.classes["@mozilla.org/browser/shell-service;1"]
+                             .getService(Components.interfaces.nsIShellService);
+    var brandBundle = document.getElementById("bundleBrand");
+    var shellBundle = document.getElementById("bundleShell");
+    var brandShortName = brandBundle.getString("brandShortName");
+    var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
+    var promptMessage;
+    const IPS = Components.interfaces.nsIPromptService;
+    var psvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
+                         .getService(IPS);
+    if (!shellSvc.isDefaultBrowser(false)) {
+      promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage", 
+                                                     [brandShortName]);
+      var rv = psvc.confirmEx(window, promptTitle, promptMessage, 
+                              IPS.STD_YES_NO_BUTTONS,
+                              null, null, null, null, { });
+      if (rv == 0)
+        shellSvc.setDefaultBrowser(true, false);
+    }
+    else {
+      promptMessage = shellBundle.getFormattedString("alreadyDefaultBrowser",
+                                                     [brandShortName]);
+      psvc.alert(window, promptTitle, promptMessage);
+    }
+  }
+#endif
 };
--- a/browser/components/preferences/advanced.xul
+++ b/browser/components/preferences/advanced.xul
@@ -47,19 +47,17 @@
 <!ENTITY % privacyDTD SYSTEM "chrome://browser/locale/preferences/privacy.dtd">
 %privacyDTD;
 ]>
 
 <overlay id="AdvancedPaneOverlay"
          xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
 
   <prefpane id="paneAdvanced" onpaneload="gAdvancedPane.init();"
-            helpURI="chrome://browser/locale/help/help.rdf"
-            xmlns:xhtml="http://www.w3.org/1999/xhtml"
-            xmlns:aaa="http://www.w3.org/2005/07/aaa">
+            helpURI="chrome://browser/locale/help/help.rdf">
 
     <preferences id="advancedPreferences">
       <preference id="browser.preferences.advanced.selectedTabIndex"
                   name="browser.preferences.advanced.selectedTabIndex"
                   type="int"/>
 
       <!--XXX button prefs -->
 
@@ -67,16 +65,25 @@
       <preference id="accessibility.browsewithcaret"   name="accessibility.browsewithcaret"   type="bool"/>
       <preference id="accessibility.typeaheadfind"     name="accessibility.typeaheadfind"     type="bool"/>
       <preference id="accessibility.blockautorefresh"  name="accessibility.blockautorefresh"  type="bool"/>
 
       <preference id="general.autoScroll"              name="general.autoScroll"              type="bool"/>
       <preference id="general.smoothScroll"            name="general.smoothScroll"            type="bool"/>
       <preference id="layout.spellcheckDefault"        name="layout.spellcheckDefault"        type="int"/>
 
+#ifdef HAVE_SHELL_SERVICE
+      <preference id="browser.shell.checkDefaultBrowser"
+                  name="browser.shell.checkDefaultBrowser"
+                  type="bool"/>
+
+      <preference id="pref.general.disable_button.default_browser"
+                  name="pref.general.disable_button.default_browser"
+                  type="bool"/>
+#endif
 
       <!-- Network tab -->
       <preference id="browser.cache.disk.capacity"     name="browser.cache.disk.capacity"     type="int"/>
 
 
       <!-- Update tab -->
       <preference id="app.update.enabled"              name="app.update.enabled"              type="bool"
                   onchange="gAdvancedPane.updateAppUpdateItems();
@@ -109,16 +116,21 @@
       <preference id="security.OCSP.disable_button.managecrl"
                   name="security.OCSP.disable_button.managecrl"
                   type="bool"/>
       <preference id="security.disable_button.openDeviceManager"
                   name="security.disable_button.openDeviceManager"
                   type="bool"/>
     </preferences>
     
+#ifdef HAVE_SHELL_SERVICE
+    <stringbundle id="bundleShell" src="chrome://browser/locale/shellservice.properties"/>
+    <stringbundle id="bundleBrand" src="chrome://branding/locale/brand.properties"/>
+#endif
+
     <script type="application/x-javascript" src="chrome://browser/content/preferences/advanced.js"/>
 
     <tabbox id="advancedPrefs" flex="1"
             onselect="gAdvancedPane.tabSelectionChanged();">
 
       <tabs id="tabsElement">
         <tab id="generalTab" label="&generalTab.label;" helpTopic="prefs-advanced-general"/>
         <tab id="networkTab" label="&networkTab.label;" helpTopic="prefs-advanced-network"/>
@@ -164,16 +176,32 @@
             <checkbox id="checkSpelling"
                       label="&checkSpelling.label;"
                       accesskey="&checkSpelling.accesskey;"
                       onsyncfrompreference="return gAdvancedPane.readCheckSpelling();"
                       onsynctopreference="return gAdvancedPane.writeCheckSpelling();"
                       preference="layout.spellcheckDefault"/>
           </groupbox>
 
+#ifdef HAVE_SHELL_SERVICE
+          <!-- System Defaults -->
+          <groupbox id="systemDefaultsGroup" orient="horizontal">
+            <caption label="&systemDefaults.label;"/>
+
+            <hbox id="checkDefaultBox" align="center" flex="1">      
+              <checkbox id="alwaysCheckDefault" preference="browser.shell.checkDefaultBrowser"
+                        label="&alwaysCheckDefault.label;" accesskey="&alwaysCheckDefault.accesskey;"
+                        flex="1"/>
+              <button id="checkDefaultButton"
+                      label="&checkNow.label;" accesskey="&checkNow.accesskey;"
+                      oncommand="gAdvancedPane.checkNow()"
+                      preference="pref.general.disable_button.default_browser"/>
+            </hbox>
+          </groupbox>
+#endif
         </tabpanel>
 
         <!-- Network -->
         <tabpanel id="networkPanel" orient="vertical">
 
            <!-- Connection -->
            <groupbox id="connectionGroup">
              <caption label="&connection.label;"/>
@@ -192,29 +220,29 @@
 
              <hbox align="center">
                <label id="useCacheBefore"
                       accesskey="&useCacheBefore.accesskey;">&useCacheBefore.label;</label>
                <textbox id="cacheSize" type="number" size="2"
                         preference="browser.cache.disk.capacity"
                         onsyncfrompreference="return gAdvancedPane.readCacheSize();"
                         onsynctopreference="return gAdvancedPane.writeCacheSize();"
-                        aaa:labelledby="useCacheBefore cacheSize useCacheAfter"/>
+                        aria-labelledby="useCacheBefore cacheSize useCacheAfter"/>
                <label id="useCacheAfter" flex="1">&useCacheAfter.label;</label>
                <button id="clearCacheButton" icon="clear"
-                       label="&clearCacheNow.label;"
+                       label="&clearCacheNow.label;" accesskey="&clearCacheNow.accesskey;"
                        oncommand="gAdvancedPane.clearCache();"/>
              </hbox>
            </groupbox>
         </tabpanel>
 
         <!-- Update -->
         <tabpanel id="updatePanel" orient="vertical" align="start">
           <label control="autoUpdateGroup">&autoCheck.label;</label>
-          <vbox class="indent" id="autoUpdateGroup" xhtml:role="group">
+          <vbox class="indent" id="autoUpdateGroup" role="group">
             <checkbox id="enableAppUpdate"
                       label="&enableAppUpdate.label;"
                       accesskey="&enableAppUpdate.accesskey;"
                       preference="app.update.enabled"/>
             <checkbox id="enableAddonUpdate"
                       label="&enableAddonsUpdate.label;"
                       accesskey="&enableAddonsUpdate.accesskey;"
                       preference="extensions.update.enabled"/>
@@ -290,17 +318,17 @@
             <description id="CertSelectionDesc" control="certSelection">&certselect.description;</description>
 
             <!--
               The values on these radio buttons may look like l12y issues, but
               they're not - this preference uses *those strings* as its values.
               I KID YOU NOT.
             -->
             <radiogroup id="certSelection" orient="horizontal" preftype="string" 
-	                      preference="security.default_personal_cert" aaa:labelledby="CertGroupCaption CertSelectionDesc">
+	                      preference="security.default_personal_cert" aria-abelledby="CertGroupCaption CertSelectionDesc">
               <radio label="&certs.auto;" accesskey="&certs.auto.accesskey;" 
                      value="Select Automatically"/>
               <radio label="&certs.ask;" accesskey="&certs.ask.accesskey;" 
                      value="Ask Every Time"/>
             </radiogroup>
 
             <separator/>
 
--- a/browser/components/preferences/cookies.js
+++ b/browser/components/preferences/cookies.js
@@ -59,16 +59,20 @@ var gCookiesWindow = {
     this._bundle = document.getElementById("bundlePreferences");
     this._tree = document.getElementById("cookiesList");
     
     this._loadCookies();
     this._tree.treeBoxObject.view = this._view;
     this.sort("rawHost");
     if (this._view.rowCount > 0) 
       this._tree.view.selection.select(0);
+
+    if ("arguments" in window && window.arguments.length > 0 &&
+        window.arguments[0].filterString)
+      this.setFilter(window.arguments[0].filterString);
     
     this._saveState();
       
     document.getElementById("filter").focus();
   },
   
   uninit: function ()
   {
@@ -910,11 +914,17 @@ var gCookiesWindow = {
       this.clearFilter();
   },
   
   focusFilterBox: function ()
   { 
     var filter = document.getElementById("filter");
     filter.focus();
     filter.select();
+  },
+
+  setFilter: function (aFilterString)
+  {
+    document.getElementById("filter").value = aFilterString;
+    this.onFilterInput();
   }
 };
 
--- a/browser/components/preferences/handlers.css
+++ b/browser/components/preferences/handlers.css
@@ -38,29 +38,16 @@ richlistitem {
   -moz-binding: url("chrome://browser/content/preferences/handlers.xml#handler");
 }
 
 richlistitem[selected="true"] {
   -moz-binding: url("chrome://browser/content/preferences/handlers.xml#handler-selected");
 }
 
 /**
- * Somewhat line up the actions menu with action labels above and below it.
- * FIXME: to really line this up, equalize the distance from the left side
- * of the action box to the left side of the icon for both the menu and the
- * non-menu versions of the action box.  Also make sure the labels are the
- * same distance away from the icons.
- */
-.actionsMenu {
-  margin-left: 0;
-}
-
-/**
- * Make the icons appear and pad them a bit.
+ * Make the icons appear.
  * Note: we display the icon box for every item whether or not it has an icon
  * so the labels of all the items align vertically.
  */
 .actionsMenu > menupopup > menuitem > .menu-iconic-left {
   display: -moz-box;
   min-width: 16px;
-  -moz-padding-start: 2px;
-  -moz-padding-end: 2px;
 }
--- a/browser/components/preferences/handlers.xml
+++ b/browser/components/preferences/handlers.xml
@@ -57,33 +57,33 @@
       </property>
     </implementation>
   </binding>
 
   <binding id="handler" extends="chrome://browser/content/preferences/handlers.xml#handler-base">
     <content>
       <xul:hbox flex="1" equalsize="always">
         <xul:hbox flex="1" align="center">
-          <xul:image src="moz-icon://goat?size=16"
+          <xul:image src="moz-icon://goat?size=16" class="typeIcon"
                      xbl:inherits="src=typeIcon" height="16" width="16"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=typeDescription"/>
         </xul:hbox>
         <xul:hbox flex="1" align="center">
-          <xul:image xbl:inherits="src=actionIcon" height="16" width="16"/>
+          <xul:image xbl:inherits="src=actionIcon" height="16" width="16" class="actionIcon"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=actionDescription"/>
         </xul:hbox>
       </xul:hbox>
     </content>
   </binding>
 
   <binding id="handler-selected" extends="chrome://browser/content/preferences/handlers.xml#handler-base">
     <content>
       <xul:hbox flex="1" equalsize="always">
         <xul:hbox flex="1" align="center">
-          <xul:image src="moz-icon://goat?size=16"
+          <xul:image src="moz-icon://goat?size=16" class="typeIcon"
                      xbl:inherits="src=typeIcon" height="16" width="16"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=typeDescription"/>
         </xul:hbox>
         <xul:hbox flex="1">
           <xul:menulist class="actionsMenu" flex="1" crop="end" selectedIndex="1"
                         oncommand="gApplicationsPane.onSelectAction(event.originalTarget)">
             <xul:menupopup/>
           </xul:menulist>
--- a/browser/components/preferences/main.js
+++ b/browser/components/preferences/main.js
@@ -461,57 +461,9 @@ var gMainPane = {
       theEM.focus();
       return;
     }
 
     const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
     const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
     window.openDialog(EMURL, "", EMFEATURES);
   }
-
-#ifdef HAVE_SHELL_SERVICE
-  ,
-
-  // SYSTEM DEFAULTS
-
-  /*
-   * Preferences:
-   *
-   * browser.shell.checkDefault
-   * - true if a default-browser check (and prompt to make it so if necessary)
-   *   occurs at startup, false otherwise
-   */
-
-  /**
-   * Checks whether the browser is currently registered with the operating
-   * system as the default browser.  If the browser is not currently the
-   * default browser, the user is given the option of making it the default;
-   * otherwise, the user is informed that this browser already is the browser.
-   */
-  checkNow: function ()
-  {
-    var shellSvc = Components.classes["@mozilla.org/browser/shell-service;1"]
-                             .getService(Components.interfaces.nsIShellService);
-    var brandBundle = document.getElementById("bundleBrand");
-    var shellBundle = document.getElementById("bundleShell");
-    var brandShortName = brandBundle.getString("brandShortName");
-    var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
-    var promptMessage;
-    const IPS = Components.interfaces.nsIPromptService;
-    var psvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
-                         .getService(IPS);
-    if (!shellSvc.isDefaultBrowser(false)) {
-      promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage", 
-                                                     [brandShortName]);
-      var rv = psvc.confirmEx(window, promptTitle, promptMessage, 
-                              IPS.STD_YES_NO_BUTTONS,
-                              null, null, null, null, { });
-      if (rv == 0)
-        shellSvc.setDefaultBrowser(true, false);
-    }
-    else {
-      promptMessage = shellBundle.getFormattedString("alreadyDefaultBrowser",
-                                                     [brandShortName]);
-      psvc.alert(window, promptTitle, promptMessage);
-    }
-  }
-#endif
 };
--- a/browser/components/preferences/main.xul
+++ b/browser/components/preferences/main.xul
@@ -88,32 +88,19 @@
                   name="browser.download.useDownloadDir"
                   type="bool"/>
       <preference id="browser.download.dir"
                   name="browser.download.dir"
                   type="file"
                   onchange="gMainPane.displayDownloadDirPref();"/>
       <preference id="browser.download.folderList"        name="browser.download.folderList"        type="int"/>
 
-      <!-- SYSTEM DEFAULTS -->
-      <preference id="browser.shell.checkDefaultBrowser"
-                  name="browser.shell.checkDefaultBrowser"
-                  type="bool"/>
-
-      <preference id="pref.general.disable_button.default_browser"
-                  name="pref.general.disable_button.default_browser"
-                  type="bool"/>
-
     </preferences>
     
     <stringbundle id="bundlePreferences" src="chrome://browser/locale/preferences/preferences.properties"/>
-#ifdef HAVE_SHELL_SERVICE
-    <stringbundle id="bundleShell" src="chrome://browser/locale/shellservice.properties"/>
-    <stringbundle id="bundleBrand" src="chrome://branding/locale/brand.properties"/>
-#endif
 
     <!-- Startup -->
     <groupbox id="startupGroup">
       <caption label="&startup.label;"/>
 
       <hbox align="center">
         <label value="&startupPage.label;" accesskey="&startupPage.accesskey;"
                control="browserStartupPage"/>
@@ -190,41 +177,25 @@
                   onsynctopreference="return gMainPane.getFolderListPref();"/>
         </hbox>
         <radio id="alwaysAsk" value="false"
                label="&alwaysAsk.label;"
                accesskey="&alwaysAsk.accesskey;"/>
       </radiogroup>
     </groupbox>
 
-#ifdef HAVE_SHELL_SERVICE
-    <!-- System Defaults -->
-    <groupbox id="systemDefaultsGroup" orient="horizontal">
-      <caption label="&systemDefaults.label;"/>
-
-      <hbox id="checkDefaultBox" align="center" flex="1">      
-        <checkbox id="alwaysCheckDefault" preference="browser.shell.checkDefaultBrowser"
-                  label="&alwaysCheckDefault.label;" accesskey="&alwaysCheckDefault.accesskey;"
-                  flex="1"/>
-        <button id="checkDefaultButton"
-                label="&checkNow.label;" accesskey="&checkNow.accesskey;"
-                oncommand="gMainPane.checkNow()"
-                preference="pref.general.disable_button.default_browser"/>
-      </hbox>
-    </groupbox>
-#endif
     <hbox class="bottomBox">
       <groupbox id="addonsMgrGroup" orient="horizontal" flex="1">
         <caption label="&addonsMgr.label;"/>
 
         <description control="manageAddons"
 #ifdef XP_WIN
-                     flex="1">&manageAddonsDesc.label;</description>
+                     flex="1">&manageAddonsDescWin.label;</description>
 #else
-                     flex="1">&manageAddonsDescUnix.label;</description>
+                     flex="1">&manageAddonsDescUnix2.label;</description>
 #endif
         <button id="manageAddons" label="&manageAddons.label;"
                 accesskey="&manageAddons.accesskey;"
                 oncommand="gMainPane.showAddonsMgr();"/>
       </groupbox>
     </hbox>
 
   </prefpane>
--- a/browser/components/preferences/preferences.xul
+++ b/browser/components/preferences/preferences.xul
@@ -44,16 +44,17 @@
 <?xml-stylesheet href="chrome://browser/skin/preferences/preferences.css"?>
 
 <!-- XXX This should be in applications.xul, but bug 393953 means putting it
    - there causes the Applications pane not to work the first time you open
    - the Preferences dialog in a browsing session, so we work around the problem
    - by putting it here instead.
    -->
 <?xml-stylesheet href="chrome://browser/content/preferences/handlers.css"?>
+<?xml-stylesheet href="chrome://browser/skin/preferences/applications.css"?>
 
 <!DOCTYPE prefwindow [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % preferencesDTD SYSTEM "chrome://browser/locale/preferences/preferences.dtd">
 %brandDTD;
 %preferencesDTD;
 ]>
 
@@ -77,22 +78,22 @@
 #ifdef XP_UNIX
 #ifndef XP_MACOSX
             title="&prefWindow.titleGNOME;"
 #endif
 #endif
 #endif
             xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
 #ifdef USE_WIN_TITLE_STYLE
-            style="&prefWin.styleWin;">
+            style="&prefWin.styleWin2;">
 #else
 #ifdef XP_MACOSX
-            style="&prefWin.styleMac;">
+            style="&prefWin.styleMac2;">
 #else
-            style="&prefWin.styleGNOME;">
+            style="&prefWin.styleGNOME2;">
 #endif
 #endif
 
     <stringbundle id="bundleBrand" src="chrome://branding/locale/brand.properties"/>
     <stringbundle id="bundlePreferences"
                   src="chrome://browser/locale/preferences/preferences.properties"/>
 
     <prefpane id="paneMain" label="&paneMain.title;"
--- a/browser/components/preferences/privacy.js
+++ b/browser/components/preferences/privacy.js
@@ -51,21 +51,30 @@ var gPrivacyPane = {
     this.updateClearNowButtonLabel();
   },
 
   // HISTORY
 
   /*
    * Preferences:
    *
+   * NOTE: These first two are no longer shown in the UI. They're controlled
+   *       via the checkbox, which uses the zero state of the pref to turn
+   *       history off.
    * browser.history_expire_days
    * - the number of days of history to remember
    * browser.history_expire_days.mirror
    * - a preference whose value mirrors that of browser.history_expire_days, to
    *   make the "days of history" checkbox easier to code
+   *
+   * browser.history_expire_days_min
+   * - the mininum number of days of history to remember
+   * browser.history_expire_days_min.mirror
+   * - a preference whose value mirrors that of browser.history_expire_days_min
+   *   to make the "days of history" checkbox easier to code
    * browser.formfill.enable
    * - true if entries in forms and the search bar should be saved, false
    *   otherwise
    * browser.download.manager.retention
    * - determines when downloads are automatically removed from the download
    *   manager:
    *
    *     0 means remove downloads when they finish downloading
@@ -77,44 +86,26 @@ var gPrivacyPane = {
    * Initializes the days-of-history mirror preference and connects it to the
    * days-of-history checkbox so that updates to the textbox are transmitted to
    * the real days-of-history preference.
    */
   _updateHistoryDaysUI: function ()
   {
     var pref = document.getElementById("browser.history_expire_days");
     var mirror = document.getElementById("browser.history_expire_days.mirror");
+    var pref_min = document.getElementById("browser.history_expire_days_min");
     var textbox = document.getElementById("historyDays");
     var checkbox = document.getElementById("rememberHistoryDays");
 
     // handle mirror non-existence or mirror/pref unsync
     if (mirror.value === null || mirror.value != pref.value)
       mirror.value = pref.value ? pref.value : pref.defaultValue;
 
     checkbox.checked = (pref.value > 0);
     textbox.disabled = !checkbox.checked;
-
-    // hook up textbox to mirror preference and force a preference read
-    textbox.setAttribute("onsynctopreference", "return gPrivacyPane._writeHistoryDaysMirror();");
-    textbox.setAttribute("preference", "browser.history_expire_days.mirror");
-    mirror.updateElements();
-  },
-
-  /**
-   * Stores the days of history to the actual days-of-history preference and
-   * returns that value, to be stored in the mirror preference.
-   */
-  _writeHistoryDaysMirror: function ()
-  {
-    var pref = document.getElementById("browser.history_expire_days");
-    var textbox = document.getElementById("historyDays");
-    pref.value = textbox.value;
-
-    // don't override the value in the textbox
-    return undefined;
   },
 
   /**
    * Responds to the checking or unchecking of the days-of-history UI, storing
    * the appropriate value to the days-of-history preference and enabling or
    * disabling the number textbox as appropriate.
    */
   onchangeHistoryDaysCheck: function ()
@@ -124,16 +115,29 @@ var gPrivacyPane = {
     var textbox = document.getElementById("historyDays");
     var checkbox = document.getElementById("rememberHistoryDays");
 
     pref.value = checkbox.checked ? mirror.value : 0;
     textbox.disabled = !checkbox.checked;
   },
 
   /**
+   * Responds to changes in the days-of-history textbox,
+   * unchecking the history-enabled checkbox if the days
+   * value is zero.
+   */
+  onkeyupHistoryDaysText: function ()
+  {
+    var textbox = document.getElementById("historyDays");
+    var checkbox = document.getElementById("rememberHistoryDays");
+    
+    checkbox.checked = textbox.value != 0;
+  },
+
+  /**
    * Converts the value of the browser.download.manager.retention preference
    * into a Boolean value.  "remove on close" and "don't remember" both map
    * to an unchecked checkbox, while "remember" maps to a checked checkbox.
    */
   readDownloadRetention: function ()
   {
     var pref = document.getElementById("browser.download.manager.retention");
     return (pref.value == 2);
--- a/browser/components/preferences/privacy.xul
+++ b/browser/components/preferences/privacy.xul
@@ -65,16 +65,19 @@
 
       <!-- History -->
       <preference id="browser.history_expire_days"
                   name="browser.history_expire_days"
                   type="int"/>
       <preference id="browser.history_expire_days.mirror"
                   name="browser.history_expire_days.mirror"
                   type="int"/>
+      <preference id="browser.history_expire_days_min"
+                  name="browser.history_expire_days_min"
+                  type="int"/>
       <preference id="browser.formfill.enable"
                   name="browser.formfill.enable"
                   type="bool"/>
       <preference id="browser.download.manager.retention"
                   name="browser.download.manager.retention"
                   type="int"/>
 
       <!-- Cookies -->
@@ -99,23 +102,25 @@
 
     <!-- History -->
     <groupbox id="historyGroup"
               xmlns:aaa="http://www.w3.org/2005/07/aaa">
       <caption label="&history.label;"/>
 
       <hbox align="center">
         <checkbox id="rememberHistoryDays"
-                  label="&rememberBefore.label;"
-                  accesskey="&rememberBefore.accesskey;"
+                  label="&rememberDaysBefore.label;"
+                  accesskey="&rememberDaysBefore.accesskey;"
                   oncommand="gPrivacyPane.onchangeHistoryDaysCheck();"
                   aaa:labelledby="rememberHistoryDays historyDays rememberAfter"/>
         <textbox id="historyDays" type="number" size="3"
-                 aaa:labelledby="rememberHistoryDays historyDays rememberAfter"/>
-        <label id="rememberAfter"> &rememberAfter.label;</label>
+                 aaa:labelledby="rememberHistoryDays historyDays rememberAfter"
+                 onkeyup="gPrivacyPane.onkeyupHistoryDaysText();"
+                 preference="browser.history_expire_days_min"/>
+        <label id="rememberAfter"> &rememberDaysAfter.label;</label>
       </hbox>
       <checkbox id="rememberForms"
                 label="&rememberForms.label;"
                 accesskey="&rememberForms.accesskey;"
                 preference="browser.formfill.enable"/>
       <checkbox id="rememberDownloads"
                 label="&rememberDownloads.label;"
                 accesskey="&rememberDownloads.accesskey;"
--- a/browser/components/safebrowsing/content/warning-overlay.xul
+++ b/browser/components/safebrowsing/content/warning-overlay.xul
@@ -29,18 +29,17 @@
     <vbox id="safebrowsing-palm-message" hidden="true" pack="center"
           class="safebrowsing-palm-fixed-width">
 
       <!-- This is the main warning area -->
 
       <vbox id="safebrowsing-palm-message-content" 
             class="safebrowsing-palm-fixed-width"
             style="-moz-user-focus: normal"
-            xmlns:xhtml="http://www.w3.org/1999/xhtml"
-            xhtml:role="alert">
+            role="alert">
 
         <hbox id="safebrowsing-palm-close-container" align="center"
               class="safebrowsing-palm-fixed-width">
           <spacer flex="1"/>
           <image id="safebrowsing-palm-close"
                  onclick="goDoCommand('safebrowsing-decline-warning')"/>
         </hbox>
 
--- a/browser/components/search/content/search.xml
+++ b/browser/components/search/content/search.xml
@@ -644,16 +644,24 @@
           ps2.addObserver("browser.search.suggest.enabled", this, false);
         ]]></body>
       </method>
 
       <method name="openPopup">
         <body><![CDATA[
           var popup = this.popup;
           if (!popup.mPopupOpen) {
+            // Initially the panel used for the searchbar (PopupAutoComplete
+            // in browser.xul) is hidden to avoid impacting startup / new
+            // window performance. The base binding's openPopup would normally
+            // call the overriden openAutocompletePopup in urlbarBindings.xml's
+            // urlbar-result-popup binding to unhide the popup, but since we're
+            // overriding openPopup we need to unhide the panel ourselves.
+            popup.hidden = false;
+
             popup.mInput = this;
             popup.view = this.controller.QueryInterface(Components.interfaces.nsITreeView);
             popup.invalidate();
             
             popup.showCommentColumn = this.showCommentColumn;
             popup.showImageColumn = this.showImageColumn;
 
             document.popupNode = null;
--- a/browser/components/sessionstore/nsISessionStore.idl
+++ b/browser/components/sessionstore/nsISessionStore.idl
@@ -34,17 +34,16 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
 interface nsIDOMWindow;
 interface nsIDOMNode;
-interface nsIDictionary;
 
 /**
  * nsISessionStore keeps track of the current browsing state - i.e.
  * tab history, cookies, scroll state, form data, POSTDATA and window features
  * - and allows to restore everything into one window.
  */
 
 [scriptable, uuid(11852a90-20de-11db-a98b-0800200c9a66)]
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -542,23 +542,21 @@ SessionStoreService.prototype = {
   onTabClose: function sss_onTabClose(aWindow, aTab) {
     var maxTabsUndo = this._prefBranch.getIntPref("sessionstore.max_tabs_undo");
     // don't update our internal state if we don't have to
     if (maxTabsUndo == 0) {
       return;
     }
     
     // make sure that the tab related data is up-to-date
-    this._saveWindowHistory(aWindow);
-    this._updateTextAndScrollData(aWindow);
+    var tabState = this._collectTabData(aTab);
+    this._updateTextAndScrollDataForTab(aWindow, aTab.linkedBrowser, tabState);
     
     // store closed-tab data for undo
-    var tabState = this._windows[aWindow.__SSi].tabs[aTab._tPos];
-    if (tabState && (tabState.entries.length > 1 ||
-        tabState.entries[0].url != "about:blank")) {
+    if (tabState.entries.length > 1 || tabState.entries[0].url != "about:blank") {
       this._windows[aWindow.__SSi]._closedTabs.unshift({
         state: tabState,
         title: aTab.getAttribute("label"),
         image: aTab.getAttribute("image"),
         pos: aTab._tPos
       });
       var length = this._windows[aWindow.__SSi]._closedTabs.length;
       if (length > maxTabsUndo)
@@ -782,86 +780,91 @@ SessionStoreService.prototype = {
 
   /**
    * Store all session data for a window
    * @param aWindow
    *        Window reference
    */
   _saveWindowHistory: function sss_saveWindowHistory(aWindow) {
     var tabbrowser = aWindow.getBrowser();
-    var browsers = tabbrowser.browsers;
-    var tabs = this._windows[aWindow.__SSi].tabs = [];
-    this._windows[aWindow.__SSi].selected = 0;
+    var tabs = tabbrowser.mTabs;
+    var tabsData = this._windows[aWindow.__SSi].tabs = [];
+    
+    for (var i = 0; i < tabs.length; i++)
+      tabsData.push(this._collectTabData(tabs[i]));
+    
+    this._windows[aWindow.__SSi].selected = tabbrowser.mTabBox.selectedIndex + 1;
+  },
+
+  /**
+   * Collect data related to a single tab
+   * @param aTab
+   *        tabbrowser tab
+   * @returns object
+   */
+  _collectTabData: function sss_collectTabData(aTab) {
+    var tabData = { entries: [], index: 0 };
+    var browser = aTab.linkedBrowser;
     
-    for (var i = 0; i < browsers.length; i++) {
-      var tabData = { entries: [], index: 0 };
-      
-      var browser = browsers[i];
-      if (!browser || !browser.currentURI) {
-        // can happen when calling this function right after .addTab()
-        tabs.push(tabData);
-        continue;
-      }
-      else if (browser.parentNode.__SS_data && browser.parentNode.__SS_data._tab) {
-        // use the data to be restored when the tab hasn't been completely loaded
-        tabs.push(browser.parentNode.__SS_data);
-        continue;
-      }
-
-      var history = null;
-      try {
-        history = browser.sessionHistory;
-      }
-      catch (ex) { } // this could happen if we catch a tab during (de)initialization
+    if (!browser || !browser.currentURI)
+      // can happen when calling this function right after .addTab()
+      return tabData;
+    else if (browser.parentNode.__SS_data && browser.parentNode.__SS_data._tab)
+      // use the data to be restored when the tab hasn't been completely loaded
+      return browser.parentNode.__SS_data;
+    
+    var history = null;
+    try {
+      history = browser.sessionHistory;
+    }
+    catch (ex) { } // this could happen if we catch a tab during (de)initialization
+    
+    if (history && browser.parentNode.__SS_data &&
+        browser.parentNode.__SS_data.entries[history.index]) {
+      tabData = browser.parentNode.__SS_data;
+      tabData.index = history.index + 1;
+    }
+    else if (history && history.count > 0) {
+      for (var j = 0; j < history.count; j++)
+        tabData.entries.push(this._serializeHistoryEntry(history.getEntryAtIndex(j, false)));
+      tabData.index = history.index + 1;
       
-      if (history && browser.parentNode.__SS_data && browser.parentNode.__SS_data.entries[history.index]) {
-        tabData = browser.parentNode.__SS_data;
-        tabData.index = history.index + 1;
-      }
-      else if (history && history.count > 0) {
-        for (var j = 0; j < history.count; j++) {
-          tabData.entries.push(this._serializeHistoryEntry(history.getEntryAtIndex(j, false)));
-        }
-        tabData.index = history.index + 1;
-        
-        browser.parentNode.__SS_data = tabData;
-      }
-      else {
-        tabData.entries[0] = { url: browser.currentURI.spec };
-        tabData.index = 1;
-      }
-
-      tabData.zoom = browser.markupDocumentViewer.textZoom;
-      
-      var disallow = [];
-      for (let i = 0; i < CAPABILITIES.length; i++) {
-        if (!browser.docShell["allow" + CAPABILITIES[i]])
-          disallow.push(CAPABILITIES[i]); 
-      }
-      if (disallow.length != 0)
-        tabData.disallow = disallow.join(",");
-      
-      if (this.xulAttributes.length != 0) {
-        var xulattr = Array.filter(tabbrowser.mTabs[i].attributes, function(aAttr) {
-          return (this.xulAttributes.indexOf(aAttr.name) > -1);
-        }, this).map(function(aAttr) {
-          return aAttr.name + "=" + encodeURI(aAttr.value);
-        });
-        tabData.xultab = xulattr.join(" ");
-      }
-      
-      if (tabbrowser.mTabs[i].__SS_extdata)
-        tabData.extData = tabbrowser.mTabs[i].__SS_extdata;
-      
-      tabs.push(tabData);
-      
-      if (browser == tabbrowser.selectedBrowser) {
-        this._windows[aWindow.__SSi].selected = i + 1;
-      }
+      browser.parentNode.__SS_data = tabData;
+    }
+    else {
+      tabData.entries[0] = { url: browser.currentURI.spec };
+      tabData.index = 1;
     }
+    
+    tabData.zoom = browser.markupDocumentViewer.textZoom;
+    
+    var disallow = [];
+    for (var i = 0; i < CAPABILITIES.length; i++)
+      if (!browser.docShell["allow" + CAPABILITIES[i]])
+        disallow.push(CAPABILITIES[i]);
+    if (disallow.length > 0)
+      tabData.disallow = disallow.join(",");
+    else if (tabData.disallow)
+      delete tabData.disallow;
+    
+    if (this.xulAttributes.length > 0) {
+      var xulattr = Array.filter(aTab.attributes, function(aAttr) {
+        return this.xulAttributes.indexOf(aAttr.name) > -1;
+      }, this).map(function(aAttr) {
+        return aAttr.name + "=" + encodeURI(aAttr.value);
+      });
+      tabData.xultab = xulattr.join(" ");
+    }
+    
+    if (aTab.__SS_extdata)
+      tabData.extData = aTab.__SS_extdata;
+    else if (tabData.extData)
+      delete tabData.extData;
+    
+    return tabData;
   },
 
   /**
    * Get an object that is a serialized representation of a History entry
    * Used for data storage
    * @param aEntry
    *        nsISHEntry instance
    * @returns object
@@ -1010,72 +1013,102 @@ SessionStoreService.prototype = {
     
     // mark this element for saving
     aPanel.__SS_text[ix] = { id: id, element: aTextarea };
     
     return true;
   },
 
   /**
-   * go through all frames and store the current scroll positions
+   * go through all tabs and store the current scroll positions
    * and innerHTML content of WYSIWYG editors
    * @param aWindow
    *        Window reference
    */
   _updateTextAndScrollData: function sss_updateTextAndScrollData(aWindow) {
-    var _this = this;
-    function updateRecursively(aContent, aData) {
-      for (var i = 0; i < aContent.frames.length; i++) {
-        if (aData.children && aData.children[i]) {
-          updateRecursively(aContent.frames[i], aData.children[i]);
-        }
-      }
-      // designMode is undefined e.g. for XUL documents (as about:config)
-      var isHTTPS = _this._getURIFromString((aContent.parent || aContent).
-                                        document.location.href).schemeIs("https");
-      if ((aContent.document.designMode || "") == "on" && _this._checkPrivacyLevel(isHTTPS)) {
-        if (aData.innerHTML == undefined) {
-          // we get no "input" events from iframes - listen for keypress here
-          aContent.addEventListener("keypress", function(aEvent) { _this.saveStateDelayed(aWindow, 3000); }, true);
-        }
-        aData.innerHTML = aContent.document.body.innerHTML;
-      }
-      aData.scroll = aContent.scrollX + "," + aContent.scrollY;
-    }
-    
-    Array.forEach(aWindow.getBrowser().browsers, function(aBrowser, aIx) {
+    var browsers = aWindow.getBrowser().browsers;
+    for (var i = 0; i < browsers.length; i++) {
       try {
-        var tabData = this._windows[aWindow.__SSi].tabs[aIx];
-        if (tabData.entries.length == 0)
-          return; // ignore incompletely initialized tabs
-        
-        var text = [];
-        if (aBrowser.parentNode.__SS_text && this._checkPrivacyLevel(aBrowser.currentURI.schemeIs("https"))) {
-          for (var ix = aBrowser.parentNode.__SS_text.length - 1; ix >= 0; ix--) {
-            var data = aBrowser.parentNode.__SS_text[ix];
-            if (!data.cache) {
-              // update the text element's value before adding it to the data structure
-              data.cache = encodeURI(data.element.value);
-            }
-            text.push(data.id + "=" + data.cache);
-          }
-        }
-        if (aBrowser.currentURI.spec == "about:config") {
-          text = ["#textbox=" + encodeURI(aBrowser.contentDocument.getElementById("textbox").wrappedJSObject.value)];
-        }
-        if (text.length != 0)
-          tabData.text = text.join(" ");
-        
-        updateRecursively(aBrowser.contentWindow, tabData.entries[tabData.index - 1]);
+        var tabData = this._windows[aWindow.__SSi].tabs[i];
+        if (tabData.entries.length == 0 ||
+            browsers[i].parentNode.__SS_data && browsers[i].parentNode.__SS_data._tab)
+          continue; // ignore incompletely initialized tabs
+        this._updateTextAndScrollDataForTab(aWindow, browsers[i], tabData);
       }
       catch (ex) { debug(ex); } // get as much data as possible, ignore failures (might succeed the next time)
-    }, this);
+    }
   },
 
   /**
+   * go through all frames and store the current scroll positions
+   * and innerHTML content of WYSIWYG editors
+   * @param aWindow
+   *        Window reference
+   * @param aBrowser
+   *        single browser reference
+   * @param aTabData
+   *        tabData object to add the information to
+   */
+  _updateTextAndScrollDataForTab:
+    function sss_updateTextAndScrollDataForTab(aWindow, aBrowser, aTabData) {
+    var text = [];
+    if (aBrowser.parentNode.__SS_text &&
+        this._checkPrivacyLevel(aBrowser.currentURI.schemeIs("https"))) {
+      for (var ix = aBrowser.parentNode.__SS_text.length - 1; ix >= 0; ix--) {
+        var data = aBrowser.parentNode.__SS_text[ix];
+        if (!data.cache)
+          // update the text element's value before adding it to the data structure
+          data.cache = encodeURI(data.element.value);
+        text.push(data.id + "=" + data.cache);
+      }
+    }
+    if (aBrowser.currentURI.spec == "about:config")
+      text = ["#textbox=" + encodeURI(aBrowser.contentDocument.getElementById("textbox").
+                                               wrappedJSObject.value)];
+    if (text.length > 0)
+      aTabData.text = text.join(" ");
+    else if (aTabData.text)
+      delete aTabData.text;
+    
+    this._updateTextAndScrollDataForFrame(aWindow, aBrowser.contentWindow,
+                                          aTabData.entries[aTabData.index - 1]);
+  },
+
+  /**
+   * go through all subframes and store the current scroll positions
+   * and innerHTML content of WYSIWYG editors
+   * @param aWindow
+   *        Window reference
+   * @param aContent
+   *        frame reference
+   * @param aData
+   *        part of a tabData object to add the information to
+   */
+  _updateTextAndScrollDataForFrame:
+    function sss_updateTextAndScrollDataForFrame(aWindow, aContent, aData) {
+    for (var i = 0; i < aContent.frames.length; i++) {
+      if (aData.children && aData.children[i])
+        this._updateTextAndScrollDataForFrame(aWindow, aContent.frames[i], aData.children[i]);
+    }
+    // designMode is undefined e.g. for XUL documents (as about:config)
+    var isHTTPS = this._getURIFromString((aContent.parent || aContent).
+                                         document.location.href).schemeIs("https");
+    if ((aContent.document.designMode || "") == "on" && this._checkPrivacyLevel(isHTTPS)) {
+      if (aData.innerHTML === undefined) {
+        // we get no "input" events from iframes - listen for keypress here
+        var _this = this;
+        aContent.addEventListener("keypress", function(aEvent) {
+          _this.saveStateDelayed(aWindow, 3000); }, true);
+      }
+      aData.innerHTML = aContent.document.body.innerHTML;
+    }
+    aData.scroll = aContent.scrollX + "," + aContent.scrollY;
+   },
+
+  /**
    * store all hosts for a URL
    * @param aWindow
    *        Window reference
    */
   _updateCookieHosts: function sss_updateCookieHosts(aWindow) {
     var hosts = this._windows[aWindow.__SSi]._hosts = {};
     
     // get all possible subdomain levels for a given URL
@@ -1147,39 +1180,32 @@ SessionStoreService.prototype = {
    * Store window dimensions, visibility, sidebar
    * @param aWindow
    *        Window reference
    */
   _updateWindowFeatures: function sss_updateWindowFeatures(aWindow) {
     var winData = this._windows[aWindow.__SSi];
     
     WINDOW_ATTRIBUTES.forEach(function(aAttr) {
-      var value = this._getWindowDimension(aWindow, aAttr);
-      switch (aAttr) {
-        case "screenX":
-        case "screenY":
-          if (value != 0)
-            winData[aAttr] = value;
-          break;
-        default:
-          winData[aAttr] = value;
-      }
+      winData[aAttr] = this._getWindowDimension(aWindow, aAttr);
     }, this);
     
-    var hidden = [];
-    WINDOW_HIDEABLE_FEATURES.forEach(function(aItem) {
-      if (aWindow[aItem] && !aWindow[aItem].visible)
-        hidden.push(aItem);
+    var hidden = WINDOW_HIDEABLE_FEATURES.filter(function(aItem) {
+      return aWindow[aItem] && !aWindow[aItem].visible;
     });
     if (hidden.length != 0)
       winData.hidden = hidden.join(",");
+    else if (winData.hidden)
+      delete winData.hidden;
 
     var sidebar = aWindow.document.getElementById("sidebar-box").getAttribute("sidebarcommand");
     if (sidebar)
       winData.sidebar = sidebar;
+    else if (winData.sidebar)
+      delete winData.sidebar;
   },
 
   /**
    * serialize session data as Ini-formatted string
    * @returns string
    */
   _getCurrentState: function sss_getCurrentState() {
     var activeWindow = this._getMostRecentBrowserWindow();
--- a/browser/config/version.txt
+++ b/browser/config/version.txt
@@ -1,1 +1,1 @@
-3.0b2pre
+3.0b3pre
--- a/browser/locales/all-locales
+++ b/browser/locales/all-locales
@@ -1,11 +1,12 @@
+af
 ar
+be
 bg
-be
 ca
 cs
 da
 de
 el
 en-GB
 es-AR
 es-ES
@@ -28,16 +29,17 @@ lt
 mk
 mn
 nb-NO
 nl
 nn-NO
 pa-IN
 pl
 pt-BR
+pt-PT
 ro
 ru
 sk
 sl
 sq
 sv-SE
 tr
 uk
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -114,16 +114,17 @@
 <!ENTITY downloads.commandkey         "j">
 <!ENTITY downloadsUnix.commandkey     "y">
 <!ENTITY addons.label                 "Add-ons">
 <!ENTITY addons.tooltip               "Show and Manage installed Add-ons">
 <!ENTITY addons.accesskey             "A">
 
 <!ENTITY errorConsoleCmd.label        "Error Console">
 <!ENTITY errorConsoleCmd.accesskey    "C">
+<!ENTITY errorConsoleCmd.commandkey   "j">
 
 <!ENTITY fileMenu.label         "File"> 
 <!ENTITY fileMenu.accesskey       "F">
 <!ENTITY newNavigatorCmd.label        "New Window">
 <!ENTITY newNavigatorCmd.key        "N">
 <!ENTITY newNavigatorCmd.accesskey      "N">
 
 <!ENTITY editMenu.label         "Edit"> 
--- a/browser/locales/en-US/chrome/browser/places/bookmarkProperties.dtd
+++ b/browser/locales/en-US/chrome/browser/places/bookmarkProperties.dtd
@@ -10,14 +10,12 @@
 <!ENTITY bookmarks.createIn.label             "Create in:">
 <!ENTITY bookmarks.createIn.accesskey         "C">
 <!ENTITY bookmarks.feed_location.label        "Feed Location:">
 <!ENTITY bookmarks.feed_location.accesskey    "F">
 <!ENTITY bookmarks.site_location.label        "Site Location:">
 <!ENTITY bookmarks.site_location.accesskey    "S">
 <!ENTITY bookmarks.loadInSidebar.label        "Load this bookmark in the sidebar">
 <!ENTITY bookmarks.loadInSidebar.accesskey    "o">
-<!ENTITY bookmarks.bookmarksFolderItem.label  "Bookmarks">
-<!ENTITY bookmarks.toolbarFolderItem.label    "Bookmarks Toolbar">
 <!ENTITY bookmarks.expanderDown.tooltip       "Show all the bookmarks folders">
 <!ENTITY bookmarks.expanderUp.tooltip         "Hide">
 <!ENTITY bookmarks.newFolderButton.label      "New Folder">
 <!ENTITY bookmarks.newFolderButton.accesskey  "e">
--- a/browser/locales/en-US/chrome/browser/places/places.dtd
+++ b/browser/locales/en-US/chrome/browser/places/places.dtd
@@ -1,10 +1,11 @@
-<!ENTITY places.organizer.title  "Places Organizer">
-<!ENTITY organize.label          "Organize">
+<!-- LOCALIZATION NOTE (places.library.title): use "Library", "Archive" or "Repository" -->
+<!ENTITY places.library.title  "Library">
+<!ENTITY organize.label        "Organize">
 
 <!ENTITY file.accesskey                 "F">
 <!ENTITY file.close.label               "Close">
 <!ENTITY file.close.accesskey           "C">
 <!ENTITY cmd.close.key                  "w">
 <!ENTITY edit.label                     "Edit">
 <!ENTITY edit.accesskey                 "E">
 <!ENTITY views.label                    "Views">
--- a/browser/locales/en-US/chrome/browser/places/places.properties
+++ b/browser/locales/en-US/chrome/browser/places/places.properties
@@ -93,19 +93,27 @@ EnterExport=Export Bookmarks File
 saveSearch.title=Save Search
 saveSearch.inputLabel=Name:
 saveSearch.defaultText=New Query
 
 detailsPane.noItems=No items
 detailsPane.oneItem=One item
 detailsPane.multipleItems=%S items
 
-placesFolderTitle=Places
-recentlyCreatedBookmarksTitle=Recently Starred Pages
-recentlyVisitedBookmarksTitle=Recently Visited Starred Pages
-mostVisitedBookmarksTitle=Most Visited Starred Pages
-recentlyUsedTagsTitle=Recently Used Tags
-mostUsedTagsTitle=Most Used Tags
-mostVisitedSitesTitle=Most Visited Pages
+smartBookmarksFolderTitle=Smart Bookmarks
+mostVisitedTitle=Most Visited
+recentlyBookmarkedTitle=Recently Bookmarked
+recentTagsTitle=Recent Tags
 
 OrganizerQueryHistory=History
 OrganizerQueryDownloads=Downloads
 OrganizerQueryAllBookmarks=All Bookmarks
+
+# LOCALIZATION NOTE (tagResultLabel) :
+# This is what we use to form the label (for screen readers)
+# for url bar autocomplete results of type "tag"
+# See createResultLabel() in urlbarBindings.xml 
+tagResultLabel=Tag
+# LOCALIZATION NOTE (bookmarkResultLabel) :
+# This is what we use to form the label (for screen readers)
+# for url bar autocomplete results of type "bookmark"
+# See createResultLabel() in urlbarBindings.xml 
+bookmarkResultLabel=Bookmark
--- a/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
@@ -1,10 +1,9 @@
-<!-- Note: due to bug 143065, the only remaining accesskeys available to be used
-     in the Advanced pane are: "j", "o", "q", "z" -->
+<!-- Note: each tab panel must contain unique accesskeys -->
 
 <!ENTITY generalTab.label                "General">
 
 <!ENTITY accessibility.label             "Accessibility">
 
 <!ENTITY useCursorNavigation.label       "Always use the cursor keys to navigate within pages">
 <!ENTITY useCursorNavigation.accesskey   "c">
 <!ENTITY searchStartTyping.label         "Search for text when I start typing">
@@ -16,16 +15,22 @@
 
 <!ENTITY useAutoScroll.label             "Use autoscrolling">
 <!ENTITY useAutoScroll.accesskey         "a">
 <!ENTITY useSmoothScrolling.label        "Use smooth scrolling">
 <!ENTITY useSmoothScrolling.accesskey    "m">
 <!ENTITY checkSpelling.label             "Check my spelling as I type">
 <!ENTITY checkSpelling.accesskey         "t">
 
+<!ENTITY systemDefaults.label            "System Defaults">
+<!ENTITY alwaysCheckDefault.label        "Always check to see if &brandShortName; is the default browser on startup"><!--XXX-->
+<!ENTITY alwaysCheckDefault.accesskey    "w">
+<!ENTITY checkNow.label                  "Check Now">
+<!ENTITY checkNow.accesskey              "N">
+
 <!ENTITY networkTab.label                "Network">
 
 <!ENTITY connection.label                "Connection">
 
 <!ENTITY connectionDesc.label            "Configure how &brandShortName; connects to the Internet">
 <!ENTITY connectionSettings.label        "Settings…">
 <!ENTITY connectionSettings.accesskey    "e">
 
@@ -36,16 +41,17 @@
   line in preferences as follows:
 
   &useCacheBefore.label  [ textbox for cache size in MB ]   &useCacheAfter.label;
 -->
 <!ENTITY useCacheBefore.label            "Use up to">
 <!ENTITY useCacheBefore.accesskey        "U">
 <!ENTITY useCacheAfter.label             "MB of space for the cache">
 <!ENTITY clearCacheNow.label             "Clear Now">
+<!ENTITY clearCacheNow.accesskey         "C">
 
 <!ENTITY updateTab.label                 "Update">
 
 <!ENTITY autoCheck.label                 "Automatically check for updates to:">
 <!ENTITY enableAppUpdate.label           "&brandShortName;">
 <!ENTITY enableAppUpdate.accesskey       "F">
 <!ENTITY enableAddonsUpdate.label        "Installed Add-ons">
 <!ENTITY enableAddonsUpdate.accesskey    "n">
--- a/browser/locales/en-US/chrome/browser/preferences/main.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/main.dtd
@@ -25,22 +25,13 @@
 <!ENTITY saveTo.accesskey "v">
 <!ENTITY chooseFolderWin.label        "Browse…">
 <!ENTITY chooseFolderWin.accesskey    "o">
 <!ENTITY chooseFolderMac.label        "Choose…">
 <!ENTITY chooseFolderMac.accesskey    "e">
 <!ENTITY alwaysAsk.label "Always ask me where to save files">
 <!ENTITY alwaysAsk.accesskey "A">
 
-
-<!ENTITY systemDefaults.label  "System Defaults">
-
-<!ENTITY alwaysCheckDefault.label      "Always check to see if &brandShortName; is the default browser on startup"><!--XXX-->
-<!ENTITY alwaysCheckDefault.accesskey  "y">
-
-<!ENTITY checkNow.label             "Check Now">
-<!ENTITY checkNow.accesskey         "N">
-
-<!ENTITY addonsMgr.label            "Add-ons">
-<!ENTITY manageAddonsDesc.label     "Change options for your add-ons.">
-<!ENTITY manageAddonsDescUnix.label "Change preferences for your add-ons.">
-<!ENTITY manageAddons.label         "Manage Add-ons…">
-<!ENTITY manageAddons.accesskey     "M">
+<!ENTITY addonsMgr.label               "Add-ons">
+<!ENTITY manageAddonsDescWin.label     "Change options for your add-ons">
+<!ENTITY manageAddonsDescUnix2.label   "Change preferences for your add-ons">
+<!ENTITY manageAddons.label            "Manage Add-ons…">
+<!ENTITY manageAddons.accesskey        "M">
--- a/browser/locales/en-US/chrome/browser/preferences/preferences.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/preferences.dtd
@@ -1,16 +1,16 @@
 
 <!ENTITY  prefWindow.titleWin     "Options">
 <!ENTITY  prefWindow.titleGNOME   "&brandShortName; Preferences">
 <!-- When making changes to prefWindow.styleWin test both Windows Classic and
      Luna since widget heights are different based on the OS theme -->
-<!ENTITY  prefWin.styleWin        "width: 42em; min-height: 44em;">
-<!ENTITY  prefWin.styleMac        "width: 47em; min-height: 45em;">
-<!ENTITY  prefWin.styleGNOME      "width: 42em; min-height: 44.5em;">
+<!ENTITY  prefWin.styleWin2       "width: 42em; min-height: 39em;">
+<!ENTITY  prefWin.styleMac2       "width: 47em; min-height: 40em;">
+<!ENTITY  prefWin.styleGNOME2     "width: 42em; min-height: 39.5em;">
 
 <!ENTITY  paneMain.title          "Main">
 <!ENTITY  paneTabs.title          "Tabs">
 <!ENTITY  paneContent.title       "Content">
 <!ENTITY  paneApplications.title  "Applications">
 <!ENTITY  panePrivacy.title       "Privacy">
 <!ENTITY  paneSecurity.title      "Security">
 <!ENTITY  paneAdvanced.title      "Advanced">
--- a/browser/locales/en-US/chrome/browser/preferences/privacy.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/privacy.dtd
@@ -1,19 +1,19 @@
 <!ENTITY  history.label "History">
 
 <!-- LOCALIZATION NOTE:
-  The entities rememberBefore.label and rememberAfter.label appear on a single
+  The entities rememberDaysBefore.label and rememberDaysAfter.label appear on a single
   line in preferences as follows:
 
-  &rememberBefore.label  [ textbox for number of days ]   &rememberAfter.label;
+  &rememberDaysBefore.label  [ textbox for number of days ]   &rememberDaysAfter.label;
 -->
-<!ENTITY  rememberBefore.label          "Remember visited pages for the last">
-<!ENTITY  rememberBefore.accesskey      "v">
-<!ENTITY  rememberAfter.label           "days.">
+<!ENTITY  rememberDaysBefore.label      "Keep my history for at least">
+<!ENTITY  rememberDaysBefore.accesskey  "h">
+<!ENTITY  rememberDaysAfter.label       "days.">
 
 <!ENTITY  rememberForms.label           "Remember what I enter in forms and the search bar">
 <!ENTITY  rememberForms.accesskey       "f">
 
 <!ENTITY  rememberDownloads.label       "Remember what I've downloaded">
 <!ENTITY  rememberDownloads.accesskey   "d">
 
 
--- a/browser/locales/shipped-locales
+++ b/browser/locales/shipped-locales
@@ -1,22 +1,30 @@
 be
+ca
 cs
 de
 el
 en-US
+es-AR
 es-ES
+eu
 fi
 fr
 fy-NL
-gu-IN linux osx
+gu-IN
+he
+it
 ja linux win32
 ja-JP-mac osx
-ka
 ko
-lt
+nb-NO
 nl
+pa-IN
 pl
+pt-PT linux osx
+ro
 ru
 sk
 sv-SE
+tr
 uk
 zh-CN
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -376,16 +376,21 @@ menuitem[command="Browser:Stop"][disable
   list-style-image: url("moz-icon://stock/gtk-stop?size=menu&state=disabled");
 }
 
 menuitem[command="Browser:Reload"],
 #context-reload {
   list-style-image: url("moz-icon://stock/gtk-refresh?size=menu");
 }
 
+menuitem[command="Browser:Reload"][disabled],
+#context-reload[disabled] {
+  list-style-image: url("moz-icon://stock/gtk-refresh?size=menu&state=disabled");
+}
+
 menuitem[command="cmd_fullZoomEnlarge"] {
   list-style-image: url("moz-icon://stock/gtk-zoom-in?size=menu");
 }
 
 menuitem[command="cmd_fullZoomReduce"] {
   list-style-image: url("moz-icon://stock/gtk-zoom-out?size=menu");
 }
 
@@ -764,17 +769,16 @@ toolbar[iconsize="small"] #paste-button[
 #page-proxy-deck,
 #page-proxy-favicon,
 #page-proxy-button {
   width: 16px;
   height: 16px;
 }
 
 #page-proxy-deck {
-  cursor: -moz-grab;
   margin: 2px 3px;
 }
 
 #page-proxy-favicon {
   list-style-image: none;
 }
 
 #page-proxy-button {
@@ -792,17 +796,21 @@ toolbar[iconsize="small"] #paste-button[
   -moz-border-end: 1px solid ThreeDShadow;
 }
 
 #identity-icon-label {
   padding: 0 2px;
   margin: 0;
 }
 
-.unknownIdentity > #identity-icon-label {
+#identity-box.verifiedIdentity > hbox {
+  background-color: rgba(0, 255, 0, 0.25);
+}
+
+#identity-box.unknownIdentity > hbox > #identity-icon-label {
   display: none;
 }
 
 /* Identity popup icons */
 #identity-popup-icon {
   height: 64px;
   width: 64px;
   padding: 0;
@@ -838,33 +846,45 @@ toolbar[iconsize="small"] #paste-button[
 }
 
 /* Identity popup body text */
 #identity-popup-content-box > description,
 #identity-popup-encryption-label {
   white-space: -moz-pre-wrap;
   color: black;
   padding-left: 10px;
+  margin-left: 0;
+}
+
+#identity-popup-content-box > label {
+  white-space: -moz-pre-wrap;
+  margin-left: 0;
+  padding-left: 10px;
 }
 
 #identity-popup-content {
   padding-top: 5px;
   margin-bottom: 0;
   max-width: 200px;
 }
 
 .verifiedIdentity > #identity-popup-content,
 .verifiedDomain > #identity-popup-content {
   font-size: 140%;
   font-weight: bold;
   max-width: 300px;
 }
 
 #identity-popup-encryption {
-  margin: 10px 0;
+  padding: 10px 0;
+}
+
+.verifiedIdentity > #identity-popup-encryption,
+.verifiedDomain > #identity-popup-encryption {
+  margin-left: -18px;
 }
 
 .verifiedIdentity > #identity-popup-encryption > * > #identity-popup-encryption-icon,
 .verifiedDomain > #identity-popup-encryption > * > #identity-popup-encryption-icon {
   list-style-image: url("chrome://browser/skin/Secure.png");
   -moz-image-region: rect(0px, 18px, 18px, 0px);
 }
 
@@ -929,23 +949,16 @@ toolbar[iconsize="small"] #paste-button[
   -moz-image-region: rect(54px, 36px, 72px, 18px);
 }
 
 /* Autocomplete */
 #urlbar .autocomplete-textbox-container {
   -moz-box-align: stretch;
 }
 
-.autocomplete-treebody::-moz-tree-image(tag, treecolAutoCompleteValue),
-.autocomplete-treebody::-moz-tree-image(favicon, treecolAutoCompleteValue),
-.autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteValue) {
-  width: 16px;
-  height: 16px;
-}
-
 #treecolAutoCompleteImage {
   max-width : 36px; 
 }
 
 .ac-result-type-bookmark,
 .autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteImage) {
   list-style-image: url("chrome://browser/skin/places/pageStarred.png");
   width: 16px;
@@ -1130,20 +1143,16 @@ tabpanels {
   -moz-image-region: rect(0px, 16px, 16px, 0px);
 }
 
 .tabbrowser-tab[busy] > .tab-icon-image {
   list-style-image: url("chrome://global/skin/throbber/Throbber-small.gif") !important;
   opacity: 0.6;
 }
 
-.tabbrowser-tab[selected="true"] > .tab-icon-image {
-  cursor: -moz-grab;
-}
-
 .tabs-bottom {
   border-bottom: 1px solid threedshadow;
 }
 
 /* tabbrowser-tab focus ring */
 .tabbrowser-tab > .tab-text {
   border: 1px dotted transparent;
 }
--- a/browser/themes/gnomestripe/browser/jar.mn
+++ b/browser/themes/gnomestripe/browser/jar.mn
@@ -43,16 +43,17 @@ classic.jar:
   skin/classic/browser/places/starPage.png            (places/starPage.png)
   skin/classic/browser/places/tag.png                 (places/tag.png)
   skin/classic/browser/places/toolbarDropMarker.png   (places/toolbarDropMarker.png)
   skin/classic/browser/places/wrench.png              (places/wrench.png)
   skin/classic/browser/preferences/application.png    (preferences/application.png)
   skin/classic/browser/preferences/Options.png        (preferences/Options.png)
   skin/classic/browser/preferences/plugin.png         (preferences/plugin.png)
 * skin/classic/browser/preferences/preferences.css    (preferences/preferences.css)
+  skin/classic/browser/preferences/applications.css   (preferences/applications.css)
 #ifdef MOZ_SAFE_BROWSING
   skin/classic/browser/safebrowsing/browser-protection.css (safebrowsing/browser-protection.css)
   skin/classic/browser/safebrowsing/close16x16.png         (safebrowsing/close16x16.png)
   skin/classic/browser/safebrowsing/dim.png                (safebrowsing/dim.png)
   skin/classic/browser/safebrowsing/tail.png               (safebrowsing/tail.png)
   skin/classic/browser/safebrowsing/warning16x16.png       (safebrowsing/warning16x16.png)
   skin/classic/browser/safebrowsing/warning24x24.png       (safebrowsing/warning24x24.png)
 #endif
--- a/browser/themes/gnomestripe/browser/places/bookmarkProperties.css
+++ b/browser/themes/gnomestripe/browser/places/bookmarkProperties.css
@@ -42,18 +42,17 @@
   height: 16px;
 }
 
 .folder-icon > .menu-iconic-left {
   display: -moz-box;
 }
 
 .folder-icon {
-  list-style-image: url("chrome://global/skin/icons/folder-item.png") !important;
-  -moz-image-region: rect(0px, 32px, 16px, 16px) !important;
+  list-style-image: url("moz-icon://stock/gtk-directory?size=menu") !important;
 }
 
 /**** expander ****/
 #expander {
   min-width: 0;
 }
 
 .up {
--- a/browser/themes/gnomestripe/browser/places/editBookmarkOverlay.css
+++ b/browser/themes/gnomestripe/browser/places/editBookmarkOverlay.css
@@ -42,18 +42,17 @@
   height: 16px;
 }
 
 .folder-icon > .menu-iconic-left {
   display: -moz-box;
 }
 
 .folder-icon {
-  list-style-image: url("chrome://global/skin/icons/folder-item.png") !important;
-  -moz-image-region: rect(0px, 32px, 16px, 16px) !important;
+  list-style-image: url("moz-icon://stock/gtk-directory?size=menu") !important;
 }
 
 
 /**** expanders ****/
 
 .expander-up,
 .expander-down {
   min-width: 0;
--- a/browser/themes/gnomestripe/browser/places/organizer.css
+++ b/browser/themes/gnomestripe/browser/places/organizer.css
@@ -209,16 +209,38 @@
 }
 
 #debugPanel {
   background-color: ThreeDFace;
   border-top: 2px solid; 
   -moz-border-top-colors: ThreeDShadow ThreeDHighlight;
 }
 
+.advancedSearchMinus {
+  list-style-image: url("moz-icon://stock/gtk-remove?size=menu");
+}
+
+.advancedSearchPlus {
+  list-style-image: url("moz-icon://stock/gtk-add?size=menu");
+}
+
+.advancedSearchMinus .button-text,
+.advancedSearchPlus .button-text {
+  display: none;
+}
+
+.advancedSearchMinus .button-icon,
+.advancedSearchPlus .button-icon {
+  margin: 0 !important;
+}
+
+#saveSearch {
+  list-style-image: url("moz-icon://stock/gtk-save?size=menu");
+}
+
 /**** expanders ****/
 
 .expander-up,
 .expander-down {
   min-width: 0;
 }
 
 .expander-up {
@@ -289,16 +311,20 @@ menuitem[command="cmd_redo"] {
 menuitem[command="cmd_redo"][disabled] {
   list-style-image: url("moz-icon://stock/gtk-redo?size=menu&state=disabled");
 }
 
 menuitem[command="cmd_selectAll"] {
   list-style-image: url("moz-icon://stock/gtk-select-all?size=menu");
 }
 
+menuitem[command="cmd_selectAll"][disabled] {
+  list-style-image: url("moz-icon://stock/gtk-select-all?size=menu&state=disabled");
+}
+
 #orgClose {
   list-style-image: url("moz-icon://stock/gtk-close?size=menu");
 }
 
 menuitem[command="placesCmd_open:window"] {
   list-style-image: url("chrome://browser/skin/Toolbar-small.png");
   -moz-image-region: rect(0px 80px 16px 64px);
 }
new file mode 100644
--- /dev/null
+++ b/browser/themes/gnomestripe/browser/preferences/applications.css
@@ -0,0 +1,76 @@
+/* ***** 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 the Firefox Preferences System.
+ *
+ * The Initial Developer of the Original Code is Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2005
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Florian Queze <florian@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Line up the actions menu with action labels above and below it.
+ * Equalize the distance from the left side of the action box to the left side
+ * of the icon for both the menu and the non-menu versions of the action box.
+ * Also make sure the labels are the same distance away from the icons.
+ */
+.actionsMenu {
+  margin-top: -1px;
+  margin-bottom: -1px;
+  -moz-margin-start: -1px;
+  -moz-margin-end: 0;
+}
+
+.typeIcon,
+.actionIcon {
+  -moz-margin-start: 3px;
+  -moz-margin-end: 3px;
+}
+
+richlistitem label {
+  -moz-margin-start: 1px;
+  margin-top: 2px;
+}
+
+richlistitem {
+  min-height: 25px;
+}
+
+.actionsMenu .menulist-icon {
+  -moz-margin-end: 1px;
+}
+
+.actionsMenu > menupopup > menuitem > .menu-iconic-left {
+  -moz-padding-start: 0;
+  -moz-padding-end: 4px;
+}
+
+.actionsMenu > menupopup > menuitem {
+  -moz-padding-start: 3px;
+}
--- a/browser/themes/gnomestripe/browser/preferences/preferences.css
+++ b/browser/themes/gnomestripe/browser/preferences/preferences.css
@@ -170,26 +170,21 @@ filefield[disabled="true"] .fileFieldIco
   margin: 0px 3px 6px 3px !important;
 }
 
 /* Cookies Manager */
 #cookiesChildren::-moz-tree-image(domainCol) {
   width: 16px;
   height: 16px;
   margin: 0px 2px;
-  list-style-image: url("chrome://global/skin/icons/folder-item.png") !important;
-  -moz-image-region: rect(0px, 16px, 16px, 0px);
+  list-style-image: url("moz-icon://stock/gtk-file?size=menu");
 }
 
 #cookiesChildren::-moz-tree-image(domainCol, container) {
-  -moz-image-region: rect(0px, 32px, 16px, 16px);
-}
-
-#cookiesChildren::-moz-tree-image(domainCol, container, open) {
-  -moz-image-region: rect(16px, 32px, 32px, 16px);
+  list-style-image: url("moz-icon://stock/gtk-directory?size=menu");
 }
 
 #cookieInfoBox {
   border: 1px solid ThreeDShadow;
   -moz-border-radius: 0px;
   margin: 4px;
   padding: 0px;
 }
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -885,20 +885,16 @@ toolbar[iconsize="small"] #paste-button:
 #page-proxy-favicon,
 #page-proxy-button {
   width: 16px;
   height: 16px;
   margin: 0px;
   padding: 0px;
 }
 
-#page-proxy-deck {
-  cursor: -moz-grab;
-}
-
 #page-proxy-favicon {
   list-style-image: none;
 }
 
 #page-proxy-button {
   list-style-image: url("chrome://mozapps/skin/places/defaultFavicon.png");
 }
 
@@ -909,23 +905,16 @@ toolbar[iconsize="small"] #paste-button:
 
 
 statusbarpanel#statusbar-display {
   padding-left: 0;
 }
 
 /* ----- AUTOCOMPLETE ----- */
 
-.autocomplete-treebody::-moz-tree-image(favicon, treecolAutoCompleteValue),
-.autocomplete-treebody::-moz-tree-image(tag, treecolAutoCompleteValue),
-.autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteValue) {
-  width: 16px;
-  height: 16px;
-}
-
 #treecolAutoCompleteImage {
   max-width: 36px;
 }
 
 .ac-result-type-bookmark,
 .autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteImage) {
   list-style-image: url("chrome://browser/skin/places/pageStarred.png");
   width: 16px;
@@ -1196,20 +1185,16 @@ toolbarbutton.chevron > .toolbarbutton-m
   min-width: 1px !important;
   text-align: center;
 }
 
 .tabbrowser-tab[selected="true"] {
   -moz-user-focus: normal;
 }
 
-.tabbrowser-tab[selected="true"] > .tab-image-middle > .tab-icon {
-  cursor: -moz-grab;
-}
-
 .tabbrowser-tab > .tab-image-middle > .tab-text {
   border: 1.4pt solid transparent;
 }
 
 .tabbrowser-tab:focus > .tab-image-middle > .tab-text {
   border: 1.4pt solid -moz-mac-focusring;
 }
 
@@ -1637,36 +1622,36 @@ toolbarbutton.bookmark-item[dragover="tr
   background-color: white;
   opacity: 0.9;
 }
 
 #identity-box:hover {
   opacity: 1.0;
 }
 
-#identity-box.verifiedIdentity {
-  background-color: #BFA;
-}
-
 #urlbar[level="high"] > #identity-box,
 #urlbar[level="low"] > #identity-box {
   /* urlbar adds padding when security level is set, which we need to
   counteract here so that we still fill the background.  */
   margin: -2px;
   padding: 1px 2px 2px;
 }
 
 #identity-icon-label {
     padding: 2px 2px 0;
     margin: 0;
     color: black;
     vertical-align: middle;
 }
 
-.unknownIdentity > #identity-icon-label {
+#identity-box.verifiedIdentity {
+  background-color: #BFA;
+}
+
+#identity-box.unknownIdentity > hbox > #identity-icon-label {
     display: none;
 }
 
 /* Popup Icons */
 #identity-popup-icon {
     height: 64px;
     width: 64px;
     padding: 0;
@@ -1704,31 +1689,42 @@ toolbarbutton.bookmark-item[dragover="tr
 /* Popup Body Text */
 #identity-popup-content-box > description,
 #identity-popup-encryption-label {
     white-space: -moz-pre-wrap;
     color: black;
     padding-left: 10px;
 }
 
+#identity-popup-content-box > label {
+    white-space: -moz-pre-wrap;
+    margin-left: 0;
+    padding-left: 10px;
+}
+
 #identity-popup-content {
     padding-top: 5px;
     margin-bottom: 0;
     max-width: 200px;
 }
 
 .verifiedIdentity > #identity-popup-content,
 .verifiedDomain > #identity-popup-content {
    font-size: 140%;
    font-weight: bold;
    max-width: 300px;
 }
 
 #identity-popup-encryption {
-  margin: 10px 0;
+  padding: 10px 0;
+}
+
+.verifiedIdentity > #identity-popup-encryption,
+.verifiedDomain > #identity-popup-encryption {
+  margin-left: -18px;
 }
 
 .verifiedIdentity > #identity-popup-encryption > * > #identity-popup-encryption-icon,
 .verifiedDomain > #identity-popup-encryption > * >#identity-popup-encryption-icon {
   list-style-image: url("chrome://browser/skin/Secure.png");
   -moz-image-region: rect(0px, 18px, 18px, 0px);
 }
 
--- a/browser/themes/pinstripe/browser/jar.mn
+++ b/browser/themes/pinstripe/browser/jar.mn
@@ -68,16 +68,17 @@ classic.jar:
   skin/classic/browser/safebrowsing/tail.png                (safebrowsing/tail.png)
   skin/classic/browser/safebrowsing/warning16x16.png        (safebrowsing/warning16x16.png)
   skin/classic/browser/safebrowsing/warning24x24.png        (safebrowsing/warning24x24.png)
 #endif
   skin/classic/browser/preferences/application.png          (preferences/application.png)
   skin/classic/browser/preferences/Options.png              (preferences/Options.png)
   skin/classic/browser/preferences/plugin.png               (preferences/plugin.png)
   skin/classic/browser/preferences/preferences.css          (preferences/preferences.css)
+  skin/classic/browser/preferences/applications.css         (preferences/applications.css)
   skin/classic/browser/tabbrowser/alltabs-box-bkgnd.png                  (tabbrowser/alltabs-box-bkgnd.png)
   skin/classic/browser/tabbrowser/alltabs-box-overflow-bkgnd.png         (tabbrowser/alltabs-box-overflow-bkgnd.png)
   skin/classic/browser/tabbrowser/alltabs-box-overflow-bkgnd-animate.png (tabbrowser/alltabs-box-overflow-bkgnd-animate.png)
   skin/classic/browser/tabbrowser/tab-arrow-start.png                    (tabbrowser/tab-arrow-start.png)
   skin/classic/browser/tabbrowser/tab-arrow-start-bkgnd.png              (tabbrowser/tab-arrow-start-bkgnd.png)
   skin/classic/browser/tabbrowser/tab-arrow-start-bkgnd-animate.png      (tabbrowser/tab-arrow-start-bkgnd-animate.png)
   skin/classic/browser/tabbrowser/tab-arrow-end.png                      (tabbrowser/tab-arrow-end.png)
   skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd.png                (tabbrowser/tab-arrow-end-bkgnd.png)
new file mode 100644
--- /dev/null
+++ b/browser/themes/pinstripe/browser/preferences/applications.css
@@ -0,0 +1,71 @@
+/* ***** 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 the Firefox Preferences System.
+ *
+ * The Initial Developer of the Original Code is Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2005
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Florian Queze <florian@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Line up the actions menu with action labels above and below it.
+ * Equalize the distance from the left side of the action box to the left side
+ * of the icon for both the menu and the non-menu versions of the action box.
+ * Also make sure the labels are the same distance away from the icons.
+ */
+.actionsMenu {
+  -moz-margin-start: -2px;
+  margin-top: 0;
+  margin-bottom: -1px;
+}
+
+.typeIcon,
+.actionIcon {
+  -moz-margin-start: 3px;
+  -moz-margin-end: 3px;
+}
+
+richlistitem label {
+  -moz-margin-start: 1px;
+  margin-top: 2px;
+}
+
+richlistitem {
+  min-height: 22px;
+}
+
+.actionsMenu .menulist-icon {
+  -moz-margin-end: 1px;
+}
+
+.actionsMenu > menupopup > menuitem > .menu-iconic-left {
+  -moz-padding-start: 3px;
+  -moz-padding-end: 1px;
+}
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -908,17 +908,16 @@ toolbar[iconsize="small"] #paste-button:
 #page-proxy-deck,
 #page-proxy-favicon,
 #page-proxy-button {
   width: 16px;
   height: 16px;
 }
 
 #page-proxy-deck {
-  cursor: -moz-grab;
   margin: 2px 3px;
 }
 
 #page-proxy-favicon {
   list-style-image: none;
 }
 
 #page-proxy-button {
@@ -932,23 +931,16 @@ toolbar[iconsize="small"] #paste-button:
 
 
 statusbarpanel#statusbar-display {
   -moz-padding-start: 0;
 }
 
 /* ::::: autocomplete ::::: */
 
-.autocomplete-treebody::-moz-tree-image(favicon, treecolAutoCompleteValue),
-.autocomplete-treebody::-moz-tree-image(tag, treecolAutoCompleteValue),
-.autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteValue) {
-  width: 16px;
-  height: 16px;
-}
-
 #treecolAutoCompleteImage {
   max-width: 36px;
 }
 
 .ac-result-type-bookmark,
 .autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteImage) {
   list-style-image: url("chrome://browser/skin/places/pageStarred.png");
   width: 16px; 
@@ -1157,20 +1149,16 @@ toolbar[mode="text"] #navigator-throbber
 .tabbrowser-tab[selected="true"] {
   height: 24px;
   margin: 2px 0px 3px;
   padding: 1px;
   background: -moz-dialog url("chrome://browser/skin/tabbrowser/tab-active-bkgnd.png") repeat-x;
   font-weight: bold;
 }
 
-.tabbrowser-tab[selected="true"] > .tab-icon-image {
-  cursor: -moz-grab;
-}
-
 .tabbrowser-tab[busy] > .tab-icon-image {
   list-style-image: url("chrome://global/skin/throbber/Throbber-small.gif") !important;
   opacity: 0.6;
 }
 
 .tab-icon-image {
   margin-top: 1px;
   -moz-margin-start: 7px;
@@ -1668,30 +1656,30 @@ toolbarbutton.bookmark-item[dragover="tr
   -moz-appearance: toolbox;
   outline: 1px solid ThreeDShadow;
   -moz-margin-start: -1px;
   /* currently, the identity box is always LTR */
   -moz-outline-radius-topleft: 2px;
   -moz-outline-radius-bottomleft: 2px;
 }
 
-#identity-box.verifiedIdentity {
-  outline-color: highlight;
-}
-
 #identity-box:hover {
   outline-color: ThreeDDarkShadow;
 }
 
 #identity-icon-label {
   padding: 0 2px;
   margin: 0;
 }
 
-.unknownIdentity > #identity-icon-label {
+#identity-box.verifiedIdentity > hbox {
+  background-color: rgba(0, 255, 0, 0.25);
+}
+
+#identity-box.unknownIdentity > hbox > #identity-icon-label {
   display: none;
 }
 
 /* Popup Icons */
 #identity-popup-icon {
     height: 64px;
     width: 64px;
     padding: 0;
@@ -1727,33 +1715,45 @@ toolbarbutton.bookmark-item[dragover="tr
 }
 
 /* Popup Body Text */
 #identity-popup-content-box > description,
 #identity-popup-encryption-label {
     white-space: -moz-pre-wrap;
     color: black;
     padding-left: 10px;
+    margin-left: 0;
+}
+
+#identity-popup-content-box > label {
+    white-space: -moz-pre-wrap;
+    margin-left: 0;
+    padding-left: 10px;
 }
 
 #identity-popup-content {
     padding-top: 5px;
     margin-bottom: 0;
     max-width: 200px;
 }
 
 .verifiedIdentity > #identity-popup-content,
 .verifiedDomain > #identity-popup-content {
    font-size: 140%;
    font-weight: bold;
    max-width: 300px;
 }
 
 #identity-popup-encryption {
-  margin: 10px 0;
+  padding: 10px 0;
+}
+
+.verifiedIdentity > #identity-popup-encryption,
+.verifiedDomain > #identity-popup-encryption {
+  margin-left: -18px;
 }
 
 .verifiedIdentity > #identity-popup-encryption > * > #identity-popup-encryption-icon,
 .verifiedDomain > #identity-popup-encryption > * >#identity-popup-encryption-icon {
   list-style-image: url("chrome://browser/skin/Secure.png");
   -moz-image-region: rect(0px, 18px, 18px, 0px);
 }
 
--- a/browser/themes/winstripe/browser/jar.mn
+++ b/browser/themes/winstripe/browser/jar.mn
@@ -53,16 +53,17 @@ classic.jar:
         skin/classic/browser/safebrowsing/tail.png                    (safebrowsing/tail.png)
         skin/classic/browser/safebrowsing/warning16x16.png            (safebrowsing/warning16x16.png)
         skin/classic/browser/safebrowsing/warning24x24.png            (safebrowsing/warning24x24.png)
 #endif
         skin/classic/browser/preferences/application.png        (preferences/application.png)
         skin/classic/browser/preferences/Options.png            (preferences/Options.png)
         skin/classic/browser/preferences/plugin.png             (preferences/plugin.png)
         skin/classic/browser/preferences/preferences.css        (preferences/preferences.css)
+        skin/classic/browser/preferences/applications.css       (preferences/applications.css)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd.png           (tabbrowser/alltabs-box-overflow-end-bkgnd.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png   (tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png     (tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd.png         (tabbrowser/alltabs-box-overflow-start-bkgnd.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png (tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png)        
         skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png   (tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png)
         skin/classic/browser/tabbrowser/tab-arrow-end.png                  (tabbrowser/tab-arrow-end.png)
         skin/classic/browser/tabbrowser/tab-arrow-start.png                (tabbrowser/tab-arrow-start.png)
new file mode 100644
--- /dev/null
+++ b/browser/themes/winstripe/browser/preferences/applications.css
@@ -0,0 +1,76 @@
+/* ***** 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 the Firefox Preferences System.
+ *
+ * The Initial Developer of the Original Code is Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2005
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Florian Queze <florian@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/**
+ * Line up the actions menu with action labels above and below it.
+ * Equalize the distance from the left side of the action box to the left side
+ * of the icon for both the menu and the non-menu versions of the action box.
+ * Also make sure the labels are the same distance away from the icons.
+ */
+.actionsMenu {
+  margin-top: 0;
+  margin-bottom: 0;
+  -moz-margin-start: -2px;
+  -moz-margin-end: 0;
+}
+
+.typeIcon,
+.actionIcon {
+  -moz-margin-start: 3px;
+  -moz-margin-end: 3px;
+}
+
+richlistitem label {
+  -moz-margin-start: 1px;
+  margin-top: 2px;
+}
+
+richlistitem {
+  min-height: 22px;
+}
+
+.actionsMenu .menulist-icon {
+  -moz-margin-end: 3px;
+}
+
+.actionsMenu > menupopup > menuitem > .menu-iconic-left {
+  -moz-padding-start: 0px;
+  -moz-padding-end: 2px;
+}
+
+.actionsMenu > menupopup > menuitem {
+  -moz-padding-start: 4px;
+}
--- a/build/autoconf/nspr.m4
+++ b/build/autoconf/nspr.m4
@@ -30,32 +30,47 @@ AC_ARG_WITH(nspr-exec-prefix,
 		if test -z "$NSPR_CONFIG"; then
 			NSPR_CONFIG=$nspr_config_prefix/bin/nspr-config
 		fi
 	fi
 
 	unset ac_cv_path_NSPR_CONFIG
 	AC_PATH_PROG(NSPR_CONFIG, nspr-config, no)
 	min_nspr_version=ifelse([$1], ,4.0.0,$1)
-	AC_MSG_CHECKING(for NSPR - version >= $min_nspr_version (skipping))
+	AC_MSG_CHECKING(for NSPR - version >= $min_nspr_version)
 
 	no_nspr=""
 	if test "$NSPR_CONFIG" = "no"; then
 		no_nspr="yes"
 	else
 		NSPR_CFLAGS=`$NSPR_CONFIG $nspr_config_args --cflags`
 		NSPR_LIBS=`$NSPR_CONFIG $nspr_config_args --libs`
 
-		dnl Skip version check for now
 		nspr_config_major_version=`$NSPR_CONFIG $nspr_config_args --version | \
 			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
 		nspr_config_minor_version=`$NSPR_CONFIG $nspr_config_args --version | \
 			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
 		nspr_config_micro_version=`$NSPR_CONFIG $nspr_config_args --version | \
 			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
+		min_nspr_major_version=`echo $min_nspr_version | \
+			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
+		min_nspr_minor_version=`echo $min_nspr_version | \
+			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
+		min_nspr_micro_version=`echo $min_nspr_version | \
+			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
+		if test "$nspr_config_major_version" -ne "$min_nspr_major_version"; then
+			no_nspr="yes"
+		elif test "$nspr_config_major_version" -eq "$min_nspr_major_version" &&
+		     test "$nspr_config_minor_version" -lt "$min_nspr_minor_version"; then
+			no_nspr="yes"
+		elif test "$nspr_config_major_version" -eq "$min_nspr_major_version" &&
+		     test "$nspr_config_minor_version" -eq "$min_nspr_minor_version" &&
+		     test "$nspr_config_micro_version" -lt "$min_nspr_micro_version"; then
+			no_nspr="yes"
+		fi
 	fi
 
 	if test -z "$no_nspr"; then
 		AC_MSG_RESULT(yes)
 		ifelse([$2], , :, [$2])     
 	else
 		AC_MSG_RESULT(no)
 	fi
--- a/build/autoconf/nss.m4
+++ b/build/autoconf/nss.m4
@@ -30,32 +30,47 @@ AC_ARG_WITH(nss-exec-prefix,
 		if test -z "$NSS_CONFIG"; then
 			NSS_CONFIG=$nss_config_prefix/bin/nss-config
 		fi
 	fi
 
 	unset ac_cv_path_NSS_CONFIG
 	AC_PATH_PROG(NSS_CONFIG, nss-config, no)
 	min_nss_version=ifelse([$1], ,3.0.0,$1)
-	AC_MSG_CHECKING(for NSS - version >= $min_nss_version (skipping))
+	AC_MSG_CHECKING(for NSS - version >= $min_nss_version)
 
 	no_nss=""
 	if test "$NSS_CONFIG" = "no"; then
 		no_nss="yes"
 	else
 		NSS_CFLAGS=`$NSS_CONFIG $nss_config_args --cflags`
 		NSS_LIBS=`$NSS_CONFIG $nss_config_args --libs`
 
-		dnl Skip version check for now
 		nss_config_major_version=`$NSS_CONFIG $nss_config_args --version | \
 			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
 		nss_config_minor_version=`$NSS_CONFIG $nss_config_args --version | \
 			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
 		nss_config_micro_version=`$NSS_CONFIG $nss_config_args --version | \
 			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
+		min_nss_major_version=`echo $min_nss_version | \
+			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
+		min_nss_minor_version=`echo $min_nss_version | \
+			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
+		min_nss_micro_version=`echo $min_nss_version | \
+			sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
+		if test "$nss_config_major_version" -lt "$min_nss_major_version"; then
+			no_nss="yes"
+		elif test "$nss_config_major_version" -eq "$min_nss_major_version" &&
+		     test "$nss_config_minor_version" -lt "$min_nss_minor_version"; then
+			no_nss="yes"
+		elif test "$nss_config_major_version" -eq "$min_nss_major_version" &&
+		     test "$nss_config_minor_version" -eq "$min_nss_minor_version" &&
+		     test "$nss_config_micro_version" -lt "$min_nss_micro_version"; then
+			no_nss="yes"
+		fi
 	fi
 
 	if test -z "$no_nss"; then
 		AC_MSG_RESULT(yes)
 		ifelse([$2], , :, [$2])     
 	else
 		AC_MSG_RESULT(no)
 	fi
--- a/build/package/mac_osx/pkg-dmg
+++ b/build/package/mac_osx/pkg-dmg
@@ -49,16 +49,17 @@ B<pkg-dmg> - Mac OS X disk image (.dmg) 
 B<pkg-dmg>
 B<--source> I<source-folder>
 B<--target> I<target-image>
 [B<--format> I<format>]
 [B<--volname> I<volume-name>]
 [B<--tempdir> I<temp-dir>]
 [B<--mkdir> I<directory>]
 [B<--copy> I<source>[:I<dest>]]
+[B<--symlink> I<source>[:I<dest>]]
 [B<--license> I<file>]
 [B<--resource> I<file>]
 [B<--icon> I<icns-file>]
 [B<--attribute> I<a>:I<file>[:I<file>...]
 [B<--idme>]
 [B<--sourcefile>]
 [B<--verbosity> I<level>]
 [B<--dry-run>]
@@ -87,16 +88,18 @@ overwritten.  If I<target-image> already
 it will be used unmodified.  If no extension is present, or the extension
 is incorrect for the selected format, the proper extension will be added.
 See B<--format>.
 
 ==item B<--format> I<format>
 
 The format to create the disk image in.  Valid values for I<format> are:
      - UDZO - zlib-compressed, read-only; extension I<.dmg>
+     - UDBZ - bzip2-compressed, read-only; extension I<.dmg>;
+              create and use on 10.4 ("Tiger") and later only
      - UDRW - read-write; extension I<.dmg>
      - UDSP - read-write, sparse; extension I<.sparseimage>
 
 UDZO is the default format.
 
 See L<hdiutil(1)> for a description of these formats.
 
 =item B<--volname> I<volume-name>
@@ -127,27 +130,35 @@ specified, I<source> is copied to the lo
 otherwise, I<source> is copied to the root of the new volume.  B<--copy>
 provides a way to package up a I<source-folder> by adding files to it
 without modifying the original I<source-folder>.  B<--copy> may appear
 multiple times.
 
 This option is useful for adding .DS_Store files and window backgrounds
 to disk images.
 
+=item B<--symlink> I<source>[:I<dest>]
+
+Like B<--copy>, but allows symlinks to point out of the volume. Empty symlink
+destinations are interpreted as "like the source path, but inside the dmg"
+
+This option is useful for adding symlinks to external resources,
+e.g. to /Applications.
+
 =item B<--license> I<file>
 
 A plain text file containing a license agreement to be displayed before
 the disk image is mounted.  English is the only supported language.  To
 include license agreements in other languages, in multiple languages,
 or to use formatted text, prepare a resource and use L<--resource>.
 
 =item B<--resource> I<file>
 
-A resource file to merge into I<target-image>.  If I<format> is UDZO,
-the disk image will be flattened to a single-fork file that contains
+A resource file to merge into I<target-image>.  If I<format> is UDZO or
+UDBZ, the disk image will be flattened to a single-fork file that contains
 the resource but may be freely transferred without any special encodings.
 I<file> must be in a format suitable for L<Rez(1)>.  See L<Rez(1)> for a
 description of the format, and L<hdiutil(1)> for a discussion on flattened
 disk images.  B<--resource> may appear multiple times.
 
 This option is useful for adding license agreements and other messages
 to disk images.
 
@@ -230,16 +241,17 @@ is to create images which consume a mini
 
 =head1 EXAMPLE
 
 pkg-dmg --source /Applications/DeerPark.app --target ~/DeerPark.dmg
   --sourcefile --volname DeerPark --icon ~/DeerPark.icns
   --mkdir /.background
   --copy DeerParkBackground.png:/.background/background.png
   --copy DeerParkDSStore:/.DS_Store
+  --symlink /Applications:"/Drag to here"
 
 =head1 REQUIREMENTS
 
 I<pkg-dmg> has been tested with Mac OS X releases 10.2 ("Jaguar")
 through 10.4 ("Tiger").  Certain adjustments to behavior are made
 depending on the host system's release.  Mac OS X 10.3 ("Panther") or
 later are recommended.
 
@@ -265,19 +277,21 @@ use Getopt::Long;
 sub argumentEscape(@);
 sub cleanupDie($);
 sub command(@);
 sub commandInternal($@);
 sub commandInternalVerbosity($$@);
 sub commandOutput(@);
 sub commandOutputVerbosity($@);
 sub commandVerbosity($@);
+sub copyFiles($@);
 sub diskImageMaker($$$$$$$$);
 sub giveExtension($$);
 sub hdidMountImage($@);
+sub isFormatCompressed($);
 sub licenseMaker($$);
 sub pathSplit($);
 sub setAttributes($@);
 sub trapSignal($);
 sub usage();
 
 # Variables used as globals
 my(@gCleanup, %gConfig, $gDarwinMajor, $gDryRun, $gVerbosity);
@@ -399,19 +413,19 @@ else {
   # have a chance to make a difference.
   #
   # Now, if someone wanted to document some of these private formats...
   print STDERR ($0.": warning, not running on Mac OS X, ".
    "this could be interesting.\n");
 }
 
 # Non-global variables used in Getopt
-my(@attributes, @copyFiles, $iconFile, $idme, $licenseFile, @makeDirs,
- $outputFormat, @resourceFiles, $sourceFile, $sourceFolder, $targetImage,
- $tempDir, $volumeName);
+my(@attributes, @copyFiles, @createSymlinks, $iconFile, $idme, $licenseFile,
+ @makeDirs, $outputFormat, @resourceFiles, $sourceFile, $sourceFolder,
+ $targetImage, $tempDir, $volumeName);
 
 # --format
 $outputFormat = 'UDZO';
 
 # --idme
 $idme = 0;
 
 # --sourcefile
@@ -428,16 +442,17 @@ delete $ENV{'NEXT_ROOT'};
 Getopt::Long::Configure('pass_through');
 GetOptions('source=s'    => \$sourceFolder,
            'target=s'    => \$targetImage,
            'volname=s'   => \$volumeName,
            'format=s'    => \$outputFormat,
            'tempdir=s'   => \$tempDir,
            'mkdir=s'     => \@makeDirs,
            'copy=s'      => \@copyFiles,
+           'symlink=s'   => \@createSymlinks,
            'license=s'   => \$licenseFile,
            'resource=s'  => \@resourceFiles,
            'icon=s'      => \$iconFile,
            'attribute=s' => \@attributes,
            'idme'        => \$idme,
            'sourcefile'  => \$sourceFile,
            'verbosity=i' => \$gVerbosity,
            'dry-run'     => \$gDryRun,
@@ -566,63 +581,48 @@ if(@makeDirs) {
       push(@tempDirsToMake, $tempRoot.'/'.$makeDir);
     }
   }
   if(command($gConfig{'cmd_mkdir'}, '-p', @tempDirsToMake) != 0) {
     cleanupDie('mkdir failed');
   }
 }
 
-my($copyFile);
-foreach $copyFile (@copyFiles) {
-  my($copySource, $copyDestination);
-  ($copySource, $copyDestination) = split(/:/, $copyFile);
-  if(!defined($copyDestination)) {
-    $copyDestination = $tempRoot;
-  }
-  elsif($copyDestination =~ /^\//) {
-    $copyDestination = $tempRoot.$copyDestination;
-  }
-  else {
-    $copyDestination = $tempRoot.'/'.$copyDestination;
-  }
-  if(command($gConfig{'cmd_rsync'}, '-a', '--copy-unsafe-links',
-   $copySource, $copyDestination) != 0) {
-    cleanupDie('rsync failed for item copy');
-  }
-}
+# copy files and/or create symlinks
+copyFiles($tempRoot, 'copy', @copyFiles);
+copyFiles($tempRoot, 'symlink', @createSymlinks);
 
 if($gConfig{'create_directly'}) {
   # If create_directly is false, the contents will be rsynced into a
   # disk image and they would lose their attributes.
   setAttributes($tempRoot, @attributes);
 }
 
 if(defined($iconFile)) {
   if(command($gConfig{'cmd_rsync'}, '-a', '--copy-unsafe-links', $iconFile,
    $tempRoot.'/.VolumeIcon.icns') != 0) {
     cleanupDie('rsync failed for volume icon');
   }
 
   # It's pointless to set the attributes of the root when diskutil create
   # -srcfolder is being used.  In that case, the attributes will be set
   # later, after the image is already created.
-  if($outputFormat eq 'UDZO' &&
+  if(isFormatCompressed($outputFormat) &&
    (command($gConfig{'cmd_SetFile'}, '-a', 'C', $tempRoot) != 0)) {
     cleanupDie('SetFile failed');
   }
 }
 
 if(command($gConfig{'cmd_chmod'}, '-R', 'a+rX,a-st,u+w,go-w',
  $tempRoot) != 0) {
   cleanupDie('chmod failed');
 }
 
 my($unflattenable);
-if($outputFormat eq 'UDZO') {
+if(isFormatCompressed($outputFormat)) {
   $unflattenable = 1;
 }
 else {
   $unflattenable = 0;
 }
 
 diskImageMaker($tempRoot, $targetImage, $outputFormat, $volumeName,
  $tempSubdir, $tempMount, $targetImageFilename, defined($iconFile));
@@ -722,47 +722,61 @@ sub cleanupDie($) {
 sub command(@) {
   my(@arguments);
   @arguments = @_;
   return commandVerbosity($gVerbosity,@arguments);
 }
 
 # commandInternal($command, @arguments)
 #
-# Removes the files specified by @arguments with a verbosity level specified
-# by $gVerbosity.
+# Runs the specified internal command at the verbosity level defined by
+# $gVerbosity.
+# Returns zero(!) on failure, because commandInternal is supposed to be a
+# direct replacement for the Perl system call wrappers, which, unlike shell
+# commands and C equivalent system calls, return true (instead of 0) to
+# indicate success.
 sub commandInternal($@) {
   my(@arguments, $command);
   ($command, @arguments) = @_;
   return commandInternalVerbosity($gVerbosity, $command, @arguments);
 }
 
 # commandInternalVerbosity($verbosity, $command, @arguments)
 #
 # Run an internal command, printing a bogus command invocation message if
 # $verbosity is true.
 #
 # If $command is unlink:
 # Removes the files specified by @arguments.  Wraps unlink.
 #
-# If $command is mkdir:
-# Creates the directory specified by @arguments, with an optional mask
-# argument, wrapping mkdir.
+# If $command is symlink:
+# Creates the symlink specified by @arguments. Wraps symlink.
 sub commandInternalVerbosity($$@) {
   my(@arguments, $command, $verbosity);
   ($verbosity, $command, @arguments) = @_;
   if($command eq 'unlink') {
     if($verbosity || $gDryRun) {
       print(join(' ', 'rm', '-f', argumentEscape(@arguments))."\n");
     }
     if($gDryRun) {
       return $#arguments+1;
     }
     return unlink(@arguments);
   }
+  elsif($command eq 'symlink') {
+    if($verbosity || $gDryRun) {
+      print(join(' ', 'ln', '-s', argumentEscape(@arguments))."\n");
+    }
+    if($gDryRun) {
+      return 1;
+    }
+    my($source, $target);
+    ($source, $target) = @arguments;
+    return symlink($source, $target);
+  }
 }
 
 # commandOutput(@arguments)
 #
 # Runs the specified command at the verbosity level defined by $gVerbosity.
 # Output is returned in an array of lines.  undef is returned on failure.
 # The exit status is available in $?.
 sub commandOutput(@) {
@@ -844,33 +858,76 @@ sub commandVerbosity($@) {
   my(@arguments, $verbosity);
   ($verbosity, @arguments) = @_;
   if(!defined(commandOutputVerbosity($verbosity, @arguments))) {
     return -1;
   }
   return $?;
 }
 
+# copyFiles($tempRoot, $method, @arguments)
+#
+# Copies files or create symlinks in the disk image.
+# See --copy and --symlink descriptions for details.
+# If $method is 'copy', @arguments are interpreted as source:target, if $method
+# is 'symlink', @arguments are interpreted as symlink:target.
+sub copyFiles($@) {
+  my(@fileList, $method, $tempRoot);
+  ($tempRoot, $method, @fileList) = @_;
+  my($file, $isSymlink);
+  $isSymlink = ($method eq 'symlink');
+  foreach $file (@fileList) {
+    my($source, $target);
+    ($source, $target) = split(/:/, $file);
+    if(!defined($target) and $isSymlink) {
+      # empty symlink targets would result in an invalid target and fail,
+      # but they shall be interpreted as "like source path, but inside dmg"
+      $target = $source;
+    }
+    if(!defined($target)) {
+      $target = $tempRoot;
+    }
+    elsif($target =~ /^\//) {
+      $target = $tempRoot.$target;
+    }
+    else {
+      $target = $tempRoot.'/'.$target;
+    }
+
+    my($success);
+    if($isSymlink) {
+      $success = commandInternal('symlink', $source, $target);
+    }
+    else {
+      $success = !command($gConfig{'cmd_rsync'}, '-a', '--copy-unsafe-links',
+                          $source, $target);
+    }
+    if(!$success) {
+      cleanupDie('copyFiles failed for method '.$method);
+    }
+  }
+}
+
 # diskImageMaker($source, $destination, $format, $name, $tempDir, $tempMount,
 #  $baseName, $setRootIcon)
 #
 # Creates a disk image in $destination of format $format corresponding to the
 # source directory $source.  $name is the volume name.  $tempDir is a good
 # place to write temporary files, which should be empty (aside from the other
 # things that this script might create there, like stage and mount).
 # $tempMount is a mount point for temporary disk images.  $baseName is the
 # name of the disk image, and is presently unused.  $setRootIcon is true if
 # a volume icon was added to the staged $source and indicates that the
 # custom volume icon bit on the volume root needs to be set.
 sub diskImageMaker($$$$$$$$) {
   my($baseName, $destination, $format, $name, $setRootIcon, $source,
    $tempDir, $tempMount);
   ($source, $destination, $format, $name, $tempDir, $tempMount,
    $baseName, $setRootIcon) = @_;
-  if($format eq 'UDZO') {
+  if(isFormatCompressed($format)) {
     my($uncompressedImage);
 
     if($gConfig{'makehybrid'}) {
       my($hybridImage);
       $hybridImage = giveExtension($tempDir.'/hybrid', '.dmg');
 
       if(command($gConfig{'cmd_hdiutil'}, 'makehybrid', '-hfs',
        '-hfs-volume-name', $name, '-hfs-openfolder', $source, '-ov',
@@ -937,52 +994,57 @@ sub diskImageMaker($$$$$$$$) {
 
         if(commandInternal('unlink', $hybridImage) != 1) {
           cleanupDie('unlink hybridImage failed: '.$!);
         }
       }
     }
     else {
       # makehybrid is not available, fall back to making a UDRW and
-      # converting to UDZO.  It ought to be possible to do a UDZO directly,
-      # but those come out far too large (journaling?) and need to be
-      # read-write to fix up the volume icon anyway.  Luckily, we can
-      # take advantage of a single call back into this function.
+      # converting to a compressed image.  It ought to be possible to
+      # create a compressed image directly, but those come out far too
+      # large (journaling?) and need to be read-write to fix up the
+      # volume icon anyway.  Luckily, we can take advantage of a single
+      # call back into this function.
       my($udrwImage);
       $udrwImage = giveExtension($tempDir.'/udrw', '.dmg');
 
       diskImageMaker($source, $udrwImage, 'UDRW', $name, $tempDir,
        $tempMount, $baseName, $setRootIcon);
 
       # The call back into diskImageMaker already removed $source.
 
       $uncompressedImage = $udrwImage;
     }
 
     # The uncompressed disk image is now in its final form.  Compress it.
     # Jaguar doesn't support hdiutil convert -ov, but it always allows
     # overwriting.
-    if(command($gConfig{'cmd_hdiutil'}, 'convert', '-format', 'UDZO',
-     '-imagekey', 'zlib-level=9', 
+    # bzip2-compressed UDBZ images can only be created and mounted on 10.4
+    # and later.  The bzip2-level imagekey is only effective when creating
+    # images in 10.5.  In 10.4, bzip2-level is harmlessly ignored, and the
+    # default value of 1 is always used.
+    if(command($gConfig{'cmd_hdiutil'}, 'convert', '-format', $format,
+     '-imagekey', ($format eq 'UDBZ' ? 'bzip2-level=9' : 'zlib-level=9'),
      (defined($gDarwinMajor) && $gDarwinMajor <= 6 ? () : ('-ov')),
      $uncompressedImage, '-o', $destination) != 0) {
       cleanupDie('hdiutil convert failed');
     }
 
     # $uncompressedImage is going to be unlinked before anything else can
     # fail.  splice in this form is the same as pop/push.
     splice(@gCleanup, -1, 1,
      sub {commandInternalVerbosity(0, 'unlink', $destination);});
 
     if(commandInternal('unlink', $uncompressedImage) != 1) {
       cleanupDie('unlink uncompressedImage failed: '.$!);
     }
 
-    # At this point, the only thing that the UDZO block has added to the
-    # cleanup stack is the removal of $destination.  $source has already
+    # At this point, the only thing that the compressed block has added to
+    # the cleanup stack is the removal of $destination.  $source has already
     # been removed, and its cleanup entry has been removed as well.
   }
   elsif($format eq 'UDRW' || $format eq 'UDSP') {
     my(@extraArguments);
     if(!$gConfig{'partition_table'}) {
       @extraArguments = ('-layout', 'NONE');
     }
 
@@ -1242,16 +1304,26 @@ sub hdidMountImage($@) {
   if(defined($rootDevice) && $rootDevice ne '') {
     # Failing anyway, so don't care about failure
     commandVerbosity(0, $gConfig{'cmd_diskutil'}, 'eject', $rootDevice);
   }
 
   return undef;
 }
 
+# isFormatCompressed($format)
+#
+# Returns true if $format corresponds to a compressed disk image format.
+# Returns false otherwise.
+sub isFormatCompressed($) {
+  my($format);
+  ($format) = @_;
+  return $format eq 'UDZO' || $format eq 'UDBZ';
+}
+
 # licenseMaker($text, $resource)
 #
 # Takes a plain text file at path $text and creates a license agreement
 # resource containing the text at path $license.  English-only, and
 # no special formatting.  This is the bare-bones stuff.  For more
 # intricate license agreements, create your own resource.
 #
 # ftp://ftp.apple.com/developer/Development_Kits/SLAs_for_UDIFs_1.0.dmg
@@ -1425,23 +1497,24 @@ sub trapSignal($) {
   ($signalName) = @_;
   cleanupDie('exiting on SIG'.$signalName);
 }
 
 sub usage() {
   print STDERR (
 "usage: pkg-dmg --source <source-folder>\n".
 "               --target <target-image>\n".
-"              [--format <format>]        (default: UDZO)\n".
-"              [--volname <volume-name>]  (default: same name as source)\n".
-"              [--tempdir <temp-dir>]     (default: same dir as target)\n".
-"              [--mkdir <directory>]      (make directory in image)\n".
-"              [--copy <source>[:<dest>]] (extra files to add)\n".
-"              [--license <file>]         (plain text license agreement)\n".
-"              [--resource <file>]        (flat .r files to merge)\n".
-"              [--icon <icns-file>]       (volume icon)\n".
-"              [--attribute <a>:<file>]   (set file attributes)\n".
-"              [--idme]                   (make an Internet-enabled image)\n".
-"              [--sourcefile]             (treat --source as a file)\n".
-"              [--verbosity <level>]      (0, 1, 2; default=2)\n".
-"              [--dry-run]                (print what would be done)\n");
+"              [--format <format>]           (default: UDZO)\n".
+"              [--volname <volume-name>]     (default: same name as source)\n".
+"              [--tempdir <temp-dir>]        (default: same dir as target)\n".
+"              [--mkdir <directory>]         (make directory in image)\n".
+"              [--copy <source>[:<dest>]]    (extra files to add)\n".
+"              [--symlink <source>[:<dest>]] (extra symlinks to add)\n".
+"              [--license <file>]            (plain text license agreement)\n".
+"              [--resource <file>]           (flat .r files to merge)\n".
+"              [--icon <icns-file>]          (volume icon)\n".
+"              [--attribute <a>:<file>]      (set file attributes)\n".
+"              [--idme]                      (make Internet-enabled image)\n".
+"              [--sourcefile]                (treat --source as a file)\n".
+"              [--verbosity <level>]         (0, 1, 2; default=2)\n".
+"              [--dry-run]                   (print what would be done)\n");
   return;
 }
--- a/caps/include/nsScriptSecurityManager.h
+++ b/caps/include/nsScriptSecurityManager.h
@@ -404,18 +404,21 @@ private:
     static JSBool JS_DLL_CALLBACK
     CheckObjectAccess(JSContext *cx, JSObject *obj,
                       jsval id, JSAccessMode mode,
                       jsval *vp);
 
     // Returns null if a principal cannot be found; generally callers
     // should error out at that point.
     static nsIPrincipal*
-    doGetObjectPrincipal(JSContext *cx, JSObject *obj,
-                         PRBool aAllowShortCircuit = PR_FALSE);
+    doGetObjectPrincipal(JSContext *cx, JSObject *obj
+#ifdef DEBUG
+                         , PRBool aAllowShortCircuit = PR_TRUE
+#endif
+                         );
 
     // Returns null if a principal cannot be found.  Note that rv can be NS_OK
     // when this happens -- this means that there was no JS running.
     nsIPrincipal*
     doGetSubjectPrincipal(nsresult* rv);
     
     static nsresult 
     ReportError(JSContext* cx, const nsAString& messageTag,
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -52,16 +52,18 @@
 #include "nsNullPrincipal.h"
 #include "nsXPIDLString.h"
 #include "nsCRT.h"
 #include "nsCRTGlue.h"
 #include "nsIJSContextStack.h"
 #include "nsDOMError.h"
 #include "nsDOMCID.h"
 #include "jsdbgapi.h"
+#include "jsarena.h"
+#include "jsfun.h"
 #include "nsIXPConnect.h"
 #include "nsIXPCSecurityManager.h"
 #include "nsTextFormatter.h"
 #include "nsIStringBundle.h"
 #include "nsNetUtil.h"
 #include "nsIProperties.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsIFile.h"
@@ -91,16 +93,24 @@
 
 static NS_DEFINE_CID(kZipReaderCID, NS_ZIPREADER_CID);
 
 nsIIOService    *nsScriptSecurityManager::sIOService = nsnull;
 nsIXPConnect    *nsScriptSecurityManager::sXPConnect = nsnull;
 nsIStringBundle *nsScriptSecurityManager::sStrBundle = nsnull;
 JSRuntime       *nsScriptSecurityManager::sRuntime   = 0;
 
+// Info we need about the JSClasses used by XPConnects wrapped
+// natives, to avoid having to QI to nsIXPConnectWrappedNative all the
+// time when doing security checks.
+static const JSClass *sXPCWrappedNativeJSClass;
+static JSGetObjectOps sXPCWrappedNativeGetObjOps1;
+static JSGetObjectOps sXPCWrappedNativeGetObjOps2;
+
+
 ///////////////////////////
 // Convenience Functions //
 ///////////////////////////
 // Result of this function should not be freed.
 static inline const PRUnichar *
 JSValIDToString(JSContext *cx, const jsval idval)
 {
     JSAutoRequest ar(cx);
@@ -1870,17 +1880,17 @@ nsScriptSecurityManager::GetCertificateP
     NS_ENSURE_ARG(!aCertFingerprint.IsEmpty() &&
                   !aSubjectName.IsEmpty() &&
                   aCertificate);
 
     return DoGetCertificatePrincipal(aCertFingerprint, aSubjectName,
                                      aPrettyName, aCertificate, aURI, PR_TRUE,
                                      result);
 }
-    
+
 nsresult
 nsScriptSecurityManager::DoGetCertificatePrincipal(const nsACString& aCertFingerprint,
                                                    const nsACString& aSubjectName,
                                                    const nsACString& aPrettyName,
                                                    nsISupports* aCertificate,
                                                    nsIURI* aURI,
                                                    PRBool aModifyTable,
                                                    nsIPrincipal **result)
@@ -2281,78 +2291,148 @@ nsScriptSecurityManager::GetObjectPrinci
     if (!*result)
         return NS_ERROR_FAILURE;
     NS_ADDREF(*result);
     return NS_OK;
 }
 
 // static
 nsIPrincipal*
-nsScriptSecurityManager::doGetObjectPrincipal(JSContext *aCx, JSObject *aObj,
-                                              PRBool aAllowShortCircuit)
+nsScriptSecurityManager::doGetObjectPrincipal(JSContext *aCx, JSObject *aObj
+#ifdef DEBUG
+                                              , PRBool aAllowShortCircuit
+#endif
+                                              )
 {
     NS_ASSERTION(aCx && aObj, "Bad call to doGetObjectPrincipal()!");
     nsIPrincipal* result = nsnull;
 
 #ifdef DEBUG
     JSObject* origObj = aObj;
 #endif
     
-    do
-    {
-        const JSClass *jsClass = JS_GetClass(aCx, aObj);
-
-        if (jsClass && !(~jsClass->flags & (JSCLASS_HAS_PRIVATE |
-                                            JSCLASS_PRIVATE_IS_NSISUPPORTS)))
-        {
-            // No need to refcount |priv| here.
-            nsISupports *priv = (nsISupports *)JS_GetPrivate(aCx, aObj);
-
-            /*
-             * If it's a wrapped native (as most
-             * JSCLASS_PRIVATE_IS_NSISUPPORTS objects are in mozilla),
-             * check the underlying native instead.
-             */
-            nsCOMPtr<nsIXPConnectWrappedNative> xpcWrapper =
-                do_QueryInterface(priv);
-
-            if (NS_LIKELY(xpcWrapper != nsnull))
-            {
-                if (NS_UNLIKELY(aAllowShortCircuit))
-                {
-                    result = xpcWrapper->GetObjectPrincipal();
+    const JSClass *jsClass = JS_GET_CLASS(aCx, aObj);
+
+    // A common case seen in this code is that we enter this function
+    // with aObj being a Function object, whose parent is a Call
+    // object. Neither of those have object principals, so we can skip
+    // those objects here before we enter the below loop. That way we
+    // avoid wasting time checking properties of their classes etc in
+    // the loop.
+
+    if (jsClass == &js_FunctionClass) {
+        aObj = JS_GetParent(aCx, aObj);
+
+        if (!aObj)
+            return nsnull;
+
+        jsClass = JS_GET_CLASS(aCx, aObj);
+
+        if (jsClass == &js_CallClass) {
+            aObj = JS_GetParent(aCx, aObj);
+
+            if (!aObj)
+                return nsnull;
+
+            jsClass = JS_GET_CLASS(aCx, aObj);
+        }
+    }
+
+    do {
+        // Note: jsClass is set before this loop, and also at the
+        // *end* of this loop.
+
+        // NOTE: These class and getObjectOps hook checks better match
+        // what IS_WRAPPER_CLASS() does in xpconnect!
+        if (jsClass == sXPCWrappedNativeJSClass ||
+            jsClass->getObjectOps == sXPCWrappedNativeGetObjOps1 ||
+            jsClass->getObjectOps == sXPCWrappedNativeGetObjOps2) {
+            nsIXPConnectWrappedNative *xpcWrapper =
+                (nsIXPConnectWrappedNative *)JS_GetPrivate(aCx, aObj);
+
+            if (xpcWrapper) {
+                nsISupports *native = xpcWrapper->Native();
+                char ch = jsClass->name[0];
+
+                // XXXjst: Ideally this code would simply call into
+                // xpcWrapper->GetObjectPrincipal() and use that if we
+                // find a principal through that. If not, we can fall
+                // back to the below code. See bug 317240.
+
+                // For classes that are unlikely to be window object
+                // classes (Window, ModalContentWindow, and
+                // ChromeWindow), check if the native pointer is an
+                // nsINode. Note that this is merely a performance
+                // optimization, so missing this optimization is
+                // non-critical and must result in us finding the same
+                // principal that we would have gotten by asking the
+                // nsINode here.
+                if (ch != 'W' && ch != 'M' && ch != 'C'
+#ifdef DEBUG
+                    && aAllowShortCircuit
+#endif
+                    ) {
+                    nsCOMPtr<nsINode> node = do_QueryInterface(native);
+
+                    if (node) {
+                        result = node->NodePrincipal();
+
+                        // NodePrincipal() *always* returns a
+                        // principal.
+
+                        break;
+                    }
                 }
-                else
-                {
-                    nsCOMPtr<nsIScriptObjectPrincipal> objPrin;
-                    objPrin = do_QueryWrappedNative(xpcWrapper);
-                    if (objPrin)
-                    {
-                        result = objPrin->GetPrincipal();
-                    }                    
+
+                // If not, check if it points to an
+                // nsIScriptObjectPrincipal
+                nsCOMPtr<nsIScriptObjectPrincipal> objPrin =
+                    do_QueryInterface(native);
+                if (objPrin) {
+                    result = objPrin->GetPrincipal();
+
+                    if (result) {
+                        break;
+                    }
                 }
             }
-            else
-            {
-                nsCOMPtr<nsIScriptObjectPrincipal> objPrin;
-                objPrin = do_QueryInterface(priv);
-                if (objPrin)
-                {
-                    result = objPrin->GetPrincipal();
+        } else if (!(~jsClass->flags & (JSCLASS_HAS_PRIVATE |
+                                        JSCLASS_PRIVATE_IS_NSISUPPORTS))) {
+            nsISupports *priv = (nsISupports *)JS_GetPrivate(aCx, aObj);
+
+#ifdef DEBUG
+            if (aAllowShortCircuit) {
+                nsCOMPtr<nsIXPConnectWrappedNative> xpcWrapper =
+                    do_QueryInterface(priv);
+
+                NS_ASSERTION(!xpcWrapper,
+                             "Uh, an nsIXPConnectWrappedNative with the "
+                             "wrong JSClass or getObjectOps hooks!");
+            }
+#endif
+
+            nsCOMPtr<nsIScriptObjectPrincipal> objPrin =
+                do_QueryInterface(priv);
+
+            if (objPrin) {
+                result = objPrin->GetPrincipal();
+
+                if (result) {
+                    break;
                 }
             }
-
-            if (result)
-            {
-                break;
-            }
         }
 
         aObj = JS_GetParent(aCx, aObj);
-    } while (aObj);
+
+        if (!aObj)
+            break;
+
+        jsClass = JS_GET_CLASS(aCx, aObj);
+    } while (1);
 
     NS_ASSERTION(!aAllowShortCircuit ||
                  result == doGetObjectPrincipal(aCx, origObj, PR_FALSE),
                  "Principal mismatch.  Not good");
     
     return result;
 }
 
@@ -3227,16 +3307,20 @@ nsresult nsScriptSecurityManager::Init()
     rv = runtimeService->GetRuntime(&sRuntime);
     NS_ENSURE_SUCCESS(rv, rv);
 
 #ifdef DEBUG
     JSCheckAccessOp oldCallback =
 #endif
         JS_SetCheckObjectAccessCallback(sRuntime, CheckObjectAccess);
 
+    sXPConnect->GetXPCWrappedNativeJSClassInfo(&sXPCWrappedNativeJSClass,
+                                               &sXPCWrappedNativeGetObjOps1,
+                                               &sXPCWrappedNativeGetObjOps2);
+
     // For now, assert that no callback was set previously
     NS_ASSERTION(!oldCallback, "Someone already set a JS CheckObjectAccess callback");
     return NS_OK;
 }
 
 static nsScriptSecurityManager *gScriptSecMan = nsnull;
 
 jsval nsScriptSecurityManager::sEnabledID   = JSVAL_VOID;
--- a/config/milestone.txt
+++ b/config/milestone.txt
@@ -5,9 +5,9 @@
 #    x.x.x.x
 #    x.x.x+
 #
 # Referenced by milestone.pl.
 # Hopefully I'll be able to automate replacement of *all*
 # hardcoded milestones in the tree from these two files.
 #--------------------------------------------------------
 
-1.9b2pre
+1.9b3pre
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -2168,16 +2168,8 @@ endif
 
 documentation:
 	@cd $(DEPTH)
 	$(DOXYGEN) $(DEPTH)/config/doxygen.cfg
 
 check:: $(SUBMAKEFILES) $(MAKE_DIRS)
 	+$(LOOP_OVER_DIRS)
 	+$(LOOP_OVER_TOOL_DIRS)
-
-check-interactive:: $(SUBMAKEFILES) $(MAKE_DIRS)
-	+$(LOOP_OVER_DIRS)
-	+$(LOOP_OVER_TOOL_DIRS)
-
-check-one:: $(SUBMAKEFILES) $(MAKE_DIRS)
-	+$(LOOP_OVER_DIRS)
-	+$(LOOP_OVER_TOOL_DIRS)
--- a/configure.in
+++ b/configure.in
@@ -5471,17 +5471,17 @@ done
 
 dnl ========================================================
 dnl Image decoders
 dnl ========================================================
 case "$MOZ_WIDGET_TOOLKIT" in
 beos|windows|os2|mac|cocoa)
     ;;
 *)
-    if test -z "$MOZ_ENABLE_GNOMEUI"; then
+    if test -z "$MOZ_ENABLE_GTK2"; then
        MOZ_IMG_DECODERS_DEFAULT=`echo $MOZ_IMG_DECODERS_DEFAULT | sed -e 's|icon||'`                
     fi
     ;;
 esac
 
 MOZ_ARG_ENABLE_STRING(image-decoders,
 [  --enable-image-decoders[={mod1,mod2,default,all,none}]
                           Enable specific image decoders],
@@ -6959,16 +6959,17 @@ if test "$MOZ_SVG" -o "$MOZ_ENABLE_CANVA
        if test "$MOZ_WIDGET_TOOLKIT" = "windows"; then
            WIN32_SURFACE_FEATURE="#define CAIRO_HAS_WIN32_SURFACE 1"
            WIN32_FONT_FEATURE="#define CAIRO_HAS_WIN32_FONT 1"
            PDF_SURFACE_FEATURE="#define CAIRO_HAS_PDF_SURFACE 1"
        fi
        if test "$MOZ_WIDGET_TOOLKIT" = "os2"; then
            OS2_SURFACE_FEATURE="#define CAIRO_HAS_OS2_SURFACE 1"
            FT_FONT_FEATURE="#define CAIRO_HAS_FT_FONT 1"
+           PDF_SURFACE_FEATURE="#define CAIRO_HAS_PDF_SURFACE 1"
            MOZ_ENABLE_CAIRO_FT=1
            CAIRO_FT_CFLAGS="-I${MZFTCFGFT2}/include"
            CAIRO_FT_LIBS="-L${MZFTCFGFT2}/lib -lmozft -lmzfntcfg"
        fi
        if test "$MOZ_ENABLE_GLITZ"; then
            GLITZ_SURFACE_FEATURE="#define CAIRO_HAS_GLITZ_SURFACE 1"
        fi
        if test "$MOZ_WIDGET_TOOLKIT" = "beos"; then
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -87,21 +87,22 @@ class nsIHTMLCSSStyleSheet;
 class nsILayoutHistoryState;
 class nsIVariant;
 class nsIDOMUserDataHandler;
 template<class E> class nsCOMArray;
 class nsIDocumentObserver;
 class nsBindingManager;
 class nsIDOMNodeList;
 class mozAutoSubtreeModified;
+struct JSObject;
 
 // IID for the nsIDocument interface
 #define NS_IDOCUMENT_IID      \
-{ 0xc7f56e99, 0x5538, 0x4841, \
-  { 0x97, 0x39, 0x43, 0x6e, 0x6d, 0x26, 0x95, 0x12 } }
+{ 0xed21686d, 0x4e2f, 0x41f5, \
+  { 0x94, 0xaa, 0xcc, 0x1f, 0xbd, 0xfa, 0x1f, 0x84 } }
 
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 //------------------------------------------