
// Features Crumb
(function($) {
	var crumbContainer = $("#body .features-crumb");
	if (crumbContainer.length == 0) {
		return;
	}
	
	// ----- Properties -----
	
	var _autoScrollSpeed = 8000;
	var _autoScrollTimer;
	
	var _animating = false;
	var _scrollSpeed = 700;
	
	var _crumbs;
	var _currentCrumb;
	
	var _containerWidth;
	var _blurbWidth;
	var _crumbWidth;
	
	
	// ----- Functions -----
	
	var init = function () {
				
		crumbs = crumbContainer.children();
		
		// Let use click the crumbs
		crumbs.find('a.stub')
			.click(event_crumbClicked);
		
		// If we mouse over the crumb, then pause the auto-scrolling
		crumbContainer.hover(event_containerMouseOver, event_containerMouseOut);
		
		_currentCrumb = crumbs.first();
		
		// Work out how much room we have
		_containerWidth = crumbContainer.width();
		_crumbWidth = crumbs.first().find('a.stub').width();
		_blurbWidth = _containerWidth - (_crumbWidth * (crumbs.length - 1));
		
		// Fix crumb widths (this is kind of for IE)
		crumbs.width(_crumbWidth)
			.first()
			.width(_blurbWidth);
		
		// Start the auto scrolling
		action_setAutoScroll(true);
	};
	
	// ----- Events -----
	
	var event_crumbClicked = function (e) {
		action_showCrumb($(this).parent());
		e.preventDefault();
	};
	
	var event_autoScrollTimerTick = function () {
		action_showNextCrumb();
	};
	
	var event_containerMouseOver = function (e) {
		action_setAutoScroll(false);
	};
	
	var event_containerMouseOut = function (e) {
		action_setAutoScroll(true);
	};
	
	// ----- Actions -----
	
	var action_showCrumb = function (crumb) {
		if (_animating || crumb[0] === _currentCrumb[0]) {
			return;
		}
		
		// Build the animation step function
		var animation = function (step) {
			step = Math.round(step);
			_currentCrumb.width(_blurbWidth - step + _crumbWidth);
			crumb.width(step);
		};

		_animating = true;
		
		// A dummy container is needed to house the animation
		var dummy = $('<div></div>').css({ width: _crumbWidth });
		dummy.animate({
			width: _blurbWidth
		}, {
			duration: _scrollSpeed,
			step: animation,
			complete: function () {
				_currentCrumb = crumb;
				_animating = false;
				
				// Queue next animation
				action_setAutoScroll(true);
			}
		});
	};
	
	var action_showNextCrumb = function () {
		var nextCrumb;
		
		nextCrumb = _currentCrumb.next();
		if (nextCrumb.length == 0) {
			nextCrumb = crumbs.first();
		}
		action_showCrumb(nextCrumb);
	};
	
	var action_setAutoScroll = function (autoScroll) {
		clearTimeout(_autoScrollTimer);
		_autoScrollTimer = null;
			
		if (autoScroll) {
			_autoScrollTimer = setTimeout(event_autoScrollTimerTick, _autoScrollSpeed);
		}
	};
	
	// Init
	init();
})(jQuery);
