var currentRating;
var ratingMediaCode = -1;

function initRating(mediaCode, value) {
	ratingMediaCode = mediaCode;
	
	var votedBefore = (document.cookie.indexOf('vote_' + mediaCode) != -1);
	displayRating(value, votedBefore);
}

function displayRating(v, locked) {
	currentRating = v;
	$('#vote').html("");
	var stars = 0;
	var img;
	while(v >= 1) {
		img = $('<img src="http://media1.limexgames.net/img/star_on.jpg" />');
		link = $('<a href="javascript:rate(' + (stars+1) + ')" title="' + getRateTitle(stars) + '" />');
		link.append(img);
		if(locked) {
			$('#vote').append(img);
		} else {
			$('#vote').append(link);
		}
		v--;
		stars++;
	}
	if(v > 0) {
		img = $('<img src="http://media1.limexgames.net/img/star_half.jpg" />')
		link = $('<a href="javascript:rate(' + (stars+1) + ')" title="' + getRateTitle(stars) + '" />');
		link.append(img);
		if(locked) {
			$('#vote').append(img);
		} else {
			$('#vote').append(link);
		}
		stars++
	}
	while(stars < 5) {
		img = $('<img src="http://media1.limexgames.net/img/star_off.jpg" />')
		link = $('<a href="javascript:rate(' + (stars+1) + ')" title="' + getRateTitle(stars) + '" />');
		link.append(img);
		if(locked) {
			$('#vote').append(img);
		} else {
			$('#vote').append(link);
		}
		stars++;
	}
	
	if(locked) {
		$('#vote').append('<p>Thanks for rating!</p>');
	} else {
	 	$('#vote').append('<p>Click stars to rate.</p>');
	}					
}




/**
 * Generates label for rating button
 */
function getRateTitle(v) {
	switch(v) {
		case 0: return "Very poor";
		case 1: return "Not so bad";
		case 2: return "Avarage";
		case 3: return "Good";
		case 4: return "Perfect Game!";
		default: return "";
	}
}

/**
 * sends rate request
 */
function rate(value) {
	var url = "http://www.limexgames.com/portal/vote/" + ratingMediaCode + "/";		
	$.getJSON(url, {rating: value}, onVotingComplete);
}
 
/**
 * handle rating response
 */
function onVotingComplete(data) {
	if(!data.r) {
		return;
	}	
	
	displayRating(data.r, true);
}

