window.onload = function(){
	// Element registration
	nameField = document.getElementById('name');
  email = document.getElementById('email');
  subject = document.getElementById('subject');
  message = document.getElementById('message');
  submitButton = document.getElementById('submitButton');
  
	// Focus on first field
	nameField.focus();
  submitButton.onclick = validate;
}

// Validation function
function validate(){
	nameField.value = Trim(nameField.value);
	email.value = Trim(email.value);
	subject.value = Trim(subject.value);
	message.value = Trim(message.value);

  msg = "";
	focusOn = "";
	
	if(nameField.value == "")
  	{
		msg = msg + "Please enter your name \n";
		// Sets a varible that this is the first missing field
		if(focusOn == ""){focusOn = nameField}
		}
	
	if(email.value == "")
  	{
		msg = msg + "Please enter your email address \n";
		// Sets a varible that this is the first missing field
		if(focusOn == ""){focusOn = email}
		}
	
  if(subject.value == "")
  	{
		msg = msg + "Please enter a subject \n";
		// Sets a varible that this is the first missing field
		if(focusOn == ""){focusOn = subject}
		}
  
  if(message.value == "")
  	{
		msg = msg + "Please enter a message \n";
		// Sets a varible that this is the first missing field
		if(focusOn == ""){focusOn = message}
		}
  
	// Stops form submition is an alert has been found
  if(msg != "")
    {
      alert(msg);
			// Focuses on the first missing field
			focusOn.focus();
      return false;
    }
}

// Fucntion removes space from the beginning and end of each field before checking the value
function Trim(str) {
  str = str.replace(/^[ ]+(.*)$/,'$1'); // Trims leading spaces
  str = str.replace(/^(.*)[ ]+$/,'$1'); // Trims trailing spaces
  return str;
}

