//----------------------- form validation ----------------------

// are regular expressions supported? If so, we can do some better
// validation of the email address format
var reSupported = 0;
if (window.RegExp) {
	var tempStr = "a";
	var tempReg = new RegExp(tempStr);
	if (tempReg.test(tempStr)) reSupported = 1;
}

// This function selects all text in a given form element to allow
// easier user correction of erroneous fields

function highlight(elem) {
	elem.blur();
	elem.focus();
	elem.select();
}

// This function trims leading and trailing spaces from a string

function trim(str) {
	while (str.charAt(0) == " ") {
		str = str.substring(1);
	}
	while (str.charAt(str.length-1) == " ") {
		str = str.substr(0, str.length-1);
	}
	return str;
}

// Validates presence of obligatory fields. If applicable, validates email format.

function validateForm (form) {
with (form) {

		email.value = trim(email.value);
		if (email.value == "") {
			alert("Please enter your email address");
			highlight(email);
			return false;
		}
		if (! validateEmail(email.value)) {
			alert("Please enter a valid email address\n" +
                  "(for example: jsmith@widgets.co.uk)");
			highlight(email);
			return false;
		}

	return true;
	}
}


// Validate the format of an email address. NB: whether an email address
// actually exists or not cannot be validated here.

function validateEmail(str) {
  if (!reSupported)
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}

//--------------------end of form validation ----------------------