/**
 * @file
 * Provides default functions for the media browser
 */

(function ($) {
namespace('Drupal.media.browser');

Drupal.media.browser.selectedMedia = [];
Drupal.media.browser.mediaAdded = function () {};
Drupal.media.browser.selectionFinalized = function (selectedMedia) {
  // This is intended to be overridden if a callee wants to be triggered
  // when the media selection is finalized from inside the browser.
  // This is used for the file upload form for instance.
};

Drupal.behaviors.MediaBrowser = {
  attach: function (context) {
    if (Drupal.settings.media && Drupal.settings.media.selectedMedia) {
      Drupal.media.browser.selectMedia(Drupal.settings.media.selectedMedia);
      // Fire a confirmation of some sort.
      Drupal.media.browser.finalizeSelection();
    }

    // Instantiate the tabs.
    var showFunc = function(event, ui) {
      // Store index of the tab being activated.
      if (parent_iframe = Drupal.media.browser.getParentIframe(window)) {
        $(parent_iframe).attr('current_tab', $('#media-tabs-wrapper > ul > li.ui-state-active').index());
      }
    };
    var activeTab = Drupal.media.browser.tabFromHash();
    $('#media-browser-tabset').tabs({
      selected: activeTab, // jquery < 1.9
      active: activeTab, // jquery >= 1.9
      show: showFunc, // jquery ui < 1.8
      activate: showFunc // jquery ui >= 1.8
    });

    $('.media-browser-tab').each( Drupal.media.browser.validateButtons );
  }
  // Wait for additional params to be passed in.
};

Drupal.media.browser.getParentIframe = function (window) {
  var arrFrames = parent.document.getElementsByTagName("IFRAME");
  for (var i = 0; i < arrFrames.length; i++) {
    if (arrFrames[i].contentWindow === window) {
      return arrFrames[i];
    }
  }
}

/**
 * Get index of the active tab from window.location.hash
 */
Drupal.media.browser.tabFromHash = function () {
  if (parent_iframe = Drupal.media.browser.getParentIframe(window)) {
    return $(parent_iframe).attr('current_tab');
  }
  return 0;
};

Drupal.media.browser.launch = function () {

};

Drupal.media.browser.validateButtons = function() {
  // The media browser runs in an IFRAME. The Drupal.media.popups.mediaBrowser()
  // function sets up the IFRAME and an "OK" button that is outside of the
  // IFRAME, so that its click handlers can destroy the IFRAME while retaining
  // information about what media items were selected. However, Drupal UI
  // convention is to place all action buttons on the same "line" at the bottom
  // of the form, so if the form within the IFRAME contains a "Submit" button or
  // other action buttons, then the "OK" button will appear below the IFRAME
  // which breaks this convention and is confusing to the user. Therefore, we
  // add a "Submit" button inside the IFRAME, and have its click action trigger
  // the click action of the corresponding "OK" button that is outside the
  // IFRAME. media.css contains CSS rules that hide the outside buttons.

  // If a submit button is present, another round-trip to the server is needed
  // before the user's selection is finalized. For these cases, when the form's
  // real Submit button is clicked, the server either returns another form for
  // the user to fill out, or else a completion page that contains or sets the
  // Drupal.media.browser.selectedMedia variable. If the latter, then
  // Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad() auto-triggers the
  // "OK" button action to finalize the selection and remove the IFRAME.

  // We need to check for the fake submit button that is used on non-form based
  // pane content. On these items we need to bind the clicks so that media can
  // be selected or the window can be closed. This is still a hacky approach,
  // but it is a step in the right direction.

  $('a.button.fake-submit', this).once().bind('click', Drupal.media.browser.submit);
};

Drupal.media.browser.submit = function () {
  // @see Drupal.media.browser.validateButtons().
  var buttons = $(parent.window.document.body).find('#mediaBrowser').parent('.ui-dialog').find('.ui-dialog-buttonpane button');
  buttons[0].click();

  // Return false to prevent the fake link "click" from continuing.
  return false;
}

Drupal.media.browser.selectMedia = function (selectedMedia) {
  Drupal.media.browser.selectedMedia = selectedMedia;
};

Drupal.media.browser.finalizeSelection = function () {
  if (!Drupal.media.browser.selectedMedia) {
    throw new exception(Drupal.t('Cannot continue, nothing selected'));
  }
  else {
    Drupal.media.browser.selectionFinalized(Drupal.media.browser.selectedMedia);
  }
};

}(jQuery));
