// Load agony/ivy voting data:
$(document).ready(function() {	
	var shown_entries = [];
	$('.entry .voting').each(function() {
		var entry_id = $(this).attr("id").split('_')[1];
		shown_entries.push(entry_id);
		
		setup_voting($(this));
	});
	
	$('.entry .voting .vote a').live("click", vote);

	$.post("/voting/count.php", {ids: shown_entries.join(',')}, function(data) {
		for (var id in data) {
			$('.entry .voting#voting_' + id).append(vote_text(id, data[id]));
		}
		
	}, "json");
});

function vote_text(id, data) {
	var a = (data['agony']) ? parseInt(data['agony']) : 0;
	var i = (data['ivy']) ? parseInt(data['ivy']) : 0;
	var t = a + i;
	
	var a_p = a / t;
	var i_p = i / t;
	
	if (a_p > i_p) {
		var label = 'Agony';
		var percentage = Math.round(100 * a_p);
	}
	else {
		var label = 'Ivy';
		var percentage = Math.round(100 * i_p);
	}
	
	if (t > 0) {
		return('<span class="vote_count">' + percentage + '%<h6>' + label + '</h6></span>');
	}
	else {
		return('<span class="vote_count"><h6>No Votes Yet</h6></span>');
	}
	
}

function setup_voting(el) {
	// Find out this entry's id:
	var entry_id = el.attr("id").split('_')[1];
	
	// See if we have a cookie set for the given entry ID; if we do, we can't vote again:
	var already_voted = ($.cookie('Agony&Ivy_vote_' + entry_id)) ? true : false;

	$('.loader', el).remove();

	if (already_voted) {
		el.append('<span class="vote"><h6 class="' + $.cookie('Agony&Ivy_vote_' + entry_id).toLowerCase() + '">You voted: ' + $.cookie('Agony&Ivy_vote_' + entry_id) + '</h6></span>');
	}
	else {
		el.append('<span class="vote"><h6>Vote:</h6> <a href="#" class="agony">Agony</a> | <a href="#" class="ivy">Ivy</a></span>');
	}
}

function vote() {
	var vote = $(this).hasClass('agony') ? 'Agony' : 'Ivy';
	var container = $(this).parent().parent();
	var entry_id = container.attr("id").split('_')[1];
	
	$.get('/voting/record.php', {vote: vote.toLowerCase(), id: entry_id}, function(data) {
		$.cookie('Agony&Ivy_vote_' + entry_id, vote, {expires: 1, path: '/'});
		$('span.vote', container).html('<h6 class="' + vote.toLowerCase() + '">You voted ' + vote + '</h6>');
		$('span.vote_count', container).replaceWith(vote_text(entry_id, data));
	}, "json");
	
	return(false);
}

