var AjaxRating = Class.create();

AjaxRating.prototype = {
	initialize: function(url, prefix, length, image_on, image_off) {
		this.url = url;
		this.prefix = prefix;
		this.rating_text = prefix+"_text";
		this.rating_img = prefix+"_img";
		this.rating_results = prefix+"_results";
		this.length = length;
		this.image_on = image_on;
		this.image_off = image_off;
		this.image_bar = new Array();
		this.cancel_mouseout = new Array();
	},
	over: function(post, image, orig) {
		if (this.image_bar[post]==null) {
			this.image_bar[post] = orig;
		}
		this.cancel_mouseout[post] = true;
		if (this.image_bar[post]==0) {
			var i;
			for (i=1;i<=this.length;i++) {
				if (i<=image) {
					$(this.prefix+post+i).src = this.image_on;
				} else {
					$(this.prefix+post+i).src = this.image_off;
				}
			}
		}
	},
	out: function(post) {
		this.cancel_mouseout[post] = false;
		setTimeout( (function() { this.render(post); }).bind(this), 500);
	},
	click: function(post, clicked) {
		if (this.image_bar[post] == clicked) {
			clicked = 0;
		}
		this.cancel_mouseout[post] = false;
		this.image_bar[post] = clicked;
		this.render(post);

		var link = this.url + "/" + post + "/" + clicked;

		var myAjax = new ajax(link, {method:"get", onComplete: this.response.bind(this)});
	},
	render: function(post) {
		var i;
		if (this.cancel_mouseout[post]) {
			return;
		}
		for (i=1;i<=this.length;i++) {
			if (i<=this.image_bar[post]) {
				$(this.prefix+post+i).src = this.image_on;
			} else {
				$(this.prefix+post+i).src = this.image_off;
			}
		}
		this.cancel_mouseout[post] = true;
	},
	response: function(req) {
		var txt = req.responseText;
		if (txt.indexOf('[split]')==-1) {
			$(this.rating_text).innerHTML = req.responseText;
		} else {
			txt = txt.split("[split]");
			$(this.rating_img).innerHTML = txt[0];
			$(this.rating_results).innerHTML = txt[1];
			$(this.rating_text).innerHTML = txt[2];
		}
	}
}
