/**
 * @file
 *
 * Dialog API inspired by HTML5 dialog element:
 * http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#the-dialog-element
 */
(function ($, Drupal, drupalSettings) {

"use strict";

drupalSettings.dialog = {
  autoOpen: true,
  dialogClass: '',
  close: function (e) {
    Drupal.detachBehaviors(e.target, null, 'unload');
  }
};

Drupal.dialog = function (element, options) {

  function openDialog (settings) {
    settings = $.extend({}, drupalSettings.dialog, options, settings);
    // Trigger a global event to allow scripts to bind events to the dialog.
    $(window).trigger('dialog:beforecreate', [dialog, $element, settings]);
    $element.dialog(settings);
    dialog.open = true;
    $(window).trigger('dialog:aftercreate', [dialog, $element, settings]);
  }

  function closeDialog (value) {
    $(window).trigger('dialog:beforeclose', [dialog, $element]);
    $element.dialog('close');
    dialog.returnValue = value;
    dialog.open = false;
    $(window).trigger('dialog:afterclose', [dialog, $element]);
  }

  var undef;
  var $element = $(element);
  var dialog = {
    open: false,
    returnValue: undef,
    show: function () {
      openDialog({modal: false});
    },
    showModal: function () {
      openDialog({modal: true});
    },
    close: closeDialog
  };

  return dialog;
};

})(jQuery, Drupal, drupalSettings);