// 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 the url to be sure it follows the correct pattern. 
function checkurl(whatYouTyped) {
    var theurl = whatYouTyped.value; 
	var tomatch=/^((http|https|ftp):\/\/)?((.*?):(.*?)@)?([a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])((\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])*)(:([0-9]{1,5}))?((\/.*?)(\?(.*?))?(\#(.*))?)?$/;
    if (tomatch.test(theurl) || theurl=="")
    {
        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 = "no name ! Please enter a name";
		thisForm.realname.focus();
	}
	else {
		if (!checkphoneforlength(thisForm.phone)) {
			errormessage = "phone number error! Please enter a valid phone number";
			thisForm.phone.focus();
		}
		else {
			if (!emailCheck(thisForm.email)) {
				errormessage = "email address is missing or invalid. Please enter your email address.";
				thisForm.email.focus();
			}
			else {
				if (!checkurl(thisForm.url)) {
					errormessage = "I don't recognise this as a web site address - please check.";
					thisForm.url.focus();
				}
			}
		}
	}
	if (errormessage !== "") {
		alert("There is a problem with the information you have entered - " + errormessage);
		return false;
	}
	else {
		return true;
	}
}
