$(function() {
	//show like button and like count
	$('#primary-content .blog-content-wrapper .extra-info .comment-count').addClass('likeshowing');
	setLikeText();
	$('.likebutton').addClass('visible');
 	$('.liketext').addClass('show');
	checkLiked();
	loadLink();
});

function loadLink(){
	$('.likebutton').click(function(e) {
		e.preventDefault();
		//get post id from a class on the button
		var postid = $(this).children().text();
		var currentbutton = $(this);
		if($(this).hasClass('like')){
			$.get(
				"/applications/blog/like.rm?blog_post_id=" + postid,
				function(){
					//set cookie to show it is liked
					$.cookie("liked"+postid, "true", {hoursToLive:17531}); //2 years
					currentbutton.addClass('unlike');
					currentbutton.removeClass('like');
					setLikeText();
				}
			);
		}else{
			$.get(
				"/applications/blog/unlike.rm?blog_post_id=" + postid,
				function(){
					//set cookie to show it is unliked
					$.cookie("liked"+postid, "false", {hoursToLive:17531}); //2 years
					currentbutton.addClass('like');
					currentbutton.removeClass('unlike');
					setLikeText();
				}
			);
		}
	});
}

function checkLiked(){
	//check if posts were previously 'liked' and update styles accordingly
	$('.likebutton').each(function(){
		var postid = $(this).children().text();
		var cookiename = "liked"+postid;
		if($.cookie(cookiename) == "true"){
			$(this).addClass('unlike');
		}else{
			$(this).addClass('like');
		}
	});
	
}
  
function setLikeText(){
	//get post id from a class on the button
	$('.liketext').each(function(){
		var postid = $(this).children().text();
		var postid = postid.replace('postid_','');
		var currenttext = $(this);
		//read current tally of likes on this post, and update text accordingly
		$.get("/applications/blog/get_tally.rm?blog_post_id=" + postid,
			function(data){
				var liketext = "";
				if(parseInt(data) == 1){
					liketext = data + " person likes this |";
				} else if (parseInt(data) > 1){
					liketext = data + " people like this |";
				};
				currenttext.html(liketext + '<span class="hidden">' + postid + '</span>');
			}
		);	
	});  
}

