$(document).ready(function() {
	var KEY = {
		LEFT_ARROW: 37,
		RIGHT_ARROW: 39,
		SPACE: 32,
		ENTER: 13
	};

	var $pages = $("#slideshow section");
	var nPages = $pages.length;
	var curPage = 0;
	var slidePause = false;

	var to = null;

	function _clearTimeout() {
		if (to) {
			clearTimeout(to);
			to = null;
		}
	}

	function status() {
		var text = slidePause ? "||" : "&#9654;";

		$('#status').html(text).fadeIn().delay(3000).fadeOut();
	}

	function moveTo(p, callback) {
		_clearTimeout();

		if (null !== p) {
			$pages.eq(curPage).fadeOut(1000);
			curPage = p;
			$pages.eq(curPage).fadeIn(1000, function() {
				if (CHANGE_AUTO) {
					to = setTimeout(nextPage, TIMEOUT);
				}
			});
		}
	}

	function prevPage(force) {
		var p = (curPage - 1);
		if (curPage < 0) {
			curPage = nPages - 1;
		}

		if (force || !slidePause) {
			moveTo(p);
		}
	}

	function nextPage(force) {
		var p = (curPage + 1) % nPages;

		if (force || !slidePause) {
			moveTo(p);
		}
	}

	$pages.hide();
	$pages.eq(0).show();
	$("#slideshow").removeClass('hidden');

	if (CHANGE_AUTO) {
		_clearTimeout();
		to = setTimeout(nextPage, TIMEOUT);
	}

	$(window).keyup(function(event) {
		if (KEY.LEFT_ARROW === event.keyCode) {
			prevPage(true);
		} else if (KEY.RIGHT_ARROW === event.keyCode) {
			nextPage(true);
		} else if (KEY.SPACE === event.keyCode) {
			_clearTimeout();
			if (false === slidePause) {
				slidePause = true;
			} else {
				slidePause = false;
				to = setTimeout(nextPage, TIMEOUT);
			}

			status();
		}
	});
});