﻿(function($) {
    $.fn.FlickrFeed = function(options) {    
        //Build main options before element iteration
        var opts = $.extend({}, $.fn.FlickrFeed.defaults, options);
    
        return this.each(function() {
            var flickrFeed = $(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);
                return false;
            });
            
            var moveRightControl = $('<a href="#" title="Move right">></a>').click(function(){
                MoveRight($(this), o);
                return false;
            });
                        
            //Set up the thumbs
			var thumbs = flickrFeed.find(o.thumbnailsSelector);
            var thumbLinks = thumbs.find('a');            
            if (thumbLinks.length > 2)
            {            
                thumbLinks.each(function(){
                    var thumb = $(this);
                    thumb.click(function(){
                        var index = $(this).parent().find('a').index(this);
                        if (index > 1)
                        {
                            MoveLeft(repeater, o);
                        }
                        else if (index < 1)
                        {
                            MoveRight(repeater, o);
                        }
                        return false;
                    });
                });
                
			    //We need to create the repeater and place our thumbs inside it
                var repeater = $('<div class="repeater"/>');
                repeater.append($('<div class="moveLeft"/>').append(moveLeftControl));
                repeater.append($('<div class="strip"/>').append(thumbs.clone(true)));
                repeater.append($('<div class="moveRight"/>').append(moveRightControl));            
                thumbs.replaceWith(repeater);
                
                
			    //Set the width of the strip
                CalculateItemsWidth(repeater);
                
                //Move right to initialise
                MoveRight(repeater, o);
                
			    //Start the auto cycle
                //InitAutoCycle(repeater, o);
            }
            else
            {  
                thumbLinks.each(function(){
                    var thumb = $(this);
                    thumb.click(function(){
                        MakeActive(thumb, o);
                        return false;
                    });
                });
                
                MakeActive($(thumbLinks[0]), 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);
            },
            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);
    }
    
    function MakeActive(thumb, options)
    {
        var thumbs = thumb.parent();
        var activePhoto;
    
        var repeater = thumbs.parents('div.repeater');
        if (repeater.length > 0)
        {
            activePhoto = repeater.parent().find(options.activePhotoSelector).find('img');
        }
        else
        {
            activePhoto = thumbs.parent().find(options.activePhotoSelector).find('img');
        }
        activePhoto.attr('src', thumb.attr('href'));
        activePhoto.attr('alt', thumb.attr('alt'));
        
        var currentActive = thumbs.find('a.active');
        currentActive.removeClass('active');
        thumb.addClass('active');
    };
  
	//Moves the repeater to the left
    function MoveLeft(control, options)
    {
		//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
                },
                options.slideDuration,
                options.slideEasing,
                function()
                {
                    firstItem.remove();
                    CalculateItemsWidth(itemsContainer);
                    itemsContainer.css('left', currentPos);
                    
                    var makeActiveThumb = $(itemsContainer.find('a')[1]);
                    MakeActive(makeActiveThumb, options);
                }
            );
        }
    };
    
	//Move the repeater to the right
    function MoveRight(control, options)
    {
		//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
                },
                options.slideDuration,
                options.slideEasing,
                function()
                {
                    lastItem.remove();
                    CalculateItemsWidth(itemsContainer);
                    
                    var makeActiveThumb = $(itemsContainer.find('a')[1]);
                    MakeActive(makeActiveThumb, options);
                }
            );
        }
    };
    
	//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.FlickrFeed.defaults = {
        activePhotoSelector: 'div.activePhoto',
        thumbnailsSelector: 'div.photoThumbs',
        slideEasing: 'easeOutCubic',
        slideDuration: 400,
        autoCycleDuration: 5000
    };
})(jQuery);

$(document).ready(function(){
    $('div.flickrFeed').FlickrFeed();
});


