//
// SCROLLER
//

(function($){
	
	var $ = jQuery;

	var container = null;
	var scroller = null;

	jQuery.fn.scroller = function(){
	
		container = $(this);
		scroller = $(this).children();
					
		container.css("position", "relative"); scroller.css("position", "absolute").css("top", "0");
	
		if(count_height(scroller)<=container.outerHeight({margin: true})) return;
		minTop = container.outerHeight({margin: true}) - count_height(scroller);
		
		container.mouseover(scroll);
		container.mouseout(function(){
			clearTimeout(scroll_timeout);
		})
		$().mousemove(function(e){
			mouse_x = e.pageX;
			mouse_y = e.pageY;
		});
	
	
	
	};

	var scroll_timeout = null;
	var mouse_x = null;
	var mouse_y = null;

	var minTop = null;

	var scroll = function(e){
		var pos = $(this).offset();
		var rLeft = mouse_x - pos.left;
		var rTop = mouse_y - pos.top;
		var height = $(this).outerHeight();
				
		var scrollzone = 40; // @TODO make scrollzone settable
			
		if(rTop>0 && rTop<scrollzone)
		{
			scroll_do("3"); // we move it up by 1 pixel
		}
	
		if(rTop>(height-scrollzone) && rTop<height)
		{
			scroll_do("-3"); // we move it down by 1 pixel
		}
	
		scroll_timeout = setTimeout(function(){container.trigger("mouseover")}, 30);
	};

	var scroll_do = function(size)
	{
		var current = scroller.css("top");
		current = current.replace("px", "");

		var newTop = parseInt(current)+parseInt(size);
		
		if(newTop>0) newTop = 0;
		scroller.css("top", newTop);
		if(newTop == 0) return;
		
		//var max = 
		if(newTop < minTop) newTop = minTop;
		scroller.css("top", newTop);
		if(newTop == minTop) return;

		scroller.css("top", newTop);
	}

	var count_height = function(el){
		var height = 0;
		$(el).children().each(function(){
			height += $(this).outerHeight({margin:true});
		});
	
		return height;
	};

})();
