var ajax = '/ajax/publicBackend.php';
var comment = { };

function submitComment() {
if ($('commentName').value != ''){
  $('errorMessage').innerHTML = '';

  comment.postId = $('commentPostId').value;
  comment.name   = $('commentName').value;
  comment.email  = $('commentEmail').value;
  comment.website = $('commentWebsite').value;
  comment.comment = $('commentComment').value;

  if ($('commentSubmit')) { $('commentSubmit').disabled = true; }

  new Ajax.Request(ajax, {parameters:'pos=postcomment&postid='+comment.postId+'&name='+encodeURIComponent(comment.name)+'&email='+encodeURIComponent(comment.email)+'&website='+encodeURIComponent(comment.website)+'&comment='+encodeURIComponent(comment.comment), onSuccess:handlerSubmitComment, onFailure:errFunc, onException:errFunc});

}else {  
	$('errorMessage').innerHTML = "You must enter your name. Please try again.";
	new Effect.Highlight('commentName', {startcolor:'#dd0000', endcolor:'#ffffff'});

      }
}

function handlerSubmitComment(t) {

  if (t.responseText.match("%%SUCCESS%%") || t.responseText.match("%%MODERATE%%")) {

    $('commentName').value = '';
    $('commentEmail').value = '';
    $('commentWebsite').value = '';
    $('commentComment').value = '';

    if ($('commentSubmit')) { $('commentSubmit').disabled = false; }

    var commentEl = document.createElement('DIV');
    var rand = Math.floor(Math.random()*10000);
    commentEl.id = "comment"+rand;

    comment.comment = comment.comment.replace(new RegExp("\n", "g"), "<br/>");
    comment.website = "http://"+comment.website.replace(/http:\/\//, "");
    comment.website = comment.website == "http://" ? "" : "<a href='"+comment.website+"'>";
    comment.endTag  = comment.website == "http://" ? "" : "</a>";
    comment.name    = comment.name    == "" ? "Anonymous" : comment.name;
    if (t.responseText.match("%%MODERATE%%")) {
      comment.moderate = "<b>Note: This comment is currently being held for moderation awaiting approval.</b><br/><br/>";
    } else {
      comment.moderate = "";
    }

    commentEl.innerHTML = comment.moderate+"<b>"+comment.website+comment.name+comment.endTag+"</b><br/>"+comment.comment+"<div style='margin: 5px 0; border-bottom: 1px solid #ccc;'> &nbsp; </div><br/>";
    commentEl.style.display = 'none';
    $('lastComment').appendChild(commentEl);
    Effect.Appear(commentEl);

    // Reset fields
    $('commentName').value = '';
    $('commentEmail').value = '';
    $('commentWebsite').value = '';
    $('commentComment').value = '';

  } else {

    if ($('commentSubmit')) { $('commentSubmit').disabled = false; }

    if (t.responseText.match("ERROR:")) {
      $('errorMessage').innerHTML = t.responseText.replace("ERROR:", "");
    } else {
      $('errorMessage').innerHTML = "There was an error submitting your comment. Please try again";
    }
  }

}

function errFunc(t) {

    $('errorMessage').innerHTML = "There was an error submitting your comment. Please try again";

}
