jQuery(function() {
	
	$("a.quote").click(function(event){
		id = $(this).html();
		$.post("/forum/quote", {id: id}, function(value) {
			
			if($("div#reply").children("form").children("textarea").val() == ''){
				$("div#reply").children("form").children("textarea").val(value);
			}
			else{
				$("div#reply").children("form").children("textarea").val($("div#reply").children("form").children("textarea").val() + "\n\n" + value);
				
			}
			
			markdown2html($("div.reply_preview"), value)
			
			$.scrollTo('textarea[name=body]')
		});
	});
	
	$("a.edit").click(function(event){
		var _this = $(this);
		var body = $(this).parent().siblings(".body");
		id = $(this).attr("href");
		
		$.post("/forum/edit", {id: id}, function(value){			
			body.html(value);
						
			var form = $("form.edit_post");
			var cancel = $("form.edit_post").children("div").children("input[name=cancel]");
			var textarea = _this.parent().siblings(".body").children("form").children("textarea[@name=edit_post]");
			var edit_preview = _this.parent().siblings(".body").children("div.edit_preview");
			
			textarea.unbind().keyup(function(event){
				markdown2html(edit_preview, $(this).val())
			});
			
			form.unbind().submit(function(event){
				_this = $(this);
				text = $(this).children("textarea").val();
				id = $(this).children("input").val();
				
				if(text == ""){
					alert("Thats no fun to read.");
					event.preventDefault();
					return;
				}
				
				$.post("/forum/update", {id: id, body: text}, function(value) {
					_this.parent(".body").html(value);
				});
				
				event.preventDefault();
			});
			
			cancel.unbind().click(function(event){
				_this = $(this);
				id = $(this).parent().siblings("input").val();
				
				$.post("/forum/comment", {id: id}, function(value) {
					_this.parent().parent("form").parent(".body").html(value);
				});
				
				event.preventDefault();
			});
			
		});
		event.preventDefault();
	});
});
