/* Adapted from VoteItUp */
/* A script for updating the contents of the vote widget on the fly */

function vote(postID ,userID, baseURL) {
	var id_base = "votecount";
	
	$.get(baseURL + "/voteinterface.php",
		{
			type: 'vote',
			uid: userID,
			pid: postID,
			auth: Math.random()
		},
		function(response){
			processReceivedVote(postID,'vote');
		}
	);
}

function sink(postID ,userID, baseURL) {
	var id_base = "votecount";
	
	$.get(baseURL + "/voteinterface.php",
		{
			type: 'sink',
			uid: userID,
			pid: postID,
			auth: Math.random()
		},
		function(response){
			processReceivedVote(postID,'sink');
		}
	);
}


function processReceivedVote(postID,type){
	var id_base = "votecount";
	var button1 = $('#' + id_base + postID + ' a.btn_voteUp');
	var button2 = $('#' + id_base + postID + ' a.btn_voteDown');
	
	$('#' + id_base + postID + ' span.voteReceived').fadeIn();
	
	var totals = $('#' + id_base + postID + ' .totals');
	var votes = $(totals[0]).find('.amount');
	var sinks = $(totals[1]).find('.amount');
	var votes_val = parseInt(votes.text());
	var sinks_val = parseInt(sinks.text());
	
	if(type == "vote"){
		votes.text(votes_val+1);
	} else if(type == "sink") {
		sinks.text(sinks_val+1);
	}
	votes_val = parseInt(votes.text());
	sinks_val = parseInt(sinks.text());
	
	if(votes_val >= sinks_val){
		votes.parent().addClass('weight');
		sinks.parent().removeClass('weight');
	} else {
		votes.parent().removeClass('weight');
		sinks.parent().addClass('weight');
	}
	
	button1.animate({
		marginLeft: "-36px"
	},250,'easeInQuad',function(){
		button2.animate({
			marginLeft: "-50px"
		},250,'easeOutQuad',function(){
			button1.remove();
			button2.remove();
		});
	});
}
