Index: modules/overlay/overlay-parent.css
===================================================================
RCS file: /cvs/drupal/drupal/modules/overlay/overlay-parent.css,v
retrieving revision 1.3
diff -u -r1.3 overlay-parent.css
--- modules/overlay/overlay-parent.css	15 Dec 2009 05:28:59 -0000	1.3
+++ modules/overlay/overlay-parent.css	20 Dec 2009 14:49:40 -0000
@@ -66,17 +66,17 @@
 .overlay #overlay-container {
   margin: 0;
   padding: 0;
+  width: 100%;
   overflow: visible;
   background: #fff url(images/loading.gif) no-repeat 50% 50%;
-  -webkit-box-shadow: 8px 8px 8px rgba(0,0,0,.5);
-  -moz-box-shadow: 8px 8px 8px rgba(0,0,0,.5);
-  box-shadow: 8px 8px 8px rgba(0,0,0,.5);
 }
 .overlay-loaded #overlay-container {
-  background: none;
+  background: #fff;
 }
 .overlay #overlay-element {
   overflow: hidden;
+  width: 100%;
+  height: 100%;
 }
 
 /**
@@ -96,6 +96,20 @@
   margin: 0 0 0 -3px;
   padding: 0;
 }
+/**
+ * CSS Hack for IE 7 and below.
+ * http://www.webdevout.net/css-hacks#in_css-selectors
+ */
+*:first-child+html .overlay .ui-dialog-titlebar ul li {
+  display: inline;
+}
+* html .overlay .ui-dialog-titlebar ul li {
+  display: inline;
+}
+/**
+ * End of CSS Hack for IE 7 and below.
+ */
+
 .overlay .ui-dialog-titlebar ul li a,
 .overlay .ui-dialog-titlebar ul li a:active,
 .overlay .ui-dialog-titlebar ul li a:visited,
