// Loads comments for post id by making a XMLHttpRequest
function LoadComments(id) {
	var loader = new net.ContentLoader("commentretrieve.php?id=" + id, WriteAllComments, null, "GET");
}

// Parses response text and display comments in div
function WriteAllComments(loader) {
	var commenttxt = this.req.responseText;
	var entrywrapperdiv = window.document.getElementById("commentform").parentNode;
	// delete the "loading" div and insert the block
	var commentloaderdiv = window.document.getElementById("commentloader");
	commentloaderdiv.parentNode.removeChild(commentloaderdiv);
	// insert the server HTML into the recipient div
	var commentdiv = window.document.getElementById("readercomments");
	commentdiv.innerHTML = commenttxt;
}


// Submit user comment via XMLHttpRequest
function SubmitComment(id) {
	var username = window.document.commentsubmit.commentname.value;
	var url = window.document.commentsubmit.commenturl.value;
	var comment = window.document.forms.commentsubmit.commenttext.value;

	if (!ValidateSubmit())
		return;
	var loader = new net.ContentLoader("commentsubmit.php", AppendComment, null, "POST", 
																	 	 "id=" + id + "&username=" + username + "&url=" + url + "&comment=" + comment);
}

// Append new comment to the readercomments div
function AppendComment(loader) {
	var commenttxt = this.req.responseText;
	var commentdiv = window.document.getElementById("readercomments");
	commentdiv.innerHTML += commenttxt;
	// bookkeeping - clear form values, change numbers
	window.document.forms.commentsubmit.commentname.value = "";
	window.document.forms.commentsubmit.commenturl.value = "";
	window.document.forms.commentsubmit.commenttext.value = "";
	var titlediv = commentdiv.parentNode.getElementsByTagName("h3")[0];
	var numposts = titlediv.innerHTML.match(/(\d+)/);
	numposts = eval(numposts + "+1");
	titlediv.innerHTML = titlediv.innerHTML.replace(/(\d+)/, numposts);
}

// ----------------------------
// Comment validation functions

var emptystr = /^\s*$/;

// Trim leading/trailing white spaces
function trimstr(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

function DisplayError(errorstr) {
	var errordiv = window.document.getElementById("commenterror");
	errordiv.innerHTML = errorstr;
	return false;
}

function ClearError() {
	DisplayError("");
	return true;
}

// Non-null username
function ValidateUsername(elem) {
	if (emptystr.test(trimstr(elem.value))) {
		return DisplayError("Error: Empty username");
	} else {
		return ClearError();
	}
}

// URL well-formed
function ValidateURL(elem) {
	var httpstr = /(\w+):\/\/([^\/:]+)(:\d*)?([^# ]*)/;
	//var httpstr = /(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	if (!httpstr.test(trimstr(elem.value)) && !emptystr.test(trimstr(elem.value))) {
		return DisplayError("Error: Malformed URL");
	} else {
		return ClearError();
	}
}

// Non-empty comment, less than or equal to 5 hyperlinks in the comment, warn on detecting HTML-like tags
function ValidateComment(elem) {
	var httpstr = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g;
	var htmlstr = /<\S[^>]*>/;
	var errormsg = "";
	if (emptystr.test(trimstr(elem.value))) {
		return DisplayError("Error: Empty comment");
	}
	if (htmlstr.test(trimstr(elem.value)))
		errormsg += "Warning: HTML tags in comment will be stripped away";
	var regexresults = trimstr(elem.value).match(httpstr);
	if (regexresults != null && regexresults.length > 5) {
		if (errormsg != "")
			errormsg += "<br />";
		errormsg += "Error: " + regexresults.length + " hyperlinks detected in comment, please stick to 5 or fewer";
	}
	if (errormsg != "")
		return DisplayError(errormsg);
	else
		return ClearError();
}

// Validate all of above
function ValidateSubmit() {
	return (ValidateComment(document.forms.commentsubmit.commenttext) &&
					ValidateURL(document.forms.commentsubmit.commenturl) &&
					ValidateUsername(document.forms.commentsubmit.commentname));
}
