function initalize_rating() {
	links = $$("a.rateLink");
	links.each(function(link) {
		link.onclick = function() {
			var item_id = null;
			var rating = null;
			var rating_type = null;
			this.id.scan(/rate_(\d+)_with_(\d)_in_(\w+)/i, function(match) {
				item_id = match[1];
				rating = match[2];
				rating_type = match[3];
			});
			var url = link.getAttribute('href').gsub(/\/rate\?/, '/rate.json?')
			new Ajax.Request(url, {method: 'get', asynchronous: true, requestHeaders: {Accept: 'text/x-json'},
				onSuccess: function(transport, json) {
					var json = transport.responseText.evalJSON(true);
					if (json.status == 'OK') {
						var rating_count = 0;
						eval('rating_count = json.item.' + rating_type + '_rating_count;')
						eval('rating = json.item.' + rating_type + '_rating;')
						$('vote_count_for_' + item_id + '_in_' + rating_type).innerHTML = rating_count;
						$('current_rating_for_' + item_id + '_in_' + rating_type).style.width = (100 - (parseInt(rating) * 25)) + '%';
					}
					display_message_for_item(json.message, item_id, rating_type);
					window.setTimeout(fade_to_rating, 3 * 1000, item_id, rating_type);
				},
				onFailure: function() {
					display_message_for_item('Fejl: Kunne ikke kommunikere med serveren...', item_id, rating_type);
					window.setTimeout(fade_to_rating, 3 * 1000, item_id, rating_type);
				}
				});
			return false;
		}
	});
}

function display_message_for_item(message, item_id, rating_type) {
	$('rating_message_for_' + item_id + '_in_' + rating_type).innerHTML = message;
	new Effect.Parallel([
		new Effect.Fade('rank_and_votes_for_' + item_id + '_in_' + rating_type, {sync: true}),
		new Effect.Appear('rating_message_for_' + item_id + '_in_' + rating_type, {sync: true})
	], {duration: 0.8, queue: {position:'front', scope: 'rating_scope'}}
	);
}

function fade_to_rating(item_id, rating_type) {
	new Effect.Parallel([
		new Effect.Fade('rating_message_for_' + item_id + '_in_' + rating_type, {sync: true}),
		new Effect.Appear('rank_and_votes_for_' + item_id + '_in_' + rating_type, {sync: true})
	], {duration: 0.8, queue: {position:'end', scope: 'rating_scope'}}
	);
}

document.observe('dom:loaded', initalize_rating);
