Merge the last green changeset on mozilla-inbound to mozilla-central
authorEhsan Akhgari <ehsan@mozilla.com>
Fri, 15 Jul 2011 08:13:08 -0400
changeset 72864 9349ae9094f6d3e725e70a8020a1f017b9ceb1c8
parent 72863 b5c5e025368d2159cc46acd8140d37ccba2ced9c (current diff)
parent 72824 037f02f89d5bc2ee302499b19ee87a4a95f9dd60 (diff)
child 72865 7749420447fa3df5a5b4cb336dda9b9dfdbf9ff6
child 72888 373edcdacf30f274a3a35293460178a9e136910d
push id20776
push usereakhgari@mozilla.com
push dateFri, 15 Jul 2011 12:13:35 +0000
treeherdermozilla-central@9349ae9094f6 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone8.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge the last green changeset on mozilla-inbound to mozilla-central
browser/base/content/test/tabview/browser_tabview_bug625666.js
content/events/src/nsEventStateManager.cpp
content/html/content/src/nsHTMLImageElement.cpp
dom/base/nsGlobalWindow.cpp
dom/interfaces/base/nsIDOMWindowInternal.idl
dom/interfaces/storage/nsIDOMStorageWindow.idl
services/sync/tests/unit/head_appinfo.js.in
testing/mochitest/browser-test.js
toolkit/components/startup/nsAppStartup.cpp
widget/src/windows/nsWindow.cpp
--- a/accessible/src/atk/nsApplicationAccessibleWrap.cpp
+++ b/accessible/src/atk/nsApplicationAccessibleWrap.cpp
@@ -50,17 +50,17 @@
 #include "nsAccessibilityService.h"
 #include "AtkSocketAccessible.h"
 
 #include <gtk/gtk.h>
 #include <atk/atk.h>
 
 typedef GType (* AtkGetTypeType) (void);
 GType g_atk_hyperlink_impl_type = G_TYPE_INVALID;
-static PRBool sATKChecked = PR_FALSE;
+static bool sATKChecked = false;
 static PRLibrary *sATKLib = nsnull;
 static const char sATKLibName[] = "libatk-1.0.so.0";
 static const char sATKHyperlinkImplGetTypeSymbol[] =
     "atk_hyperlink_impl_get_type";
 static const char sAccEnv [] = "GNOME_ACCESSIBILITY";
 static const char sSysPrefService [] =
     "@mozilla.org/system-preference-service;1";
 static const char sAccessibilityKey [] =
@@ -95,33 +95,37 @@ static guint add_listener (GSignalEmissi
                            const gchar *hook_data,
                            guint gail_listenerid = 0);
 static AtkKeyEventStruct *atk_key_event_from_gdk_event_key(GdkEventKey *key);
 static gboolean notify_hf(gpointer key, gpointer value, gpointer data);
 static void insert_hf(gpointer key, gpointer value, gpointer data);
 static gint mai_key_snooper(GtkWidget *the_widget, GdkEventKey *event,
                             gpointer func_data);
 
-static GHashTable *listener_list = NULL;
-static gint listener_idx = 1;
+static GHashTable* sListener_list = NULL;
+static gint sListener_idx = 1;
 
 #define MAI_TYPE_UTIL              (mai_util_get_type ())
 #define MAI_UTIL(obj)              (G_TYPE_CHECK_INSTANCE_CAST ((obj), \
                                     MAI_TYPE_UTIL, MaiUtil))
 #define MAI_UTIL_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), \
                                     MAI_TYPE_UTIL, MaiUtilClass))
 #define MAI_IS_UTIL(obj)           (G_TYPE_CHECK_INSTANCE_TYPE ((obj), \
                                     MAI_TYPE_UTIL))
 #define MAI_IS_UTIL_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), \
                                     MAI_TYPE_UTIL))
 #define MAI_UTIL_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), \
                                     MAI_TYPE_UTIL, MaiUtilClass))
 
-static GHashTable *key_listener_list = NULL;
-static guint key_snooper_id = 0;
+static GHashTable* sKey_listener_list = NULL;
+static guint sKey_snooper_id = 0;
+static GQuark sQuark_gecko_acc_obj = g_quark_from_static_string("GeckoAccObj");
+static bool sToplevel_event_hook_added = false;
+static gulong sToplevel_show_hook = 0;
+static gulong sToplevel_hide_hook = 0;
 
 G_BEGIN_DECLS
 typedef void (*GnomeAccessibilityInit) (void);
 typedef void (*GnomeAccessibilityShutdown) (void);
 G_END_DECLS
 
 struct MaiUtil
 {
@@ -218,26 +222,32 @@ mai_util_get_type(void)
     return type;
 }
 
 static void
 window_added (AtkObject *atk_obj,
               guint     index,
               AtkObject *child)
 {
-  guint id =  g_signal_lookup ("create", MAI_TYPE_ATK_OBJECT);
+  if (!IS_MAI_OBJECT(child))
+      return;
+
+  static guint id =  g_signal_lookup ("create", MAI_TYPE_ATK_OBJECT);
   g_signal_emit (child, id, 0);
 }
 
 static void
 window_removed (AtkObject *atk_obj,
                 guint     index,
                 AtkObject *child)
 {
-  guint id =  g_signal_lookup ("destroy", MAI_TYPE_ATK_OBJECT);
+  if (!IS_MAI_OBJECT(child))
+      return;
+
+  static guint id =  g_signal_lookup ("destroy", MAI_TYPE_ATK_OBJECT);
   g_signal_emit (child, id, 0);
 }
 
 /* intialize the the atk interface (function pointers) with MAI implementation.
  * When atk bridge get loaded, these interface can be used.
  */
 static void
 mai_util_class_init(MaiUtilClass *klass)
@@ -259,18 +269,18 @@ mai_util_class_init(MaiUtilClass *klass)
     atk_class->remove_global_event_listener =
         mai_util_remove_global_event_listener;
     atk_class->add_key_event_listener = mai_util_add_key_event_listener;
     atk_class->remove_key_event_listener = mai_util_remove_key_event_listener;
     atk_class->get_root = mai_util_get_root;
     atk_class->get_toolkit_name = mai_util_get_toolkit_name;
     atk_class->get_toolkit_version = mai_util_get_toolkit_version;
 
-    listener_list = g_hash_table_new_full(g_int_hash, g_int_equal, NULL,
-                                          _listener_info_destroy);
+    sListener_list = g_hash_table_new_full(g_int_hash, g_int_equal, NULL,
+                                           _listener_info_destroy);
     // Keep track of added/removed windows.
     AtkObject *root = atk_get_root ();
     g_signal_connect (root, "children-changed::add", (GCallback) window_added, NULL);
     g_signal_connect (root, "children-changed::remove", (GCallback) window_removed, NULL);
 }
 
 static guint
 mai_util_add_global_event_listener(GSignalEmissionHook listener,
@@ -284,17 +294,17 @@ mai_util_add_global_event_listener(GSign
     if (split_string) {
         if (!strcmp ("window", split_string[0])) {
             guint gail_listenerid = 0;
             if (gail_add_global_event_listener) {
                 // call gail's function to track gtk native window events
                 gail_listenerid =
                     gail_add_global_event_listener(listener, event_type);
             }
-            
+
             rc = add_listener (listener, "MaiAtkObject", split_string[1],
                                event_type, gail_listenerid);
         }
         else {
             rc = add_listener (listener, split_string[1], split_string[2],
                                event_type);
         }
         g_strfreev(split_string);
@@ -305,32 +315,32 @@ mai_util_add_global_event_listener(GSign
 static void
 mai_util_remove_global_event_listener(guint remove_listener)
 {
     if (remove_listener > 0) {
         MaiUtilListenerInfo *listener_info;
         gint tmp_idx = remove_listener;
 
         listener_info = (MaiUtilListenerInfo *)
-            g_hash_table_lookup(listener_list, &tmp_idx);
+            g_hash_table_lookup(sListener_list, &tmp_idx);
 
         if (listener_info != NULL) {
             if (gail_remove_global_event_listener &&
                 listener_info->gail_listenerid) {
               gail_remove_global_event_listener(listener_info->gail_listenerid);
             }
-            
+
             /* Hook id of 0 and signal id of 0 are invalid */
             if (listener_info->hook_id != 0 && listener_info->signal_id != 0) {
                 /* Remove the emission hook */
                 g_signal_remove_emission_hook(listener_info->signal_id,
                                               listener_info->hook_id);
 
                 /* Remove the element from the hash */
-                g_hash_table_remove(listener_list, &tmp_idx);
+                g_hash_table_remove(sListener_list, &tmp_idx);
             }
             else {
                 g_warning("Invalid listener hook_id %ld or signal_id %d\n",
                           listener_info->hook_id, listener_info->signal_id);
             }
         }
         else {
             // atk-bridge is initialized with gail (e.g. yelp)
@@ -361,24 +371,24 @@ atk_key_event_from_gdk_event_key (GdkEve
         break;
     default:
         g_assert_not_reached ();
         return NULL;
     }
     event->state = key->state;
     event->keyval = key->keyval;
     event->length = key->length;
-    if (key->string && key->string [0] && 
+    if (key->string && key->string [0] &&
         (key->state & GDK_CONTROL_MASK ||
          g_unichar_isgraph (g_utf8_get_char (key->string)))) {
         event->string = key->string;
     }
     else if (key->type == GDK_KEY_PRESS ||
              key->type == GDK_KEY_RELEASE) {
-        event->string = gdk_keyval_name (key->keyval);	    
+        event->string = gdk_keyval_name (key->keyval);
     }
     event->keycode = key->hardware_keycode;
     event->timestamp = key->time;
 
     MAI_LOG_DEBUG(("MaiKey:\tsym %u\n\tmods %x\n\tcode %u\n\ttime %lx\n",
                    (unsigned int) event->keyval,
                    (unsigned int) event->state,
                    (unsigned int) event->keycode,
@@ -404,19 +414,19 @@ insert_hf(gpointer key, gpointer value, 
 
 static gint
 mai_key_snooper(GtkWidget *the_widget, GdkEventKey *event, gpointer func_data)
 {
     /* notify each AtkKeySnoopFunc in turn... */
 
     MaiKeyEventInfo *info = g_new0(MaiKeyEventInfo, 1);
     gint consumed = 0;
-    if (key_listener_list) {
+    if (sKey_listener_list) {
         GHashTable *new_hash = g_hash_table_new(NULL, NULL);
-        g_hash_table_foreach (key_listener_list, insert_hf, new_hash);
+        g_hash_table_foreach (sKey_listener_list, insert_hf, new_hash);
         info->key_event = atk_key_event_from_gdk_event_key (event);
         info->func_data = func_data;
         consumed = g_hash_table_foreach_steal (new_hash, notify_hf, info);
         g_hash_table_destroy (new_hash);
         g_free(info->key_event);
     }
     g_free(info);
     return (consumed ? 1 : 0);
@@ -425,39 +435,39 @@ mai_key_snooper(GtkWidget *the_widget, G
 static guint
 mai_util_add_key_event_listener (AtkKeySnoopFunc listener,
                                  gpointer data)
 {
     NS_ENSURE_TRUE(listener, 0);
 
     static guint key=0;
 
-    if (!key_listener_list) {
-        key_listener_list = g_hash_table_new(NULL, NULL);
-        key_snooper_id = gtk_key_snooper_install(mai_key_snooper, data);
+    if (!sKey_listener_list) {
+        sKey_listener_list = g_hash_table_new(NULL, NULL);
+        sKey_snooper_id = gtk_key_snooper_install(mai_key_snooper, data);
     }
     AtkKeySnoopFuncPointer atkKeySnoop;
     atkKeySnoop.func_ptr = listener;
-    g_hash_table_insert(key_listener_list, GUINT_TO_POINTER (key++),
+    g_hash_table_insert(sKey_listener_list, GUINT_TO_POINTER (key++),
                         atkKeySnoop.data);
     return key;
 }
 
 static void
 mai_util_remove_key_event_listener (guint remove_listener)
 {
-    if (!key_listener_list) {
+    if (!sKey_listener_list) {
         // atk-bridge is initialized with gail (e.g. yelp)
         // try gail_remove_key_event_listener
         return gail_remove_key_event_listener(remove_listener);
     }
 
-    g_hash_table_remove(key_listener_list, GUINT_TO_POINTER (remove_listener));
-    if (g_hash_table_size(key_listener_list) == 0) {
-        gtk_key_snooper_remove(key_snooper_id);
+    g_hash_table_remove(sKey_listener_list, GUINT_TO_POINTER (remove_listener));
+    if (g_hash_table_size(sKey_listener_list) == 0) {
+        gtk_key_snooper_remove(sKey_snooper_id);
     }
 }
 
 AtkObject *
 mai_util_get_root(void)
 {
     if (nsAccessibilityService::IsShutdown()) {
         // We've shutdown, try to use gail instead
@@ -507,31 +517,31 @@ add_listener (GSignalEmissionHook listen
     gint rc = 0;
 
     type = g_type_from_name(object_type);
     if (type) {
         signal_id = g_signal_lookup(signal, type);
         if (signal_id > 0) {
             MaiUtilListenerInfo *listener_info;
 
-            rc = listener_idx;
+            rc = sListener_idx;
 
             listener_info =  (MaiUtilListenerInfo *)
                 g_malloc(sizeof(MaiUtilListenerInfo));
-            listener_info->key = listener_idx;
+            listener_info->key = sListener_idx;
             listener_info->hook_id =
                 g_signal_add_emission_hook(signal_id, 0, listener,
                                            g_strdup(hook_data),
                                            (GDestroyNotify)g_free);
             listener_info->signal_id = signal_id;
             listener_info->gail_listenerid = gail_listenerid;
 
-            g_hash_table_insert(listener_list, &(listener_info->key),
+            g_hash_table_insert(sListener_list, &(listener_info->key),
                                 listener_info);
-            listener_idx++;
+            sListener_idx++;
         }
         else {
             g_warning("Invalid signal type %s\n", signal);
         }
     }
     else {
         g_warning("Invalid object type %s\n", object_type);
     }
@@ -549,16 +559,59 @@ nsApplicationAccessibleWrap::nsApplicati
 }
 
 nsApplicationAccessibleWrap::~nsApplicationAccessibleWrap()
 {
     MAI_LOG_DEBUG(("======Destory AppRootAcc=%p\n", (void*)this));
     nsAccessibleWrap::ShutdownAtkObject();
 }
 
+static gboolean
+toplevel_event_watcher(GSignalInvocationHint* ihint,
+                       guint                  n_param_values,
+                       const GValue*          param_values,
+                       gpointer               data)
+{
+  if (nsAccessibilityService::IsShutdown())
+    return TRUE;
+
+  GObject* object = reinterpret_cast<GObject*>(g_value_get_object(param_values));
+  if (!GTK_IS_WINDOW(object))
+    return TRUE;
+
+  AtkObject* child = gtk_widget_get_accessible(GTK_WIDGET(object));
+
+  // GTK native dialog
+  if (!IS_MAI_OBJECT(child) &&
+      (atk_object_get_role(child) == ATK_ROLE_DIALOG)) {
+
+    if (data == reinterpret_cast<gpointer>(nsIAccessibleEvent::EVENT_SHOW)) {
+
+      // Attach the dialog accessible to app accessible tree
+      nsAccessible* windowAcc = GetAccService()->AddNativeRootAccessible(child);
+      g_object_set_qdata(G_OBJECT(child), sQuark_gecko_acc_obj,
+                         reinterpret_cast<gpointer>(windowAcc));
+
+    } else {
+
+      // Deattach the dialog accessible
+      nsAccessible* windowAcc =
+        reinterpret_cast<nsAccessible*>
+                        (g_object_get_qdata(G_OBJECT(child), sQuark_gecko_acc_obj));
+      if (windowAcc) {
+        GetAccService()->RemoveNativeRootAccessible(windowAcc);
+        g_object_set_qdata(G_OBJECT(child), sQuark_gecko_acc_obj, NULL);
+      }
+
+    }
+  }
+
+  return TRUE;
+}
+
 PRBool
 nsApplicationAccessibleWrap::Init()
 {
     // XXX following code is copied from widget/src/gtk2/nsWindow.cpp
     // we should put it to somewhere that can be used from both modules
     // see bug 390761
 
     // check if accessibility enabled/disabled by environment variable
@@ -597,24 +650,44 @@ nsApplicationAccessibleWrap::Init()
         // load and initialize atk-bridge library
         rv = LoadGtkModule(sAtkBridge);
         if (NS_SUCCEEDED(rv)) {
             // init atk-bridge
             (*sAtkBridge.init)();
         }
         else
             MAI_LOG_DEBUG(("Fail to load lib: %s\n", sAtkBridge.libName));
+
+        if (!sToplevel_event_hook_added) {
+          sToplevel_event_hook_added = true;
+          sToplevel_show_hook =
+            g_signal_add_emission_hook(g_signal_lookup("show", GTK_TYPE_WINDOW),
+              0, toplevel_event_watcher,
+              reinterpret_cast<gpointer>(nsIAccessibleEvent::EVENT_SHOW), NULL);
+          sToplevel_hide_hook =
+            g_signal_add_emission_hook(g_signal_lookup("hide", GTK_TYPE_WINDOW),
+              0, toplevel_event_watcher,
+              reinterpret_cast<gpointer>(nsIAccessibleEvent::EVENT_HIDE), NULL);
+        }
     }
 
     return nsApplicationAccessible::Init();
 }
 
 void
 nsApplicationAccessibleWrap::Unload()
 {
+    if (sToplevel_event_hook_added) {
+      sToplevel_event_hook_added = false;
+      g_signal_remove_emission_hook(g_signal_lookup("show", GTK_TYPE_WINDOW),
+                                    sToplevel_show_hook);
+      g_signal_remove_emission_hook(g_signal_lookup("hide", GTK_TYPE_WINDOW),
+                                    sToplevel_hide_hook);
+    }
+
     if (sAtkBridge.lib) {
         // Do not shutdown/unload atk-bridge,
         // an exit function registered will take care of it
         // if (sAtkBridge.shutdown)
         //     (*sAtkBridge.shutdown)();
         // PR_UnloadLibrary(sAtkBridge.lib);
         sAtkBridge.lib = NULL;
         sAtkBridge.init = NULL;
@@ -666,17 +739,17 @@ struct AtkRootAccessibleAddedEvent {
 gboolean fireRootAccessibleAddedCB(gpointer data)
 {
     AtkRootAccessibleAddedEvent* eventData = (AtkRootAccessibleAddedEvent*)data;
     g_signal_emit_by_name(eventData->app_accessible, "children_changed::add",
                           eventData->index, eventData->root_accessible, NULL);
     g_object_unref(eventData->app_accessible);
     g_object_unref(eventData->root_accessible);
     free(data);
-    
+
     return FALSE;
 }
 
 PRBool
 nsApplicationAccessibleWrap::AppendChild(nsAccessible *aChild)
 {
     if (!nsApplicationAccessible::AppendChild(aChild))
       return PR_FALSE;
@@ -736,17 +809,17 @@ nsApplicationAccessibleWrap::PreCreate()
                   PR_FindFunctionSymbol(sATKLib,
                                         AtkSocketAccessible
                                           ::sATKSocketEmbedSymbol);
             AtkSocketAccessible::gCanEmbed =
               AtkSocketAccessible::g_atk_socket_type != G_TYPE_INVALID &&
               AtkSocketAccessible::g_atk_socket_embed;
             }
         }
-        sATKChecked = PR_TRUE;
+        sATKChecked = true;
     }
 }
 
 static nsresult
 LoadGtkModule(GnomeAccessibilityModule& aModule)
 {
     NS_ENSURE_ARG(aModule.libName);
 
--- a/accessible/src/atk/nsMaiInterfaceComponent.cpp
+++ b/accessible/src/atk/nsMaiInterfaceComponent.cpp
@@ -38,21 +38,16 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsMaiInterfaceComponent.h"
 
 #include "nsAccessibleWrap.h"
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 
-#include "nsIDOMDocument.h"
-#include "nsIDOMWindowInternal.h"
-#include "nsIDocShellTreeItem.h"
-#include "nsIInterfaceRequestorUtils.h"
-
 void
 componentInterfaceInitCB(AtkComponentIface *aIface)
 {
     NS_ASSERTION(aIface, "Invalid Interface");
     if(!aIface)
         return;
 
     /*
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -41,19 +41,18 @@
 #include "nsIAccessibleTypes.h"
 
 #include "nsAccessNode.h"
 
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMHTMLElement.h"
-#include "nsIDOMNodeList.h"
 #include "nsIDOMRange.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIDOMXULElement.h"
 #include "nsIDocShell.h"
 #include "nsIContentViewer.h"
 #include "nsEventListenerManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIScrollableFrame.h"
 #include "nsEventStateManager.h"
@@ -422,22 +421,21 @@ nsCoreUtils::GetScreenCoordsForWindow(ns
   nsCOMPtr<nsIDocShellTreeItem> rootTreeItem;
   treeItem->GetRootTreeItem(getter_AddRefs(rootTreeItem));
   nsCOMPtr<nsIDOMDocument> domDoc = do_GetInterface(rootTreeItem);
   if (!domDoc)
     return coords;
 
   nsCOMPtr<nsIDOMWindow> window;
   domDoc->GetDefaultView(getter_AddRefs(window));
-  nsCOMPtr<nsIDOMWindowInternal> windowInter(do_QueryInterface(window));
-  if (!windowInter)
+  if (!window)
     return coords;
 
-  windowInter->GetScreenX(&coords.x);
-  windowInter->GetScreenY(&coords.y);
+  window->GetScreenX(&coords.x);
+  window->GetScreenY(&coords.y);
   return coords;
 }
 
 already_AddRefed<nsIDocShellTreeItem>
 nsCoreUtils::GetDocShellTreeItemFor(nsINode *aNode)
 {
   if (!aNode)
     return nsnull;
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -174,17 +174,17 @@ nsHTMLImageAccessible::DoAction(PRUint8 
     NS_ENSURE_TRUE(element, NS_ERROR_FAILURE);
 
     nsAutoString longDesc;
     nsresult rv = element->GetLongDesc(longDesc);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsIDocument* document = mContent->GetOwnerDoc();
     nsCOMPtr<nsPIDOMWindow> piWindow = document->GetWindow();
-    nsCOMPtr<nsIDOMWindowInternal> win(do_QueryInterface(piWindow));
+    nsCOMPtr<nsIDOMWindow> win = do_QueryInterface(piWindow);
     NS_ENSURE_TRUE(win, NS_ERROR_FAILURE);
     nsCOMPtr<nsIDOMWindow> tmp;
     return win->Open(longDesc, EmptyString(), EmptyString(),
                      getter_AddRefs(tmp));
   }
   return nsLinkableAccessible::DoAction(aIndex);
 }
 
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -506,17 +506,17 @@ nsHTMLTableAccessible::GetAttributesInte
 NS_IMETHODIMP
 nsHTMLTableAccessible::GetRelationByType(PRUint32 aRelationType,
                                          nsIAccessibleRelation **aRelation)
 {
   nsresult rv = nsAccessibleWrap::GetRelationByType(aRelationType,
                                                     aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (aRelationType == nsIAccessibleRelation::RELATION_DESCRIBED_BY)
+  if (aRelationType == nsIAccessibleRelation::RELATION_LABELLED_BY)
     return nsRelUtils::AddTarget(aRelationType, aRelation, Caption());
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTableAccessible: nsIAccessibleTable implementation
 
@@ -1523,21 +1523,18 @@ nsHTMLTableAccessible::IsProbablyForLayo
 NS_IMETHODIMP
 nsHTMLCaptionAccessible::GetRelationByType(PRUint32 aRelationType,
                                            nsIAccessibleRelation **aRelation)
 {
   nsresult rv = nsHyperTextAccessible::GetRelationByType(aRelationType,
                                                          aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (aRelationType == nsIAccessibleRelation::RELATION_DESCRIPTION_FOR) {
-    nsCOMPtr<nsIAccessible> accParent;
-    GetParent(getter_AddRefs(accParent));
-    return nsRelUtils::AddTarget(aRelationType, aRelation, accParent);
-  }
+  if (aRelationType == nsIAccessibleRelation::RELATION_LABEL_FOR)
+    return nsRelUtils::AddTarget(aRelationType, aRelation, GetParent());
 
   return NS_OK;
 }
 
 PRUint32
 nsHTMLCaptionAccessible::NativeRole()
 {
   return nsIAccessibleRole::ROLE_CAPTION;
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -44,20 +44,18 @@
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 #include "nsTextAttrs.h"
 
 #include "nsIClipboard.h"
 #include "nsContentCID.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
-#include "nsPIDOMWindow.h"        
 #include "nsIDOMRange.h"
 #include "nsIDOMNSRange.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
 #include "nsIFrame.h"
 #include "nsFrameSelection.h"
 #include "nsILineIterator.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPlaintextEditor.h"
--- a/accessible/tests/mochitest/relations/test_general.html
+++ b/accessible/tests/mochitest/relations/test_general.html
@@ -97,18 +97,18 @@
       // output 'for' relations
       testRelation("output", RELATION_CONTROLLED_BY, ["input", "input2"]);
       testRelation("output2", RELATION_CONTROLLED_BY, ["input", "input2"]);
       testRelation("input", RELATION_CONTROLLER_FOR, ["output", "output2"]);
       testRelation("input2", RELATION_CONTROLLER_FOR, ["output", "output2"]);
 
       // 'described by'/'description for' relation for html:table and
       // html:caption
-      testRelation("caption", RELATION_DESCRIPTION_FOR, "table");
-      testRelation("table", RELATION_DESCRIBED_BY, "caption");
+      testRelation("caption", RELATION_LABEL_FOR, "table");
+      testRelation("table", RELATION_LABELLED_BY, "caption");
 
       // 'labelled by'/'label for' relation for html:fieldset and
       // html:legend
       testRelation("legend", RELATION_LABEL_FOR, "fieldset");
       testRelation("fieldset", RELATION_LABELLED_BY, "legend");
 
       // 'embeds' relation for root accessible
       var docAcc = null;
old mode 100755
new mode 100644
--- a/browser/base/content/browser-tabview.js
+++ b/browser/base/content/browser-tabview.js
@@ -430,12 +430,17 @@ let TabView = {
       return;
 
     // do nothing if we already enabled session restore once
     if (this.sessionRestoreEnabledOnce)
       return;
 
     this.sessionRestoreEnabledOnce = true;
 
-    // enable session restore
-    Services.prefs.setIntPref(this.PREF_STARTUP_PAGE, 3);
+    // enable session restore if necessary
+    if (Services.prefs.getIntPref(this.PREF_STARTUP_PAGE) != 3) {
+      Services.prefs.setIntPref(this.PREF_STARTUP_PAGE, 3);
+
+      // show banner
+      this._window.UI.notifySessionRestoreEnabled();
+    }
   }
 };
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -186,16 +186,17 @@ function GroupItem(listOfEls, options) {
   };
 
   this.$title
     .blur(function() {
       self._titleFocused = false;
       self.$titleShield.show();
       if (self.getTitle())
         gTabView.firstUseExperienced = true;
+      self.save();
     })
     .focus(function() {
       self._unfreezeItemSize();
       if (!self._titleFocused) {
         (self.$title)[0].select();
         self._titleFocused = true;
       }
     })
@@ -820,19 +821,17 @@ GroupItem.prototype = Utils.extend(new I
       child.removeSubscriber(self, "close");
 
       let removed = child.close(true);
       if (removed) {
         shouldRemoveTabItems.push(child);
       } else {
         // child.removeSubscriber() must be called before child.close(), 
         // therefore we call child.addSubscriber() if the tab is not removed.
-        child.addSubscriber(self, "close", function() {
-          self.remove(child);
-        });
+        child.addSubscriber(self, "close", self._onChildClose.bind(self));
       }
     });
 
     if (shouldRemoveTabItems.length != toClose.length) {
       // remove children without the assiciated tab and show the group item
       shouldRemoveTabItems.forEach(function(child) {
         self.remove(child, { dontArrange: true });
       });
@@ -1005,29 +1004,17 @@ GroupItem.prototype = Utils.extend(new I
       this._children.splice(index, 0, item);
 
       item.setZ(this.getZ() + 1);
 
       if (!wasAlreadyInThisGroupItem) {
         item.droppable(false);
         item.groupItemData = {};
 
-        item.addSubscriber(this, "close", function() {
-          let count = self._children.length;
-          let dontArrange = self.expanded || !self.shouldStack(count);
-          let dontClose = !item.closedManually && gBrowser._numPinnedTabs > 0;
-          self.remove(item, {dontArrange: dontArrange, dontClose: dontClose});
-
-          if (dontArrange)
-            self._freezeItemSize(count);
-
-          if (self._children.length > 0 && self._activeTab)
-            UI.setActive(self);
-        });
-
+        item.addSubscriber(this, "close", this._onChildClose.bind(this));
         item.setParent(this);
 
         if (typeof item.setResizable == 'function')
           item.setResizable(false, options.immediately);
 
         if (item == UI.getActiveTab() || !this._activeTab)
           this.setActiveTab(item);
 
@@ -1046,16 +1033,35 @@ GroupItem.prototype = Utils.extend(new I
 
       UI.setReorderTabsOnHide(this);
     } catch(e) {
       Utils.log('GroupItem.add error', e);
     }
   },
 
   // ----------
+  // Function: _onChildClose
+  // Handles "close" events from the group's children.
+  //
+  // Parameters:
+  //   tabItem - The tabItem that is closed.
+  _onChildClose: function GroupItem__onChildClose(tabItem) {
+    let count = this._children.length;
+    let dontArrange = this.expanded || !this.shouldStack(count);
+    let dontClose = !tabItem.closedManually && gBrowser._numPinnedTabs > 0;
+    this.remove(tabItem, {dontArrange: dontArrange, dontClose: dontClose});
+
+    if (dontArrange)
+      this._freezeItemSize(count);
+
+    if (this._children.length > 0 && this._activeTab)
+      UI.setActive(this);
+  },
+
+  // ----------
   // Function: remove
   // Removes an item from the groupItem.
   // Parameters:
   //
   //   a - The item to remove. Can be an <Item>, a DOM element or an iQ object.
   //       The latter two must refer to the container of an <Item>.
   //   options - An optional object with settings for this call. See below.
   //
--- a/browser/base/content/tabview/tabview.css
+++ b/browser/base/content/tabview/tabview.css
@@ -173,16 +173,30 @@ body {
 .shield {
   left: 0;
   top: 0;
   width: 100%;
   height: 100%;
   position: absolute;
 }
 
+.banner {
+  left: 0;
+  bottom: 0;
+  right: 0;
+  padding: 10px 0;
+  position: absolute;
+  z-index: 1000060;
+  background: #000;
+  color: #fff;
+  opacity: 0;
+  text-align: center;
+  font-weight: 700;
+}
+
 /* Resizable
 ----------------------------------*/
 .resizer {
   position: absolute;
 }
 
 .iq-resizable-handle {
   position: absolute;
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -130,16 +130,20 @@ let UI = {
   // Variable: isDOMWindowClosing
   // Tells wether the parent window is about to close
   isDOMWindowClosing: false,
 
   // Variable: _browserKeys
   // Used to keep track of allowed browser keys.
   _browserKeys: null,
 
+  // Variable: _browserKeysWithShift
+  // Used to keep track of allowed browser keys with Shift key combination.
+  _browserKeysWithShift: null,
+
   // Variable: ignoreKeypressForSearch
   // Used to prevent keypress being handled after quitting search mode.
   ignoreKeypressForSearch: false,
 
   // Variable: _lastOpenedTab
   // Used to keep track of the last opened tab.
   _lastOpenedTab: null,
 
@@ -968,34 +972,37 @@ let UI = {
 #endif
 #ifdef XP_MACOSX
       "preferencesCmdMac", "minimizeWindow", "hideThisAppCmdMac",
 #endif
       "newNavigator", "newNavigatorTab", "undo", "cut", "copy", "paste", 
       "selectAll", "find"
     ].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
-      keys[key] = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
+      let code = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
+      keys[code] = key;
     });
+    this._browserKeys = keys;
 
-    // for key combinations with shift key, the charCode of upper case letters 
-    // are different to the lower case ones so need to handle them differently.
+    keys = {};
+    // The lower case letters are passed to processBrowserKeys() even with shift 
+    // key when stimulating a key press using EventUtils.synthesizeKey() so need 
+    // to handle both upper and lower cases here.
     [
 #ifdef XP_UNIX
       "redo",
 #endif
       "closeWindow", "tabview", "undoCloseTab", "undoCloseWindow",
       "privatebrowsing"
     ].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
-      keys[key] = element.getAttribute("key").toLocaleUpperCase().charCodeAt(0);
+      let code = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
+      keys[code] = key;
     });
-
-    delete this._browserKeys;
-    this._browserKeys = keys;
+    this._browserKeysWithShift = keys;
   },
 
   // ----------
   // Function: _setTabViewFrameKeyHandlers
   // Sets up the key handlers for navigating between tabs within the TabView UI.
   _setTabViewFrameKeyHandlers: function UI__setTabViewFrameKeyHandlers() {
     let self = this;
 
@@ -1017,54 +1024,35 @@ let UI = {
 
 #ifdef XP_MACOSX
         if (evt.metaKey) {
 #else
         if (evt.ctrlKey) {
 #endif
           let preventDefault = true;
           if (evt.shiftKey) {
-            switch (evt.charCode) {
-              case self._browserKeys.tabview:
+            // when a user presses ctrl+shift+key, upper case letter charCode 
+            // is passed to processBrowserKeys() so converting back to lower 
+            // case charCode before doing the check
+            let lowercaseCharCode =
+              String.fromCharCode(evt.charCode).toLocaleLowerCase().charCodeAt(0);
+            if (lowercaseCharCode in self._browserKeysWithShift) {
+              let key = self._browserKeysWithShift[lowercaseCharCode];
+              if (key == "tabview")
                 self.exit();
-                break;
-#ifdef XP_UNIX
-              case self._browserKeys.redo:
-#endif
-              case self._browserKeys.closeWindow:
-              case self._browserKeys.undoCloseTab:
-              case self._browserKeys.undoCloseWindow:
-              case self._browserKeys.privatebrowsing:
+              else
                 preventDefault = false;
-                break;
             }
           } else {
-            switch (evt.charCode) {
-              case self._browserKeys.find:
+            if (evt.charCode in self._browserKeys) {
+              let key = self._browserKeys[evt.charCode];
+              if (key == "find")
                 self.enableSearch();
-                break;
-#ifdef XP_UNIX
-              case self._browserKeys.quitApplication:
-#else
-              case self._browserKeys.redo:
-#endif
-#ifdef XP_MACOSX
-              case self._browserKeys.preferencesCmdMac:
-              case self._browserKeys.minimizeWindow:
-              case self._browserKeys.hideThisAppCmdMac:
-#endif
-              case self._browserKeys.newNavigator:
-              case self._browserKeys.newNavigatorTab:
-              case self._browserKeys.undo:
-              case self._browserKeys.cut:
-              case self._browserKeys.copy:
-              case self._browserKeys.paste:
-              case self._browserKeys.selectAll:
+              else
                 preventDefault = false;
-                break;
             }
           }
           if (preventDefault) {
             evt.stopPropagation();
             evt.preventDefault();
           }
         }
       }
@@ -1563,13 +1551,42 @@ let UI = {
 
     // use the tab image if it doesn't start with http e.g. data:image/png, chrome://
     if (tab.image && !(/^https?:/.test(tab.image)))
       url = tab.image;
     else
       url = gFavIconService.getFaviconImageForPage(tab.linkedBrowser.currentURI).spec;
 
     return url;
+  },
+
+  // ----------
+  // Function: notifySessionRestoreEnabled
+  // Notify the user that session restore has been automatically enabled
+  // by showing a banner that expects no user interaction. It fades out after
+  // some seconds.
+  notifySessionRestoreEnabled: function UI_notifySessionRestoreEnabled() {
+    let brandBundle = gWindow.document.getElementById("bundle_brand");
+    let brandShortName = brandBundle.getString("brandShortName");
+    let notificationText = tabviewBundle.formatStringFromName(
+      "tabview.notification.sessionStore", [brandShortName], 1);
+
+    let banner = iQ("<div>")
+      .text(notificationText)
+      .addClass("banner")
+      .appendTo("body");
+
+    let onFadeOut = function () {
+      banner.remove();
+    };
+
+    let onFadeIn = function () {
+      setTimeout(function () {
+        banner.animate({opacity: 0}, {duration: 1500, complete: onFadeOut});
+      }, 5000);
+    };
+
+    banner.animate({opacity: 0.7}, {duration: 1500, complete: onFadeIn});
   }
 };
 
 // ----------
 UI.init();
--- a/browser/base/content/test/browser_bug553455.js
+++ b/browser/base/content/test/browser_bug553455.js
@@ -45,17 +45,17 @@ function wait_for_notification_close(aCa
 function wait_for_install_dialog(aCallback) {
   info("Waiting for install dialog");
   Services.wm.addListener({
     onOpenWindow: function(aXULWindow) {
       info("Install dialog opened, waiting for focus");
       Services.wm.removeListener(this);
 
       var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-                                .getInterface(Ci.nsIDOMWindowInternal);
+                                .getInterface(Ci.nsIDOMWindow);
       waitForFocus(function() {
         info("Saw install dialog");
         is(domwindow.document.location.href, XPINSTALL_URL, "Should have seen the right window open");
 
         // Override the countdown timer on the accept button
         var button = domwindow.document.documentElement.getButton("accept");
         button.disabled = false;
 
--- a/browser/base/content/test/browser_sanitize-download-history.js
+++ b/browser/base/content/test/browser_sanitize-download-history.js
@@ -136,30 +136,30 @@ function test()
            getService(Ci.nsIDownloadManager);
   let db = dm.DBConnection;
 
   // Empty any old downloads
   db.executeSimpleSQL("DELETE FROM moz_downloads");
 
   // Close the UI if necessary
   let win = Services.ww.getWindowByName("Sanatize", null);
-  if (win && (win instanceof Ci.nsIDOMWindowInternal))
+  if (win && (win instanceof Ci.nsIDOMWindow))
     win.close();
 
   // Start the test when the sanitize window loads
   Services.ww.registerNotification(function (aSubject, aTopic, aData) {
     Services.ww.unregisterNotification(arguments.callee);
     aSubject.QueryInterface(Ci.nsIDOMEventTarget)
             .addEventListener("DOMContentLoaded", doTest, false);
   });
 
   // Let the methods that run onload finish before we test
   let doTest = function() setTimeout(function() {
     let win = Services.ww.getWindowByName("Sanitize", null)
-                .QueryInterface(Ci.nsIDOMWindowInternal);
+                .QueryInterface(Ci.nsIDOMWindow);
 
     for (let i = 0; i < tests.length; i++)
       tests[i](win);
 
     win.close();
     finish();
   }, 0);
  
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -105,17 +105,16 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug624692.js \
                  browser_tabview_bug624727.js \
                  browser_tabview_bug624847.js \
                  browser_tabview_bug624931.js \
                  browser_tabview_bug624953.js \
                  browser_tabview_bug625195.js \
                  browser_tabview_bug625269.js \
                  browser_tabview_bug625424.js \
-                 browser_tabview_bug625666.js \
                  browser_tabview_bug626368.js \
                  browser_tabview_bug626525.js \
                  browser_tabview_bug626791.js \
                  browser_tabview_bug627239.js \
                  browser_tabview_bug627288.js \
                  browser_tabview_bug627736.js \
                  browser_tabview_bug628061.js \
                  browser_tabview_bug628165.js \
--- a/browser/base/content/test/tabview/browser_tabview_bug580412.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug580412.js
@@ -1,126 +1,80 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
   waitForExplicitFinish();
-
-  window.addEventListener("tabviewshown", onTabViewWindowLoaded, false);
-  if (TabView.isVisible())
-    onTabViewWindowLoaded();
-  else
-    TabView.show();
+  showTabView(onTabViewShown);
 }
 
-function onTabViewWindowLoaded() {
-  window.removeEventListener("tabviewshown", onTabViewWindowLoaded, false);
-
-  let contentWindow = document.getElementById("tab-view").contentWindow;
+function onTabViewShown() {
+  let contentWindow = TabView.getContentWindow();
   let [originalTab] = gBrowser.visibleTabs;
 
   ok(TabView.isVisible(), "Tab View is visible");
   is(contentWindow.GroupItems.groupItems.length, 1, "There is only one group");
   let currentActiveGroup = contentWindow.GroupItems.getActiveGroupItem();
 
-  // set double click interval to negative so quick drag and drop doesn't 
-  // trigger the double click code.
-  let origDBlClickInterval = contentWindow.UI.DBLCLICK_INTERVAL;
-  contentWindow.UI.DBLCLICK_INTERVAL = -1;
-
   let endGame = function() {
-    contentWindow.UI.reset();
-    contentWindow.UI.DBLCLICK_INTERVAL = origDBlClickInterval;
-
-    let onTabViewHidden = function() {
-      window.removeEventListener("tabviewhidden", onTabViewHidden, false);
-      ok(!TabView.isVisible(), "TabView is shown");
-      finish();
-    };
-    window.addEventListener("tabviewhidden", onTabViewHidden, false);
-
     ok(TabView.isVisible(), "TabView is shown");
-
     gBrowser.selectedTab = originalTab;
-    TabView.hide();
-  }
 
-  let part1 = function() {
-    // move down 20 so we're far enough away from the top.
-    checkSnap(currentActiveGroup, 0, 20, contentWindow, function(snapped){
-      ok(!snapped,"Move away from the edge");
-
-      // Just pick it up and drop it.
-      checkSnap(currentActiveGroup, 0, 0, contentWindow, function(snapped){
-        ok(!snapped,"Just pick it up and drop it");
-
-        checkSnap(currentActiveGroup, 0, 1, contentWindow, function(snapped){
-          ok(snapped,"Drag one pixel: should snap");
-
-          checkSnap(currentActiveGroup, 0, 5, contentWindow, function(snapped){
-            ok(!snapped,"Moving five pixels: shouldn't snap");
-            endGame();
-          });
-        });
-      });
+    hideTabView(function () {
+      ok(!TabView.isVisible(), "TabView is hidden");
+      finish();
     });
   }
 
+  // we need to stop the setBounds() css animation or else the test will
+  // fail in single-mode because the group is newly created "ontabshown".
+  let $container = contentWindow.iQ(currentActiveGroup.container);
+  $container.css("-moz-transition-property", "none");
+
   currentActiveGroup.setPosition(40, 40, true);
   currentActiveGroup.arrange({animate: false});
-  part1();
+
+  // move down 20 so we're far enough away from the top.
+  checkSnap(currentActiveGroup, 0, 20, contentWindow, function(snapped){
+    is(currentActiveGroup.getBounds().top, 60, "group.top is 60px");
+    ok(!snapped,"Move away from the edge");
+
+    // Just pick it up and drop it.
+    checkSnap(currentActiveGroup, 0, 0, contentWindow, function(snapped){
+      is(currentActiveGroup.getBounds().top, 60, "group.top is 60px");
+      ok(!snapped,"Just pick it up and drop it");
+
+      checkSnap(currentActiveGroup, 0, 1, contentWindow, function(snapped){
+        is(currentActiveGroup.getBounds().top, 60, "group.top is 60px");
+        ok(snapped,"Drag one pixel: should snap");
+
+        checkSnap(currentActiveGroup, 0, 5, contentWindow, function(snapped){
+          is(currentActiveGroup.getBounds().top, 65, "group.top is 65px");
+          ok(!snapped,"Moving five pixels: shouldn't snap");
+          endGame();
+        });
+      });
+    });
+  });
 }
 
-function simulateDragDrop(tabItem, offsetX, offsetY, contentWindow) {
-  // enter drag mode
-  let dataTransfer;
-
-  EventUtils.synthesizeMouse(
-    tabItem.container, 1, 1, { type: "mousedown" }, contentWindow);
-  let event = contentWindow.document.createEvent("DragEvents");
-  event.initDragEvent(
-    "dragenter", true, true, contentWindow, 0, 0, 0, 0, 0,
-    false, false, false, false, 1, null, dataTransfer);
-  tabItem.container.dispatchEvent(event);
+function simulateDragDrop(item, offsetX, offsetY, contentWindow) {
+  let target = item.container;
 
-  // drag over
-  if (offsetX || offsetY) {
-    let Ci = Components.interfaces;
-    let utils = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor).
-                              getInterface(Ci.nsIDOMWindowUtils);
-    let rect = tabItem.getBounds();
-    for (let i = 1; i <= 5; i++) {
-      let left = rect.left + 1 + Math.round(i * offsetX / 5);
-      let top = rect.top + 1 + Math.round(i * offsetY / 5);
-      utils.sendMouseEvent("mousemove", left, top, 0, 1, 0);
-    }
-    event = contentWindow.document.createEvent("DragEvents");
-    event.initDragEvent(
-      "dragover", true, true, contentWindow, 0, 0, 0, 0, 0,
-      false, false, false, false, 0, null, dataTransfer);
-    tabItem.container.dispatchEvent(event);
-  }
-
-  // drop
-  EventUtils.synthesizeMouse(
-    tabItem.container, 0, 0, { type: "mouseup" }, contentWindow);
-  event = contentWindow.document.createEvent("DragEvents");
-  event.initDragEvent(
-    "drop", true, true, contentWindow, 0, 0, 0, 0, 0,
-    false, false, false, false, 0, null, dataTransfer);
-  tabItem.container.dispatchEvent(event);
+  EventUtils.synthesizeMouse(target, 1, 1, {type: "mousedown"}, contentWindow);
+  EventUtils.synthesizeMouse(target, 1 + offsetX, 1 + offsetY, {type: "mousemove"}, contentWindow);
+  EventUtils.synthesizeMouse(target, 1, 1, {type: "mouseup"}, contentWindow);
 }
 
 function checkSnap(item, offsetX, offsetY, contentWindow, callback) {
   let firstTop = item.getBounds().top;
   let firstLeft = item.getBounds().left;
-  let onDrop = function() {
-    let snapped = false;
-    item.container.removeEventListener('drop', onDrop, false);
-    if (item.getBounds().top != firstTop + offsetY)
-      snapped = true;
-    if (item.getBounds().left != firstLeft + offsetX)
-      snapped = true;
-    callback(snapped);
-  };
-  item.container.addEventListener('drop', onDrop, false);
+
   simulateDragDrop(item, offsetX, offsetY, contentWindow);
+
+  let snapped = false;
+  if (item.getBounds().top != firstTop + offsetY)
+    snapped = true;
+  if (item.getBounds().left != firstLeft + offsetX)
+    snapped = true;
+
+  callback(snapped);
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug587276.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug587276.js
@@ -12,17 +12,17 @@ function test() {
 function test1() {
   ok(TabView.isVisible(), "Tab View is visible");
 
   contentWindow = document.getElementById("tab-view").contentWindow;
   whenTabViewIsHidden(function() {
     ok(!TabView.isVisible(), "Tab View is not visible");
     showTabView(test2);
   });
-  EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, contentWindow);
+  EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, contentWindow);
 }
 
 function test2() {
   ok(TabView.isVisible(), "Tab View is visible");
 
   whenSearchIsEnabled(function() {
     ok(contentWindow.isSearchEnabled(), "The search is enabled")
 
@@ -53,17 +53,17 @@ function test3() {
 function test4() {
   is(gBrowser.tabs.length, 2, "There are two tabs");
 
   let onTabClose = function() {
     gBrowser.tabContainer.removeEventListener("TabClose", onTabClose, true);
     executeSoon(function() {
       is(gBrowser.tabs.length, 1, "There is one tab after removing one");
 
-      EventUtils.synthesizeKey("T", { accelKey: true, shiftKey: true }, contentWindow);
+      EventUtils.synthesizeKey("t", { accelKey: true, shiftKey: true }, contentWindow);
       is(gBrowser.tabs.length, 2, "There are two tabs after restoring one");
 
       gBrowser.tabs[0].linkedBrowser.loadURI("about:blank");
       gBrowser.selectedTab = gBrowser.tabs[0];
       test8();
     });
   };
   gBrowser.tabContainer.addEventListener("TabClose", onTabClose, true);
@@ -91,15 +91,15 @@ function test9() {
   is(ZoomManager.zoom, zoomLevel, "The zoom level remains unchanged after cmd/ctrl + - is pressed");
 
   test10();
 }
 
 function test10() {
   is(gBrowser.tabs.length, 1, "There is one tab before cmd/ctrl + shift + a is pressed");
   // it would open about:addons on a new tab if it passes through the white list.
-  EventUtils.synthesizeKey("A", { accelKey: true, shiftKey: true }, contentWindow);
+  EventUtils.synthesizeKey("a", { accelKey: true, shiftKey: true }, contentWindow);
 
   executeSoon(function() {
     is(gBrowser.tabs.length, 1, "There is still one tab after cmd/ctrl + shift + a is pressed");
     hideTabView(finish);
   })
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug595020.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595020.js
@@ -6,16 +6,18 @@ let ss = Cc["@mozilla.org/browser/sessio
 let stateStartup = {windows:[
   {tabs:[{entries:[{url:"about:home"}]}], extData:{"tabview-last-session-group-name":"title"}}
 ]};
 
 function test() {
   let assertWindowTitle = function (win, title) {
     let browser = win.gBrowser.tabs[0].linkedBrowser;
     let winTitle = win.gBrowser.getWindowTitleForBrowser(browser);
+
+    info('window title is: "' + winTitle + '"');
     is(winTitle.indexOf(title), 0, "title starts with '" + title + "'");
   };
 
   let testGroupNameChange = function (win) {
     showTabView(function () {
       let cw = win.TabView.getContentWindow();
       let groupItem = cw.GroupItems.groupItems[0];
       groupItem.setTitle("new-title");
--- a/browser/base/content/test/tabview/browser_tabview_bug595191.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595191.js
@@ -52,10 +52,10 @@ function toggleTabViewTest(contentWindow
   let onTabViewHidden = function() {
     contentWindow.removeEventListener("tabviewhidden", onTabViewHidden, false);
 
     ok(!TabView.isVisible(), "Tab View is hidden");
     finish();
   }
   contentWindow.addEventListener("tabviewhidden", onTabViewHidden, false);
   // Use keyboard shortcut to toggle back to browser view
-  EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true });
+  EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug595518.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595518.js
@@ -23,17 +23,17 @@ function onTabViewWindowLoaded() {
     
     // verify that the exit button no longer has focus
     is(contentWindow.iQ("#exit-button:focus").length, 0, 
        "The exit button doesn't have the focus");
 
     // verify that the keyboard combo works (this is the crux of bug 595518)
     // Prepare the key combo
     window.addEventListener("tabviewshown", onTabViewShown, false);
-    EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, contentWindow);
+    EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, contentWindow);
   }
   
   let onTabViewShown = function() {
     window.removeEventListener("tabviewshown", onTabViewShown, false);
     
     // test if the key combo worked
     ok(TabView.isVisible(), "Tab View is visible");
 
--- a/browser/base/content/test/tabview/browser_tabview_bug595930.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595930.js
@@ -36,17 +36,17 @@ function onTabViewWindowLoaded() {
       finish();
     };
     window.addEventListener("tabviewhidden", onTabViewHidden, false);
 
     // delay to give time for hidden group DOM element to be removed so
     // the appropriate group would get selected when the key
     // combination is pressed
     executeSoon(function() { 
-      EventUtils.synthesizeKey("E", {accelKey : true, shiftKey: true}, contentWindow);
+      EventUtils.synthesizeKey("e", {accelKey : true, shiftKey: true}, contentWindow);
     });
   });
 
   group1.addSubscriber(group1, "groupHidden", function() {
     group1.removeSubscriber(group1, "groupHidden");
 
     // close undo group
     let closeButton = group1.$undoContainer.find(".close");
--- a/browser/base/content/test/tabview/browser_tabview_bug597980.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug597980.js
@@ -73,13 +73,13 @@ function part2(win) {
 
     win.addEventListener("tabviewhidden", function () {
       win.removeEventListener("tabviewhidden", arguments.callee, false);
       is(win.gBrowser.selectedTab, newTab, "The seleted tab should be the same as before (new tab)");
        win.close();
        finish();
     }, false);
     // show tabview
-    EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, win);
+    EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, win);
     // hide tabview
-    EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, win);
+    EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, win);
   })
 }
deleted file mode 100644
--- a/browser/base/content/test/tabview/browser_tabview_bug625666.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  let cw;
-
-  let getTabItemAspect = function (tabItem) {
-    let bounds = cw.iQ('.thumb', tabItem.container).bounds();
-    let padding = cw.TabItems.tabItemPadding;
-    return (bounds.height + padding.y) / (bounds.width + padding.x);
-  }
-
-  let getAspectRange = function () {
-    let aspect = cw.TabItems.tabAspect;
-    let variance = aspect / 100 * 1.5;
-    return new cw.Range(aspect - variance, aspect + variance);
-  }
-
-  waitForExplicitFinish();
-
-  newWindowWithTabView(function (win) {
-    registerCleanupFunction(function () win.close());
-    cw = win.TabView.getContentWindow();
-
-    // prepare orphan tab
-    let tabItem = win.gBrowser.tabs[0]._tabViewTabItem;
-    tabItem.parent.remove(tabItem, {immediately: true});
-    tabItem.setBounds(new cw.Rect(20, 20, 200, 165), true);
-
-    let bounds = tabItem.getBounds();
-
-    // prepare group item
-    let box = new cw.Rect(20, 300, 400, 200);
-    let groupItem = new cw.GroupItem([], {bounds: box, immediately: true});
-
-    groupItem.setBounds(new cw.Rect(20, 100, 400, 200));
-    groupItem.pushAway(true);
-
-    let newBounds = tabItem.getBounds();
-    ok(newBounds.width < bounds.width, "The new width of item is smaller than the old one.");
-    ok(newBounds.height < bounds.height, "The new height of item is smaller than the old one.");
-
-    let aspectRange = getAspectRange();
-    let aspect = getTabItemAspect(tabItem);
-    ok(aspectRange.contains(aspect), "orphaned tabItem's aspect is correct");
-
-    finish();
-  });
-}
--- a/browser/base/content/test/tabview/browser_tabview_bug656778.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug656778.js
@@ -25,16 +25,26 @@ function test() {
   };
 
   let assertPreferences = function (startupPage, firstRun, enabledOnce) {
     assertIntPref(TabView.PREF_STARTUP_PAGE, startupPage);
     assertBoolPref(TabView.PREF_FIRST_RUN, firstRun);
     assertBoolPref(TabView.PREF_RESTORE_ENABLED_ONCE, enabledOnce);
   };
 
+  let assertNotificationBannerVisible = function (win) {
+    let cw = win.TabView.getContentWindow();
+    is(cw.iQ(".banner").length, 1, "notification banner is visible");
+  };
+
+  let assertNotificationBannerNotVisible = function (win) {
+    let cw = win.TabView.getContentWindow();
+    is(cw.iQ(".banner").length, 0, "notification banner is not visible");
+  };
+
   let next = function () {
     if (tests.length == 0) {
       waitForFocus(finish);
       return;
     }
 
     let test = tests.shift();
     info("running " + test.name + "...");
@@ -47,16 +57,17 @@ function test() {
   //
   // Expected result:
   // When entering Panorma session restore will be enabled and a notification
   // banner is shown.
   let test1 = function test1() {
     setPreferences(1, true, false);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -67,20 +78,22 @@ function test() {
   // Expected result:
   // When entering Panorma nothing happens. When we detect that Panorama is
   // really used (firstUseExperienced = true) we notify that session restore
   // is now enabled.
   let test2 = function test2() {
     setPreferences(1, false, false);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(1, false, false);
 
       win.TabView.firstUseExperienced = true;
 
+      assertNotificationBannerVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -89,16 +102,17 @@ function test() {
   //
   // Expected result:
   // When entering Panorama nothing happens because session store is already
   // enabled so there's no reason to notify.
   let test3 = function test3() {
     setPreferences(3, true, false);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -106,16 +120,17 @@ function test() {
   // restore has been automatically activated.
   //
   // Expected result:
   // When entering Panorama nothing happens.
   let test4 = function test4() {
     setPreferences(3, true, true);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(3, true, true);
 
       win.close();
       next();
     });
   };
 
   // State:
@@ -124,16 +139,17 @@ function test() {
   // disabled by the user so we won't touch that again.
   //
   // Expected result:
   // When entering Panorama nothing happens and we didn't enable session restore.
   let test5 = function test5() {
     setPreferences(1, true, true);
 
     newWindowWithTabView(function (win) {
+      assertNotificationBannerNotVisible(win);
       assertPreferences(1, true, true);
 
       win.close();
       next();
     });
   };
 
   let tests = [test1, test2, test3, test4, test5];
--- a/browser/base/content/test/tabview/browser_tabview_launch.js
+++ b/browser/base/content/test/tabview/browser_tabview_launch.js
@@ -23,17 +23,17 @@ function test() {
       deck.removeEventListener("select", onSelect, true);
 
       whenTabViewIsShown(function() {
         executeSoon(function() {
           testMethodToHideAndShowTabView(function() {
             newWin.document.getElementById("menu_tabview").doCommand();
           }, function() {
             testMethodToHideAndShowTabView(function() {
-              EventUtils.synthesizeKey("E", { accelKey: true, shiftKey: true }, newWin);
+              EventUtils.synthesizeKey("e", { accelKey: true, shiftKey: true }, newWin);
             }, finish);
           });
         });
       }, win);
     };
 
     let deck = win.document.getElementById("tab-view-deck");
     deck.addEventListener("select", onSelect, true);
--- a/browser/base/content/test/tabview/head.js
+++ b/browser/base/content/test/tabview/head.js
@@ -78,19 +78,21 @@ function afterAllTabItemsUpdated(callbac
 function newWindowWithTabView(shownCallback, loadCallback, width, height) {
   let winWidth = width || 800;
   let winHeight = height || 800;
   let win = window.openDialog(getBrowserURL(), "_blank",
                               "chrome,all,dialog=no,height=" + winHeight +
                               ",width=" + winWidth);
 
   whenWindowLoaded(win, function () {
-    if (typeof loadCallback == "function")
+    if (loadCallback)
       loadCallback(win);
+  });
 
+  whenDelayedStartupFinished(win, function () {
     showTabView(function () shownCallback(win), win);
   });
 }
 
 // ----------
 function afterAllTabsLoaded(callback, win) {
   const TAB_STATE_NEEDS_RESTORE = 1;
 
--- a/browser/components/migration/src/nsProfileMigrator.cpp
+++ b/browser/components/migration/src/nsProfileMigrator.cpp
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsProfileMigrator.h"
 
 #include "nsIBrowserProfileMigrator.h"
 #include "nsIComponentManager.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsILocalFile.h"
 #include "nsIObserverService.h"
 #include "nsIProperties.h"
 #include "nsIServiceManager.h"
 #include "nsISupportsPrimitives.h"
 #include "nsISupportsArray.h"
 #include "nsIToolkitProfile.h"
 #include "nsIToolkitProfileService.h"
--- a/browser/components/preferences/sync.js
+++ b/browser/components/preferences/sync.js
@@ -109,20 +109,20 @@ let gSyncPane = {
 
   startOver: function (showDialog) {
     if (showDialog) {
       let flags = Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
                   Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL + 
                   Services.prompt.BUTTON_POS_1_DEFAULT;
       let buttonChoice =
         Services.prompt.confirmEx(window,
-                                  this._stringBundle.GetStringFromName("stopUsingAccount.title"),
-                                  this._stringBundle.GetStringFromName("differentAccount.label"),
+                                  this._stringBundle.GetStringFromName("syncUnlink.title"),
+                                  this._stringBundle.GetStringFromName("syncUnlink.label"),
                                   flags,
-                                  this._stringBundle.GetStringFromName("differentAccountConfirm.label"),
+                                  this._stringBundle.GetStringFromName("syncUnlinkConfirm.label"),
                                   null, null, null, {});
 
       // If the user selects cancel, just bail
       if (buttonChoice == 1)
         return;
     }
 
     Weave.Service.startOver();
--- a/browser/components/preferences/sync.xul
+++ b/browser/components/preferences/sync.xul
@@ -96,22 +96,22 @@
             <hbox>
               <button type="menu"
                       label="&manageAccount.label;"
                       accesskey="&manageAccount.accesskey;">
                 <menupopup>
                   <menuitem label="&viewQuota.label;"
                             oncommand="gSyncPane.openQuotaDialog();"/>
                   <menuseparator/>
-                  <menuitem label="&changePassword.label;"
+                  <menuitem label="&changePassword2.label;"
                             oncommand="gSyncUtils.changePassword();"/>
                   <menuitem label="&mySyncKey.label;"
                             oncommand="gSyncUtils.resetPassphrase();"/>
                   <menuseparator/>
-                  <menuitem label="&resetSync.label;"
+                  <menuitem label="&resetSync2.label;"
                             oncommand="gSyncPane.resetSync();"/>
                 </menupopup>
               </button>
             </hbox>
 
             <hbox>
               <label id="syncAddDeviceLabel"
                      class="text-link"
@@ -167,17 +167,17 @@
                   <textbox id="syncComputerName"
                            onchange="gSyncUtils.changeName(this)"/>
                 </row>
               </rows>
             </grid>
             <hbox>
               <label class="text-link"
                      onclick="gSyncPane.startOver(true); return false;"
-                     value="&deactivateDevice.label;"/>
+                     value="&unlinkDevice.label;"/>
             </hbox>
           </groupbox>
           <hbox id="tosPP" pack="center">
             <label class="text-link"
                    onclick="event.stopPropagation();gSyncUtils.openToS();"
                    value="&prefs.tosLink.label;"/>
             <label class="text-link"
                    onclick="event.stopPropagation();gSyncUtils.openPrivacyPolicy();"
@@ -192,13 +192,13 @@
                    onclick="gSyncPane.updatePass(); return false;"
                    value="&updatePass.label;"/>
             <label class="text-link"
                    onclick="gSyncPane.resetPass(); return false;"
                    value="&resetPass.label;"/>
           </hbox>
           <label class="text-link"
                  onclick="gSyncPane.startOver(true); return false;"
-                 value="&deactivateDevice.label;"/>
+                 value="&unlinkDevice.label;"/>
         </vbox>
       </deck>
   </prefpane>
 </overlay>
--- a/browser/components/preferences/tests/browser_permissions.js
+++ b/browser/components/preferences/tests/browser_permissions.js
@@ -290,17 +290,17 @@ function getSiteItem(aHost) {
 
 function addWindowListener(aURL, aCallback) {
   Services.wm.addListener({
     onOpenWindow: function(aXULWindow) {
       info("window opened, waiting for focus");
       Services.wm.removeListener(this);
 
       var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-                                .getInterface(Ci.nsIDOMWindowInternal);
+                                .getInterface(Ci.nsIDOMWindow);
       waitForFocus(function() {
         is(domwindow.document.location.href, aURL, "should have seen the right window open");
         domwindow.close();
         aCallback();
       }, domwindow);
     },
     onCloseWindow: function(aXULWindow) { },
     onWindowTitleChange: function(aXULWindow, aNewTitle) { }
--- a/browser/components/sessionstore/content/aboutSessionRestore.js
+++ b/browser/components/sessionstore/content/aboutSessionRestore.js
@@ -284,16 +284,17 @@ var treeView = {
   getCellText: function(idx, column) { return gTreeData[idx].label; },
   isContainer: function(idx)         { return "open" in gTreeData[idx]; },
   getCellValue: function(idx, column){ return gTreeData[idx].checked; },
   isContainerOpen: function(idx)     { return gTreeData[idx].open; },
   isContainerEmpty: function(idx)    { return false; },
   isSeparator: function(idx)         { return false; },
   isSorted: function()               { return false; },
   isEditable: function(idx, column)  { return false; },
+  canDrop: function(idx, orientation, dt) { return false; },
   getLevel: function(idx)            { return this.isContainer(idx) ? 0 : 1; },
 
   getParentIndex: function(idx) {
     if (!this.isContainer(idx))
       for (var t = idx - 1; t >= 0 ; t--)
         if (this.isContainer(t))
           return t;
     return -1;
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -2217,18 +2217,24 @@ SessionStoreService.prototype = {
     var jscookies = {};
     var _this = this;
     // MAX_EXPIRY should be 2^63-1, but JavaScript can't handle that precision
     var MAX_EXPIRY = Math.pow(2, 62);
     aWindows.forEach(function(aWindow) {
       if (!aWindow._hosts)
         return;
       for (var [host, isPinned] in Iterator(aWindow._hosts)) {
-        var list = CookieSvc.getCookiesFromHost(host);
-        while (list.hasMoreElements()) {
+        let list;
+        try {
+          list = CookieSvc.getCookiesFromHost(host);
+        }
+        catch (ex) {
+          debug("getCookiesFromHost failed. Host: " + host);
+        }
+        while (list && list.hasMoreElements()) {
           var cookie = list.getNext().QueryInterface(Ci.nsICookie2);
           // aWindow._hosts will only have hosts with the right privacy rules,
           // so there is no need to do anything special with this call to
           // _checkPrivacyLevel.
           if (cookie.isSession && _this._checkPrivacyLevel(cookie.isSecure, isPinned)) {
             // use the cookie's host, path, and name as keys into a hash,
             // to make sure we serialize each cookie only once
             if (!(cookie.host in jscookies &&
@@ -2947,18 +2953,21 @@ SessionStoreService.prototype = {
     if (tabData.userTypedValue) {
       browser.userTypedValue = tabData.userTypedValue;
       if (tabData.userTypedClear) {
         // Make it so that we'll enter restoreDocument on page load. We will
         // fire SSTabRestored from there. We don't have any form data to restore
         // so we can just set the URL to null.
         browser.__SS_restore_data = { url: null };
         browser.__SS_restore_tab = aTab;
+        if (didStartLoad)
+          browser.stop();
         didStartLoad = true;
-        browser.loadURI(tabData.userTypedValue, null, null, true);
+        browser.loadURIWithFlags(tabData.userTypedValue,
+                                 Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP);
       }
     }
 
     // If we didn't start a load, then we won't reset this tab through the usual
     // channel (via the progress listener), so reset the tab ourselves. We will
     // also send SSTabRestored since this tab has technically been restored.
     if (!didStartLoad) {
       this._sendTabRestoredNotification(aTab);
--- a/browser/components/wintaskbar/test/browser_taskbar_preview.js
+++ b/browser/components/wintaskbar/test/browser_taskbar_preview.js
@@ -124,16 +124,16 @@ function test() {
       thumbnailWidth = thumbnailHeight * ratio;
     else
       thumbnailHeight = thumbnailWidth / ratio;
 
     return getCanvas(thumbnailWidth, thumbnailHeight);
   }
 
   function getCanvas(width, height) {
-    let win = window.QueryInterface(Ci.nsIDOMWindowInternal);
+    let win = window.QueryInterface(Ci.nsIDOMWindow);
     let doc = win.document;
     let canvas = doc.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
     canvas.width = width;
     canvas.height = height;
     return canvas;
   }
 }
--- a/browser/fuel/src/fuelApplication.js
+++ b/browser/fuel/src/fuelApplication.js
@@ -217,17 +217,17 @@ BrowserTab.prototype = {
   /*
    * Helper event callback used to redirect events made on the XBL element
    */
   _event : function bt_event(aEvent) {
     if (aEvent.type == "load") {
       if (!(aEvent.originalTarget instanceof Ci.nsIDOMDocument))
         return;
 
-      if (aEvent.originalTarget.defaultView instanceof Ci.nsIDOMWindowInternal &&
+      if (aEvent.originalTarget.defaultView instanceof Ci.nsIDOMWindow &&
           aEvent.originalTarget.defaultView.frameElement)
         return;
     }
     this._events.dispatch(aEvent.type, this);
   },
   /*
    * Helper used to determine the index offset of the browsertab
    */
--- a/browser/fuel/test/browser_Application.js
+++ b/browser/fuel/test/browser_Application.js
@@ -29,17 +29,17 @@ WindowOpenListener.prototype = {
   },
 
   onOpenWindow: function(window) {
     if (this.window)
       return;
 
     this.window = window;
     this.domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
-                           .getInterface(Ci.nsIDOMWindowInternal);
+                           .getInterface(Ci.nsIDOMWindow);
     this.domwindow.addEventListener("load", this, false);
   },
 
   onCloseWindow: function(window) {
     if (this.window != window)
       return;
 
     Services.wm.removeListener(this);
--- a/browser/locales/en-US/chrome/browser/preferences/preferences.properties
+++ b/browser/locales/en-US/chrome/browser/preferences/preferences.properties
@@ -106,11 +106,11 @@ offlinepermissionstitle=Offline Data
 
 ####Preferences::Advanced::Network
 #LOCALIZATION NOTE: The next string is for the disk usage of the http cache.
 #   e.g., "Your cache is currently using 200 MB"
 #   %1$S = size
 #   %2$S = unit (MB, KB, etc.)
 actualCacheSize=Your cache is currently using %1$S %2$S of disk space
 
-stopUsingAccount.title=Do you want to stop using this account?
-differentAccount.label=This will reset all of your Sync account information and preferences.
-differentAccountConfirm.label=Reset All Information
+syncUnlink.title=Do you want to unlink your device?
+syncUnlink.label=This device will no longer be associated with your Sync account. All of your personal data, both on this device and in your Sync account, will remain intact.
+syncUnlinkConfirm.label=Unlink
--- a/browser/locales/en-US/chrome/browser/preferences/sync.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/sync.dtd
@@ -8,19 +8,20 @@
 <!-- Login error feedback -->
 <!ENTITY updatePass.label             "Update">
 <!ENTITY resetPass.label              "Reset">
 
 <!-- Manage Account -->
 <!ENTITY manageAccount.label          "Manage Account">
 <!ENTITY manageAccount.accesskey      "A">
 <!ENTITY viewQuota.label              "View Quota">
-<!ENTITY changePassword.label         "Change Password">
+<!ENTITY changePassword2.label         "Change Password…">
 <!ENTITY mySyncKey.label              "My Sync Key">
-<!ENTITY resetSync.label              "Reset Sync">
+<!ENTITY resetSync2.label              "Reset Sync…">
+
 <!ENTITY addDevice.label              "Add a Device">
 
 <!ENTITY syncMy.label               "Sync My">
 <!ENTITY engine.bookmarks.label     "Bookmarks">
 <!ENTITY engine.bookmarks.accesskey "m">
 <!ENTITY engine.tabs.label          "Tabs">
 <!ENTITY engine.tabs.accesskey      "T">
 <!ENTITY engine.history.label       "History">
@@ -28,13 +29,13 @@
 <!ENTITY engine.passwords.label     "Passwords">
 <!ENTITY engine.passwords.accesskey "P">
 <!ENTITY engine.prefs.label         "Preferences">
 <!ENTITY engine.prefs.accesskey     "S">
 
 <!-- Device Settings -->
 <!ENTITY syncComputerName.label       "Computer Name:">
 <!ENTITY syncComputerName.accesskey   "c">
-<!ENTITY deactivateDevice.label       "Deactivate This Device">
+<!ENTITY unlinkDevice.label           "Unlink This Device">
 
 <!-- Footer stuff -->
 <!ENTITY prefs.tosLink.label        "Terms of Service">
 <!ENTITY prefs.ppLink.label         "Privacy Policy">
--- a/browser/locales/en-US/chrome/browser/tabview.properties
+++ b/browser/locales/en-US/chrome/browser/tabview.properties
@@ -1,4 +1,5 @@
 tabview.groupItem.newTabButton=New tab
 tabview.groupItem.defaultName=Name this tab group…
 tabview.groupItem.undoCloseGroup=Undo Close Group
 tabview.search.otherWindowTabs=Tabs from other windows
+tabview.notification.sessionStore=Tabs and groups will automatically be restored the next time you start %S.
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -2707,17 +2707,17 @@ nsScriptSecurityManager::CheckConfirmDia
 
     //-- Get a prompter for the current window.
     nsCOMPtr<nsIPrompt> prompter;
     if (cx)
     {
         nsIScriptContext *scriptContext = GetScriptContext(cx);
         if (scriptContext)
         {
-            nsCOMPtr<nsIDOMWindowInternal> domWin =
+            nsCOMPtr<nsIDOMWindow> domWin =
                 do_QueryInterface(scriptContext->GetGlobalObject());
             if (domWin)
                 domWin->GetPrompter(getter_AddRefs(prompter));
         }
     }
 
     if (!prompter)
     {
--- a/chrome/src/nsChromeRegistry.cpp
+++ b/chrome/src/nsChromeRegistry.cpp
@@ -59,17 +59,17 @@
 #include "nsCSSStyleSheet.h"
 #include "nsIConsoleService.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocShell.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMLocation.h"
 #include "nsIDOMWindowCollection.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIIOService.h"
 #include "nsIJARProtocolHandler.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
 #include "nsIProtocolHandler.h"
 #include "nsIScriptError.h"
 #include "nsIWindowMediator.h"
 
@@ -346,17 +346,17 @@ nsChromeRegistry::ConvertChromeURL(nsIUR
   return NS_NewURI(aResult, path, nsnull, baseURI);
 }
 
 ////////////////////////////////////////////////////////////////////////
 
 // theme stuff
 
 
-static void FlushSkinBindingsForWindow(nsIDOMWindowInternal* aWindow)
+static void FlushSkinBindingsForWindow(nsIDOMWindow* aWindow)
 {
   // Get the DOM document.
   nsCOMPtr<nsIDOMDocument> domDocument;
   aWindow->GetDocument(getter_AddRefs(domDocument));
   if (!domDocument)
     return;
 
   nsCOMPtr<nsIDocument> document = do_QueryInterface(domDocument);
@@ -378,32 +378,32 @@ NS_IMETHODIMP nsChromeRegistry::RefreshS
   nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
   windowMediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
   PRBool more;
   windowEnumerator->HasMoreElements(&more);
   while (more) {
     nsCOMPtr<nsISupports> protoWindow;
     windowEnumerator->GetNext(getter_AddRefs(protoWindow));
     if (protoWindow) {
-      nsCOMPtr<nsIDOMWindowInternal> domWindow = do_QueryInterface(protoWindow);
+      nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(protoWindow);
       if (domWindow)
         FlushSkinBindingsForWindow(domWindow);
     }
     windowEnumerator->HasMoreElements(&more);
   }
 
   FlushSkinCaches();
 
   windowMediator->GetEnumerator(nsnull, getter_AddRefs(windowEnumerator));
   windowEnumerator->HasMoreElements(&more);
   while (more) {
     nsCOMPtr<nsISupports> protoWindow;
     windowEnumerator->GetNext(getter_AddRefs(protoWindow));
     if (protoWindow) {
-      nsCOMPtr<nsIDOMWindowInternal> domWindow = do_QueryInterface(protoWindow);
+      nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(protoWindow);
       if (domWindow)
         RefreshWindow(domWindow);
     }
     windowEnumerator->HasMoreElements(&more);
   }
    
   return NS_OK;
 }
@@ -423,29 +423,28 @@ static PRBool IsChromeURI(nsIURI* aURI)
 {
     PRBool isChrome=PR_FALSE;
     if (NS_SUCCEEDED(aURI->SchemeIs("chrome", &isChrome)) && isChrome)
         return PR_TRUE;
     return PR_FALSE;
 }
 
 // XXXbsmedberg: move this to windowmediator
-nsresult nsChromeRegistry::RefreshWindow(nsIDOMWindowInternal* aWindow)
+nsresult nsChromeRegistry::RefreshWindow(nsIDOMWindow* aWindow)
 {
   // Deal with our subframes first.
   nsCOMPtr<nsIDOMWindowCollection> frames;
   aWindow->GetFrames(getter_AddRefs(frames));
   PRUint32 length;
   frames->GetLength(&length);
   PRUint32 j;
   for (j = 0; j < length; j++) {
     nsCOMPtr<nsIDOMWindow> childWin;
     frames->Item(j, getter_AddRefs(childWin));
-    nsCOMPtr<nsIDOMWindowInternal> childInt(do_QueryInterface(childWin));
-    RefreshWindow(childInt);
+    RefreshWindow(childWin);
   }
 
   nsresult rv;
   // Get the DOM document.
   nsCOMPtr<nsIDOMDocument> domDocument;
   aWindow->GetDocument(getter_AddRefs(domDocument));
   if (!domDocument)
     return NS_OK;
@@ -563,18 +562,17 @@ nsChromeRegistry::ReloadChrome()
       // Get each dom window
       PRBool more;
       rv = windowEnumerator->HasMoreElements(&more);
       if (NS_FAILED(rv)) return rv;
       while (more) {
         nsCOMPtr<nsISupports> protoWindow;
         rv = windowEnumerator->GetNext(getter_AddRefs(protoWindow));
         if (NS_SUCCEEDED(rv)) {
-          nsCOMPtr<nsIDOMWindowInternal> domWindow =
-            do_QueryInterface(protoWindow);
+          nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(protoWindow);
           if (domWindow) {
             nsCOMPtr<nsIDOMLocation> location;
             domWindow->GetLocation(getter_AddRefs(location));
             if (location) {
               rv = location->Reload(PR_FALSE);
               if (NS_FAILED(rv)) return rv;
             }
           }
--- a/chrome/src/nsChromeRegistry.h
+++ b/chrome/src/nsChromeRegistry.h
@@ -58,17 +58,17 @@
 #include "nsURIHashKey.h"
 #include "nsInterfaceHashtable.h"
 #include "nsXULAppAPI.h"
 #include "nsIResProtocolHandler.h"
 #include "nsIXPConnect.h"
 
 #include "mozilla/Omnijar.h"
 
-class nsIDOMWindowInternal;
+class nsIDOMWindow;
 class nsIURL;
 
 // The chrome registry is actually split between nsChromeRegistryChrome and
 // nsChromeRegistryContent. The work/data that is common to both resides in
 // the shared nsChromeRegistry implementation, with operations that only make
 // sense for one side erroring out in the other.
 
 // for component registration
@@ -125,17 +125,17 @@ protected:
   virtual nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                         const nsCString& aProvider,
                                         const nsCString& aPath) = 0;
   virtual nsresult GetFlagsFromPackage(const nsCString& aPackage,
                                        PRUint32* aFlags) = 0;
 
   nsresult SelectLocaleFromPref(nsIPrefBranch* prefs);
 
-  static nsresult RefreshWindow(nsIDOMWindowInternal* aWindow);
+  static nsresult RefreshWindow(nsIDOMWindow* aWindow);
   static nsresult GetProviderAndPath(nsIURL* aChromeURL,
                                      nsACString& aProvider, nsACString& aPath);
 
 public:
   static already_AddRefed<nsChromeRegistry> GetSingleton();
 
   struct ManifestProcessingContext
   {
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -61,17 +61,17 @@
 #include "nsIParser.h"
 #include "nsContentErrors.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIViewManager.h"
 #include "nsIContentViewer.h"
 #include "nsIAtom.h"
 #include "nsGkAtoms.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsNetCID.h"
 #include "nsIOfflineCacheUpdate.h"
 #include "nsIApplicationCache.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIApplicationCacheChannel.h"
 #include "nsIScriptSecurityManager.h"
@@ -510,17 +510,17 @@ nsContentSink::ProcessHeaderData(nsIAtom
 
     // Note that a non-codebase principal (eg the system principal) will return
     // a null URI.
     nsCOMPtr<nsIURI> codebaseURI;
     rv = mDocument->NodePrincipal()->GetURI(getter_AddRefs(codebaseURI));
     NS_ENSURE_TRUE(codebaseURI, rv);
 
     nsCOMPtr<nsIPrompt> prompt;
-    nsCOMPtr<nsIDOMWindowInternal> window (do_QueryInterface(mDocument->GetScriptGlobalObject()));
+    nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(mDocument->GetScriptGlobalObject());
     if (window) {
       window->GetPrompter(getter_AddRefs(prompt));
     }
 
     nsCOMPtr<nsIChannel> channel;
     if (mParser) {
       mParser->GetChannel(getter_AddRefs(channel));
     }
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -111,17 +111,17 @@
 #include "nsIWebNavigation.h"
 #include "nsIScriptError.h"
 
 #include "nsNetUtil.h"     // for NS_MakeAbsoluteURI
 
 #include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
 
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMElement.h"
 #include "nsFocusManager.h"
 
 // for radio group stuff
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIRadioVisitor.h"
 #include "nsIFormControl.h"
@@ -5090,31 +5090,30 @@ nsDocument::GetDefaultView(nsIDOMWindow*
 }
 
 NS_IMETHODIMP
 nsDocument::GetLocation(nsIDOMLocation **_retval)
 {
   NS_ENSURE_ARG_POINTER(_retval);
   *_retval = nsnull;
 
-  nsCOMPtr<nsIDOMWindowInternal> w(do_QueryInterface(mScriptGlobalObject));
+  nsCOMPtr<nsIDOMWindow> w = do_QueryInterface(mScriptGlobalObject);
 
   if (!w) {
     return NS_OK;
   }
 
   return w->GetLocation(_retval);
 }
 
 Element*
 nsIDocument::GetHtmlElement()
 {
   Element* rootElement = GetRootElement();
-  if (rootElement && rootElement->Tag() == nsGkAtoms::html &&
-      rootElement->IsHTML())
+  if (rootElement && rootElement->IsHTML(nsGkAtoms::html))
     return rootElement;
   return nsnull;
 }
 
 Element*
 nsIDocument::GetHtmlChildElement(nsIAtom* aTag)
 {
   Element* html = GetHtmlElement();
--- a/content/base/src/nsStyledElement.cpp
+++ b/content/base/src/nsStyledElement.cpp
@@ -48,16 +48,17 @@
 #include "nsServiceManagerUtils.h"
 #include "nsIDocument.h"
 #include "mozilla/css/StyleRule.h"
 #include "nsCSSParser.h"
 #include "mozilla/css/Loader.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsXULElement.h"
 #include "nsIDOMSVGStylable.h"
+#include "nsContentUtils.h"
 
 namespace css = mozilla::css;
 
 //----------------------------------------------------------------------
 // nsIContent methods
 
 nsIAtom*
 nsStyledElementNotElementCSSInlineStyle::GetClassAttributeName() const
--- a/content/events/src/nsDOMUIEvent.cpp
+++ b/content/events/src/nsDOMUIEvent.cpp
@@ -38,17 +38,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "base/basictypes.h"
 #include "IPC/IPCMessageUtils.h"
 #include "nsCOMPtr.h"
 #include "nsDOMUIEvent.h"
 #include "nsIPresShell.h"
 #include "nsIInterfaceRequestorUtils.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIDOMNode.h"
 #include "nsIContent.h"
 #include "nsContentUtils.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "nsLayoutUtils.h"
 #include "nsIScrollableFrame.h"
 
@@ -90,17 +90,17 @@ nsDOMUIEvent::nsDOMUIEvent(nsPresContext
   }
 
   mView = nsnull;
   if (mPresContext)
   {
     nsCOMPtr<nsISupports> container = mPresContext->GetContainer();
     if (container)
     {
-       nsCOMPtr<nsIDOMWindowInternal> window = do_GetInterface(container);
+       nsCOMPtr<nsIDOMWindow> window = do_GetInterface(container);
        if (window)
           mView = do_QueryInterface(window);
     }
   }
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMUIEvent)
 
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -60,37 +60,24 @@
 #include "nsIPresShell.h"
 #include "nsDOMEvent.h"
 #include "nsGkAtoms.h"
 #include "nsIEditorDocShell.h"
 #include "nsIFormControl.h"
 #include "nsIComboboxControlFrame.h"
 #include "nsIScrollableFrame.h"
 #include "nsIDOMNSHTMLElement.h"
-#include "nsIDOMHTMLAnchorElement.h"
-#include "nsIDOMHTMLInputElement.h"
-#include "nsIDOMHTMLLabelElement.h"
-#include "nsIDOMHTMLSelectElement.h"
-#include "nsIDOMHTMLTextAreaElement.h"
-#include "nsIDOMHTMLAreaElement.h"
-#include "nsIDOMHTMLButtonElement.h"
-#include "nsIDOMHTMLObjectElement.h"
-#include "nsIDOMHTMLImageElement.h"
-#include "nsIDOMHTMLMapElement.h"
-#include "nsIDOMHTMLBodyElement.h"
 #include "nsIDOMXULControlElement.h"
-#include "nsIDOMXULTextboxElement.h"
 #include "nsINameSpaceManager.h"
 #include "nsIBaseWindow.h"
 #include "nsIView.h"
 #include "nsIViewManager.h"
 #include "nsISelection.h"
 #include "nsFrameSelection.h"
 #include "nsIPrivateDOMEvent.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsIEnumerator.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewer.h"
 #ifdef MOZ_XUL
@@ -111,17 +98,16 @@
 #include "nsIMarkupDocumentViewer.h"
 #include "nsIDOMMouseScrollEvent.h"
 #include "nsIDOMDragEvent.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMNSUIEvent.h"
 #include "nsDOMDragEvent.h"
 #include "nsIDOMNSEditableElement.h"
 
-#include "nsIDOMRange.h"
 #include "nsCaret.h"
 #include "nsILookAndFeel.h"
 #include "nsWidgetsCID.h"
 
 #include "nsSubDocumentFrame.h"
 #include "nsIFrameTraversal.h"
 #include "nsLayoutCID.h"
 #include "nsLayoutUtils.h"
@@ -213,17 +199,17 @@ PrintDocTree(nsIDocShellTreeItem* aParen
   nsRefPtr<nsPresContext> presContext;
   parentAsDocShell->GetPresContext(getter_AddRefs(presContext));
   nsCOMPtr<nsIContentViewer> cv;
   parentAsDocShell->GetContentViewer(getter_AddRefs(cv));
   nsCOMPtr<nsIDOMDocument> domDoc;
   if (cv)
     cv->GetDOMDocument(getter_AddRefs(domDoc));
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
-  nsCOMPtr<nsIDOMWindowInternal> domwin = doc ? doc->GetWindow() : nsnull;
+  nsCOMPtr<nsIDOMWindow> domwin = doc ? doc->GetWindow() : nsnull;
   nsIURI* uri = doc ? doc->GetDocumentURI() : nsnull;
 
   printf("DS %p  Type %s  Cnt %d  Doc %p  DW %p  EM %p%c",
     static_cast<void*>(parentAsDocShell.get()),
     type==nsIDocShellTreeItem::typeChrome?"Chrome":"Content",
     childWebshellCount, static_cast<void*>(doc.get()),
     static_cast<void*>(domwin.get()),
     static_cast<void*>(presContext ? presContext->EventStateManager() : nsnull),
@@ -2381,17 +2367,17 @@ nsEventStateManager::GetMarkupDocumentVi
   if(!fm) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMWindow> focusedWindow;
   fm->GetFocusedWindow(getter_AddRefs(focusedWindow));
 
   nsCOMPtr<nsPIDOMWindow> ourWindow = do_QueryInterface(focusedWindow);
   if(!ourWindow) return NS_ERROR_FAILURE;
 
-  nsIDOMWindowInternal *rootWindow = ourWindow->GetPrivateRoot();
+  nsIDOMWindow *rootWindow = ourWindow->GetPrivateRoot();
   if(!rootWindow) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMWindow> contentWindow;
   rootWindow->GetContent(getter_AddRefs(contentWindow));
   if(!contentWindow) return NS_ERROR_FAILURE;
 
   nsIDocument *doc = GetDocumentFromWindow(contentWindow);
   if(!doc) return NS_ERROR_FAILURE;
--- a/content/html/content/public/nsIFormSubmitObserver.idl
+++ b/content/html/content/public/nsIFormSubmitObserver.idl
@@ -36,24 +36,24 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 
 #include "nsISupports.idl"
 
 interface nsIDOMHTMLFormElement;
-interface nsIDOMWindowInternal;
+interface nsIDOMWindow;
 interface nsIURI;
 interface nsIArray;
 
-[scriptable, uuid(0b3cc84d-25d2-448e-ae71-746ee6e41c2d)]
+[scriptable, uuid(534ab795-6a99-4195-bfab-cfdd7836657d)]
 interface nsIFormSubmitObserver: nsISupports
 {
-  void notify(in nsIDOMHTMLFormElement formNode, in nsIDOMWindowInternal window, in nsIURI actionURL, out boolean cancelSubmit);
+  void notify(in nsIDOMHTMLFormElement formNode, in nsIDOMWindow window, in nsIURI actionURL, out boolean cancelSubmit);
 
   void notifyInvalidSubmit(in nsIDOMHTMLFormElement formNode,
                            in nsIArray invalidElements);
 };
 
 %{C++
 #define NS_FORMSUBMIT_SUBJECT "formsubmit"
 #define NS_EARLYFORMSUBMIT_SUBJECT "earlyformsubmit"
--- a/content/html/content/src/nsHTMLImageElement.cpp
+++ b/content/html/content/src/nsHTMLImageElement.cpp
@@ -40,17 +40,16 @@
 #include "nsImageLoadingContent.h"
 #include "nsGkAtoms.h"
 #include "nsStyleConsts.h"
 #include "nsPresContext.h"
 #include "nsMappedAttributes.h"
 #include "nsIJSNativeInitializer.h"
 #include "nsSize.h"
 #include "nsIDocument.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMDocument.h"
 #include "nsIScriptContext.h"
 #include "nsIURL.h"
 #include "nsIIOService.h"
 #include "nsIServiceManager.h"
 #include "nsNetUtil.h"
 #include "nsContentUtils.h"
 #include "nsIFrame.h"
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -32,16 +32,18 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+#include "nsHTMLInputElement.h"
+
 #include "nsIDOMHTMLInputElement.h"
 #include "nsITextControlElement.h"
 #include "nsIDOMNSEditableElement.h"
 #include "nsIRadioVisitor.h"
 #include "nsIPhonetic.h"
 
 #include "nsIControllers.h"
 #include "nsFocusManager.h"
@@ -106,32 +108,29 @@
 #include "nsIContentURIGrouper.h"
 #include "nsIContentPrefService.h"
 #include "nsIObserverService.h"
 #include "nsIPopupWindowManager.h"
 #include "nsGlobalWindow.h"
 
 // input type=image
 #include "nsImageLoadingContent.h"
-#include "nsIDOMWindowInternal.h"
 
 #include "mozAutoDocUpdate.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsContentUtils.h"
 #include "nsRadioVisitor.h"
 
 #include "nsTextEditRules.h"
 
 // JS headers are needed for the pattern attribute.
 #include "jsapi.h"
 #include "jscntxt.h"
 
-#include "nsHTMLInputElement.h"
-
 using namespace mozilla::dom;
 
 // XXX align=left, hspace, vspace, border? other nav4 attrs
 
 static NS_DEFINE_CID(kXULControllersCID,  NS_XULCONTROLLERS_CID);
 static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 
 // First bits are needed for the control type.
@@ -263,17 +262,17 @@ protected:
   PopupControlState mPopupControlState;
 };
 
 NS_IMETHODIMP
 AsyncClickHandler::Run()
 {
   nsresult rv;
 
-  // Get parent nsIDOMWindowInternal object.
+  // Get parent nsPIDOMWindow object.
   nsCOMPtr<nsIDocument> doc = mInput->GetOwnerDoc();
   if (!doc)
     return NS_ERROR_FAILURE;
 
   nsPIDOMWindow* win = doc->GetWindow();
   if (!win) {
     return NS_ERROR_FAILURE;
   }
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -394,17 +394,17 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsHTMLMediaElement)
   NS_INTERFACE_MAP_ENTRY(nsIObserver)
 NS_INTERFACE_MAP_END_INHERITING(nsGenericHTMLElement)
 
 // nsIDOMHTMLMediaElement
 NS_IMPL_URI_ATTR(nsHTMLMediaElement, Src, src)
 NS_IMPL_BOOL_ATTR(nsHTMLMediaElement, Controls, controls)
 NS_IMPL_BOOL_ATTR(nsHTMLMediaElement, Autoplay, autoplay)
-NS_IMPL_STRING_ATTR(nsHTMLMediaElement, Preload, preload)
+NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(nsHTMLMediaElement, Preload, preload, NULL)
 
 /* readonly attribute nsIDOMHTMLMediaElement mozAutoplayEnabled; */
 NS_IMETHODIMP nsHTMLMediaElement::GetMozAutoplayEnabled(PRBool *aAutoplayEnabled)
 {
   *aAutoplayEnabled = mAutoplayEnabled;
 
   return NS_OK;
 }
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -263,19 +263,20 @@ include $(topsrcdir)/config/rules.mk
 		test_bug636336.html \
 		test_bug610212.html \
 		test_bug633058.html \
 		test_bug641219.html \
 		test_bug643051.html \
 		test_bug583514.html \
 		test_bug514437.html \
 		test_bug560112.html \
+		test_bug586786.html \
 		test_bug649134.html \
 		test_bug658746.html \
 		test_bug659596.html \
 		test_bug659743.xml \
 		test_bug660663.html \
-		test_bug586786.html \
+		test_bug666666.html \
 		test_restore_from_parser_fragment.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug666666.html
@@ -0,0 +1,33 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=666666
+-->
+<head>
+  <title>Test for Bug 666666</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="reflect.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666666">Mozilla Bug 666666</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+/** Test for Bug 666666 **/
+["audio", "video"].forEach(function(element) {
+  reflectLimitedEnumerated({
+    element: document.createElement(element),
+    attribute: "preload",
+    validValues: ["none", "metadata", "auto"],
+    invalidValues: ["cheesecake", ""]
+  });
+});
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -1523,17 +1523,17 @@ nsHTMLDocument::Open(const nsAString& aC
                      JSContext* cx, PRUint8 aOptionalArgCount,
                      nsISupports** aReturn)
 {
   NS_ASSERTION(nsContentUtils::CanCallerAccess(static_cast<nsIDOMHTMLDocument*>(this)),
                "XOW should have caught this!");
 
   // When called with 3 or more arguments, document.open() calls window.open().
   if (aOptionalArgCount > 2) {
-    nsCOMPtr<nsIDOMWindowInternal> window = GetWindowInternal();
+    nsCOMPtr<nsIDOMWindow> window = GetWindowInternal();
     if (!window) {
       return NS_OK;
     }
     nsCOMPtr<nsIDOMWindow> newWindow;
     nsresult rv = window->Open(aContentTypeOrUrl, aReplaceOrName, aFeatures,
                                getter_AddRefs(newWindow));
     *aReturn = newWindow.forget().get();
     return rv;
--- a/content/smil/nsDOMTimeEvent.cpp
+++ b/content/smil/nsDOMTimeEvent.cpp
@@ -57,17 +57,17 @@ nsDOMTimeEvent::nsDOMTimeEvent(nsPresCon
   }
 
   mEvent->flags |= NS_EVENT_FLAG_CANT_BUBBLE |
                    NS_EVENT_FLAG_CANT_CANCEL;
 
   if (mPresContext) {
     nsCOMPtr<nsISupports> container = mPresContext->GetContainer();
     if (container) {
-      nsCOMPtr<nsIDOMWindowInternal> window = do_GetInterface(container);
+      nsCOMPtr<nsIDOMWindow> window = do_GetInterface(container);
       if (window) {
         mView = do_QueryInterface(window);
       }
     }
   }
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMTimeEvent)
--- a/content/xbl/builtin/emacs/platformHTMLBindings.xml
+++ b/content/xbl/builtin/emacs/platformHTMLBindings.xml
@@ -64,20 +64,16 @@
     <handler event="keypress" keycode="VK_LEFT" modifiers="shift,control" 
         command="cmd_selectWordPrevious"/>
     <handler event="keypress" keycode="VK_RIGHT" modifiers="shift,control" 
         command="cmd_selectWordNext"/>
     <handler event="keypress" key="y" modifiers="accel"
         command="cmd_redo"/>
     <handler event="keypress" key="a" modifiers="alt"
         command="cmd_selectAll"/>
-    <handler event="keypress" keycode="VK_F20" command="cmd_cut" />
-    <handler event="keypress" keycode="VK_F16" command="cmd_copy" />
-    <handler event="keypress" keycode="VK_F18" command="cmd_paste" />
-    <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
     </handlers>
   </binding>
 
   <binding id="textAreas">
     <handlers>
 #include ../textareas-base.inc
     <!-- Emacsish single-line motion and delete keys -->
     <handler event="keypress" key="a" modifiers="control"
@@ -152,20 +148,16 @@
     <handler event="keypress" keycode="VK_RIGHT" modifiers="shift,control" 
         command="cmd_selectWordNext"/>
     <handler event="keypress" keycode="VK_BACK" modifiers="control"
         command="cmd_deleteWordBackward"/>
     <handler event="keypress" key="y" modifiers="accel"
         command="cmd_redo"/>
     <handler event="keypress" key="a" modifiers="alt"
         command="cmd_selectAll"/>
-    <handler event="keypress" keycode="VK_F20" command="cmd_cut" />
-    <handler event="keypress" keycode="VK_F16" command="cmd_copy" />
-    <handler event="keypress" keycode="VK_F18" command="cmd_paste" />
-    <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
     </handlers>
   </binding>
 
   <binding id="browser">
     <handlers>
 #include ../browser-base.inc
       <handler event="keypress" keycode="VK_PAGE_UP" command="cmd_movePageUp"/>
       <handler event="keypress" keycode="VK_PAGE_DOWN" command="cmd_movePageDown"/>
@@ -177,20 +169,16 @@
       <handler event="keypress" keycode="VK_INSERT" modifiers="control" command="cmd_copy" /> 
       <handler event="keypress" keycode="VK_HOME" command="cmd_beginLine"/>
       <handler event="keypress" keycode="VK_END" command="cmd_endLine"/>
       <handler event="keypress" keycode="VK_HOME" modifiers="control" command="cmd_scrollTop"/>
       <handler event="keypress" keycode="VK_END" modifiers="control" command="cmd_scrollBottom"/>
       <handler event="keypress" keycode="VK_HOME" modifiers="shift,control" command="cmd_selectTop" /> 
       <handler event="keypress" keycode="VK_END" modifiers="shift,control" command="cmd_selectBottom" /> 
 
-      <handler event="keypress" keycode="VK_F20" command="cmd_cut" /> 
-      <handler event="keypress" keycode="VK_F16" command="cmd_copy" /> 
-      <handler event="keypress" keycode="VK_F18" command="cmd_paste" /> 
-      <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
       <handler event="keypress" keycode="VK_LEFT" modifiers="control" command="cmd_wordPrevious" />
       <handler event="keypress" keycode="VK_RIGHT" modifiers="control" command="cmd_wordNext" />
       <handler event="keypress" keycode="VK_LEFT" modifiers="control,shift" command="cmd_selectWordPrevious" />
       <handler event="keypress" keycode="VK_RIGHT" modifiers="control,shift" command="cmd_selectWordNext" />
       <handler event="keypress" keycode="VK_LEFT" modifiers="shift" command="cmd_selectCharPrevious" />
       <handler event="keypress" keycode="VK_RIGHT" modifiers="shift" command="cmd_selectCharNext" />
       <handler event="keypress" keycode="VK_HOME" modifiers="shift" command="cmd_selectBeginLine" />
       <handler event="keypress" keycode="VK_END" modifiers="shift" command="cmd_selectEndLine" />
@@ -235,15 +223,11 @@
       <handler event="keypress" keycode="VK_HOME" modifiers="shift,control" command="cmd_selectTop"/>
       <handler event="keypress" keycode="VK_END" modifiers="shift,control" command="cmd_selectBottom"/>
       <handler event="keypress" keycode="VK_HOME" modifiers="control" command="cmd_moveTop"/>
       <handler event="keypress" keycode="VK_END" modifiers="control" command="cmd_moveBottom"/>
       <handler event="keypress" keycode="VK_PAGE_UP" command="cmd_movePageUp"/>
       <handler event="keypress" keycode="VK_PAGE_DOWN" command="cmd_movePageDown"/>
       <handler event="keypress" keycode="VK_PAGE_UP" modifiers="shift" command="cmd_selectPageUp"/>
       <handler event="keypress" keycode="VK_PAGE_DOWN" modifiers="shift" command="cmd_selectPageDown"/>
-      <handler event="keypress" keycode="VK_F20" command="cmd_cut" />
-      <handler event="keypress" keycode="VK_F16" command="cmd_copy" />
-      <handler event="keypress" keycode="VK_F18" command="cmd_paste" />
-      <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
     </handlers>
   </binding>
 </bindings>
--- a/content/xbl/builtin/unix/platformHTMLBindings.xml
+++ b/content/xbl/builtin/unix/platformHTMLBindings.xml
@@ -8,33 +8,28 @@
     <handlers>
 #include ../input-fields-base.inc
     <handler event="keypress" key="a" modifiers="alt"
         command="cmd_selectAll"/>
     <handler event="keypress" key="y" modifiers="accel"
         command="cmd_redo"/>
     <handler event="keypress" key="z" modifiers="accel,shift" command="cmd_redo"/>
     <handler event="keypress" key="z" modifiers="accel" command="cmd_undo"/>
-    <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
     </handlers>
   </binding>
 
   <binding id="textAreas">
     <handlers>
 #include ../textareas-base.inc
     <handler event="keypress" key="a" modifiers="alt"
         command="cmd_selectAll"/>
     <handler event="keypress" key="y" modifiers="accel"
         command="cmd_redo"/>
     <handler event="keypress" key="z" modifiers="accel" command="cmd_undo"/>
     <handler event="keypress" key="z" modifiers="accel,shift" command="cmd_redo"/>
-    <handler event="keypress" keycode="VK_F20" command="cmd_cut" />
-    <handler event="keypress" keycode="VK_F16" command="cmd_copy" />
-    <handler event="keypress" keycode="VK_F18" command="cmd_paste" />
-    <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
     </handlers>
   </binding>
 
   <binding id="browser">
     <handlers>
 #include ../browser-base.inc
       <handler event="keypress" keycode="VK_PAGE_UP" command="cmd_movePageUp"/>
       <handler event="keypress" keycode="VK_PAGE_DOWN" command="cmd_movePageDown"/>
@@ -46,20 +41,16 @@
       <handler event="keypress" keycode="VK_INSERT" modifiers="control" command="cmd_copy" /> 
       <handler event="keypress" keycode="VK_HOME" command="cmd_beginLine"/>
       <handler event="keypress" keycode="VK_END" command="cmd_endLine"/>
       <handler event="keypress" keycode="VK_HOME" modifiers="control" command="cmd_scrollTop"/>
       <handler event="keypress" keycode="VK_END" modifiers="control" command="cmd_scrollBottom"/>
       <handler event="keypress" keycode="VK_HOME" modifiers="shift,control" command="cmd_selectTop" /> 
       <handler event="keypress" keycode="VK_END" modifiers="shift,control" command="cmd_selectBottom" /> 
 
-      <handler event="keypress" keycode="VK_F20" command="cmd_cut" /> 
-      <handler event="keypress" keycode="VK_F16" command="cmd_copy" /> 
-      <handler event="keypress" keycode="VK_F18" command="cmd_paste" /> 
-      <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
       <handler event="keypress" keycode="VK_LEFT" modifiers="control" command="cmd_wordPrevious" />
       <handler event="keypress" keycode="VK_RIGHT" modifiers="control" command="cmd_wordNext" />
       <handler event="keypress" keycode="VK_LEFT" modifiers="control,shift" command="cmd_selectWordPrevious" />
       <handler event="keypress" keycode="VK_RIGHT" modifiers="control,shift" command="cmd_selectWordNext" />
       <handler event="keypress" keycode="VK_LEFT" modifiers="shift" command="cmd_selectCharPrevious" />
       <handler event="keypress" keycode="VK_RIGHT" modifiers="shift" command="cmd_selectCharNext" />
       <handler event="keypress" keycode="VK_HOME" modifiers="shift" command="cmd_selectBeginLine" />
       <handler event="keypress" keycode="VK_END" modifiers="shift" command="cmd_selectEndLine" />
@@ -71,15 +62,11 @@
 
   <binding id="editor">
     <handlers>
 #include ../editor-base.inc
       <handler event="keypress" key="z" modifiers="accel" command="cmd_undo"/>
       <handler event="keypress" key="z" modifiers="accel,shift" command="cmd_redo"/>
       <handler event="keypress" key="y" modifiers="accel"   command="cmd_redo"/>
       <handler event="keypress" key="a" modifiers="alt" command="cmd_selectAll"/>
-      <handler event="keypress" keycode="VK_F20" command="cmd_cut" />
-      <handler event="keypress" keycode="VK_F16" command="cmd_copy" />
-      <handler event="keypress" keycode="VK_F18" command="cmd_paste" />
-      <handler event="keypress" keycode="VK_F14" command="cmd_undo" />
     </handlers>
   </binding>
 </bindings>
--- a/content/xbl/src/nsXBLPrototypeHandler.cpp
+++ b/content/xbl/src/nsXBLPrototypeHandler.cpp
@@ -60,17 +60,17 @@
 #include "nsFocusManager.h"
 #include "nsEventListenerManager.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMEventListener.h"
 #include "nsIPrivateDOMEvent.h"
 #include "nsIDOMNSEvent.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptError.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsGkAtoms.h"
 #include "nsGUIEvent.h"
 #include "nsIXPConnect.h"
 #include "nsIDOMScriptObjectFactory.h"
@@ -565,17 +565,17 @@ nsXBLPrototypeHandler::GetController(nsI
 
   if (!controllers) {
     nsCOMPtr<nsIDOMHTMLInputElement> htmlInputElement(do_QueryInterface(aTarget));
     if (htmlInputElement)
       htmlInputElement->GetControllers(getter_AddRefs(controllers));
   }
 
   if (!controllers) {
-    nsCOMPtr<nsIDOMWindowInternal> domWindow(do_QueryInterface(aTarget));
+    nsCOMPtr<nsIDOMWindow> domWindow(do_QueryInterface(aTarget));
     if (domWindow)
       domWindow->GetControllers(getter_AddRefs(controllers));
   }
 
   // Return the first controller.
   // XXX This code should be checking the command name and using supportscommand and
   // iscommandenabled.
   nsIController* controller;
--- a/content/xbl/src/nsXBLWindowKeyHandler.cpp
+++ b/content/xbl/src/nsXBLWindowKeyHandler.cpp
@@ -49,17 +49,16 @@
 #include "nsXBLService.h"
 #include "nsIServiceManager.h"
 #include "nsGkAtoms.h"
 #include "nsXBLDocumentInfo.h"
 #include "nsIDOMElement.h"
 #include "nsINativeKeyBindings.h"
 #include "nsIController.h"
 #include "nsIControllers.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsFocusManager.h"
 #include "nsPIWindowRoot.h"
 #include "nsIURI.h"
 #include "nsNetUtil.h"
 #include "nsContentUtils.h"
 #include "nsXBLPrototypeBinding.h"
 #include "nsIDOMDocument.h"
 #include "nsPIWindowRoot.h"
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -75,17 +75,16 @@
 #include "nsIScriptElement.h"
 #include "nsScriptLoader.h"
 #include "nsStyleLinkElement.h"
 #include "nsIImageLoadingContent.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsICookieService.h"
 #include "nsIPrompt.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIChannel.h"
 #include "nsIPrincipal.h"
 #include "nsXMLPrettyPrinter.h"
 #include "nsNodeInfoManager.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsIContentPolicy.h"
 #include "nsIDocumentViewer.h"
 #include "nsContentPolicyUtils.h"
--- a/content/xul/content/src/nsXULPopupListener.cpp
+++ b/content/xul/content/src/nsXULPopupListener.cpp
@@ -52,17 +52,17 @@
 #include "nsIDOMNodeList.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsContentCID.h"
 #include "nsContentUtils.h"
 #include "nsXULPopupManager.h"
 #include "nsEventStateManager.h"
 #include "nsIScriptContext.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDocument.h"
 #include "nsIDOMNSUIEvent.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMNSEvent.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptSecurityManager.h"
--- a/content/xul/document/public/nsIController.idl
+++ b/content/xul/document/public/nsIController.idl
@@ -65,17 +65,17 @@ interface nsICommandController : nsISupp
     
   void        doCommandWithParams(in string command, in nsICommandParams aCommandParams);
 
 };
 
 
 /*
   An API for registering commands in groups, to allow for 
-  updating via nsIDOMWindowInternal::UpdateCommands.
+  updating via nsIDOMWindow::UpdateCommands.
 */
 interface nsISimpleEnumerator;
 
 [scriptable, uuid(9F82C404-1C7B-11D5-A73C-ECA43CA836FC)]
 interface nsIControllerCommandGroup : nsISupports
 {
 
   void  addCommandToGroup(in string aCommand, in string aGroup);
--- a/content/xul/document/src/nsXULCommandDispatcher.cpp
+++ b/content/xul/document/src/nsXULCommandDispatcher.cpp
@@ -45,17 +45,17 @@
 
 #include "nsIContent.h"
 #include "nsFocusManager.h"
 #include "nsIControllers.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMElement.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIDOMXULElement.h"
 #include "nsIDocument.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsRDFCID.h"
--- a/docshell/base/nsDSURIContentListener.cpp
+++ b/docshell/base/nsDSURIContentListener.cpp
@@ -1,11 +1,10 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * ***** BEGIN LICENSE BLOCK *****
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  *
  * The contents of this file are subject to the Mozilla Public License Version
  * 1.1 (the "License"); you may not use this file except in compliance with
  * the License. You may obtain a copy of the License at
  * http://www.mozilla.org/MPL/
  *
  * Software distributed under the License is distributed on an "AS IS" basis,
@@ -39,17 +38,17 @@
 
 #include "nsDocShell.h"
 #include "nsDSURIContentListener.h"
 #include "nsIChannel.h"
 #include "nsServiceManagerUtils.h"
 #include "nsXPIDLString.h"
 #include "nsDocShellCID.h"
 #include "nsIWebNavigationInfo.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsAutoPtr.h"
 #include "nsIHttpChannel.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsNetError.h"
 
 //*****************************************************************************
 //***    nsDSURIContentListener: Object Management
 //*****************************************************************************
@@ -153,17 +152,17 @@ nsDSURIContentListener::DoContent(const 
     }
 
     if (NS_FAILED(rv)) {
        // it's okay if we don't know how to handle the content   
         return NS_OK;
     }
 
     if (loadFlags & nsIChannel::LOAD_RETARGETED_DOCUMENT_URI) {
-        nsCOMPtr<nsIDOMWindowInternal> domWindow = do_GetInterface(static_cast<nsIDocShell*>(mDocShell));
+        nsCOMPtr<nsIDOMWindow> domWindow = do_GetInterface(static_cast<nsIDocShell*>(mDocShell));
         NS_ENSURE_TRUE(domWindow, NS_ERROR_FAILURE);
         domWindow->Focus();
     }
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -48,17 +48,16 @@
 
 #include "nsIBrowserDOMWindow.h"
 #include "nsIComponentManager.h"
 #include "nsIContent.h"
 #include "mozilla/dom/Element.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
-#include "nsIDOMStorageObsolete.h"
 #include "nsIDOMStorage.h"
 #include "nsPIDOMStorage.h"
 #include "nsIDocumentViewer.h"
 #include "nsIDocumentLoaderFactory.h"
 #include "nsCURILoader.h"
 #include "nsURILoader.h"
 #include "nsDocShellCID.h"
 #include "nsLayoutCID.h"
@@ -66,17 +65,17 @@
 #include "nsIDOMScriptObjectFactory.h"
 #include "nsNetUtil.h"
 #include "nsRect.h"
 #include "prprf.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsIDOMChromeWindow.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIWebBrowserChrome.h"
 #include "nsPoint.h"
 #include "nsGfxCIID.h"
 #include "nsIObserverService.h"
 #include "nsIPrompt.h"
 #include "nsIAuthPrompt.h"
 #include "nsIAuthPrompt2.h"
 #include "nsTextFormatter.h"
@@ -170,19 +169,16 @@
 #include "nsPIWindowRoot.h"
 #include "nsIDOMDocument.h"
 #include "nsICachingChannel.h"
 #include "nsICacheVisitor.h"
 #include "nsICacheEntryDescriptor.h"
 #include "nsIMultiPartChannel.h"
 #include "nsIWyciwygChannel.h"
 
-// The following are for bug #13871: Prevent frameset spoofing
-#include "nsIHTMLDocument.h"
-
 // For reporting errors with the console service.
 // These can go away if error reporting is propagated up past nsDocShell.
 #include "nsIConsoleService.h"
 #include "nsIScriptError.h"
 
 // used to dispatch urls to default protocol handlers
 #include "nsCExternalHandlerService.h"
 #include "nsIExternalProtocolService.h"
@@ -918,18 +914,17 @@ NS_IMETHODIMP nsDocShell::GetInterface(c
     }
     else if (aIID.Equals(NS_GET_IID(nsIURIContentListener))) {
         *aSink = mContentListener;
     }
     else if (aIID.Equals(NS_GET_IID(nsIScriptGlobalObject)) &&
              NS_SUCCEEDED(EnsureScriptEnvironment())) {
         *aSink = mScriptGlobal;
     }
-    else if ((aIID.Equals(NS_GET_IID(nsIDOMWindowInternal)) ||
-              aIID.Equals(NS_GET_IID(nsPIDOMWindow)) ||
+    else if ((aIID.Equals(NS_GET_IID(nsPIDOMWindow)) ||
               aIID.Equals(NS_GET_IID(nsIDOMWindow))) &&
              NS_SUCCEEDED(EnsureScriptEnvironment())) {
         return mScriptGlobal->QueryInterface(aIID, aSink);
     }
     else if (aIID.Equals(NS_GET_IID(nsIDOMDocument)) &&
              NS_SUCCEEDED(EnsureContentViewer())) {
         mContentViewer->GetDOMDocument((nsIDOMDocument **) aSink);
         return *aSink ? NS_OK : NS_NOINTERFACE;
@@ -2771,40 +2766,38 @@ nsDocShell::CanAccessItem(nsIDocShellTre
         return PR_FALSE;
     }
 
     if (!aConsiderOpener) {
         // All done here
         return PR_FALSE;
     }
 
-    nsCOMPtr<nsIDOMWindow> targetWindow(do_GetInterface(aTargetItem));
-    nsCOMPtr<nsIDOMWindowInternal> targetInternal(do_QueryInterface(targetWindow));
-    if (!targetInternal) {
+    nsCOMPtr<nsIDOMWindow> targetWindow = do_GetInterface(aTargetItem);
+    if (!targetWindow) {
         NS_ERROR("This should not happen, really");
         return PR_FALSE;
     }
 
-    nsCOMPtr<nsIDOMWindowInternal> targetOpener;
-    targetInternal->GetOpener(getter_AddRefs(targetOpener));
+    nsCOMPtr<nsIDOMWindow> targetOpener;
+    targetWindow->GetOpener(getter_AddRefs(targetOpener));
     nsCOMPtr<nsIWebNavigation> openerWebNav(do_GetInterface(targetOpener));
     nsCOMPtr<nsIDocShellTreeItem> openerItem(do_QueryInterface(openerWebNav));
 
     if (!openerItem) {
         return PR_FALSE;
     }
 
     return CanAccessItem(openerItem, aAccessingItem, PR_FALSE);    
 }
 
 static PRBool
 ItemIsActive(nsIDocShellTreeItem *aItem)
 {
-    nsCOMPtr<nsIDOMWindow> tmp(do_GetInterface(aItem));
-    nsCOMPtr<nsIDOMWindowInternal> window(do_QueryInterface(tmp));
+    nsCOMPtr<nsIDOMWindow> window(do_GetInterface(aItem));
 
     if (window) {
         PRBool isClosed;
 
         if (NS_SUCCEEDED(window->GetClosed(&isClosed)) && !isClosed) {
             return PR_TRUE;
         }
     }
@@ -2984,17 +2977,17 @@ PrintDocTree(nsIDocShellTreeItem * aPare
   PRInt32 type;
   aParentNode->GetItemType(&type);
   nsCOMPtr<nsIPresShell> presShell;
   parentAsDocShell->GetPresShell(getter_AddRefs(presShell));
   nsRefPtr<nsPresContext> presContext;
   parentAsDocShell->GetPresContext(getter_AddRefs(presContext));
   nsIDocument *doc = presShell->GetDocument();
 
-  nsCOMPtr<nsIDOMWindowInternal> domwin(doc->GetWindow());
+  nsCOMPtr<nsIDOMWindow> domwin(doc->GetWindow());
 
   nsCOMPtr<nsIWidget> widget;
   nsIViewManager* vm = presShell->GetViewManager();
   if (vm) {
     vm->GetWidget(getter_AddRefs(widget));
   }
   dom::Element* rootElement = doc->GetRootElement();
 
@@ -8229,17 +8222,17 @@ nsDocShell::InternalLoad(nsIURI * aURI,
         nsCOMPtr<nsIDocShellTreeItem> targetItem;
         FindItemWithName(aWindowTarget, nsnull, this,
                          getter_AddRefs(targetItem));
 
         nsCOMPtr<nsIDocShell> targetDocShell = do_QueryInterface(targetItem);
         
         PRBool isNewWindow = PR_FALSE;
         if (!targetDocShell) {
-            nsCOMPtr<nsIDOMWindowInternal> win =
+            nsCOMPtr<nsIDOMWindow> win =
                 do_GetInterface(GetAsSupports(this));
             NS_ENSURE_TRUE(win, NS_ERROR_NOT_AVAILABLE);
 
             nsDependentString name(aWindowTarget);
             nsCOMPtr<nsIDOMWindow> newWin;
             rv = win->Open(EmptyString(), // URL to load
                            name,          // window name
                            EmptyString(), // Features
@@ -8285,17 +8278,17 @@ nsDocShell::InternalLoad(nsIURI * aURI,
                 if (isNewWindow) {
                     //
                     // At this point, a new window has been created, but the
                     // URI did not have any data associated with it...
                     //
                     // So, the best we can do, is to tear down the new window
                     // that was just created!
                     //
-                    nsCOMPtr<nsIDOMWindowInternal> domWin =
+                    nsCOMPtr<nsIDOMWindow> domWin =
                         do_GetInterface(targetDocShell);
                     if (domWin) {
                         domWin->Close();
                     }
                 }
                 //
                 // NS_ERROR_NO_CONTENT should not be returned to the
                 // caller... This is an internal error code indicating that
--- a/docshell/base/nsIContentViewerFile.idl
+++ b/docshell/base/nsIContentViewerFile.idl
@@ -35,36 +35,35 @@
  * 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 "nsISupports.idl"
 #include "nsIPrintSettings.idl"
 
-interface nsIDOMWindowInternal;
+interface nsIDOMWindow;
 interface nsIWebProgressListener;
 
 %{ C++
 #include <stdio.h>
 %}
 
 [ptr] native FILE(FILE);
 
 /**
  * The nsIDocShellFile    
  */
 
-[scriptable, uuid(6317f32c-9bc7-11d3-bccc-0060b0fc76bd)]
+[scriptable, uuid(1b373597-6132-49f7-940e-6ff62fca5d35)]
 interface nsIContentViewerFile : nsISupports
 {
-  /* readonly attribute boolean printable; */
   readonly attribute boolean printable;
 
   [noscript] void print(in boolean aSilent,
                         in FILE    aDebugFile, 
                         in nsIPrintSettings aPrintSettings);
 
-  [noscript] void printWithParent(in nsIDOMWindowInternal aParentWin,
+  [noscript] void printWithParent(in nsIDOMWindow aParentWin,
                                   in nsIPrintSettings aThePrintSettings,
                                   in nsIWebProgressListener aWPListener);
 
 };
--- a/dom/base/nsBarProps.cpp
+++ b/dom/base/nsBarProps.cpp
@@ -31,26 +31,27 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+#include "nsBarProps.h"
+
 #include "nsCOMPtr.h"
 #include "nscore.h"
-#include "nsBarProps.h"
 #include "nsGlobalWindow.h"
 #include "nsStyleConsts.h"
 #include "nsIDocShell.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIScrollable.h"
 #include "nsIWebBrowserChrome.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsDOMClassInfo.h"
 
 //
 //  Basic (virtual) BarProp class implementation
 //
 nsBarProp::nsBarProp(nsGlobalWindow *aWindow)
 {
   mDOMWindow = aWindow;
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -109,17 +109,17 @@
 #include "nsJSEnvironment.h"
 
 // DOM base includes
 #include "nsIDOMPluginArray.h"
 #include "nsIDOMPlugin.h"
 #include "nsIDOMMimeTypeArray.h"
 #include "nsIDOMMimeType.h"
 #include "nsIDOMLocation.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMJSWindow.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIDOMHistory.h"
 #include "nsIDOMMediaList.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsIDOMConstructor.h"
 #include "nsIDOMPerformanceTiming.h"
@@ -2387,49 +2387,41 @@ nsDOMClassInfo::Init()
   rv = stack->GetSafeJSContext(&cx);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (nsGlobalWindow::HasIndexedDBSupport()) {
     if (nsGlobalWindow::HasPerformanceSupport()) {
       DOM_CLASSINFO_MAP_BEGIN(Window, nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowInternal)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageIndexedDB)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowPerformance)
       DOM_CLASSINFO_MAP_END
     } else {
       DOM_CLASSINFO_MAP_BEGIN(Window, nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowInternal)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageIndexedDB)
       DOM_CLASSINFO_MAP_END
     }
   } else {
     if (nsGlobalWindow::HasPerformanceSupport()) {
       DOM_CLASSINFO_MAP_BEGIN(Window, nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowInternal)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowPerformance)
       DOM_CLASSINFO_MAP_END
     } else {
       DOM_CLASSINFO_MAP_BEGIN(Window, nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowInternal)
         DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-        DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageWindow)
       DOM_CLASSINFO_MAP_END
     }
   }
 
   DOM_CLASSINFO_MAP_BEGIN(WindowUtils, nsIDOMWindowUtils)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowUtils)
   DOM_CLASSINFO_MAP_END
 
@@ -3138,20 +3130,18 @@ nsDOMClassInfo::Init()
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMProcessingInstruction)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMLinkStyle)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN_NO_CLASS_IF(ChromeWindow, nsIDOMWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowInternal)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMChromeWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageIndexedDB)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(RangeException, nsIDOMRangeException)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMRangeException)
     DOM_CLASSINFO_MAP_ENTRY(nsIException)
   DOM_CLASSINFO_MAP_END
 
@@ -4033,19 +4023,17 @@ nsDOMClassInfo::Init()
 
   DOM_CLASSINFO_MAP_BEGIN(DOMStringMap, nsIDOMDOMStringMap)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMDOMStringMap)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN_NO_CLASS_IF(ModalContentWindow, nsIDOMWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowInternal)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageWindow)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMStorageIndexedDB)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMModalContentWindow)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(DataContainerEvent, nsIDOMDataContainerEvent)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMDataContainerEvent)
     DOM_CLASSINFO_EVENT_MAP_ENTRIES
   DOM_CLASSINFO_MAP_END
@@ -5566,17 +5554,17 @@ nsWindowSH::SetProperty(nsIXPConnectWrap
                         JSObject *obj, jsid id, jsval *vp, PRBool *_retval)
 {
   if (id == sLocation_id) {
     JSAutoRequest ar(cx);
 
     JSString *val = ::JS_ValueToString(cx, *vp);
     NS_ENSURE_TRUE(val, NS_ERROR_UNEXPECTED);
 
-    nsCOMPtr<nsIDOMWindowInternal> window(do_QueryWrappedNative(wrapper));
+    nsCOMPtr<nsIDOMWindow> window = do_QueryWrappedNative(wrapper);
     NS_ENSURE_TRUE(window, NS_ERROR_UNEXPECTED);
 
     nsCOMPtr<nsIDOMLocation> location;
     nsresult rv = window->GetLocation(getter_AddRefs(location));
     NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && location, rv);
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
     rv = WrapNative(cx, obj, location, &NS_GET_IID(nsIDOMLocation), PR_TRUE,
@@ -6910,17 +6898,17 @@ nsWindowSH::NewResolve(nsIXPConnectWrapp
         // again for this property name.
 
         JSObject *wrapperObj;
         wrapper->GetJSObject(&wrapperObj);
 
         jsval v;
         nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
         rv = WrapNative(cx, wrapperObj, child_win,
-                        &NS_GET_IID(nsIDOMWindowInternal), PR_TRUE, &v,
+                        &NS_GET_IID(nsIDOMWindow), PR_TRUE, &v,
                         getter_AddRefs(holder));
         NS_ENSURE_SUCCESS(rv, rv);
 
         JSAutoRequest ar(cx);
 
         PRBool ok = JS_WrapValue(cx, &v) &&
                     JS_DefinePropertyById(cx, obj, id, v, nsnull, nsnull, 0);
         if (!ok) {
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -1338,24 +1338,22 @@ nsGlobalWindow::FreeInnerObjects(PRBool 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsGlobalWindow)
 
 DOMCI_DATA(Window, nsGlobalWindow)
 
 // QueryInterface implementation for nsGlobalWindow
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsGlobalWindow)
   // Make sure this matches the cast in nsGlobalWindow::FromWrapper()
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIScriptGlobalObject)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMWindowInternal)
   NS_INTERFACE_MAP_ENTRY(nsIDOMWindow)
   NS_INTERFACE_MAP_ENTRY(nsIDOMJSWindow)
   NS_INTERFACE_MAP_ENTRY(nsIScriptGlobalObject)
   NS_INTERFACE_MAP_ENTRY(nsIScriptObjectPrincipal)
   NS_INTERFACE_MAP_ENTRY(nsIDOMEventTarget)
   NS_INTERFACE_MAP_ENTRY(nsPIDOMWindow)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMStorageWindow)
   NS_INTERFACE_MAP_ENTRY(nsIDOMStorageIndexedDB)
   NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
   NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
   NS_INTERFACE_MAP_ENTRY(nsIDOMWindowPerformance)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Window)
   OUTER_WINDOW_ONLY
     NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   END_OUTER_WINDOW_ONLY
@@ -1834,18 +1832,16 @@ nsGlobalWindow::SetNewDocument(nsIDocume
   if (aForceReuseInnerWindow &&
       !wouldReuseInnerWindow &&
       mDoc &&
       mDoc->NodePrincipal() != aDocument->NodePrincipal()) {
     NS_ERROR("Attempted forced inner window reuse while changing principal");
     return NS_ERROR_UNEXPECTED;
   }
 
-  nsresult rv = NS_OK;
-
   nsCOMPtr<nsIDocument> oldDoc(do_QueryInterface(mDocument));
 
   nsIScriptContext *scx = GetContextInternal();
   NS_ENSURE_TRUE(scx, NS_ERROR_NOT_INITIALIZED);
 
   JSContext *cx = (JSContext *)scx->GetNativeContext();
 #ifndef MOZ_DISABLE_DOMCRYPTO
   // clear smartcard events, our document has gone away.
@@ -1854,19 +1850,19 @@ nsGlobalWindow::SetNewDocument(nsIDocume
   }
 #endif
   if (!mDocument) {
     // First document load.
 
     // Get our private root. If it is equal to us, then we need to
     // attach our global key bindings that handles browser scrolling
     // and other browser commands.
-    nsIDOMWindowInternal *internal = nsGlobalWindow::GetPrivateRoot();
-
-    if (internal == static_cast<nsIDOMWindowInternal *>(this)) {
+    nsIDOMWindow* privateRoot = nsGlobalWindow::GetPrivateRoot();
+
+    if (privateRoot == static_cast<nsIDOMWindow*>(this)) {
       nsCOMPtr<nsIXBLService> xblService = do_GetService("@mozilla.org/xbl;1");
       if (xblService) {
         xblService->AttachGlobalKeyHandler(mChromeEventHandler);
       }
     }
   }
 
   /* No mDocShell means we're already been partially closed down.  When that
@@ -1879,16 +1875,18 @@ nsGlobalWindow::SetNewDocument(nsIDocume
   PRBool reUseInnerWindow = aForceReuseInnerWindow || wouldReuseInnerWindow;
 
   // Remember the old document's principal.
   nsIPrincipal *oldPrincipal = nsnull;
   if (oldDoc) {
     oldPrincipal = oldDoc->NodePrincipal();
   }
 
+  nsresult rv = NS_OK;
+
   // Drop our reference to the navigator object unless we're reusing
   // the existing inner window or the new document is from the same
   // origin as the old document.
   if (!reUseInnerWindow && mNavigator && oldPrincipal) {
     PRBool equal;
     rv = oldPrincipal->Equals(aDocument->NodePrincipal(), &equal);
 
     if (NS_FAILED(rv) || !equal) {
@@ -2472,17 +2470,17 @@ nsGlobalWindow::SetDocShell(nsIDocShell*
 
     PRBool docShellActive;
     mDocShell->GetIsActive(&docShellActive);
     mIsBackground = !docShellActive;
   }
 }
 
 void
-nsGlobalWindow::SetOpenerWindow(nsIDOMWindowInternal* aOpener,
+nsGlobalWindow::SetOpenerWindow(nsIDOMWindow* aOpener,
                                 PRBool aOriginalOpener)
 {
   FORWARD_TO_OUTER_VOID(SetOpenerWindow, (aOpener, aOriginalOpener));
 
   NS_ASSERTION(!aOriginalOpener || !mSetOpenerWindowCalled,
                "aOriginalOpener is true, but not first call to "
                "SetOpenerWindow!");
   NS_ASSERTION(aOpener || !aOriginalOpener,
@@ -2907,36 +2905,32 @@ nsGlobalWindow::GetDocument(nsIDOMDocume
   if (!mDocument && (docShell = GetDocShell()))
     nsCOMPtr<nsIDOMDocument> domdoc(do_GetInterface(docShell));
 
   NS_IF_ADDREF(*aDocument = mDocument);
 
   return NS_OK;
 }
 
-//*****************************************************************************
-// nsGlobalWindow::nsIDOMWindowInternal
-//*****************************************************************************
-
-NS_IMETHODIMP
-nsGlobalWindow::GetWindow(nsIDOMWindowInternal** aWindow)
+NS_IMETHODIMP
+nsGlobalWindow::GetWindow(nsIDOMWindow** aWindow)
 {
   FORWARD_TO_OUTER(GetWindow, (aWindow), NS_ERROR_NOT_INITIALIZED);
 
-  *aWindow = static_cast<nsIDOMWindowInternal *>(this);
+  *aWindow = static_cast<nsIDOMWindow*>(this);
   NS_ADDREF(*aWindow);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsGlobalWindow::GetSelf(nsIDOMWindowInternal** aWindow)
+nsGlobalWindow::GetSelf(nsIDOMWindow** aWindow)
 {
   FORWARD_TO_OUTER(GetSelf, (aWindow), NS_ERROR_NOT_INITIALIZED);
 
-  *aWindow = static_cast<nsIDOMWindowInternal *>(this);
+  *aWindow = static_cast<nsIDOMWindow*>(this);
   NS_ADDREF(*aWindow);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGlobalWindow::GetNavigator(nsIDOMNavigator** aNavigator)
 {
   FORWARD_TO_OUTER(GetNavigator, (aNavigator), NS_ERROR_NOT_INITIALIZED);
@@ -3037,17 +3031,17 @@ nsGlobalWindow::GetParent(nsIDOMWindow**
   docShellAsItem->GetSameTypeParent(getter_AddRefs(parent));
 
   if (parent) {
     nsCOMPtr<nsIScriptGlobalObject> globalObject(do_GetInterface(parent));
     NS_ENSURE_SUCCESS(CallQueryInterface(globalObject.get(), aParent),
                       NS_ERROR_FAILURE);
   }
   else {
-    *aParent = static_cast<nsIDOMWindowInternal *>(this);
+    *aParent = static_cast<nsIDOMWindow*>(this);
     NS_ADDREF(*aParent);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGlobalWindow::GetTop(nsIDOMWindow** aTop)
 {
@@ -3099,17 +3093,17 @@ nsGlobalWindow::GetContent(nsIDOMWindow*
   if (!primaryContent) {
     nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
     GetTreeOwner(getter_AddRefs(treeOwner));
     NS_ENSURE_TRUE(treeOwner, NS_ERROR_FAILURE);
 
     treeOwner->GetPrimaryContentShell(getter_AddRefs(primaryContent));
   }
 
-  nsCOMPtr<nsIDOMWindowInternal> domWindow(do_GetInterface(primaryContent));
+  nsCOMPtr<nsIDOMWindow> domWindow(do_GetInterface(primaryContent));
   NS_IF_ADDREF(*aContent = domWindow);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGlobalWindow::GetPrompter(nsIPrompt** aPrompt)
 {
@@ -3356,17 +3350,17 @@ nsGlobalWindow::GetControllers(nsIContro
   }
 
   *aResult = mControllers;
   NS_ADDREF(*aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsGlobalWindow::GetOpener(nsIDOMWindowInternal** aOpener)
+nsGlobalWindow::GetOpener(nsIDOMWindow** aOpener)
 {
   FORWARD_TO_OUTER(GetOpener, (aOpener), NS_ERROR_NOT_INITIALIZED);
 
   *aOpener = nsnull;
 
   nsCOMPtr<nsPIDOMWindow> opener = do_QueryReferent(mOpener);
   if (!opener) {
     return NS_OK;
@@ -3408,17 +3402,17 @@ nsGlobalWindow::GetOpener(nsIDOMWindowIn
     }
   }
 
   NS_IF_ADDREF(*aOpener);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsGlobalWindow::SetOpener(nsIDOMWindowInternal* aOpener)
+nsGlobalWindow::SetOpener(nsIDOMWindow* aOpener)
 {
   // check if we were called from a privileged chrome script.
   // If not, opener is settable only to null.
   if (aOpener && !nsContentUtils::IsCallerTrustedForWrite()) {
     return NS_OK;
   }
 
   SetOpenerWindow(aOpener, PR_FALSE);
@@ -4399,17 +4393,17 @@ nsGlobalWindow::SetFullScreen(PRBool aFu
   }
 
   // SetFullScreen needs to be called on the root window, so get that
   // via the DocShell tree, and if we are not already the root,
   // call SetFullScreen on that window instead.
   nsCOMPtr<nsIDocShellTreeItem> treeItem = do_QueryInterface(mDocShell);
   nsCOMPtr<nsIDocShellTreeItem> rootItem;
   treeItem->GetRootTreeItem(getter_AddRefs(rootItem));
-  nsCOMPtr<nsIDOMWindowInternal> window = do_GetInterface(rootItem);
+  nsCOMPtr<nsIDOMWindow> window = do_GetInterface(rootItem);
   if (!window)
     return NS_ERROR_FAILURE;
   if (rootItem != treeItem)
     return window->SetFullScreen(aFullScreen);
 
   // make sure we don't try to set full screen on a non-chrome window,
   // which might happen in embedding world
   PRInt32 itemType;
@@ -4454,17 +4448,17 @@ nsGlobalWindow::GetFullScreen(PRBool* aF
 
   // Get the fullscreen value of the root window, to always have the value
   // accurate, even when called from content.
   nsCOMPtr<nsIDocShellTreeItem> treeItem = do_QueryInterface(mDocShell);
   if (treeItem) {
     nsCOMPtr<nsIDocShellTreeItem> rootItem;
     treeItem->GetRootTreeItem(getter_AddRefs(rootItem));
     if (rootItem != treeItem) {
-      nsCOMPtr<nsIDOMWindowInternal> window = do_GetInterface(rootItem);
+      nsCOMPtr<nsIDOMWindow> window = do_GetInterface(rootItem);
       if (window)
         return window->GetFullScreen(aFullScreen);
     }
   }
 
   // We are the root window, or something went wrong. Return our internal value.
   *aFullScreen = mFullScreen;
   return NS_OK;
@@ -4924,19 +4918,19 @@ nsGlobalWindow::Focus()
     baseWin->GetVisibility(&isVisible);
   }
 
   if (!isVisible) {
     // A hidden tab is being focused, ignore this call.
     return NS_OK;
   }
 
-  nsIDOMWindowInternal *caller =
-    static_cast<nsIDOMWindowInternal*>(nsContentUtils::GetWindowFromCaller());
-  nsCOMPtr<nsIDOMWindowInternal> opener;
+  nsIDOMWindow *caller =
+    static_cast<nsIDOMWindow*>(nsContentUtils::GetWindowFromCaller());
+  nsCOMPtr<nsIDOMWindow> opener;
   GetOpener(getter_AddRefs(opener));
 
   // Enforce dom.disable_window_flip (for non-chrome), but still allow the
   // window which opened us to raise us at times when popups are allowed
   // (bugs 355482 and 369306).
   PRBool canFocus = CanSetProperty("dom.disable_window_flip") ||
                     (opener == caller &&
                      RevisePopupAbuseLevel(gPopupControlState) < openAbused);
@@ -4972,17 +4966,17 @@ nsGlobalWindow::Focus()
   nsCOMPtr<nsIPresShell> presShell;
   // Don't look for a presshell if we're a root chrome window that's got
   // about:blank loaded.  We don't want to focus our widget in that case.
   // XXXbz should we really be checking for IsInitialDocument() instead?
   PRBool lookForPresShell = PR_TRUE;
   PRInt32 itemType = nsIDocShellTreeItem::typeContent;
   treeItem->GetItemType(&itemType);
   if (itemType == nsIDocShellTreeItem::typeChrome &&
-      GetPrivateRoot() == static_cast<nsIDOMWindowInternal*>(this) &&
+      GetPrivateRoot() == static_cast<nsIDOMWindow*>(this) &&
       mDocument) {
     nsCOMPtr<nsIDocument> doc(do_QueryInterface(mDocument));
     NS_ASSERTION(doc, "Bogus doc?");
     nsIURI* ourURI = doc->GetDocumentURI();
     if (ourURI) {
       lookForPresShell = !IsAboutBlank(ourURI);
     }
   }
@@ -5390,17 +5384,17 @@ nsGlobalWindow::GetWindowRoot(nsIDOMEven
 {
   nsCOMPtr<nsPIWindowRoot> root = GetTopWindowRoot();
   return CallQueryInterface(root, aWindowRoot);
 }
 
 already_AddRefed<nsPIWindowRoot>
 nsGlobalWindow::GetTopWindowRoot()
 {
-  nsIDOMWindowInternal *rootWindow = GetPrivateRoot();
+  nsIDOMWindow *rootWindow = GetPrivateRoot();
   nsCOMPtr<nsPIDOMWindow> piWin(do_QueryInterface(rootWindow));
   if (!piWin)
     return nsnull;
 
   nsCOMPtr<nsPIWindowRoot> window = do_QueryInterface(piWin->GetChromeEventHandler());
   return window.forget();
 }
 
@@ -7149,17 +7143,17 @@ nsGlobalWindow::Find(const nsAString& aS
   }
   
   // The Find API does not accept empty strings. Launch the Find Dialog.
   if (aStr.IsEmpty() || aShowDialog) {
     // See if the find dialog is already up using nsIWindowMediator
     nsCOMPtr<nsIWindowMediator> windowMediator =
       do_GetService(NS_WINDOWMEDIATOR_CONTRACTID);
 
-    nsCOMPtr<nsIDOMWindowInternal> findDialog;
+    nsCOMPtr<nsIDOMWindow> findDialog;
 
     if (windowMediator) {
       windowMediator->GetMostRecentWindow(NS_LITERAL_STRING("findInPage").get(),
                                           getter_AddRefs(findDialog));
     }
 
     if (findDialog) {
       // The Find dialog is already open, bring it to the top.
@@ -7455,19 +7449,19 @@ nsGlobalWindow::ActivateOrDeactivate(PRB
   // Get the top level widget (if the main widget is a sheet, this will
   // be the sheet's top (non-sheet) parent).
   nsCOMPtr<nsIWidget> topLevelWidget = mainWidget->GetSheetWindowParent();
   if (!topLevelWidget) {
     topLevelWidget = mainWidget;
   }
 
   // Get the top level widget's nsGlobalWindow
-  nsCOMPtr<nsIDOMWindowInternal> topLevelWindow;
+  nsCOMPtr<nsIDOMWindow> topLevelWindow;
   if (topLevelWidget == mainWidget) {
-    topLevelWindow = static_cast<nsIDOMWindowInternal*>(this);
+    topLevelWindow = static_cast<nsIDOMWindow*>(this);
   } else {
     // This is a workaround for the following problem:
     // When a window with an open sheet loses focus, only the sheet window
     // receives the NS_DEACTIVATE event. However, it's not the sheet that
     // should lose the active styling, but the containing top level window.
     void* clientData;
     topLevelWidget->GetClientData(clientData); // clientData is nsXULWindow
     nsISupports* data = static_cast<nsISupports*>(clientData);
@@ -8022,20 +8016,16 @@ nsGlobalWindow::GetComputedStyle(nsIDOME
                                        getter_AddRefs(compStyle));
   NS_ENSURE_SUCCESS(rv, rv);
 
   *aReturn = compStyle.forget().get();
 
   return NS_OK;
 }
 
-//*****************************************************************************
-// nsGlobalWindow::nsIDOMStorageWindow
-//*****************************************************************************
-
 NS_IMETHODIMP
 nsGlobalWindow::GetSessionStorage(nsIDOMStorage ** aSessionStorage)
 {
   FORWARD_TO_INNER(GetSessionStorage, (aSessionStorage), NS_ERROR_UNEXPECTED);
 
   nsIPrincipal *principal = GetPrincipal();
   nsIDocShell* docShell = GetDocShell();
 
@@ -8578,34 +8568,29 @@ nsGlobalWindow::FireDelayedDOMEvents()
 
   return NS_OK;
 }
 
 //*****************************************************************************
 // nsGlobalWindow: Window Control Functions
 //*****************************************************************************
 
-nsIDOMWindowInternal *
+nsIDOMWindow *
 nsGlobalWindow::GetParentInternal()
 {
   FORWARD_TO_OUTER(GetParentInternal, (), nsnull);
 
-  nsIDOMWindowInternal *parentInternal = nsnull;
-
   nsCOMPtr<nsIDOMWindow> parent;
   GetParent(getter_AddRefs(parent));
 
   if (parent && parent != static_cast<nsIDOMWindow *>(this)) {
-    nsCOMPtr<nsIDOMWindowInternal> tmp(do_QueryInterface(parent));
-    NS_ASSERTION(parent, "Huh, parent not an nsIDOMWindowInternal?");
-
-    parentInternal = tmp;
-  }
-
-  return parentInternal;
+    return parent;
+  }
+
+  return NULL;
 }
 
 // static
 void
 nsGlobalWindow::CloseBlockScriptTerminationFunc(nsISupports *aRef)
 {
   nsGlobalWindow* pwin = static_cast<nsGlobalWindow*>
                                     (static_cast<nsPIDOMWindow*>(aRef));
@@ -8727,17 +8712,17 @@ nsGlobalWindow::OpenInternal(const nsASt
         
       rv = pwwatch->OpenWindowJS(this, url.get(), name_ptr, options_ptr,
                                  aDialog, argv,
                                  getter_AddRefs(domReturn));
     } else {
       // Push a null JSContext here so that the window watcher won't screw us
       // up.  We do NOT want this case looking at the JS context on the stack
       // when searching.  Compare comments on
-      // nsIDOMWindowInternal::OpenWindow and nsIWindowWatcher::OpenWindow.
+      // nsIDOMWindow::OpenWindow and nsIWindowWatcher::OpenWindow.
       nsCOMPtr<nsIJSContextStack> stack;
 
       if (!aContentModal) {
         stack = do_GetService(sJSStackContractID);
       }
 
       if (stack) {
         rv = stack->Push(nsnull);
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -62,17 +62,16 @@
 #include "nsIDocShellTreeOwner.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDOMClientInformation.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMNavigator.h"
 #include "nsIDOMNavigatorGeolocation.h"
 #include "nsIDOMNavigatorDesktopNotification.h"
 #include "nsIDOMLocation.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIDOMJSWindow.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptContext.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIScriptTimeoutHandler.h"
@@ -92,17 +91,16 @@
 #include "nsIXPCScriptable.h"
 #include "nsPoint.h"
 #include "nsSize.h"
 #include "nsRect.h"
 #include "mozFlushType.h"
 #include "prclist.h"
 #include "nsIDOMStorageObsolete.h"
 #include "nsIDOMStorageList.h"
-#include "nsIDOMStorageWindow.h"
 #include "nsIDOMStorageEvent.h"
 #include "nsIDOMStorageIndexedDB.h"
 #include "nsIDOMOfflineResourceList.h"
 #include "nsIArray.h"
 #include "nsIContent.h"
 #include "nsIIDBFactory.h"
 #include "nsFrameMessageManager.h"
 #include "mozilla/TimeStamp.h"
@@ -271,17 +269,16 @@ JSObject *NS_NewOuterWindowProxy(JSConte
 // belonging to the same outer window, but that's an unimportant
 // side effect of inheriting PRCList).
 
 class nsGlobalWindow : public nsPIDOMWindow,
                        public nsIScriptGlobalObject,
                        public nsIDOMJSWindow,
                        public nsIScriptObjectPrincipal,
                        public nsIDOMEventTarget,
-                       public nsIDOMStorageWindow,
                        public nsIDOMStorageIndexedDB,
                        public nsSupportsWeakReference,
                        public nsIInterfaceRequestor,
                        public nsWrapperCache,
                        public PRCListStr,
                        public nsIDOMWindowPerformance
 {
 public:
@@ -320,19 +317,16 @@ public:
   virtual void SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts);
 
   // nsIScriptObjectPrincipal
   virtual nsIPrincipal* GetPrincipal();
 
   // nsIDOMWindow
   NS_DECL_NSIDOMWINDOW
 
-  // nsIDOMWindowInternal
-  NS_DECL_NSIDOMWINDOWINTERNAL
-
   // nsIDOMWindowPerformance
   NS_DECL_NSIDOMWINDOWPERFORMANCE
 
   // nsIDOMJSWindow
   NS_DECL_NSIDOMJSWINDOW
 
   // nsIDOMEventTarget
   NS_DECL_NSIDOMEVENTTARGET
@@ -365,33 +359,33 @@ public:
 
   virtual NS_HIDDEN_(PRBool) WouldReuseInnerWindow(nsIDocument *aNewDocument);
 
   virtual NS_HIDDEN_(void) SetDocShell(nsIDocShell* aDocShell);
   virtual NS_HIDDEN_(nsresult) SetNewDocument(nsIDocument *aDocument,
                                               nsISupports *aState,
                                               PRBool aForceReuseInnerWindow);
   void DispatchDOMWindowCreated();
-  virtual NS_HIDDEN_(void) SetOpenerWindow(nsIDOMWindowInternal *aOpener,
+  virtual NS_HIDDEN_(void) SetOpenerWindow(nsIDOMWindow* aOpener,
                                            PRBool aOriginalOpener);
   virtual NS_HIDDEN_(void) EnsureSizeUpToDate();
 
-  virtual NS_HIDDEN_(nsIDOMWindow *) EnterModalState();
-  virtual NS_HIDDEN_(void) LeaveModalState(nsIDOMWindow *aWindow);
+  virtual NS_HIDDEN_(nsIDOMWindow*) EnterModalState();
+  virtual NS_HIDDEN_(void) LeaveModalState(nsIDOMWindow* aWindow);
 
   virtual NS_HIDDEN_(PRBool) CanClose();
   virtual NS_HIDDEN_(nsresult) ForceClose();
 
   virtual NS_HIDDEN_(void) SetHasOrientationEventListener();
   virtual NS_HIDDEN_(void) MaybeUpdateTouchState();
   virtual NS_HIDDEN_(void) UpdateTouchState();
   virtual NS_HIDDEN_(PRBool) DispatchCustomEvent(const char *aEventName);
 
-  // nsIDOMStorageWindow
-  NS_DECL_NSIDOMSTORAGEWINDOW
+  // nsIDOMStorageIndexedDB
+  NS_DECL_NSIDOMSTORAGEINDEXEDDB
 
   // nsIInterfaceRequestor
   NS_DECL_NSIINTERFACEREQUESTOR
 
   // Object Management
   nsGlobalWindow(nsGlobalWindow *aOuterWindow);
 
   static nsGlobalWindow *FromSupports(nsISupports *supports)
@@ -577,17 +571,17 @@ protected:
   void FreeInnerObjects(PRBool aClearScope);
   nsGlobalWindow *CallerInnerWindow();
 
   nsresult InnerSetNewDocument(nsIDocument* aDocument);
 
   nsresult DefineArgumentsProperty(nsIArray *aArguments);
 
   // Get the parent, returns null if this is a toplevel window
-  nsIDOMWindowInternal *GetParentInternal();
+  nsIDOMWindow* GetParentInternal();
 
   // popup tracking
   PRBool IsPopupSpamWindow()
   {
     if (IsInnerWindow() && !mOuterWindow) {
       return PR_FALSE;
     }
 
--- a/dom/base/nsHistory.cpp
+++ b/dom/base/nsHistory.cpp
@@ -32,20 +32,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 "nsHistory.h"
+
 #include "nsCOMPtr.h"
 #include "nscore.h"
-#include "nsHistory.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsPIDOMWindow.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -35,21 +35,21 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 
 #ifndef nsPIDOMWindow_h__
 #define nsPIDOMWindow_h__
 
-#include "nsISupports.h"
+#include "nsIDOMWindow.h"
+
 #include "nsIDOMLocation.h"
 #include "nsIDOMXULCommandDispatcher.h"
 #include "nsIDOMElement.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMDocument.h"
 #include "nsCOMPtr.h"
 #include "nsEvent.h"
 #include "nsIURI.h"
 
 #define DOM_WINDOW_DESTROYED_TOPIC "dom-window-destroyed"
 #define DOM_WINDOW_FROZEN_TOPIC "dom-window-frozen"
@@ -75,20 +75,20 @@ class nsIDocument;
 class nsIScriptTimeoutHandler;
 struct nsTimeout;
 class nsScriptObjectHolder;
 class nsXBLPrototypeHandler;
 class nsIArray;
 class nsPIWindowRoot;
 
 #define NS_PIDOMWINDOW_IID \
-{ 0xa595249b, 0x1e74, 0x467e, \
- { 0x92, 0x56, 0x58, 0xff, 0x07, 0x1b, 0xc2, 0x96 } }
+{ 0x1bfacc26, 0xad77, 0x42bb, \
+  { 0xb9, 0xbb, 0xa0, 0x19, 0xc8, 0x27, 0x5c, 0x0e } }
 
-class nsPIDOMWindow : public nsIDOMWindowInternal
+class nsPIDOMWindow : public nsIDOMWindow
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_PIDOMWINDOW_IID)
 
   virtual nsPIDOMWindow* GetPrivateRoot() = 0;
 
   virtual void ActivateOrDeactivate(PRBool aActivate) = 0;
 
@@ -391,17 +391,17 @@ public:
 
   /**
    * Set the opener window.  aOriginalOpener is true if and only if this is the
    * original opener for the window.  That is, it can only be true at most once
    * during the life cycle of a window, and then only the first time
    * SetOpenerWindow is called.  It might never be true, of course, if the
    * window does not have an opener when it's created.
    */
-  virtual void SetOpenerWindow(nsIDOMWindowInternal *aOpener,
+  virtual void SetOpenerWindow(nsIDOMWindow* aOpener,
                                PRBool aOriginalOpener) = 0;
 
   virtual void EnsureSizeUpToDate() = 0;
 
   /**
    * Callback for notifying a window about a modal dialog being
    * opened/closed with the window as a parent.
    */
--- a/dom/base/nsWindowRoot.cpp
+++ b/dom/base/nsWindowRoot.cpp
@@ -35,28 +35,25 @@
  * 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 "nsCOMPtr.h"
 #include "nsWindowRoot.h"
 #include "nsPIDOMWindow.h"
-#include "nsIDOMWindow.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocument.h"
 #include "nsEventListenerManager.h"
 #include "nsPresContext.h"
 #include "nsLayoutCID.h"
 #include "nsContentCID.h"
 #include "nsIPrivateDOMEvent.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsString.h"
 #include "nsEventDispatcher.h"
-#include "nsIProgrammingLanguage.h"
 #include "nsGUIEvent.h"
 #include "nsGlobalWindow.h"
 #include "nsFocusManager.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsIControllers.h"
 
 #include "nsCycleCollectionParticipant.h"
@@ -239,17 +236,17 @@ nsWindowRoot::GetControllers(nsIControll
       do_QueryInterface(focusedContent);
     if (htmlInputElement)
       return htmlInputElement->GetControllers(aResult);
 
     if (focusedContent->IsEditable() && focusedWindow)
       return focusedWindow->GetControllers(aResult);
   }
   else {
-    nsCOMPtr<nsIDOMWindowInternal> domWindow = do_QueryInterface(focusedWindow);
+    nsCOMPtr<nsIDOMWindow> domWindow = do_QueryInterface(focusedWindow);
     if (domWindow)
       return domWindow->GetControllers(aResult);
   }
 
   return NS_OK;
 }
 
 nsresult
@@ -269,34 +266,34 @@ nsWindowRoot::GetControllerForCommand(co
       controller.swap(*_retval);
       return NS_OK;
     }
   }
 
   nsCOMPtr<nsPIDOMWindow> focusedWindow;
   nsFocusManager::GetFocusedDescendant(mWindow, PR_TRUE, getter_AddRefs(focusedWindow));
   while (focusedWindow) {
-    nsCOMPtr<nsIDOMWindowInternal> domWindow(do_QueryInterface(focusedWindow));
+    nsCOMPtr<nsIDOMWindow> domWindow(do_QueryInterface(focusedWindow));
 
     nsCOMPtr<nsIControllers> controllers2;
     domWindow->GetControllers(getter_AddRefs(controllers2));
     if (controllers2) {
       controllers2->GetControllerForCommand(aCommand,
                                             getter_AddRefs(controller));
       if (controller) {
         controller.swap(*_retval);
         return NS_OK;
       }
     }
 
     // XXXndeakin P3 is this casting safe?
     nsCOMPtr<nsPIDOMWindow> piWindow = do_QueryInterface(focusedWindow); 
     nsGlobalWindow *win =
       static_cast<nsGlobalWindow *>
-                 (static_cast<nsIDOMWindowInternal *>(piWindow));
+                 (static_cast<nsIDOMWindow*>(piWindow));
     focusedWindow = win->GetPrivateParent();
   }
   
   return NS_OK;
 }
 
 nsIDOMNode*
 nsWindowRoot::GetPopupNode()
--- a/dom/interfaces/base/Makefile.in
+++ b/dom/interfaces/base/Makefile.in
@@ -69,17 +69,16 @@ XPIDLSRCS =					\
 	nsIDOMMediaQueryList.idl		\
 	nsIDOMMimeType.idl			\
 	nsIDOMMimeTypeArray.idl			\
 	nsIDOMNavigator.idl			\
 	nsIDOMPkcs11.idl			\
 	nsIDOMPlugin.idl			\
 	nsIDOMPluginArray.idl			\
 	nsIDOMScreen.idl			\
-	nsIDOMWindowInternal.idl		\
 	nsIDOMJSWindow.idl			\
 	nsIDOMModalContentWindow.idl		\
 	nsIDOMChromeWindow.idl			\
         nsIDOMClientRect.idl			\
         nsIDOMClientRectList.idl		\
 	nsIFocusManager.idl			\
 	nsIQueryContentEventResult.idl		\
 	nsITabChild.idl				\
--- a/dom/interfaces/base/domstubs.idl
+++ b/dom/interfaces/base/domstubs.idl
@@ -71,17 +71,16 @@ interface RangeException;
 // Style Sheets
 interface nsIDOMStyleSheetList;
 interface nsIDOMLinkStyle;
 interface nsIDOMStyleSheet;
 interface nsIDOMMediaList;
 
 // Base
 interface nsIDOMWindow;
-interface nsIDOMWindowInternal;
 interface nsIDOMWindowCollection;
 interface nsIDOMPlugin;
 interface nsIDOMPluginArray;
 interface nsIDOMMimeType;
 interface nsIDOMMimeTypeArray;
 interface nsIDOMBarProp;
 interface nsIDOMNavigator;
 interface nsIDOMScreen;
--- a/dom/interfaces/base/nsIDOMJSWindow.idl
+++ b/dom/interfaces/base/nsIDOMJSWindow.idl
@@ -72,32 +72,32 @@ interface nsIDOMJSWindow : nsISupports
    */
   void                      captureEvents(in long eventFlags);
   void                      releaseEvents(in long eventFlags);
   void                      routeEvent(in nsIDOMEvent evt);
   void                      enableExternalCapture();
   void                      disableExternalCapture();
 
   /**
-   * This is the scriptable version of nsIDOMWindowInternal::open()
+   * This is the scriptable version of nsIDOMWindow::open()
    * that takes 3 optional arguments. Its binary name is OpenJS to
-   * avoid colliding with nsIDOMWindowInternal::open(), which has the
+   * avoid colliding with nsIDOMWindow::open(), which has the
    * same signature. The reason we can't have that collision is that
    * the implementation needs to know whether it was called from JS or
    * not.
    *
    * IOW, DO NOT CALL THIS FROM C++
    */
   [binaryname(OpenJS)] nsIDOMWindow open([optional] in DOMString url,
                                          [optional] in DOMString name,
                                          [optional] in DOMString options);
 
   /**
    * This is the scriptable version of
-   * nsIDOMWindowInternal::openDialog() that takes 3 optional
+   * nsIDOMWindow::openDialog() that takes 3 optional
    * arguments, plus any additional arguments are passed on as
    * arguments on the dialog's window object (window.arguments).
    */
   nsIDOMWindow              openDialog([optional] in DOMString url,
                                        [optional] in DOMString name,
                                        [optional] in DOMString options);
 
   /**
--- a/dom/interfaces/base/nsIDOMWindow.idl
+++ b/dom/interfaces/base/nsIDOMWindow.idl
@@ -17,16 +17,18 @@
  * The Initial Developer of the Original Code is
  * Netscape Communications Corporation.
  * Portions created by the Initial Developer are Copyright (C) 2000
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Vidur Apparao <vidur@netscape.com> (original author)
  *   Johnny Stenback <jst@netscape.com>
+ *   Neil Deakin <enndeakin@sympatico.ca>
+ *   Ms2ger <ms2ger@gmail.com>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either of the GNU General Public License Version 2 or later (the "GPL"),
  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
@@ -34,107 +36,259 @@
  * 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 "domstubs.idl"
 
+%{ C++
+#include "jspubtd.h"
+%}
+
+interface nsIAnimationFrameListener;
+interface nsIControllers;
+interface nsIDOMBlob;
+interface nsIDOMLocation;
+interface nsIDOMMediaQueryList;
 interface nsIDOMOfflineResourceList;
+interface nsIDOMPerformance;
+interface nsIDOMStorage;
+interface nsIDOMStorageList;
+interface nsIPrompt;
 interface nsISelection;
+interface nsIVariant;
+
+[scriptable, uuid(8fc58f56-f769-4368-a098-edd08550cf1a)]
+interface nsIDOMMozURLProperty : nsISupports
+{
+  DOMString createObjectURL(in nsIDOMBlob blob);
+  void revokeObjectURL(in DOMString URL);
+};
 
 /**
  * The nsIDOMWindow interface is the primary interface for a DOM
  * window object. It represents a single window object that may
  * contain child windows if the document in the window contains a
  * HTML frameset document or if the document contains iframe elements.
  *
  * @see <http://www.whatwg.org/html/#window>
  */
 
-[scriptable, uuid(90fec5b7-c58b-463f-a147-f91b6b104a96)]
+[scriptable, uuid(972cb379-6bdc-4544-8b46-8d721e12e906)]
 interface nsIDOMWindow : nsISupports
 {
+  // the current browsing context
+  readonly attribute nsIDOMWindow                       window;
+
+  /* [replaceable] self */
+  readonly attribute nsIDOMWindow                       self;
+
   /**
    * Accessor for the document in this window.
    */
   readonly attribute nsIDOMDocument                     document;
 
   /**
    * Set/Get the name of this window.
    *
    * This attribute is "replaceable" in JavaScript
    */
            attribute DOMString                          name;
 
+  /* The setter that takes a string argument needs to be special cased! */
+  readonly attribute nsIDOMLocation                     location;
+
+  readonly attribute nsIDOMHistory                      history;
+
+
+  /* [replaceable] locationbar */
+  readonly attribute nsIDOMBarProp                      locationbar;
+
+  /* [replaceable] menubar */
+  readonly attribute nsIDOMBarProp                      menubar;
+
+  /* [replaceable] personalbar */
+  readonly attribute nsIDOMBarProp                      personalbar;
+
   /**
    * Accessor for the object that controls whether or not scrollbars
    * are shown in this window.
    *
    * This attribute is "replaceable" in JavaScript
    */
   readonly attribute nsIDOMBarProp                      scrollbars;
 
+  /* [replaceable] statusbar */
+  readonly attribute nsIDOMBarProp                      statusbar;
+
+  /* [replaceable] toolbar */
+  readonly attribute nsIDOMBarProp                      toolbar;
+
+  /* [replaceable] */
+           attribute DOMString                          status;
+
+  void                      close();
+  void                      stop();
+  void                      focus();
+  void                      blur();
+
+
+  // other browsing contexts
+  /* [replaceable] length */
+  readonly attribute unsigned long                      length;
+
   /**
    * Accessor for the root of this hierarchy of windows. This root may
    * be the window itself if there is no parent, or if the parent is
    * of different type (i.e. this does not cross chrome-content
    * boundaries).
    *
    * This property is "replaceable" in JavaScript */
   readonly attribute nsIDOMWindow                       top;
 
+           attribute nsIDOMWindow                       opener;
+
   /**
    * Accessor for this window's parent window, or the window itself if
    * there is no parent, or if the parent is of different type
    * (i.e. this does not cross chrome-content boundaries).
    */
   readonly attribute nsIDOMWindow                       parent;
 
+  readonly attribute nsIDOMElement                      frameElement;
+
+
+  // the user agent
+  readonly attribute nsIDOMNavigator                    navigator;
+
   /**
    * Get the application cache object for this window.
    */
   readonly attribute nsIDOMOfflineResourceList          applicationCache;
 
 
+  // user prompts
+  void                      alert(in DOMString text);
+  boolean                   confirm(in DOMString text);
+
+  // prompt() should return a null string if cancel is pressed
+  DOMString                 prompt([optional] in DOMString aMessage,
+                                   [optional] in DOMString aInitial);
+
+  void                      print();
+
+  nsIVariant                showModalDialog(in DOMString aURI,
+                                            [optional] in nsIVariant aArgs,
+                                            [optional] in DOMString aOptions);
+
+
+  // cross-document messaging
+  /**
+   * Implements a safe message-passing system which can cross same-origin
+   * boundaries.
+   *
+   * This method, when called, causes a MessageEvent to be asynchronously
+   * dispatched at the primary document for the window upon which this method is
+   * called.  (Note that the postMessage property on windows is allAccess and
+   * thus is readable cross-origin.)  The dispatched event will have message as
+   * its data, the calling context's window as its source, and an origin
+   * determined by the calling context's main document URI.  The targetOrigin
+   * argument specifies a URI and is used to restrict the message to be sent
+   * only when the target window has the same origin as targetOrigin (since,
+   * when the sender and the target have different origins, neither can read the
+   * location of the other).
+   * 
+   * @see <http://www.whatwg.org/html/#dom-window-postmessage>
+   */
+  [implicit_jscontext, binaryname(PostMessageMoz)]
+    void postMessage(in jsval message, in DOMString targetOrigin);
+
+
+  // WindowBase64
+  // Ascii base64 data to binary data and vice versa...
+  DOMString                 atob(in DOMString aAsciiString);
+  DOMString                 btoa(in DOMString aBase64Data);
+
+
+  // WindowSessionStorage
+  /**
+   * Session storage for the current browsing context.
+   */
+  readonly attribute nsIDOMStorage sessionStorage;
+
+
+  // WindowLocalStorage
+  /**
+   * Local storage for the current browsing context.
+   */
+  readonly attribute nsIDOMStorage localStorage;
+
+
+  // DOM Range
+  /**
+   * Method for accessing this window's selection object.
+   */
+  nsISelection              getSelection();
+
+
   // CSSOM-View
+  // http://dev.w3.org/csswg/cssom-view/#extensions-to-the-window-interface
+  nsIDOMMediaQueryList      matchMedia(in DOMString media_query_list);
+
+  readonly attribute nsIDOMScreen                       screen;
+
+  // viewport
+           attribute long                               innerWidth;
+           attribute long                               innerHeight;
+
+
+  // viewport scrolling
   /**
    * Accessor for the current x scroll position in this window in
    * pixels.
    *
    * This attribute is "replaceable" in JavaScript
    */
   readonly attribute long                               scrollX;
 
+  /* The offset in pixels by which the window is scrolled */
+  readonly attribute long                               pageXOffset;
+
   /**
    * Accessor for the current y scroll position in this window in
    * pixels.
    *
    * This attribute is "replaceable" in JavaScript
    */
   readonly attribute long                               scrollY;
 
+  /* The offset in pixels by which the window is scrolled */
+  readonly attribute long                               pageYOffset;
+
+  void                      scroll(in long xScroll, in long yScroll);
+
   /**
    * Method for scrolling this window to an absolute pixel offset.
    */
   void                      scrollTo(in long xScroll, in long yScroll);
 
   /**
    * Method for scrolling this window to a pixel offset relative to
    * the current scroll position.
    */
   void                      scrollBy(in long xScrollDif, in long yScrollDif);
 
 
-  // DOM Range
-  /**
-   * Method for accessing this window's selection object.
-   */
-  nsISelection              getSelection();
+  // client
+           attribute long                        screenX;
+           attribute long                        screenY;
+           attribute long                        outerWidth;
+           attribute long                        outerHeight;
 
 
   // CSSOM
   /**
    * @see <http://dev.w3.org/csswg/cssom/#dom-window-getcomputedstyle>
    */
   nsIDOMCSSStyleDeclaration getComputedStyle(in nsIDOMElement elt, 
                                              [optional] in DOMString pseudoElt);
@@ -172,9 +326,125 @@ interface nsIDOMWindow : nsISupports
    * Method for scrolling this window by a number of pages.
    */
   void                      scrollByPages(in long numPages);
 
   /**
    * Method for sizing this window to the content in the window.
    */
   void                      sizeToContent();
+
+  /* [replaceable] content */
+  readonly attribute nsIDOMWindow                       content;
+
+  /* [replaceable] prompter */
+  [noscript] readonly attribute nsIPrompt               prompter;
+
+  readonly attribute boolean                            closed;
+  // http://wiki.whatwg.org/wiki/Crypto
+  readonly attribute nsIDOMCrypto                       crypto;
+  readonly attribute nsIDOMPkcs11                       pkcs11;
+
+  // XXX Shouldn't this be in nsIDOMChromeWindow?
+  /* [replaceable] controllers */
+  readonly attribute nsIControllers                     controllers;
+
+           attribute DOMString                          defaultStatus;
+
+  readonly attribute float                              mozInnerScreenX;
+  readonly attribute float                              mozInnerScreenY;
+
+  /* The maximum offset that the window can be scrolled to
+     (i.e., the document width/height minus the scrollport width/height) */
+  readonly attribute long                               scrollMaxX;
+  readonly attribute long                               scrollMaxY;
+
+           attribute boolean                            fullScreen;
+
+  void                      back();
+  void                      forward();
+  void                      home();
+
+  void                      moveTo(in long xPos, in long yPos);
+  void                      moveBy(in long xDif, in long yDif);
+  void                      resizeTo(in long width, in long height);
+  void                      resizeBy(in long widthDif, in long heightDif);
+
+  /**
+   * Open a new window with this one as the parent.  This method will
+   * NOT examine the JS stack for purposes of determining a caller.
+   * This window will be used for security checks during the search by
+   * name and the default character set on the newly opened window
+   * will just be the default character set of this window.
+   */
+  [noscript] nsIDOMWindow   open(in DOMString url, in DOMString name,
+                                 in DOMString options);
+
+  /**
+   * This method works like open except that aExtraArgument gets
+   * converted into the array window.arguments in JS, if
+   * aExtraArgument is a nsISupportsArray then the individual items in
+   * the array are inserted into window.arguments, and primitive
+   * nsISupports (nsISupportsPrimitives) types are converted to native
+   * JS types when possible.
+   */
+  [noscript] nsIDOMWindow   openDialog(in DOMString url, in DOMString name,
+                                       in DOMString options,
+                                       in nsISupports aExtraArgument);
+
+  // XXX Should this be in nsIDOMChromeWindow?
+  void                      updateCommands(in DOMString action);
+
+  /* Find in page.
+   * @param str: the search pattern
+   * @param caseSensitive: is the search caseSensitive
+   * @param backwards: should we search backwards
+   * @param wrapAround: should we wrap the search
+   * @param wholeWord: should we search only for whole words
+   * @param searchInFrames: should we search through all frames
+   * @param showDialog: should we show the Find dialog
+   */
+  boolean                   find([optional] in DOMString str,
+                                 [optional] in boolean caseSensitive,
+                                 [optional] in boolean backwards,
+                                 [optional] in boolean wrapAround,
+                                 [optional] in boolean wholeWord,
+                                 [optional] in boolean searchInFrames,
+                                 [optional] in boolean showDialog);
+
+  /**
+   * Returns the number of times this document for this window has
+   * been painted to the screen.
+   */
+  readonly attribute unsigned long long mozPaintCount;
+
+  /**
+   * Request a refresh of this browser window.
+   *
+   * @see <http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/RequestAnimationFrame/Overview.html>
+   */
+  void
+    mozRequestAnimationFrame([optional] in nsIAnimationFrameListener aListener);
+
+  /**
+   * The current animation start time in milliseconds since the epoch.
+   */
+  readonly attribute long long mozAnimationStartTime;
+
+  /**
+   * @see <http://dev.w3.org/2006/webapi/FileAPI/#creating-revoking>
+   */
+  readonly attribute nsIDOMMozURLProperty URL;
+
+  /**
+   * Global storage, accessible by domain.
+   */
+  readonly attribute nsIDOMStorageList globalStorage;
 };
+
+[scriptable, uuid(2146c906-57f7-486c-a1b4-8cdb57ef577f)]
+interface nsIDOMWindowPerformance : nsISupports
+{
+  /**
+   * A namespace to hold performance related data and statistics.
+   */
+  readonly attribute nsIDOMPerformance performance;
+};
deleted file mode 100644
--- a/dom/interfaces/base/nsIDOMWindowInternal.idl
+++ /dev/null
@@ -1,266 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Vidur Apparao <vidur@netscape.com> (original author)
- *   Johnny Stenback <jst@netscape.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "nsIDOMWindow.idl"
-
-%{ C++
-#include "jspubtd.h"
-%}
-
-interface nsIPrompt;
-interface nsIControllers;
-interface nsIDOMLocation;
-interface nsIDOMPerformance;
-interface nsIVariant;
-interface nsIAnimationFrameListener;
-interface nsIDOMMediaQueryList;
-interface nsIDOMBlob;
-
-[scriptable, uuid(8fc58f56-f769-4368-a098-edd08550cf1a)]
-interface nsIDOMMozURLProperty : nsISupports
-{
-  DOMString createObjectURL(in nsIDOMBlob blob);
-  void revokeObjectURL(in DOMString URL);
-};
-
-[scriptable, uuid(7fec9403-7562-4ae0-8d9b-0735f0a55d7d)]
-interface nsIDOMWindowInternal : nsIDOMWindow
-{
-  readonly attribute nsIDOMWindowInternal        window;
-
-  /* [replaceable] self */
-  readonly attribute nsIDOMWindowInternal        self;
-
-  readonly attribute nsIDOMNavigator             navigator;
-  readonly attribute nsIDOMScreen                screen;
-  readonly attribute nsIDOMHistory               history;
-
-  /* [replaceable] content */
-  readonly attribute nsIDOMWindow                content;
-
-  /* [replaceable] prompter */
-  [noscript] readonly attribute nsIPrompt        prompter;
-
-  /* [replaceable] menubar */
-  readonly attribute nsIDOMBarProp               menubar;
-
-  /* [replaceable] toolbar */
-  readonly attribute nsIDOMBarProp               toolbar;
-
-  /* [replaceable] locationbar */
-  readonly attribute nsIDOMBarProp               locationbar;
-
-  /* [replaceable] personalbar */
-  readonly attribute nsIDOMBarProp               personalbar;
-
-  /* [replaceable] statusbar */
-  readonly attribute nsIDOMBarProp               statusbar;
-
-  readonly attribute boolean                     closed;
-  readonly attribute nsIDOMCrypto                crypto;
-  readonly attribute nsIDOMPkcs11                pkcs11;
-
-  // XXX Shouldn't this be in nsIDOMChromeWindow?
-  /* [replaceable] controllers */
-  readonly attribute nsIControllers              controllers;
-
-           attribute nsIDOMWindowInternal        opener;
-
-  /* [replaceable] */
-           attribute DOMString                   status;
-           attribute DOMString                   defaultStatus;
-
-  // XXX: The setter that takes a string argument needs to be special
-  // cased!
-  readonly attribute nsIDOMLocation              location;
-  
-  /* [replaceable] */
-           attribute long                        innerWidth;
-           attribute long                        innerHeight;
-           attribute long                        outerWidth;
-           attribute long                        outerHeight;
-           attribute long                        screenX;
-           attribute long                        screenY;
-  readonly attribute float                       mozInnerScreenX;
-  readonly attribute float                       mozInnerScreenY;
-
-  /* The offset in pixels by which the window is scrolled */
-  readonly attribute long                        pageXOffset;
-  readonly attribute long                        pageYOffset;
-
-  /* The maximum offset that the window can be scrolled to
-     (i.e., the document width/height minus the scrollport width/height) */
-  readonly attribute long                        scrollMaxX;
-  readonly attribute long                        scrollMaxY;
-
-  /* [replaceable] length */
-  readonly attribute unsigned long               length;
-
-           attribute boolean                     fullScreen;
-
-  void                      alert(in DOMString text);
-  boolean                   confirm(in DOMString text);
-
-  // prompt() should return a null string if cancel is pressed
-  DOMString                 prompt([optional] in DOMString aMessage,
-                                   [optional] in DOMString aInitial);
-
-  void                      focus();
-  void                      blur();
-
-  void                      back();
-  void                      forward();
-  void                      home();
-  void                      stop();
-
-  void                      print();
-
-  void                      moveTo(in long xPos, in long yPos);
-  void                      moveBy(in long xDif, in long yDif);
-  void                      resizeTo(in long width, in long height);
-  void                      resizeBy(in long widthDif, in long heightDif);
-  void                      scroll(in long xScroll, in long yScroll);
-
-  /**
-   * Open a new window with this one as the parent.  This method will
-   * NOT examine the JS stack for purposes of determining a caller.
-   * This window will be used for security checks during the search by
-   * name and the default character set on the newly opened window
-   * will just be the default character set of this window.
-   */
-  [noscript] nsIDOMWindow   open(in DOMString url, in DOMString name,
-                                 in DOMString options);
-
-  /**
-   * This method works like open except that aExtraArgument gets
-   * converted into the array window.arguments in JS, if
-   * aExtraArgument is a nsISupportsArray then the individual items in
-   * the array are inserted into window.arguments, and primitive
-   * nsISupports (nsISupportsPrimitives) types are converted to native
-   * JS types when possible.
-   */
-  [noscript] nsIDOMWindow   openDialog(in DOMString url, in DOMString name,
-                                       in DOMString options,
-                                       in nsISupports aExtraArgument);
-  void                      close();
-
-  // XXX Should this be in nsIDOMChromeWindow?
-  void                      updateCommands(in DOMString action);
-
-  /* Find in page.
-   * @param str: the search pattern
-   * @param caseSensitive: is the search caseSensitive
-   * @param backwards: should we search backwards
-   * @param wrapAround: should we wrap the search
-   * @param wholeWord: should we search only for whole words
-   * @param searchInFrames: should we search through all frames
-   * @param showDialog: should we show the Find dialog
-   */
-  boolean                   find([optional] in DOMString str,
-                                 [optional] in boolean caseSensitive,
-                                 [optional] in boolean backwards,
-                                 [optional] in boolean wrapAround,
-                                 [optional] in boolean wholeWord,
-                                 [optional] in boolean searchInFrames,
-                                 [optional] in boolean showDialog);
-
-  // Ascii base64 data to binary data and vice versa...
-  DOMString                 atob(in DOMString aAsciiString);
-  DOMString                 btoa(in DOMString aBase64Data);
-
-  readonly attribute nsIDOMElement               frameElement;
-
-  nsIVariant                showModalDialog(in DOMString aURI,
-                                            [optional] in nsIVariant aArgs,
-                                            [optional] in DOMString aOptions);
-
-  /**
-   * Implements a safe message-passing system which can cross same-origin
-   * boundaries.
-   *
-   * This method, when called, causes a MessageEvent to be asynchronously
-   * dispatched at the primary document for the window upon which this method is
-   * called.  (Note that the postMessage property on windows is allAccess and
-   * thus is readable cross-origin.)  The dispatched event will have message as
-   * its data, the calling context's window as its source, and an origin
-   * determined by the calling context's main document URI.  The targetOrigin
-   * argument specifies a URI and is used to restrict the message to be sent
-   * only when the target window has the same origin as targetOrigin (since,
-   * when the sender and the target have different origins, neither can read the
-   * location of the other).
-   * 
-   * See the WHATWG HTML5 specification, section 6.4, for more details.
-   */
-  [implicit_jscontext, binaryname(PostMessageMoz)]
-    void postMessage(in jsval message, in DOMString targetOrigin);
-
-  /**
-   * Returns the number of times this document for this window has
-   * been painted to the screen.
-   */
-  readonly attribute unsigned long long mozPaintCount;
-
-  /**
-   * Request a refresh of this browser window.
-   */
-  void
-    mozRequestAnimationFrame([optional] in nsIAnimationFrameListener aListener);
-
-  /**
-   * The current animation start time in milliseconds since the epoch.
-   */
-  readonly attribute long long mozAnimationStartTime;
-
-  /**
-   * http://dev.w3.org/csswg/cssom-view/#extensions-to-the-window-interface
-   */
-  nsIDOMMediaQueryList matchMedia(in DOMString media_query_list);
-
-  readonly attribute nsIDOMMozURLProperty URL;
-};
-
-[scriptable, uuid(2146c906-57f7-486c-a1b4-8cdb57ef577f)]
-interface nsIDOMWindowPerformance : nsISupports
-{
-  /**
-   * A namespace to hold performance related data and statistics.
-   */
-  readonly attribute nsIDOMPerformance performance;
-};
-
--- a/dom/interfaces/storage/Makefile.in
+++ b/dom/interfaces/storage/Makefile.in
@@ -58,12 +58,11 @@ XPIDLSRCS =                             
 SDK_XPIDLSRCS =                      \
         nsIDOMStorage.idl        \
         nsIDOMStorageObsolete.idl\
         nsIDOMStorageEvent.idl   \
         nsIDOMStorageEventObsolete.idl \
         nsIDOMStorageItem.idl    \
         nsIDOMStorageIndexedDB.idl \
         nsIDOMStorageList.idl    \
-        nsIDOMStorageWindow.idl  \
        $(NULL)
 
 include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/dom/interfaces/storage/nsIDOMStorageWindow.idl
+++ /dev/null
@@ -1,76 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- *   Neil Deakin <enndeakin@sympatico.ca>
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "domstubs.idl"
-
-/**
- * Interface for a client side storage. See
- * http://www.whatwg.org/specs/web-apps/current-work/#scs-client-side and
- * http://www.w3.org/TR/IndexedDB/ for more information.
- *
- * Allows access to contextual storage areas.
- */
-
-interface nsIDOMStorageObsolete;
-interface nsIDOMStorage;
-interface nsIDOMStorageList;
-interface nsIIDBFactory;
-
-[scriptable, uuid(b6f6efd8-1bdc-43af-b8ef-6685d6260931)]
-interface nsIDOMStorageWindow : nsISupports
-{
-  /**
-   * Session storage for the current browsing context.
-   */
-  readonly attribute nsIDOMStorage sessionStorage;
-
-  /**
-   * Global storage, accessible by domain.
-   */
-  readonly attribute nsIDOMStorageList globalStorage;
-
-  /**
-   * Local storage for the current browsing context.
-   */
-  readonly attribute nsIDOMStorage localStorage;
-
-  /**
-   * Indexed Databases for the current browsing context.
-   * NOTE: mozIndexedDB should be removed post-2.0. Bug 623316.
-   */
-  [noscript] readonly attribute nsIIDBFactory mozIndexedDB;
-};
--- a/editor/composer/src/nsEditingSession.cpp
+++ b/editor/composer/src/nsEditingSession.cpp
@@ -37,17 +37,16 @@
  * 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 "nsPIDOMWindow.h"
 #include "nsIDOMWindowUtils.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDocument.h"
 #include "nsIHTMLDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIURI.h"
 #include "nsISelectionPrivate.h"
 #include "nsITransactionManager.h"
 
@@ -1209,31 +1208,25 @@ nsEditingSession::SetupEditorCommandCont
                                   nsIDOMWindow *aWindow,
                                   nsISupports *aContext,
                                   PRUint32 *aControllerId)
 {
   NS_ENSURE_ARG_POINTER(aControllerClassName);
   NS_ENSURE_ARG_POINTER(aWindow);
   NS_ENSURE_ARG_POINTER(aContext);
   NS_ENSURE_ARG_POINTER(aControllerId);
-
-  nsresult rv;
-  nsCOMPtr<nsIDOMWindowInternal> domWindowInt =
-                                    do_QueryInterface(aWindow, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
   
   nsCOMPtr<nsIControllers> controllers;      
-  rv = domWindowInt->GetControllers(getter_AddRefs(controllers));
+  nsresult rv = aWindow->GetControllers(getter_AddRefs(controllers));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // We only have to create each singleton controller once
   // We know this has happened once we have a controllerId value
   if (!*aControllerId)
   {
-    nsresult rv;
     nsCOMPtr<nsIController> controller;
     controller = do_CreateInstance(aControllerClassName, &rv);
     NS_ENSURE_SUCCESS(rv, rv);  
 
     // We must insert at head of the list to be sure our
     //   controller is found before other implementations
     //   (e.g., not-implemented versions by browser)
     rv = controllers->InsertControllerAt(0, controller);
@@ -1253,25 +1246,20 @@ nsEditingSession::SetupEditorCommandCont
   SetEditorOnControllers
 
   Set the editor on the controller(s) for this window
 ----------------------------------------------------------------------------*/
 NS_IMETHODIMP
 nsEditingSession::SetEditorOnControllers(nsIDOMWindow *aWindow,
                                          nsIEditor* aEditor)
 {
-  nsresult rv;
-  
-  // set the editor on the controller
-  nsCOMPtr<nsIDOMWindowInternal> domWindowInt =
-                                     do_QueryInterface(aWindow, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(aWindow, NS_ERROR_NULL_POINTER);
   
   nsCOMPtr<nsIControllers> controllers;      
-  rv = domWindowInt->GetControllers(getter_AddRefs(controllers));
+  nsresult rv = aWindow->GetControllers(getter_AddRefs(controllers));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsISupports> editorAsISupports = do_QueryInterface(aEditor);
   if (mBaseCommandControllerId)
   {
     rv = SetContextOnControllerById(controllers, editorAsISupports,
                                     mBaseCommandControllerId);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -1310,21 +1298,20 @@ nsEditingSession::SetContextOnController
   return editorController->SetCommandContext(aContext);
 }
 
 void
 nsEditingSession::RemoveEditorControllers(nsIDOMWindow *aWindow)
 {
   // Remove editor controllers from the aWindow, call when we're 
   // tearing down/detaching editor.
-  nsCOMPtr<nsIDOMWindowInternal> domWindowInt(do_QueryInterface(aWindow));
 
   nsCOMPtr<nsIControllers> controllers;
-  if (domWindowInt)
-    domWindowInt->GetControllers(getter_AddRefs(controllers));
+  if (aWindow)
+    aWindow->GetControllers(getter_AddRefs(controllers));
 
   if (controllers)
   {
     nsCOMPtr<nsIController> controller;
     if (mBaseCommandControllerId)
     {
       controllers->GetControllerById(mBaseCommandControllerId,
                                      getter_AddRefs(controller));
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -283,24 +283,17 @@ nsEditor::PostCreate()
   nsresult rv = SetFlags(~mFlags);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // These operations only need to happen on the first PostCreate call
   if (!mDidPostCreate) {
     mDidPostCreate = PR_TRUE;
 
     // Set up listeners
-    rv = CreateEventListeners();
-    if (NS_FAILED(rv))
-    {
-      RemoveEventListeners();
-
-      return rv;
-    }
-
+    CreateEventListeners();
     rv = InstallEventListeners();
     NS_ENSURE_SUCCESS(rv, rv);
 
     // nuke the modification count, so the doc appears unmodified
     // do this before we notify listeners
     ResetModificationCount();
 
     // update the UI with our state
@@ -322,24 +315,24 @@ nsEditor::PostCreate()
     nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(focusedContent);
     if (target) {
       InitializeSelection(target);
     }
   }
   return NS_OK;
 }
 
-nsresult
+/* virtual */
+void
 nsEditor::CreateEventListeners()
 {
   // Don't create the handler twice
   if (!mEventListener) {
     mEventListener = new nsEditorEventListener();
   }
-  return NS_OK;
 }
 
 nsresult
 nsEditor::InstallEventListeners()
 {
   NS_ENSURE_TRUE(mDocWeak && mEventListener,
                  NS_ERROR_NOT_INITIALIZED);
 
--- a/editor/libeditor/base/nsEditor.h
+++ b/editor/libeditor/base/nsEditor.h
@@ -367,17 +367,17 @@ protected:
 
   // Get nsIWidget interface
   nsresult GetWidget(nsIWidget **aWidget);
 
 
   // install the event listeners for the editor 
   virtual nsresult InstallEventListeners();
 
-  virtual nsresult CreateEventListeners();
+  virtual void CreateEventListeners();
 
   // unregister and release our event listeners
   virtual void RemoveEventListeners();
 
   /**
    * Return true if spellchecking should be enabled for this editor.
    */
   PRBool GetDesiredSpellCheckState();
--- a/editor/libeditor/html/nsHTMLEditor.cpp
+++ b/editor/libeditor/html/nsHTMLEditor.cpp
@@ -434,24 +434,24 @@ nsHTMLEditor::FindSelectionRoot(nsINode 
   }
 
   // For non-readonly editors we want to find the root of the editable subtree
   // containing aContent.
   content = content->GetEditingHost();
   return content.forget();
 }
 
-nsresult
+/* virtual */
+void
 nsHTMLEditor::CreateEventListeners()
 {
   // Don't create the handler twice
   if (!mEventListener) {
     mEventListener = new nsHTMLEditorEventListener();
   }
-  return NS_OK;
 }
 
 nsresult
 nsHTMLEditor::InstallEventListeners()
 {
   NS_ENSURE_TRUE(mDocWeak && mEventListener,
                  NS_ERROR_NOT_INITIALIZED);
 
--- a/editor/libeditor/html/nsHTMLEditor.h
+++ b/editor/libeditor/html/nsHTMLEditor.h
@@ -441,17 +441,17 @@ public:
 
   nsresult RemoveStyleSheetFromList(const nsAString &aURL);
                        
 protected:
 
   NS_IMETHOD  InitRules();
 
   // Create the event listeners for the editor to install
-  virtual nsresult CreateEventListeners();
+  virtual void CreateEventListeners();
 
   virtual nsresult InstallEventListeners();
   virtual void RemoveEventListeners();
 
   PRBool ShouldReplaceRootElement();
   void ResetRootElementAndEventTarget();
   nsresult GetBodyElement(nsIDOMHTMLElement** aBody);
   // Get the focused node of this editor.
--- a/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
+++ b/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
@@ -975,59 +975,47 @@ nsDocShellTreeOwner::HandleEvent(nsIDOME
   }
 
   return NS_OK;
 }
 
 already_AddRefed<nsIWebBrowserChrome>
 nsDocShellTreeOwner::GetWebBrowserChrome()
 {
-  nsIWebBrowserChrome* chrome = nsnull;
-  if (mWebBrowserChromeWeak != nsnull) {
-    mWebBrowserChromeWeak->
-                        QueryReferent(NS_GET_IID(nsIWebBrowserChrome),
-                                      reinterpret_cast<void**>(&chrome));
+  nsCOMPtr<nsIWebBrowserChrome> chrome;
+  if (mWebBrowserChromeWeak) {
+    chrome = do_QueryReferent(mWebBrowserChromeWeak);
   } else if (mWebBrowserChrome) {
     chrome = mWebBrowserChrome;
-    NS_ADDREF(mWebBrowserChrome);
   }
-
-  return chrome;
+  return chrome.forget();
 }
 
 already_AddRefed<nsIEmbeddingSiteWindow>
 nsDocShellTreeOwner::GetOwnerWin()
 {
-  nsIEmbeddingSiteWindow* win = nsnull;
-  if (mWebBrowserChromeWeak != nsnull) {
-    mWebBrowserChromeWeak->
-                        QueryReferent(NS_GET_IID(nsIEmbeddingSiteWindow),
-                                      reinterpret_cast<void**>(&win));
+  nsCOMPtr<nsIEmbeddingSiteWindow> win;
+  if (mWebBrowserChromeWeak) {
+    win = do_QueryReferent(mWebBrowserChromeWeak);
   } else if (mOwnerWin) {
     win = mOwnerWin;
-    NS_ADDREF(mOwnerWin);
   }
-
-  return win;
+  return win.forget();
 }
 
 already_AddRefed<nsIInterfaceRequestor>
 nsDocShellTreeOwner::GetOwnerRequestor()
 {
-  nsIInterfaceRequestor* req = nsnull;
-  if (mWebBrowserChromeWeak != nsnull) {
-    mWebBrowserChromeWeak->
-                        QueryReferent(NS_GET_IID(nsIInterfaceRequestor),
-                                      reinterpret_cast<void**>(&req));
+  nsCOMPtr<nsIInterfaceRequestor> req;
+  if (mWebBrowserChromeWeak) {
+    req = do_QueryReferent(mWebBrowserChromeWeak);
   } else if (mOwnerRequestor) {
     req = mOwnerRequestor;
-    NS_ADDREF(mOwnerRequestor);
   }
-
-  return req;
+  return req.forget();
 }
 
 
 ///////////////////////////////////////////////////////////////////////////////
 // DefaultTooltipTextProvider
 
 class DefaultTooltipTextProvider : public nsITooltipTextProvider
 {
--- a/embedding/browser/webBrowser/nsWebBrowser.cpp
+++ b/embedding/browser/webBrowser/nsWebBrowser.cpp
@@ -50,17 +50,16 @@
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMElement.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIWebBrowserChrome.h"
 #include "nsPIDOMWindow.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIWebProgress.h"
 #include "nsIWebProgressListener.h"
 #include "nsIWebBrowserFocus.h"
 #include "nsIWebBrowserStream.h"
 #include "nsIPresShell.h"
 #include "nsIGlobalHistory.h"
 #include "nsIDocShellHistory.h"
 #include "nsIURIContentListener.h"
@@ -1765,31 +1764,30 @@ nsEventStatus nsWebBrowser::HandleEvent(
 
   default:
     break;
   }
 
   return nsEventStatus_eIgnore;
 }
 
-NS_IMETHODIMP nsWebBrowser::GetPrimaryContentWindow(nsIDOMWindowInternal **aDOMWindow)
+NS_IMETHODIMP nsWebBrowser::GetPrimaryContentWindow(nsIDOMWindow** aDOMWindow)
 {
   *aDOMWindow = 0;
 
   nsCOMPtr<nsIDocShellTreeItem> item;
   NS_ENSURE_TRUE(mDocShellTreeOwner, NS_ERROR_FAILURE);
   mDocShellTreeOwner->GetPrimaryContentShell(getter_AddRefs(item));
   NS_ENSURE_TRUE(item, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIDocShell> docShell;
   docShell = do_QueryInterface(item);
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
   
-  nsCOMPtr<nsIDOMWindowInternal> domWindow;
-  domWindow = do_GetInterface(docShell);
+  nsCOMPtr<nsIDOMWindow> domWindow = do_GetInterface(docShell);
   NS_ENSURE_TRUE(domWindow, NS_ERROR_FAILURE);
 
   *aDOMWindow = domWindow;
   NS_ADDREF(*aDOMWindow);
   return NS_OK;
   
 }
 //*****************************************************************************
--- a/embedding/browser/webBrowser/nsWebBrowser.h
+++ b/embedding/browser/webBrowser/nsWebBrowser.h
@@ -142,17 +142,17 @@ public:
 
 protected:
     virtual ~nsWebBrowser();
     NS_IMETHOD InternalDestroy();
 
     // XXXbz why are these NS_IMETHOD?  They're not interface methods!
     NS_IMETHOD SetDocShell(nsIDocShell* aDocShell);
     NS_IMETHOD EnsureDocShellTreeOwner();
-    NS_IMETHOD GetPrimaryContentWindow(nsIDOMWindowInternal **aDomWindow);
+    NS_IMETHOD GetPrimaryContentWindow(nsIDOMWindow **aDomWindow);
     NS_IMETHOD BindListener(nsISupports *aListener, const nsIID& aIID);
     NS_IMETHOD UnBindListener(nsISupports *aListener, const nsIID& aIID);
     NS_IMETHOD EnableGlobalHistory(PRBool aEnable);
 
     static nsEventStatus HandleEvent(nsGUIEvent *aEvent);
 
 protected:
    nsDocShellTreeOwner*       mDocShellTreeOwner;
--- a/embedding/components/commandhandler/src/nsCommandManager.cpp
+++ b/embedding/components/commandhandler/src/nsCommandManager.cpp
@@ -46,17 +46,16 @@
 
 #include "nsServiceManagerUtils.h"
 #include "nsIScriptSecurityManager.h"
 
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIFocusManager.h"
 #include "nsIDOMEventTarget.h"
 
 #include "nsCOMArray.h"
 
 #include "nsCommandManager.h"
 
 
@@ -310,25 +309,20 @@ nsCommandManager::GetControllerForComman
     if (!aTargetWindow)
       return rv;
 
     // if a target window is specified, it must be the window we expect
     if (aTargetWindow != mWindow)
         return NS_ERROR_FAILURE;
   }
 
-  if (aTargetWindow)
-  {
+  if (aTargetWindow) {
     // get the controller for this particular window
-    nsCOMPtr<nsIDOMWindowInternal> domWindowInternal = do_QueryInterface(aTargetWindow);
-    if (!domWindowInternal)
-      return NS_ERROR_FAILURE;
-
     nsCOMPtr<nsIControllers> controllers;
-    rv = domWindowInternal->GetControllers(getter_AddRefs(controllers));
+    rv = aTargetWindow->GetControllers(getter_AddRefs(controllers));
     if (NS_FAILED(rv))
       return rv;
     if (!controllers)
       return NS_ERROR_FAILURE;
 
     // dispatch the command
     return controllers->GetControllerForCommand(aCommand, outController);
   }
--- a/embedding/components/printingui/src/mac/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/mac/nsPrintProgress.cpp
@@ -64,18 +64,18 @@ nsPrintProgress::nsPrintProgress()
   m_pendingStateValue = 0;
 }
 
 nsPrintProgress::~nsPrintProgress()
 {
   (void)ReleaseListeners();
 }
 
-/* void openProgressDialog (in nsIDOMWindowInternal parent, in string dialogURL, in nsISupports parameters); */
-NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindowInternal *parent,
+/* void openProgressDialog (in nsIDOMWindow parent, in string dialogURL, in nsISupports parameters); */
+NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindow *parent,
                                                   const char *dialogURL,
                                                   nsISupports *parameters, 
                                                   nsIObserver *openDialogObserver,
                                                   PRBool *notifyOnOpen)
 {
   m_observer = openDialogObserver;
 
   nsresult rv = NS_ERROR_FAILURE;
@@ -337,18 +337,18 @@ NS_IMETHODIMP nsPrintProgress::StopMeteo
 }
 
 /* void showProgress (in long percent); */
 NS_IMETHODIMP nsPrintProgress::ShowProgress(PRInt32 percent)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindowInternal window); */
-NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindowInternal *window)
+/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindow window); */
+NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindow *window)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* void closeWindow (); */
 NS_IMETHODIMP nsPrintProgress::CloseWindow()
 {
   return NS_ERROR_NOT_IMPLEMENTED;
--- a/embedding/components/printingui/src/mac/nsPrintProgress.h
+++ b/embedding/components/printingui/src/mac/nsPrintProgress.h
@@ -39,38 +39,38 @@
 
 #ifndef __nsPrintProgress_h
 #define __nsPrintProgress_h
 
 #include "nsIPrintProgress.h"
 
 #include "nsCOMPtr.h"
 #include "nsISupportsArray.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIPrintStatusFeedback.h"
 #include "nsIObserver.h"
 #include "nsString.h"
 
 class nsPrintProgress : public nsIPrintProgress, public nsIPrintStatusFeedback
 {
 public: 
 	NS_DECL_ISUPPORTS
   NS_DECL_NSIPRINTPROGRESS
   NS_DECL_NSIWEBPROGRESSLISTENER
   NS_DECL_NSIPRINTSTATUSFEEDBACK
 
 	nsPrintProgress();
 	virtual ~nsPrintProgress();
 
 private:
-  nsresult ReleaseListeners(void);
+  nsresult ReleaseListeners();
 
   PRBool                            m_closeProgress;
   PRBool                            m_processCanceled;
   nsString                          m_pendingStatus;
   PRInt32                           m_pendingStateFlags;
   PRInt32                           m_pendingStateValue;
-  nsCOMPtr<nsIDOMWindowInternal>    m_dialog;
+  nsCOMPtr<nsIDOMWindow>            m_dialog;
   nsCOMPtr<nsISupportsArray>        m_listenerList;
   nsCOMPtr<nsIObserver>             m_observer;
 };
 
 #endif
--- a/embedding/components/printingui/src/os2/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/os2/nsPrintProgress.cpp
@@ -64,18 +64,18 @@ nsPrintProgress::nsPrintProgress()
   m_pendingStateValue = 0;
 }
 
 nsPrintProgress::~nsPrintProgress()
 {
   (void)ReleaseListeners();
 }
 
-/* void openProgressDialog (in nsIDOMWindowInternal parent, in string dialogURL, in nsISupports parameters); */
-NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindowInternal *parent,
+/* void openProgressDialog (in nsIDOMWindow parent, in string dialogURL, in nsISupports parameters); */
+NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindow *parent,
                                                   const char *dialogURL,
                                                   nsISupports *parameters, 
                                                   nsIObserver *openDialogObserver,
                                                   PRBool *notifyOnOpen)
 {
   *notifyOnOpen = PR_TRUE;
   m_observer = openDialogObserver;
   nsresult rv = NS_ERROR_FAILURE;
@@ -334,18 +334,18 @@ NS_IMETHODIMP nsPrintProgress::StopMeteo
 }
 
 /* void showProgress (in long percent); */
 NS_IMETHODIMP nsPrintProgress::ShowProgress(PRInt32 percent)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindowInternal window); */
-NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindowInternal *window)
+/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindow window); */
+NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindow *window)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* void closeWindow (); */
 NS_IMETHODIMP nsPrintProgress::CloseWindow()
 {
   return NS_ERROR_NOT_IMPLEMENTED;
--- a/embedding/components/printingui/src/os2/nsPrintProgress.h
+++ b/embedding/components/printingui/src/os2/nsPrintProgress.h
@@ -39,38 +39,38 @@
 
 #ifndef __nsPrintProgress_h
 #define __nsPrintProgress_h
 
 #include "nsIPrintProgress.h"
 
 #include "nsCOMPtr.h"
 #include "nsISupportsArray.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIPrintStatusFeedback.h"
 #include "nsIObserver.h"
 #include "nsString.h"
 
 class nsPrintProgress : public nsIPrintProgress, public nsIPrintStatusFeedback
 {
 public: 
 	NS_DECL_ISUPPORTS
   NS_DECL_NSIPRINTPROGRESS
   NS_DECL_NSIWEBPROGRESSLISTENER
   NS_DECL_NSIPRINTSTATUSFEEDBACK
 
 	nsPrintProgress();
 	virtual ~nsPrintProgress();
 
 private:
-  nsresult ReleaseListeners(void);
+  nsresult ReleaseListeners();
 
   PRBool                            m_closeProgress;
   PRBool                            m_processCanceled;
   nsString                          m_pendingStatus;
   PRInt32                           m_pendingStateFlags;
   PRInt32                           m_pendingStateValue;
-  nsCOMPtr<nsIDOMWindowInternal>    m_dialog;
+  nsCOMPtr<nsIDOMWindow>            m_dialog;
   nsCOMPtr<nsISupportsArray>        m_listenerList;
   nsCOMPtr<nsIObserver>             m_observer;
 };
 
 #endif
--- a/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp
@@ -120,17 +120,17 @@ nsPrintingPromptService::ShowPrintDialog
       return rv;
 
     block->SetInt(0, 0);
     return DoDialog(parent, block, webBrowserPrint, printSettings, kPrintDialogURL);
 }
 
 /* void showProgress (in nsIDOMWindow parent, in nsIWebBrowserPrint webBrowserPrint, in nsIPrintSettings printSettings, in nsIObserver openDialogObserver, in boolean isForPrinting, out nsIWebProgressListener webProgressListener, out nsIPrintProgressParams printProgressParams, out boolean notifyOnOpen); */
 NS_IMETHODIMP 
-nsPrintingPromptService::ShowProgress(nsIDOMWindow*           parent, 
+nsPrintingPromptService::ShowProgress(nsIDOMWindow*            parent, 
                                       nsIWebBrowserPrint*      webBrowserPrint,    // ok to be null
                                       nsIPrintSettings*        printSettings,      // ok to be null
                                       nsIObserver*             openDialogObserver, // ok to be null
                                       PRBool                   isForPrinting,
                                       nsIWebProgressListener** webProgressListener,
                                       nsIPrintProgressParams** printProgressParams,
                                       PRBool*                  notifyOnOpen)
 {
@@ -146,31 +146,26 @@ nsPrintingPromptService::ShowProgress(ns
 
     rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams();
     rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (printProgressParams) 
-    {
-        nsCOMPtr<nsIDOMWindowInternal> parentDOMIntl(do_QueryInterface(parent));
+    if (printProgressParams) {
+        nsCOMPtr<nsIDOMWindow> parentDOMIntl = parent;
 
-        if (mWatcher && !parentDOMIntl) 
-        {
-            nsCOMPtr<nsIDOMWindow> active;
-            mWatcher->GetActiveWindow(getter_AddRefs(active));
-            parentDOMIntl = do_QueryInterface(active);
+        if (mWatcher && !parentDOMIntl) {
+            mWatcher->GetActiveWindow(getter_AddRefs(parentDOMIntl));
         }
 
-        if (parentDOMIntl) 
-        {
-            mPrintProgress->OpenProgressDialog(parentDOMIntl, 
-                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL, 
+        if (parentDOMIntl) {
+            mPrintProgress->OpenProgressDialog(parentDOMIntl,
+                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL,
                                                *printProgressParams, openDialogObserver, notifyOnOpen);
         }
     }
 
     *webProgressListener = static_cast<nsIWebProgressListener*>(this);
     NS_ADDREF(*webProgressListener);
 
     return rv;
--- a/embedding/components/printingui/src/unixshared/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/unixshared/nsPrintProgress.cpp
@@ -65,18 +65,18 @@ nsPrintProgress::nsPrintProgress(nsIPrin
   m_PrintSetting = aPrintSettings;
 }
 
 nsPrintProgress::~nsPrintProgress()
 {
   (void)ReleaseListeners();
 }
 
-/* void openProgressDialog (in nsIDOMWindowInternal parent, in string dialogURL, in nsISupports parameters); */
-NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindowInternal *parent,
+/* void openProgressDialog (in nsIDOMWindow parent, in string dialogURL, in nsISupports parameters); */
+NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindow *parent,
                                                   const char *dialogURL,
                                                   nsISupports *parameters, 
                                                   nsIObserver *openDialogObserver,
                                                   PRBool *notifyOnOpen)
 {
   *notifyOnOpen = PR_TRUE;
   m_observer = openDialogObserver;
   nsresult rv = NS_ERROR_FAILURE;
@@ -337,18 +337,18 @@ NS_IMETHODIMP nsPrintProgress::StopMeteo
 }
 
 /* void showProgress (in long percent); */
 NS_IMETHODIMP nsPrintProgress::ShowProgress(PRInt32 percent)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindowInternal window); */
-NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindowInternal *window)
+/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindow window); */
+NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindow *window)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* void closeWindow (); */
 NS_IMETHODIMP nsPrintProgress::CloseWindow()
 {
   return NS_ERROR_NOT_IMPLEMENTED;
--- a/embedding/components/printingui/src/unixshared/nsPrintProgress.h
+++ b/embedding/components/printingui/src/unixshared/nsPrintProgress.h
@@ -40,39 +40,39 @@
 #ifndef __nsPrintProgress_h
 #define __nsPrintProgress_h
 
 #include "nsIPrintProgress.h"
 #include "nsIPrintingPromptService.h"
 
 #include "nsCOMPtr.h"
 #include "nsISupportsArray.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIPrintStatusFeedback.h"
 #include "nsIObserver.h"
 #include "nsString.h"
 
 class nsPrintProgress : public nsIPrintProgress, public nsIPrintStatusFeedback
 {
 public: 
 	NS_DECL_ISUPPORTS
   NS_DECL_NSIPRINTPROGRESS
   NS_DECL_NSIWEBPROGRESSLISTENER
   NS_DECL_NSIPRINTSTATUSFEEDBACK
 
 	nsPrintProgress(nsIPrintSettings* aPrintSettings);
 	virtual ~nsPrintProgress();
 
 private:
-  nsresult ReleaseListeners(void);
+  nsresult ReleaseListeners();
 
   PRBool                            m_closeProgress;
   PRBool                            m_processCanceled;
   nsString                          m_pendingStatus;
   PRInt32                           m_pendingStateFlags;
   PRInt32                           m_pendingStateValue;
-  nsCOMPtr<nsIDOMWindowInternal>    m_dialog;
+  nsCOMPtr<nsIDOMWindow>            m_dialog;
   nsCOMPtr<nsISupportsArray>        m_listenerList;
   nsCOMPtr<nsIObserver>             m_observer;
   nsCOMPtr<nsIPrintSettings>        m_PrintSetting;
 };
 
 #endif
--- a/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp
@@ -149,31 +149,26 @@ nsPrintingPromptService::ShowProgress(ns
 
     rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams();
     rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (printProgressParams) 
-    {
-        nsCOMPtr<nsIDOMWindowInternal> parentDOMIntl(do_QueryInterface(parent));
+    if (printProgressParams) {
+        nsCOMPtr<nsIDOMWindow> parentDOMIntl = parent;
 
-        if (mWatcher && !parentDOMIntl) 
-        {
-            nsCOMPtr<nsIDOMWindow> active;
-            mWatcher->GetActiveWindow(getter_AddRefs(active));
-            parentDOMIntl = do_QueryInterface(active);
+        if (mWatcher && !parentDOMIntl) {
+            mWatcher->GetActiveWindow(getter_AddRefs(parentDOMIntl));
         }
 
-        if (parentDOMIntl) 
-        {
-            mPrintProgress->OpenProgressDialog(parentDOMIntl, 
-                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL, 
+        if (parentDOMIntl) {
+            mPrintProgress->OpenProgressDialog(parentDOMIntl,
+                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL,
                                                *printProgressParams, openDialogObserver, notifyOnOpen);
         }
     }
 
     *webProgressListener = static_cast<nsIWebProgressListener*>(this);
     NS_ADDREF(*webProgressListener);
 
     return rv;
--- a/embedding/components/printingui/src/win/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/win/nsPrintProgress.cpp
@@ -94,18 +94,18 @@ nsPrintProgress::nsPrintProgress()
   m_pendingStateValue = 0;
 }
 
 nsPrintProgress::~nsPrintProgress()
 {
   (void)ReleaseListeners();
 }
 
-/* void openProgressDialog (in nsIDOMWindowInternal parent, in string dialogURL, in nsISupports parameters); */
-NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindowInternal *parent,
+/* void openProgressDialog (in nsIDOMWindow parent, in string dialogURL, in nsISupports parameters); */
+NS_IMETHODIMP nsPrintProgress::OpenProgressDialog(nsIDOMWindow *parent,
                                                   const char *dialogURL,
                                                   nsISupports *parameters, 
                                                   nsIObserver *openDialogObserver, 
                                                   PRBool *notifyOnOpen)
 {
   *notifyOnOpen = PR_TRUE;
   m_observer = openDialogObserver;
 
@@ -365,18 +365,18 @@ NS_IMETHODIMP nsPrintProgress::StopMeteo
 }
 
 /* void showProgress (in long percent); */
 NS_IMETHODIMP nsPrintProgress::ShowProgress(PRInt32 percent)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindowInternal window); */
-NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindowInternal *window)
+/* [noscript] void setDocShell (in nsIDocShell shell, in nsIDOMWindow window); */
+NS_IMETHODIMP nsPrintProgress::SetDocShell(nsIDocShell *shell, nsIDOMWindow *window)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* void closeWindow (); */
 NS_IMETHODIMP nsPrintProgress::CloseWindow()
 {
   return NS_ERROR_NOT_IMPLEMENTED;
--- a/embedding/components/printingui/src/win/nsPrintProgress.h
+++ b/embedding/components/printingui/src/win/nsPrintProgress.h
@@ -39,17 +39,17 @@
 
 #ifndef __nsPrintProgress_h
 #define __nsPrintProgress_h
 
 #include "nsIPrintProgress.h"
 
 #include "nsCOMPtr.h"
 #include "nsISupportsArray.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIPrintStatusFeedback.h"
 #include "nsString.h"
 #include "nsIWindowWatcher.h"
 #include "nsIObserver.h"
 
 class nsPrintProgress : public nsIPrintProgress, public nsIPrintStatusFeedback
 {
 public: 
@@ -57,21 +57,21 @@ public:
   NS_DECL_NSIPRINTPROGRESS
   NS_DECL_NSIWEBPROGRESSLISTENER
   NS_DECL_NSIPRINTSTATUSFEEDBACK
 
 	nsPrintProgress();
 	virtual ~nsPrintProgress();
 
 private:
-  nsresult ReleaseListeners(void);
+  nsresult ReleaseListeners();
 
   PRBool                            m_closeProgress;
   PRBool                            m_processCanceled;
   nsString                          m_pendingStatus;
   PRInt32                           m_pendingStateFlags;
   PRInt32                           m_pendingStateValue;
-  nsCOMPtr<nsIDOMWindowInternal>    m_dialog;
+  nsCOMPtr<nsIDOMWindow>            m_dialog;
   nsCOMPtr<nsISupportsArray>        m_listenerList;
   nsCOMPtr<nsIObserver>             m_observer;
 };
 
 #endif
--- a/embedding/components/printingui/src/win/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/win/nsPrintingPromptService.cpp
@@ -222,31 +222,26 @@ nsPrintingPromptService::ShowProgress(ns
 
     rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams();
     rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (printProgressParams) 
-    {
-        nsCOMPtr<nsIDOMWindowInternal> parentDOMIntl(do_QueryInterface(parent));
+    if (printProgressParams) {
+        nsCOMPtr<nsIDOMWindow> parentDOMIntl = parent;
 
-        if (mWatcher && !parentDOMIntl) 
-        {
-            nsCOMPtr<nsIDOMWindow> active;
-            mWatcher->GetActiveWindow(getter_AddRefs(active));
-            parentDOMIntl = do_QueryInterface(active);
+        if (mWatcher && !parentDOMIntl) {
+            mWatcher->GetActiveWindow(getter_AddRefs(parentDOMIntl));
         }
 
-        if (parentDOMIntl) 
-        {
-            mPrintProgress->OpenProgressDialog(parentDOMIntl, 
-                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL, 
+        if (parentDOMIntl) {
+            mPrintProgress->OpenProgressDialog(parentDOMIntl,
+                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL,
                                                *printProgressParams, openDialogObserver, notifyOnOpen);
         }
     }
 
     *webProgressListener = static_cast<nsIWebProgressListener*>(this);
     NS_ADDREF(*webProgressListener);
 
     return rv;
--- a/embedding/components/windowwatcher/public/nsPIWindowWatcher.idl
+++ b/embedding/components/windowwatcher/public/nsPIWindowWatcher.idl
@@ -77,17 +77,17 @@ interface nsPIWindowWatcher : nsISupport
              impossible to get to an nsIWebBrowserChrome from aParent, this
              method will effectively act as if aParent were null.
       @param aURL url to which to open the new window. Must already be
              escaped, if applicable. can be null.
       @param aName window name from JS window.open. can be null.  If a window
              with this name already exists, the openWindow call may just load
              aUrl in it (if aUrl is not null) and return it.
       @param aFeatures window features from JS window.open. can be null.
-      @param aDialog use dialog defaults (see nsIDOMWindowInternal::openDialog)
+      @param aDialog use dialog defaults (see nsIDOMWindow::openDialog)
       @param aArgs Window argument
       @return the new window
 
       @note This method may examine the JS context stack for purposes of
             determining the security context to use for the search for a given
             window named aName.
       @note This method should try to set the default charset for the new
             window to the default charset of the document in the calling window
--- a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
+++ b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
@@ -52,17 +52,16 @@
 #include "nsIDocShellLoadInfo.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIDocumentLoader.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMChromeWindow.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMModalContentWindow.h"
 #include "nsIPrompt.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIScreen.h"
 #include "nsIScreenManager.h"
 #include "nsIScriptContext.h"
 #include "nsIJSContextStack.h"
 #include "nsIObserverService.h"
@@ -1773,18 +1772,17 @@ nsWindowWatcher::ReadyOpenedDocShellItem
                                          nsIDOMWindow        **aOpenedWindow)
 {
   nsresult rv = NS_ERROR_FAILURE;
 
   *aOpenedWindow = 0;
   nsCOMPtr<nsPIDOMWindow> piOpenedWindow(do_GetInterface(aOpenedItem));
   if (piOpenedWindow) {
     if (aParent) {
-      nsCOMPtr<nsIDOMWindowInternal> internalParent(do_QueryInterface(aParent));
-      piOpenedWindow->SetOpenerWindow(internalParent, aWindowIsNew); // damnit
+      piOpenedWindow->SetOpenerWindow(aParent, aWindowIsNew); // damnit
 
       if (aWindowIsNew) {
 #ifdef DEBUG
         // Assert that we're not loading things right now.  If we are, when
         // that load completes it will clobber whatever principals we set up
         // on this new window!
         nsCOMPtr<nsIDocumentLoader> docloader =
           do_QueryInterface(aOpenedItem);
--- a/js/src/xpconnect/src/dom_quickstubs.qsconf
+++ b/js/src/xpconnect/src/dom_quickstubs.qsconf
@@ -51,32 +51,35 @@ members = [
     # dom/interfaces/base
     #
     # Note that many implementations of interfaces in this directory
     # use GetCurrentNativeCallContext, notably:
     #   - nsIDOMCrypto.{generateCRMFRequest,signText}
     #   - nsIDOMLocation.reload
     #   - nsIDOMNSHistory.go
     #   - nsIDOMJSPluginArray.refresh
-    #   - nsIDOMWindowInternal.postMessage
+    #   - nsIDOMWindow.postMessage
     #   - nsIDOMJSWindow.{prompt,setTimeout,setInterval,open,openDialog}
     #
     # (And nsIDOMModalContentWindow.returnValue is an attribute of type
     # nsIVariant, which qsgen.py can't handle.)
     #
     'nsIDOMWindow.name',
     'nsIDOMWindow.parent',
     'nsIDOMWindow.top',
     # Several window properties are magically resolved, including
     # location, _content, navigator, document, and window itself.
     # These do not need quick stubs.
     #'nsIDOMWindow.document',
     'nsIDOMWindow.getSelection',
     'nsIDOMWindow.scrollByLines',
     'nsIDOMWindow.getComputedStyle',
+    'nsIDOMWindow.sessionStorage',
+    'nsIDOMWindow.localStorage',
+    'nsIDOMWindow.globalStorage',
     'nsIDOMJSWindow.dump',
     'nsIDOMScreen.top',
     'nsIDOMScreen.height',
     'nsIDOMScreen.width',
     'nsIDOMScreen.left',
     'nsIDOMClientRect.*',
     'nsIDOMClientRectList.*',
     'nsIDOMPaintRequest.*',
@@ -352,17 +355,16 @@ members = [
     'nsIDOMToString.toString',
     'nsIDOMStorage.setItem',
     'nsIDOMStorage.length',
     'nsIDOMStorage.getItem',
     'nsIDOMStorage.key',
     'nsIDOMStorage.removeItem',
     'nsIDOMStorage.clear',
     'nsIDOMStorageItem.value',
-    'nsIDOMStorageWindow.*',
 
     # dom/interfaces/stylesheets - None.
 
     # dom/interfaces/svg - None.
     'nsIDOMSVGStylable.*',
 
     # dom/interfaces/threads - None.
 
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -107,17 +107,16 @@
 #include "nsLayoutUtils.h"
 #include "nsAutoPtr.h"
 #include "nsBoxFrame.h"
 #include "nsBoxLayout.h"
 #include "nsImageFrame.h"
 #include "nsIObjectLoadingContent.h"
 #include "nsContentErrors.h"
 #include "nsIPrincipal.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsStyleUtil.h"
 #include "nsBox.h"
 #include "nsTArray.h"
 #include "nsGenericDOMDataNode.h"
 #include "mozilla/dom/Element.h"
 #include "FrameLayerBuilder.h"
 
 #ifdef MOZ_XUL
@@ -206,20 +205,16 @@ NS_NewSVGFilterFrame(nsIPresShell *aPres
 nsIFrame*
 NS_NewSVGPatternFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
 nsIFrame*
 NS_NewSVGMaskFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
 nsIFrame*
 NS_NewSVGLeafFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
 
 #include "nsIDocument.h"
-#include "nsIDOMElement.h"
-#include "nsIDOMNodeList.h"
-#include "nsIDOMDocument.h"
-#include "nsIDOMDocumentXBL.h"
 #include "nsIScrollable.h"
 #include "nsINodeInfo.h"
 #include "prenv.h"
 #include "nsWidgetsCID.h"
 #include "nsNodeInfoManager.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsIServiceManager.h"
 
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -2668,19 +2668,19 @@ DocumentViewerImpl::Print(PRBool        
 
 
   return Print(printSettings, nsnull);
 #else
   return NS_ERROR_FAILURE;
 #endif
 }
 
-/* [noscript] void printWithParent (in nsIDOMWindowInternal aParentWin, in nsIPrintSettings aThePrintSettings, in nsIWebProgressListener aWPListener); */
+/* [noscript] void printWithParent (in nsIDOMWindow aParentWin, in nsIPrintSettings aThePrintSettings, in nsIWebProgressListener aWPListener); */
 NS_IMETHODIMP 
-DocumentViewerImpl::PrintWithParent(nsIDOMWindowInternal *aParentWin, nsIPrintSettings *aThePrintSettings, nsIWebProgressListener *aWPListener)
+DocumentViewerImpl::PrintWithParent(nsIDOMWindow*, nsIPrintSettings *aThePrintSettings, nsIWebProgressListener *aWPListener)
 {
 #ifdef NS_PRINTING
   return Print(aThePrintSettings, aWPListener);
 #else
   return NS_ERROR_FAILURE;
 #endif
 }
 
@@ -4283,17 +4283,17 @@ DocumentViewerImpl::OnDonePrinting()
       mPrintEngine->Destroy();
       mPrintEngine = nsnull;
     }
 
     // We are done printing, now cleanup 
     if (mDeferredWindowClose) {
       mDeferredWindowClose = PR_FALSE;
       nsCOMPtr<nsISupports> container = do_QueryReferent(mContainer);
-      nsCOMPtr<nsIDOMWindowInternal> win = do_GetInterface(container);
+      nsCOMPtr<nsIDOMWindow> win = do_GetInterface(container);
       if (win)
         win->Close();
     } else if (mClosingWhilePrinting) {
       if (mDocument) {
         mDocument->SetScriptGlobalObject(nsnull);
         mDocument->Destroy();
         mDocument = nsnull;
       }
--- a/layout/build/nsLayoutStatics.cpp
+++ b/layout/build/nsLayoutStatics.cpp
@@ -171,21 +171,17 @@ nsLayoutStatics::Initialize()
   }
 
   rv = nsTextFragment::Init();
   if (NS_FAILED(rv)) {
     NS_ERROR("Could not initialize nsTextFragment");
     return rv;
   }
 
-  rv = nsCellMap::Init();
-  if (NS_FAILED(rv)) {
-    NS_ERROR("Could not initialize nsCellMap");
-    return rv;
-  }
+  nsCellMap::Init();
 
   nsCSSRendering::Init();
 
   nsTextFrameTextRunCache::Init();
 
   rv = nsHTMLDNSPrefetch::Initialize();
   if (NS_FAILED(rv)) {
     NS_ERROR("Could not initialize HTML DNS prefetch");
--- a/layout/forms/nsFileControlFrame.cpp
+++ b/layout/forms/nsFileControlFrame.cpp
@@ -417,17 +417,17 @@ NS_IMETHODIMP
 nsFileControlFrame::CaptureMouseListener::HandleEvent(nsIDOMEvent* aMouseEvent)
 {
   nsresult rv;
 
   NS_ASSERTION(mFrame, "We should have been unregistered");
   if (!ShouldProcessMouseClick(aMouseEvent))
     return NS_OK;
 
-  // Get parent nsIDOMWindowInternal object.
+  // Get parent nsPIDOMWindow object.
   nsIContent* content = mFrame->GetContent();
   if (!content)
     return NS_ERROR_FAILURE;
 
   nsHTMLInputElement* inputElement = nsHTMLInputElement::FromContent(content);
   if (!inputElement)
     return NS_ERROR_FAILURE;
 
--- a/layout/generic/nsCanvasFrame.cpp
+++ b/layout/generic/nsCanvasFrame.cpp
@@ -52,17 +52,16 @@
 #include "nsIPresShell.h"
 #include "nsIScrollPositionListener.h"
 #include "nsDisplayList.h"
 #include "nsAbsoluteContainingBlock.h"
 #include "nsCSSFrameConstructor.h"
 #include "nsFrameManager.h"
 
 // for focus
-#include "nsIDOMWindowInternal.h"
 #include "nsIScrollableFrame.h"
 #include "nsIDocShell.h"
 
 #ifdef DEBUG_rods
 //#define DEBUG_CANVAS_FOCUS
 #endif
 
 #define CANVAS_ABS_POS_CHILD_LIST NS_CONTAINER_LIST_COUNT_INCL_OC
--- a/layout/inspector/public/inIFlasher.idl
+++ b/layout/inspector/public/inIFlasher.idl
@@ -33,19 +33,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
-interface nsIDOMDocument;
 interface nsIDOMElement;
-interface nsIDOMWindowInternal;
 
 [scriptable, uuid(7B4A099F-6F6E-4565-977B-FB622ADBFF49)]
 interface inIFlasher : nsISupports 
 {
   attribute DOMString       color;
   attribute boolean         invert;
   attribute unsigned short  thickness;
 
--- a/layout/inspector/src/inDOMUtils.cpp
+++ b/layout/inspector/src/inDOMUtils.cpp
@@ -45,17 +45,17 @@
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMCharacterData.h"
 #include "nsRuleNode.h"
 #include "nsIStyleRule.h"
 #include "mozilla/css/StyleRule.h"
 #include "nsICSSStyleRuleDOMWrapper.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsXBLBinding.h"
 #include "nsXBLPrototypeBinding.h"
 #include "nsIMutableArray.h"
 #include "nsBindingManager.h"
 #include "nsComputedDOMStyle.h"
 #include "nsEventStateManager.h"
 #include "nsIAtom.h"
 #include "nsIRange.h"
@@ -90,17 +90,17 @@ inDOMUtils::IsIgnorableWhitespace(nsIDOM
 
   if (!content->TextIsOnlyWhitespace()) {
     return NS_OK;
   }
 
   // Okay.  We have only white space.  Let's check the white-space
   // property now and make sure that this isn't preformatted text...
 
-  nsCOMPtr<nsIDOMWindowInternal> win = inLayoutUtils::GetWindowFor(aDataNode);
+  nsCOMPtr<nsIDOMWindow> win = inLayoutUtils::GetWindowFor(aDataNode);
   if (!win) {
     // Hmm.  Things are screwy if we have no window...
     NS_ERROR("No window!");
     return NS_OK;
   }
 
   nsIFrame* frame = content->GetPrimaryFrame();
   if (frame) {
--- a/layout/inspector/src/inFlasher.cpp
+++ b/layout/inspector/src/inFlasher.cpp
@@ -141,17 +141,17 @@ inFlasher::RepaintElement(nsIDOMElement*
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 inFlasher::DrawElementOutline(nsIDOMElement* aElement)
 {
   NS_ENSURE_ARG_POINTER(aElement);
-  nsCOMPtr<nsIDOMWindowInternal> window = inLayoutUtils::GetWindowFor(aElement);
+  nsCOMPtr<nsIDOMWindow> window = inLayoutUtils::GetWindowFor(aElement);
   if (!window) return NS_OK;
   nsCOMPtr<nsIPresShell> presShell = inLayoutUtils::GetPresShellFor(window);
   if (!presShell) return NS_OK;
 
   nsIFrame* frame = inLayoutUtils::GetFrameFor(aElement);
 
   PRBool isFirstFrame = PR_TRUE;
 
@@ -178,17 +178,17 @@ inFlasher::DrawElementOutline(nsIDOMElem
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 inFlasher::ScrollElementIntoView(nsIDOMElement *aElement)
 {
   NS_ENSURE_ARG_POINTER(aElement);
-  nsCOMPtr<nsIDOMWindowInternal> window = inLayoutUtils::GetWindowFor(aElement);
+  nsCOMPtr<nsIDOMWindow> window = inLayoutUtils::GetWindowFor(aElement);
   if (!window) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIPresShell> presShell = inLayoutUtils::GetPresShellFor(window);
   if (!presShell) {
     return NS_OK;
   }
--- a/layout/inspector/src/inLayoutUtils.cpp
+++ b/layout/inspector/src/inLayoutUtils.cpp
@@ -42,35 +42,30 @@
 #include "nsIContentViewer.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocShell.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 
 ///////////////////////////////////////////////////////////////////////////////
 
-nsIDOMWindowInternal*
+nsIDOMWindow*
 inLayoutUtils::GetWindowFor(nsIDOMNode* aNode)
 {
   nsCOMPtr<nsIDOMDocument> doc1;
   aNode->GetOwnerDocument(getter_AddRefs(doc1));
   return GetWindowFor(doc1.get());
 }
 
-nsIDOMWindowInternal*
+nsIDOMWindow*
 inLayoutUtils::GetWindowFor(nsIDOMDocument* aDoc)
 {
   nsCOMPtr<nsIDOMWindow> window;
   aDoc->GetDefaultView(getter_AddRefs(window));
-  if (!window) {
-    return nsnull;
-  }
-  
-  nsCOMPtr<nsIDOMWindowInternal> windowInternal = do_QueryInterface(window);
-  return windowInternal;
+  return window;
 }
 
 nsIPresShell* 
 inLayoutUtils::GetPresShellFor(nsISupports* aThing)
 {
   nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aThing);
 
   nsCOMPtr<nsIPresShell> presShell;
--- a/layout/inspector/src/inLayoutUtils.h
+++ b/layout/inspector/src/inLayoutUtils.h
@@ -37,27 +37,27 @@
 
 #ifndef __inLayoutUtils_h__
 #define __inLayoutUtils_h__
 
 class nsBindingManager;
 class nsIDOMDocument;
 class nsIDOMElement;
 class nsIDOMNode;
-class nsIDOMWindowInternal;
+class nsIDOMWindow;
 class nsEventStateManager;
 class nsIFrame;
 class nsIPresShell;
 class nsISupports;
 
 class inLayoutUtils
 {
 public:
-  static nsIDOMWindowInternal* GetWindowFor(nsIDOMNode* aNode);
-  static nsIDOMWindowInternal* GetWindowFor(nsIDOMDocument* aDoc);
+  static nsIDOMWindow* GetWindowFor(nsIDOMNode* aNode);
+  static nsIDOMWindow* GetWindowFor(nsIDOMDocument* aDoc);
   static nsIPresShell* GetPresShellFor(nsISupports* aThing);
   static nsIFrame* GetFrameFor(nsIDOMElement* aElement);
   static nsEventStateManager* GetEventStateManagerFor(nsIDOMElement *aElement);
   static nsBindingManager* GetBindingManagerFor(nsIDOMNode* aNode);
   static nsIDOMDocument* GetSubDocumentFor(nsIDOMNode* aNode);
   static nsIDOMNode* GetContainerFor(nsIDOMDocument* aDoc);
 };
 
--- a/layout/printing/nsIPrintProgress.idl
+++ b/layout/printing/nsIPrintProgress.idl
@@ -34,27 +34,27 @@
  * 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 "nsISupports.idl"
 #include "nsIWebProgressListener.idl"
 
-interface nsIDOMWindowInternal;
+interface nsIDOMWindow;
 interface nsIObserver;
 interface nsIPrompt;
 
-[scriptable, uuid(7E46BC35-FB7D-4b45-AB35-82FD61015380)]
+[scriptable, uuid(594fd36d-5b1b-412f-a74e-ab72099a5bb2)]
 interface nsIPrintProgress: nsIWebProgressListener {
 
   /* Open the progress dialog
      you can specify parameters through an xpcom object
   */
-  void openProgressDialog(in nsIDOMWindowInternal parent, 
+  void openProgressDialog(in nsIDOMWindow parent, 
                           in string dialogURL, 
                           in nsISupports parameters, 
                           in nsIObserver openDialogObserver,
                           out boolean notifyOnOpen);
   
   /* Close the progress dialog */
   void closeProgressDialog(in boolean forceClose);
   
--- a/layout/printing/nsIPrintStatusFeedback.idl
+++ b/layout/printing/nsIPrintStatusFeedback.idl
@@ -33,21 +33,21 @@
  * 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 "nsISupports.idl"
 
 interface nsIDocShell;
-interface nsIDOMWindowInternal;
+interface nsIDOMWindow;
 
-[scriptable, uuid(19855DFF-3248-4902-B196-93EE4C477880)]
+[scriptable, uuid(e439d3eb-b1ed-449c-aaf7-c693e399b16f)]
 interface nsIPrintStatusFeedback : nsISupports {
 
 	void showStatusString(in wstring status);
 	void startMeteors();
 	void stopMeteors();
 	void showProgress(in long percent);
-	[noscript] void setDocShell(in nsIDocShell shell, in nsIDOMWindowInternal window);
+	[noscript] void setDocShell(in nsIDocShell shell, in nsIDOMWindow window);
 	void closeWindow();
 };
 
--- a/layout/svg/base/src/nsSVGOuterSVGFrame.cpp
+++ b/layout/svg/base/src/nsSVGOuterSVGFrame.cpp
@@ -44,17 +44,17 @@
 #include "nsDisplayList.h"
 #include "nsStubMutationObserver.h"
 #include "gfxContext.h"
 #include "gfxMatrix.h"
 #include "gfxRect.h"
 #include "nsIContentViewer.h"
 #include "nsIDocShell.h"
 #include "nsIDOMDocument.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIObjectLoadingContent.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsSVGMatrix.h"
 
 namespace dom = mozilla::dom;
 
 class nsSVGMutationObserver : public nsStubMutationObserver
@@ -832,17 +832,17 @@ nsSVGOuterSVGFrame::UnregisterForeignObj
 }
 
 PRBool
 nsSVGOuterSVGFrame::IsRootOfReplacedElementSubDoc(nsIFrame **aEmbeddingFrame)
 {
   if (!mContent->GetParent()) {
     // Our content is the document element
     nsCOMPtr<nsISupports> container = PresContext()->GetContainer();
-    nsCOMPtr<nsIDOMWindowInternal> window = do_GetInterface(container);
+    nsCOMPtr<nsIDOMWindow> window = do_GetInterface(container);
     if (window) {
       nsCOMPtr<nsIDOMElement> frameElement;
       window->GetFrameElement(getter_AddRefs(frameElement));
       nsCOMPtr<nsIObjectLoadingContent> olc = do_QueryInterface(frameElement);
       if (olc) {
         // Our document is inside an HTML 'object', 'embed' or 'applet' element
         if (aEmbeddingFrame) {
           nsCOMPtr<nsIContent> element = do_QueryInterface(frameElement);
--- a/layout/tables/nsCellMap.cpp
+++ b/layout/tables/nsCellMap.cpp
@@ -164,41 +164,39 @@ nsTableCellMap::InsertGroupCellMap(nsCel
   }
   aNewMap.SetNextSibling(next);
 }
 
 void nsTableCellMap::InsertGroupCellMap(nsTableRowGroupFrame*  aNewGroup,
                                         nsTableRowGroupFrame*& aPrevGroup)
 {
   nsCellMap* newMap = new nsCellMap(aNewGroup, mBCInfo != nsnull);
-  if (newMap) {
-    nsCellMap* prevMap = nsnull;
-    nsCellMap* lastMap = mFirstMap;
-    if (aPrevGroup) {
-      nsCellMap* map = mFirstMap;
-      while (map) {
-        lastMap = map;
-        if (map->GetRowGroup() == aPrevGroup) {
-          prevMap = map;
-          break;
-        }
-        map = map->GetNextSibling();
+  nsCellMap* prevMap = nsnull;
+  nsCellMap* lastMap = mFirstMap;
+  if (aPrevGroup) {
+    nsCellMap* map = mFirstMap;
+    while (map) {
+      lastMap = map;
+      if (map->GetRowGroup() == aPrevGroup) {
+        prevMap = map;
+        break;
       }
+      map = map->GetNextSibling();
     }
-    if (!prevMap) {
-      if (aPrevGroup) {
-        prevMap = lastMap;
-        aPrevGroup = (prevMap) ? prevMap->GetRowGroup() : nsnull;
-      }
-      else {
-        aPrevGroup = nsnull;
-      }
+  }
+  if (!prevMap) {
+    if (aPrevGroup) {
+      prevMap = lastMap;
+      aPrevGroup = (prevMap) ? prevMap->GetRowGroup() : nsnull;
     }
-    InsertGroupCellMap(prevMap, *newMap);
+    else {
+      aPrevGroup = nsnull;
+    }
   }
+  InsertGroupCellMap(prevMap, *newMap);
 }
 
 void nsTableCellMap::RemoveGroupCellMap(nsTableRowGroupFrame* aGroup)
 {
   nsCellMap* map = mFirstMap;
   nsCellMap* prior = nsnull;
   while (map) {
     if (map->GetRowGroup() == aGroup) {
@@ -1172,24 +1170,21 @@ nsCellMap::~nsCellMap()
     PRUint32 colCount = row.Length();
     for (PRUint32 colX = 0; colX < colCount; colX++) {
       DestroyCellData(row[colX]);
     }
   }
 }
 
 /* static */
-nsresult
+void
 nsCellMap::Init()
 {
-  NS_ASSERTION(!sEmptyRow, "How did that happen?");
+  NS_ABORT_IF_FALSE(!sEmptyRow, "How did that happen?");
   sEmptyRow = new nsCellMap::CellDataArray();
-  NS_ENSURE_TRUE(sEmptyRow, NS_ERROR_OUT_OF_MEMORY);
-
-  return NS_OK;
 }
 
 /* static */
 void
 nsCellMap::Shutdown()
 {
   delete sEmptyRow;
   sEmptyRow = nsnull;
--- a/layout/tables/nsCellMap.h
+++ b/layout/tables/nsCellMap.h
@@ -306,17 +306,17 @@ public:
     */
   nsCellMap(nsTableRowGroupFrame* aRowGroupFrame, PRBool aIsBC);
 
   /** destructor
     * NOT VIRTUAL BECAUSE THIS CLASS SHOULD **NEVER** BE SUBCLASSED
     */
   ~nsCellMap();
 
-  static nsresult Init();
+  static void Init();
   static void Shutdown();
 
   nsCellMap* GetNextSibling() const;
   void SetNextSibling(nsCellMap* aSibling);
 
   nsTableRowGroupFrame* GetRowGroup() const;
 
   nsTableCellFrame* GetCellFrame(PRInt32   aRowIndex,
--- a/layout/xul/base/src/nsMenuBarFrame.cpp
+++ b/layout/xul/base/src/nsMenuBarFrame.cpp
@@ -48,17 +48,16 @@
 #include "nsINameSpaceManager.h"
 #include "nsIDocument.h"
 #include "nsIDOMEventTarget.h"
 #include "nsGkAtoms.h"
 #include "nsMenuFrame.h"
 #include "nsMenuPopupFrame.h"
 #include "nsGUIEvent.h"
 #include "nsUnicharUtils.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMDocument.h"
 #include "nsPIDOMWindow.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsCSSFrameConstructor.h"
 #ifdef XP_WIN
 #include "nsISound.h"
 #include "nsWidgetsCID.h"
 #endif
--- a/layout/xul/base/src/nsXULPopupManager.cpp
+++ b/layout/xul/base/src/nsXULPopupManager.cpp
@@ -713,21 +713,19 @@ CheckCaretDrawingState() {
   // document and erase its caret.
   nsIFocusManager* fm = nsFocusManager::GetFocusManager();
   if (fm) {
     nsCOMPtr<nsIDOMWindow> window;
     fm->GetFocusedWindow(getter_AddRefs(window));
     if (!window)
       return;
 
-    nsCOMPtr<nsIDOMWindowInternal> windowInternal = do_QueryInterface(window);
-
     nsCOMPtr<nsIDOMDocument> domDoc;
     nsCOMPtr<nsIDocument> focusedDoc;
-    windowInternal->GetDocument(getter_AddRefs(domDoc));
+    window->GetDocument(getter_AddRefs(domDoc));
     focusedDoc = do_QueryInterface(domDoc);
     if (!focusedDoc)
       return;
 
     nsIPresShell* presShell = focusedDoc->GetShell();
     if (!presShell)
       return;
 
--- a/mobile/chrome/content/sanitize.js
+++ b/mobile/chrome/content/sanitize.js
@@ -85,16 +85,31 @@ Sanitizer.prototype = {
           dump("Error sanitizing " + itemName + ": " + er + "\n");
         }
       }
     }
     return errors;
   },
   
   items: {
+    // Clear Sync account before passwords so that Sync still has access to the
+    // credentials to clean up device-specific records on the server. Also
+    // disable it before wiping history so we don't accidentally sync that.
+    syncAccount: {
+      clear: function ()
+      {
+        WeaveGlue.disconnect();
+      },
+
+      get canClear()
+      {
+        return (Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED);
+      }
+    },
+
     cache: {
       clear: function ()
       {
         var cacheService = Cc["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
         try {
           cacheService.evictEntries(Ci.nsICache.STORE_ANYWHERE);
         } catch(er) {}
 
@@ -275,28 +290,16 @@ Sanitizer.prototype = {
         var authMgr = Cc['@mozilla.org/network/http-auth-manager;1'].getService(Ci.nsIHttpAuthManager);
         authMgr.clearAll();
       },
       
       get canClear()
       {
         return true;
       }
-    },
-
-    syncAccount: {
-      clear: function ()
-      {
-        WeaveGlue.disconnect();
-      },
-
-      get canClear()
-      {
-        return (Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED);
-      }
     }
   }
 };
 
 
 // "Static" members
 Sanitizer.prefDomain          = "privacy.sanitize.";
 Sanitizer.prefShutdown        = "sanitizeOnShutdown";
--- a/mobile/components/HelperAppDialog.js
+++ b/mobile/components/HelperAppDialog.js
@@ -112,17 +112,17 @@ HelperAppLauncherDialog.prototype = {
         if (file)
           return file;
       }
     }
 
     // Use file picker to show dialog.
     let picker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
     let windowTitle = "";
-    let parent = aContext.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal);
+    let parent = aContext.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
     picker.init(parent, windowTitle, Ci.nsIFilePicker.modeSave);
     picker.defaultString = aDefaultFile;
 
     if (aSuggestedFileExt) {
       // aSuggestedFileExtension includes the period, so strip it
       picker.defaultExtension = aSuggestedFileExt.substring(1);
     }
     else {
--- a/netwerk/protocol/http/nsHttpConnection.cpp
+++ b/netwerk/protocol/http/nsHttpConnection.cpp
@@ -625,16 +625,22 @@ nsHttpConnection::CloseTransaction(nsAHt
 
     // mask this error code because its not a real error.
     if (reason == NS_BASE_STREAM_CLOSED)
         reason = NS_OK;
 
     mTransaction->Close(reason);
     mTransaction = nsnull;
 
+    if (mCallbacks) {
+        nsIInterfaceRequestor *cbs = nsnull;
+        mCallbacks.swap(cbs);
+        NS_ProxyRelease(mCallbackTarget, cbs);
+    }
+
     if (NS_FAILED(reason))
         Close(reason);
 
     // flag the connection as reused here for convenience sake.  certainly
     // it might be going away instead ;-)
     mIsReused = PR_TRUE;
 }
 
--- a/netwerk/test/browser/browser_NetUtil.js
+++ b/netwerk/test/browser/browser_NetUtil.js
@@ -74,17 +74,17 @@ function test_asyncFetchBadCert() {
 
 function WindowListener(aURL, aCallback) {
   this.callback = aCallback;
   this.url = aURL;
 }
 WindowListener.prototype = {
   onOpenWindow: function(aXULWindow) {
     var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-                              .getInterface(Ci.nsIDOMWindowInternal);
+                              .getInterface(Ci.nsIDOMWindow);
     var self = this;
     domwindow.addEventListener("load", function() {
       domwindow.removeEventListener("load", arguments.callee, false);
 
       if (domwindow.document.location.href != self.url)
         return;
 
       // Allow other window load listeners to execute before passing to callback
--- a/security/manager/boot/src/nsSecureBrowserUIImpl.cpp
+++ b/security/manager/boot/src/nsSecureBrowserUIImpl.cpp
@@ -415,17 +415,17 @@ static PRUint32 GetSecurityStateFromSecu
   PR_LOG(gSecureDocLog, PR_LOG_DEBUG, ("SecureUI: GetSecurityState: - Returning %d\n", 
                                        securityState));
   return securityState;
 }
 
 
 NS_IMETHODIMP
 nsSecureBrowserUIImpl::Notify(nsIDOMHTMLFormElement* aDOMForm,
-                              nsIDOMWindowInternal* aWindow, nsIURI* actionURL,
+                              nsIDOMWindow* aWindow, nsIURI* actionURL,
                               PRBool* cancelSubmit)
 {
   // Return NS_OK unless we want to prevent this form from submitting.
   *cancelSubmit = PR_FALSE;
   if (!aWindow || !actionURL || !aDOMForm)
     return NS_OK;
   
   nsCOMPtr<nsIContent> formNode = do_QueryInterface(aDOMForm);
@@ -1786,22 +1786,22 @@ nsUIContext::~nsUIContext()
 
 /* void getInterface (in nsIIDRef uuid, [iid_is (uuid), retval] out nsQIResult result); */
 NS_IMETHODIMP nsUIContext::GetInterface(const nsIID & uuid, void * *result)
 {
   NS_ENSURE_TRUE(mWindow, NS_ERROR_FAILURE);
   nsresult rv;
 
   if (uuid.Equals(NS_GET_IID(nsIPrompt))) {
-    nsCOMPtr<nsIDOMWindowInternal> internal = do_QueryInterface(mWindow, &rv);
+    nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(mWindow, &rv);
     if (NS_FAILED(rv)) return rv;
 
     nsIPrompt *prompt;
 
-    rv = internal->GetPrompter(&prompt);
+    rv = window->GetPrompter(&prompt);
     *result = prompt;
   } else if (uuid.Equals(NS_GET_IID(nsIDOMWindow))) {
     *result = mWindow;
     NS_ADDREF ((nsISupports*) *result);
     rv = NS_OK;
   } else {
     rv = NS_ERROR_NO_INTERFACE;
   }
--- a/security/manager/boot/src/nsSecureBrowserUIImpl.h
+++ b/security/manager/boot/src/nsSecureBrowserUIImpl.h
@@ -86,17 +86,17 @@ public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIWEBPROGRESSLISTENER
   NS_DECL_NSISECUREBROWSERUI
   
   // nsIObserver
   NS_DECL_NSIOBSERVER
   NS_DECL_NSISSLSTATUSPROVIDER
 
-  NS_IMETHOD Notify(nsIDOMHTMLFormElement* formNode, nsIDOMWindowInternal* window,
+  NS_IMETHOD Notify(nsIDOMHTMLFormElement* formNode, nsIDOMWindow* window,
                     nsIURI *actionURL, PRBool* cancelSubmit);
   NS_IMETHOD NotifyInvalidSubmit(nsIDOMHTMLFormElement* formNode,
                                  nsIArray* invalidElements) { return NS_OK; };
   
 protected:
   mozilla::ReentrantMonitor mReentrantMonitor;
   
   nsWeakPtr mWindow;
--- a/security/manager/pki/src/nsFormSigningDialog.cpp
+++ b/security/manager/pki/src/nsFormSigningDialog.cpp
@@ -62,17 +62,17 @@ nsFormSigningDialog::ConfirmSignText(nsI
                                      const PRUnichar **aCertNickList,
                                      const PRUnichar **aCertDetailsList,
                                      PRUint32 aCount, PRInt32 *aSelectedIndex,
                                      nsAString &aPassword, PRBool *aCanceled) 
 {
   *aCanceled = PR_TRUE;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(aContext);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(aContext);
 
   nsresult rv;
   nsCOMPtr<nsIDialogParamBlock> block =
     do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   block->SetNumberStrings(3 + aCount * 2);
 
--- a/security/manager/pki/src/nsNSSDialogHelper.cpp
+++ b/security/manager/pki/src/nsNSSDialogHelper.cpp
@@ -46,36 +46,30 @@
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 
 static const char kOpenDialogParam[] = "centerscreen,chrome,modal,titlebar";
 static const char kOpenWindowParam[] = "centerscreen,chrome,titlebar";
 
 nsresult
 nsNSSDialogHelper::openDialog(
-    nsIDOMWindowInternal *window,
+    nsIDOMWindow *window,
     const char *url,
     nsISupports *params,
     PRBool modal)
 {
   nsresult rv;
   nsCOMPtr<nsIWindowWatcher> windowWatcher = 
            do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
   if (NS_FAILED(rv)) return rv;
 
-  nsIDOMWindowInternal *parent = window;
+  nsCOMPtr<nsIDOMWindow> parent = window;
 
-  nsCOMPtr<nsIDOMWindowInternal> activeParent;
   if (!parent) {
-    nsCOMPtr<nsIDOMWindow> active;
-    windowWatcher->GetActiveWindow(getter_AddRefs(active));
-    if (active) {
-      active->QueryInterface(NS_GET_IID(nsIDOMWindowInternal), getter_AddRefs(activeParent));
-      parent = activeParent;
-    }
+    windowWatcher->GetActiveWindow(getter_AddRefs(parent));
   }
 
   nsCOMPtr<nsIDOMWindow> newWindow;
   rv = windowWatcher->OpenWindow(parent,
                                  url,
                                  "_blank",
                                  modal
                                  ? kOpenDialogParam
--- a/security/manager/pki/src/nsNSSDialogHelper.h
+++ b/security/manager/pki/src/nsNSSDialogHelper.h
@@ -33,28 +33,28 @@
  * 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 "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 
 /**
  * Common class that uses the window watcher service to open a
  * standard dialog, with or without a parent context. The params
  * parameter can be an nsISupportsArray so any number of additional
  * arguments can be used.
  */
 class nsNSSDialogHelper
 {
 public:
   //The params is going to be either a nsIPKIParamBlock or
   //nsIDialogParamBlock
   static nsresult openDialog(
-                  nsIDOMWindowInternal *window,
+                  nsIDOMWindow *window,
                   const char *url,
                   nsISupports *params,
                   PRBool modal = PR_TRUE);
 };
 
--- a/security/manager/pki/src/nsNSSDialogs.cpp
+++ b/security/manager/pki/src/nsNSSDialogs.cpp
@@ -42,17 +42,17 @@
 /*
  * Dialog services for PIP.
  */
 #include "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsIPrompt.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIDialogParamBlock.h"
 #include "nsIComponentManager.h"
 #include "nsIServiceManager.h"
 #include "nsIStringBundle.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIX509Cert.h"
 #include "nsIX509CertDB.h"
@@ -108,17 +108,17 @@ nsresult
 nsNSSDialogs::SetPassword(nsIInterfaceRequestor *ctx,
                           const PRUnichar *tokenName, PRBool* _canceled)
 {
   nsresult rv;
 
   *_canceled = PR_FALSE;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
 
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
 
   // void ChangePassword(in wstring tokenName, out int status);
   rv = block->SetString(1, tokenName);
   if (NS_FAILED(rv)) return rv;
@@ -143,17 +143,17 @@ nsresult
 nsNSSDialogs::GetPassword(nsIInterfaceRequestor *ctx,
                           const PRUnichar *tokenName, 
                           PRUnichar **_password,
                           PRBool* _canceled)
 {
   nsresult rv;
   *_canceled = PR_FALSE;
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
   nsCOMPtr<nsIDialogParamBlock> block = 
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
   // Set the token name in the window
   rv = block->SetString(1, tokenName);
   if (NS_FAILED(rv)) return rv;
   // open up the window
   rv = nsNSSDialogHelper::openDialog(parent,
@@ -199,29 +199,29 @@ nsNSSDialogs::ConfirmDownloadCACert(nsII
                                     PRUint32 *_trust,
                                     PRBool *_retval)
 {
   nsresult rv;
 
   *_retval = PR_TRUE;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
 
   nsCOMPtr<nsIPKIParamBlock> block =
            do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID);
   if (!block)
     return NS_ERROR_FAILURE;
 
   rv = block->SetISupportAtIndex(1, cert);
   if (NS_FAILED(rv))
     return rv;
 
   rv = nsNSSDialogHelper::openDialog(parent, 
-                                   "chrome://pippki/content/downloadcert.xul",
+                                     "chrome://pippki/content/downloadcert.xul",
                                      block);
   if (NS_FAILED(rv)) return rv;
 
   PRInt32 status;
   PRInt32 ssl, email, objsign;
 
   nsCOMPtr<nsIDialogParamBlock> dlgParamBlock = do_QueryInterface(block);
   
@@ -246,17 +246,17 @@ nsNSSDialogs::ConfirmDownloadCACert(nsII
 
 
 NS_IMETHODIMP 
 nsNSSDialogs::NotifyCACertExists(nsIInterfaceRequestor *ctx)
 {
   nsresult rv;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
 
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
 
   
   rv = nsNSSDialogHelper::openDialog(parent, 
                                      "chrome://pippki/content/cacertexists.xul",
@@ -270,17 +270,17 @@ NS_IMETHODIMP
 nsNSSDialogs::ChooseCertificate(nsIInterfaceRequestor *ctx, const PRUnichar *cn, const PRUnichar *organization, const PRUnichar *issuer, const PRUnichar **certNickList, const PRUnichar **certDetailsList, PRUint32 count, PRInt32 *selectedIndex, PRBool *canceled) 
 {
   nsresult rv;
   PRUint32 i;
 
   *canceled = PR_FALSE;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
 
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
 
   block->SetNumberStrings(4+count*2);
 
   rv = block->SetString(0, cn);
@@ -341,17 +341,17 @@ nsNSSDialogs::PickCertificate(nsIInterfa
                               PRBool *canceled) 
 {
   nsresult rv;
   PRUint32 i;
 
   *canceled = PR_FALSE;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
 
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
 
   block->SetNumberStrings(1+count*2);
 
   for (i = 0; i < count; i++) {
@@ -391,17 +391,17 @@ nsNSSDialogs::PickCertificate(nsIInterfa
 NS_IMETHODIMP 
 nsNSSDialogs::SetPKCS12FilePassword(nsIInterfaceRequestor *ctx, 
                                     nsAString &_password,
                                     PRBool *_retval)
 {
   nsresult rv;
   *_retval = PR_TRUE;
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
   // open up the window
   rv = nsNSSDialogHelper::openDialog(parent,
                                   "chrome://pippki/content/setp12password.xul",
                                   block);
   if (NS_FAILED(rv)) return rv;
@@ -425,17 +425,17 @@ nsNSSDialogs::SetPKCS12FilePassword(nsII
 NS_IMETHODIMP 
 nsNSSDialogs::GetPKCS12FilePassword(nsIInterfaceRequestor *ctx, 
                                     nsAString &_password,
                                     PRBool *_retval)
 {
   nsresult rv;
   *_retval = PR_TRUE;
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
   // open up the window
   rv = nsNSSDialogHelper::openDialog(parent,
                                   "chrome://pippki/content/getp12password.xul",
                                   block);
   if (NS_FAILED(rv)) return rv;
@@ -468,48 +468,48 @@ nsNSSDialogs::ViewCert(nsIInterfaceReque
   if (!block)
     return NS_ERROR_FAILURE;
 
   rv = block->SetISupportAtIndex(1, cert);
   if (NS_FAILED(rv))
     return rv;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(ctx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);
 
   rv = nsNSSDialogHelper::openDialog(parent,
                                      "chrome://pippki/content/certViewer.xul",
                                      block,
                                      PR_FALSE);
   return rv;
 }
 
 NS_IMETHODIMP
 nsNSSDialogs::DisplayGeneratingKeypairInfo(nsIInterfaceRequestor *aCtx, nsIKeygenThread *runnable) 
 {
   nsresult rv;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(aCtx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(aCtx);
 
   rv = nsNSSDialogHelper::openDialog(parent,
                                      "chrome://pippki/content/createCertInfo.xul",
                                      runnable);
   return rv;
 }
 
 NS_IMETHODIMP
 nsNSSDialogs::ChooseToken(nsIInterfaceRequestor *aCtx, const PRUnichar **aTokenList, PRUint32 aCount, PRUnichar **aTokenChosen, PRBool *aCanceled) {
   nsresult rv;
   PRUint32 i;
 
   *aCanceled = PR_FALSE;
 
   // Get the parent window for the dialog
-  nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(aCtx);
+  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(aCtx);
 
   nsCOMPtr<nsIDialogParamBlock> block =
            do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
   if (!block) return NS_ERROR_FAILURE;
 
   block->SetNumberStrings(aCount);
 
   for (i = 0; i < aCount; i++) {
@@ -579,33 +579,25 @@ nsNSSDialogs::DisplayProtectedAuth(nsIIn
     // We cannot use nsNSSDialogHelper here. We cannot allow close widget
     // in the window because protected authentication is interruptible
     // from user interface and changing nsNSSDialogHelper's static variable
     // would not be thread-safe
     
     nsresult rv = NS_ERROR_FAILURE;
     
     // Get the parent window for the dialog
-    nsCOMPtr<nsIDOMWindowInternal> parent = do_GetInterface(aCtx);
+    nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(aCtx);
     
     nsCOMPtr<nsIWindowWatcher> windowWatcher = 
         do_GetService("@mozilla.org/embedcomp/window-watcher;1", &rv);
     if (NS_FAILED(rv))
         return rv;
     
-    nsCOMPtr<nsIDOMWindowInternal> activeParent;
-    if (!parent)
-    {
-        nsCOMPtr<nsIDOMWindow> active;
-        windowWatcher->GetActiveWindow(getter_AddRefs(active));
-        if (active)
-        {
-            active->QueryInterface(NS_GET_IID(nsIDOMWindowInternal), getter_AddRefs(activeParent));
-            parent = activeParent;
-        }
+    if (!parent) {
+        windowWatcher->GetActiveWindow(getter_AddRefs(parent));
     }
     
     nsCOMPtr<nsIDOMWindow> newWindow;
     rv = windowWatcher->OpenWindow(parent,
         "chrome://pippki/content/protectedAuth.xul",
         "_blank",
         "centerscreen,chrome,modal,titlebar,close=no",
         runnable,
--- a/security/manager/ssl/src/nsNSSComponent.cpp
+++ b/security/manager/ssl/src/nsNSSComponent.cpp
@@ -71,17 +71,16 @@
 #include "nsIPrefBranch.h"
 #include "nsIPrefBranch2.h"
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMWindowCollection.h"
-#include "nsIDOMWindowInternal.h"
 #include "nsIDOMSmartCardEvent.h"
 #include "nsIDOMCrypto.h"
 #include "nsThreadUtils.h"
 #include "nsAutoPtr.h"
 #include "nsCRT.h"
 #include "nsCRLInfo.h"
 #include "nsCertOverrideService.h"
 
@@ -543,23 +542,23 @@ nsNSSComponent::DispatchEventToWindow(ns
       DispatchEventToWindow(childWin, eventType, tokenName);
     }
   }
 
   // check if we've enabled smart card events on this window
   // NOTE: it's not an error to say that we aren't going to dispatch
   // the event.
   {
-    nsCOMPtr<nsIDOMWindowInternal> intWindow = do_QueryInterface(domWin);
-    if (!intWindow) {
+    nsCOMPtr<nsIDOMWindow> domWindow = domWin;
+    if (!domWindow) {
       return NS_OK; // nope, it's not an internal window
     }
 
     nsCOMPtr<nsIDOMCrypto> crypto;
-    intWindow->GetCrypto(getter_AddRefs(crypto));
+    domWindow->GetCrypto(getter_AddRefs(crypto));
     if (!crypto) {
       return NS_OK; // nope, it doesn't have a crypto property
     }
 
     PRBool boolrv;
     crypto->GetEnableSmartCardEvents(&boolrv);
     if (!boolrv) {
       return NS_OK; // nope, it's not enabled.
--- a/services/sync/modules/constants.js
+++ b/services/sync/modules/constants.js
@@ -194,17 +194,16 @@ JPAKE_ERROR_INVALID:                   "
 JPAKE_ERROR_NODATA:                    "jpake.error.nodata",
 JPAKE_ERROR_KEYMISMATCH:               "jpake.error.keymismatch",
 JPAKE_ERROR_WRONGMESSAGE:              "jpake.error.wrongmessage",
 JPAKE_ERROR_USERABORT:                 "jpake.error.userabort",
 
 // Ways that a sync can be disabled (messages only to be printed in debug log)
 kSyncMasterPasswordLocked:             "User elected to leave Master Password locked",
 kSyncWeaveDisabled:                    "Weave is disabled",
-kSyncNotLoggedIn:                      "User is not logged in",
 kSyncNetworkOffline:                   "Network is offline",
 kSyncBackoffNotMet:                    "Trying to sync before the server said it's okay",
 kFirstSyncChoiceNotMade:               "User has not selected an action for first sync",
 
 // Application IDs
 FIREFOX_ID:                            "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}",
 FENNEC_ID:                             "{a23983c0-fd0e-11dc-95ff-0800200c9a66}",
 SEAMONKEY_ID:                          "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}",
--- a/services/sync/modules/jpakeclient.js
+++ b/services/sync/modules/jpakeclient.js
@@ -36,22 +36,23 @@
  * ***** END LICENSE BLOCK ***** */
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cr = Components.results;
 const Cu = Components.utils;
 
 Cu.import("resource://services-sync/log4moz.js");
-Cu.import("resource://services-sync/resource.js");
+Cu.import("resource://services-sync/rest.js");
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/util.js");
 
 const EXPORTED_SYMBOLS = ["JPAKEClient"];
 
+const REQUEST_TIMEOUT         = 60; // 1 minute
 const JPAKE_SIGNERID_SENDER   = "sender";
 const JPAKE_SIGNERID_RECEIVER = "receiver";
 const JPAKE_LENGTH_SECRET     = 8;
 const JPAKE_LENGTH_CLIENTID   = 256;
 const JPAKE_VERIFY_VALUE      = "0123456789ABCDEF";
 
 
 /*
@@ -131,17 +132,16 @@ function JPAKEClient(observer) {
   this._serverUrl = Svc.Prefs.get("jpake.serverURL");
   this._pollInterval = Svc.Prefs.get("jpake.pollInterval");
   this._maxTries = Svc.Prefs.get("jpake.maxTries");
   if (this._serverUrl.slice(-1) != "/")
     this._serverUrl += "/";
 
   this._jpake = Cc["@mozilla.org/services-crypto/sync-jpake;1"]
                   .createInstance(Ci.nsISyncJPAKE);
-  this._auth = new NoOpAuthenticator();
 
   this._setClientID();
 }
 JPAKEClient.prototype = {
 
   _chain: Utils.asyncChain,
 
   /*
@@ -235,44 +235,48 @@ JPAKEClient.prototype = {
     const key = "23456789abcdefghijkmnpqrstuvwxyz";
     let rng = Cc["@mozilla.org/security/random-generator;1"]
                 .createInstance(Ci.nsIRandomGenerator);
     let bytes = rng.generateRandomBytes(JPAKE_LENGTH_SECRET);
     return [key[Math.floor(byte * key.length / 256)]
             for each (byte in bytes)].join("");
   },
 
+  _newRequest: function _newRequest(uri) {
+    let request = new RESTRequest(uri);
+    request.setHeader("X-KeyExchange-Id", this._clientID);
+    request.timeout = REQUEST_TIMEOUT;
+    return request;
+  },
+
   /*
    * Steps of J-PAKE procedure
    */
 
   _getChannel: function _getChannel(callback) {
     this._log.trace("Requesting channel.");
-    let resource = new AsyncResource(this._serverUrl + "new_channel");
-    resource.authenticator = this._auth;
-    resource.setHeader("X-KeyExchange-Id", this._clientID);
-    resource.get(Utils.bind2(this, function handleChannel(error, response) {
+    let request = this._newRequest(this._serverUrl + "new_channel");
+    request.get(Utils.bind2(this, function handleChannel(error) {
       if (this._finished)
         return;
 
       if (error) {
         this._log.error("Error acquiring channel ID. " + error);
         this.abort(JPAKE_ERROR_CHANNEL);
         return;
       }
-      if (response.status != 200) {
+      if (request.response.status != 200) {
         this._log.error("Error acquiring channel ID. Server responded with HTTP "
-                        + response.status);
+                        + request.response.status);
         this.abort(JPAKE_ERROR_CHANNEL);
         return;
       }
 
-      let channel;
       try {
-        this._channel = response.obj;
+        this._channel = JSON.parse(request.response.body);
       } catch (ex) {
         this._log.error("Server responded with invalid JSON.");
         this.abort(JPAKE_ERROR_CHANNEL);
         return;
       }
       this._log.debug("Using channel " + this._channel);
       this._channelUrl = this._serverUrl + this._channel;
 
@@ -282,113 +286,109 @@ JPAKEClient.prototype = {
                        this, "_timer_displayPIN");
       callback();
     }));
   },
 
   // Generic handler for uploading data.
   _putStep: function _putStep(callback) {
     this._log.trace("Uploading message " + this._outgoing.type);
-    let resource = new AsyncResource(this._channelUrl);
-    resource.authenticator = this._auth;
-    resource.setHeader("X-KeyExchange-Id", this._clientID);
-    resource.put(this._outgoing, Utils.bind2(this, function (error, response) {
+    let request = this._newRequest(this._channelUrl);
+    request.put(this._outgoing, Utils.bind2(this, function (error) {
       if (this._finished)
         return;
 
       if (error) {
         this._log.error("Error uploading data. " + error);
         this.abort(JPAKE_ERROR_NETWORK);
         return;
       }
-      if (response.status != 200) {
+      if (request.response.status != 200) {
         this._log.error("Could not upload data. Server responded with HTTP "
-                        + response.status);
+                        + request.response.status);
         this.abort(JPAKE_ERROR_SERVER);
         return;
       }
       // There's no point in returning early here since the next step will
       // always be a GET so let's pause for twice the poll interval.
-      this._etag = response.headers["etag"];
+      this._etag = request.response.headers["etag"];
       Utils.namedTimer(function () { callback(); }, this._pollInterval * 2,
                        this, "_pollTimer");
     }));
   },
 
   // Generic handler for polling for and retrieving data.
   _pollTries: 0,
   _getStep: function _getStep(callback) {
     this._log.trace("Retrieving next message.");
-    let resource = new AsyncResource(this._channelUrl);
-    resource.authenticator = this._auth;
-    resource.setHeader("X-KeyExchange-Id", this._clientID);
-    if (this._etag)
-      resource.setHeader("If-None-Match", this._etag);
+    let request = this._newRequest(this._channelUrl);
+    if (this._etag) {
+      request.setHeader("If-None-Match", this._etag);
+    }
 
-    resource.get(Utils.bind2(this, function (error, response) {
+    request.get(Utils.bind2(this, function (error) {
       if (this._finished)
         return;
 
       if (error) {
         this._log.error("Error fetching data. " + error);
         this.abort(JPAKE_ERROR_NETWORK);
         return;
       }
 
-      if (response.status == 304) {
+      if (request.response.status == 304) {
         this._log.trace("Channel hasn't been updated yet. Will try again later.");
         if (this._pollTries >= this._maxTries) {
           this._log.error("Tried for " + this._pollTries + " times, aborting.");
           this.abort(JPAKE_ERROR_TIMEOUT);
           return;
         }
         this._pollTries += 1;
         Utils.namedTimer(function() { this._getStep(callback); },
                          this._pollInterval, this, "_pollTimer");
         return;
       }
       this._pollTries = 0;
 
-      if (response.status == 404) {
+      if (request.response.status == 404) {
         this._log.error("No data found in the channel.");
         this.abort(JPAKE_ERROR_NODATA);
         return;
       }
-      if (response.status != 200) {
+      if (request.response.status != 200) {
         this._log.error("Could not retrieve data. Server responded with HTTP "
-                        + response.status);
+                        + request.response.status);
         this.abort(JPAKE_ERROR_SERVER);
         return;
       }
 
       try {
-        this._incoming = response.obj;
+        this._incoming = JSON.parse(request.response.body);
       } catch (ex) {
         this._log.error("Server responded with invalid JSON.");
         this.abort(JPAKE_ERROR_INVALID);
         return;
       }
       this._log.trace("Fetched message " + this._incoming.type);
       callback();
     }));
   },
 
   _reportFailure: function _reportFailure(reason, callback) {
     this._log.debug("Reporting failure to server.");
-    let resource = new AsyncResource(this._serverUrl + "report");
-    resource.authenticator = this._auth;
-    resource.setHeader("X-KeyExchange-Id", this._clientID);
-    resource.setHeader("X-KeyExchange-Cid", this._channel);
-    resource.setHeader("X-KeyExchange-Log", reason);
-    resource.post("", Utils.bind2(this, function (error, response) {
-      if (error)
+    let request = this._newRequest(this._serverUrl + "report");
+    request.setHeader("X-KeyExchange-Cid", this._channel);
+    request.setHeader("X-KeyExchange-Log", reason);
+    request.post("", Utils.bind2(this, function (error) {
+      if (error) {
         this._log.warn("Report failed: " + error);
-      else if (response.status != 200)
+      } else if (request.response.status != 200) {
         this._log.warn("Report failed. Server responded with HTTP "
-                       + response.status);
+                       + request.response.status);
+      }
 
       // Do not block on errors, we're done or aborted by now anyway.
       callback();
     }));
   },
 
   _computeStepOne: function _computeStepOne(callback) {
     this._log.trace("Computing round 1.");
--- a/services/sync/modules/policies.js
+++ b/services/sync/modules/policies.js
@@ -244,26 +244,18 @@ let SyncScheduler = {
     this.adjustSyncInterval();
   },
 
   /**
    * Check if we should be syncing and schedule the next sync, if it's not scheduled
    */
   checkSyncStatus: function checkSyncStatus() {
     // Should we be syncing now, if not, cancel any sync timers and return
-    // if we're in backoff, we'll schedule the next sync
-    let ignore = [kSyncBackoffNotMet];
-
-    // We're ready to sync even if we're not logged in... so long as the
-    // master password isn't locked.
-    if (Utils.mpLocked()) {
-      ignore.push(kSyncNotLoggedIn);
-      ignore.push(kSyncMasterPasswordLocked);
-    }
-
+    // if we're in backoff, we'll schedule the next sync.
+    let ignore = [kSyncBackoffNotMet, kSyncMasterPasswordLocked];
     let skip = Weave.Service._checkSync(ignore);
     this._log.trace("_checkSync returned \"" + skip + "\".");
     if (skip) {
       this.clearSyncTriggers();
       return;
     }
 
     // Only set the wait time to 0 if we need to sync right away
new file mode 100644
--- /dev/null
+++ b/services/sync/modules/rest.js
@@ -0,0 +1,633 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Firefox Sync.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Philipp von Weitershausen <philipp@weitershausen.de>
+ *   Richard Newman <rnewman@mozilla.com>
+ *   Dan Mills <thunder@mozilla.com>
+ *   Anant Narayanan <anant@kix.in>
+ *
+ * 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 ***** */
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.import("resource://services-sync/log4moz.js");
+Cu.import("resource://services-sync/util.js");
+Cu.import("resource://services-sync/identity.js");
+Cu.import("resource://services-sync/constants.js");
+
+const EXPORTED_SYMBOLS = ["RESTRequest", "SyncStorageRequest"];
+
+const STORAGE_REQUEST_TIMEOUT = 5 * 60; // 5 minutes
+
+/**
+ * Single use HTTP requests to RESTish resources.
+ * 
+ * @param uri
+ *        URI for the request. This can be an nsIURI object or a string
+ *        that can be used to create one. An exception will be thrown if
+ *        the string is not a valid URI.
+ *
+ * Examples:
+ *
+ * (1) Quick GET request:
+ *
+ *   new RESTRequest("http://server/rest/resource").get(function (error) {
+ *     if (error) {
+ *       // Deal with a network error.
+ *       processNetworkErrorCode(error.result);
+ *       return;
+ *     }
+ *     if (!this.response.success) {
+
+ *  *       // Bail out if we're not getting an HTTP 2xx code.
+ *       processHTTPError(this.response.status);
+ *       return;
+ *     }
+ *     processData(this.response.body);
+ *   });
+ *
+ * (2) Quick PUT request (non-string data is automatically JSONified)
+ *
+ *   new RESTRequest("http://server/rest/resource").put(data, function (error) {
+ *     ...
+ *   });
+ *
+ * (3) Streaming GET
+ *
+ *   let request = new RESTRequest("http://server/rest/resource");
+ *   request.setHeader("Accept", "application/newlines");
+ *   request.onComplete = function (error) {
+ *     if (error) {
+ *       // Deal with a network error.
+ *       processNetworkErrorCode(error.result);
+ *       return;
+ *     }
+ *     callbackAfterRequestHasCompleted()
+ *   });
+ *   request.onProgress = function () {
+ *     if (!this.response.success) {
+ *       // Bail out if we're not getting an HTTP 2xx code.
+ *       return;
+ *     }
+ *     // Process body data and reset it so we don't process the same data twice.
+ *     processIncrementalData(this.response.body);
+ *     this.response.body = "";
+ *   });
+ *   request.get();
+ */
+function RESTRequest(uri) {
+  this.status = this.NOT_SENT;
+
+  // If we don't have an nsIURI object yet, make one. This will throw if
+  // 'uri' isn't a valid URI string.
+  if (!(uri instanceof Ci.nsIURI)) {
+    uri = Services.io.newURI(uri, null, null);
+  }
+  this.uri = uri;
+
+  this._headers = {};
+  this._log = Log4Moz.repository.getLogger(this._logName);
+  this._log.level =
+    Log4Moz.Level[Svc.Prefs.get("log.logger.network.resources")];
+}
+RESTRequest.prototype = {
+
+  _logName: "Sync.RESTRequest",
+
+  QueryInterface: XPCOMUtils.generateQI([
+    Ci.nsIBadCertListener2,
+    Ci.nsIInterfaceRequestor
+  ]),
+
+  /*** Public API: ***/
+
+  /**
+   * URI for the request (an nsIURI object).
+   */
+  uri: null,
+
+  /**
+   * HTTP method (e.g. "GET")
+   */
+  method: null,
+
+  /**
+   * RESTResponse object
+   */
+  response: null,
+
+  /**
+   * nsIRequest load flags. Don't do any caching by default.
+   */
+  loadFlags: Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_CACHING,
+
+  /**
+   * nsIHttpChannel
+   */
+  channel: null,
+
+  /**
+   * Flag to indicate the status of the request.
+   *
+   * One of NOT_SENT, SENT, IN_PROGRESS, COMPLETED, ABORTED.
+   */
+  status: null,
+
+  NOT_SENT:    0,
+  SENT:        1,
+  IN_PROGRESS: 2,
+  COMPLETED:   4,
+  ABORTED:     8,
+
+  /**
+   * Request timeout (in seconds, though decimal values can be used for
+   * up to millisecond granularity.)
+   *
+   * 0 for no timeout.
+   */
+  timeout: null,
+
+  /**
+   * Called when the request has been completed, including failures and
+   * timeouts.
+   * 
+   * @param error
+   *        Error that occurred while making the request, null if there
+   *        was no error.
+   */
+  onComplete: function onComplete(error) {
+  },
+
+  /**
+   * Called whenever data is being received on the channel. If this throws an
+   * exception, the request is aborted and the exception is passed as the
+   * error to onComplete().
+   */
+  onProgress: function onProgress() {
+  },
+
+  /**
+   * Set a request header.
+   */
+  setHeader: function setHeader(name, value) {
+    this._headers[name.toLowerCase()] = value;
+  },
+
+  /**
+   * Perform an HTTP GET.
+   *
+   * @param onComplete
+   *        Short-circuit way to set the 'onComplete' method. Optional.
+   * @param onProgress
+   *        Short-circuit way to set the 'onProgress' method. Optional.
+   *
+   * @return the request object.
+   */
+  get: function get(onComplete, onProgress) {
+    return this.dispatch("GET", null, onComplete, onProgress);
+  },
+
+  /**
+   * Perform an HTTP PUT.
+   *
+   * @param data
+   *        Data to be used as the request body. If this isn't a string
+   *        it will be JSONified automatically.
+   * @param onComplete
+   *        Short-circuit way to set the 'onComplete' method. Optional.
+   * @param onProgress
+   *        Short-circuit way to set the 'onProgress' method. Optional.
+   *
+   * @return the request object.
+   */
+  put: function put(data, onComplete, onProgress) {
+    return this.dispatch("PUT", data, onComplete, onProgress);
+  },
+
+  /**
+   * Perform an HTTP POST.
+   *
+   * @param data
+   *        Data to be used as the request body. If this isn't a string
+   *        it will be JSONified automatically.
+   * @param onComplete
+   *        Short-circuit way to set the 'onComplete' method. Optional.
+   * @param onProgress
+   *        Short-circuit way to set the 'onProgress' method. Optional.
+   *
+   * @return the request object.
+   */
+  post: function post(data, onComplete, onProgress) {
+    return this.dispatch("POST", data, onComplete, onProgress);
+  },
+
+  /**
+   * Perform an HTTP DELETE.
+   *
+   * @param onComplete
+   *        Short-circuit way to set the 'onComplete' method. Optional.
+   * @param onProgress
+   *        Short-circuit way to set the 'onProgress' method. Optional.
+   *
+   * @return the request object.
+   */
+  delete: function delete_(onComplete, onProgress) {
+    return this.dispatch("DELETE", null, onComplete, onProgress);
+  },
+
+  /**
+   * Abort an active request.
+   */
+  abort: function abort() {
+    if (this.status != this.SENT && this.status != this.IN_PROGRESS) {
+      throw "Can only abort a request that has been sent.";
+    }
+
+    this.status = this.ABORTED;
+    this.channel.cancel(Cr.NS_BINDING_ABORTED);
+
+    if (this.timeoutTimer) {
+      // Clear the abort timer now that the channel is done.
+      this.timeoutTimer.clear();
+    }
+  },
+
+  /*** Implementation stuff ***/
+
+  dispatch: function dispatch(method, data, onComplete, onProgress) {
+    if (this.status != this.NOT_SENT) {
+      throw "Request has already been sent!";
+    }
+
+    this.method = method;
+    if (onComplete) {
+      this.onComplete = onComplete;
+    }
+    if (onProgress) {
+      this.onProgress = onProgress;
+    }
+
+    // Create and initialize HTTP channel.
+    let channel = Services.io.newChannelFromURI(this.uri, null, null)
+                          .QueryInterface(Ci.nsIRequest)
+                          .QueryInterface(Ci.nsIHttpChannel);
+    this.channel = channel;
+    channel.loadFlags |= this.loadFlags;
+    channel.notificationCallbacks = this;
+
+    // Set request headers.
+    let headers = this._headers;
+    for (let key in headers) {
+      if (key == 'authorization') {
+        this._log.trace("HTTP Header " + key + ": ***** (suppressed)");
+      } else {
+        this._log.trace("HTTP Header " + key + ": " + headers[key]);
+      }
+      channel.setRequestHeader(key, headers[key], false);
+    }
+
+    // Set HTTP request body.
+    if (method == "PUT" || method == "POST") {
+      // Convert non-string bodies into JSON.
+      if (typeof data != "string") {
+        data = JSON.stringify(data);
+      }
+
+      this._log.debug(method + " Length: " + data.length);
+      if (this._log.level <= Log4Moz.Level.Trace) {
+        this._log.trace(method + " Body: " + data);
+      }
+
+      let stream = Cc["@mozilla.org/io/string-input-stream;1"]
+                     .createInstance(Ci.nsIStringInputStream);
+      stream.setData(data, data.length);
+
+      let type = headers["content-type"] || "text/plain";
+      channel.QueryInterface(Ci.nsIUploadChannel);
+      channel.setUploadStream(stream, type, data.length);
+    }
+    // We must set this after setting the upload stream, otherwise it
+    // will always be 'PUT'. Yeah, I know.
+    channel.requestMethod = method;
+
+    // Blast off!
+    channel.asyncOpen(this, null);
+    this.status = this.SENT;
+    this.delayTimeout();
+    return this;
+  },
+
+  /**
+   * Create or push back the abort timer that kills this request.
+   */
+  delayTimeout: function delayTimeout() {
+    if (this.timeout) {
+      Utils.namedTimer(this.abortTimeout, this.timeout * 1000, this,
+                       "timeoutTimer");
+    }
+  },
+
+  /**
+   * Abort the request based on a timeout.
+   */
+  abortTimeout: function abortTimeout() {
+    this.abort();
+    let error = Components.Exception("Aborting due to channel inactivity.",
+                                     Cr.NS_ERROR_NET_TIMEOUT);
+    this.onComplete(error);
+  },
+
+  /*** nsIStreamListener ***/
+
+  onStartRequest: function onStartRequest(channel) {
+    if (this.status == this.ABORTED) {
+      this._log.trace("Not proceeding with onStartRequest, request was aborted.");
+      return;
+    }
+    this.status = this.IN_PROGRESS;
+
+    channel.QueryInterface(Ci.nsIHttpChannel);
+    this._log.trace("onStartRequest: " + channel.requestMethod + " " +
+                    channel.URI.spec);
+
+    // Create a response object and fill it with some data.
+    let response = this.response = new RESTResponse();
+    response.request = this;
+    response.body = "";
+
+    // Define this here so that we don't have make a new one each time
+    // onDataAvailable() gets called.
+    this._inputStream = Cc["@mozilla.org/scriptableinputstream;1"]
+                          .createInstance(Ci.nsIScriptableInputStream);
+
+    this.delayTimeout();
+  },
+
+  onStopRequest: function onStopRequest(channel, context, statusCode) {
+    if (this.timeoutTimer) {
+      // Clear the abort timer now that the channel is done.
+      this.timeoutTimer.clear();
+    }
+
+    // We don't want to do anything for a request that's already been aborted.
+    if (this.status == this.ABORTED) {
+      this._log.trace("Not proceeding with onStopRequest, request was aborted.");
+      return;
+    }
+    this.status = this.COMPLETED;
+
+    let uri = channel && channel.URI && channel.URI.spec || "<unknown>";
+    this._log.trace("Channel for " + channel.requestMethod + " " + uri +
+                    " returned status code " + statusCode);
+
+    // Throw the failure code and stop execution.  Use Components.Exception()
+    // instead of Error() so the exception is QI-able and can be passed across
+    // XPCOM borders while preserving the status code.
+    if (!Components.isSuccessCode(statusCode)) {
+      let message = Components.Exception("", statusCode).name;
+      let error = Components.Exception(message, statusCode);
+      this.onComplete(error);
+      this.onComplete = this.onProgress = null;
+      return;
+    }
+
+    this._log.debug(this.method + " " + uri + " " + this.response.status);
+
+    // Additionally give the full response body when Trace logging.
+    if (this._log.level <= Log4Moz.Level.Trace) {
+      this._log.trace(this.method + " body: " + this.response.body);
+    }
+
+    delete this._inputStream;
+
+    this.onComplete(null);
+    this.onComplete = this.onProgress = null;
+  },
+
+  onDataAvailable: function onDataAvailable(req, cb, stream, off, count) {
+    this._inputStream.init(stream);
+    try {
+      this.response.body += this._inputStream.read(count);
+    } catch (ex) {
+      this._log.warn("Exception thrown reading " + count +
+                     " bytes from the channel.");
+      this._log.debug(Utils.exceptionStr(ex));
+      throw ex;
+    }
+
+    try {
+      this.onProgress();
+    } catch (ex) {
+      this._log.warn("Got exception calling onProgress handler, aborting " +
+                     this.method + " " + req.URI.spec);
+      this._log.debug("Exception: " + Utils.exceptionStr(ex));
+      this.abort();
+      this.onComplete(ex);
+      this.onComplete = this.onProgress = null;
+      return;
+    }
+
+    this.delayTimeout();
+  },
+
+  /*** nsIInterfaceRequestor ***/
+
+  getInterface: function(aIID) {
+    return this.QueryInterface(aIID);
+  },
+
+  /*** nsIBadCertListener2 ***/
+
+  notifyCertProblem: function notifyCertProblem(socketInfo, sslStatus, targetHost) {
+    this._log.warn("Invalid HTTPS certificate encountered!");
+    // Suppress invalid HTTPS certificate warnings in the UI.
+    // (The request will still fail.)
+    return true;
+  }
+};
+
+
+/**
+ * Response object for a RESTRequest. This will be created automatically by
+ * the RESTRequest.
+ */
+function RESTResponse() {
+  this._log = Log4Moz.repository.getLogger(this._logName);
+  this._log.level =
+    Log4Moz.Level[Svc.Prefs.get("log.logger.network.resources")];
+}
+RESTResponse.prototype = {
+
+  _logName: "Sync.RESTResponse",
+
+  /**
+   * Corresponding REST request
+   */
+  request: null,
+
+  /**
+   * HTTP status code
+   */
+  get status() {
+    let status;
+    try {
+      let channel = this.request.channel.QueryInterface(Ci.nsIHttpChannel);
+      status = channel.responseStatus;
+    } catch (ex) {
+      this._log.debug("Caught exception fetching HTTP status code:" +
+                      Utils.exceptionStr(ex));
+      return null;
+    }
+    delete this.status;
+    return this.status = status;
+  },
+
+  /**
+   * Boolean flag that indicates whether the HTTP status code is 2xx or not.
+   */
+  get success() {
+    let success;
+    try {
+      let channel = this.request.channel.QueryInterface(Ci.nsIHttpChannel);
+      success = channel.requestSucceeded;
+    } catch (ex) {
+      this._log.debug("Caught exception fetching HTTP success flag:" +
+                      Utils.exceptionStr(ex));
+      return null;
+    }
+    delete this.success;
+    return this.success = success;
+  },
+
+  /**
+   * Object containing HTTP headers (keyed as lower case)
+   */
+  get headers() {
+    let headers = {};
+    try {
+      this._log.trace("Processing response headers.");
+      let channel = this.request.channel.QueryInterface(Ci.nsIHttpChannel);
+      channel.visitResponseHeaders(function (header, value) {
+        headers[header.toLowerCase()] = value;
+      });
+    } catch (ex) {
+      this._log.debug("Caught exception processing response headers:" +
+                      Utils.exceptionStr(ex));
+      return null;
+    }
+
+    delete this.headers;
+    return this.headers = headers;
+  },
+
+  /**
+   * HTTP body (string)
+   */
+  body: null
+
+};
+
+
+/**
+ * RESTRequest variant for use against a Sync storage server.
+ */
+function SyncStorageRequest(uri) {
+  RESTRequest.call(this, uri);
+}
+SyncStorageRequest.prototype = {
+
+  __proto__: RESTRequest.prototype,
+
+  _logName: "Sync.StorageRequest",
+
+  /**
+   * The string to use as the base User-Agent in Sync requests.
+   * These strings will look something like
+   * 
+   *   Firefox/4.0 FxSync/1.8.0.20100101.mobile
+   * 
+   * or
+   * 
+   *   Firefox Aurora/5.0a1 FxSync/1.9.0.20110409.desktop
+   */
+  userAgent:
+    Services.appinfo.name + "/" + Services.appinfo.version +  // Product.
+    " FxSync/" + WEAVE_VERSION + "." +                        // Sync.
+    Services.appinfo.appBuildID + ".",                        // Build.
+
+  /**
+   * Wait 5 minutes before killing a request.
+   */
+  timeout: STORAGE_REQUEST_TIMEOUT,
+
+  dispatch: function dispatch(method, data, onComplete, onProgress) {
+    // Compose a UA string fragment from the various available identifiers.
+    if (Svc.Prefs.get("sendVersionInfo", true)) {
+      let ua = this.userAgent + Svc.Prefs.get("client.type", "desktop");
+      this.setHeader("user-agent", ua);
+    }
+
+    // Set the BasicAuth header.
+    let id = ID.get("WeaveID");
+    if (id) {
+      let auth_header = "Basic " + btoa(id.username + ':' + id.passwordUTF8);
+      this.setHeader("authorization", auth_header);
+    } else {
+      this._log.debug("Couldn't set Authentication header: WeaveID not found.");
+    }
+
+    RESTRequest.prototype.dispatch.apply(this, arguments);
+  },
+
+  onStartRequest: function onStartRequest(channel) {
+    RESTRequest.prototype.onStartRequest.call(this, channel);
+
+    let headers = this.response.headers;
+    // Save the latest server timestamp when possible.
+    if (headers["x-weave-timestamp"]) {
+      SyncStorageRequest.serverTime = parseFloat(headers["x-weave-timestamp"]);
+    }
+
+    // This is a server-side safety valve to allow slowing down
+    // clients without hurting performance.
+    if (headers["x-weave-backoff"]) {
+      Svc.Obs.notify("weave:service:backoff:interval",
+                     parseInt(headers["x-weave-backoff"], 10));
+    }
+
+    if (this.response.success && headers["x-weave-quota-remaining"]) {
+      Svc.Obs.notify("weave:service:quota:remaining",
+                     parseInt(headers["x-weave-quota-remaining"], 10));
+    }
+  }
+};
--- a/services/sync/modules/service.js
+++ b/services/sync/modules/service.js
@@ -1046,44 +1046,24 @@ WeaveSvc.prototype = {
   */
   delayedAutoConnect: function delayedAutoConnect(delay) {
     if (this._checkSetup() == STATUS_OK) {
       Utils.namedTimer(this._autoConnect, delay * 1000, this, "_autoTimer");
     }
   },
 
   _autoConnect: function _autoConnect() {
-    let isLocked = Utils.mpLocked();
-    if (isLocked) {
-      // There's no reason to back off if we're locked: we'll just try to login
-      // during sync. Clear our timer, see if we should go ahead and sync, then
-      // just return.
-      this._log.trace("Autoconnect skipped: master password still locked.");
-
-      if (this._autoTimer)
-        this._autoTimer.clear();
-
-      SyncScheduler.checkSyncStatus();
-
-      return;
-    }
-
-    let reason = this._checkSync([kSyncNotLoggedIn, kFirstSyncChoiceNotMade]);
-
-    // Can't autoconnect if we're missing these values.
-    if (!reason) {
-      if (!this.username || !this.password || !this.passphrase)
-        return;
-
+    if (this._checkSetup() == STATUS_OK && !this._checkSync()) {
       Utils.nextTick(this.sync, this);
     }
 
     // Once _autoConnect is called we no longer need _autoTimer.
-    if (this._autoTimer)
+    if (this._autoTimer) {
       this._autoTimer.clear();
+    }
   },
 
   persistLogin: function persistLogin() {
     // Canceled master password prompt can prevent these from succeeding.
     try {
       ID.get("WeaveID").persist();
       ID.get("WeaveCryptoID").persist();
     }
@@ -1387,18 +1367,16 @@ WeaveSvc.prototype = {
       reason = kSyncWeaveDisabled;
     else if (Services.io.offline)
       reason = kSyncNetworkOffline;
     else if (Status.minimumNextSync > Date.now())
       reason = kSyncBackoffNotMet;
     else if ((Status.login == MASTER_PASSWORD_LOCKED) &&
              Utils.mpLocked())
       reason = kSyncMasterPasswordLocked;
-    else if (!this._loggedIn)
-      reason = kSyncNotLoggedIn;
     else if (Svc.Prefs.get("firstSync") == "notReady")
       reason = kFirstSyncChoiceNotMade;
 
     if (ignore && ignore.indexOf(reason) != -1)
       return "";
 
     return reason;
   },
--- a/services/sync/tests/Makefile.in
+++ b/services/sync/tests/Makefile.in
@@ -42,11 +42,8 @@ VPATH     = @srcdir@
 relativesrcdir = services/sync/tests
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE = test_services_sync
 XPCSHELL_TESTS = unit
 
 include $(topsrcdir)/config/rules.mk
-
-libs:: unit/head_appinfo.js.in
-	$(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) $(XULPPFLAGS) $^ > $(DEPTH)/_tests/xpcshell/$(relativesrcdir)/unit/head_appinfo.js
rename from services/sync/tests/unit/head_appinfo.js.in
rename to services/sync/tests/unit/head_appinfo.js
--- a/services/sync/tests/unit/head_appinfo.js.in
+++ b/services/sync/tests/unit/head_appinfo.js
@@ -50,31 +50,8 @@ function addResourceAlias() {
                           .QueryInterface(Ci.nsIResProtocolHandler);
   let uri;
   uri = Services.io.newURI("resource:///modules/services-sync/", null, null);
   resProt.setSubstitution("services-sync", uri);
   uri = Services.io.newURI("resource:///modules/services-crypto/", null, null);
   resProt.setSubstitution("services-crypto", uri);
 }
 addResourceAlias();
-
-
-// Some tests hang on OSX debug builds. See bug 604565.
-let DISABLE_TESTS_BUG_604565 = false;
-#ifdef XP_MACOSX
-#ifdef DEBUG
-DISABLE_TESTS_BUG_604565 = true;
-#endif
-#endif
-
-// test_jpakeclient.js produces random failures on Windows 7
-let DISABLE_TESTS_BUG_618233 = false;
-#ifdef XP_WIN
-DISABLE_TESTS_BUG_618233 = true;
-#endif
-
-// test_service_login.js persistently fails on Windows opt builds
-let DISABLE_TESTS_BUG_664090 = false;
-#ifdef XP_WIN
-#ifndef DEBUG
-DISABLE_TESTS_BUG_664090 = true;
-#endif
-#endif
--- a/services/sync/tests/unit/head_helpers.js
+++ b/services/sync/tests/unit/head_helpers.js
@@ -203,25 +203,16 @@ function encryptPayload(cleartext) {
 }
 
 function generateNewKeys(collections) {
   let wbo = CollectionKeys.generateNewKeysWBO(collections);
   let modified = new_timestamp();
   CollectionKeys.setContents(wbo.cleartext, modified);
 }
 
-function basic_auth_header(user, password) {
-  return "Basic " + btoa(user + ":" + Utils.encodeUTF8(password));
-}
-
-function basic_auth_matches(req, user, password) {
-  return req.hasHeader("Authorization") &&
-         (req.getHeader("Authorization") == basic_auth_header(user, password));
-}
-
 function do_check_throws(aFunc, aResult, aStack)
 {
   if (!aStack) {
     try {
       // We might not have a 'Components' object.
       aStack = Components.stack.caller;
     } catch (e) {}
   }
--- a/services/sync/tests/unit/head_http_server.js
+++ b/services/sync/tests/unit/head_http_server.js
@@ -10,22 +10,37 @@ function httpd_setup (handlers) {
   for (let path in handlers) {
     server.registerPathHandler(path, handlers[path]);
   }
   server.start(8080);
   return server;
 }
 
 function httpd_handler(statusCode, status, body) {
-  return function(request, response) {
+  return function handler(request, response) {
+    // Allow test functions to inspect the request.
+    request.body = readBytesFromInputStream(request.bodyInputStream);
+    handler.request = request;
+
     response.setStatusLine(request.httpVersion, statusCode, status);
-    response.bodyOutputStream.write(body, body.length);
+    if (body) {
+      response.bodyOutputStream.write(body, body.length);
+    }
   };
 }
 
+function basic_auth_header(user, password) {
+  return "Basic " + btoa(user + ":" + Utils.encodeUTF8(password));
+}
+
+function basic_auth_matches(req, user, password) {
+  return req.hasHeader("Authorization") &&
+         (req.getHeader("Authorization") == basic_auth_header(user, password));
+}
+
 function httpd_basic_auth_handler(body, metadata, response) {
   if (basic_auth_matches(metadata, "guest", "guest")) {
     response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
     response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
   } else {
     body = "This path exists and is protected - failed";
     response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
     response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
--- a/services/sync/tests/unit/test_interval_triggers.js
+++ b/services/sync/tests/unit/test_interval_triggers.js
@@ -50,20 +50,21 @@ function run_test() {
   Log4Moz.repository.getLogger("Sync.SyncScheduler").level = Log4Moz.Level.Trace;
 
   run_next_test();
 }
 
 add_test(function test_successful_sync_adjustSyncInterval() {
   _("Test successful sync calling adjustSyncInterval");
   let syncSuccesses = 0;
-  Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
+  function onSyncFinish() {
     _("Sync success.");
     syncSuccesses++;
-  });
+  };
+  Svc.Obs.add("weave:service:sync:finish", onSyncFinish);
 
   let server = sync_httpd_setup();
   setUp();
 
   // Confirm defaults
   do_check_false(SyncScheduler.idle);
   do_check_false(SyncScheduler.numClients > 1);
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.singleDeviceInterval);
@@ -140,40 +141,34 @@ add_test(function test_successful_sync_a
   SyncScheduler.hasIncomingItems = true;
   Service.sync();
   do_check_eq(syncSuccesses, 8);
   do_check_false(SyncScheduler.idle);
   do_check_true(SyncScheduler.numClients > 1);
   do_check_false(SyncScheduler.hasIncomingItems); //gets reset to false
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.immediateInterval);
 
-  Records.clearCache();
-  Svc.Prefs.resetBranch("");
-  SyncScheduler.setDefaults();
-  Clients.resetClient();
-
+  Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
+  Service.startOver();
   server.stop(run_next_test);
 });
 
 add_test(function test_unsuccessful_sync_adjustSyncInterval() {
   _("Test unsuccessful sync calling adjustSyncInterval");
 
   let syncFailures = 0;
-  Svc.Obs.add("weave:service:sync:error", function onSyncError() {
+  function onSyncError() {
     _("Sync error.");
     syncFailures++;
-  });
+  }
+  Svc.Obs.add("weave:service:sync:error", onSyncError);
     
   _("Test unsuccessful sync calls adjustSyncInterval");
-  let origLockedSync = Service._lockedSync;
-  Service._lockedSync = function () {
-    // Force a sync fail.
-    Service._loggedIn = false;
-    origLockedSync.call(Service);
-  };
+  // Force sync to fail.
+  Svc.Prefs.set("firstSync", "notReady");
   
   let server = sync_httpd_setup();
   setUp();
 
   // Confirm defaults
   do_check_false(SyncScheduler.idle);
   do_check_false(SyncScheduler.numClients > 1);
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.singleDeviceInterval);
@@ -255,22 +250,18 @@ add_test(function test_unsuccessful_sync
   SyncScheduler.hasIncomingItems = true;
   Service.sync();
   do_check_eq(syncFailures, 8);
   do_check_false(SyncScheduler.idle);
   do_check_true(SyncScheduler.numClients > 1);
   do_check_false(SyncScheduler.hasIncomingItems); //gets reset to false
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.immediateInterval);
 
-  Records.clearCache();
-  Svc.Prefs.resetBranch("");
-  SyncScheduler.setDefaults();
-  Clients.resetClient();
-  Service._lockedSync = origLockedSync;
-
+  Service.startOver();
+  Svc.Obs.remove("weave:service:sync:error", onSyncError);
   server.stop(run_next_test);
 });
 
 add_test(function test_back_triggers_sync() {
   let server = sync_httpd_setup();
   setUp();
 
   // Single device: no sync triggered.
@@ -285,15 +276,16 @@ add_test(function test_back_triggers_syn
   Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
     Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
 
     Records.clearCache();
     Svc.Prefs.resetBranch("");
     SyncScheduler.setDefaults();
     Clients.resetClient();
 
+    Service.startOver();
     server.stop(run_next_test);
   });
 
   SyncScheduler.idle = true;
   SyncScheduler.observe(null, "back", Svc.Prefs.get("scheduler.idleTime"));
   do_check_false(SyncScheduler.idle);
 });
--- a/services/sync/tests/unit/test_jpakeclient.js
+++ b/services/sync/tests/unit/test_jpakeclient.js
@@ -1,10 +1,10 @@
 Cu.import("resource://services-sync/log4moz.js");
-Cu.import("resource://services-sync/resource.js");
+Cu.import("resource://services-sync/identity.js");
 Cu.import("resource://services-sync/jpakeclient.js");
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/util.js");
 
 const JPAKE_LENGTH_SECRET     = 8;
 const JPAKE_LENGTH_CLIENTID   = 256;
 
 /*
@@ -107,35 +107,33 @@ ServerChannel.prototype = {
 
 };
 
 
 const DATA = {"msg": "eggstreamly sekrit"};
 const POLLINTERVAL = 50;
 
 function run_test() {
-  if (DISABLE_TESTS_BUG_618233)
-    return;
-
   Svc.Prefs.set("jpake.serverURL", "http://localhost:8080/");
   Svc.Prefs.set("jpake.pollInterval", POLLINTERVAL);
   Svc.Prefs.set("jpake.maxTries", 5);
   Svc.Prefs.set("jpake.firstMsgMaxTries", 5);
   // Ensure clean up
   Svc.Obs.add("profile-before-change", function() {
     Svc.Prefs.resetBranch("");
   });
 
   // Ensure PSM is initialized.
   Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports);
 
-  // Simulate Sync setup with a default authenticator in place. We
-  // want to make sure the J-PAKE requests don't include those data.
-  Auth.defaultAuthenticator = new BasicAuthenticator(
-    new Identity("Some Realm", "johndoe"));
+  // Simulate Sync setup with credentials in place. We want to make
+  // sure the J-PAKE requests don't include those data.
+  let id = new Identity(PWDMGR_PASSWORD_REALM, "johndoe");
+  id.password = "ilovejane";
+  ID.set("WeaveID", id);
 
   server = httpd_setup({"/new_channel": server_new_channel,
                         "/report":      server_report});
 
   initTestLogging("Trace");
   run_next_test();
 }
 
new file mode 100644
--- /dev/null
+++ b/services/sync/tests/unit/test_restrequest.js
@@ -0,0 +1,581 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+Cu.import("resource://services-sync/rest.js");
+Cu.import("resource://services-sync/log4moz.js");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+
+function run_test() {
+  Log4Moz.repository.getLogger("Sync.RESTRequest").level = Log4Moz.Level.Trace;
+  initTestLogging();
+
+  run_next_test();
+}
+
+/**
+ * Initializing a RESTRequest with an invalid URI throws
+ * NS_ERROR_MALFORMED_URI.
+ */
+add_test(function test_invalid_uri() {
+  do_check_throws(function() {
+    new RESTRequest("an invalid URI");
+  }, Cr.NS_ERROR_MALFORMED_URI);
+  run_next_test();
+});
+
+/**
+ * Verify initial values for attributes.
+ */
+add_test(function test_attributes() {
+  let uri = "http://foo.com/bar/baz";
+  let request = new RESTRequest(uri);
+
+  do_check_true(request.uri instanceof Ci.nsIURI);
+  do_check_eq(request.uri.spec, uri);
+  do_check_eq(request.response, null);
+  do_check_eq(request.status, request.NOT_SENT);
+  let expectedLoadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE |
+                          Ci.nsIRequest.INHIBIT_CACHING;
+  do_check_eq(request.loadFlags, expectedLoadFlags);
+
+  run_next_test();
+});
+
+/**
+ * Demonstrate API short-hand: create a request and dispatch it immediately.
+ */
+add_test(function test_simple_get() {
+  let handler = httpd_handler(200, "OK", "Huzzah!");
+  let server = httpd_setup({"/resource": handler});
+
+  let uri = "http://localhost:8080/resource";
+  let request = new RESTRequest(uri).get(function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "Huzzah!");
+
+    server.stop(run_next_test);
+  });
+  do_check_eq(request.status, request.SENT);
+  do_check_eq(request.method, "GET");
+});
+
+/**
+ * Test HTTP GET with all bells and whistles.
+ */
+add_test(function test_get() {
+  let handler = httpd_handler(200, "OK", "Huzzah!");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  do_check_eq(request.status, request.NOT_SENT);
+
+  request.onProgress = request.onComplete = function () {
+    do_throw("This function should have been overwritten!");
+  };
+
+  let onProgress_called = false;
+  function onProgress() {
+    onProgress_called = true;
+    do_check_eq(this.status, request.IN_PROGRESS);
+    do_check_true(this.response.body.length > 0);
+
+    do_check_true(!!(this.channel.loadFlags & Ci.nsIRequest.LOAD_BYPASS_CACHE));
+    do_check_true(!!(this.channel.loadFlags & Ci.nsIRequest.INHIBIT_CACHING));
+  };
+
+  function onComplete(error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "Huzzah!");
+    do_check_eq(handler.request.method, "GET");
+
+    do_check_true(onProgress_called);
+    Utils.nextTick(function () {
+      do_check_eq(request.onComplete, null);
+      do_check_eq(request.onProgress, null);
+      server.stop(run_next_test);
+    });
+  };
+
+  do_check_eq(request.get(onComplete, onProgress), request);
+  do_check_eq(request.status, request.SENT);
+  do_check_eq(request.method, "GET");
+  do_check_throws(function () {
+    request.get();
+  });
+});
+
+/**
+ * Test HTTP PUT with a simple string argument and default Content-Type.
+ */
+add_test(function test_put() {
+  let handler = httpd_handler(200, "OK", "Got it!");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  do_check_eq(request.status, request.NOT_SENT);
+
+  request.onProgress = request.onComplete = function () {
+    do_throw("This function should have been overwritten!");
+  };
+
+  let onProgress_called = false;
+  function onProgress() {
+    onProgress_called = true;
+    do_check_eq(this.status, request.IN_PROGRESS);
+    do_check_true(this.response.body.length > 0);
+  };
+
+  function onComplete(error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "Got it!");
+
+    do_check_eq(handler.request.method, "PUT");
+    do_check_eq(handler.request.body, "Hullo?");
+    do_check_eq(handler.request.getHeader("Content-Type"), "text/plain");
+
+    do_check_true(onProgress_called);
+    Utils.nextTick(function () {
+      do_check_eq(request.onComplete, null);
+      do_check_eq(request.onProgress, null);
+      server.stop(run_next_test);
+    });
+  };
+
+  do_check_eq(request.put("Hullo?", onComplete, onProgress), request);
+  do_check_eq(request.status, request.SENT);
+  do_check_eq(request.method, "PUT");
+  do_check_throws(function () {
+    request.put("Hai!");
+  });
+});
+
+/**
+ * Test HTTP POST with a simple string argument and default Content-Type.
+ */
+add_test(function test_post() {
+  let handler = httpd_handler(200, "OK", "Got it!");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  do_check_eq(request.status, request.NOT_SENT);
+
+  request.onProgress = request.onComplete = function () {
+    do_throw("This function should have been overwritten!");
+  };
+
+  let onProgress_called = false;
+  function onProgress() {
+    onProgress_called = true;
+    do_check_eq(this.status, request.IN_PROGRESS);
+    do_check_true(this.response.body.length > 0);
+  };
+
+  function onComplete(error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "Got it!");
+
+    do_check_eq(handler.request.method, "POST");
+    do_check_eq(handler.request.body, "Hullo?");
+    do_check_eq(handler.request.getHeader("Content-Type"), "text/plain");
+
+    do_check_true(onProgress_called);
+    Utils.nextTick(function () {
+      do_check_eq(request.onComplete, null);
+      do_check_eq(request.onProgress, null);
+      server.stop(run_next_test);
+    });
+  };
+
+  do_check_eq(request.post("Hullo?", onComplete, onProgress), request);
+  do_check_eq(request.status, request.SENT);
+  do_check_eq(request.method, "POST");
+  do_check_throws(function () {
+    request.post("Hai!");
+  });
+});
+
+/**
+ * Test HTTP DELETE.
+ */
+add_test(function test_delete() {
+  let handler = httpd_handler(200, "OK", "Got it!");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  do_check_eq(request.status, request.NOT_SENT);
+
+  request.onProgress = request.onComplete = function () {
+    do_throw("This function should have been overwritten!");
+  };
+
+  let onProgress_called = false;
+  function onProgress() {
+    onProgress_called = true;
+    do_check_eq(this.status, request.IN_PROGRESS);
+    do_check_true(this.response.body.length > 0);
+  };
+
+  function onComplete(error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "Got it!");
+    do_check_eq(handler.request.method, "DELETE");
+
+    do_check_true(onProgress_called);
+    Utils.nextTick(function () {
+      do_check_eq(request.onComplete, null);
+      do_check_eq(request.onProgress, null);
+      server.stop(run_next_test);
+    });
+  };
+
+  do_check_eq(request.delete(onComplete, onProgress), request);
+  do_check_eq(request.status, request.SENT);
+  do_check_eq(request.method, "DELETE");
+  do_check_throws(function () {
+    request.delete();
+  });
+});
+
+/**
+ * Test an HTTP response with a non-200 status code.
+ */
+add_test(function test_get_404() {
+  let handler = httpd_handler(404, "Not Found", "Cannae find it!");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_false(this.response.success);
+    do_check_eq(this.response.status, 404);
+    do_check_eq(this.response.body, "Cannae find it!");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * The 'data' argument to PUT, if not a string already, is automatically
+ * stringified as JSON.
+ */
+add_test(function test_put_json() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let sample_data = {
+    some: "sample_data",
+    injson: "format",
+    number: 42
+  };
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.put(sample_data, function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    do_check_eq(handler.request.method, "PUT");
+    do_check_eq(handler.request.body, JSON.stringify(sample_data));
+    do_check_eq(handler.request.getHeader("Content-Type"), "text/plain");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * The 'data' argument to POST, if not a string already, is automatically
+ * stringified as JSON.
+ */
+add_test(function test_post_json() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let sample_data = {
+    some: "sample_data",
+    injson: "format",
+    number: 42
+  };
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.post(sample_data, function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    do_check_eq(handler.request.method, "POST");
+    do_check_eq(handler.request.body, JSON.stringify(sample_data));
+    do_check_eq(handler.request.getHeader("Content-Type"), "text/plain");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * HTTP PUT with a custom Content-Type header.
+ */
+add_test(function test_put_override_content_type() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.setHeader("Content-Type", "application/lolcat");
+  request.put("O HAI!!1!", function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    do_check_eq(handler.request.method, "PUT");
+    do_check_eq(handler.request.body, "O HAI!!1!");
+    do_check_eq(handler.request.getHeader("Content-Type"), "application/lolcat");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * HTTP POST with a custom Content-Type header.
+ */
+add_test(function test_post_override_content_type() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.setHeader("Content-Type", "application/lolcat");
+  request.post("O HAI!!1!", function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.status, this.COMPLETED);
+    do_check_true(this.response.success);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    do_check_eq(handler.request.method, "POST");
+    do_check_eq(handler.request.body, "O HAI!!1!");
+    do_check_eq(handler.request.getHeader("Content-Type"), "application/lolcat");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * No special headers are sent by default on a GET request.
+ */
+add_test(function test_get_no_headers() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let ignore_headers = ["host", "user-agent", "accept", "accept-language",
+                        "accept-encoding", "accept-charset", "keep-alive",
+                        "connection", "pragma", "cache-control",
+                        "content-length"];
+
+  new RESTRequest("http://localhost:8080/resource").get(function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    let server_headers = handler.request.headers;
+    while (server_headers.hasMoreElements()) {
+      let header = server_headers.getNext().toString();
+      if (ignore_headers.indexOf(header) == -1) {
+        do_throw("Got unexpected header!");
+      }
+    }
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * Test changing the URI after having created the request.
+ */
+add_test(function test_changing_uri() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/the-wrong-resource");
+  request.uri = Utils.makeURI("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * Test setting HTTP request headers.
+ */
+add_test(function test_request_setHeader() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+
+  request.setHeader("X-What-Is-Weave", "awesome");
+  request.setHeader("X-WHAT-is-Weave", "more awesomer");
+  request.setHeader("Another-Header", "Hello World");
+
+  request.get(function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    do_check_eq(handler.request.getHeader("X-What-Is-Weave"), "more awesomer");
+    do_check_eq(handler.request.getHeader("another-header"), "Hello World");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * Test receiving HTTP response headers.
+ */
+add_test(function test_response_headers() {
+  function handler(request, response) {
+    response.setHeader("X-What-Is-Weave", "awesome");
+    response.setHeader("Another-Header", "Hello World");
+    response.setStatusLine(request.httpVersion, 200, "OK");
+  }
+  let server = httpd_setup({"/resource": handler});
+  let request = new RESTRequest("http://localhost:8080/resource");
+
+  request.get(function (error) {
+    do_check_eq(error, null);
+
+    do_check_eq(this.response.status, 200);
+    do_check_eq(this.response.body, "");
+
+    do_check_eq(this.response.headers["x-what-is-weave"], "awesome");
+    do_check_eq(this.response.headers["another-header"], "Hello World");
+
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * The onComplete() handler gets called in case of any network errors
+ * (e.g. NS_ERROR_CONNECTION_REFUSED).
+ */
+add_test(function test_connection_refused() {
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.onProgress = function onProgress() {
+    do_throw("Shouldn't have called request.onProgress()!");
+  };
+  request.get(function (error) {
+    do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED);
+    do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED");
+    do_check_eq(this.status, this.COMPLETED);
+    run_next_test();
+  });
+  do_check_eq(request.status, request.SENT);
+});
+
+/**
+ * Abort a request that just sent off.
+ */
+add_test(function test_abort() {
+  function handler() {
+    do_throw("Shouldn't have gotten here!");
+  }
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+
+  // Aborting a request that hasn't been sent yet is pointless and will throw.
+  do_check_throws(function () {
+    request.abort();
+  });
+
+  request.onProgress = request.onComplete = function () {
+    do_throw("Shouldn't have gotten here!");
+  };
+  request.get();
+  request.abort();
+
+  // Aborting an already aborted request is pointless and will throw.
+  do_check_throws(function () {
+    request.abort();
+  });
+
+  do_check_eq(request.status, request.ABORTED);
+  Utils.nextTick(function () {
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * A non-zero 'timeout' property specifies the amount of seconds to wait after
+ * channel activity until the request is automatically canceled.
+ */
+add_test(function test_timeout() {
+  let server = new nsHttpServer();
+  let server_connection;
+  server._handler.handleResponse = function(connection) {
+    // This is a handler that doesn't do anything, just keeps the connection
+    // open, thereby mimicking a timing out connection. We keep a reference to
+    // the open connection for later so it can be properly disposed of. That's
+    // why you really only want to make one HTTP request to this server ever.
+    server_connection = connection;
+  };
+  server.start(8080);
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.timeout = 0.1; // 100 milliseconds
+  request.get(function (error) {
+    do_check_eq(error.result, Cr.NS_ERROR_NET_TIMEOUT);
+    do_check_eq(this.status, this.ABORTED);
+
+    server_connection.close();
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * An exception thrown in 'onProgress' propagates to the 'onComplete' handler.
+ */
+add_test(function test_exception_in_onProgress() {
+  let handler = httpd_handler(200, "OK", "Foobar");
+  let server = httpd_setup({"/resource": handler});
+
+  let request = new RESTRequest("http://localhost:8080/resource");
+  request.onProgress = function onProgress() {
+    it.does.not.exist();
+  };
+  request.get(function (error) {
+    do_check_eq(error, "ReferenceError: it is not defined");
+    do_check_eq(this.status, this.ABORTED);
+
+    server.stop(run_next_test);
+  });
+});
--- a/services/sync/tests/unit/test_service_filelog.js
+++ b/services/sync/tests/unit/test_service_filelog.js
@@ -3,20 +3,16 @@
 
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://services-sync/log4moz.js");
 
 const logsdir = FileUtils.getDir("ProfD", ["weave", "logs"], true);
 
 function run_test() {
-  if (DISABLE_TESTS_BUG_664090) {
-    return;
-  }
-
   run_next_test();
 }
 
 add_test(function test_noOutput() {
   // Clear log output from startup.
   Svc.Prefs.set("log.appender.file.logOnSuccess", false);
   Svc.Obs.notify("weave:service:sync:finish");
 
--- a/services/sync/tests/unit/test_service_login.js
+++ b/services/sync/tests/unit/test_service_login.js
@@ -17,53 +17,63 @@ function login_handling(handler) {
     }
   };
 }
 
 function run_test() {
   let logger = Log4Moz.repository.rootLogger;
   Log4Moz.repository.rootLogger.addAppender(new Log4Moz.DumpAppender());
 
+  run_next_test();
+}
+
+add_test(function test_offline() {
   try {
     _("The right bits are set when we're offline.");
     Services.io.offline = true;
     do_check_eq(Service._ignorableErrorCount, 0);
     do_check_false(!!Service.login());
     do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
     do_check_eq(Service._ignorableErrorCount, 0);
     Services.io.offline = false;
   } finally {
     Svc.Prefs.resetBranch("");
+    run_next_test();
   }
- 
+});
+
+function setup() {
+  Service.serverURL = "http://localhost:8080/";
+  Service.clusterURL = "http://localhost:8080/";
+
   let janeHelper = track_collections_helper();
   let janeU      = janeHelper.with_updated_collection;
   let janeColls  = janeHelper.collections;
   let johnHelper = track_collections_helper();
   let johnU      = johnHelper.with_updated_collection;
   let johnColls  = johnHelper.collections;
 
-  do_test_pending();
-  let server = httpd_setup({
+  return httpd_setup({
     "/1.1/johndoe/info/collections": login_handling(johnHelper.handler),
     "/1.1/janedoe/info/collections": login_handling(janeHelper.handler),
-      
+
     // We need these handlers because we test login, and login
     // is where keys are generated or fetched.
     // TODO: have Jane fetch her keys, not generate them...
     "/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
     "/1.1/johndoe/storage/meta/global": johnU("meta",   new ServerWBO("global").handler()),
     "/1.1/janedoe/storage/crypto/keys": janeU("crypto", new ServerWBO("keys").handler()),
     "/1.1/janedoe/storage/meta/global": janeU("meta",   new ServerWBO("global").handler())
   });
+}
+
+add_test(function test_login_logout() {
+  let server = setup();
 
   try {
-    Service.serverURL = "http://localhost:8080/";
-    Service.clusterURL = "http://localhost:8080/";
-
     _("Force the initial state.");
     Status.service = STATUS_OK;
     do_check_eq(Status.service, STATUS_OK);
 
     _("Try logging in. It won't work because we're not configured yet.");
     Service.login();
     do_check_eq(Status.service, CLIENT_NOT_CONFIGURED);
     do_check_eq(Status.login, LOGIN_FAILED_NO_USERNAME);
@@ -93,135 +103,142 @@ function run_test() {
     do_check_eq(Status.login, LOGIN_FAILED_LOGIN_REJECTED);
     do_check_false(Service.isLoggedIn);
 
     _("Try again with correct password.");
     Service.login("janedoe", "ilovejohn");
     do_check_eq(Status.service, STATUS_OK);
     do_check_eq(Status.login, LOGIN_SUCCEEDED);
     do_check_true(Service.isLoggedIn);
-    
+
     _("Calling login() with parameters when the client is unconfigured sends notification.");
     let notified = false;
     Svc.Obs.add("weave:service:setup-complete", function() {
       notified = true;
     });
     Service.username = "";
     Service.password = "";
-    Service.passphrase = "";    
+    Service.passphrase = "";
     Service.login("janedoe", "ilovejohn", "bar");
     do_check_true(notified);
     do_check_eq(Status.service, STATUS_OK);
     do_check_eq(Status.login, LOGIN_SUCCEEDED);
     do_check_true(Service.isLoggedIn);
 
     _("Logout.");
     Service.logout();
     do_check_false(Service.isLoggedIn);
 
     _("Logging out again won't do any harm.");
     Service.logout();
     do_check_false(Service.isLoggedIn);
 
-    /*
-     * Testing login-on-sync.
-     */
-    
+  } finally {
+    Svc.Prefs.resetBranch("");
+    server.stop(run_next_test);
+  }
+});
+
+add_test(function test_login_on_sync() {
+  let server = setup();
+  Service.username = "johndoe";
+  Service.password = "ilovejane";
+  Service.passphrase = "bar";
+
+  try {
     _("Sync calls login.");
     let oldLogin = Service.login;
     let loginCalled = false;
     Service.login = function() {
       loginCalled = true;
       Status.login = LOGIN_SUCCEEDED;
       this._loggedIn = false;           // So that sync aborts.
       return true;
-    }
-    try {
-      Service.sync();
-    } catch (ex) {}
-    
+    };
+
+    Service.sync();
+
     do_check_true(loginCalled);
     Service.login = oldLogin;
-    
+
     // Stub mpLocked.
     let mpLockedF = Utils.mpLocked;
     let mpLocked = true;
     Utils.mpLocked = function() mpLocked;
-    
+
     // Stub scheduleNextSync. This gets called within checkSyncStatus if we're
     // ready to sync, so use it as an indicator.
     let scheduleNextSyncF = SyncScheduler.scheduleNextSync;
     let scheduleCalled = false;
     SyncScheduler.scheduleNextSync = function(wait) {
       scheduleCalled = true;
       scheduleNextSyncF.call(this, wait);
-    }
-    
+    };
+
     // Autoconnect still tries to connect in the background (useful behavior:
     // for non-MP users and unlocked MPs, this will detect version expiry
     // earlier).
-    // 
+    //
     // Consequently, non-MP users will be logged in as in the pre-Bug 543784 world,
     // and checkSyncStatus reflects that by waiting for login.
-    // 
+    //
     // This process doesn't apply if your MP is still locked, so we make
     // checkSyncStatus accept a locked MP in place of being logged in.
-    // 
+    //
     // This test exercises these two branches.
-    
+
     _("We're ready to sync if locked.");
     Service.enabled = true;
     Services.io.offline = false;
     SyncScheduler.checkSyncStatus();
     do_check_true(scheduleCalled);
-    
+
+    _("... and also if we're not locked.");
     scheduleCalled = false;
     mpLocked = false;
-    
-    _("... and not if not.");
     SyncScheduler.checkSyncStatus();
-    do_check_false(scheduleCalled);
+    do_check_true(scheduleCalled);
     SyncScheduler.scheduleNextSync = scheduleNextSyncF;
-    
+
     // TODO: need better tests around master password prompting. See Bug 620583.
 
     mpLocked = true;
-    
+
     // Testing exception handling if master password dialog is canceled.
     // Do this by stubbing out Service.passphrase.
     let oldPP = Service.__lookupGetter__("passphrase");
     _("Old passphrase function is " + oldPP);
     Service.__defineGetter__("passphrase",
                            function() {
                              throw "User canceled Master Password entry";
                            });
-    
+
     let oldClearSyncTriggers = SyncScheduler.clearSyncTriggers;
     let oldLockedSync = Service._lockedSync;
-    
+
     let cSTCalled = false;
     let lockedSyncCalled = false;
-    
+
     SyncScheduler.clearSyncTriggers = function() { cSTCalled = true; };
     Service._lockedSync = function() { lockedSyncCalled = true; };
-    
+
     _("If master password is canceled, login fails and we report lockage.");
     do_check_false(!!Service.login());
     do_check_eq(Status.login, MASTER_PASSWORD_LOCKED);
     do_check_eq(Status.service, LOGIN_FAILED);
     _("Locked? " + Utils.mpLocked());
     _("checkSync reports the correct term.");
     do_check_eq(Service._checkSync(), kSyncMasterPasswordLocked);
-    
+
     _("Sync doesn't proceed and clears triggers if MP is still locked.");
     Service.sync();
-    
+
     do_check_true(cSTCalled);
     do_check_false(lockedSyncCalled);
 
     // N.B., a bunch of methods are stubbed at this point. Be careful putting
     // new tests after this point!
-    
+
   } finally {
     Svc.Prefs.resetBranch("");
-    server.stop(do_test_finished);
+    server.stop(run_next_test);
   }
-}
+});
--- a/services/sync/tests/unit/test_service_sync_checkServerError.js
+++ b/services/sync/tests/unit/test_service_sync_checkServerError.js
@@ -300,14 +300,11 @@ add_test(function test_engine_applyFaile
     Status.resetSync();
     Service.startOver();
   }
   server.stop(run_next_test);
 });
 
 
 function run_test() {
-  if (DISABLE_TESTS_BUG_604565)
-    return;
-
   Engines.register(CatapultEngine);
   run_next_test();
 }
--- a/services/sync/tests/unit/test_service_sync_remoteSetup.js
+++ b/services/sync/tests/unit/test_service_sync_remoteSetup.js
@@ -1,19 +1,16 @@
 Cu.import("resource://services-sync/main.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://services-sync/status.js");
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/log4moz.js");
 
 function run_test() {
-  if (DISABLE_TESTS_BUG_604565)
-    return;
-
   let logger = Log4Moz.repository.rootLogger;
   Log4Moz.repository.rootLogger.addAppender(new Log4Moz.DumpAppender());
 
   let guidSvc = new FakeGUIDService();
   let clients = new ServerCollection();
   let meta_global = new ServerWBO('global');
 
   let collectionsHelper = track_collections_helper();
--- a/services/sync/tests/unit/test_service_sync_updateEnabledEngines.js
+++ b/services/sync/tests/unit/test_service_sync_updateEnabledEngines.js
@@ -381,13 +381,10 @@ add_test(function test_dependentEnginesD
     do_check_false(stirlingEngine.enabled);
   } finally {
     Service.startOver();
     server.stop(run_next_test);
   }
 });
 
 function run_test() {
-  if (DISABLE_TESTS_BUG_604565)
-    return;
-
   run_next_test();
 }
--- a/services/sync/tests/unit/test_syncengine_sync.js
+++ b/services/sync/tests/unit/test_syncengine_sync.js
@@ -13,19 +13,16 @@ function makeRotaryEngine() {
 
 function cleanAndGo(server) {
   Svc.Prefs.resetBranch("");
   Records.clearCache();
   server.stop(run_next_test);
 }
 
 function run_test() {
-  if (DISABLE_TESTS_BUG_604565)
-    return;
-
   generateNewKeys();
   run_next_test();
 }
 
 /*
  * Tests
  * 
  * SyncEngine._sync() is divided into four rather independent steps:
--- a/services/sync/tests/unit/test_syncscheduler.js
+++ b/services/sync/tests/unit/test_syncscheduler.js
@@ -157,19 +157,17 @@ add_test(function test_masterpassword_lo
 
   do_check_true(loginFailed);
   do_check_eq(Status.login, MASTER_PASSWORD_LOCKED);
   do_check_true(rescheduleInterval);
 
   Service.verifyLogin = Service._verifyLogin;
   SyncScheduler.scheduleAtInterval = SyncScheduler._scheduleAtInterval;
 
-  Svc.Prefs.resetBranch("");
-  SyncScheduler.setDefaults();
-  Clients.resetClient();
+  Service.startOver();
   server.stop(run_next_test);
 });
 
 add_test(function test_calculateBackoff() {
   do_check_eq(Status.backoffInterval, 0);
 
   // Test no interval larger than the maximum backoff is used if
   // Status.backoffInterval is smaller.
@@ -199,16 +197,17 @@ add_test(function test_scheduleNextSync(
   Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
     // Ensure this gets called after SyncScheduler's observer so we
     // can cancel the timer set by SyncScheduler.scheduleNextSync().
     Utils.nextTick(function () {
       SyncScheduler.setDefaults();
       Svc.Prefs.resetBranch("");
       SyncScheduler.syncTimer.clear();
       Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
+      Service.startOver();
       server.stop(run_next_test);
     }, this);
   });
   
   // Make sync happen faster
   SyncScheduler.singleDeviceInterval = 100;
   SyncScheduler.syncInterval = SyncScheduler.singleDeviceInterval;
 
@@ -238,22 +237,18 @@ add_test(function test_scheduleNextSync(
   do_check_true(SyncScheduler.nextSync - Date.now() <= expectedInterval);
   do_check_true(SyncScheduler.syncTimer.delay <= expectedInterval);
 });
 
 add_test(function test_handleSyncError() {
   let server = sync_httpd_setup();
   setUp();
  
-  let origLockedSync = Service._lockedSync;
-  Service._lockedSync = function () {
-    // Force a sync fail.
-    Service._loggedIn = false;
-    origLockedSync.call(Service);
-  };
+  // Force sync to fail.
+  Svc.Prefs.set("firstSync", "notReady");
 
   _("Ensure expected initial environment.");
   do_check_eq(SyncScheduler._syncErrors, 0);
   do_check_false(Status.enforceBackoff);
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.singleDeviceInterval);
   do_check_eq(Status.backoffInterval, 0);
 
   // Trigger sync with an error several times & observe
@@ -293,18 +288,17 @@ add_test(function test_handleSyncError()
   Service.sync();
   maxInterval = SyncScheduler._syncErrors * (2 * MINIMUM_BACKOFF_INTERVAL);
   do_check_true(SyncScheduler.nextSync <= Date.now() + maxInterval);
   do_check_true(SyncScheduler.syncTimer.delay <= maxInterval);
   do_check_eq(SyncScheduler._syncErrors, 4);
   do_check_true(Status.enforceBackoff);
   SyncScheduler.syncTimer.clear();
 
-  Service._lockedSync = origLockedSync;
-  SyncScheduler.setDefaults();
+  Service.startOver();
   server.stop(run_next_test);
 });
 
 add_test(function test_client_sync_finish_updateClientMode() {
   let server = sync_httpd_setup();
   setUp();
 
   // Confirm defaults.
@@ -329,39 +323,101 @@ add_test(function test_client_sync_finis
 
   // Goes back to single user if # clients is 1.
   do_check_eq(SyncScheduler.numClients, 1);
   do_check_eq(SyncScheduler.syncThreshold, SINGLE_USER_THRESHOLD);
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.singleDeviceInterval);
   do_check_false(SyncScheduler.numClients > 1);
   do_check_false(SyncScheduler.idle);
 
-  Svc.Prefs.resetBranch("");
-  SyncScheduler.setDefaults();
-  Clients.resetClient();
+  Service.startOver();
   server.stop(run_next_test);
 });
 
-add_test(function test_sync_at_startup() {
+add_test(function test_autoconnect() {
   Svc.Obs.add("weave:service:sync:finish", function onSyncFinish() {
     Svc.Obs.remove("weave:service:sync:finish", onSyncFinish);
 
-    Svc.Prefs.resetBranch("");
-    SyncScheduler.setDefaults();
-    Clients.resetClient();
-
+    Service.startOver();
     server.stop(run_next_test);
   });
 
   let server = sync_httpd_setup();
   setUp();
 
   Service.delayedAutoConnect(0);
 });
 
+add_test(function test_autoconnect_mp_locked() {
+  let server = sync_httpd_setup();
+  setUp();
+
+  // Pretend user did not unlock master password.
+  let origLocked = Utils.mpLocked;
+  Utils.mpLocked = function() true;
+
+  let origPP = Service.__lookupGetter__("passphrase");
+  delete Service.passphrase;
+  Service.__defineGetter__("passphrase", function() {
+    throw "User canceled Master Password entry";
+  });
+
+  // A locked master password will still trigger a sync, but then we'll hit
+  // MASTER_PASSWORD_LOCKED and hence MASTER_PASSWORD_LOCKED_RETRY_INTERVAL.
+  Svc.Obs.add("weave:service:login:error", function onLoginError() {
+    Svc.Obs.remove("weave:service:login:error", onLoginError);
+    Utils.nextTick(function aLittleBitAfterLoginError() {
+      do_check_eq(Status.login, MASTER_PASSWORD_LOCKED);
+
+      Utils.mpLocked = origLocked;
+      delete Service.passphrase;
+      Service.__defineGetter__("passphrase", origPP);
+
+      Service.startOver();
+      server.stop(run_next_test);
+    });
+  });
+
+  Service.delayedAutoConnect(0);
+});
+
+let timer;
+add_test(function test_no_autoconnect_during_wizard() {
+  let server = sync_httpd_setup();
+  setUp();
+
+  // Simulate the Sync setup wizard.
+  Svc.Prefs.set("firstSync", "notReady");
+
+  // Ensure we don't actually try to sync (or log in for that matter).
+  function onLoginStart() {
+    do_throw("Should not get here!");
+  }
+  Svc.Obs.add("weave:service:login:start", onLoginStart);
+
+  // First wait >100ms (nsITimers can take up to that much time to fire, so
+  // we can account for the timer in delayedAutoconnect) and then two event
+  // loop ticks (to account for the Utils.nextTick() in _autoConnect).
+  let ticks = 2;
+  function wait() {
+    if (ticks) {
+      ticks -= 1;
+      Utils.nextTick(wait);
+      return;
+    }
+    Svc.Obs.remove("weave:service:login:start", onLoginStart);
+
+    Service.startOver();
+    server.stop(run_next_test);    
+  }
+  timer = Utils.namedTimer(wait, 150, {}, "timer");
+
+  Service.delayedAutoConnect(0);
+});
+
 add_test(function test_idle_adjustSyncInterval() {
   // Confirm defaults.
   do_check_eq(SyncScheduler.idle, false);
 
   // Single device: nothing changes.
   SyncScheduler.observe(null, "idle", Svc.Prefs.get("scheduler.idleTime"));
   do_check_eq(SyncScheduler.idle, true);
   do_check_eq(SyncScheduler.syncInterval, SyncScheduler.singleDeviceInterval);
new file mode 100644
--- /dev/null
+++ b/services/sync/tests/unit/test_syncstoragerequest.js
@@ -0,0 +1,167 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+Cu.import("resource://services-sync/rest.js");
+Cu.import("resource://services-sync/util.js");
+Cu.import("resource://services-sync/identity.js");
+Cu.import("resource://services-sync/constants.js");
+Cu.import("resource://services-sync/log4moz.js");
+
+function run_test() {
+  Log4Moz.repository.getLogger("Sync.RESTRequest").level = Log4Moz.Level.Trace;
+  initTestLogging();
+
+  run_next_test();
+}
+
+add_test(function test_user_agent_desktop() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let expectedUA = Services.appinfo.name + "/" + Services.appinfo.version +
+                   " FxSync/" + WEAVE_VERSION + "." +
+                   Services.appinfo.appBuildID + ".desktop";
+
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(handler.request.getHeader("User-Agent"), expectedUA);
+    server.stop(run_next_test);
+  });
+});
+
+add_test(function test_user_agent_mobile() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  Svc.Prefs.set("client.type", "mobile");
+  let expectedUA = Services.appinfo.name + "/" + Services.appinfo.version +
+                   " FxSync/" + WEAVE_VERSION + "." +
+                   Services.appinfo.appBuildID + ".mobile";
+
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(handler.request.getHeader("User-Agent"), expectedUA);
+    Svc.Prefs.resetBranch("");
+    server.stop(run_next_test);
+  });
+});
+
+add_test(function test_auth() {
+  let handler = httpd_handler(200, "OK");
+  let server = httpd_setup({"/resource": handler});
+
+  let id = new Identity(PWDMGR_PASSWORD_REALM, "johndoe");
+  id.password = "ilovejane";
+  ID.set("WeaveID", id);
+
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    do_check_true(basic_auth_matches(handler.request, "johndoe", "ilovejane"));
+
+    ID.del("WeaveID");
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ *  The X-Weave-Timestamp header updates SyncStorageRequest.serverTime.
+ */
+add_test(function test_weave_timestamp() {
+  const TIMESTAMP = 1274380461;
+  function handler(request, response) {
+    response.setHeader("X-Weave-Timestamp", "" + TIMESTAMP, false);
+    response.setStatusLine(request.httpVersion, 200, "OK");
+  }
+  let server = httpd_setup({"/resource": handler});
+
+  do_check_eq(SyncStorageRequest.serverTime, undefined);
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(SyncStorageRequest.serverTime, TIMESTAMP);
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * The X-Weave-Backoff header notifies an observer.
+ */
+add_test(function test_weave_backoff() {
+  function handler(request, response) {
+    response.setHeader("X-Weave-Backoff", '600', false);
+    response.setStatusLine(request.httpVersion, 200, "OK");
+  }
+  let server = httpd_setup({"/resource": handler});
+
+  let backoffInterval;  
+  Svc.Obs.add("weave:service:backoff:interval", function onBackoff(subject) {
+    Svc.Obs.remove("weave:service:backoff:interval", onBackoff);
+    backoffInterval = subject;
+  });
+
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(backoffInterval, 600);
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * X-Weave-Quota-Remaining header notifies observer on successful requests.
+ */
+add_test(function test_weave_quota_notice() {
+  function handler(request, response) {
+    response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
+    response.setStatusLine(request.httpVersion, 200, "OK");
+  }
+  let server = httpd_setup({"/resource": handler});
+
+  let quotaValue;
+  Svc.Obs.add("weave:service:quota:remaining", function onQuota(subject) {
+    Svc.Obs.remove("weave:service:quota:remaining", onQuota);
+    quotaValue = subject;
+  });
+
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 200);
+    do_check_eq(quotaValue, 1048576);
+    server.stop(run_next_test);
+  });
+});
+
+/**
+ * X-Weave-Quota-Remaining header doesn't notify observer on failed requests.
+ */
+add_test(function test_weave_quota_error() {
+  function handler(request, response) {
+    response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
+    response.setStatusLine(request.httpVersion, 400, "Bad Request");
+  }
+  let server = httpd_setup({"/resource": handler});
+
+  let quotaValue;
+  function onQuota(subject) {
+    quotaValue = subject;
+  }
+  Svc.Obs.add("weave:service:quota:remaining", onQuota);
+
+  let request = new SyncStorageRequest("http://localhost:8080/resource");
+  request.get(function (error) {
+    do_check_eq(error, null);
+    do_check_eq(this.response.status, 400);
+    do_check_eq(quotaValue, undefined);
+    Svc.Obs.remove("weave:service:quota:remaining", onQuota);
+    server.stop(run_next_test);
+  });
+});
--- a/services/sync/tests/unit/xpcshell.ini
+++ b/services/sync/tests/unit/xpcshell.ini
@@ -28,59 +28,73 @@ tail =
 [test_forms_store.js]
 [test_forms_tracker.js]
 [test_history_engine.js]
 [test_history_store.js]
 [test_history_tracker.js]
 [test_hmac_error.js]
 [test_interval_triggers.js]
 [test_jpakeclient.js]
+# Bug 618233: this test produces random failures on Windows 7.
+skip-if = os == "win"
 [test_keys.js]
 [test_load_modules.js]
 [test_log4moz.js]
 [test_notifications.js]
 [test_password_store.js]
 [test_password_tracker.js]
 [test_places_guid_downgrade.js]
 [test_prefs_store.js]
 [test_prefs_tracker.js]
 [test_records_crypto.js]
 [test_records_crypto_generateEntry.js]
 [test_records_wbo.js]
 [test_resource.js]
 [test_resource_async.js]
 [test_resource_ua.js]
+[test_restrequest.js]
 [test_score_triggers.js]
 [test_service_attributes.js]
 [test_service_changePassword.js]
 [test_service_checkAccount.js]
 [test_service_cluster.js]
 [test_service_createAccount.js]
 [test_service_detect_upgrade.js]
 [test_service_filelog.js]
+# Bug 664090: this test persistently fails on Windows opt builds.
+skip-if = os == "win" && !debug
 [test_service_login.js]
 [test_service_migratePrefs.js]
 [test_service_passwordUTF8.js]
 [test_service_persistLogin.js]
 [test_service_quota.js]
 [test_service_startOver.js]
 [test_service_startup.js]
 [test_service_sync_401.js]
 [test_service_sync_checkServerError.js]
+# Bug 604565: this test intermittently hangs on OS X debug builds.
+skip-if = os == "mac" && debug
 [test_service_sync_locked.js]
 [test_service_sync_remoteSetup.js]
+# Bug 604565: this test intermittently hangs on OS X debug builds.
+skip-if = os == "mac" && debug
 [test_service_sync_updateEnabledEngines.js]
+# Bug 604565: this test intermittently hangs on OS X debug builds.
+skip-if = os == "mac" && debug
 [test_service_verifyLogin.js]
 [test_service_wipeClient.js]
 [test_service_wipeServer.js]
 [test_status.js]
 [test_status_checkSetup.js]
 [test_syncengine.js]
 [test_syncengine_sync.js]
+# Bug 604565: this test intermittently hangs on OS X debug builds.
+skip-if = os == "mac" && debug
 [test_syncscheduler.js]
+[test_syncstoragerequest.js]
 [test_tab_engine.js]
 [test_tab_store.js]
 [test_tab_tracker.js]
 [test_tracker_addChanged.js]
 [test_upgrade_old_sync_key.js]
 [test_utils_asyncChain.js]
 [test_utils_atob.js]
 [test_utils_catch.js]
--- a/services/sync/version.txt
+++ b/services/sync/version.txt
@@ -1,1 +1,1 @@
-1.10.0
+1.11.0
--- a/testing/jetpack/jetpack-location.txt
+++ b/testing/jetpack/jetpack-location.txt
@@ -1,1 +1,1 @@
-http://hg.mozilla.org/projects/addon-sdk/archive/49e4c09bca42.tar.bz2
+http://hg.mozilla.org/projects/addon-sdk/archive/f29423e6edec.tar.bz2
--- a/testing/mochitest/Makefile.in
+++ b/testing/mochitest/Makefile.in
@@ -95,16 +95,17 @@ include $(topsrcdir)/build/automation-bu
 		ipc.js \
 		browser-harness.xul \
 		redirect.html \
 		redirect.js \
 		$(topsrcdir)/build/pgo/server-locations.txt \
 		$(topsrcdir)/netwerk/test/httpserver/httpd.js \
 		mozprefs.js \
 		pywebsocket_wrapper.py \
+ 	 	plain-loop.html \
 		$(NULL)	
 
 _PYWEBSOCKET_FILES = \
 		pywebsocket/standalone.py \
 		$(NULL)
 
 _MOD_PYWEBSOCKET_FILES = \
 		pywebsocket/mod_pywebsocket/__init__.py \
--- a/testing/mochitest/browser-test.js
+++ b/testing/mochitest/browser-test.js
@@ -1,15 +1,16 @@
 // Test timeout (seconds)
 const TIMEOUT_SECONDS = 30;
 var gConfig;
 
 if (Cc === undefined) {
   var Cc = Components.classes;
   var Ci = Components.interfaces;
+  var Cu = Components.utils;
 }
 window.addEventListener("load", testOnLoad, false);
 
 function testOnLoad() {
   window.removeEventListener("load", testOnLoad, false);
 
   // Make sure to launch the test harness for the first opened window only
   var prefs = Cc["@mozilla.org/preferences-service;1"].
@@ -52,27 +53,32 @@ function Tester(aTests, aDumper, aCallba
   this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/SimpleTest.js", simpleTestScope);
   this._scriptLoader.loadSubScript("chrome://mochikit/content/chrome-harness.js", simpleTestScope);
   this.SimpleTest = simpleTestScope.SimpleTest;
 }
 Tester.prototype = {
   EventUtils: {},
   SimpleTest: {},
 
+  loops: 0,
   checker: null,
   currentTestIndex: -1,
   lastStartTime: null,
   get currentTest() {
     return this.tests[this.currentTestIndex];
   },
   get done() {
     return this.currentTestIndex == this.tests.length - 1;
   },
 
   start: function Tester_start() {
+    //if testOnLoad was not called, then gConfig is not defined
+    if(!gConfig)
+      gConfig = readConfig();
+    this.loops = gConfig.loops;
     this.dumper.dump("*** Start BrowserChrome Test Results ***\n");
     this._cs.registerListener(this);
 
     if (this.tests.length)
       this.nextTest();
     else
       this.finish();
   },
@@ -118,43 +124,50 @@ Tester.prototype = {
       }
     }
 
     // Make sure the window is raised before each test.
     this.SimpleTest.waitForFocus(aCallback);
   },
 
   finish: function Tester_finish(aSkipSummary) {
-    this._cs.unregisterListener(this);
-
-    this.dumper.dump("\nINFO TEST-START | Shutdown\n");
-    if (this.tests.length) {
-      this.dumper.dump("Browser Chrome Test Summary\n");
-
-      function sum(a,b) a+b;
-      var passCount = this.tests.map(function (f) f.passCount).reduce(sum);
-      var failCount = this.tests.map(function (f) f.failCount).reduce(sum);
-      var todoCount = this.tests.map(function (f) f.todoCount).reduce(sum);
-
-      this.dumper.dump("\tPassed: " + passCount + "\n" +
-                       "\tFailed: " + failCount + "\n" +
-                       "\tTodo: " + todoCount + "\n");
-    } else {
-      this.dumper.dump("TEST-UNEXPECTED-FAIL | (browser-test.js) | " +
-                       "No tests to run. Did you pass an invalid --test-path?");
+    if(this.loops > 0){
+      --this.loops;
+      this.currentTestIndex = -1;
+      this.nextTest();
     }
-
-    this.dumper.dump("\n*** End BrowserChrome Test Results ***\n");
-
-    this.dumper.done();
-
-    // Tests complete, notify the callback and return
-    this.callback(this.tests);
-    this.callback = null;
-    this.tests = null;
+    else{
+      this._cs.unregisterListener(this);
+  
+      this.dumper.dump("\nINFO TEST-START | Shutdown\n");
+      if (this.tests.length) {
+        this.dumper.dump("Browser Chrome Test Summary\n");
+  
+        function sum(a,b) a+b;
+        var passCount = this.tests.map(function (f) f.passCount).reduce(sum);
+        var failCount = this.tests.map(function (f) f.failCount).reduce(sum);
+        var todoCount = this.tests.map(function (f) f.todoCount).reduce(sum);
+  
+        this.dumper.dump("\tPassed: " + passCount + "\n" +
+                         "\tFailed: " + failCount + "\n" +
+                         "\tTodo: " + todoCount + "\n");
+      } else {
+        this.dumper.dump("TEST-UNEXPECTED-FAIL | (browser-test.js) | " +
+                         "No tests to run. Did you pass an invalid --test-path?");
+      }
+  
+      this.dumper.dump("\n*** End BrowserChrome Test Results ***\n");
+  
+      this.dumper.done();
+  
+      // Tests complete, notify the callback and return
+      this.callback(this.tests);
+      this.callback = null;
+      this.tests = null;
+    }
   },
 
   observe: function Tester_observe(aConsoleMessage) {
     try {
       var msg = "Console message: " + aConsoleMessage.message;
       if (this.currentTest)
         this.currentTest.addResult(new testMessage(msg));
       else
--- a/testing/mochitest/harness-overlay.xul
+++ b/testing/mochitest/harness-overlay.xul
@@ -27,47 +27,51 @@ if (Cc === undefined) {
   var Cc = Components.classes;
   var Ci = Components.interfaces;
 }
 
 function loadTests()
 {
   window.removeEventListener("load", loadTests, false);
   [links, singleTestPath] = getTestList();
-
+ 
   // load server.js in so we can share template functions
   var scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                        getService(Ci.mozIJSSubScriptLoader);
   var srvScope = {};
   scriptLoader.loadSubScript('chrome://mochikit/content/server.js',
                              srvScope);
 
   // generate our test list
   srvScope.makeTags();
   var tableContent = srvScope.linksToTableRows(links, 0);
 
   function populate() {
     $("test-table").innerHTML += tableContent;
   }
   gTestList = eval(srvScope.jsonArrayOfTestFiles(links));
   populate();
-  hookup();
 
-  if (singleTestPath)
-    window.location.href = singleTestPath;
+  if (singleTestPath) {
+    TestRunner.loopTest(singleTestPath);
+  } else {
+    hookup();
+  }
+
 }
 
     window.addEventListener("load", loadTests, false);
   ]]>
   </script>
 
   <vbox>   
     <button label="Run Chrome Tests" id="runtests" flex="1"/>
 
     <body xmlns="http://www.w3.org/1999/xhtml" id="xulharness">
+      <!--TODO: this should be separated into a file that both this file and server.js uses-->
       <div class="container">
         <p style="float:right;">
           <small>Based on the MochiKit unit tests.</small>
         </p>
         <div class="status">
           <h1 id="indicator">Status</h1>
           <h2 id="pass">Passed: <span id="pass-count">0</span></h2>
           <h2 id="fail">Failed: <span id="fail-count">0</span></h2>
@@ -93,15 +97,21 @@ function loadTests()
               <tr>
                 <td>Passed</td>
                 <td>Failed</td>
                 <td>Todo</td>
                 <td>Test Files</td>
               </tr>
             </tbody>
           </table>
+          <br/>
+          <table cellpadding="0" cellspacing="0" border="1" bordercolor="red">
+          <!-- tbody needed to avoid bug 494546 causing performance problems -->
+            <tbody id="fail-table">
+            </tbody>
+          </table>
         </div>
       </div>
     </body>
   </vbox>
 </window>
 
 </overlay>
new file mode 100644
--- /dev/null
+++ b/testing/mochitest/plain-loop.html
@@ -0,0 +1,80 @@
+<html>
+<head>
+  <link rel="stylesheet" type="text/css" href="/static/harness.css" />
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/TestRunner.js"></script>        
+  <script type="text/javascript" src="/tests/SimpleTest/MozillaFileLogger.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/setup.js"></script>
+  </head>
+  <script type="text/javascript">
+
+function loadTests()
+{
+  var links = {};
+  var params = {};
+  if (window.parseQueryString) {
+    params = parseQueryString(location.search.substring(1), true);
+  }
+
+  var table = $("test-table");
+  var row = table.rows[1];
+  row.id = 'tr-' + params.testname;
+  row.cells[3].innerHTML= "<a href=" + params.testname + ">" + params.testname + "</a>";
+
+  TestRunner.loopTest(params.testname);
+}
+</script>
+
+<body onload="loadTests()">
+      <!--TODO: this should be separated into a file that both this file and server.js uses-->
+      <div class="container">
+        <p style="float:right;">
+          <small>Based on the MochiKit unit tests.</small>
+        </p>
+        <div class="status">
+          <h1 id="indicator">Status</h1>
+          <h2 id="pass">Passed: <span id="pass-count">0</span></h2>
+          <h2 id="fail">Failed: <span id="fail-count">0</span></h2>
+          <h2 id="fail">Todo: <span id="todo-count">0</span></h2>
+        </div>
+        <div class="clear"></div>
+        <div id="current-test">
+          <b>Currently Executing: <span id="current-test-path">_</span></b>
+        </div>
+        <div class="clear"></div>
+        <div class="frameholder">
+          <iframe type="content" scrolling="no" id="testframe" width="550" height="350"></iframe>
+        </div>
+        <div class="clear"></div>
+        <div class="toggle">
+          <a href="#" id="toggleNonTests">Show Non-Tests</a>
+          <br />
+        </div>
+        <div id="wrapper">
+          <table cellpadding="0" cellspacing="0">
+          <!-- tbody needed to avoid bug 494546 causing performance problems -->
+            <tbody id="test-table">
+              <tr>
+                <td>Passed</td>
+                <td>Failed</td>
+                <td>Todo</td>
+                <td>Test Files</td>
+              </tr>
+              <tr class="dir">
+                <td>0</td>
+                <td>0</td>
+                <td>0</td>
+                <td></td>
+              </tr>
+            </tbody>
+          </table>
+          <br/>
+          <table cellpadding="0" cellspacing="0" border="1" bordercolor="red">
+          <!-- tbody needed to avoid bug 494546 causing performance problems -->
+            <tbody id="fail-table">
+            </tbody>
+          </table>
+        </div>
+      </div>
+</body>
+</html>
--- a/testing/mochitest/runtests.py
+++ b/testing/mochitest/runtests.py
@@ -227,16 +227,23 @@ class MochitestOptions(optparse.OptionPa
     defaults["profilePath"] = tempfile.mkdtemp()
 
     self.add_option("--use-vmware-recording",
                     action = "store_true", dest = "vmwareRecording",
                     help = "enables recording while the application is running "
                            "inside a VMware Workstation 7.0 or later VM")
     defaults["vmwareRecording"] = False
 
+    self.add_option("--loops",
+                    action = "store", type = "int",
+                    dest = "loops", metavar = "LOOPS",
+                    help = "repeats the test or set of tests the given number of times "
+                           "without restarting the browser (given number > 0)")
+    defaults["loops"] = 0
+
     # -h, --help are automatically handled by OptionParser
 
     self.set_defaults(**defaults)
 
     usage = """\
 Usage instructions for runtests.py.
 All arguments are optional.
 If --chrome is specified, chrome tests will be run instead of web content tests.
@@ -400,16 +407,17 @@ class WebSocketServer(object):
 
   def stop(self):
     self._process.kill()
 
 class Mochitest(object):
   # Path to the test script on the server
   TEST_PATH = "/tests/"
   CHROME_PATH = "/redirect.html";
+  PLAIN_LOOP_PATH = "/plain-loop.html";
   urlOpts = []
   runSSLTunnel = True
   vmwareHelper = None
 
   oldcwd = os.getcwd()
 
   def __init__(self, automation):
     self.automation = automation
@@ -428,16 +436,18 @@ class Mochitest(object):
   def getFullPath(self, path):
     " Get an absolute path relative to self.oldcwd."
     return os.path.normpath(os.path.join(self.oldcwd, os.path.expanduser(path)))
 
   def buildTestPath(self, options):
     """ Build the url path to the specific test harness and test file or directory """
     testHost = "http://mochi.test:8888"
     testURL = testHost + self.TEST_PATH + options.testPath
+    if os.path.isfile(self.oldcwd + self.TEST_PATH + options.testPath) and options.loops > 0:
+       testURL = testHost + self.PLAIN_LOOP_PATH
     if options.chrome or options.a11y:
        testURL = testHost + self.CHROME_PATH
     elif options.browserChrome:
       testURL = "about:blank"
     elif options.ipcplugins:
       testURL = testHost + self.TEST_PATH + "dom/plugins/test"
     return testURL
 
@@ -532,16 +542,17 @@ class Mochitest(object):
         URL parameters to test URL:
 
         autorun -- kick off tests automatically
         closeWhenDone -- runs quit.js after tests
         logFile -- logs test run to an absolute path
         totalChunks -- how many chunks to split tests into
         thisChunk -- which chunk to run
         timeout -- per-test timeout in seconds
+        loops -- How many times to run the test
     """
   
     # allow relative paths for logFile
     if options.logFile:
       options.logFile = self.getLogFilePath(options.logFile)
     if options.browserChrome or options.chrome or options.a11y:
       self.makeTestConfig(options)
     else:
@@ -558,16 +569,20 @@ class Mochitest(object):
         self.urlOpts.append("consoleLevel=" + encodeURIComponent(options.consoleLevel))
       if options.totalChunks:
         self.urlOpts.append("totalChunks=%d" % options.totalChunks)
         self.urlOpts.append("thisChunk=%d" % options.thisChunk)
       if options.chunkByDir:
         self.urlOpts.append("chunkByDir=%d" % options.chunkByDir)
       if options.shuffle:
         self.urlOpts.append("shuffle=1")
+      if options.loops:
+        self.urlOpts.append("loops=%d" % options.loops)
+      if os.path.isfile(self.oldcwd + self.TEST_PATH + options.testPath) and options.loops > 0:
+        self.urlOpts.append("testname=%s" % (self.TEST_PATH + options.testPath))
 
   def cleanup(self, manifest, options):
     """ remove temporary files and profile """
     os.remove(manifest)
     shutil.rmtree(options.profilePath)
 
   def startVMwareRecording(self, options):
     """ starts recording inside VMware VM using the recording helper dll """
--- a/testing/mochitest/server.js
+++ b/testing/mochitest/server.js
@@ -657,16 +657,21 @@ function testListing(metadata, response)
             A({href: "#", id: "toggleNonTests"}, "Show Non-Tests"),
             BR()
           ),
     
           TABLE({cellpadding: 0, cellspacing: 0, id: "test-table"},
             TR(TD("Passed"), TD("Failed"), TD("Todo"), TD("Test Files")),
             linksToTableRows(links, 0)
           ),
+
+          BR(),
+          TABLE({cellpadding: 0, cellspacing: 0, border: 1, bordercolor: "red", id: "fail-table"}
+          ),
+
           DIV({class: "clear"})
         )
       )
     )
   );
 }
 
 /**
--- a/testing/mochitest/tests/SimpleTest/TestRunner.js
+++ b/testing/mochitest/tests/SimpleTest/TestRunner.js
@@ -32,16 +32,17 @@ function contentAsyncEvent(type, data) {
  *  * Avoid moving iframes: That causes reloads on mozilla and opera.
  *
  *
 **/
 var TestRunner = {};
 TestRunner.logEnabled = false;
 TestRunner._currentTest = 0;
 TestRunner.currentTestURL = "";
+TestRunner.originalTestURL = "";
 TestRunner._urls = [];
 
 TestRunner.timeout = 5 * 60 * 1000; // 5 minutes.
 TestRunner.maxTimeouts = 4; // halt testing after too many timeouts
 
 TestRunner.ipcMode = SpecialPowers.hasContentProcesses();
 TestRunner._expectingProcessCrash = false;
 
@@ -81,16 +82,22 @@ TestRunner._checkForHangs = function() {
   }
 }
 
 TestRunner.requestLongerTimeout = function(factor) {
     TestRunner._timeoutFactor = factor;
 }
 
 /**
+ * This is used to loop tests
+**/
+TestRunner.loops = 0;
+TestRunner._currentLoop = 0;
+
+/**
  * This function is called after generating the summary.
 **/
 TestRunner.onComplete = null;
 
 /**
  * If logEnabled is true, this is the logger that will be used.
 **/
 TestRunner.logger = MochiKit.Logging.logger;
@@ -119,17 +126,16 @@ TestRunner._toggle = function(el) {
         el.className = "";
         el.style.cssText = "";
     } else {
         el.className = "noshow";
         el.style.cssText = "width:0px; height:0px; border:0px;";
     }
 };
 
-
 /**
  * Creates the iframe that contains a test
 **/
 TestRunner._makeIframe = function (url, retry) {
     var iframe = $('testframe');
     if (url != "about:blank" &&
         (("hasFocus" in document && !document.hasFocus()) ||
          ("activeElement" in document && document.activeElement != iframe))) {
@@ -158,28 +164,72 @@ TestRunner._makeIframe = function (url, 
 /**
  * TestRunner entry point.
  *
  * The arguments are the URLs of the test to be ran.
  *
 **/
 TestRunner.runTests = function (/*url...*/) {
     TestRunner.log("SimpleTest START");
+    TestRunner.originalTestURL = $("current-test").innerHTML;
 
     SpecialPowers.registerProcessCrashObservers();
 
     TestRunner._urls = flattenArguments(arguments);
     $('testframe').src="";
     TestRunner._checkForHangs();
     window.focus();
     $('testframe').focus();
     TestRunner.runNextTest();
 };
 
 /**
+ * Used for running a set of tests in a loop for debugging purposes
+ * Takes an array of URLs
+**/
+TestRunner.resetTests = function(listURLs) {
+  TestRunner._currentTest = 0;
+  // Reset our "Current-test" line - functionality depends on it
+  $("current-test").innerHTML = TestRunner.originalTestURL;
+  if (TestRunner.logEnabled)
+    TestRunner.log("SimpleTest START Loop " + TestRunner._currentLoop);
+
+  TestRunner._urls = listURLs;
+  $('testframe').src="";
+  TestRunner._checkForHangs();
+  window.focus();
+  $('testframe').focus();
+  TestRunner.runNextTest();
+}
+
+/*
+ * Used to run a single test in a loop and update the UI with the results
+ */
+TestRunner.loopTest = function(testPath){
+ var numLoops = TestRunner.loops;
+  while(numLoops >= 0){
+    //must set the following line so that TestHarness.updateUI finds the right div to update
+    $("current-test-path").innerHTML = testPath;
+    function checkComplete() {
+      var testWindow = window.open(testPath, 'test window');
+      if (testWindow.document.readyState == "complete") {
+        TestRunner.currentTestURL = testPath;
+        TestRunner.updateUI(testWindow.SimpleTest._tests);
+        testWindow.close();
+      } else {
+        setTimeout(checkComplete, 1000);
+      }
+    }
+    checkComplete();
+    numLoops--;
+  }
+}
+
+/**
+/**
  * Run the next test. If no test remains, calls onComplete().
  **/
 TestRunner._haltTests = false;
 TestRunner.runNextTest = function() {
     if (TestRunner._currentTest < TestRunner._urls.length &&
         !TestRunner._haltTests)
     {
         var url = TestRunner._urls[TestRunner._currentTest];
@@ -211,21 +261,37 @@ TestRunner.runNextTest = function() {
           indicator.innerHTML = "Status: Fail (No checks actually run)";
           indicator.style.backgroundColor = "red";
         }
 
         TestRunner.log("TEST-START | Shutdown"); // used by automation.py
         TestRunner.log("Passed: " + $("pass-count").innerHTML);
         TestRunner.log("Failed: " + $("fail-count").innerHTML);
         TestRunner.log("Todo:   " + $("todo-count").innerHTML);
-        TestRunner.log("SimpleTest FINISHED");
+        // If we are looping, don't send this cause it closes the log file
+        if (TestRunner.loops == 0)
+          TestRunner.log("SimpleTest FINISHED");
 
-        if (TestRunner.onComplete) {
+        if (TestRunner.loops == 0 && TestRunner.onComplete) {
+             TestRunner.onComplete();
+         }
+ 
+        if (TestRunner._currentLoop < TestRunner.loops){
+          TestRunner._currentLoop++;
+          TestRunner.resetTests(TestRunner._urls);
+        } else {
+          // Loops are finished
+          if (TestRunner.logEnabled) {
+            TestRunner.log("TEST-INFO | Ran " + TestRunner._currentLoop + " Loops");
+            TestRunner.log("SimpleTest FINISHED");
+          }
+
+          if (TestRunner.onComplete)
             TestRunner.onComplete();
-        }
+       }
     }
 };
 
 TestRunner.expectChildProcessCrash = function() {
     TestRunner._expectingProcessCrash = true;
 };
 
 /**
@@ -287,16 +353,57 @@ TestRunner.countResults = function(tests
       nOK++;
     } else {
       nNotOK++;
     }
   }
   return {"OK": nOK, "notOK": nNotOK, "todo": nTodo};
 }
 
+/**
+ * Print out table of any error messages found during looped run
+ */
+TestRunner.displayLoopErrors = function(tableName, tests) {
+  if(TestRunner.countResults(tests).notOK >0){
+    var table = $(tableName);
+    var curtest;
+    if (table.rows.length == 0) {
+      //if table headers are not yet generated, make them
+      var row = table.insertRow(table.rows.length); 
+      var cell = row.insertCell(0);
+      var textNode = document.createTextNode("Test File Name:");
+      cell.appendChild(textNode);
+      cell = row.insertCell(1);
+      textNode = document.createTextNode("Test:");
+      cell.appendChild(textNode);
+      cell = row.insertCell(2);
+      textNode = document.createTextNode("Error message:");
+      cell.appendChild(textNode);
+    }
+  
+    //find the broken test
+    for (var testnum in tests){
+      curtest = tests[testnum];
+      if( !((curtest.todo && !curtest.result) || (curtest.result && !curtest.todo)) ){
+        //this is a failed test or the result of todo test. Display the related message
+        row = table.insertRow(table.rows.length); 
+        cell = row.insertCell(0);
+        textNode = document.createTextNode(TestRunner.currentTestURL);
+        cell.appendChild(textNode);
+        cell = row.insertCell(1);
+        textNode = document.createTextNode(curtest.name);
+        cell.appendChild(textNode);
+        cell = row.insertCell(2);
+        textNode = document.createTextNode((curtest.diag ? curtest.diag : "" ));
+        cell.appendChild(textNode);
+      }
+    }
+  }
+}
+
 TestRunner.updateUI = function(tests) {
   var results = TestRunner.countResults(tests);
   var passCount = parseInt($("pass-count").innerHTML) + results.OK;
   var failCount = parseInt($("fail-count").innerHTML) + results.notOK;
   var todoCount = parseInt($("todo-count").innerHTML) + results.todo;
   $("pass-count").innerHTML = passCount;
   $("fail-count").innerHTML = failCount;
   $("todo-count").innerHTML = todoCount;
@@ -314,14 +421,19 @@ TestRunner.updateUI = function(tests) {
     indicator.style.backgroundColor = "orange";
   }
 
   // Set the table values
   var trID = "tr-" + $('current-test-path').innerHTML;
   var row = $(trID);
   var tds = row.getElementsByTagName("td");
   tds[0].style.backgroundColor = "#0d0";
-  tds[0].innerHTML = results.OK;
+  tds[0].innerHTML = parseInt(tds[0].innerHTML) + parseInt(results.OK);
   tds[1].style.backgroundColor = results.notOK > 0 ? "red" : "#0d0";
-  tds[1].innerHTML = results.notOK;
+  tds[1].innerHTML = parseInt(tds[1].innerHTML) + parseInt(results.notOK);
   tds[2].style.backgroundColor = results.todo > 0 ? "orange" : "#0d0";
-  tds[2].innerHTML = results.todo;
+  tds[2].innerHTML = parseInt(tds[2].innerHTML) + parseInt(results.todo);
+
+  //if we ran in a loop, display any found errors
+  if(TestRunner.loops > 0){
+    TestRunner.displayLoopErrors('fail-table', tests);
+  }
 }
--- a/testing/mochitest/tests/SimpleTest/setup.js
+++ b/testing/mochitest/tests/SimpleTest/setup.js
@@ -64,16 +64,21 @@ if (config.testRoot == "chrome" || confi
 if (params.timeout) {
   TestRunner.timeout = parseInt(params.timeout) * 1000;
 }
 
 // log levels for console and logfile
 var fileLevel =  params.fileLevel || null;
 var consoleLevel = params.consoleLevel || null;
 
+// loop tells us how many times to run the tests
+if (params.loops) {
+  TestRunner.loops = params.loops;
+} 
+
 // closeWhenDone tells us to call quit.js when complete
 if (params.closeWhenDone) {
   TestRunner.onComplete = goQuitApplication;
 }
 
 // logFile to write our results
 if (params.logFile) {
   MozillaFileLogger.init(params.logFile);
@@ -149,29 +154,29 @@ RunSet.runall = function(e) {
       var j = Math.floor(Math.random() * i);
       var tmp = my_tests[j];
       my_tests[j] = my_tests[i];
       my_tests[i] = tmp;
     }
   }
   TestRunner.runTests(my_tests);
 }
+
 RunSet.reloadAndRunAll = function(e) {
   e.preventDefault();
   //window.location.hash = "";
   var addParam = "";
   if (params.autorun) {
     window.location.search += "";
     window.location.href = window.location.href;
   } else if (window.location.search) {
     window.location.href += "&autorun=1";
   } else {
     window.location.href += "?autorun=1";
-  }
-  
+  }  
 };
 
 // UI Stuff
 function toggleVisible(elem) {
     toggleElementClass("invisible", elem);
 }
 
 function makeVisible(elem) {
@@ -200,13 +205,13 @@ function toggleNonTests (e) {
     $("toggleNonTests").innerHTML = "Show Non-Tests";
   }
 }
 
 // hook up our buttons
 function hookup() {
   connect("runtests", "onclick", RunSet, "reloadAndRunAll");
   connect("toggleNonTests", "onclick", toggleNonTests);
-  // run automatically if
+  // run automatically if autorun specified
   if (params.autorun) {
     RunSet.runall();
   }
 }
--- a/toolkit/components/alerts/nsAlertsService.cpp
+++ b/toolkit/components/alerts/nsAlertsService.cpp
@@ -35,41 +35,42 @@
  * 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 "mozilla/dom/ContentChild.h"
 #include "nsXULAppAPI.h"
-using mozilla::dom::ContentChild;
 
 #include "nsAlertsService.h"
 
 #ifdef ANDROID
 #include "AndroidBridge.h"
 #else
 
 #include "nsISupportsArray.h"
 #include "nsXPCOM.h"
 #include "nsISupportsPrimitives.h"
 #include "nsIServiceManager.h"
-#include "nsIDOMWindowInternal.h"
+#include "nsIDOMWindow.h"
 #include "nsIWindowWatcher.h"
 #include "nsDependentString.h"
 #include "nsWidgetsCID.h"
 #include "nsILookAndFeel.h"
 #include "nsToolkitCompsCID.h"