// 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 = "";
	var name = document.getElementById("enquiryform").realname;
	if (!checkrealnameforlength(name)) {
		errormessage = "Please enter your name";
		document.getElementById("enquiryform").realname.focus();
	}
	else {
		var phone = document.getElementById("enquiryform").phone
		if (!checkphoneforlength(phone)) {
			errormessage = "phone number error!";
			document.getElementById("enquiryform").phone.focus();
		}
		else {
			email = document.getElementById("enquiryform").email
			if (!emailCheck(email)) {
				errormessage = "email missing or invalid";
				document.getElementById("enquiryform").email.focus();
			}
			else {
				var loc = document.getElementById("enquiryform").location
				if (!checklocationforlength(loc)) {
					errormessage = "Please enter your location";
					document.getElementById("enquiryform").location.focus();
				}
			}
		}
	}
	if (errormessage !== "") {
		alert("validation failed: " + errormessage);
		return false;
	}
	else {
		return true;
	}
}

