﻿var AjaxVotes = Class.create();

AjaxVotes.prototype = {
	initialize: function(prefix,id,value,link) {
		this.id = id;
		this.link = link;
		this.value = value;
		this.legend = {1:'Sucks',2:'Slabo',3:'Srednje',4:'V redu',5:'Carsko!'};
		this.prefix = prefix+id;
		this.elements = [1,2,3,4,5];
		this.elements.each(
			(
				function (elm) {
					Event.observe(this.prefix+"_"+elm,"mouseover",(function() { this.over(elm); }).bindAsEventListener(this));
					Event.observe(this.prefix+"_"+elm,"mouseout",(function() { this.out(elm); }).bindAsEventListener(this));
					Event.observe(this.prefix+"_"+elm,"click",(function() { this.click(elm); }).bindAsEventListener(this));
					this.updateImage(elm);
				}
			).bind(this)
		);
	},
	updateImage: function(elm) {
		var img = $(this.prefix+"_"+elm);
		if (elm <= this.value) {
			img.src = "/theme/img/heart_on.gif";
		} else {
			img.src = "/theme/img/heart_off.gif";
		}
	},
	over: function(elm) {
		if (this.value == 0) {
			var temp = this.value;
			this.value = elm;
			this.elements.each(this.updateImage.bind(this));
			$(this.prefix).innerHTML = this.legend[elm] + ' ['+elm+'/5]';
			this.value = temp;
		}
	},
	out: function(elm) {
		if (this.value == 0) {
			this.elements.each(this.updateImage.bind(this));
			$(this.prefix).innerHTML = 'Z miško izberite oceno katero želite podeliti.';
		}
	},
	click: function(elm) {
		if (this.value == elm) {
			this.value = 0;
		} else {
			this.value = elm;
		}
		this.elements.each(this.updateImage.bind(this));
		var pars = '&id='+this.id+'&data='+this.value;
		var myAjax = new Ajax.Request(this.link, {method: 'post', parameters: pars, onComplete: this.response.bind(this)});
	},
	response: function(req) {
		$(this.prefix).innerHTML = req.responseText;
	}
}


