/* Form Validating Functions */

function validateForm() {
	var theform = document.getElementById("target");
	var reason = "";
	reason += checkName(theform.name);
	reason += checkEmail(theform.email);
	reason += checkRadio(theform.aff);
	reason += checkEmpty(theform.usertext);
	if (reason != "") {
		alert(reason);
		return false;
	} else {
		return true;
	};
}

function checkName(fld) {
	var error = "";
	var badChars = /[^a-zA-Z',\s\.]/;
	if (fld.value == "") {
		error = "The required Name field is empty.\n\n";
	} else if (badChars.test(fld.value)) {
		error = "The Name entered contains illegal characters.\n\n";
	} else {
		error = "";
	};
	return error;
}

function trim(s) {
	return s.replace(/^\s+|\s+$/, '');
}

function checkEmail(fld) {
	var error = "";
	var trfld = trim(fld.value);
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; 
	if (fld.value == "") {
		error = "The required Email field is empty.\n\n";
	} else if (!emailFilter.test(trfld)) {
		error = "Please enter a valid email address.\n\n";
	} else if (fld.value.match(illegalChars)) {
		error = "The email address contains illegal characters.\n\n";
	} else {
		error = "";
	};
	return error;
}

function checkEmpty(fld) {
	var error = "";
	if (fld.value.length == 0) {
		error = "The required Question or Comment field is empty.\n\n";
	};
	return error;
}

function checkRadio(fld) {
	var error = "";
	var chosen = -1;
	for (var r = fld.length - 1; r > -1; r--) {
		if (fld[r].checked) {
			chosen = r;
			r = -1;
		};
	};
	if (chosen == -1) {
		error = "Please select an Institutional Affiliation from the list.\n\n";
	};
	return error;
}
