window["CommentPage"] = 1;
window["ajaxIsBusy"]  = 0;

function ajaxSubmit()
{
	if (window["ajaxIsBusy"] == 1) return;
	window["ajaxIsBusy"] = 1;
	var t = $('CommentTitleInput');
	var d = $('CommentDescriptionInput');
	var a = $('ArticleId');
	var z = $('CommentNameInput');
	
	if (t.value.length < 1 && d.value.length < 1)
	{
		window["ajaxIsBusy"] = 0;
		return;
	}
	
	new Ajax.Request(
		"/webservices/comments.ws.php?PostComments", 
		{
			method: "post", 
			parameters: {"a": a.value, "d":d.value, "t":t.value, "z":z.value}, 
			onSuccess: function (transport) 
			           { 
			           		var response = transport.responseText; 
			           		$('FormHolder').style.display = 'none';
			           		$('CommentTitleInput').value = '';
			           		$('CommentDescriptionInput').value = '';
			           		$('CommentList').style.display = 'block';
			           		GetCommentPage(a.value, 1);
			           }
		}
		);
}

function GetCommentPage(a, p)
{
	window["CommentPage"] = p;
	new Ajax.Request("/webservices/comments.ws.php?GetCommentPage", 
		{
			method: "post",
			parameters: {"a" : a, "p":p, "s":6 },
			onSuccess: function(t) {DrawComments(t.responseText); }
		}
	);
}

function escapeHTML (str) 
{
	var div = document.createElement('div');
	var text = document.createTextNode(str);
	div.appendChild(text);
	return div.innerHTML;
}
				
function DrawComments(stuff) 
{
	cp = stuff.evalJSON();
	div = $('CommentList');
	window["CommentPage"] = cp.Page;
	
	s = '';
	for (i=0;i<cp.Results.length;i++) 
	{
		s += '<span class="postedwhen">Posted by ' + cp.Results[i].Username + ' on ' + cp.Results[i].CommentDate + '</span><h4 class="commenth4">' + escapeHTML(cp.Results[i].Title) + '</h4><p class="commentp">' + escapeHTML(cp.Results[i].Comments) + '</p>';
	}
	if (cp.PageCount > 1)
	{
		s += '<div id="CommentBottom"><div id="CBin">Next Page ';
		for (i=1;i<=cp.PageCount;i++) 
		{
			s += (i > 1) ? ' | ' : '';
			s += (i == cp.Page) ? (i.toString()) : ('<a href="javascript:GetCommentPage(' + cp.ArticleId + ',' + i.toString() + ');">' + i.toString() + '</a>');
		}
		s += '</div></div>';
	}
	div.innerHTML = s;
}

function addIdeaAction()
{
	if (UserId < 1) 
	{
		alert("You must be logged in to add an idea. Please click on the \"Login\" link to sign up or to log in.");
		return;
	}
	
	window["ajaxIsBusy"] = 0;
	$('FormHolder').style.display = 'block';
	$('CommentList').style.display = 'none';
}