/*
Copyright (c) 2010 Church Media Group, Inc (http://churchmedia.cc) All rights reserved.

This code is distributed under the following terms:

Redistribution and use of this software in source and binary forms, with or without modification,
are not permitted without prior written permission by the copyright holders.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * ??
 *
 * @category   ??
 * @package    JonahCMS
 * @copyright  2010 Church Media Group, Inc.
 * @version    SVN:
 * @link       n/a
 * @see        n/a
 * @since      File available since Release 1.0.0
 */


$(document).ready(function() {
  $('div.rotator_cmg').cmgRotator();
});

(function($){
  $.fn.cmgRotator = function(options) {
    var defaults = {
      speed: 600,
      fastOnEvent: true
    };
    options = $.extend(defaults, options);

    return this.each(function() {
      var $div = $(this).css('position', 'relative');
      var params = $.parseJSON($div.find('input[name="rotator_params"]').val());

      options.timeout = params.interval;

      if (params.navigation) {
        if (params.navigation == 1 || $(params.navigation).length == 0) {
          $div.append('<div class="rotator_pager"></div>');
          options.pager = '.rotator_pager';
        }
        else {
          options.pager = params.navigation;
        }
      }

      var titleSelector, descSelector;
      if (params.title && params.title != 1 && $(params.title).length > 0) {
        $(params.title).html($div.find('.title').hide().html());
        titleSelector = params.title;
      }
      if (params.description && params.description != 1 && $(params.description).length > 0) {
        $(params.description).html($div.find('.description').hide().html());
        descSelector = params.description;
      }

      if (titleSelector || descSelector) {
        options.before = function(current, next) {
          var $next = $(next);
          if (titleSelector) {
            $(titleSelector).html($next.find('.title').html());
          }
          if (descSelector) {
            $(descSelector).html($next.find('.description').html());
          }
        }
      }

      $div.find('div.rotator_content').cycle(options);
    });
  };
})(jQuery);