Index: modules/overlay/overlay-parent.js
===================================================================
RCS file: /cvs/drupal/drupal/modules/overlay/overlay-parent.js,v
retrieving revision 1.7
diff -u -r1.7 overlay-parent.js
--- modules/overlay/overlay-parent.js	15 Dec 2009 05:28:59 -0000	1.7
+++ modules/overlay/overlay-parent.js	20 Dec 2009 14:49:40 -0000
@@ -29,8 +29,8 @@
     $('#toolbar a.toggle', context).once('overlay').click(function () {
       setTimeout(function () {
         // Resize the overlay, if it's open.
-        if (Drupal.overlay.iframe.documentSize) {
-          Drupal.overlay.resize(Drupal.overlay.iframe.documentSize);
+        if (Drupal.overlay.isOpen) {
+          Drupal.overlay.autoResize();
         }
       }, 150);
     });
@@ -65,8 +65,24 @@
  */
 Drupal.overlay = Drupal.overlay || {
   options: {},
-  iframe: { $container: null, $element: null },
-  isOpen: false
+  isOpen: false,
+  isOpening: false,
+  isClosing: false,
+  isLoading: false,
+
+  onOverlayCloseArgs: null,
+  onOverlayCloseStatusMessages: null,
+
+  resizeTimeoutID: null,
+
+  $dialog: null,
+  $dialogTitlebar: null,
+  $container: null,
+  $iframe: null,
+
+  $iframeWindow: null,
+  $iframeDocument: null,
+  $iframeBody: null
 };
 
 /**
@@ -95,9 +111,10 @@
   var self = this;
 
   // Just one overlay is allowed.
-  if (self.isOpen || $('#overlay-container').size()) {
+  if (self.isOpen || self.isOpening) {
     return false;
   }
+  self.isOpening = true;
 
   var defaultOptions = {
     url: options.url,
@@ -108,7 +125,7 @@
     onOverlayCanClose: options.onOverlayCanClose,
     onOverlayClose: options.onOverlayClose,
     customDialogOptions: options.customDialogOptions || {}
-  }
+  };
 
   self.options = $.extend(defaultOptions, options);
 
@@ -116,7 +133,7 @@
   self.create();
 
   // Open the dialog offscreen where we can set its size, etc.
-  var temp = self.iframe.$container.dialog('option', { position: ['-999em', '-999em'] }).dialog('open');;
+  self.$container.dialog('open');
 
   return true;
 };
@@ -130,109 +147,112 @@
 Drupal.overlay.create = function () {
   var self = this;
 
-  self.iframe.$element = $(Drupal.theme('overlayElement'));
-  self.iframe.$container = $(Drupal.theme('overlayContainer')).append(self.iframe.$element);
-
-  $('body').append(self.iframe.$container);
+  self.$iframe = $(Drupal.theme('overlayElement'));
+  self.$container = $(Drupal.theme('overlayContainer')).append(self.$iframe);
 
   // Open callback for jQuery UI Dialog.
   var dialogOpen = function () {
+    // Adjust overlay size when window is resized.
+    $(window).bind('resize', self.autoResize);
+
     // Unbind the keypress handler installed by ui.dialog itself.
     // IE does not fire keypress events for some non-alphanumeric keys
     // such as the tab character. http://www.quirksmode.org/js/keys.html
     // Also, this is not necessary here because we need to deal with an
     // iframe element that contains a separate window.
     // We'll try to provide our own behavior from bindChild() method.
-    $('.overlay').unbind('keypress.ui-dialog');
+    self.$dialog.unbind('keypress.ui-dialog');
 
-    // Adjust close button features.
-    $('.overlay .ui-dialog-titlebar-close:not(.overlay-processed)').addClass('overlay-processed')
-      .attr('href', '#')
-      .attr('title', Drupal.t('Close'))
-      .unbind('click')
-      .bind('click', function () {
-        try { self.close(); } catch(e) {}
-        // Allow the click event to propagate, to clear the hash state.
-        return true;
-      });
+    // Add title to close button features for accessibility.
+    self.$dialogTitlebar.find('.ui-dialog-titlebar-close').attr('title', Drupal.t('Close'));
 
     // Replace the title span element with an h1 element for accessibility.
-    $('.overlay .ui-dialog-title').replaceWith(Drupal.theme('overlayTitleHeader', $('.overlay .ui-dialog-title').html()));
+    var $dialogTitle = self.$dialogTitlebar.find('.ui-dialog-title');
+    $dialogTitle.replaceWith(Drupal.theme('overlayTitleHeader', $dialogTitle.html()));
 
     // Compute initial dialog size.
-    var dialogSize = self.sanitizeSize({width: self.options.width, height: self.options.height});
-
-    // Compute frame size and dialog position based on dialog size.
-    var frameSize = $.extend({}, dialogSize);
-    frameSize.height -= $('.overlay .ui-dialog-titlebar').outerHeight(true);
-    var dialogPosition = self.computePosition($('.overlay'), dialogSize);
-
-    // Adjust size of the iframe element and container.
-    $('.overlay').width(dialogSize.width).height(dialogSize.height);
-    self.iframe.$container.width(frameSize.width).height(frameSize.height);
-    self.iframe.$element.width(frameSize.width).height(frameSize.height);
+    self.resize({width: self.options.width, height: 100}, true);
+    self.resize({});
 
-    // Update the dialog size so that UI internals are aware of the change.
-    self.iframe.$container.dialog('option', { width: dialogSize.width, height: dialogSize.height });
-
-    // Hide the dialog, position it on the viewport and then fade it in with
-    // the frame hidden until the child document is loaded.
-    self.iframe.$element.hide();
-    $('.overlay').hide().css({top: dialogPosition.top, left: dialogPosition.left});
-    $('.overlay').fadeIn('fast', function () {
-      // Load the document on hidden iframe (see bindChild method).
-      self.load(self.options.url);
-    });
+    // Load the document on hidden iframe (see bindChild method).
+    self.load(self.options.url);
 
     if ($.isFunction(self.options.onOverlayOpen)) {
       self.options.onOverlayOpen(self);
     }
 
     self.isOpen = true;
+    self.isOpening = false;
   };
 
   // Before close callback for jQuery UI Dialog.
   var dialogBeforeClose = function () {
-    if (self.beforeCloseEnabled) {
-      return true;
+    // Prevent double execution when close is requested more than once.
+    if (!self.isOpen || self.isClosing) {
+      return false;
     }
-    if (!self.beforeCloseIsBusy) {
-      self.beforeCloseIsBusy = true;
-      setTimeout(function () { self.close(); }, 1);
+
+    // Allow external scripts decide if the overlay can be closed.
+    // The external script should call Drupal.overlay.close() again when it is ready for closing.
+    if ($.isFunction(self.options.onOverlayCanClose) && self.options.onOverlayCanClose(self) === false) {
+      return false;
     }
-    return false;
+
+    self.isClosing = true;
+
+    // Stop all animations.
+    $(window).unbind('resize', self.autoResize);
+    clearTimeout(self.resizeTimeoutID);
+    self.$dialog.stop();
+    self.$container.stop();
+    self.$iframe.stop();
+
+    // Close overlay with an animation.
+    self.$container.animate({height: 'hide'}, { duration: 'fast', 'queue': false });
+    self.$dialog.animate({opacity: 'hide'});
   };
 
   // Close callback for jQuery UI Dialog.
   var dialogClose = function () {
     $(document).unbind('keydown.overlay-event');
-    $('.overlay .ui-dialog-titlebar-close').unbind('keydown.overlay-event');
-    try {
-      self.iframe.$element.remove();
-      self.iframe.$container.dialog('destroy').remove();
-    } catch(e) {};
-    delete self.iframe.documentSize;
-    delete self.iframe.Drupal;
-    delete self.iframe.$element;
-    delete self.iframe.$container;
-    if (self.beforeCloseEnabled) {
-      delete self.beforeCloseEnabled;
-    }
-    if (self.beforeCloseIsBusy) {
-      delete self.beforeCloseIsBusy;
+
+    if (!self.isLoading) {
+      self.$container.dialog('destroy').remove();
+
+      self.$dialog = null;
+      self.$dialogTitlebar = null;
+      self.$container = null;
+      self.$iframe = null;
+
+      self.$iframeWindow = null;
+      self.$iframeDocument = null;
+      self.$iframeBody = null;
     }
+
     self.isOpen = false;
+    self.isClosing = false;
+
+    if ($.isFunction(self.options.onOverlayClose)) {
+      self.options.onOverlayClose(self.onOverlayCloseArgs, self.onOverlayCloseStatusMessages);
+    }
+    self.onOverlayCloseArgs = null;
+    self.onOverlayCloseStatusMessages = null;
   };
 
   // Default jQuery UI Dialog options.
   var dialogOptions = {
-    modal: true,
     autoOpen: false,
     closeOnEscape: true,
+    dialogClass: 'overlay',
+    draggable: false,
+    modal: true,
     resizable: false,
     title: Drupal.t('Loading...'),
-    dialogClass: 'overlay',
     zIndex: 500,
+
+    // Make sure hiding is queued so we can add animations in dialogBeforeClose().
+    hide: 'fast',
+
     open: dialogOpen,
     beforeclose: dialogBeforeClose,
     close: dialogClose
@@ -242,7 +262,10 @@
   $.extend(dialogOptions, self.options.customDialogOptions);
 
   // Create the jQuery UI Dialog.
-  self.iframe.$container.dialog(dialogOptions);
+  self.$container.dialog(dialogOptions);
+  // Cache dialog selector.
+  self.$dialog = self.$container.parents('.' + dialogOptions.dialogClass);
+  self.$dialogTitlebar = self.$dialog.find('.ui-dialog-titlebar');
 };
 
 /**
@@ -253,40 +276,58 @@
  */
 Drupal.overlay.load = function (url) {
   var self = this;
-  var iframe = self.iframe.$element.get(0);
-  
-  // Add a loaded class to the overlay once the iframe is loaded.
-  $(iframe).load(function () {
-    $('.overlay').addClass('overlay-loaded');
+  var iframeElement = self.$iframe.get(0);
+
+  self.isLoading = true;
+
+  self.$iframeWindow = null;
+  self.$iframeDocument = null;
+  self.$iframeBody = null;
+
+  // No need to resize when loading.
+  clearTimeout(self.resizeTimeoutID);
+
+  // Change the overlay title.
+  self.$container.dialog('option', 'title', Drupal.t('Loading...'));
+
+  // When a new page is being loaded we fade the iframe to 20% opacity and remove
+  // the loaded class from the overlay. Once the page is loaded we restore the
+  // iframe opacity and add the loaded class back to the overlay.
+  self.$dialog.removeClass('overlay-loaded');
+  self.$iframe
+    .fadeTo('fast', .2)
+    .load(function () {
+      self.isLoading = false;
+
+      if (self.isOpen && !self.isClosing) {
+        self.$iframe.fadeTo('fast', 1);
+        self.$dialog.addClass('overlay-loaded');
+      }
+      else {
+        self.$container.dialog('destroy').remove();
+
+        self.$dialog = null;
+        self.$dialogTitlebar = null;
+        self.$container = null;
+        self.$iframe = null;
+
+        self.$iframeWindow = null;
+        self.$iframeDocument = null;
+        self.$iframeBody = null;
+      }
   });
-  
+
   // Get the document object of the iframe window.
   // @see http://xkr.us/articles/dom/iframe-document/
-  var doc = (iframe.contentWindow || iframe.contentDocument);
-  if (doc.document) {
-    doc = doc.document;
+  var iframeDocument = (iframeElement.contentWindow || iframeElement.contentDocument);
+  if (iframeDocument.document) {
+    iframeDocument = iframeDocument.document;
   }
+
   // location.replace doesn't create a history entry. location.href does.
   // In this case, we want location.replace, as we're creating the history
   // entry using URL fragments.
-  doc.location.replace(url);
-};
-
-/**
- * Check if the dialog can be closed.
- */
-Drupal.overlay.canClose = function () {
-  var self = this;
-  if (!self.isOpen) {
-    return false;
-  }
-  // Allow external scripts decide if the overlay can be closed.
-  if ($.isFunction(self.options.onOverlayCanClose)) {
-    if (!self.options.onOverlayCanClose(self)) {
-      return false;
-    }
-  }
-  return true;
+  iframeDocument.location.replace(url);
 };
 
 /**
@@ -295,40 +336,10 @@
 Drupal.overlay.close = function (args, statusMessages) {
   var self = this;
 
-  // Offer the user a chance to change their mind if there is a form on the
-  // page, which may have unsaved work on it.
-  var iframeElement = self.iframe.$element.get(0);
-  var iframeDocument = (iframeElement.contentWindow || iframeElement.contentDocument);
-  if (iframeDocument.document) {
-    iframeDocument = iframeDocument.document;
-  }
-
-  // Check if the dialog can be closed.
-  if (!self.canClose()) {
-    delete self.beforeCloseIsBusy;
-    return false;
-  }
+  self.onOverlayCloseArgs = args;
+  self.onOverlayCloseStatusMessages = statusMessages;
 
-  // Hide and destroy the dialog.
-  function closeDialog() {
-    // Prevent double execution when close is requested more than once.
-    if (!$.isObject(self.iframe.$container)) {
-      return;
-    }
-    self.beforeCloseEnabled = true;
-    self.iframe.$container.dialog('close');
-    if ($.isFunction(self.options.onOverlayClose)) {
-      self.options.onOverlayClose(args, statusMessages);
-    }
-  }
-  if (!$.isObject(self.iframe.$element) || !self.iframe.$element.size() || !self.iframe.$element.is(':visible')) {
-    closeDialog();
-  }
-  else {
-    self.iframe.$container.animate({height: 'hide'}, { duration: 'fast', 'queue': false });
-    $('.overlay').animate({opacity: 'hide'}, closeDialog);
-  }
-  return true;
+  return self.$container.dialog('close');
 };
 
 /**
@@ -344,203 +355,180 @@
   }
   location.href = link;
   return true;
-}
+};
 
 /**
  * Bind the child window.
  *
  * Add tabs on the overlay, keyboard actions and display animation.
  */
-Drupal.overlay.bindChild = function (iFrameWindow, isClosing) {
+Drupal.overlay.bindChild = function (iframeWindow, isClosing) {
   var self = this;
-  var $iFrameWindow = iFrameWindow.jQuery;
-  var $iFrameDocument = $iFrameWindow(iFrameWindow.document);
-  var autoResizing = false;
-  self.iframe.Drupal = iFrameWindow.Drupal;
+  self.$iframeWindow = iframeWindow.jQuery;
+  self.$iframeDocument = self.$iframeWindow(iframeWindow.document);
+  self.$iframeBody = self.$iframeWindow('body');
 
   // We are done if the child window is closing.
-  if (isClosing) {
+  if (isClosing || self.isClosing || !self.isOpen) {
     return;
   }
 
   // Make sure the parent window URL matches the child window URL.
-  self.syncChildLocation($iFrameDocument[0].location);
+  self.syncChildLocation(iframeWindow.document.location);
+
+  // Reset the scroll to the top of the window so that the overlay is visible again.
+  window.scrollTo(0, 0);
+
+  var iframeTitle = self.$iframeDocument.attr('title');
+
   // Update the dialog title with the child window title.
-  $('.overlay .ui-dialog-title').html($iFrameDocument.attr('title')).focus();
+  self.$container.dialog('option', 'title', iframeTitle);
+  self.$dialogTitlebar.find('.ui-dialog-title').focus();
   // Add a title attribute to the iframe for accessibility.
-  self.iframe.$element.attr('title', Drupal.t('@title dialog', { '@title': $iFrameDocument.attr('title') }));
+  self.$iframe.attr('title', Drupal.t('@title dialog', { '@title': iframeTitle }));
 
+  // Remove any existing shortcut button markup in the title section.
+  self.$dialogTitlebar.find('.add-or-remove-shortcuts').remove();
   // If the shortcut add/delete button exists, move it to the dialog title.
-  var addToShortcuts = $('.add-or-remove-shortcuts', $iFrameDocument);
-  if (addToShortcuts.length) {
-    // Remove any existing shortcut button markup in the title section.
-    $('.ui-dialog-titlebar .add-or-remove-shortcuts').remove();
+  var $addToShortcuts = self.$iframeWindow('.add-or-remove-shortcuts');
+  if ($addToShortcuts.length) {
     // Make the link overlay-friendly.
-    var $link = $('a', addToShortcuts);
+    var $link = $('a', $addToShortcuts);
     $link.attr('href', Drupal.overlay.fragmentizeLink($link.get(0)));
     // Move the button markup to the title section. We need to copy markup
-    // instead of moving the DOM element, because Webkit browsers will not
-    // move DOM elements between two DOM documents.
-    var shortcutsMarkup = '<div class="' + $(addToShortcuts).attr('class') + '">' + $(addToShortcuts).html() + '</div>';
-    $('.overlay .ui-dialog-title').after(shortcutsMarkup);
-    $('.add-or-remove-shortcuts', $iFrameDocument).remove();
-  }
-
-  // Remove any existing tabs.
-  $('.overlay .ui-dialog-titlebar ul').remove();
-
-  // Setting tabIndex makes the div focusable.
-  $iFrameDocument.attr('tabindex', -1);
-
-  $('.ui-dialog-titlebar-close-bg').animate({opacity: 0.9999}, 'fast');
-
-  // Perform animation to show the iframe element.
-  self.iframe.$element.fadeIn('fast', function () {
-    // @todo: Watch for experience in the way we compute the size of the
-    // iframed document. There are many ways to do it, and none of them
-    // seem to be perfect. Note though, that the size of the iframe itself
-    // may affect the size of the child document, especially on fluid layouts.
-    self.iframe.documentSize = { width: $iFrameDocument.width(), height: $iFrameWindow('body').height() + 25 };
-
-    // Adjust overlay to fit the iframe content?
-    if (self.options.autoFit) {
-      self.resize(self.iframe.documentSize);
-    }
-
-    // Try to enhance keyboard based navigation of the overlay.
-    // Logic inspired by the open() method in ui.dialog.js, and
-    // http://wiki.codetalks.org/wiki/index.php/Docs/Keyboard_navigable_JS_widgets
-
-    // Get a reference to the close button.
-    var $closeButton = $('.overlay .ui-dialog-titlebar-close');
-
-    // Search tabbable elements on the iframed document to speed up related
-    // keyboard events.
-    // @todo: Do we need to provide a method to update these references when
-    // AJAX requests update the DOM on the child document?
-    var $iFrameTabbables = $iFrameWindow(':tabbable:not(form)');
-    var $firstTabbable = $iFrameTabbables.filter(':first');
-    var $lastTabbable = $iFrameTabbables.filter(':last');
-
-    // Unbind keyboard event handlers that may have been enabled previously.
-    $(document).unbind('keydown.overlay-event');
-    $closeButton.unbind('keydown.overlay-event');
-
-    // When the focus leaves the close button, then we want to jump to the
-    // first/last inner tabbable element of the child window.
-    $closeButton.bind('keydown.overlay-event', function (event) {
-      if (event.keyCode && event.keyCode == $.ui.keyCode.TAB) {
-        var $target = (event.shiftKey ? $lastTabbable : $firstTabbable);
-        if (!$target.size()) {
-          $target = $iFrameDocument;
-        }
-        setTimeout(function () { $target.focus(); }, 10);
-        return false;
+    // instead of moving the DOM element, because Webkit and IE browsers will
+    // not move DOM elements between two DOM documents.
+    var shortcutsMarkup = '<div class="' + $($addToShortcuts).attr('class') + '">' + $($addToShortcuts).html() + '</div>';
+    self.$dialogTitlebar.find('.ui-dialog-title').after(shortcutsMarkup);
+    self.$iframeWindow('.add-or-remove-shortcuts').remove();
+  }
+
+  // Remove any existing tabs in the title section.
+  self.$dialogTitlebar.find('ul').remove();
+  // If there are tabs in the page, move them to the titlebar.
+  var $tabs = self.$iframeWindow('ul.primary');
+  if ($tabs.length) {
+    // Move the tabs markup to the title section. We need to copy markup
+    // instead of moving the DOM element, because Webkit and IE browsers will
+    // not move DOM elements between two DOM documents.
+    $tabs = $(self.$iframeWindow('<div>').append($tabs.clone()).remove().html());
+
+    self.$dialogTitlebar.append($tabs);
+    if ($tabs.is('.primary')) {
+      $tabs.find('a').removeClass('overlay-processed');
+      Drupal.attachBehaviors($tabs);
+    }
+    // Remove any classes from the list element to avoid theme styles
+    // clashing with our styling.
+    $tabs.removeAttr('class');
+  }
+
+  // Try to enhance keyboard based navigation of the overlay.
+  // Logic inspired by the open() method in ui.dialog.js, and
+  // http://wiki.codetalks.org/wiki/index.php/Docs/Keyboard_navigable_JS_widgets
+
+  // Get a reference to the close button.
+  var $closeButton = self.$dialogTitlebar.find('.ui-dialog-titlebar-close');
+
+  // Search tabbable elements on the iframed document to speed up related
+  // keyboard events.
+  // @todo: Do we need to provide a method to update these references when
+  // AJAX requests update the DOM on the child document?
+  var $iframeTabbables = self.$iframeWindow(':tabbable:not(form)');
+  var $firstTabbable = $iframeTabbables.filter(':first');
+  var $lastTabbable = $iframeTabbables.filter(':last');
+
+  // Unbind keyboard event handlers that may have been enabled previously.
+  $(document).unbind('keydown.overlay-event');
+  $closeButton.unbind('keydown.overlay-event');
+
+  // When the focus leaves the close button, then we want to jump to the
+  // first/last inner tabbable element of the child window.
+  $closeButton.bind('keydown.overlay-event', function (event) {
+    if (event.keyCode && event.keyCode == $.ui.keyCode.TAB) {
+      var $target = (event.shiftKey ? $lastTabbable : $firstTabbable);
+      if (!$target.size()) {
+        $target = self.$iframeDocument;
       }
-    });
+      setTimeout(function () { $target.focus(); }, 10);
+      return false;
+    }
+  });
 
-    // When the focus leaves the child window, then drive the focus to the
-    // close button of the dialog.
-    $iFrameDocument.bind('keydown.overlay-event', function (event) {
-      if (event.keyCode) {
-        if (event.keyCode == $.ui.keyCode.TAB) {
-          if (event.shiftKey && event.target == $firstTabbable.get(0)) {
-            setTimeout(function () { $closeButton.focus(); }, 10);
-            return false;
-          }
-          else if (!event.shiftKey && event.target == $lastTabbable.get(0)) {
-            setTimeout(function () { $closeButton.focus(); }, 10);
-            return false;
-          }
+  // When the focus leaves the child window, then drive the focus to the
+  // close button of the dialog.
+  self.$iframeDocument.bind('keydown.overlay-event', function (event) {
+    if (event.keyCode) {
+      if (event.keyCode == $.ui.keyCode.TAB) {
+        if (event.shiftKey && event.target == $firstTabbable.get(0)) {
+          setTimeout(function () { $closeButton.focus(); }, 10);
+          return false;
         }
-        else if (event.keyCode == $.ui.keyCode.ESCAPE) {
-          setTimeout(function () { self.close(); }, 10);
+        else if (!event.shiftKey && event.target == $lastTabbable.get(0)) {
+          setTimeout(function () { $closeButton.focus(); }, 10);
           return false;
         }
       }
-    });
-
-    var autoResize = function () {
-      if (typeof self.iframe.$element == 'undefined') {
-        autoResizing = false;
-        $(window).unbind('resize', windowResize);
-        return;
-      }
-      var iframeElement = self.iframe.$element.get(0);
-      var iframeDocument = (iframeElement.contentWindow || iframeElement.contentDocument);
-      if (iframeDocument.document) {
-        iframeDocument = iframeDocument.document;
+      else if (event.keyCode == $.ui.keyCode.ESCAPE) {
+        setTimeout(function () { self.close(); }, 10);
+        return false;
       }
-      // Use outerHeight() because otherwise the calculation will be off
-      // because of padding and/or border added by the theme.
-      var height = $(iframeDocument).find('body').outerHeight() + 25;
-      self.iframe.$element.css('height', height);
-      self.iframe.$container.css('height', height);
-      self.iframe.$container.parent().css('height', height + 45);
-      // Don't allow the shadow background to shrink so it's not enough to hide
-      // the whole page. Take the existing document height (with overlay) and
-      // the body height itself for our base calculation.
-      var docHeight = Math.min($(document).find('body').outerHeight(), $(document).height());
-      $('.ui-widget-overlay').height(Math.max(docHeight, $(window).height(), height + 145));
-      setTimeout(autoResize, 150);
-    };
-
-    var windowResize = function () {
-      var width = $(window).width()
-      var change = lastWidth - width;
-      var currentWidth = self.iframe.$element.width();
-      var newWidth = lastFrameWidth - change;
-      lastWidth = width;
-      lastFrameWidth = newWidth;
-
-      if (newWidth >= 300) {
-        self.iframe.$element.css('width', newWidth);
-        self.iframe.$container.css('width', newWidth);
-        self.iframe.$container.parent().css('width', newWidth);
-        widthBelowMin = false;
+    }
+  });
+
+  // When the focus is captured by the parent document, then try
+  // to drive the focus back to the first tabbable element, or the
+  // close button of the dialog (default).
+  $(document).bind('keydown.overlay-event', function (event) {
+    if (event.keyCode && event.keyCode == $.ui.keyCode.TAB) {
+      setTimeout(function () {
+        if (!self.$iframeWindow(':tabbable:not(form):first').focus().size()) {
+          $closeButton.focus();
+        }
+      }, 10);
+      return false;
+    }
+  });
+
+  self.autoResize();
+
+  // Adjust overlay to fit the iframe content?
+  if (self.options.autoFit) {
+    if (document.implementation.hasFeature('MutationEvents','2.0') || window.MutationEvent) {
+      var delayedResize = function() {
+        clearTimeout(self.resizeTimeoutID);
+        self.resizeTimeoutID = setTimeout(self.autoResize, 150);
+      };
+
+      // Bind the autoResize callback to DOM changes of the iframe.
+      if ($.browser.opera) {
+        // Opera doesn't support the DOMSubtreeModified event.
+        self.$iframeDocument.bind('DOMAttrModified', delayedResize);
+        self.$iframeDocument.bind('DOMNodeInserted', delayedResize);
+        self.$iframeDocument.bind('DOMNodeRemoved', delayedResize);
       }
       else {
-        widthBelowMin = true;
+        self.$iframeDocument.bind('DOMSubtreeModified', delayedResize);
       }
     }
+    // IE and possibly other browsers don't support MutationEvents.
+    else if (!self.autoResizing) {
+      var delayedResize = function() {
+        if (!(self.isOpen && self.resizeTimeoutID)) {
+          self.resizeTimeoutID = null;
+          return;
+        }
 
-    if (!autoResizing) {
-      autoResizing = true;
-      autoResize();
-      var lastFrameWidth = self.iframe.$element.width();
-      var lastWidth = $(window).width();
-      $(window).resize(windowResize);
-    }
-
-    // When the focus is captured by the parent document, then try
-    // to drive the focus back to the first tabbable element, or the
-    // close button of the dialog (default).
-    $(document).bind('keydown.overlay-event', function (event) {
-      if (event.keyCode && event.keyCode == $.ui.keyCode.TAB) {
-        setTimeout(function () {
-          if (!$iFrameWindow(':tabbable:not(form):first').focus().size()) {
-            $closeButton.focus();
-          }
-        }, 10);
-        return false;
-      }
-    });
-
-    // If there are tabs in the page, move them to the titlebar.
-    var tabs = $iFrameDocument.find('ul.primary').get(0);
+        self.autoResize();
+        self.$dialog.queue(function() {
+          self.resizeTimeoutID = setTimeout(delayedResize, 1000);
+          self.$dialog.dequeue();
+        });
+      };
 
-    // This breaks in anything less than IE 7. Prevent it from running.
-    if (typeof tabs != 'undefined' && (!$.browser.msie || parseInt($.browser.version) >= 7)) {
-      $('.ui-dialog-titlebar').append($(tabs).remove().get(0));
-      if ($(tabs).is('.primary')) {
-        $(tabs).find('a').removeClass('overlay-processed');
-        Drupal.attachBehaviors($(tabs));
-      }
-      // Remove any classes from the list element to avoid theme styles
-      // clashing with our styling.
-      $(tabs).removeAttr('class');
+      self.resizeTimeoutID = setTimeout(delayedResize, 1000);
     }
-  });
+  }
 };
 
 /**
@@ -548,18 +536,19 @@
  *
  * Remove keyboard event handlers, reset title and hide the iframe.
  */
-Drupal.overlay.unbindChild = function (iFrameWindow) {
+Drupal.overlay.unbindChild = function (iframeWindow) {
   var self = this;
+  var $iframeDocument = iframeWindow.jQuery(iframeWindow.document);
 
   // Prevent memory leaks by explicitly unbinding keyboard event handler
   // on the child document.
-  iFrameWindow.jQuery(iFrameWindow.document).unbind('keydown.overlay-event');
+  $iframeDocument.unbind('keydown.overlay-event');
 
   // Change the overlay title.
-  $('.overlay .ui-dialog-title').html(Drupal.t('Please wait...'));
+  self.$container.dialog('option', 'title', Drupal.t('Please wait...'));
 
   // Hide the iframe element.
-  self.iframe.$element.fadeOut('fast');
+  self.$iframe.fadeOut('fast');
 };
 
 /**
@@ -600,117 +589,135 @@
   }
 
   return self.adminPathRegExp.exec(path) && !self.nonAdminPathRegExp.exec(path);
-}
+};
 
 /**
- * Sanitize dialog size.
+ * Resize overlay to the given size.
  *
- * Do not let the overlay go over the 0.78x of the width of the screen and set
- * minimal height. The height is not limited due to how we rely on the parent
- * window to provide scrolling instead of scrolling in scrolling with the
- * overlay.
+ * This is the only function that should change overlay's size and position.
  *
  * @param size
  *   Contains 'width' and 'height' items as numbers.
- * @return
- *   The same structure with sanitized number values.
+ * @param immediately
+ *   Boolean whether the size change should be performed immediately or animated.
  */
-Drupal.overlay.sanitizeSize = function (size) {
-  var width, height;
+Drupal.overlay.resize = function (size, immediately) {
+  var self = this;
+  // Proceed only if the dialog still exists.
+  if (!(self.isOpen || self.isOpening) || self.isClosing) {
+    return;
+  }
+
   var $window = $(window);
 
+  // Consider any region that should be visible above the overlay (such as
+  // an admin toolbar).
+  var $toolbar = $('.overlay-displace-top');
+  var toolbarHeight = 0;
+  $toolbar.each(function () {
+    toolbarHeight += $toolbar.height();
+  });
+
+  var titleBarHeight = self.$dialogTitlebar.outerHeight(true);
+
   // Use 300px as the minimum width but at most expand to 78% of the window.
   // Ensures that users see that there is an actual website in the background.
   var minWidth = 300, maxWidth = parseInt($window.width() * .78);
-  if (typeof size.width != 'number') {
-    width = maxWidth;
-  }
-  // Set to at least minWidth but at most maxWidth.
-  else if (size.width < minWidth || size.width > maxWidth) {
-    width = Math.min(maxWidth, Math.max(minWidth, size.width));
+  if (typeof size.width != 'number' || isNaN(size.width)) {
+    size.width = Math.max(minWidth, maxWidth);
   }
   else {
-    width = size.width;
+    // Set to at least minWidth but at most maxWidth.
+    size.width = Math.min(maxWidth, Math.max(minWidth, size.width));
   }
 
-  // Use 100px as the minimum height. Expand to 92% of the window if height
-  // was invalid, to ensure that we have a reasonable chance to show content.
-  var minHeight = 100, maxHeight = parseInt($window.height() * .92);
-  if (typeof size.height != 'number') {
-    height = maxHeight;
-  }
-  else if (size.height < minHeight) {
-    // Do not consider maxHeight as the actual maximum height, since we rely on
-    // the parent window scroll bar to scroll the window. Only set up to be at
-    // least the minimal height.
-    height = Math.max(minHeight, size.height);
+  // Use 100px as the minimum height.
+  var minHeight = 100;
+  if (typeof size.height != 'number' || isNaN(size.height)) {
+    // Expand to 92% of the window if height was invalid, to ensure that we have
+    size.height = parseInt($window.height() - toolbarHeight - titleBarHeight - 45);
+  }
+  // Do not consider a maximum height, since we rely on the parent window scroll
+  // bar to scroll the window. Only set up to be at least the minimal height.
+  size.height = Math.max(minHeight, size.height);
+
+  var dialogOptions = $.extend({}, size);
+  dialogOptions.height += titleBarHeight + 15;
+
+  // Compute position to center horizontally and on viewport top vertically.
+  dialogOptions.left = Math.max(0, parseInt(($window.width() - dialogOptions.width) / 2));
+  dialogOptions.top = toolbarHeight + 20;
+
+  if (!immediately) {
+    // Perform the resize animation.
+    self.$dialog.animate(dialogOptions, 'fast', function () {
+      // Proceed only if the dialog still exists.
+      if (!(self.isOpen || self.isOpening) || self.isClosing) {
+        return;
+      }
+
+      // Resize the container.
+      self.$container.height(size.height);
+
+      // Update the dialog size so that UI internals are aware of the change.
+      self.$container.dialog('option', {
+        width: dialogOptions.width,
+        height: dialogOptions.height
+        // Can't set position as it will call $(document).scrollTop(), which
+        // should be called only when loading a new page in the overlay
+        //position: [dialogOptions.left, dialogOptions.top]
+      });
+
+      // Keep the dim background grow or shrink with the dialog.
+      $.ui.dialog.overlay.resize();
+    });
   }
   else {
-    height = size.height;
+    self.$dialog.css(dialogOptions);
+    // Resize the container.
+    self.$container.height(size.height);
+    // Update the dialog size so that UI internals are aware of the change.
+    self.$container.dialog('option', {
+      width: dialogOptions.width,
+      height: dialogOptions.height
+      // Can't set position as it will call $(document).scrollTop(), which
+      // should be called only when loading a new page in the overlay
+      //position: [dialogOptions.left, dialogOptions.top]
+    });
+    // Keep the dim background grow or shrink with the dialog.
+    $.ui.dialog.overlay.resize();
   }
-  return { width: width, height: height };
 };
 
 /**
- * Compute position to center horizontally and on viewport top vertically.
- */
-Drupal.overlay.computePosition = function ($element, elementSize) {
-  var $window = $(window);
-  // Consider any region that should be visible above the overlay (such as
-  // an admin toolbar).
-  var $toolbar = $('.overlay-displace-top');
-  var toolbarHeight = 0;
-  $toolbar.each(function () {
-    toolbarHeight += $toolbar.height();
-  });
-  var position = {
-    left: Math.max(0, parseInt(($window.width() - elementSize.width) / 2)),
-    top: toolbarHeight + 20
-  };
-
-  // Reset the scroll to the top of the window so that the overlay is visible again.
-  window.scrollTo(0, 0);
-  return position;
-};
-
-/**
- * Resize overlay to the given size.
+ * Resize overlay according to the size of its content.
  *
- * @param size
- *   Contains 'width' and 'height' items as numbers.
+ * @todo: Watch for experience in the way we compute the size of the
+ * iframed document. There are many ways to do it, and none of them
+ * seem to be perfect. Note though, that the size of the iframe itself
+ * may affect the size of the child document, especially on fluid layouts.
  */
-Drupal.overlay.resize = function (size) {
-  var self = this;
-
-  // Compute frame and dialog size based on requested document size.
-  var titleBarHeight = $('.overlay .ui-dialog-titlebar').outerHeight(true);
-  var frameSize = self.sanitizeSize(size);
-  var dialogSize = $.extend({}, frameSize);
-  dialogSize.height += titleBarHeight + 15;
-
-  // Compute position on viewport.
-  var dialogPosition = self.computePosition($('.overlay'), dialogSize);
-
-  var animationOptions = $.extend(dialogSize, dialogPosition);
-
-  // Perform the resize animation.
-  $('.overlay').animate(animationOptions, 'fast', function () {
-    // Proceed only if the dialog still exists.
-    if ($.isObject(self.iframe.$element) && $.isObject(self.iframe.$container)) {
-      // Resize the iframe element and container.
-      $('.overlay').width(dialogSize.width).height(dialogSize.height);
-      self.iframe.$container.width(frameSize.width).height(frameSize.height);
-      self.iframe.$element.width(frameSize.width).height(frameSize.height);
+Drupal.overlay.autoResize = function (animate) {
+  var self = Drupal.overlay;
+  // Proceed only if the dialog still exists.
+  if (!(self.isOpen || self.isOpening) || self.isClosing) {
+    return;
+  }
 
-      // Update the dialog size so that UI internals are aware of the change.
-      self.iframe.$container.dialog('option', { width: dialogSize.width, height: dialogSize.height });
+  var size = {};
 
-      // Keep the dim background grow or shrink with the dialog.
-      $('.ui-widget-overlay').height($(document).height());
+  // Only set height when iframe content is loaded.
+  if (self.options.autoFit && $.isObject(self.$iframeBody)) {
+    size.height = self.$iframeBody.outerHeight() + 25;
+  }
+  // Use current height.
+  else {
+    size.height = self.$iframe.height();
+  }
 
-      // Animate body opacity, so we fade in the page as it loads in.
-      $(self.iframe.$element.get(0)).contents().find('body.overlay').animate({opacity: 0.9999}, 'slow');
-    }
+  self.$dialog.queue(function(){
+    self.resize(size, animate);
+    $(this).dequeue();
   });
 };
 
@@ -760,21 +767,15 @@
           $('a.overlay-processed').each(function () {
             $(this).removeClass('active');
           });
-        },
-        draggable: false
+        }
       };
       Drupal.overlay.open(overlayOptions);
     }
   }
-  else {
-    // If there is no overlay URL in the fragment, close the overlay.
-    try {
-      Drupal.overlay.close();
-    }
-    catch(e) {
-      // The close attempt may have failed because the overlay isn't open.
-      // If so, no special handling is needed here.
-    }
+  // If there is no overlay URL in the fragment and the overlay is (still)
+  // open, close the overlay.
+  else if (Drupal.overlay.isOpen) {
+    Drupal.overlay.close();
   }
 };
 
@@ -796,9 +797,12 @@
 
   // Determine the link's original destination, and make it relative to the
   // Drupal site.
-  var fullpath = link.pathname;
-  var re = new RegExp('^' + Drupal.settings.basePath);
-  var path = fullpath.replace(re, '');
+  var path = link.pathname;
+  // Ensure a leading slash on the path, omitted in some browsers.
+  if (path.substr(0, 1) != '/') {
+    path = '/' + path;
+  }
+  path = path.replace(new RegExp(Drupal.settings.basePath), '');
   // Preserve existing query and fragment parameters in the URL.
   var fragment = link.hash;
   var querystring = link.search;
@@ -815,7 +819,7 @@
   // Assemble the overlay-ready link.
   var base = window.location.href;
   return $.param.fragment(base, {'overlay':destination});
-}
+};
 
 /**
  * Make sure the internal overlay URL is reflected in the parent URL fragment.
@@ -882,7 +886,7 @@
  */
 Drupal.theme.prototype.overlayContainer = function () {
   return '<div id="overlay-container"/>';
-}
+};
 
 /**
  * Theme function for the overlay title markup.
