var AjaxRatingBar = new Class({
	
	elements: [],
	currentScore: false,
	txtScore: false,
	txtVotes: false,
	fxSlide: false,
	
	initialize: function(element){
		
		this.elements     = element.getElementsBySelector('a.vote');
		this.currentScore = element.getElement('li.current');
		this.txtScore     = element.getElement('span.txtScore');
		this.txtVotes     = element.getElement('span.txtVotes');
		this.loading      = element.getElement('li.loading div');
		this.fxSlide      = new Fx.Slide(this.loading);
		this.fxSlide.hide('horizontal');
		this.start();
	},
	
	start: function()
	{
		if (this.elements)
		{
			this.elements.each(function(btn){
				btn.addEvent('click', function(evt){
					evt = new Event(evt);
					if (evt.target)
					{
						evt.stop();
						this.call(evt.target);
					}
				}.bind(this))
			}.bind(this));
		}
	},
	
	call: function(targetEl)
	{
		target = targetEl.getAttribute('href');
		if (target)
		{
			new Json.Remote(target + "/viaajax",{
				onRequest: function()
				{
					this.fxSlide.show('horizontal');
				}.bind(this),
				onComplete: function(result)
				{
					if (result.error == true)
					{
						alert(result.message);
					}
					else
					{
						this.currentScore.setStyle('width', result.newScore * 30);
						this.txtScore.setText(Math.round(result.newScore*10, 2)/10);
						this.txtVotes.setText(result.votes);
					}
					this.fxSlide.stop();
					this.fxSlide.slideOut('horizontal');
				}.bind(this)
			}).send();
		}
	}
});

window.addEvent('domready', function(){
	var bars = $$('.ratingbar');
	bars.each(function(bar){
		var ratingBar = new AjaxRatingBar(bar);
	});
});