/**************************************************
 * Attempts to find the form field with the
 * specified name.
 * IN : name: [scalar] form field name
 *      form: [object] form to search in
 * OUT: form field object
 */
function findFormField(name, form)
{
	var result = false;
	
	if (!form)
		form = document.forms[0];
	
	for (var i = 0; i < form.elements.length; i++)
		if (form.elements[i].name.toLowerCase() == name.toLowerCase())
			result = form.elements[i];
	
	return result;
}



/**************************************************
 * Attempts to match the specified value with the
 * specified value type and returns whether the
 * supplied value is indeed of the requested type.
 * IN : value: [scalar] value to test
 *      type : [scalar] requested value type
 * OUT: success [true|false]
 */
function typeMatch(value, type)
{
	var regexp;
	var result = false;
	
	value = value.replace(/^\s*|\s*$/g, '');
	type = type.toLowerCase();
	
	if (type == 'postal')
		regexp = /^\d{4}\s*\w{2}$/i;
	else if (type == 'telephone')
		regexp = /^((\+|00)\d{2}(\s*|-)?0?|0)(\d\s*-?(\s*\d\s*){8}|\d{2}\s*-?(\s*\d\s*){7}|\d{3}\s*-?(\s*\d\s*){6}|\d{4}\s*-?(\s*\d\s*){5}|\d{5}\s*-?(\s*\d\s*){4})$/;
	else if (type == 'email')
		regexp = /^(\w[-\w]*\.)*\w[-\w]*@(\w[-\w]*\.)+\w+$/;
	
	if (regexp.test(value))
		result = true;
	
	return result;
}



/**************************************************
 * Validates the supplied list of field names using
 * their specified types.
 * IN : @args: [scalar] a list of field names and
 *             their required types
 *      form : [object] form to search for the
 *             form fields in
 * OUT: success [true|false]
 */
function validate()
{
	var extra = arguments.length % 2;
	var field;
	var result = true;
	
	if (extra)
		form = arguments[arguments.length - 1];
	if (!form)
		form = document.forms[0];
	
	for (var i = 0; i < (arguments.length - extra) / 2; i++)
	{
		field = findFormField(arguments[i * 2], form);
		if (field)
		{
			if (field.value == '')
			{
				result = false;
				field.focus();
				window.alert('Dit veld dient ingevuld te zijn.');
				break;
			} else if ((arguments[(i * 2) + 1]) && (!typeMatch(field.value, arguments[(i * 2) + 1])))
			{
				result = false;
				field.focus();
				window.alert('Dit veld dient correct te worden ingevuld.');
				break;
			}
		}
	}
	
	return result;
}