$.fn.rotator = function() {
		return this.each(function() {
			var $rotator = $(this), 
				settings = { speed: 5000, startPosition: 0 },
				$navigation = $('<ul class="navigation"></ul>'),
				$items = $rotator.find('> a');

			if ($items.length > 1) {
				$items.each(function(i) {
					$navigation.append('<li><a class="image-index" href="#">' + (i + 1) +'</a></li>');
				});

				$navigation.append('<li><a class="rotator-control" href="#"><span>Play/Pause</span></a></li>');
				$rotator.append($navigation);
			}	
			
			$navigation
				.find('li:first')
					.addClass('first')
					.end()
				.find('li:last')
					.addClass('last')
					.end()
				.find('a.image-index')
					.hover(
						function() {
							pause();
							show($navigation.find('li a.image-index').index(this));
						},
						function(){
							play();
						}
					)
					.end()
				.find('a.rotator-control')
					.click(function() {
						$(this).hasClass('rotator-play') ? pause() : play();
						return false;
					})
					.end()
				.find('a')
					.click(function() { return false; });

			show(settings.startPosition);
			play();

			/*
			 * Rotation
			 */
			var intervalId;

			function show(index) {
				$items.hide().filter(function(i) { return i === index; }).show();

				$navigation
					.find('a')
						.removeClass('rotator-current')
						.filter(function(i) { return i === index; })
							.addClass('rotator-current');
			}

			function rotate() {
				var currentIndex = null;
				$items.each(function(i) { if ($(this).is(':visible')) {	currentIndex = i; }	});

				var newIndex = (currentIndex || 0) + 1;
				if (newIndex > ($items.length - 1) || newIndex < 0) {
					newIndex = 0;
				}

				show(newIndex);
			}

			function pause() {
				clearInterval(intervalId);
				$navigation.find('.rotator-control').removeClass('rotator-play').addClass('rotator-pause');
			}

			function play() {
				intervalId = setInterval(rotate, settings.speed);
				$navigation.find('.rotator-control').addClass('rotator-play').removeClass('rotator-pause');
			}
		});
	};
$(function(){
	$('.main-images').rotator();
});
