/*
 * Recieves a cb-mdb series and displays it using shadowbox. You need to make
 * sure that Shadowbox.init() has been called before using this.
 *
 * Author: Johannes Wüller
 * Created On: 26.10.2010
 *
 * Usage:
 *    // Most simple usage; display cb-mdb series 12345 in shadowbox using
 *    // default configuration
 *    displayMdbSeriesShadowbox(12345);
 *
 *    // Add a callback for manipulating every item before displaying them.
 *    displayMdbSeriesShadowbox(12345, function (item, record) {
 *       item.title = record.copyright;
 *       return item;
 *    });
 */
window.displayMdbSeriesShadowbox = (function ($, SB) {
   var domain, // const
      url, // const
      cache,
      requestCallback; // const

   // Set data source.
   domain = document.location.protocol+'//'+document.location.host;
   url = domain+'/module/lib/framework/getMdbSeries.php';

   // Store all requests here.
   cache = {};

   /**
    * Processes request data and displays them in a shadowbox.
    *
    * @param data Items to be displayed
    * @param formatCallback Function to be called for formatting all data.
    */
   requestCallback = function (data, formatCallback) {
      var items;

      items = [];

      // Fit all items into shadowbox notation.
      $.each(data, function (index, record) {
         items.push(formatCallback({
            content: record.file,
            player:  'img',
            title:   record.title,
            options: {}
         }, record));
      });

      // Let's get ready to rumble!™
      SB.open(items);
   };

   /**
    * Request cb-mdb series and display it using shadowbox.
    *
    * @param mdbSeriesId ID of cb-mdb series
    * @param formatCallback (Optional) function to be called for formatting
    *    every item before displaying it
    */
   return function (mdbSeriesId, formatCallback) {
      var request, // const
         serializedRequest; // const

      mdbSeriesId = parseInt(mdbSeriesId, 10);
      formatCallback = formatCallback || function (item, record) {
         return item;
      };

      // Build request parameters.
      request = {
         id:     mdbSeriesId,
         format: 'json'
      };

      // Stringify request for caching.
      serializedRequest = $.param(request);

      // Only query the external source if needed.
      if (cache[serializedRequest] !== undefined) {
         requestCallback(cache[serializedRequest], formatCallback);
      } else {
         $.get(url, request, function (data) {
            cache[serializedRequest] = data;
            requestCallback(cache[serializedRequest], formatCallback);
         }, 'json');
      }
   };
}(jQuery, Shadowbox));
