
function getReplyMsgTxt() {
	return $("#fmessage").val();
}

var messagefocused = false;

$(document).ready(function() {
	
	$("#forum").animate({opacity:1}, 1000, function(){ resizeAvatars(); });
	
	$("#fpostslist .postitem").live("mouseover", function(){
		$(this).addClass("hov");
	}).live("mouseout", function(){
		$(this).removeClass("hov");
	});
	
	$("#reply-opts .tabbed-nav li a").click(function(e) {
		e.preventDefault();
		$(this).parent("li").attr("class","on").siblings("li").removeClass("on");
		var $subj = $(this).attr("rel");
		$("#"+$subj).show().siblings(".opt").hide();
		if($subj == "RO-preview") {
			$("#RO-preview").html('<img src="/bin/img/loading-thickbox.gif" alt="loading"/>');
			$.post(
				"/forums/action.php",
				{ previewtxt: getReplyMsgTxt() },
				function(t){
					$("#RO-preview").html(t);
				}
			);
		}
	});
	
	$(":input[name='message']").focus(function(){
		messagefocused = true;
	});
	
	//keynav
	var thisn = -1;
	var isCtrl = false;
	var uposts = $("#unreadposts");
	if(uposts.length){
		
		uposts = $(uposts).val().split(",");
		
		$(document).keyup(function (e) {
			if(e.which == 17) isCtrl = false;
		}).keydown(function (e) {
			if(e.ctrlKey) {
				isCtrl=true;
			} else return;
			if(e.which == 38) { //up
				if(!isCtrl) return;
				thisn--;
			} else if(e.which == 40) { //down
				if(!isCtrl) return;
				thisn++;
			} else return;
			
			//e.preventDefault();
			
			if(thisn < 1) thisn = 0;
			if(thisn >= uposts.length) thisn--;
			
			var loc = window.location.href;
			var h = loc.indexOf("#");
			if(h) loc = loc.substr(0, h);
			window.location = loc+'#p'+uposts[thisn];
			$('#p'+uposts[thisn]).focus();
			
		});
	}
	
	/*$(document).keydown(function(Ev) {
		if(messagefocused) return;
		if(!$("#unreadposts").length) return;
		var uposts = $("#unreadposts").val().split(",");
		if(!uposts.length) return;
		
		var k = Ev.keyCode;
		if(k == 38) {//up
			thisn--;
		} else if(k == 40) {//down
			thisn++;
		} else return;
		
		Ev.preventDefault();
		if(thisn < 1) thisn = 0;
		if(thisn >= uposts.length) thisn--;
		
		var loc = window.location.href;
		var h = loc.indexOf("#");
		if(h) loc = loc.substr(0, h);
		window.location = loc+'#p'+uposts[thisn];
		$('#p'+uposts[thisn]).focus();
	});*/
	
});


function togglePreview(i){
	if( $("#fmsg-"+i+"-prevbutton").val() == "Preview" ) {
		$("#fmsg-"+i+"-form :input").attr("disabled", "disabled");
		$("#fmsg-"+i+"-loading").show();
		$.post(
			"/forums/action.php", 
			{ previewtxt: $("#fmsg-"+i).val(),
				disable_emoticons: ( $("#fmsg-"+i+"-disableemotes:checked").length ? '1' : '' )
			},
			function(t) {
				$("#fmsg-"+i+"-prevbutton").val("Edit");
				$("#fmsg-"+i+"-form .message-preview").html(t).show().prev().hide();
				$("#fmsg-"+i+"-form :input").removeAttr("disabled");
				$("#fmsg-"+i+"-loading").hide();
			}
		);
	} else {
		$("#fmsg-"+i+"-prevbutton").val("Preview");
		$("#fmsg-"+i+"-form .message-preview").hide().prev().show();
	}
}

