$(document).ready(function(){
	$('#add_post').live('click',function(e){
		e.preventDefault();
		//		var orig_html = $(this).html();
		var form_elems = $('#add_my_stuff :input');
		var jsondata = {};
		$(form_elems).each(function(i){
			jsondata[$(form_elems[i]).attr('id')] = $(form_elems[i]).val();
		});
		jsondata['category'] = $('#current_category').html();
		$(this).attr('id','adding_post');	//.html('Processing...');
		$.post('community_ajax.php', jsondata, function(data){
			if (data.length == 0) {
				$('#error').html('There was an error with your submission!').fadeIn();
			} else {
				$('#error').fadeOut().empty();
				$('#stuff_list').prepend(data).slideDown();
			}
			$('#adding_post').attr('id','add_post');	//.html(orig_html);
			$('#add_my_stuff form').hide();
			$('a.show_form').fadeIn();
		}, 'html');
	});
	$('.add_comment a').live('click',function(e){
		e.preventDefault();
		var comment_template = '<textarea></textarea><button>Comment</button><button>Never Mind</button>';
		$(this).parent().html(comment_template);
	});
	// Switch views
	$('#categories a').live('click',function(e){
		e.preventDefault();
		var new_category = $(this).text();
		var user = $('#user strong').html();
		$.post('community_ajax.php', {change_categories: new_category, user: user}, function(data){
			$('#stuff_list').html(data);
		}, 'html');
		$('#categories a').removeClass('active');
		$(this).addClass('active');
		$('#current_category').html($(this).text());
		if ($(this).text() == 'All') {
			$('#add_my_stuff').hide();
		} else {
			$('#add_my_stuff').show();
		}
	});
	// Comment
	$('div.add_comment button').live('click',function(){
		switch($(this).html()) {
			case 'Comment':
				var comment = $(this).parent().find('textarea').val();
				if (comment.length > 0) {
					var jsondata = {
						make_comment: true,
						user_email: $('#user strong').html(),
						post_id: $(this).parent().parent().attr('id').substr(7),
						comment: comment
					};
					$.post('community_ajax.php', jsondata, function(data){
						if (data.success) {
							// success
//							$(this).parent().html(data).addClass('comment');
						}
					}, 'html');
					$(this).parent().html('<span>You just said...</span>'+jsondata.comment).addClass('comment').removeClass('add_comment');
				}
				break;
			case 'Never Mind':
			default:
				$(this).parent().html('[<a href="#" class="add_comment">Comment</a>]');
				break;
		}
	});
	// Show the form to add a post
	$('a.show_form').click(function(e){
		e.preventDefault();
		$(this).hide();
		$('#add_my_stuff form').slideDown();
	});
	// Paginate
	$('#paginate a').live('click',function(e){
		e.preventDefault();
		var page = $(this).text();
		if (page == 'Next') {
			page = $('#paginate .current').next('span').text();
		}
		var jsonpost = {
			change_categories:	$('#current_category').html(),
			page:				page
		}
		$.post('community_ajax.php', jsonpost, function(data){
			$('#stuff_list').html(data);
		});
	});
});