var currentSlider = null;

function Slider(element, max)
{
	this.element = element;
	this.max = max;

	this.slider = null;
	this.counter = null;
	this.bar = null;
	this.cursor = null;
	this.moving = false;
	this.cursorPos = 0;
	this.cursorLeft = 0;

	this.mouseStart = 0;
	this.maxWidth = 0;

	this.create = function()
	{
		this.slider = document.createElement('div');
		this.slider.className = 'slider';

		this.counter = document.createElement('div');
		this.counter.className = 'slider_counter';
		this.counter.appendChild(document.createTextNode(this.cursorPos + '/' + this.max));

		this.bar = document.createElement('div');
		this.bar.className = 'slider_bar';

		this.cursor = document.createElement('div');
		this.cursor.className = 'slider_cursor';

		this.slider.appendChild(this.counter);
		this.slider.appendChild(this.bar);
		this.bar.appendChild(this.cursor);

		this.element.style.display = 'none';
		this.element.parentNode.appendChild(this.slider, this.element);

		this.cursor.slider = this;
	}

	this.create();

	var self = this;

	this.onMove = function(ev)
	{
		if (this.moving)
		{
			var x = getCursorPos(ev) - this.mouseStart + this.cursorLeft;

			if (x <= 0)
				x = 0;
			else if (x >= this.maxWidth)
				x = this.maxWidth;

			this.cursorPos = Math.round(x / this.maxWidth * this.max);
			this.cursor.style.left = Math.round(this.cursorPos / this.max * this.maxWidth ) + 'px';
			this.counter.firstChild.nodeValue = this.cursorPos  + '/' + this.max;
		}
	};

	this.cursor.onmousedown = function(ev)
	{
		var targ;

		if (!ev)
			var ev = window.event;

		if (ev.target)
			targ = ev.target;
		else if (ev.srcElement)
			targ = ev.srcElement;

		if (targ.nodeType == 3)
			targ = targ.parentNode;

  		self = targ.slider;

		self.maxWidth = self.bar.clientWidth;
		self.mouseStart = getCursorPos(ev);
		self.moving = true;

		currentSlider = self;
	};
}

function getCursorPos(ev)
{
	var x;

	if(ev.pageX || ev.pageY)
		x = ev.pageX;
	else
		x = ev.clientX + document.body.scrollLeft - document.body.clientLeft;

	return x;
}

document.onmousemove = function mouseMove(ev)
{
	if (currentSlider)
		var mousePos = currentSlider.onMove(ev || window.event);
}

document.onmouseup = function(ev)
{
	if (currentSlider)
	{
		var x = getCursorPos(ev || window.event);

		if (x <= 0)
			x = 0;
		else if (x >= currentSlider.maxWidth)
			x = currentSlider.maxWidth;

		currentSlider.cursorLeft = Math.round(currentSlider.cursorPos / currentSlider.max * currentSlider.maxWidth);
		currentSlider.moving = false;

		currentSlider.element.value = currentSlider.cursorPos;
		currentSlider.element.onchange();

		currentSlider = null;
	}
};

