var autoFeedItemList = new Array();

var commentId;
var pendingCall = false;

var numCommentsToShow = 8;
var commentRequestMargin = 3;

function findCommentId(){
	with (this)
	return this.htmlElement.id.replace(/^recentQualityComment-/, '');
}

function autoFeedItem(htmlElement){

	this.htmlElement = htmlElement;
	this.commentId = findCommentId;
}

function commentPolling(pollingRate) {

    intervalId = window.setInterval(addComment, pollingRate);
}

function addComment(){

	//we have one call right off the bat to populate the list if it's empty
	if(!pendingCall && autoFeedItemList.length == 0){
		updateRecentCommentIdAndFetchComments();
	}

	if(autoFeedItemList.length > 0){

		var feedItem = autoFeedItemList.shift();

		$('recentQualityComments').insertBefore(feedItem.htmlElement, $('recentQualityComments').firstChild);
        new Effect.Highlight($('recentQualityComments').firstChild.id, { startcolor: "#F3901C" });

		//sometimes the browser will report extra child nodes if it improperly handles whitespace, so we only get the ones we know we want
		var rqcElements = $('recentQualityComments').getElementsBySelector('div[id^="recentQualityComment-"]');

	    //and remove the last one if we're over the limit to show
		if(rqcElements.length > numCommentsToShow){
			$('recentQualityComments').removeChild(rqcElements[rqcElements.length - 1]);
		}
	}

	//and another update call in the interim, if necessary
	if(!pendingCall && autoFeedItemList.length > 0 && autoFeedItemList.length < commentRequestMargin){
		updateRecentCommentIdAndFetchComments();
	}
}

function updateRecentCommentIdAndFetchComments(){

	getRecentQualityComments(commentId);
}

function getRecentQualityComments(recentId){

	pendingCall = true;

	var req = gatherAjax.Request({
		url: 'peopleAreTalking.action',
		options: {
			method: 'POST',
			parameters: {
				recentId: recentId
			},
			onSuccess: function(transport) {

				var ele = document.createElement('div');
				ele.innerHTML = transport.responseText;

				//start at the bottom, the database call returns comments in decending order
				for(j=ele.childNodes.length - 1; j>-1; j--){

					//there may be extra elements, look for this id in the recentQualityComment jsp/jspf
					if(ele.childNodes[j].id && ele.childNodes[j].id.match(/^recentQualityComment-/)){

						var newItem = new autoFeedItem(ele.childNodes[j]);
						autoFeedItemList.push(newItem);
					}
				}

				if(autoFeedItemList.length > 0){
					commentId = autoFeedItemList[autoFeedItemList.length - 1].commentId();
				}

				pendingCall = false;
     		},
     		onError: function(transport){
     		}
     	}
	});
}