function Trim(str)
{
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}


$(function() {
	
	//retrieve comments to display on page
	$.getJSON("comments_script/comments.php?jsoncallback=?", function(data) {

	var commentsPerPage = 10;				 
	var y = 0;
	var pageDiv = $("<div>").addClass("commentPage").appendTo("#comments");
	if (data != null)
		//loop through all items in the JSON array
		for (var x = 0; x < data.length; x++) {
					
			//create a container for each comment
			var div = $("<div>").addClass("commentLine").appendTo(pageDiv);
						
			//add author name and comment to container
															$("<div>").addClass("comment").html(data[x].comment.replace(/\n/g, "<br/>"
				)).appendTo(div);
			var authorHtml = data[x].name;
			if (data[x].email != null)
				authorHtml = '<a href="mailto:' + data[x].email + '">' + authorHtml + '</a>';
			$("<div>").addClass("author").html("Posted by " + 									authorHtml + " on " + data[x].date).appendTo(div);
			if (data[x].display_name != null)
			{													var repDiv = $("<div>").addClass("replyLine").html(data[x].reply.replace(/\n/g, "<br/>"
					)).appendTo(div);
				$("<div>").addClass("author").text("Posted by " + 									data[x].display_name + " on " + data[x].reply_date).appendTo(repDiv);
			}
			y++;
			if (y >= commentsPerPage)
			{
				y = 0;
				pageDiv = $("<div>").addClass("commentPage").appendTo("#comments");
			}
		}
		$('#comments').pager('.commentPage', {navId: 'commentPageNav', height: 0});
	});	
				
	//add click handler for button
	$("#add").click(function() {
				
		//define ajax config object
		var ajaxOpts = {
			type: "post",
			url: "comments_script/addComment.php",
			data: "&author=" + $("#inName").val() + "&comment=" + 						$("#inComment").val() + "&email=" + $("#inEmail").val(),
			success: function(data) {
				$("#leaveComment").text("Message posted.");
			},
			error: function(data) {
				$("#leaveComment").text("Cannot post your message right now - please try again later.");
			}
		};
		if ((Trim($("#leaveComment").find("input").val()) != "") && 						(Trim($("#leaveComment").find("textarea").val()) != ""))

			$.ajax(ajaxOpts);

                return false;
				
	});		
});