function postReply(i) {

	var message = $("#fmsg-"+i).val();
	if(message == ''){ alert("Missing the message field"); return; }
	var tid = $("#tid").val();
	if(!tid){ alert("Error reading topic ID; couldn't post reply."); return; }
	
	$("#fmsg-"+i+"-form :input").attr("disabled", "disabled");
	$("#fmsg-"+i+"-loading").show();
	
	$.post(
		"/forums/action.php",
		{ _do: "post_reply",
			tid: tid,
			message: message,
			'subscribe[tid]': $("#fmsg-"+i+"-subscribe-tid:checked").length,
			'subscribe[pid]': $("#fmsg-"+i+"-subscribe-pid:checked").length,
			dont_send_mail: $("#fmsg-"+i+"-dontemailgroup:checked").length,
			disable_emoticons: $("#fmsg-"+i+"-disableemotes:checked").length,
			reply_to: $("#fmsg-"+i).data("reply_to")
		}, function(res){
			if(res.err) alert("Error: "+res.err);
			else if(res.pid){
				$.post("/forums/action.php", { load_post:res.pid, newpost:'1' }, function(post){
					$("#fmsg-"+i+"-form").parent("li").hide().before(post);
					initTagAutocomplete();
				});
			} else alert("An unknown error ocurred. Your post may or may not have been saved.");
			$("#fmsg-"+i+"-form :input").removeAttr("disabled");
			$("#fmsg-"+i+"-loading").hide();
		}, "json"
	);
	
}

function resizeAvatars() {
	// get the height of each speech bubble and hide avatar if it's not high enough
	$("#fpostslist > .aboveth").each(function(){
		if( $(this).height() > 190 ) {
			$(this).find(".avatardisp").toggle();
		}
	});
}

var reply_i = 0;
function threadedReply(pid, threadid, replyto, act){
	
	messagefocused = true;
	
	reply_i++;
	var rspace = $("#reply-"+threadid);
	
	if( $(rspace).children("dl").is(":visible") ) {
		if(!confirm("Load a new reply form and replace the current one?")) return;
	}
	$(rspace).show().html('<dl><dt><span style="background-image:url(/bin/img/mascot.png);" class="avatartn"></span></dt><dd class="message"><div class="speechpoint"></div><div class="bubble"><div style="padding-left:22px; background:url(/bin/img/loading_arrows_blue.gif) no-repeat left center;">Loading reply form</div></div></dd></dl>');
	
	var replyinp = '[url=#p'+pid+']@[/url]'+replyto+' ';
	if(act == "quote") replyinp+= 'PID:'+pid;
	
	$.post("/forums/action.php",
		{ _do: 'load_reply_form',
			i: reply_i,
			textinp: replyinp
		}, function(res){
			$(rspace).html(res);
			TBinit();
			$(rspace).find(".message-text").prepend('<div style="margin:0 0 15px; padding:0 0 0 25px; font-size:15px; color:#888; background:url(/bin/img/icons/chat.png) no-repeat left center;">You\'re replying to <a href="#p'+pid+'">'+replyto+'</a></div>');
			$("#fmsg-"+reply_i).data("reply_to", threadid).focus();
		}
	);
}

function initEditPost(pid){
	if( $("#edit-"+pid).is(":visible") ) { alert("Can't load edit form since you're already editing that post"); return; }
	$("#p"+pid).addClass("loading");
	var h = $("#message-"+pid).height() + 14;
	if(h < 200) h = 200;
	$.post("/forums/action.php", { load_edit_form:pid }, function(res){
		$("#edit-"+pid).html(res).show().prev().hide();
		$("#edit-"+pid+"-text").css("height", h+"px");
		TBinit();
		$("#p"+pid).removeClass("loading");
	});
}

function submitEditPost(pid){
	$("#p"+pid).addClass("loading");
	$("#edit-"+pid+" :input").attr("disabled", "disabled");
	$.post(
		"/forums/action.php",
		{ _do: "edit_post",
			pid: pid,
			message: $("#edit-"+pid+"-text").val(),
			disable_emoticons: $("#edit-"+pid+"-disableemotes:checked").length,
			clearedit: $("#edit-"+pid+"-clearedit:checked").length
		}, function(res){
			var rm = $("#p"+pid+".loading");
			$("#p"+pid).before(res);
			$(rm).remove();
			initTagAutocomplete();
			//$("#message-"+pid).html(res).show().next().hide();
			//$("#p"+pid).removeClass("loading");
		}
	);
}

