var maxScrollBars = 25;
var direction = new Array(maxScrollBars); // 0 - vertical, 1 - orizontal
var maxPos = new Array(maxScrollBars);
var scrollBox = new Array(maxScrollBars); // the container div
var ratio = new Array(maxScrollBars);

var current = 0;
var offset = 0;
var isDragging = false;
var dragObject = null;
var scrollBars = 0;

document.onselectstart = function() { return false; }
document.onmousemove = scrollmM;
document.onmouseup = scrollmU;

function addScrollbar(id, pDirection, scrollItem, buttonItem, scrollHeight) {
	direction[id] = pDirection;
	scrollBox[id] = document.getElementById(scrollItem);
	var maxScroll = 0;
	if(pDirection == 0)
		maxScroll = scrollBox[id].offsetHeight - scrollHeight;
	else
		maxScroll = scrollBox[id].offsetWidth - scrollHeight;
	var btnSize = 30;
	if(maxScroll < 0) {
		btnSize = scrollHeight;
		ratio[id] = -1;
		maxPos[id] = 0;
	}
	else {
		btnSize = (scrollHeight * scrollHeight) / (maxScroll + scrollHeight);
		if(btnSize < 20) btnSize = 20;
		maxPos[id] = scrollHeight - btnSize;
		ratio[id] = maxScroll / maxPos[id];
	}
	
	var d = document.getElementById(buttonItem);
	d.ondrag = function() { return false; }
	d.onselectstart = function() { return false; }
	if(direction[id] == 0) {
		d.style.height = btnSize + "px";
		d.style.marginTop = "0px";
		scrollBox[id].style.marginTop = "0px";
	}
	else {
		d.style.width = btnSize + "px";
		d.style.marginLeft = "0px";
		scrollBox[id].style.marginLeft = "0px";
	}

	scrollBars++;
}

function scrollmD(id, ob, e) {
	if(ratio[id] < 0) return false;
	dragObject = ob;
	current = id;
	if(window.event) e = window.event;
	var target = e.target != null ? e.target : e.srcElement;
	var dragX = parseInt(dragObject.style.marginLeft);
	var dragY = parseInt(dragObject.style.marginTop);
	var mouseX = e.clientX;
	var mouseY = e.clientY;
	if(direction[id] == 0)
		offset = mouseY - dragY;
	else
		offset = mouseX - dragX;
	isDragging = true;
	document.onselectstart = function() { return false; }
	target.ondragstart = function() { return false; }
	document.body.focus();
	return false;
}

function scrollmM(e) {
	if(!isDragging) return;
	if(window.event) e = window.event;
	
	if(direction[current] == 0) {
		var newY = e.clientY - offset;
		if(newY < 0) newY = 0;
		if(newY > maxPos[current]) newY = maxPos[current];
		scrollBox[current].style.marginTop = "-" + (newY * ratio[current]) + "px";
		dragObject.style.marginTop = newY + "px";
	} else {
		var newX = e.clientX - offset;
		if(newX < 0) newX = 0;
		if(newX > maxPos[current]) newX = maxPos[current];
		scrollBox[current].style.marginLeft = "-" + (newX * ratio[current]) + "px";
		dragObject.style.marginLeft = newX + "px";
	}
	document.body.focus();
	return false;
}

function scrollmU() {
	if(!isDragging) return;
	isDragging = false;
	document.body.focus();
	return false;
}
