/*
 * This code is based on Chris Coyier's Moving Boxes
 *   (http://css-tricks.com/moving-boxes/)
 *
 * requires jQuery 1.3 or above
 */
$(function() {
	$("#noscript1").css('display', 'none');
	$("#noscript2").css('display', 'none');
	$("#slider_top").css('display', 'inline');

	var totalPanels		= $("#slider .scrollContainer").children().size();	// パネルの枚数（最低4枚は必要）

	// 通常時のサイズ
	var curImgWidth		= slideImageWidth;	// 画像の幅
	var curWidth		= curImgWidth + 2;	// パネルの幅

	// 縮小時のサイズ
	var regWidth		= parseInt($("#slider .panel").css("width"));		// パネルの幅
	var regImgWidth		= parseInt($("#slider .panel img").css("width"));	// 画像の幅

	var movingDistance	= regWidth + 10 * 2;	// 移動距離

	var $panels			= $('#slider .scrollContainer > div');
	var $container		= $('#slider .scrollContainer');

	var leftmostPanel = 1;	// 左端のパネルの番号
	var curPanel = 2;		// カレントパネルの番号

	var timerID = null;
	var interval = 5000;	// スライドの停止間隔（ミリ秒単位）

	var opacityOfNormalPanel = 0.5;		// 縮小したパネルの opacity
	var opacityOfBiggerPanel = 1.0;		// 拡大したパネルの opacity

	$panels.css({ 'float' : 'left', 'position' : 'relative', 'left' : '0px' });
	$panels.css("opacity", opacityOfNormalPanel);
	$("#panel_" + curPanel).css("opacity", opacityOfBiggerPanel);

	$("#slider").data("currentlyMoving", false);		// スライダーが現在動作中か？
	$("#slider .panel").data("currentlyMoving", false);	// 各パネルが現在動作中か？

	$container
		.css('width', ($panels[0].offsetWidth * $panels.length) + 1000)
		.css('left', "" + ((parseInt($("#slider .scroll").css("width")) - (regWidth * 2 + curWidth + 10 * 6)) / 2) + "px");

	$('#slider .scroll').css('overflow', 'hidden');

	debugPrint();

	// Set up "Current" panel and next and prev
	growBigger("#panel_" + curPanel);


	/*
	 * デバッグ情報出力
	 */
	function debugPrint() {
		return;

		var message = "";
		for (var i = 1; i <= $panels.length; i++)
			message += i + ":[" + $("#panel_" + i).css("left") + "] ";

		message += "moving: "
		for (var i = 1; i <= totalPanels; i++)
			message += i + ":[" + $("#panel_" + i).data("currentlyMoving") + "] ";
		message += "all:[" + $("#slider").data("currentlyMoving") + "] ";

		message += "leftmostPanel:[" + leftmostPanel + "] ";
		message += "curPanel:[" + curPanel + "] ";

		$("#slider_debug_info").text(message);
	}

	/*
	 * パネルを通常のサイズに戻す
	 */
	function returnToNormal(element) {
		$(element)
			.animate({ width: regWidth, opacity : opacityOfNormalPanel }, { queue : false })
			.find("img")
			.animate({ width: regImgWidth }, { queue : false })
			;
	}

	/*
	 * パネルを拡大する
	 */
	function growBigger(element) {
		$(element)
			.animate({ width: curWidth, opacity : opacityOfBiggerPanel }, { queue : false })
			.find("img")
			.animate({ width: curImgWidth }, { queue : false })
			;
	}

	/*
	 * パネルの番号を求める（剰余）
	 */
	function mod(x) {
		return (totalPanels + x - 1) % totalPanels + 1;
	}

	/*
	 * パネルを移動する
	 *
	 * direction : "right" または "left"
	 */
	function change(direction) {
		// 動作中ならば抜ける
		if ($("#slider").data("currentlyMoving"))
			return false;

		$("#slider").data("currentlyMoving", true);			// 動作中
		$("#slider .panel").data("currentlyMoving", true);	// 動作中

		if (direction == "left") {
			var nextLeftmostPanel = mod(leftmostPanel - 1);
			$("#panel_" + nextLeftmostPanel).insertBefore("#panel_" + leftmostPanel);	// 右端のパネルを左端のパネルの左に移動する
			leftmostPanel = nextLeftmostPanel;
			$panels = $('#slider .scrollContainer > div');
			$panels.css("left", "-" + movingDistance + "px");
		}
		debugPrint();

		var nextPanel	= mod(curPanel + (direction == "right" ? 1 : -1));		// 次にカレントになるパネルの番号
		var movement	= (direction == "right" ? "-=" : "+=") + movingDistance + "px";

		// 各パネルを移動する
		$("#slider .panel")
			.animate({ left : movement }, {
				queue : false,
				complete : function() {		// アニメーション完了時のコールバック関数
					// TODO 排他制御が必要？
					$(this).data("currentlyMoving", false);		// 停止中
					var somethingMoving = false;		// 何れかのパネルが動作中か？
					for (var i = 1; i <= totalPanels; i++)
						somethingMoving = somethingMoving || $("#panel_" + i).data("currentlyMoving");
					if (!somethingMoving) {		// 全てのパネルが停止中
						if (direction == "right") {
							var rightmostPanel     = mod(leftmostPanel + totalPanels - 1);
							var nextRightmostPanel = mod(rightmostPanel + 1);
							var nextLeftmostPanel  = mod(leftmostPanel  + 1);
							$("#panel_" + nextRightmostPanel).insertAfter("#panel_" + rightmostPanel);	// 左端のパネルを右端のパネルの右に移動する
							leftmostPanel = nextLeftmostPanel;
							$panels = $('#slider .scrollContainer > div');
							$panels.css("left", "0px");
						}
						$("#slider").data("currentlyMoving", false);	// 停止中
					}
					debugPrint();
				}
			});

		returnToNormal("#panel_" + curPanel);
		growBigger("#panel_" + nextPanel);

		curPanel = nextPanel;

		// remove all previous bound functions
		$("#panel_" + mod(curPanel + 1)).unbind();

		// go forward
		$("#panel_" + mod(curPanel + 1)).click(function() { goForward();  return false; });

        // remove all previous bound functions
		$("#panel_" + mod(curPanel - 1)).unbind();

		// go back
		$("#panel_" + mod(curPanel - 1)).click(function() { goBack();     return false; });

		// remove all previous bound functions
		$("#panel_" + curPanel).unbind();
	}


	$("#panel_" + (curPanel + 1)).click(function() { goForward(); return false; });
	$("#panel_" + (curPanel - 1)).click(function() { goBack();    return false; });

	// when the left/right arrows are clicked
	$("#slider .right").click(function() { goForward(); });
	$("#slider .left") .click(function() { goBack(); });

	$(window).keydown(function(event) {
		switch (event.keyCode) {
		case 13: // enter
			goForward();
			break;
		case 32: // space
			goForward();
			break;
		case 37: // left arrow
			goBack();
			break;
		case 39: // right arrow
			goForward();
			break;
		}
	});

	timerId = window.setInterval(function() { change('right'); }, interval);


	function clearTimer() {
		if (timerId != null)
			clearInterval(timerId);
		timerId = null;
	}

	function goForward() {
		clearTimer();
		change("right");
	}

	function goBack() {
		clearTimer();
		change("left");
	}
});
