var ANCHOR_APP = ANCHOR_APP || {};

ANCHOR_APP.util = {};

ANCHOR_APP.util.window = (function () {
	var

		_canScrollTop1 = (document.documentElement) ? !isNaN(document.documentElement.scrollTop) : undefined,	//document.documentElement.scrollTopが使えるか
		_canScrollTop2 = (document.body) ? !isNaN(document.body.scrollTop) : undefined,	//document.body.scrollTopが使えるか
		_canScrollTop3 = !isNaN(window.scrollTop),	//window.scrollTopが使えるか

		/**
		 * ページをスクロール
		 *
		 * @param targetName {String} 移動対象のアンカー名（#hogehoge）
		 * @param option {Object}
		 * 		time {Number} スクロール時間
		 * 		isTimeWithDistance {Boolean} スクロール時間を移動距離から計算するか
		 * 		ease {String} イージング
		 * 		onComplete {Function} コールバック
		 * @return スクロールに成功したか
		 */
		scrollTo = function (targetName, option) {
			var targetElements = $("a[name=" + targetName.replace("#","") + "]"),	//移動先の要素
				headerHeight = $("#header2ndContainer").outerHeight() || 0,	//ヘッダーの高さ
				scrollTop = Number($(window).scrollTop()),	//ページのスクロール位置
				positionTop,	//移動先のtop
				o = option || {},
				time = o.time || 600,
				ease = o.ease || "easeOutCubic",
				isTimeWithDistance = o.isTimeWithDistance || false,
				onComplete = o.onComplete || undefined;

			if(targetElements.length > 0) {
				positionTop = Number($(targetElements[0]).position().top);

				if (isTimeWithDistance) {
					time = Math.abs(scrollTop - positionTop) / 1000 * time;	//移動距離から時間を計算
				}
				
				$("html, body")
					.stop()
					.animate({
						scrollTop: positionTop - headerHeight//ヘッダーの高さ分を引く
					}, time, ease, function () {
//						document.location.hash = targetName.replace("#", "");	//本来のハッシュを設定。"#"は削除しなくてもいいはず
						if(onComplete) {
							onComplete.apply(this);
						}
					});

				return true;
			}
			else {
				return false;
			}
		},

		/**
		 * 縦方向のスクロール
		 *
		 * @param y {Number} y座標
		 */
		scrollY = function (y) {
			if(_canScrollTop1) {
				document.documentElement.scrollTop = y;
			}

			if(_canScrollTop2) {
				document.body.scrollTop = y;
			}

			if(_canScrollTop3) {
				window.scrollTop = y;
			}
		};
	
	return {
		scrollTo: scrollTo,
		scrollY: scrollY
	};
}());

ANCHOR_APP.util.hashObserver = (function () {
	var
		_hash = document.location.hash,
		_intervalId,

		/**
		 * 監視を開始
		 *
		 * @param interval {Number} 監視の間隔（ミリ秒）
		 */
		start = function (interval) {
			if(_intervalId) {
				clearInterval(_intervalId);
			}
			_intervalId = setInterval(_observer, interval || 100);
		},

		/**
		 * 監視を停止
		 *
		 */
		stop = function () {
			if(_intervalId) {
				clearInterval(_intervalId);
				_intervalId = undefined;
			}
		},

		/**
		 * 監視
		 * 
		 */
		_observer = function () {
			if(document.location.hash != _hash) {
				_hash = document.location.hash;
				$(window).trigger("hashChanged", [_hash]);
			}
		};

	return {
		start: start,
		stop: stop
	};
}());

$(function () {
	var windowUtil = ANCHOR_APP.util.window,
		hashObserver = ANCHOR_APP.util.hashObserver,
		dataHolder = ANCHOR_APP.data,

		//---------------------------------
		//  variable
		//----------------------------------
		isIE7lt = !$.support.hrefNormalized,	//ie7以下か
		_hashChangeListener;


	//アンカーのリンクを書き換え
	$("a[name]").each(function () {
		if(!isIE7lt) {
			//IE6,7以外
			this.name = this.name + "_";	//単純にnameを変更
		}
		else {
			//IE6 or IE7の場合、name属性が振り替えられてしまうので、要素自体を入れ替える
			var $me = $(this),
				prev = $me.prev(),	//前の要素
				parent = $me.parent(),	//親要素
				newElement = document.createElement('<a name="' + this.name + '_"></a>');	//新たに要素を作成

			$me.remove();
			$(newElement).html($me.html());	//要素をコピー

			//配置
			if(prev.length != 0) {
				//兄弟がいた場合、その次に配置
				prev.after(newElement);
			}
			else {
				//兄弟がいなかった場合、親の1番目に配置
				parent.prepend(newElement);
			}
		}
	});

	//ページ内アンカーの設定
	$("a[href*=#]")
		.each(function () {
			var $me = $(this),	//aタグ
				href = $me.attr("href"),	//hrefの文字列
				toUrl = href.substring(0, href.indexOf("#")).replace(/[\.]+\/|/, "");	//ハッシュを除いたリンクを取得。"../"、"./"は削除

			if(toUrl == "" || document.location.href.replace(document.location.hash, "").match(toUrl)) {
				//同じページなら
				$me.click(function (e) {
					var targetName = href.substring(href.indexOf("#")) + "_",	//アンカー名。アンカーは書き換えられるので、文字を追加しておく
						timeOrg = $me.attr("time"),	//指定された効果時間
						time,	//効果時間
						ease = $me.attr("ease"),	//イージングタイプ
						isTimeWithDistance,	//時間を距離から計算するか
						result;

					if($me.attr("time")) {
						time = Number(timeOrg.replace(/!/g, ""));
						isTimeWithDistance = Boolean(timeOrg.match("!"));
					}

					result = windowUtil.scrollTo(targetName, {
						time: time,
						isTimeWithDistance: isTimeWithDistance,
						ease: ease
					});

					if(result) {
						e.preventDefault();
					}
				});
			}
		});

	//ハッシュありならスクロール
	if(document.location.hash) {
		var hash = document.location.hash;

		windowUtil.scrollY(0);
		$(window).bind("load", function () {
			windowUtil.scrollTo(hash + "_", {
				isTimeWithDistance: true
			});
		});
	}

	$(window).bind("hashChanged", function (e, hash) {
		windowUtil.scrollTo(document.location.hash + "_");
	});
	hashObserver.start(100);
});


(function () {
	var windowUtil = ANCHOR_APP.util.window;
	if(document.location.hash) {
		windowUtil.scrollY(0);	//Fx用
	}
}());
