
function Slider(parent) {
	this.element = document.createElement('div');
	this.element.className = 'slider';
	
	parent.appendChild(this.element);
	
	this.handle = new SliderHandle(this);
	
	this.min = 0;
	this.setMaximum(10);
	this.value = 0;
	
	this.element.onselectstart = function() {
		return false;
	}
}


Slider.prototype.setMaximum = function(max) {
	this.max = max;
	this.range = (this.element.offsetWidth-this.handle.element.offsetWidth) / this.max;
}

Slider.prototype.setValue = function(val) {	
	var upd = this.value != val;
		
	if(val >= 0 && val <= this.max){
		this.value = val;
		var pos = Math.round(this.value) * this.range;
		this.handle.element.style.left = pos + 'px';
	}
	
	if(upd)
		this.update();
}

Slider.prototype.getValue = function() {
	return this.value;
}

Slider.prototype.update = function() {
	if((typeof this.onchange) == 'function')
		this.onchange();
}

Slider.prototype.setHandle = function(url){
	this.handle.setHandle(url);
}


function SliderHandle(parent) {
	this.element = document.createElement('div');
	this.element.className = 'sliderhandle';
	this.element.obj = this;
	
	this.img = document.createElement('img');
	this.img.border = 0;
	this.element.appendChild(this.img);
	
	var div = document.createElement('div');
	div.style.position = 'absolute';
	div.style.top = '0px';
	div.style.left = '0px';
	
	var span = document.createElement('span');
	span.style.width = '100%';
	span.style.height = '100%';
	div.appendChild(span);
	
	this.element.appendChild(div);	
	
	this.slider = parent;
	this.position = 0;
	
	parent.element.appendChild(this.element);
		
	this.eventMouseDown = this.startDrag.bindAsEventListener(this);
	this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
	this.eventMouseMove = this.update.bindAsEventListener(this);
	
	top.Event.observe(this.element, "mousedown", this.eventMouseDown);
	top.Event.observe(document, "mouseup", this.eventMouseUp);
	top.Event.observe(document, "mousemove", this.eventMouseMove);
}

SliderHandle.prototype.startDrag = function(event) {
	this.drag = true;
}

SliderHandle.prototype.update = function(event) {
	if(this.drag) {
		var left = getOffsetLeft(this.slider.element) + this.element.offsetWidth/2;
		var pos = Event.pointerX(event) - left;
		var max = this.slider.element.offsetWidth - this.element.offsetWidth;
		
		if(pos < 0)
			pos = 0;
		if(pos > max)
			pos = max;
		
		this.position = pos;
		this.element.style.left = pos + 'px';
	}
}

SliderHandle.prototype.endDrag = function(event) {
	if(this.drag) {
		var val = this.position / this.slider.range;
		this.slider.setValue(Math.round(val));
	}
	this.drag = false;
}

SliderHandle.prototype.setHandle = function(url) {
	this.img.src = url;
}
