
// author:	Guy Murphy
// date:	28th April 2005
// purpose:	validate form elements
// history:	modified from perviously existing code that came from.... somewhere
// notes:	specific to Pal Mar.... I think

// the normal fields in the form to check
var normalFields = new Array (
	'full_name', 'from'
);

// messages should the normal fields fail to validate
// these message elements pair up with the
// normalFields elements
var normalMessages = new Array (
	'Your Name\n',
	'Friends Email\n'
);

// the email fields to validate
var emailFields = new Array (
	'email'
);

// the messages for failed e-mail fields
// these elements pair up with the emailFields elements
var emailMessages = new Array (
	'Your Email Address\n'
);

// NOTE: if one wished to add additional types of validation
// checks then we'd introduce a new pair of arrays, the former
// to specify the fields to perform the check upon, and the later
// for failure messages

// functon to check if a field
// has a value
function hasValue (field) {
	if (field == null) {
		return false;
	} else {
		return (field.value != ''); 
	}
}

// function to check if the value of a field
// is a valid address
function isValidEmailAddress (field) {
	var addy = field.value;
	var valid = addy.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
	return valid;
}

// NOTE: if we wanted to add an additional type of validation
//

// function to style a field as valid
function styleAsValid (field) {
	field.style.borderColor = 'green';
	field.style.borderWidth = 2;
	field.style.borderStyle = 'solid';
}

// function to style a field as valid
function styleAsInValid (field) {
	if (field != null) {
		field.style.borderColor = 'red';
		field.style.borderWidth = 1;
		field.style.borderStyle = 'solid';
	}
}

// main entry point
function checkForm (form) {
	
	var isValid = true;
	var alertText = '';
	// check the regular fields
	for (var i = 0; i < normalFields.length; i++) {
		var fieldName = normalFields[i];
		var field = form.elements[fieldName];
		if (!hasValue(field)) { // validation failed
			styleAsInValid(field);
			alertText += normalMessages[i];
			isValid = false;
		} else {
			styleAsValid(field);
		}
	}
	// check the e-mail fields
	for (var i = 0; i < emailFields.length; i++) {
		var fieldName = emailFields[i];
		var field = form.elements[fieldName];
		if (!isValidEmailAddress(field)) { // validation failed
			styleAsInValid(field);
			alertText += emailMessages[i];
			isValid = false;
		} else {
			styleAsValid(field);
		}
	}
	
	if (isValid) {
		return true;
	} else {
		alert('Oops.. please complete:-\n\n' + alertText);
		return false;
	}
}