Star = new Class({
	initialize: function(percent, star_system, position)
	{
		this.position = position;
		this.star_system = star_system;
		this.percent = percent;
		this.star_empty = new Element('div', {'class':'star'});
		this.star_empty.me = this;
		this.star_empty.injectInside(this.star_system.box);
		this.star_full = new Element('div', {'style':'width: ' + percent + '%'});
		this.star_full.me = this;
		this.star_full.injectInside(this.star_empty);
		
		var me = this;
		window.addEvent('domready', function(){
			me.reset();
		});
	},
	
	fillTo: function()
	{
		this.star_system.fillTo(this.position);
	},
	
	fill: function()
	{
		this.star_full.setStyle('width', '100%');
	},
	
	clear: function()
	{
		this.star_full.setStyle('width', '0%');
	},
	
	reset: function()
	{
		this.star_full.setStyle('width', this.percent + '%');
	},
	
	setTo: function()
	{
		this.star_system.setTo(this.position);
	},
	
	set: function(percent)
	{
		this.percent = percent;
	}
});

StarRating = new Class({
	initialize: function(average, star_count)
	{
		this.average = average;
		this.full_stars = 0;
		this.stars = new Array(star_count);
		
		this.box = new Element('div', {'class':'starbox'});
	
		var i = average * star_count;
		
		for(var s = 0; s < this.stars.length; s++)
		{
			if(i >= 100)
			{
				this.stars[s] = new Star(100, this, s);
				i -= 100;
				this.full_stars++;
			}
			else
			{
				this.stars[s] = new Star(i, this, s);
				i = 0;
			}
		}
	},
	
	fillTo: function(position)
	{
		for(var i = 0; i <= position; i++)
		{
			this.stars[i].fill();
		}
		
		for(; i < this.stars.length; i++)
		{
			this.stars[i].clear();
		}
	},
	
	reset: function()
	{
		for(var i = 0; i < this.stars.length; i++)
		{
			this.stars[i].reset();
		}
	},
	
	setTo: function(position)
	{
		for(var i = 0; i <= position; i++)
		{
			this.stars[i].set(100);
		}
		
		for(; i < this.stars.length; i++)
		{
			this.stars[i].set(0);
		}
		
		if(this.inputField)
		{
			this.inputField.value = position + 1;
		}
	},
	
	inputMode: function(name)
	{
		this.inputField = new Element('input', {'type': 'hidden', 'name': name, 'value': this.full_stars});
		this.inputField.injectInside(this.box);
		
		for(var s = 0; s < this.stars.length; s++)
		{
			this.stars[s].star_empty.addEvent('mouseover', function(e){
				e = new Event(e);
				e.target.me.fillTo();
			});
			
			this.stars[s].star_empty.addEvent('mouseout', function(e){
				e = new Event(e);
				e.target.me.star_system.reset();
			});
			
			this.stars[s].star_full.addEvent('click', function(e){
				e = new Event(e);
				e.target.me.setTo();
			});
		}
	}
});


