/*
 *  (c) pulka Marek Mojzík, druha pulka Martin Cacky
 */

var Scrollbar = function(param)
{
	var container = document.getElementById(param.container);
	var scrollbar = document.getElementById(param.bar);
	var rod = document.getElementById(param.rod);

	container.className += " js-scrollbar";

	var rodWidth = rod.offsetWidth;
	var containerWidth, innerWidth, scrollbarWidth;

	var delta = scrollbar.offsetLeft;
	var currentX = null;

	scrollbar.onmousedown = function(e)
	{
		var event = window.event || e;
		move(event.clientX - delta);
		document.documentElement.onmousemove = function(e)
		{
			var event = window.event || e;
			move(event.clientX - delta);
		};
		document.documentElement.onmouseup = function(e)
		{
			document.documentElement.onmousemove = null;
			document.documentElement.onmouseup = null;
			
			document.onselectstart = function() {
                return true;
            };
		};
		document.onselectstart = function() {
            return false;
        };
		return false;
	};

	var move = function(x)
	{
	    currentX = x;
		var s = Math.min(Math.max((x - rodWidth / 2) / (scrollbarWidth - rodWidth), 0), 1);
		container.scrollLeft = s * (containerWidth - innerWidth)
		update();
	};

	var update = function()
	{
		var l = container.scrollLeft / (containerWidth - innerWidth) * (scrollbarWidth - rodWidth);
		rod.style.left = Math.round(l) + "px";
	};
	var resize = function()
	{
		scrollbarWidth = scrollbar.offsetWidth;
		containerWidth = container.scrollWidth;
		innerWidth = container.offsetWidth;
		if(param.rodWidth == "auto") rodWidth = (innerWidth / containerWidth) * scrollbarWidth;
		rod.style.width = Math.round(rodWidth) + "px";
		update();
	};
	
	var reset = function(jump) {
	    var x = currentX;
	    var jump = jump || 100;
	    var interval = 1;
        var id = window.setInterval(function() {
            move(x-jump);
            x -= jump;
            if (x <= 0) window.clearInterval(id);
        }, interval);
	        
	};

	resize();
	Scrollbar.onresize.push(resize);
	
    return {
        reset: reset
    };
};
Scrollbar.onresize = [];

window.onresize = function()
{
	for(var i = 0, r; r = Scrollbar.onresize[i]; i++) r();
}

