﻿$(function () {
	var current, cancelled = false, display = $('#display'), next, timer = $('#timer');

	function Animate(x, y) {
		$('#thumbnails').find('a').eq(x.index()).removeClass('current');
		$('#thumbnails').find('a').eq(y.index()).addClass('current');

		x.css('z-index', '1');
		y.css('z-index', '2');
		current = y;

		y.animate(arguments[2], 750).animate(arguments[3], 250, function () {
			x.css({ right: '100%' });
			Reset();
			AutoPlay();
		});
	};

	function AutoPlay() {
		if (!cancelled) {
			timer.animate({ width: '100%' }, 5000, function () {
				Next();
			});
		};
	};

	function Cancel() {
		if (!cancelled) {
			timer.stop(true, false);
			Reset();
			cancelled = true;
			$('#pause').hide();
			$('#play').show();
		};
	};

	function JumpTo(index) {
		var x = current, y = display.find('li').eq(index);
		y.css({ right: '0%', top: '200%' });
		Animate(x, y, { top: '-10%' }, { top: '0%' });
	};

	function Next() {
		var x = current, y = current.next();
		if (y.length === 0) y = display.find('li').first();
		Animate(x, y, { right: '-10%' }, { right: '0%' });
	};

	function Previous() {
		var x = current, y = current.prev();
		if (y.length === 0) y = display.find('li').last();
		y.css({ right: '-100%' });
		Animate(x, y, { right: '10%' }, { right: '0%' });
	};

	function Reset() {
		timer.width('0%');
	};

	$('#display, #controls').mouseenter(function () {
		$('#actions').show();
	}).mouseleave(function () {
		$('#actions').hide();
	});

	$('#play').click(function () {
		$('#pause').show();
		$('#play').hide();
		cancelled = false;
		AutoPlay();
		return false;
	});

	$('#pause').click(function () {
		Cancel();
		return false;
	});

	$('#next').click(function () {
		Cancel();
		Next();
		return false;
	});

	$('#previous').click(function () {
		Cancel();
		Previous();
		return false;
	});

	$('#display li').each(function (index) {
		if (index == 0) {
			current = $(this);
			current.css({ right: '0%' });
		};
	});

	$('#thumbnails a').each(function (index) {
		if (index === 0) $(this).addClass('current');
		$(this).click(function () {
			Cancel();
			JumpTo(index);
			return false;
		});
	});

	$('#play').trigger('click');
});
