// forum javascript

function showhideReply(){

	if(document.getElementById('reply_form').style.visibility == 'hidden'){
		document.getElementById('reply_form').style.visibility = 'visible'; 
	} else {
		document.getElementById('reply_form').style.visibility = 'hidden'; 
	}
}

function showEdit(reply_id){

	if(document.getElementById('edit_form').style.visibility == 'hidden'){
		document.getElementById('edit_form').style.visibility = 'visible'; 
	}
	
	var source_div = 'reply_' + reply_id;
	
	document.getElementById('reply_edited_content').innerHTML = document.getElementById(source_div).innerHTML;
	document.getElementById('reply_id').value = reply_id;
}

function hideEdit(){
	document.getElementById('edit_form').style.visibility = 'hidden'; 
}

function loadEditForm(editLink, replyContainer, replyId){

	var content = $(".forum-reply-content", replyContainer);

	function exitEditmode(){
		$(".forum-reply-edit-form", replyContainer).empty();
		content.show();
		$(editLink).show();
		replyContainer.inEditmode = false;
	}
	
	if(replyContainer.inEditmode){
		exitEditmode();
		return;
	}
	
	replyContainer.inEditmode = true;	
	$(editLink).text("Edit (loading)");
	
	$.get("forum/reply_ajax.php?reply_id=" + replyId, function(data){
		
		$(editLink).text("Edit");
		$(editLink).hide();
		
		var editForm = document.createElement("div");
		editForm.className = "forum-reply-edit-form";
		editForm.style.textAlign="right";
		
		var editText = document.createElement("textarea");
		editText.style.width = (content.width() - 2) + "px";
		editText.style.height = Math.max(100, content.height()) + "px";
		editForm.appendChild(editText);
		$(editText).text(data);
		
		editForm.appendChild(document.createElement("br"));
		
		var cancelEditButton = document.createElement("button");
		$(cancelEditButton).text("Cancel");
		cancelEditButton.onclick = function(){
			loadEditForm(editLink, replyContainer, replyId);
		}
		editForm.appendChild(cancelEditButton);
		
		var sendEditButton = document.createElement("button");
		$(sendEditButton).text("Send Edit");
		
		editForm.appendChild(sendEditButton);
		sendEditButton.onclick = function(){
		
			editText.disabled = true;
			cancelEditButton.disabled = true;
			sendEditButton.disabled = true;
			
			$.post("forum/edit_post.php", { reply_id: replyId, reply_edited_content: editText.value}, function(){
				$.get("forum/reply_formatted_ajax.php?reply_id=" + replyId, function(newContent){
					$(".forum-reply-content-container", replyContainer).html(newContent);
					exitEditmode();
				});
			});
		}
		
		$(editForm).insertAfter(content);
		content.hide();
	});
}

