
$.fn.rbRotatorWidget = function (options) {

  var defaults = {
  }
  
  // Merge top level objects
  var opts = $.extend(defaults, options);

  return this.each(function () {
    
    var self = this;
    //var $self = $(this);
    
    var cycleIndex  = null;
    var $imageCycle = $('div.rb-rotator-images', self);
    var $buttons    = $('div.rb-rotator-menu-items div.rb-button', self);
    var $next = $('.rb-rotator-next', self);
    var $prev = $('.rb-rotator-prev', self);

    function activate() {
        initControls();
        initCycle();
    }
        
    function initControls()
    {
        // Arrows
        
        var arrowBase = '/assets/gfx/rotator/arrow';
        $prev.hover(function() {
            $(this).attr('src', arrowBase + '-l-h.gif');
        }, function() {
            $(this).attr('src', arrowBase + '-l.gif');
        });
        $next.hover(function() {
            $(this).attr('src', arrowBase + '-r-h.gif');
        }, function() {
            $(this).attr('src', arrowBase + '-r.gif');
        });
        
        // Buttons
        
        $buttons.each(function(index) {
            $(this).data('cycleIndex', index);
        }).click(function() {
            $imageCycle.cycle(parseInt($(this).data('cycleIndex')));
        }).hover(function () {
            $(this).addClass('rb-button-hover');
        }, function() {
            $(this).removeClass('rb-button-hover');
        });
        
    }
    
    function initCycle() {
            
            // Init Cycle
            
            $imageCycle.cycle({
                timeout: 7000,
                speed: 600,
                fx: 'scrollHorz',
                next: $next,
                prev: $prev,
                nowrap: false,
                pause: true,
                before: function(curr, prev, opts) {
                    if(cycleIndex != null) {
                        $buttons.removeClass('rb-button-selected');
                        $buttons.eq(opts.nextSlide).addClass('rb-button-selected');
                    }
                },
                after: function (curr, next, opts) {
                    cycleIndex = opts.currSlide;
                }
            });
            
    }

    activate();

  });

}
