// JavaScript Document
//These functions are used to validate the enquiry form

// Generic function to add another function to the existing onload sequence

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

//Initialisation function for this form

function initialise() {
	var inputs = document.getElementsByTagName("input");
	inputs[2].focus();
}

addLoadEvent(initialise);

// Delete all fields and set focus back on first field

function clearForm() {
	var inputs = document.getElementsByTagName("input");
	for (var i=2; i<inputs.length; i++){
	  inputs[i] = "";
	}
	inputs[2].focus();
}

// This function checks if the realname field is at least 1 character.

function checkrealnameforlength(whatYouTyped) {
	var txt = whatYouTyped.value;
	if (txt.length > 0) {
		return true;
	}
	else {
		return false;
	}
}

// This function checks if the phone field is at least 11 characters long.

function checkphoneforlength(whatYouTyped) {
	var txt = whatYouTyped.value;
	if (txt.length > 10 || txt.length == 0)  {
		return true;
	}
	else {
		return false;
	}
}

// This function checks if the location field is at least 1 character.

function checklocationforlength(whatYouTyped) {
	var txt = whatYouTyped.value;
	if (txt.length > 0) {
		return true;
	}
	else {
		return false;
	}
}


//This function validates all inputs when the 'submit' button is pressed

function checkForm (thisForm) {
	var errormessage = "";
	if (!checkrealnameforlength(thisForm.realname)) {
		errormessage = "Please enter your name";
		thisForm.realname.focus();
	}
	else {
		if (!emailCheck(thisForm.email)) {
			errormessage = "email missing or invalid";
			thisForm.email.focus();
		}
	}
	if (errormessage !== "") {
		alert("validation failed: " + errormessage);
		return false;
	}
	else {
		return true;
	}
}
