// JavaScript Document: Forum
// Setup for all posts/enteries page.

var g_ajaxSetLike_url='/ajax/doforumlike/';

$(document).ready(function() {
	$("body").attr('id', 'all-posts');

	$('#mc-read-more').hide();
	// reset the location hash so that the browser repositions itself correctly.
	if(location.hash)
		location.hash = location.hash;

	$('#mca-read-more').click(function() {
		$('#mc-read-more').slideToggle('slow');
		return false;
	});

	// bind event handler to likes
	//

	// first set event handler on all disabled anchors to abort the click event.
	$("div.post .like > a.disabled").each(function(index) {
		$(this).click(function() {
			return false;
		});
	});

	// set event handlers on the active 'postLike' anchors.
	$("div.post .like > a").not("a.disabled").each(function(index) {
		var $thisAnchor = $(this); //$(this) will not be in scope of ajaxSuccess Handler.
		var splitArray = $(this).attr('id').split('-');
		var postId = splitArray[1];
		var cookieName='postLike-'+postId;

		// load cookies and deactivate these anchors if the cookies are set.
		//each anchor has an id:postLike-nn where 'nn' is the postid.
		if($.cookie(cookieName)) {
			$thisAnchor.addClass('disabled');
			$thisAnchor.unbind('click'); // MUST first unbind before binding a new event handler.
			$thisAnchor.click(function() {
				return false; //ignore the click.
			});
			return true; // a jquery 'continue' equivalent.
		}

		// anchors not found in the cookie
		$(this).click(function() {
			// save the postid in the cookie and disable this anchor.
			$.ajax({
				url: g_ajaxSetLike_url,
				data: {post_id: postId},
				dataType: 'json',
				success: function(data) {
					if(data['ErrorNumber']!=0) {
						alert(data['ErrorMessage']);
						return false;
					}

					// set the cookie.
					$.cookie(cookieName, '1', {path: '/'});

					// disable the link and remap event handler.
					$thisAnchor.addClass('disabled');
					$thisAnchor.unbind('click'); // MUST first unbind before binding a new event handler.
					$thisAnchor.click(function() {
						return false;
					});
					// increment the number of digs/likes
					var n = $("#like-content-"+postId).text();
					$("#like-content-"+postId).text(++n);
					//alert(++n);
				},
				error: function() {
					alert("ajax failed");
				}
			});

			return false; //abort redirection.
		});
	});

});

