// scrollcontrol.js

function scrollcontrol(name, min, max, value, width, scale, hidden) {

	if (min === undefined) min = 0;
	if (max === undefined) max = 100;
	if (value === undefined) value = min;
	if (width === undefined) width = 200;

	this.scale = (scale !== undefined) ? scale : 1;

	this.scrollControl = document.createElement('div');
	this.scrollControl.style.position = 'relative';

	this.scrollValue = document.createElement('input');
	this.scrollValue.id = name;
	this.scrollValue.name = name;
	this.scrollValue.type = (hidden) ? "hidden" : "text";
	this.scrollValue.size = 4;
	this.scrollValue.value = value;
	this.scrollValue.style.position = 'absolute';
	this.scrollValue.style.left = width + 'px';
	this.scrollValue.style.top = '0px';
	this.scrollValue.style.height = '16px';
	this.scrollValue.style.fontSize = '10px';
	this.scrollValue.style.padding = 0;
	this.scrollValue.style.margin = 0;



	this.scroller = document.createElement('div');
		this.scroller.onscroll =_scrollcontrol_scroll_callback(this.scrollValue, this.scale);
		this.scroller.style.width = width + "px";
		this.scroller.style.height = "16px";
		this.scroller.style.overflow = "auto";
		//div_0.scrollLeft=80;//(value - min,0);

	_scrollcontrol_watch(this.scrollControl, this.scroller, this.scrollValue, this.scale);
	this.scrollValue.onblur  = _scrollcontrol_blur_callback( this.scroller, this.scale );

	this.div_scroller = document.createElement('div');
		this.div_scroller.style.width = (((max - min) * this.scale) + width) +"px";
		this.div_scroller.style.height = "20px";
		this.div_scroller.id = "scroller_"+name;
		this.div_scroller.appendChild( document.createTextNode(" ") );

	// The following ugliness occurs due to the fact that you can't alter scrollLeft until something is on the page


	this.scroller.appendChild( this.div_scroller );

	this.scrollControl.appendChild( this.scroller );
	this.scrollControl.appendChild( this.scrollValue );

}

function _scrollcontrol_scroll_callback(scrollValue, scale){
	return function(){
		scrollValue.value = Math.round(this.scrollLeft / scale);
		if(scrollValue.onchange) scrollValue.onchange();
	};
}

function _scrollcontrol_blur_callback(scroller, scale){
	return function(){ scroller.scrollLeft = this.value * scale };
}

function _scrollcontrol_watch(scrollControl, moveThis, where, scale){
	if (scrollControl.parentNode) {
		moveThis.scrollLeft = where.value * scale
	}
	setTimeout(function(){ _scrollcontrol_watch(scrollControl, moveThis, where, scale) }, 200);
}
