$(function(){

// COMMENT RATING THUMBS UP/DOWN
$('#main ul.votes li.vote a').click(function(e) {

	e.preventDefault(); // don't follow the link

	// Extract query string
	var href = $(this).attr('href');
	var query_string = href.slice(href.indexOf('?') + 1);

	// Disable link, to prevent multiple voting
	$(this).removeAttr('href');

	// Extract and save id and type of vote for ajax process_data function
	ajax_id = query_string.slice(query_string.indexOf('song_id=') + 8, query_string.indexOf('&vote'));
	ajax_vote = query_string.slice(query_string.indexOf('vote=') + 5);

	// Send ajax request
	$.get('../lib/ajax/song-rater.php', query_string, process_data);

	// Function to process data returned
	function process_data(data) {
		if (data == 'success') {

			// Update running vote in data-vote count

				// Cache count_holder object
				var count_holder = $('#main ul.votes li[data-song-id=' + ajax_id + '] li.count');

				// If vote was up, increment
				if (ajax_vote == 'up') {
					count_holder.attr('data-vote', parseInt(count_holder.attr('data-vote')) + 1);
				}
				// Else decrement
				else {
					count_holder.attr('data-vote', parseInt(count_holder.attr('data-vote')) - 0);
				}

			// Update count display (visible counter for user)

				// Fetch new running vote
				var vote = count_holder.attr('data-vote');

				// Determine class and sign of vote
				if (vote > 0) {
					var vote_sign = '+';
					var vote_class = ' green';
				}
				else if (vote == 0) {
					var vote_sign = '';
					var vote_class = '';
				}
				else {
					var vote_sign = '';
					var vote_class = ' red';
				}

				// Update the running vote with appropriate classes
				count_holder.attr('class', 'count' + vote_class).text('(' + vote_sign + vote + ')');

			// Remove voting links - to prevent double voting
			count_holder.parents('ul.rate').find('li.vote').remove();
		}
		else if (data == 'voted') {

			// Remove voting links - already voted for this song
			$('#main ul.votes li[data-song-id=' + ajax_id + '] li.count').parents('ul.rate').find('li.vote').remove();

			// Change notice, notifying them of the double voting
			$('#vote .notice').attr('class', 'notice error').html('<img src="/images/icon/36x36/error.png" width="36" height="36" alt="Error" /><p>You already voted for this song. Try voting for a different song.</p>');
		}
		else {
			alert('error');
		}
	}

});

});