// JavaScript Document
/**
 * pagescroll
 *
 * @category   jQuery
 * @package    pagescroll
 * @version    0.6
 * 
 * require jquery
 * require jquery.easing
 *
 */
(function ($) {
	$.fn.pagescroll = function (options) {
		options = $.extend({
			scrollTarget: 'html, body',
			speed: 500,
			easing: 'swing'
		}, options);
		
		var $this = $(this);
		var nowAnimate = false;
		
		if ($.browser.webkit && options.scrollTarget == 'html, body') options.scrollTarget = 'body';
		
		function init() {
			$this.each(function () {
				var $a = $(this);
				var hrefAnchor = '#' + $a.attr('href').replace(/#/,'');
				var anchorPos = $(hrefAnchor).offset();
				if (anchorPos == null) {
					anchorPos = {top:0};
				}
				$a.attr('href', 'javascript:;');
				$a.click(function () {
					if (nowAnimate) return;
					var targetPos = $(options.scrollTarget).offset();
					var targetHeight = $(options.scrollTarget).height();
					if (options.scrollTarget == 'html, body') {
						targetHeight = $('body').height();
					}
					var windowHeight = $(window).height();
					var maxPos = targetHeight - windowHeight;
					var scrollPos = anchorPos.top;
					if (maxPos < anchorPos.top) scrollPos = maxPos;
					nowAnimate = true;
					$(options.scrollTarget).animate({
						scrollTop: scrollPos
					},
					{
						duration: options.speed,
						easing: options.easing,
						complete: function () { nowAnimate = false; }
					});
				});
			});
			return $this;
		}
		
		return init();
	}
	
	$.fn.moveTarget = function (options) {
		var options = $.extend({
			scrollTarget: 'html, body',
			speed: 500,
			easing: 'swing'
		}, options);

		var $this = $(this);
		var nowAnimate = false;
		
		if ($.browser.webkit && options.scrollTarget == 'html, body') options.scrollTarget = 'body';
		
		var targetPos = $(options.scrollTarget).offset();
		var targetHeight = $(options.scrollTarget).height();
		if (options.scrollTarget == 'html, body') {
			targetHeight = $('body').height();
		}
		
		var initialize = function () {
			var anchorPos = $this.offset();
			if (anchorPos == null) {
				anchorPos = {top:0};
			}
			
			if (nowAnimate) return;
			var windowHeight = $(window).height();
			var maxPos = targetHeight - windowHeight;
			var scrollPos = anchorPos.top;
			if (maxPos < anchorPos.top) scrollPos = maxPos;
			nowAnimate = true;
			$(options.scrollTarget).animate({
				scrollTop: scrollPos
			},
			{
				duration: options.speed,
				easing: options.easing,
				complete: function () { nowAnimate = false; }
			});
		};
		
		return initialize();
	};
})(jQuery);
