// JavaScript Document
function validateFormOnSubmit(theForm) {
var reason = "";
  
  reason += validateEmpty(theForm.firstname, 'First name');
  reason += validateEmpty(theForm.surname, 'Surname');
  reason += validateEmpty(theForm.suburb, 'Suburb');
  reason += validateMenu(theForm.state, 'State');
  reason += validateEmail(theForm.email);
  reason += validateCodeEmpty();
      
  if (reason != "") {
    alert("Please correct the following:\n\n" + reason);
    return false;
  }
  return true;
}
function validateCodeEmpty(){
	var error = "";
	if(document.signup_form.number.value==0){
		error = " - User validation code\n";
		document.signup_form.number.style.background = 'Yellow'; 
	} else {
		document.signup_form.number.style.background = 'White';   
	}
	return error;
}

function codeIncorrect(){
	alert("Please enter the correct user validation code.");
    document.signup_form.number.style.background = 'Yellow';
	document.signup_form.number.focus();
}


function validateEmpty(fld, msg) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = " - " + msg + " field has not been entered.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function validateMenu(fld, msg){
 	 var error = "";
	 var stateChoice = fld.selectedIndex;
	 if (fld.options[stateChoice].value == ""){
	 	 error = " - Select a " + msg +"\n";
		 fld.style.background = 'Yellow';
	 } else {
		fld.style.background = 'White';   
	}
	 return error;  
}
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = " - A valid email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = " - A valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = " - The email address contains invalid characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (isNaN(parseInt(stripped))) {
        error = " - The phone number contains invalid characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = " - The phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    } else {
		 fld.style.background = 'White';
	}
    return error;
}
