/**
 * WordPress audio player functions exist in the AudioPlayer name space.
 */

/**
 * Ensure AudioPlayer name space is established.
 */
var AudioPlayer = AudioPlayer || {};

/**
 * Define AudioPlayer listeners.
 */
var AudioPlayer = function () {
  return {
    syncVolumes: function (playerID, volume) {
      Drupal.behaviors.swftools_wpaudio.volume(playerID, volume);
    },
    activate: function (playerID, info) {
      if (Drupal.settings.swftools_wpaudio.player && Drupal.settings.swftools_wpaudio.player != playerID) {
        swftools.getObject(Drupal.settings.swftools_wpaudio.player).close();
      }
      Drupal.settings.swftools_wpaudio.player = playerID;
    }
  };
}();

/**
 * Define behaviors that interact with the players.
 */
(function ($) {

Drupal.behaviors.swftools_wpaudio = {

  /**
   * Attaches accessibility controls to the appropriate links.
   */
  attach: function(context) {

    /**
     * Initialise the active player variable as null.
     */
    Drupal.settings.swftools_wpaudio = Drupal.settings.swftools_wpaudio || {player: null};

    /**
     * Attach action to open a player when link is clicked.
     */
    $('[class^=wpaudio-accessible-open]', context).once(function () {
      $(this).click(function() {
        swftools.getObject(Drupal.behaviors.swftools_wpaudio.player_from_element($(this))).open();
      });
    });

    /**
     * Attach action to close a player when a link is clicked.
     */
    $('[class^=wpaudio-accessible-close]', context).once(function () {
      $(this).click(function() {
        var playerID = Drupal.behaviors.swftools_wpaudio.player_from_element($(this));
        swftools.getObject(playerID).close();
        if (playerID == Drupal.settings.swftools_wpaudio.player) {
          Drupal.settings.swftools_wpaudio.player = null;
        }
      });
    });
  },

  /**
   * Extracts the playerID from from the element ID.
   */
  player_from_element: function(element) {
    var class = element.attr('class').split(' ')[0];
    var parts = class.split('-');
    var idStarts = 20 + parts[2].length;
    return class.substring(idStarts);
  },

  /**
   * Synchronises the volume across all WordPress players.
   */
  volume: function(playerID, volume) {
    $('.swftools-wpaudio').each(function () {
      swftools.getObject($(this).attr('id').substring(9)).setVolume(volume);
    });
  }
};
})(jQuery);
;

