
(function($){

	$(function(){

		var $mainimg = $("#rotbnr .mainimg");
		var $bnrs = $("#rotbnr li");
		var $highlight = $("#rotbnr .btn_active");
		var length = $bnrs.length;
		var bLock = false; // バナー変更ロック
		var bLock2 = false; // メイン画像変更ロック
		var bLock3 = false; // ユーザー操作ロック
		var EffectDuration = 500;
		var IntervalTime = 4000;
		var targetY,targetIndex;
		var timer;
		var activeID = "mainimg_rot1";
		var preID;
			   
		$("#rotbnr li>a").mouseover(function(){
			bLock3 = true;
			clearTimeout(timer);
			//if(!bLock2){
				var index = $("#rotbnr li>a").index($(this));
				$highlight.stop().animate({top:(index*70+15)+"px"},100,"swing",function(){
				});
				mainimgChange($(this));
			//}
		}).mouseout(function(){
			bLock3 = false;
			timer = setTimeout(bnrRotation,IntervalTime);
		});
		
		// #をリンクなしとして処理
		 $("#rotbnr li a").each(function(){
			 if($(this).attr("href")=="#"){
				 $(this).css("cursor","default");
			 }
		 });

		// バナー変更	
		var bnrChange = function(step){
			clearTimeout(timer);
			timer = setTimeout(bnrRotation,IntervalTime+EffectDuration);
			if( !bLock && !bLock3){
				bLock = true;
				if(step==1){
					//▽next
					$("#rotbnr li:first").clone(true).appendTo("#rotbnr ul");
					targetY = -70;
					targetIndex = 2;
				}else{
					//△prev
					$("#rotbnr li:last").clone(true).css("margin-top","-70px").prependTo("#rotbnr ul");
					targetY = 0;
					targetIndex = 1;
				}
				var $target = $("#rotbnr li:eq("+targetIndex+") a");
				mainimgChange($target);
				$highlight.stop().animate({top:"85px"},100,"swing",function(){
				});
				$("#rotbnr li:first").animate( { marginTop: targetY+"px" }, EffectDuration, 'swing', function(){
					if(step==1){
						$("#rotbnr li:first").remove();
					}else{
						$("#rotbnr li:last").remove();
					}
					bLock = false;
				});
			}
		}
		
		// バナーローテーション
		function bnrRotation(){
			bnrChange(1);
		}
		
		timer = setTimeout(bnrRotation,IntervalTime);
		
		
		
		// メインイメージ変更
		function mainimgChange($target){
			var length = $("#rotbnr .mainimg p").length;
			bLock2 = true;
			preID = activeID;
			var id = "main"+$target.attr("id");
			activeID = id;
			$("#rotbnr .mainimg p:animated").stop().hide();
			if(activeID!=preID){
				//$(".headline").text(($("#"+id).length)+":"+($("#rotbnr .mainimg p").length));
				$("#"+activeID).css("opacity",1).prependTo("#rotbnr .mainimg").show();
				$("#"+preID).animate({opacity:0},"slow","swing",function(){
					bLock2 = false;
					$(this).prependTo("#rotbnr .mainimg").hide();
				});
			}
		}
		
		// ボタンを割り当て
		$("#rotbnr .btn_next").css("cursor","pointer").click(function(){bnrChange(1);});
		$("#rotbnr .btn_prev").css("cursor","pointer").click(function(){bnrChange(-1);});

			   
	});

})(jQuery);
