
var RatingStars = new Class({
	Implements: [Options, Events],

	options: {
		container: null,
		readOnly: false,
		mini: false,
		rating: 0.0,
		label: false,
		hidden: false
	},

	initialize: function(options) {
		this.setOptions(options);

		this.element = new Element('div', {'class': 'rate'});
		if (this.options.hidden) this.element.hide();
		this.options.container.grab(this.element);

		if (this.options.label)
			this.element.grab(new Element('p', {'class': 'rate', text: 'Rate'}));

		for (var i=0; i<5; i++)
			this.element.grab(new Element('span', {'class': 'star empty'}));

		this.stars = this.element.getChildren('span.star');

		if (this.options.mini) this.stars.addClass('mini');
		this.hookEvents();
		if (this.options.rating > 0) this.showRating();
	},

	hookEvents: function() {
		if (this.options.readOnly) return;
		this.stars.addEvents({
			mouseenter: function(event) { this.showHover(event);    }.bind(this),
			click:      function(event) { this.recordRating(event); }.bind(this)
		});
		this.element.addEvents({
			mouseleave: function(event) { this.showRating(); }.bind(this)
		});
	},

	removeEvents: function() {
		this.stars.removeEvents();
		this.element.removeEvents();
	},

	recordRating: function(event) {
		this.setRating($(event.target).getAllPrevious('span.star').length+1);
		this.removeEvents();
		this.fireEvent('recordRating', [this.options.rating]);
	},

	setRating: function(rating) {
		this.options.rating = rating;
		this.showRating();
		this.hookEvents();
	},

	showHover: function(event) {
		this.stars.removeClass('full');
		this.hightlightStars($(event.target).getAllPrevious('span.star').length+1);
	},

	showRating: function() {
		this.stars.removeClass('full');
		this.element.set('title', (this.options.rating > 0)? 'Average: ' + this.options.rating.toFixed(2) : 'Be the first to rate this show!');
		this.hightlightStars(Math.round(this.options.rating));
	},

	hightlightStars: function(rating) {
		for (var i=0; i<Math.round(rating); i++)
			this.stars[i].addClass('full');
	}
});
