//comment code

function showComments(msgId) {
	//show the comment section
	var el = document.getElementById("comments_" + msgId);
	if(el.style.display = "none") {
		el.style.display = "";	
		//load the comments
		var oHTTP = false;
		var sUrl = "comment_service.php";
		var sQuery = "action=LIST&messageId=" + msgId;
		if (window.XMLHttpRequest) {
	  	oHTTP = new XMLHttpRequest();
	    } // IE
		else if (window.ActiveXObject) {
	    oHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	  }	
		oHTTP.open('GET', sUrl + "?" + sQuery, true);
	  oHTTP.onreadystatechange = function() {
	  	if (oHTTP.readyState == 4) {
	    	UpdateComments(msgId, oHTTP.responseText);
	    }
	  }
	  oHTTP.send(null);	
	}	
}

function UpdateComments(msgId, sResponse){
	var div = document.getElementById("item_comments_" + msgId);
	//alert(sResponse);
	div.innerHTML = sResponse;
	doCommentCounts();
}

function imposeMaxLength(Object, MaxLen)
{
	if(Object.value.length >= MaxLen) {
		Object.value = Object.value.substring(0,254);
	}
  //return (Object.value.length <= MaxLen);
}

function commentSave(msgId) {
	var comment = $("comment_text_" + msgId).value;
	//alert("comment: " + comment);
	var result;
	// add the comment
	var oHTTP = false;
	var sUrl = "comment_service.php";
	var sQuery = "action=SEND&messageId=" + msgId + "&comment=" + comment;
	if (window.XMLHttpRequest) {
  	oHTTP = new XMLHttpRequest();
    } // IE
	else if (window.ActiveXObject) {
    oHTTP = new ActiveXObject("Microsoft.XMLHTTP");
  }	
	oHTTP.open('GET', sUrl + "?" + sQuery, true);
  oHTTP.onreadystatechange = function() {
  	if (oHTTP.readyState == 4) {
  		CommentSaved(msgId, oHTTP.responseText);
    }
  }
  oHTTP.send(null);	

	// hide the form
	//hideCommentForm(msgId);
	
}

function CommentSaved(msgId, sResponse){
	var div = document.getElementById("comment_form_" + msgId);
	//alert(sResponse);
	div.innerHTML = sResponse;
	showComments(msgId);
}

function showCommentForm(msgId) {
	$("comment_form_" + msgId).style.display = "";
}
function hideCommentForm(msgId) {
	$("comment_form_" + msgId).style.display = "none";
}


function doCommentCounts() {
	var oHTTP = false;
	var sUrl = "comment_service.php";
	var sQuery = "action=COUNT";
	if (window.XMLHttpRequest) {
  	oHTTP = new XMLHttpRequest();
    } // IE
	else if (window.ActiveXObject) {
    oHTTP = new ActiveXObject("Microsoft.XMLHTTP");
  }	
	oHTTP.open('GET', sUrl + "?" + sQuery, true);
  oHTTP.onreadystatechange = function() {
  	if (oHTTP.readyState == 4) {
  		onReceivedCommentCounts(oHTTP.responseText);
    }
  }
  oHTTP.send(null);	
}

function onReceivedCommentCounts(sResponse) {
	var pairs = sResponse.split("~");
	var tmp, span;
	for (var i = 0; i < pairs.length; i++) {
		tmp = pairs[i].split(",");
		span = $("comment_count_" + tmp[0]);
		if(span) {
			span.innerHTML = "(" + tmp[1] + ")";
		}		
	}
}