/**
 * @file
 * Defines the Drupal behaviors needed for the Image Widget Crop module.
 */

(function ($, Drupal) {
  'use strict';

  /**
   * Drupal behavior for the Image Widget Crop module.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior and creates Cropper instances.
   * @prop {Drupal~behaviorAttach} detach
   *   Detaches the behavior and destroys Cropper instances.
   */
  Drupal.behaviors.imageWidgetCrop = {
    attach: function (context) {
      this.createInstances(context);
    },
    detach: function (context, settings, trigger) {
      if (trigger === "unload") {
        this.destroyInstances(context);
      }
    },

    /**
     * Creates necessary instances of Drupal.ImageWidgetCrop.
     *
     * @param {HTMLElement|jQuery} [context=document]
     *   The context which to find elements in.
     */
    createInstances: function (context) {
      var $context = $(context || document);
      $context.find(Drupal.ImageWidgetCrop.prototype.selectors.wrapper).each(function () {
        var $element = $(this);
        if (!$element.data('ImageWidgetCrop')) {
          $element.data('ImageWidgetCrop', new Drupal.ImageWidgetCrop($element));
        }
      });
    },

    /**
     * Destroys any instances of Drupal.ImageWidgetCrop.
     *
     * @param {HTMLElement|jQuery} [context=document]
     *   The context which to find elements in.
     */
    destroyInstances: function (context) {
      var $context = $(context || document);
      $context.find(Drupal.ImageWidgetCrop.prototype.selectors.wrapper).each(function () {
        var $element = $(this);
        var instance = $element.data('ImageWidgetCrop');
        if (instance) {
          instance.destroy();
          $element.removeData('ImageWidgetCrop');
        }
      });
    }
  };

}(jQuery, Drupal));
