/**
 * @file
 * Overrides methods of the Drupal.overlay object in order to support D8-style
 * viewport displacement
 */

(function ($, Drupal, displace) {

"use strict";

/**
 * Implements Drupal.behaviors.
 */
Drupal.behaviors.NavbarOverlayOverrides = {
  attach: function (context, settings) {
    $(document)
      .bind('drupalViewportOffsetChange.navbar', $.proxy(Drupal.overlay, 'eventhandlerViewportOffsetChange'))
  }
};

Drupal.overlay = Drupal.overlay || {};

$.extend(Drupal.overlay, {
  /**
   * Responds to the drupalViewportOffsetChange event.
   *
   * @param object event
   *   A jQuery event object.
   *
   * @param object offsets
   *   An object whose keys are the for sides an element -- top, right, bottom
   *   and left. The value of each key is the viewport displacement distance for
   *   that edge.
   */
  eventhandlerViewportOffsetChange: function (event, offsets) {
    // Allow other scripts to respond to this event.
    $(document).trigger('drupalOverlayResize');
  },

  /**
   * Event handler: resizes displaced elements so they won't overlap the
   * scrollbar of overlay's iframe.
   *
   * @param event
   *   Event being triggered, with the following restrictions:
   *   - event.type: any
   *   - event.currentTarget: any
   */
  eventhandlerAlterDisplacedElements: function (event) {
    // Proceed only if the overlay still exists.
    if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
      return;
    }

    var offsets = displace.offsets;

    // Move the body of the iframe contentDocument inward a sufficient distance
    // to prevent it from appearing underneath displacing elements like the
    // navbar.
    var iframeBody = this.iframeWindow.document.body;
    $(iframeBody).css({
      'padding-top': offsets.top,
      'padding-right': offsets.right,
      'padding-bottom': offsets.bottom,
      'padding-left': offsets.left
    });
    // Trigger a repaint.
    iframeBody.style.display = 'none';
    var _tmp = iframeBody.offsetHeight;
    iframeBody.style.display = 'block';

    // Constrain the width of offsetting top and bottom elements, such as the
    // navbar, so that a scroll in the overlay iframe won't be occluded.
    var iframeBodyWidth = iframeBody.clientWidth;
    if (iframeBodyWidth > 0 && iframeBodyWidth < document.documentElement.clientWidth) {
      $('[data-offset-top], [data-offset-bottom]').css('max-width', iframeBodyWidth);
    }
  },
  /**
   * Event handler: restores size of displaced elements as they were before
   * overlay was opened.
   *
   * @param event
   *   Event being triggered, with the following restrictions:
   *   - event.type: any
   *   - event.currentTarget: any
   */
  eventhandlerRestoreDisplacedElements: function (event) {
    $('[data-offset-top], [data-offset-bottom]').css('max-width', 'none');
  }
});

}(jQuery, Drupal, Drupal.displace));
