/* vscroll - jQuery plugin 1.0
 * Revision: $Id: jquery.vscroll.js,v 1.3 2010/12/09 14:14:55 dedukhin Exp $
 */

(function($) {
	$.fn.vscroll = function(options){
		$.fn.vscroll.defaults = {
			multiplier: 4,
			up_arrow_class: 'scrollbar-arrow-up',
			down_arrow_class: 'scrollbar-arrow-down'
		};
		var opts = $.extend({}, $.fn.vscroll.defaults, options);
		return this.each(function() {
			var timer = null;
			var lastWheelDirection = 0;
			var $scrollpane = $(this);
			var $scrollcontainer = $(this).parent();
			var scrollcontainer_height = 0, scrollpane_height = 0;
			var $ua = $('.'+opts.up_arrow_class, $scrollpane.next());
			var $da = $('.'+opts.down_arrow_class, $scrollpane.next());
			// let's bind event handlers
			$('body').bind('mouseup', function(e) {
				stopTimedout(300);
			});
			$ua.bind('mousedown', function(e) {
				$(this).blur();
				move('up');
				return false;
			});
			$da.bind('mousedown', function(e) {
				$(this).blur();
				move('down');
				return false;
			});
			$scrollcontainer.bind('mousewheel', function(e, delta) {
				direction = (delta < 0 ? -1 : +1);
				if(lastWheelDirection != direction) {
					$scrollpane.stop(true); // stop animation
				}
				lastWheelDirection = direction;
				move(delta < 0 ? 'down' : 'up', 2); // speedup wheel
				stopTimedout(500);
				return false;
			});
			var move = function(to, speedup) {
				if(scrollcontainer_height == 0 || scrollpane_height == 0) {
					scrollcontainer_height = $scrollcontainer.height();
					scrollpane_height = $scrollpane.innerHeight();
				}
				if(to == 'down') {
					to = scrollcontainer_height - scrollpane_height;
				} else {
					to = 0;
				}
				if(!speedup) speedup = 1;

				var deltaY = to - parseInt($scrollpane.css('top'));
				if(deltaY == 0) return;

				var delay = Math.abs(deltaY * opts.multiplier) / speedup;
				if(delay < 600) delay = 600;

				if($scrollpane.queue().length == 0) { // start animation if not start yet
					$scrollpane.animate({'top': to}, delay);
				}
			};
			var stopTimedout = function(t) {
				clearTimeout(timer);
				timer = null;
				timer = setTimeout(function() {
					timer = null;
					lastWheelDirection = 0;
					$scrollpane.stop(true); // stop animation
				}, t);
			};
		});
	};
})(jQuery);

