/* Form validation functions */

//set up fixed regular expressions
if (window.RegExp)
{
	//Email user RegEx: matches words or anything enclosed in ""s
	var userEx = new RegExp("^[\\w-.]+$|^\"[^\"]+\"$");
	//Email host RegEx: matches numeric IP ([127.0.0.1]) or domain name (blah.co.nz)
	var hostEx = new RegExp("^\\[?(\\d{1,3}\\.){3}\\d{1,3}\\]?$|^([-0-9a-z]+\\.)+[a-z]{2,3}$", "i");
}
else var userEx = hostEx = null;


//Selects a field and shouts an error (called internally by checking functions)
function fieldAlert(field, msg)
{
	if (field.focus) field.focus();
	if (field.select) field.select();
	alert(msg);
	return false;
}


//checks through form to make sure required fields are filled in
//Usage: bool checkRequired(object form [, string field [, ...]])
function checkRequired(form)
{
	for (var cnt = 1; cnt < arguments.length; cnt++)
	{
		var field = form.elements[arguments[cnt]];
		var msg = '';
		if (!field) continue;

		if (field.value) continue; //field has a value, move along
		else //print out errors for field types
		{
			if (field.title) msg = 'Please fill in the ' + field.title + ' field.';
			else msg = 'Please fill in this required field.';
			return fieldAlert(field, msg);
		}
	}
	return true;
}


//checks through form to make sure email addresses are valid
//Usage: bool checkEmail(object form [, string field (only text-input) [, ...]])
function checkEmail(form)
{
	var error = false;
	for (var cnt = 1; cnt < arguments.length; cnt++)
	{
		var field = form.elements[arguments[cnt]];
		//field isn't filled in, skip it (use checkRequired if it needs to be filled in)
		value = field.value;
		if (!value) continue;

		var email = value.split('@'); //split email into user & host
		if (email.length != 2) error = true; //there was less/more than one @

		//if browser supports regular expressions, validate it further
		else if (userEx && hostEx && (!userEx.test(email[0]) || !hostEx.test(email[1]))) error = true;

		if (error) return fieldAlert(field, 'The email address you have entered is invalid.');
	}
	return true;
}