var submittingForm = false;
var labelMap = new Array();

function numeralsOnly(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	return (charCode <= 31 || (charCode >= 48 && charCode <= 57));
}

// Validation related functions.
function setErrorState(theField, theState) {
	if (! theField.nodeName.match(/^(input|select|textarea)$/i)) return;
	theField.parentNode.parentNode.className = theState ? "error" : "";
//	document.getElementById(theField.name + "_err").style.display = theState ? "inline" : "none";
}

function showWTF(id) {
	document.getElementById(id + "_wtf").style.display = "block";
}

function hideWTF(id) {
	document.getElementById(id + "_wtf").style.display = "none";
}

function validate(theField) {
	var valid = false;
	try {
		// Check that a value is entered.
		if (theField.required) {
			if (theField.type.match(/^text/i)) {
				if (theField.value.match(/\S/) == null) throw "required";
			} else if (theField.type.match(/^select-/i)) {
				if (theField.options[theField.selectedIndex].value == "") throw "required";
			}
		}
		
		// Match value to regular expression (text fields only).
		if (theField.regex && ! theField.value.match(theField.regex)) {
			throw "please verify";
		}
		
		// Run custom validator.
		if (theField.validator) {
			var message = theField.validator();
			if (message) throw message;
		}
		
		// If all goes well, then it's good.
		valid = true;
	} catch(err) {
		// Grab the error and present it to the user.
		document.getElementById(theField.name + "_err").innerHTML = "(" + err + ")";
	}
	
	// Set error state.
	setErrorState(theField, !valid);
	return valid;
}

function validateForm(theForm) {
	// We're now submitting the form.
	submittingForm = true;

	// Setup our accumulator variable.
	var valid = true;
	var fields = new Array();
	var idx = 0;

	// Loop through all the form fields and validate them.
	for (var i = 0; i < theForm.elements.length; i++) {
		if (! validate(theForm.elements[i])) {
			valid = false;
			fields[idx++] = "<b>" + labelMap[theForm.elements[i].name] + "</b>";
		}
	}
	
	// Call custom validator function, if any.
	if (theForm.validator) valid = valid && theForm.validator();
	
	// We're no longer submitting the form.
	submittingForm = false;
	
	// Return true/false to allow/prevent the form submission.
	if (!valid) {
		// Build the error message.
		document.getElementById("err_fields").innerHTML = fields.join(", ") + ".";
		
		// Show the error message.
		document.getElementById("err_block").style.display = "block";
		document.location = "#top";
	} else {
		document.getElementById("err_block").style.display = "none";
	}

	return valid;
}