/*==== 設定項目 ================================================*/
var moveSpeed   = 10;  // タイマーの更新間隔
var moveLength  = 40;  // 1タイマーでの移動距離
var reduceStart = 150; // 減速開始位置
var reduceRate  = 0.8; // 減速率（0～1）1=減速無し
var minSpeed    = 10;  // 減速時の1タイマーでの最低移動距離
/*==== 設定項目ここまで ========================================*/

var scrollTimer;
var nowLength = moveLength;
function $i(id){
	if(document.getElementById){
		return document.getElementById(id);
	}else if(document.all){
		return document.all(id);
	}else{
		return '';
	}
}
function $N(tag){
	return document.getElementsByTagName(tag);
}

function getPosition(e,sId,tId){
	var target = $i(tId).offsetTop ? $i(tId).offsetTop : null;
	var nowClientTop = null;
	tmp = new Array();
	// IE以外
	if(!isNaN(window.pageYOffset)){
		nowClientTop = window.pageYOffset;
	// IE
	}else if(window.event && !isNaN($i(sId).offsetTop)){
		nowClientTop = $i(sId).offsetTop - event.y;
	// その他
	}else{
		nowClientTop = $i(sId).offsetTop;
	}
	
	tmp[0] = Math.abs(nowClientTop);
	tmp[1] = target;
	return tmp;
}

function setScroll(selfPosition,targetPosition,direction){
	nowLength = Math.floor(Math.abs(targetPosition-selfPosition) > reduceStart ? moveLength : nowLength * reduceRate);
	if(nowLength < minSpeed) nowLength = minSpeed;
	selfPosition = selfPosition + nowLength * direction;
	if(direction == 1){
		if(selfPosition > targetPosition) selfPosition = targetPosition;
	}else{
		if(selfPosition < targetPosition) selfPosition = targetPosition;
	}
	var	nextfunc = 'setScroll('+selfPosition+','+targetPosition+','+direction+')';
//	$i('pageFooterArea').innerHTML += nextfunc+'：'+nowLength+'<br>';
	window.scrollTo(0,selfPosition);
	if(direction == 1){
		if(selfPosition >= targetPosition){
			clearTimeout(scrollTimer);
			nowLength = moveLength;
			return;
		}
	}else{
		if(selfPosition <= targetPosition){
			clearTimeout(scrollTimer);
			nowLength = moveLength;
			return;
		}
	}
	scrollTimer = setTimeout(nextfunc,moveSpeed);
}
function initNavigation(){
	if(!$N('a')){ return; }
	var aTag = $N('a');
	var aNum = aTag.length
	for(i=0;i<aNum;i++){
		var anchorFlg = aTag[i].href.indexOf('#');
		if(anchorFlg == -1) continue;

		var selfFlg = (aTag[i].href.split('#')[0] == location.href) ? true : false;
		if(selfFlg == false) continue;
		
		aTag[i].setAttribute("id", "self_"+[i]);
		// onClick時にリンク先に飛んでしまう（a hrefが有効になる）のを防ぐ為
		aTag[i].childId = aTag[i].href.split('#')[1];
		aTag[i].href = 'javascript:void(0)';

		aTag[i].onclick = function(e){
			clearTimeout(scrollTimer);
			var target = this.childId;
			posi = new Array;
			posi = getPosition(e,this.id,target);
			var arrow = posi[1] > posi[0] ? 1 : -1;
			
			setScroll(posi[0],posi[1],arrow);
		}
	}
}

/*
window.onload = function(){
	initNavigation();
}
*/

$(function(){
	$(window).load(function(){ initNavigation(); });
});
