window.onload = prepareForm;

/* Function examples are from Jeremy Keith's 'Bulletproof Ajax' and were modified to fit this form.  Read the book for more details on how to use Ajax on top of HTML, CSS, and PHP. */

/* Grabs all the data from the elements in the contactform div */
function prepareForm() {
  if(!document.getElementById) {
    return;
  }
  if(!document.getElementById("contactform")) {
    return;
  }
  document.getElementById("contactform").onsubmit = function() {
    var data = "";
    for (var i=0; i<this.elements.length; i++) {
      data+= this.elements[i].name;
      data+= "=";
      data+= escape(this.elements[i].value);
      data+= "&";
    }
    return !sendData(data);
  };
}

/* Sends the data to the server on POST and returns the changes */
function sendData(data) {
  var request = getHTTPObject();
  if (request) {
    request.onreadystatechange = function() {
      parseResponse(request);
    };
    request.open( "POST", "form.php", true );
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    request.send(data);
    return true;
  } else {
    return false;
  }
}

/* Determines if the browser is in the correct status to run the script */
function parseResponse(request) {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      var container = document.getElementById("formcontainer");
      container.innerHTML = request.responseText;
      prepareForm();
    }
  }
}

/* Allows these functions to work in all browsers */
function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}