// An object for scrolling the content withing a div
// within a box of a given size

// Example:
// 	var s = new Scrollable('mydiv', 100, 100);
// 	document.getElementById('downarrow').onclick = 's.scrollBy(0, 10)';
// 	document.getElementById('uparrow').onclick = 's.scrollBy(0, -10)';


// Constructor
// 		id: the id of the element to make scrollable
//		width: the width of the visable area
//		height: the height of the scrollable area
function Scrollable(id, width, height) {
	this._id = id;
	this._e = document.getElementById(id);
	this.width = width;
	this.height = height;
	
	this._objheight = this._e.offsetHeight;
	this._objwidth = this._e.offsetWidth;
	this._objtop = this._e.style.top.replace(/[^0-9]/g,'');
	this._objleft = this._e.style.left.replace(/[^0-9]/g,'');
	this._objtop = this._objtop ? this._objtop : 0;
	this._objleft = this._objleft ? this._objleft : 0;
	
//	this._e.style.width = width + 'px';
//	this._e.style.height = height + 'px';
	
	this.setScroll(0,0);
	
	return this;
}

// Scroll div to specific x(horizontal) and y(vertical) offset
Scrollable.prototype.setScroll = function(x, y) {

	this._e.style.scrollTop = this._e.style.scrollTop + x;
	// range limit
	if ( x < 0 ) x = 0;
	if ( y < 0 ) y = 0;
	if ( x > (this._objwidth - this.width) ) x = this._objwidth - this.width;
	if ( y > (this._objheight - this.height) ) y = this._objheight - this.height;	

	this.scrollx = x;
	this.scrolly = y;
	
	this._e.style.clip = this._clip(
		this.scrolly, this.scrollx + this.width, this.scrolly + this.height, this.scrollx	);
	this._e.style.left = (this._objleft - this.scrollx) + 'px';
	this._e.style.top = (this._objtop - this.scrolly) + 'px';
}

// Scroll div by given number of x(horizontal) and y(vertical) pixels
// Negative numbers scroll up/left, positive numbers scroll down/right
Scrollable.prototype.scrollBy = function(dx, dy) {
	this.setScroll(this.scrollx + dx, this.scrolly + dy);
}

// Scroll the div so the child element with the given id is at the top
Scrollable.prototype.scrollToId = function(id) {
	var elem = document.getElementById(id);
	this.setScroll(0, 0);
	this.scrollBy(elem.offsetLeft, elem.offsetTop);
}

Scrollable.prototype._clip = function(top, right, bottom, left) {
	return 'rect('+top+'px '+right+'px '+bottom+'px '+left+'px)';
//	return 'rect('+top+' '+right+' '+bottom+' '+left+')';
}