
var moving = false;
var speed = 5;
var increment = 0.04;

$$('.scrollable').each(function(s) {
	var panel_id = s.id;
	var scrollbar_id = panel_id + '-scroll';
	var vscrollbar_id = panel_id + '-vscrollbar';
	var vbuttonup_id = panel_id + '-vbuttonup';
	var vtrack_id = panel_id + '-vtrack';
	var vhandle_id = panel_id + '-vhandle';
	var vbuttondown_id = panel_id + '-vbuttondown';
	
	if (!$(scrollbar_id)) {
		return;
	}
	
	$(scrollbar_id).innerHTML = '<div id="' + vscrollbar_id + '" class="vscrollbar">'
				+ '<div id="' + vbuttonup_id + '" class="vbuttonup"></div>'
				+ '<div id="' + vtrack_id + '" class="vtrack">'
					+ '<div id="' + vhandle_id + '" class="selected vhandle"></div>'
				+ '</div>'
				+ '<div id="' + vbuttondown_id + '" class="vbuttondown"></div>'
			+ '</div>';
	
	var vslider = new Control.Slider(vhandle_id, vtrack_id, {
		axis: 'vertical',
		onSlide: function(v) { scrollVertical(v, $(panel_id), vslider); },
		onChange: function(v) { scrollVertical(v, $(panel_id), vslider); }
	});
	
	Event.observe(vbuttonup_id, 'mousedown', function() {
		moving = true;
		new PeriodicalExecuter(function(pe) {
			vslider.setValue(vslider.value - increment);
			if (!moving) {
				pe.stop();
			}
		}, speed/100);
	});
	Event.observe(vbuttonup_id, 'mouseup', stop);
	Event.observe(vbuttonup_id, 'mouseout', stop);
	Event.observe(vbuttondown_id, 'mousedown', function() {
		moving = true;
		new PeriodicalExecuter(function(pe) {
			vslider.setValue(vslider.value + increment);
			if (!moving) {
				pe.stop();
			}
		}, speed/100);
	});
	Event.observe(vbuttondown_id, 'mouseup', stop);
	Event.observe(vbuttondown_id, 'mouseout', stop);
	
	$(panel_id).style.overflow='hidden';
	
	// disable vertical scrolling if text doesn't overflow the div
	if ($(panel_id).scrollHeight <= $(panel_id).offsetHeight) {
		vslider.setDisabled();
		$(vscrollbar_id).hide();
	}
});

function stop() {
	moving = false;
}

// scroll the element vertically based on its width and the slider maximum value
function scrollVertical(value, element, slider) {
	element.scrollTop = Math.round(value / slider.maximum * (element.scrollHeight - element.offsetHeight));
}

