/**
 * @file
 * Javascript for the interface at admin/content/media and also for interfaces
 * related to setting up media fields and for media type administration.
 *
 * Basically, if it's on the /admin path, it's probably here.
 */

(function ($) {

/**
 * Functionality for the administrative file listings.
 */
Drupal.behaviors.mediaAdmin = {
  attach: function (context) {
    // Show a javascript confirmation dialog if a user has files selected and
    // they try to switch between the "Thumbnail" and "List" local tasks.
    $('.tabs.secondary a').once('media-admin').bind('click', function () {
      if ($(':checkbox:checked', $('.file-entity-admin-file-form')).length != 0) {
        return confirm(Drupal.t('If you switch views, you will lose your selection.'));
      }
    });

    if ($('.media-display-thumbnails').length && !$('.media-thumbnails-select').length) {
      // Implements 'select all/none' for thumbnail view.
      // @TODO: Support grabbing more than one page of thumbnails.
      var allLink = $('<a href="#">' + Drupal.t('all') + '</a>')
        .click(function () {
          $('.media-display-thumbnails', $(this).parents('form')).find(':checkbox').attr('checked', true).change();
          return false;
        });
      var noneLink = $('<a href="#">' + Drupal.t('none') + '</a>')
        .click(function () {
          $('.media-display-thumbnails', $(this).parents('form')).find(':checkbox').attr('checked', false).change();
          return false;
        });
      $('<div class="media-thumbnails-select" />')
        .append('<strong>' + Drupal.t('Select') + ':</strong> ')
        .append(allLink)
        .append(', ')
        .append(noneLink)
        .prependTo('.media-display-thumbnails')
      // If the media item is clicked anywhere other than on the image itself
      // check the checkbox. For the record, JS thinks this is wonky.
      $('.media-item').bind('click', function (e) {
        if ($(e.target).is('img, a')) {
          return;
        }
        var checkbox = $(this).parent().find(':checkbox');
        if (checkbox.is(':checked')) {
          checkbox.attr('checked', false).change();
        } else {
          checkbox.attr('checked', true).change();
        }
      });

      // Add an extra class to selected thumbnails.
      $('.media-display-thumbnails :checkbox').each(function () {
        var checkbox = $(this);
        if (checkbox.is(':checked')) {
          $(checkbox.parents('li').find('.media-item')).addClass('selected');
        }

        checkbox.bind('change.media', function () {
          if (checkbox.is(':checked')) {
            $(checkbox.parents('li').find('.media-item')).addClass('selected');
          }
          else {
            $(checkbox.parents('li').find('.media-item')).removeClass('selected');
          }
        });
      });
    }
  }
};

})(jQuery);
