var imgWidth = 915;
var imgHeight = 200;
var topDiv;
var intervalObj;
var btn_base_path = '';

$(document).ready(function () {
	
	topDiv = $("#top_image");
	
	if (!topDiv) {
		return;
	}
	
	//自由に位置が調整できるようにスタイル指定
	topDiv.css({
		position:'relative',
		width:imgWidth,
		height:imgHeight,
		overflow:'hidden'
	});
	
	topDiv.find("div").each(function(index) {
		$(this).css({
			position:'absolute',
			top:0,
			left:0
		});
		
		setClass($(this), (index == 0)?"active":"non");
	});
	
	$("#top_image_btn").find("img").each(function(i) {
	  if (btn_base_path == '') {
	      btn_base_path = $(this).attr('src');
	  }
	  if (i == 0) {
	      $(this).attr({src: btn_base_path.replace('01', '02')});
	  } else {
	      $(this).attr({src: btn_base_path});
	  }
	});
	
	intervalObj = setInterval(slideImage, 4400);
});

function slideImage(idx) {
	
	//数を把握
	var maxImg = topDiv.find("div").size();
	if(maxImg > 1) {
		var activeIndex = topDiv.find(".active").index();
		
		var nextIndex = activeIndex + 1;
		if (idx != undefined) {
		  nextIndex = idx;
		}
		
		if (maxImg <= nextIndex) {
			nextIndex = 0;
		}
		
		if (activeIndex == nextIndex) {
		  return;
		}
		
		$("#top_image_btn").find("img").each(function(i) {
		  if (btn_base_path == '') {
		      btn_base_path = $(this).attr('src');
		  }
		  if (i == nextIndex) {
		      $(this).attr({src: btn_base_path.replace('01', '02')});
		  } else {
		      $(this).attr({src: btn_base_path});
		  }
		});
		
		topDiv.find(".pre").each(function(){
			setClass($(this), "non");
		});
		
		topDiv.find(".active").each(function(){
			setClass($(this), "pre");
		});
		
		//位置の制御
		var moveIndex = 1;
		var moveT = 0;
		var moveL = 0;
		switch(moveIndex) {
			case 0:
				//上から
				moveT = imgHeight * -1;
				break;
			case 1:
				//下から
				moveT = imgHeight;
				break;
			case 2:
				//左から
				moveL = imgWidth * -1;
				break;
			default:
				//右から
				moveL = imgWidth;
				break;
		}
		
		var nextObj = $(topDiv.find("div").get(nextIndex));
		nextObj.css({
			top: moveT + "px",
			left: moveL + "px"
		});
		setClass(nextObj, "active");
		nextObj.animate({
			top:"0px",
			left:"0px"
		}, 
		{
			duration: 1200,
			easing: "easeInOutBack"
		}
		);
	}
	
}

function setClass(obj, param) {
	if (param == "active") {
		obj.css({zIndex:10});
	} else if (param == "pre") {
		obj.css({zIndex:9});
	} else {
		obj.css({zIndex:8});
	}
	obj.removeClass("active non pre");
	obj.addClass(param);
}

function delClass(obj, param) {
	obj.css({zIndex:8});
	obj.removeClass(param);
}

function clickTopImageBtn(idx) {
    clearInterval(intervalObj);
    slideImage(idx);
}

