var arr_comments = new Array();

function toggle_comments(id) {
	block = $("comments_" + id);
	if (block.style.display == 'none')
		get_comments(id, true);
	else
		close_comments(id);
}

function add_comment(id) {
	block = $("addcomment_" + id);
	show_add_comment(id);
	if (block.innerHTML == "")
		block.innerHTML = '<form method="post" action="#" onsubmit="post_comment(' + id + ', $(\'name_' + id + '\').value, $(\'msg_' + id + '\').value); return false;"><fieldset style="padding: 10px 25px; width: 350px;"><legend style="font-weight: bold;">Submit your quote meaning</legend><p>Your Name: <input type="text" id="name_' + id + '" style="width: 300px;" /></p><p>Message: <textarea id="msg_' + id + '" style="width: 300px; height: 150px;" /></textarea></p><p><button type="submit"><strong>Post Comment</strong></button> <button type="button" onclick="hide_add_comment(' + id + ');">Cancel</button></p></fieldset></form>';
}

function post_comment(id, name, msg) {
	qs = "id=" + id + "&name=" + encodeURIComponent(name) + "&msg=" + encodeURIComponent(msg);
	xmlhttpPost("http://www.quotemeanings.net/post_comment.php", qs, "POST", id);
}

function get_comments(id, force) {
	if (!force && arr_comments["comments_" + id] != undefined)
		return arr_comments["comments_" + id];
	xmlhttpPost("http://www.quotemeanings.net/get_comments.php", "id=" + id, "POST", id);
}

function update_comments(str, id) {
	str = '<div style="margin: 5px 0; padding: 5px;">' + str + '</div>';
	arr_comments["comments_" + id] = str;
	open_comments(id);
	hide_add_comment(id);
	$("comments_" + id).innerHTML = str;
}

function hide_add_comment(id) {
	$("addcomment_" + id).style.display = "none";
}

function show_add_comment(id) {
	$("addcomment_" + id).style.display = "";
}

function close_comments(id) {
	$("comments_" + id).style.display = "none";
}

function open_comments(id) {
	$("comments_" + id).style.display = "";
}

function $(id) {
	return document.getElementById(id);
}

function xmlhttpPost(strURL, sendQuery, method, id) {
	var xmlHttpReq = false;
	var self = this;
	// Mozilla/Safari
	if (window.XMLHttpRequest) {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	// IE
	else if (window.ActiveXObject) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	self.xmlHttpReq.open(method, strURL, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
		if (self.xmlHttpReq.readyState == 4) {
			update_comments(self.xmlHttpReq.responseText, id);
		}
	}
    self.xmlHttpReq.setRequestHeader("Content-length", sendQuery.length);
    self.xmlHttpReq.setRequestHeader("Connection", "close");
	self.xmlHttpReq.send(sendQuery);
}