/**
 * jQuery.insideScroll.js
 * Copyright (c) 2010 KEYTON.CO,Ltd.
 * Dual licensed under MIT and GPL.
 * Date: 2010-1-20
 * @author Hayashi Naoki
 * @version 1.0.2
 * 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 = getPath(document.URL.split("#")[0]);
		var win=$(window),doc=$(document),tmpPos={},offGoal={},offScroll={},maxH,maxW;
		var elScroll = window.opera ? document.compatMode=='BackCompat'?'body':'html':'html,body';
		return this.each(function(){
			var oClick = $(this);
			if(oClick.attr('href')=="#")return;
			var cID = oClick.attr('href').split('#');
			if(cID[0] != '' && getPath(cID[0]) != hereUrl)return;
			var oObj = $('#'+cID[1]+',[name="'+cID[1]+'"]').length ? $('#'+cID[1]+',[name="'+cID[1]+'"]').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 = oObj.offset();
						offScroll = el.offset();
						offGoal.top = offGoal.top - offScroll.top;
						offGoal.left = offGoal.left - offScroll.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+'#'+cID[1]);
				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(e){
							$(this).queue([]).stop();
						});
					},
					complete:function(){
						$(this).queue([]).stop();
						if(aUrl && option.replace){window.location.href=aUrl};
				 	}
				}
			);
		}
		function getPath(p){
			var h = new Image;
			h.src = p;
			return h.src;
		}
	}
	$("a[href*='#']").insideScroll();
});
