﻿(function($) {
    $.fn.Repeater = function(options) {    
        //Build main options before element iteration
        var opts = $.extend({}, $.fn.Repeater.defaults, options);
    
        return this.each(function() {
            var elem = $(this);
          
            //Build element specific options
            var o = $.meta ? $.extend({}, opts, elem.data()) : opts;
            
			//Create the anchors that allow you to scroll the repeater left and right
            var moveLeftControl = $('<a href="#" title="Move left"><</a>').click(function(){
                MoveLeft($(this), o.slideEasing, o.slideDuration);
                return false;
            });
            
            var moveRightControl = $('<a href="#" title="Move right">></a>').click(function(){
                MoveRight($(this), o.slideEasing, o.slideDuration);
                return false;
            });
            
			//We need to create the repeater and place our element in side it
            var repeater = $('<div class="repeater"/>');
            repeater.append($('<div class="moveLeft"/>').append(moveLeftControl));
            repeater.append($('<div class="strip"/>').append(elem.clone(true)));
            repeater.append($('<div class="moveRight"/>').append(moveRightControl));            
            elem.replaceWith(repeater);
            
			//Set the width of the strip
            CalculateItemsWidth(repeater);
            
			//Start the auto cycle
            InitAutoCycle(repeater, o);
        });
    };
    
    ////Private functions
	
	//Creates the auto-cycling functionality
    function InitAutoCycle(repeater, options)
    {     
		//Only start the auto cycle if the duration has been set to something greater than 0
        if (options.autoCycleDuration > 0)
        {
			//Bind the auto-cycle to the mouseenter and mouseleave events
            repeater.bind('mouseenter', function(){
                ClearAutoCycle(repeater);
            });
            repeater.bind('mouseleave', function(){
                ClearAutoCycle(repeater);
                StartAutoCycle(repeater, options);
            });
			
			//Start the auto-cycle
            StartAutoCycle(repeater, options);
        }
    };
    
	//Starts the repeater auto-cycling
    function StartAutoCycle(repeater, options)
    {       
		//Create an interval to trigger the repeater to move automatically
        var intervalId = setInterval(
            function(){
                MoveRight(repeater, options.slideEasing, options.slideDuration);
            },
            options.autoCycleDuration
        );        
		
		//Add the interval id to the repeaters data element so we can get it later
        repeater.data('autoCycleIntervalId', intervalId);
    }
    
	//Stops the repeater from auto-cycling
    function ClearAutoCycle(repeater)
    {
		//Get the interval id from the repeater and clear it
        var intervalId = repeater.data('autoCycleIntervalId');
        clearInterval(intervalId);
    }
  
	//Moves the repeater to the left
    function MoveLeft(control, easing, duration)
    {
		//We only want to do this if the repeater is not currently being animated
        var itemsContainer = GetItemsContainer(control);
        if (!itemsContainer.is(':animated'))
        {
			//We need to move left and then move the first item to be the last in the list
            var firstItem = itemsContainer.find('a:first');
            var currentPos = parseInt(itemsContainer.css('left'), 10);
            var itemWidth = firstItem.outerWidth(true);
            var newPos = currentPos - itemWidth;
            
            itemsContainer.append(firstItem.clone(true));
            CalculateItemsWidth(itemsContainer);
            
            itemsContainer.animate(
                {
                    left: newPos
                },
                duration,
                easing,
                function()
                {
                    firstItem.remove();
                    CalculateItemsWidth(itemsContainer);
                    itemsContainer.css('left', currentPos);
                }
            );
        }
    };
    
	//Move the repeater to the right
    function MoveRight(control, easing, duration)
    {
		//We only want to do this if the repeater is not currently being animated
        var itemsContainer = GetItemsContainer(control);
        if (!itemsContainer.is(':animated'))
        {
			//Before we move right we need to move the last item in the list to the front of the queue, 
			//then after animating, remove the last item
            var lastItem = itemsContainer.find('a:last');
            var currentPos = parseInt(itemsContainer.css('left'), 10);
            var itemWidth = lastItem.outerWidth(true);
            var newPos = currentPos;            
                        
            itemsContainer.prepend(lastItem.clone(true));
            CalculateItemsWidth(itemsContainer);
            itemsContainer.css('left', currentPos - itemWidth);
            
            itemsContainer.animate(
                {
                    left: newPos
                },
                duration,
                easing,
                function()
                {
                    lastItem.remove();
                    CalculateItemsWidth(itemsContainer);
                }
            );
        }
    };
    
	//Get and set the total width of our repeating strip
    function CalculateItemsWidth(control)
    {
        var itemsContainer = GetItemsContainer(control);
        var items = itemsContainer.children();
        
        var totalWidth = 0;
        items.each(function(){
            totalWidth += $(this).outerWidth(true);
        });
        
        itemsContainer.css('width', totalWidth);
    };
    
	//Get the items container
    function GetItemsContainer(control)
    {
        var repeater = control;
        if (!repeater.hasClass('repeater'))
        {
            repeater = repeater.parents('div.repeater');
        }        
        return repeater.find('div.strip').find(':first');
    }
  
    ////Plugin defaults
    $.fn.Repeater.defaults = {
        slideEasing: 'swing',
        slideDuration: 2000,
        autoCycleDuration: 0
    };
})(jQuery);

$(document).ready(function(){
    $('div#sponsors div.logos').Repeater({
        slideEasing: 'easeOutCubic',
        slideDuration: 2000,
        autoCycleDuration: 5000
    });
});

