forum = {	
	ajaxuri: "/forum",
	
	wysiwygactive: function(id) {
		return tinyMCE.getInstanceById("postform_" + id + "_message");
	},
	
	//switch reply format, taking into account the current format and transforming the text if necessary
	switchpostformat: function(id, format) {
		switch(this.getformat(id)) {
			case 0: //plain text
				var str = $("#postform_" + id + "_message").val();
				switch(format) {
					case 1:
					case 3:
						this.setpostformat(id, format, texttohtml(str));
						break;
					case 2:
						this.setpostformat(id, format, str);
						break;
					case 0:
					default:
						return;
				}
				break;
			case 1: //wysiwyg
			case 3: //html coded by hand
				if(this.getformat(id) == 1) {
					var str = tinyMCE.get("postform_" + id + "_message").getContent();
				} else {
					var str = $("#postform_" + id + "_message").val();
				}
				switch(format) {
					case 0:
					case 2:
						if(!this.emptymessage(id) && !confirm("You will lose any special formatting (HTML tags) if you switch from HTML mode. Are you sure you want to do this?")) {
							$("#postform_" + id + "_format_" + this.getformat(id)).attr("checked", "checked");
							return;
						}
						this.setpostformat(id, format, htmltotext(str));
						break;
					case 1:
					case 3:
						if(this.getformat(id) == format) return;
						this.setpostformat(id, format, str);
						break;
					default:
						return;
				}
				break;
			case 2: //preformatted text
				var str = $("#postform_" + id + "_message").val();
				switch(format) {
					case 0:
						this.setpostformat(id, format, str);
						break;
					case 1:
					case 3:
						if(!this.emptymessage(id)) str = "<pre>" + str + "</pre>";
						this.setpostformat(id, format, str);
						break;
					case 2:
					default:
						return;
				}
				break;
			default:
				return;
		}
	},
	setpostformat: function(id, format, str) {
		switch(format) {
			case 0:
			case 2:
			case 3:
				if(this.wysiwygactive(id)) {
					tinyMCE.execCommand("mceRemoveControl", false, "postform_" + id + "_message");
				}
				
				var oldarea = $("#postform_" + id + "_message");
				var newarea = oldarea.clone();
				
				newarea.val(str);
				
				if(format == 0) {
					newarea.addClass("plain");
				} else {
					newarea.removeClass("plain");
				}
				if(format == 2) {
					newarea.attr("wrap", "off");
					newarea.addClass("preformatted");
				} else {
					newarea.removeAttr("wrap");
					newarea.removeClass("preformatted");
				}
				if(format == 3) {
					newarea.addClass("html");
				} else {
					newarea.removeClass("html");
				}
				
				oldarea.before(newarea);
				oldarea.remove();
				
				break;
			case 1:
				var textarea = $("#postform_" + id + "_message");
				textarea.val(str);
				tinyMCE.execCommand("mceAddControl", false, "postform_" + id + "_message");
				break;
			default:
				return;
		}
	},
	
	quote: function(el) {
		this.showreplybox();
		
		var postinfo = $(el).parents(".postinfo:first");
		var author = postinfo.find(".postauthor").text().replace(/^\s*(.*?)\s*$/, "$1");
		var messagehtml = postinfo.parents(".post:first").find(".postmessage:not(.edit)").html().replace(/^\s*(.*?)\s*$/, "$1");
		
		var textarea = $("#postform_reply_message");
		switch(forum.getformat("reply")) {
			case 0: //plain text
			case 2: //preformatted text
				var newtext = author + " said:\n" + htmltotext(messagehtml) + "\n-----eoq-----\n";
				if(textarea.get(0).getCaretPosition() > 0) {
					newtext = "\n\n" + newtext;
				}
				textarea.get(0).insertAtCaret(newtext);
				textarea.focus();
				var t = setTimeout(function() {
					$("#postform_reply_message").focus();
				}, 50);
				break;
			case 1: //wysiwyg
				tinyMCE.execCommand("mceFocus", false, "postform_reply_message");
				
				tinyMCE.selectedInstance.execCommand("mceInsertContent", false, "<p><cite>" + author + "</cite></p><blockquote>" + messagehtml + "</blockquote>");
				break;
			case 3: //html by hand
				textarea.get(0).insertAtCaret("\n<p><cite>" + author + "</cite></p>\n<blockquote>" + messagehtml + "</blockquote>\n");
				textarea.focus();
				var t = setTimeout(function() {
					$("#postform_reply_message").focus();
				}, 50);
				break;
		}
	},
	
	setmessage: function(id, str) {
		switch(this.getformat(id)) {
			case 0:
			case 2:
			case 3:
				$("#postform_" + id + "_message").val(str);
				break;
			case 1:
				tinyMCE.get("postform_" + id + "_message").setContent(str);
				break;
		}
	},
	
	postreply: function() {
		if(this.wysiwygactive("reply")) {
			var editor = tinyMCE.get("postform_reply_message");
			editor.setProgressState(true);
			tinyMCE.execCommand("mceCleanup", false, "postform_reply_message");
			var message = editor.getContent();
		} else {
			var message = $("#postform_reply_message").val();
		}
		var format = $("#postform_reply input[@name=format]:checked").val();
		var subscribe = $("#postform_reply input[@name=subscribe]").is(":checked");
		var subject = $("#postform_reply input[@name=subject]").is(".dim") ? "" : $("#postform_reply input[@name=subject]").val();
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:		"true",
				action:		"submit",
				tid:		$(".metadata .tid").text(),
				subject:	subject,
				format:		format,
				message:	message,
				subscribe:	subscribe
			},
			dataType:	"json",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				tinyMCE.get("postform_reply_message").setProgressState(false);
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				if(forum.wysiwygactive("reply")) tinyMCE.get("postform_reply_message").setProgressState(false);
				forum.canceledit("reply", true);
				$(".metadata .lastpostpid").html(data.pid);
				var prevpost = $("#pid_" + data.prevpid);
				if(prevpost.length > 0) {
					prevpost.after(data.html);
				} else {
					if(confirm("Your reply was posted successfully. Navigate to the last page so you can see it?")) {
						window.location = "?action=viewthread&pid=" + data.pid + "#pid_" + data.pid;
					}
				}
			},
			url:	this.ajaxuri
		});
	},
	
	emptymessage: function(id, format) {
		if(typeof(format) == "undefined") format = this.getformat(id);
		var str = this.getmessage(id);
		switch(parseInt(format)) {
			case 0:
			case 2:
				return /^\s*$/.test(str);
			case 1:
			case 3:
			default:
				return /^\s*(<br\b[^>]*>|<(p|div|span|font|ul|ol|dl|pre|code|tt)\b[^>]*>\s*?<\/\2>\s*)*$/.test(str.replace(/&nbsp;/g, " "));
		}
	},
	
	getformat: function(id) {
		if(this.wysiwygactive(id)) {
			return 1;
		} else {
			var editor = $("#postform_" + id + "_message");
			if(editor.is(".preformatted")) {
				return 2;
			} else if(editor.is(".html")) {
				return 3;
			} else {
				return 0;
			}
		}
	},
	
	getmessage: function(id) {
		switch(this.getformat(id)) {
			case 0:
			case 2:
			case 3:
				return $("#postform_" + id + "_message").val();
				break;
			case 1:
				return tinyMCE.get("postform_" + id + "_message").getContent();
				break;
		}
	},
	
	settabindex: function(inst) {
		$("#" + $(inst).attr("id") + "_ifr").attr("tabindex", "4");
	},
	
	showreplybox: function() {
		$("#newreply").show();
		$("#showreplyboxbutton").hide();
		if($(".metadata .subscribed").text() == "1") {
			$("#postform_reply_subscribe").attr("checked", "checked");
		} else {
			$("#postform_reply_subscribe").removeAttr("checked");
		}
		$.scrollTo($("#newreply"));
	},
	
	editpost: function(pid) {
		var post = $("#pid_" + pid);
		if(!post) return;
		
		post.find(".actions").hide();
		post.find(".postbody .edited").hide();
		
		var subjectel = post.find(".postsubject").hide();
		var messageel = post.find(".postmessage").hide();
		
		var subject = subjectel.html().replace(/^\s*(.*?)\s*$/, "$1");
		var subjecthtml = '<div class="postsubject edit"><input class="inputtext';
		if(subject == "") subjecthtml += ' dim';
		subjecthtml += '" type="text" name="subject" id="postform_' + pid + '_subject" tabindex="' + pid + '3" ';
		if(subject == "") subjecthtml += ' onfocus="cleariffirstclick(this);"';
		subjecthtml += ' value="';
		if(subject == "") {
			subjecthtml += "Subject (optional)";
		} else {
			subjecthtml += subject;
		}
		subjecthtml += '"></div>';
		subjectel.after(subjecthtml);
		
		var html = messageel.html().replace(/^\s*(.*?)\s*$/, "$1");
		var editor = '<div class="postmessage edit"><textarea name="message" id="postform_' + pid + '_message" class="medium ';
		
		var format = parseInt(post.find(".metadata .format").text());
		switch(format) {
			case 0:
				editor += 'plain';
				var content = htmltotext(html);
				break;
			case 1:
				editor += 'forumwysiwyg';
				var content = html;
				break;
			case 2:
				editor += 'preformatted" wrap="off"'
				var content = htmltotext(html);
				break;
			case 3:
				editor += 'html';
				var content = html;
				break;
		}
		editor += '" tabindex="' + pid + '4"></textarea></div>';
		messageel.after(editor);
		
		var html = '<div class="editcontrols"><h3>Format</h3><div><label>';
		var cb1 = '<input id="postform_' + pid + '_format_0" class="inputcheckboxradio" type="radio" tabindex="' + pid + '1" onclick="forum.switchpostformat(' + pid + ', 0);" value="0" name="format">';
		var label1 = ' Plain text ';
		var between = '</label></div><div><label>';
		var cb2 = '<input id="postform_' + pid + '_format_1" class="inputcheckboxradio" type="radio" tabindex="' + pid + '1" onclick="forum.switchpostformat(' + pid + ', 1);" value="1" name="format">';
		var label2 = ' Styled ';
		var cb3 = '<input id="postform_' + pid + '_format_3" class="inputcheckboxradio" type="radio" tabindex="' + pid + '1" onclick="forum.switchpostformat(' + pid + ', 3);" value="3" name="format">';
		var label3 = ' HTML by hand ';
		var cb4 = '<input id="postform_' + pid + '_format_2" class="inputcheckboxradio" type="radio" tabindex="' + pid + '1" onclick="forum.switchpostformat(' + pid + ', 2);" value="2" name="format">';
		var label4 = ' Preformatted ';
		if(post.is(".mine")) {
			html += cb1 + label1 + between + cb2 + label2 + between + cb3 + label3 + between + cb4 + label4;
		} else {
			html += label1 + cb1 + between + label2 + cb2 + between + label3 + cb3 + between + label4 + cb4;
		}
		html += '</label></div><h3>Actions</h3><div><input type="button" class="inputbutton massive" onclick="forum.submiteditpost(' + pid + ');" value="Edit post" tabindex="' + pid + '5"></div><ul><li><a href="#" onclick="forum.canceledit(' + pid + '); return false;">Cancel</a></li></ul></div>';
		post.find(".postinfo").append(html);
		
		$("#postform_" + pid + "_format_" + format).attr("checked", "checked");
		this.setpostformat(pid, format, content);
		$("#postform_" + pid + "_message_ifr").attr("tabindex", pid + "4");
	},
	
	submiteditpost: function(id) {
		if(this.wysiwygactive(id)) {
			var editor = tinyMCE.get("postform_" + id + "_message");
			editor.setProgressState(true);
			tinyMCE.execCommand("mceCleanup", false, "postform_" + id + "_message");
			var message = editor.getContent();
		} else {
			var message = $("#postform_" + id + "_message").val();
		}
		var format = $("input[id^=postform_" + id + "_format_]:checked").val();
		var subject = $("#postform_" + id + "_subject").is(".dim") ? "" : $("#postform_" + id + "_subject").val();
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:		"true",
				action:		"submit",
				pid:		id,
				subject:	subject,
				format:		format,
				message:	message
			},
			dataType:	"json",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				tinyMCE.get("postform_" + id + "_message").setProgressState(false);
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				if(forum.wysiwygactive(data.pid)) tinyMCE.get("postform_" + data.pid + "_message").setProgressState(false);
				forum.canceledit(data.pid, true);
				$("#pid_" + data.pid).replaceWith(data.html);
				if($("#pid_" + data.pid).is(".first")) {
					var title = $("#pid_" + data.pid + " .postbody .postsubject").html();
					$(".threadsubject").html(title);
					document.title = document.title.substring(0, document.title.indexOf("Thread: ") + 8) + title;
				}
			},
			url:	this.ajaxuri
		});
	},
	
	canceledit: function(id, force) {
		if(force || this.emptymessage(id) || confirm("Are you sure you want to cancel?")) {
			this.setmessage(id, "");
			if(id == "reply") {
				$("#postform_reply_subject").addClass("dim").val("Subject (optional)").get(0).beenclicked = false;
				$("#newreply").hide();
				$("#showreplyboxbutton").show();
			} else {
				var post = $("#pid_" + id);
				if(this.wysiwygactive(id)) {
					tinyMCE.execCommand("mceRemoveControl", false, "postform_" + id + "_message");
				}
				post.find(".postsubject.edit, .postmessage.edit, .editcontrols").remove();
				post.find(".postmessage").show();
				var subject = post.find(".postsubject");
				if(subject.text().length > 0) {
					subject.show();
				}
				post.find(".actions").show();
				post.find(".postbody .edited").show();
			}
		}
	},
	
	deletepost: function(id) {
		if(!confirm("Are you sure you want to delete this " + ($("#pid_" + id).is(".first") ? "thread" : "post") + "?")) return;
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:	"true",
				action:	"delete",
				type:	"post",
				id:	id
			},
			dataType:	"json",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				if($("#pid_" + id).is(".first")) {
					alert("The thread has been deleted. Click OK to return to the category.");
					window.location = "?action=viewcategory&cid=" + $(".metadata .cid").text();
				} else {
					$("#pid_" + id).replaceWith(data.html);
				}
			},
			url:	this.ajaxuri
		});
	},
	
	undeletepost: function(id) {
		if(!confirm("Are you sure you want to undelete this post?")) return;
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:	"true",
				action:	"undelete",
				type:	"post",
				id:	id
			},
			dataType:	"json",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				$("#pid_" + data.pid).replaceWith(data.html);
			},
			url:	this.ajaxuri
		});
	},
	
	removepost: function(id) {
		if(!confirm("Are you sure you want to completely remove this post? In most cases this should not be done.")) return;
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:	"true",
				action:	"remove",
				type:	"post",
				id:	id
			},
			dataType:	"text",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				$("#pid_" + id).remove();
			},
			url:	this.ajaxuri
		});
	},
	
	subscribe: function(id) {
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:	"true",
				action:	"subscribe",
				"var":	id
			},
			dataType:	"text",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				$(".threadtools .subscriptioninfo, #threadrow_" + id)
					.find(".emblem.subscribed").removeClass("false").addClass("true").attr("title", "You are subscribed to this thread").end()
					.find(".not").hide().end()
					.find(".un").show();
			},
			url:	this.ajaxuri
		});
	},
	unsubscribe: function(id) {
		$.ajax({
			type:	"POST",
			cache:	false,
			data:{
				async:	"true",
				action:	"unsubscribe",
				"var":	id
			},
			dataType:	"text",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				$(".threadtools .subscriptioninfo, #threadrow_" + id)
					.find(".emblem.subscribed").removeClass("true").addClass("false").attr("title", "You are not subscribed to this thread").end()
					.find(".not").show().end()
					.find(".un").hide();
			},
			url:	this.ajaxuri
		});
	},
	
	getupdatedtimes: function() {
		var pids = [];
		$(".post[id^=pid_]").each(function() {
			pids[pids.length] = $(this).attr("id").substr(4);
		});
		$.ajax({
			type:	"GET",
			cache:	false,
			data:{
				async:	"true",
				action:	"getupdatedtimes",
				"pids[]":	pids,
				tid:	$(".metadata .tid").text()
			},
			dataType:	"json",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				for(pid in data.times) {
					if(data.times[pid].posted != null) {
						$("#pid_" + pid + " .postdate").html(data.times[pid].postedhtml);
					} else {
						$("#pid_" + pid).remove();
						continue;
					}
					if(String(data.times[pid].deleted) != String($("#pid_" + pid + " .postinfo .metadata .deleteddate").text())) {
						forum.reloadpost(pid);
						continue;
					} else {
						$("#pid_" + pid + " .postbody p.deleted span.date").replaceWith(data.times[pid].deletedhtml);
					}
					if(String(data.times[pid].edited) != String($("#pid_" + pid + " .postinfo .metadata .editeddate").text())) {
						forum.reloadpost(pid);
						continue;
					} else {
						$("#pid_" + pid + " .postbody p.edited span.date").replaceWith(data.times[pid].editedhtml);
					}
				}
				if(parseInt(data.lastpostpid) > parseInt($(".metadata .lastpostpid").text())) {
					$(".metadata .lastpostpid").html(data.lastpostpid);
					if(confirm("A new post has been made in this thread. Click OK to view it or cancel to stay.")) {
						window.location = "?action=viewthread&pid=" + data.lastpostpid + "#pid_" + data.lastpostpid;
					}
				}
			},
			url:	this.ajaxuri
		});
	},
	
	reloadpost: function(id) {
		$.ajax({
			type:	"GET",
			cache:	false,
			data:{
				async:	"true",
				action:	"getpost",
				"var":	id
			},
			dataType:	"json",
			error:function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest.responseText);
			},
			success:function(data, textStatus) {
				$("#pid_" + id).replaceWith(data.html);
			},
			url:	this.ajaxuri
		});
	},
	
	initeditors: function() {
		tinyMCE.init({
			mode: "specific_textareas",
			editor_selector: "forumwysiwyg",
			plugins: "fullscreen,safari,paste,selfclosetags",
			selfclosetags: ">",
			dialog_tipe: "modal",
			theme: "advanced",
			skin: "dark",
			theme_advanced_buttons1: "formatselect,|,bold,italic,underline,forecolor,backcolor,removeformat,|,bullist,numlist,|,outdent,indent,|,link,unlink,|,image,|,undo,redo,|,pastetext,pasteword,cleanup,|,fullscreen,code",
			theme_advanced_buttons2: "",
			theme_advanced_buttons3: "",
			theme_advanced_buttons4: "",
			theme_advanced_toolbar_location: "bottom",
			tab_focus: ":prev,:next",
			accessibility_focus: false,
			width: "100%",
			height: "200",
			content_css: forum.stylesheet,
			init_instance_callback: "forum.settabindex"
		});
	}
};
$(document).ready(function() {
	forum.initeditors();
	if($(".metadata .view").text() == "viewthread") {
		var i = setInterval(function() {
			forum.getupdatedtimes();
		}, 60000);
	}
	$(".threadtools .subscriptioninfo a, .threadtools .subscriptioninfo .emblem").click(function(e) {
		e.preventDefault();
		var tid = $(".metadata .tid").text();
		if($(".threadtools .subscriptioninfo .emblem").is(".true")) {
			forum.unsubscribe(tid);
		} else {
			forum.subscribe(tid);
		}
	});
	$(".threadlist .emblem.subscribed").click(function() {
		var tid = $(this).parents("tr:first").find(".metadata .tid").text();
		if($(this).is(".true")) {
			forum.unsubscribe(tid);
		} else {
			forum.subscribe(tid);
		}
	});
});
