////////////////////////////////////
//	AJAX comments
//

var http;
var submitBtn;

//	Language-specific strings
var langComments = '';
var langAuthorError = '';
var langCommentError = '';
var langPostedBy = '';
var langDelete = '';

//	variables for blog location, postId, and comment delete permission
var blogLocation;
var postId;
var allowDelComment;
var lastAction;

//	Calling Init without disrupting previous onloads
if(window.onload)
{
	var oldHandler = window.onload;
	var newHandler = Init;
	window.onload = function(){oldHandler(); newHandler();}
}
else
{
	window.onload = Init;
}

//	Initialize XMLHttpRequest or the other object
function Init()
{
	var success = false;

	try
	{
		http = new XMLHttpRequest();
		success = true;
	}
	catch(e)
	{
		try
		{
			http = new ActiveXObject('Microsoft.XMLHTTP');
			success = true;
		}
		catch(e2)
		{
			success = false;
		}
	}

   submitBtn = document.getElementById('commentSubmitBtn');
/*
//	If AJAX is not supported, just use the normal submission method
	if(success)
	{
      try
		{
			http.open('post', blogLocation + '?NewCommentXML&post=' + postId);
			http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			http.onreadystatechange = function()
         {
            if(http.readyState == 4)
            {
               var xmlResponse = http.responseXML;
               var error = xmlResponse.getElementsByTagName('error');

            //	Errors in submitted comment
               if(error.length == 0)
               {
                  submitBtn = document.getElementById('commentSubmitBtn')
                  if(submitBtn)
                     submitBtn.parentNode.parentNode.onsubmit = AddComment;
               }
               else
                  throw new Error('Not supported');
            }
         };

			http.send('');
		}
		catch(e)
		{
		//	Do nothing
		}
	}
*/
}

//	Send posted comment to server
function AddComment()
{
// Remove AJAX comment handling for submits
   if(document.getElementById('submit').value == 'add')
   {
      return true;
   }

	http.open('post', blogLocation + '?NewCommentXML&post=' + postId);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = ShowComments;

	var message = '';
	var author = encodeURIComponent(document.getElementById('authorInput').value);
   var codeInput = '';

   if(document.getElementById('codeInput'))
   {
      codeInput = document.getElementById('codeInput').value;
   }

// Set this current action as the last action
	lastAction = document.getElementById('submit').value;

   if(document.getElementById('msgInput') && document.getElementById('msgInput').value != '')
   {
      message = encodeURIComponent(document.getElementById('msgInput').value);

      http.send('my-email=' + document.getElementById('commentEmailInput').value + '&author=' + author + '&message=' + message + '&submit=' + document.getElementById('submit').value + '&codeInput=' +  codeInput );
   }
   else if(document.getElementById('messageEditorIframe'))
   {
      message = encodeURIComponent(document.getElementById('messageEditorIframe').contentWindow.document.body.innerHTML);

      http.send('my-email=' + document.getElementById('commentEmailInput').value + '&author=' + author + '&message=' + message + '&submit=' + document.getElementById('submit').value + '&codeInput=' +  codeInput);
   }
   else
   {
      http.send('my-email=' + document.getElementById('commentEmailInput').value + '&author=' + author + '&message=&submit=' + document.getElementById('submit').value  + '&codeInput=' +  codeInput );
   }

	return false;
}

//	Delete comment, send commentId to server
function DeleteComment(postId, commentId)
{
	if(confirm(langDelete + '?'))
	{
		http.open('post', blogLocation + '?DeleteCommentXML&post=' + postId);
      http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.onreadystatechange = ShowComments;
		http.send('comment=' + commentId);
	}

	return false;
}

//	Parse the server's response and display new comments
function ShowComments()
{
	if(http.readyState == 4)
	{
		var xmlResponse = http.responseXML;
		var error = xmlResponse.getElementsByTagName('error');

	//	Remove previous errors
		var errorSpan = document.getElementById('errorSpan');
		if(errorSpan)
		{
			errorSpan.parentNode.removeChild(errorSpan);
		}

	//	Errors in submitted comment
		if(error.length > 0)
		{
			error = error[0];

			var errorId = error.getElementsByTagName('error-id');
			errorId = errorId[0].firstChild.data;
			var errorMsg = error.getElementsByTagName('error-message');
			errorMsg = errorMsg[0].firstChild.data;

			var errorSpan = document.createElement('span');
			errorSpan.setAttribute('class', 'error');
			errorSpan.setAttribute('id', 'errorSpan');

			if(errorMsg == 'author')
			{
			//	Author error
				errorSpan.innerHTML = langAuthorError;
				var author = document.getElementById('authorInput');
				author.parentNode.insertBefore(errorSpan, author.nextSibling);

			//	Focus on author
				author.focus();
			}
			else if(errorMsg == 'message')
			{
			//	Message error
				errorSpan.innerHTML = langCommentError;

				if(document.getElementById('messageEditor'))
					var message = document.getElementById('messageEditor');
				else
					var message = document.getElementById('msgInput');

				message.parentNode.insertBefore(errorSpan, message);
			}
			else if(errorMsg = 'codeInput')
			{
         // Code error
				errorSpan.innerHTML = langCodeError;
				var codeInput = document.getElementById('codeInput');
				codeInput.parentNode.insertBefore(errorSpan, codeInput.nextSibling);

         // Refresh code image
				document.getElementById('codeImage').src = blogLocation+ '?Captcha&'+ new Date().getTime();

			//	Focus on code
				codeInput.focus();
			}
		}
		else
		{
		//	Clear the message textarea if last action was a submit
			if(lastAction == 'add')
			{
				if(document.getElementById('messageEditorIframe'))
					document.getElementById('messageEditorIframe').contentWindow.document.body.innerHTML = '';
				if(document.getElementById('msgInput'))
					document.getElementById('msgInput').value = '';
				if( document.getElementById('codeInput'))
					document.getElementById('codeInput').value = '';
			}

		//	Find commentBlock div
			var commentBlock = document.getElementsByTagName('div');
			for(var i = 0; i < commentBlock.length; i++)
			{
				if(commentBlock[i].className == 'commentBlock')
					break;
			}
			commentBlock = commentBlock[i];
			commentBlock.innerHTML = '';

		//	Loop through comments and add them to HTML
			var comments = xmlResponse.getElementsByTagName('comment');
			for(var i = comments.length - 1; i >= 0; i--)
			{
				var newComment = document.createElement('div');

				var commentId = comments[i].getAttribute('commentid');
				var author = comments[i].getElementsByTagName('author');
				author = author[0].firstChild.data;

				var timestamp = comments[i].getElementsByTagName('timestamp');
				timestamp = timestamp[0].firstChild.data;

				var message = comments[i].getElementsByTagName('message');
				message = message[0].firstChild.data;

				var preview = comments[i].getAttribute('preview');

				newComment.innerHTML = '<h5 class="time">' + langPostedBy + ' ' + author + ' ' + timestamp + '</h5><p class="commentText">' + message + '</p>';

				if(allowDelComment && preview != 'true')
					newComment.innerHTML += '<a class="delCommentAnchor" onclick="return DeleteComment(' + postId + ', ' + commentId + ');" href="index.php?page=DeleteCommentXML&amp;blog=' + blogLocation + '&amp;post=' + postId + '&amp;comment=' + commentId + '">' + langDelete + '</a>';

				newComment.className = 'comment';
				commentBlock.appendChild(newComment);
			}

		//	Change number of comments
			document.getElementById('commentCntAnchor').innerHTML = langComments + '(' + comments.length + ')';
		}
	}
}
