// thanks, http://www.ajaxf1.com/tutorial/ajax-php.html?page=3
var httpObject = null;

// Get the HTTP Object
function getHTTPObject() {
	if ( window.ActiveXObject )
		return new ActiveXObject("Microsoft.XMLHTTP");
	else if ( window.XMLHttpRequest )
		return new XMLHttpRequest();
	else
		return null;
}

function checkAJAX() {
	if( getHTTPObject() != null ) {
		/*
		* this does have the drawback of clearing the contents if the
		* user reloads the page, but this shouldn't be an issue often
		* and most bots shouldn't be able to see it.
		*/		
		getForm();
	}
	/* else = no form on this page */
}

function updateLoading() {
	if( httpObject.readyState < 4 )
		document.getElementById("formholder").innerHTML = '<img src="images/ajax-loader.gif" alt="Loading form..." />';
	if( httpObject.readyState == 4 && httpObject.status == 200 )
		document.getElementById("formholder").innerHTML = httpObject.responseText;
}

function getForm() {
	httpObject = getHTTPObject();
	if( httpObject != null ) {
		var params = "getform=true";
		httpObject.onreadystatechange = updateLoading;
		httpObject.open("POST", "ajaxform.php", true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.send( params );
	}
}

function checkStatus ( obj ) {
	// declare the vars
	var reg;
	var txt = obj.value;
	var name = obj.name;
	
	// figure out which regexp we should be using
	if( name == "name" )
		reg = /^\s|[a-z\-]+$/i;
	else if( name == "email" )
		reg = /^[a-z0-9._%-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}$/i;
	else if( name == "phone" )
		reg = /^[0-9-.()]+$/i;
//	else if( name == "website" )
//		reg = /^(http(s?)\:\/\/)?[a-z0-9\-\.]+\.[a-z]{2,3}(\/\s*)?$/i; // hopefully this matches any valid url
	else if( name == "answer" )
		reg = /^orange$/i;
	
	// check if field is valid
	var match = reg.test(txt);
	
	// red border if it's invalid
	if( match )
		obj.style.border = '1px solid #ddd';
	else
		obj.style.border = '1px solid red';
	
	// don't allow submitting if the answer is wrong
	if( name == "answer" && match )
		document.contact.submit.disabled = false;
	else if( name == "answer" && !match )
		document.contact.submit.disabled = true;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(checkAJAX);