$(document).ready(function()
{
	$('.showComments').click(function()
	{
		$(this).parent().siblings('.comments').slideToggle();
	});
	
	//Submit comment
	$('.comment_editor .submit').click(function()
	{
		var self = this;
		var formData = $(this).parents('.comment_editor').serialize();
		
		$.post('posting.php?mode=submit_comment', formData, function(data)
		{
			var response;
			
			try
			{
				response = JSON.parse(data);
			}
			catch(ex)
			{
				showMessage('An unparsable message was returned', 'Error submitting post', data, ['OK']);
				return;
			}
			
			if(response.result == 'success')
			{
				$(self).parents('.comment_editor').find('.content').val('');
				window.location.reload();
			}
			else if(response.result == 'denied')
				showMessage(response.data, 'Error submitting post', '', ['OK']);
			else
				showMessage('There was an error while attempting to submit comment.  Please make sure all information was entered.', 'Error submitting comment', response.data, ['OK']);
		});
		
		return false;	//Prevent form submission
	});
	
	//Edit comment
	/*
	$('.admin_tools .edit').click(function()
	{
		if(posting)
			return;
		
		var post = $(this).parents('.post');
		
		posting = true;
		
		post.slideUp(function()
		{
			var editor = $('#post_editor');
			var hotspotType = $(this).attr('data-hotspot-type');
			var category = $(this).attr('data-category-id');
			var featured = $(this).attr('data-featured');
			
			if(parseInt(featured))
				setPostHotspotOrFeatured('featured', true);
			else
				setPostHotspotOrFeatured('hotspot', hotspotType);
				
			$('#post_editor select[name=category]').val(category);
			$('#post_editor .title').val($(this).find('.title').text());
			$('#post_content').val($(this).find('.content').attr('data-original'));
			$('#post_editor input[name=id]').val($(this).attr('data-post-id'));
			editor.prependTo('#news_posts').hide().slideDown();
		});
	});
	*/
	
	//Delete comment
	$('.comments .admin_tools .delete').click(function()
	{
		var comment = $(this).parents('.comments article')
		var commentId = comment.attr('data-comment-id');
		
		showMessage('Are you sure you want to delete this comment?', 'Delete Comment', '', ['Delete', 'Cancel'], function(result, messageBox)
		{
			if(result == 'Delete')
			{
				showMessageSpinner();
				$.post('posting.php?mode=delete_comment', { 'c' : commentId}, function(data, textStatus)
				{
					var response;
					
					try
					{
						response = JSON.parse(data);
					}
					catch(ex)
					{
						console.err('Error parsing result: ', ex);
						//showMessageBox(data, 'Error deleting post', '', ['OK']);
						return;
					}
					
					if(response.result == 'success')
					{
						closeMessageBox();
						comment.css('min-height', '0').slideUp(function(){ $(this).remove(); });
					}
					else
						console.err('Error deleting comment: ', response);
				});
			}
			else
				return true;
		});
	});
});
