var _starbars = { };

function StarBar(id, imgActive, imgInactive, imgW, imgH, maxValue, value, editable)
{
	this.value     = value;
	this.tmpvalue  = 0;
	this.maxvalue  = maxValue;
	this.id        = id;
	this.imgSize   = { 'width' : imgW, 'height' : imgH };
	this.imgActive = imgActive;
	this.imgInactive = imgInactive;
	this.state     = 1;
	this.editable = editable;
	this.handlerOnChange = null;
	
	this.getValueByX = function (x)
	{
		return Math.ceil(x / this.imgSize['width']);
	}

	this.update = function (value)
	{		
		for (var i = 0; i < this.maxvalue; i++)
		{
			if (i + 1 <= value)
				iSrc = this.imgActive;
			else
				iSrc = this.imgInactive;
				
			if ($(this.id + '_sbimg_' + (i + 1))) {
				$(this.id + '_sbimg_' + (i + 1)).src = iSrc;
			}
		}
	}
	
	this.onMouseMove = function (event)
	{
		starbar = _starbars[this.id];
		
		if (starbar.state > 1)
			return;
					
		vp = this.viewportOffset();
		localx = event.clientX - vp['left'];
		localy = event.clientY - vp['top'];		
		
		starbar.tmpvalue = starbar.getValueByX(localx);
		starbar.update(starbar.tmpvalue);		
	}
	
	this.onMouseClick = function (event)
	{
		starbar = _starbars[this.id];
		if (starbar.state == 1)
		{
			starbar.setValue(starbar.tmpvalue);
			starbar.state = 2;
		}
		else
		{
			vp = this.viewportOffset();
			localx = event.clientX - vp['left'];
			starbar.setValue(starbar.getValueByX(localx));
			starbar.update(starbar.value);
		}
	}
	
	this.setValue = function (value)
	{
		this.value = value;
		if (this.handlerOnChange)
			this.handlerOnChange(this);
	}
	
	var code = '';
	for (var i = 0, x = 0; i < this.maxvalue; i++)
		code += '<img src="' + imgInactive + '" alt="" id="' + this.id + '_sbimg_' + (i + 1) + '"/>';

	this.container = $(this.id);
	if (this.container)
	{
		this.container.innerHTML = code;
		if (this.editable)
		{
			this.container.observe('mousemove', this.onMouseMove);
			this.container.observe('click', this.onMouseClick);
		}
		this.container.style.width = this.imgSize['width'] * this.maxvalue + 2 +'px';
		
		this.update(this.value);
		
		_starbars[this.id] = this;
	}
	else
		alert('StarBar error: invalid container id');
}
