function getHTTPObject()
{
  if(window.XMLHttpRequest) return new XMLHttpRequest();
  else if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  else {
    alert("Posting comments requires browser with AJAX compatible JavaScript.");
    return null;
  }
} 

function trim(stringToTrim) 
{
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function validateForm()
{	
	if(document.form_comments.comments.value == ""
	|| document.form_comments.comments.value.length < 3
	|| document.form_comments.comments.value.length > 2000)
	{
		alert("Comments must be between 3 and 2000 characters.");
		return false;
	}		
	else if(document.form_comments.name.value == ""
	|| document.form_comments.name.value.length < 3)
	{
		alert("Name must be between 3 and 20 characters.");
		return false;
	}
	else if(document.form_comments.email.value == "" 
	|| document.form_comments.email.value.indexOf("@") < 1 
	|| document.form_comments.email.value.indexOf(".") == -1 
	|| document.form_comments.email.value.length < 5)
	{
		alert("E-mail address is not valid.");
		return false;
	}
	else return true;
}

function postComment()
{
  if(!validateForm()) return;

  httpObject = getHTTPObject();
  if (httpObject == null) return;

  var params = "action=post";
  params += "&name=" + document.form_comments.name.value;
  params += "&email=" + document.form_comments.email.value;
  params += "&comments=" + document.form_comments.comments.value;
  params += "&id=" + document.form_comments.id.value;
  params += "&type=" + document.form_comments.type.value;

  httpObject.open("POST", "/include/comments.php", true);

  //Send the proper header information along with the request
  httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  httpObject.setRequestHeader("Content-length", params.length);
  httpObject.setRequestHeader("Connection", "close");

  httpObject.send(params); 
  httpObject.onreadystatechange = setOutput;
  document.form_comments.comments.value = ""; //blank out the comment on post instead of on response to prevent duplicates
  document.form_comments.btnSubmit.disabled = true;
}

// Change the value of the outputText field
function setOutput()
{
  if(httpObject.readyState == 4)
  { 
    if(httpObject.responseText == "-1") 
      alert("There was a problem with the form inputs. Please make sure they are valid values.");
    else if(httpObject.responseText == "-2") 
      alert("There was a server error posting the comment.  Please try again later.");
    else if(httpObject.responseText != "")
    {
      var currValue = document.getElementById('commentsMade').innerHTML
      if(currValue == "Want to be the first to let us know what you think?") currValue = "";

      document.getElementById('commentsMade').innerHTML = httpObject.responseText + currValue;
    }
  }
  document.form_comments.btnSubmit.disabled = false;
}

var httpObject = null;