/* (c) Line Digital 2009 <http://www.line.uk.com/> */
(function ($) {
	var SETTINGS = {
		childSelector: '> *',
		displayFor: 4000,
		pauseOnHover: true,
		transitionSpeed: 500,
		crossFade: true
	}

	$.fn.ticker = function (options) {
		var settings = $.extend(SETTINGS, options);

		var ticker = $(this);
		var headlines = ticker.find(settings.childSelector);
		var currentHeadlineIndex = 0;
		var pauseAutoRotation = false;

		// The swapping
		function swap(from, to, callback) {
			function fadeIn () {
				to.fadeIn(settings.transitionSpeed, function () {
					to.addClass('on');
					callback();
				});
			}

			from.fadeOut(settings.transitionSpeed, function () {
				from.removeClass('on');
				if (!settings.crossFade) {
					fadeIn();
				}
			});
			if (settings.crossFade) {
				fadeIn();
			}
		}

		// The auto rotation
		function autoRotate() {
			if (!pauseAutoRotation) {
				var next = (currentHeadlineIndex + 1) % headlines.size();
				swap(headlines.eq(currentHeadlineIndex), headlines.eq(next), function () {
					setTimeout(autoRotate, settings.displayFor)
				});
				currentHeadlineIndex = next;
			}
		}

		// Kick off the auto rotation
		$(window).load(function () {
			setTimeout(autoRotate, settings.displayFor);
		});

		// Pause on hover
		if (settings.pauseOnHover) {
			ticker.hover(function () {
				pauseAutoRotation = true;
			}, function () {
				pauseAutoRotation = false;
			});
		}
	}
})(jQuery);

