/**
 * jQuery.insideScroll.js
 * Copyright (c) 2010 KEYTON.CO,Ltd.
 * Dual licensed under MIT and GPL.
 * Date: 2010-5-20
 * @author Hayashi Naoki
 * @version 1.0.3
 * http://www.keyton-co.jp/
 */
jQuery(function($){
	$.fn.insideScroll=function(option){
		option = option || {};
		option.duration = option.duration || 800;
		option.easing   = option.easing   || 'swing';
		option.replace  = option.replace  || false;
		var hereUrl = document.URL.split("#")[0];
		var win=$(window),doc=$(document),tmpPos={},offGoal={},maxH,maxW;
		var elScroll = window.opera ? document.compatMode=='BackCompat'?'body':'html':'html,body';
		return this.each(function(){
			var oClick = $(this);
			var cID = oClick.attr('href').split('#');
			var oID = cID[1];
			if(cID[0] != '' && cID[0] != hereUrl)return;
			var oObj = $('#'+oID+',[name="'+oID+'"]').length ? $('#'+oID+',[name="'+oID+'"]').eq(0) : $('body') ;
			var sObj = oObj;
			oObj.parents(':not(html,body)').each(function(){
				var el = $(this);
				if(el.css('overflow')!='visible'){
					oClick.bind('click',function(){
						tmpPos.t = el.scrollTop();
						tmpPos.l = el.scrollLeft();
						el.scrollTop(0).scrollLeft(0);
						offGoal.top = oObj.offset().top - el.offset().top;
						offGoal.left = oObj.offset().left - el.offset().left;
						el.scrollTop(tmpPos.t).scrollLeft(tmpPos.l);
						iScroll(el,offGoal);
					});
					sObj = el;
					return;
				}
			});
			oClick.bind('click',function(){
				offGoal = sObj.offset();
				maxH = doc.height() - win.height();
				maxW = doc.width() - win.width();
				if(offGoal.top > maxH){offGoal.top = maxH;}
				if(offGoal.left > maxW){offGoal.left= maxW;}
				iScroll($(elScroll),offGoal,hereUrl+'#'+oID);
				return false;
			});
		});
		function iScroll(scrollObj,of,aUrl){
			scrollObj.animate(
				{scrollTop:of.top,scrollLeft:of.left},
				{
					duration:option.duration,
					easing:option.easing,
					step:function(){
						$(this).bind('mousedown mousewheel DOMMouseScroll',function(){
							$(this).queue([]).stop();
						});
					},
					complete:function(){
						$(this).queue([]).stop();
						if(aUrl && option.replace){window.location.href=aUrl};
				 	}
				}
			);
		}
	}
	$("a[href*='#']").insideScroll();
});
