
var hosturl = "http://chucknorrism.com";

jQuery(function() {
	
	if ($.cookie('voted') == null) { $.cookie('voted', '');	}

	$('.up, .down').click(function(e) {

		var tid = $(this).parent().attr('id');
		var t = tid.split('_');
		var id = t[1];

		var coo = $.cookie('voted');
		var ta = coo.split(':');

		// Already voted
		if ($.inArray(id, ta) >= 0) { return; }

		var cval = coo + ':'+id;
		$.cookie('voted', cval);

		if ($(this).hasClass('up')) { castVote(id, 1);}
		else { castVote(id, 0);	}

	});

});


function castVote(id, vote) {
	$.post(hosturl+"/vote.php", { 'id':id, 'vote': vote}, function(res) {
		if(res == 1) {
			var pid = '#fact_'+ id;
			var ud = (vote)?2:1;
			var tc = $(pid + ' :nth-child('+ud+')').text();
			var count;			
			if (ud == 2) {
				var ts = tc.split(' ');
				count = (ts[1]*1) + 1;
				count = ': ' + count ;
			}
			else { count = ((tc*1) + 1); }
			$(pid + ' :nth-child('+ud+')').text(count);
		}
		else { alert(res); }
	});
}

