function deletePost(pid) {
	if( confirm("Permanently delete this post?") ){
		$("#p"+pid).addClass("loading");
		$.post(
			"/forums/action.php",
			{ delete_post: pid },
			function(res){
				if(res.error){
					alert("Error: "+res.error);
					$("#p"+pid).removeClass("loading");
				} else {
					$("#p"+pid).fadeOut();
				}
			}, "json"
		);
	}
}

function forumSubscription(subj, id, elem) {
	if( !$("#usrid").val() ) {
		$("#login, body > .overlay").fadeIn();
		return;
	}
	$(elem).addClass("chbox-loading");
	$.post(
		"/forums/action.php",
		{ _do: "manage_subscription",
			_subj: subj,
			_id: id
		}, function(res){
			if(res) alert("Error: "+res);
			$(elem).animate({opacity:1}, 500, function(){ $(this).removeClass("chbox-loading"); });
		}
	);
}

function requiredA() {
	if(!$("#NT-title").val()) { alert("Please input a TOPIC TITLE"); return false; }
	if(!$("#fmessage").val()) { alert("Please input a MESSAGE"); return false; }
	confirm_exit=false;
	return true;
}

function loadPosts(tid) {
	$(".postnav .loading img").show();
	$.post(
		"/forums/action.php", 
		{ load_posts: tid },
		function(t) {
			$(".postnav").hide();
			$("#fpostslist .postitem").remove();
			$("#fpostslist").addClass("loaded").prepend(t);
			resizeAvatars();
			tooltip();
		}
	);
}

function fRatePost(pid, r, el){
	if( !$("#usrid").val() ) {
		$("#login, body > .overlay").fadeIn();
		return;
	}
	$(el).addClass("loading");
	$.post(
		"/forums/action.php",
		{ rate_post:pid,
			rating:r
		}, function(res){
			if(res.error) alert("Error: "+res.error);
			$(el).removeClass("loading").find(".rating").attr("title", res.title).html(res.outp);
		}, "json"
	);
}




function forumToggle(what,jump) {
	$("#"+what).toggle();
	$("#no-stuff").toggle();
	$("#reply-cell").toggleClass('on');
	$("#posts-cell").toggleClass('on');
	if(jump) window.location='#'+jump;
}

function postQuote(what,jump,who) {
	initiateReply();
	if(who) who="[b]"+who+"[/b] \n";
	$('#fmessage').focus().val( $('#fmessage').val() + '[quote]' + who + $('#edit-text-'+what).html() + "[/quote]\n" );
	$("#quote-inserted").show();
	window.location='#'+jump;
}

function postNewTopic() {

	var $message = $('#fmessage').val().replace(/&/g, '[AMP]').replace(/\+/g, '[PLUS]');
	if($message == "") {
		alert("Missing the message field");
		return;
	}
	var $title = $("#forum-form input[name='title']").val().replace(/&/g, '[AMP]').replace(/\+/g, '[PLUS]');
	var $tags = $("#forum-form input[name='tags']").val().replace(/&/g, '[AMP]').replace(/\+/g, '[PLUS]');
	var $type = $("#forum-form input[name='type']").val();
	
	$('#reply-button').attr("disabled","disabled");
	$('#reply-loading').show().siblings().hide();
	
	$.ajax({
		type: "POST",
		url: "/forums/action.php",
		data: "do=Post Topic&ajax=1&message="+$message+"&tags="+$tags+"&title="+$title+"&type="+$type,
		success: function(t){
			var $arr = t.split("|--|");
			if($arr[0] != "") alert($arr[2]);
			if($arr[1]) $("#reply-permalink").slideDown().attr("href", $arr[1]);
			if($arr[2]) $("#reply-form").html($arr[2]);
		}
	});
	
}
