(function($) {
$(function(){
	var _imgNum = 0;	//画像の枚数
	var _imgSize = 0;	//画像のサイズ
	var _current = 0;	//現在の画像
	var _timer = 5000;	//タイマー時間
	
	//各ボタンの配置
	$('#container').append('<a href="#"><img src="images/btn_prev.gif" width="30" height="30" id="btn-prev" /></a><a href="#"><img src="images/btn_next.gif" width="30" height="30" id="btn-next"  /></a><div id="pagenation"><ul></ul></div>');
	
	//画像サイズ取得
	_imgSize = $('#banner ul li').width();
		
	//メイン画像の数だけ繰り返す
	$('#banner ul li').each(function(){
		//画像をずらして外に配置
		$(this).css('margin-left', -_imgSize);
		//画像の数だけページネーションボタンを作成
		if (_imgNum == _current) {
			//currentだったらアクティブ、メインの画像は表示
			$('#pagenation ul').append('<li class="active"><a href="#"><img src="images/pagenation.gif" width="12" height="24" /></a></li>');
			$(this).css('margin-left', '0px');
		} else {
			$('#pagenation ul').append('<li><a href="#"><img src="images/pagenation.gif" width="12" height="24" /></a></li>');
		}
		//ループの数をカウントして_imgNumに入れる
		_imgNum++;
	});

	//ボタンをクリック
	$('#btn-next').click(function(){
		imageMove(_current +1);
	});
	$('#btn-prev').click(function(){
		imageMove(_current -1);
	});
	//ページネーションクリック
	$('#pagenation ul li').click(function() {
		var thisNum = $('#pagenation li').index(this);
		//押したボタンが現在の画像じゃなかったら実行
		if(thisNum  != _current) {
			imageMove(thisNum );
		}
	});
	//一定時間ごとにimageMoveを実行
	setInterval(function(){
		imageMove(_current +1);
	}, _timer);
	
	function imageMove(next) {
		//次の画像が次の画像より多きかったら右に配置（小さかったら左）
		var pos;
		if (_current < next) {
			pos = -_imgSize;
		} else {
			pos = _imgSize;
		}
		
		//次の画像が最後なら1枚目、１枚目なら最後
		if (next == _imgNum) {
			next = 0;
		} else if(next == -1) {
			next = (_imgNum-1);
		}

		//次の画像を動かす
		$("#banner li").eq(next)
		//次の画像を次の位置に配置
		.css("margin-left", pos)
		.animate({
			marginLeft: "0"
		},"fast");
		
		//現在の画像を動かす
		$("#banner li").eq(_current)
		.animate({
			marginLeft: -pos
		},"fast");
		
		//ページネーション現在のを消し次のをアクティブに
		$('#pagenation li').eq(_current).removeClass('active');
		$('#pagenation li').eq(next).addClass('active');
		
		//現在の番号を次の番号にする。
		_current = next;
	}
});
})(jQuery);
