var Rating = Class.create();
Rating.prototype = {
	initialize : function(dom_object)
	{
		this.object = dom_object;
		this.status = 'out';

		Event.observe(this.object, 'mouseover', this.evt_over.bindAsEventListener(this));
		Event.observe(this.object, 'mouseout', this.evt_out.bindAsEventListener(this));
		Event.observe(this.object, 'click', this.evt_click.bindAsEventListener(this));
	},
	evt_over :  function(e)
	{
		this.status = 'over';

		var p = this.object.id.split('-');
		p[3] = parseInt(p[3]);

		for(i = 1; i <= p[3]; ++i) {
			$('post-star-'+p[2]+'-'+i).style.backgroundPosition = '1px -42px';
		}
		for(i = p[3]+1; i <= 5; ++i) {
			$('post-star-'+p[2]+'-'+i).style.backgroundPosition = '1px -28px';
		}
	},
	evt_out : function(e)
	{
		this.status = 'out';
	
		var p = this.object.id.split('-');

		for(i = 1; i <= 5; ++i) {
			var s = $('post-star-'+p[2]+'-'+i);
			if(s.innerHTML == '+') {
				s.style.backgroundPosition = '1px -14px';
			}
			else {
				s.style.backgroundPosition = '1px 0';
			}
		}
	},
	evt_click : function(e)
	{
		var p = this.object.id.split('-');
		
		var req = new Ajax.Request(
			'index.php',
			{
				method : 'post',
				parameters : 'action=rp_process&id_post='+p[2]+'&vote='+p[3],
				onComplete : this.ajax_response.bindAsEventListener(this),
				onError : this.ajax_error.bindAsEventListener(this)
			}
		);
		Event.stop(e);
	},
	ajax_response : function(request, a, b, c)
	{
		var n = parseInt(request.responseText);
		var p = this.object.id.split('-');

		var t = '';
		if (n > 0) {
			for (i = 1;	i <= n; ++i) {
				$('post-star-'+p[2]+'-'+i).innerHTML = '+';
			}
			for (i = n+1; i <= 5; ++i) {
				$('post-star-'+p[2]+'-'+i).innerHTML = '-';
			}
			t = 'Köszi, hogy szavaztál!';
		}
		else {
			t = 'Erre a bejegyzésre már szavaztál egyszer!';
		}

		if (this.status == 'out') {
			for(i=1; i <= 5; ++i) {
				var s = $('post-star-'+p[2]+'-'+i);
				if (s.innerHTML == '+') {
					s.style.backgroundPosition='1px -14px';
				}
				else {
					s.style.backgroundPosition='1px 0';
				}
			}
		}

		if (t.length > 0) {
			alert(t);
		}
	},
	ajax_error : function(request)
	{
		alert('A szavazás nem volt sikeres!');
	}
};

var rating_object = new Array();
Event.observe(window, 'load', function (e) {
	var t = document.getElementsByClassName('post-star');
	for(i = 0; i < t.length; ++i) {
		rating_object[i] = new Rating(t[i]);
	}
});