var scrollamount = 16; // should match lineheight

var scrolling = false;
var scrolldiv;
var multiplier;
var sTimeout = null;
var stop = false;

function initScroll(d) {
	// see if text overflows container
	if ($(d+'text').offsetHeight > $(d+'textcontainer').offsetHeight) {
		// calc and store max scrollup
		$(d+'text').setAttribute('mt', $(d+'textcontainer').offsetHeight - $(d+'text').offsetHeight - scrollamount);
		// reduce container height to make room for scroll nav
		$(d+'textcontainer').style.height = ($(d+'textcontainer').offsetHeight - scrollamount) + 'px';
		// hide scrollup for now
		as = $(d+'bottomscroll').getElementsByTagName('a');
		as[0].style.visibility = 'hidden';
		// show scrolldown for now
		$(d+'bottomscroll').style.display = 'block';
	}
}

// this function not used anymore
function scrollIt(d, m) {
	// get previously stored max scrollup
	thismt = $(d+'text').getAttribute('mt');
	// calc proposed new text style.top
	nt = (parseInt($(d+'text').offsetTop) + (m * scrollamount));
	if (nt <= 0 && nt >= thismt && !scrolling) {
		scrolling = true;
		new Effect.Morph(d+'text', { style: "top:" + nt + "px", duration: 0.5, afterFinish: function () { scrolling = false; } });
		as = $(d+'bottomscroll').getElementsByTagName('a');
		as[0].style.visibility = nt == 0 ? 'hidden' : 'visible';
		as[1].style.visibility = nt == thismt ? 'hidden' : 'visible';
	}
}

function scrollOnce() {
	// get previously stored max scrollup
	thismt = $(scrolldiv+'text').getAttribute('mt');
	// calc proposed new text style.top
	nt = (parseInt($(scrolldiv+'text').offsetTop) + (multiplier * scrollamount));
	if (nt <= 0 && nt >= thismt && !stop) {
		if (!scrolling) {
			scrolling = true;
			new Effect.Morph(scrolldiv+'text', { style: "top:" + nt + "px", duration: 0.35, transition: Effect.Transitions.linear, afterFinish: function () { scrolling = false; sTimeout = setTimeout(scrollOnce, 0); } });
			as = $(scrolldiv+'bottomscroll').getElementsByTagName('a');
			as[0].style.visibility = nt == 0 ? 'hidden' : 'visible';
			as[1].style.visibility = nt == thismt ? 'hidden' : 'visible';
		}
	}
	else {
		stop = false;
	}
}

function startScroll(d, m) {
	// d = div to scroll
	// m = multiplier (1 for scrollup, -1 for scrolldown)
	
	scrolldiv = d;
	multiplier = m;
	
	scrollOnce();
}

function stopScroll() {
	stop = true;
}
