var testValid = 'yes';
// If the length of the element's string is 0 then display helper message
function isEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		testValid = 'no';
		alert(helperMsg);
		elem.focus(); // set the focus to this input

		return true;
	}
	return false;
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		testValid = 'no';
		alert(helperMsg);
		elem.focus();

		return false;
	}
}

function formValidator(){
	// add references to specific form fields
	var name = document.getElementById('name');
	var company = document.getElementById('company');	
	var employees = document.getElementById('employees');	
	var position = document.getElementById('position');	
	var telephone = document.getElementById('telephone');
	var email = document.getElementById('email');	
	var address = document.getElementById('address');
	var postcode = document.getElementById('postcode');			

	testValid = 'yes';


	// Load each check one by one
	if(isEmpty(name, "Please enter a valid name")){
	}
	
	if(isEmpty(company, "Please enter a valid company name")){
	}
	
	if(isEmpty(employees, "Please enter the number of employees at your company")){
	}
	
	if(isEmpty(position, "Please enter your position at your company")){
	}		
	
	if(isEmpty(telephone, "Please enter a valid telephone number")){
	}
	
	if(emailValidator(email, "Please enter a valid email address")){
	}
	
	if(isEmpty(address, "Please enter a valid address")){
	}
	
	if(isEmpty(postcode, "Please enter a valid postcode")){
	}		

	if (testValid == 'yes') {
		return true;
	}

	else {
		return false;
	}

}

// Make sure the page has loaded first

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

// Add formValidator to submit button

addLoadEvent(function() {
	document.getElementById('goButton').onclick = function(){
		return formValidator();
	}

});