/* Javascript Document */

/*  Clicking on the text in the label will bring the associated field into focus */
/*  ---------------------------------------------------------------------------- */
function focusLabels() {
	if (!document.getElementsByTagName) {
		return false;
	}
	var labels = document.getElementsByTagName("label");
	for (var i=0; i<labels.length; i++) {
		if (!labels[i].getAttribute("for")) {
			continue;
		}
		labels[i].onclick = function() {
			var id = this.getAttribute("for");
			if (!document.getElementById(id)) {
				return false;
			}
			var element = document.getElementById(id);
			element.focus();
		}
	}
}
addLoadEvent(focusLabels);

/*  Default values are deleted whenever the form field is brought into focus */
/*  Default values are restored whenever the form field is out of focus */
/*  ------------------------------------------------------------------------ */
function resetFields(whichform) {
	for (var i=0; i<whichform.elements.length; i++) {
		var element = whichform.elements[i];
		if(element.type == "submit") {
			continue;
		}
		if(!element.defaultValue) {
			continue;
		}
		element.onfocus = function() {
			if(this.value == this.defaultValue) {
				this.value = "";
			} 
		}
		element.onblur = function() {
			if(this.value == "") {
				this.value = this.defaultValue;
			}
		}
	}
}

/* Form Validation */
/* --------------- */
function isFilled(field) {
	if(field.value.length<1 || field.value == field.defaultValue) {
		return false;
	}
	else {
		return true;
	}
}

function validateForm(whichform) {
	for(var i=0; i<whichform.elements.length; i++) { // loop through the elements array of the form
		var element = whichform.elements[i];
		if(element.className.indexOf("required") != -1) { // if "required" is found in "class" pass the element to the isFilled() function
			if(!isFilled(element)) { // if isFilled() returns "false" display alert message			
				alert("Please fill in the " + element.name + " field.");
				return false;
			}
		}
	}
        return true;
}


/*  Activates the function resetFields() by passing it a Form object */
/*  ---------------------------------------------------------------- */
function prepareForms() {
	for (var i=0; i<document.forms.length; i++) {
		var thisform = document.forms[i];
		resetFields(thisform);
		thisform.onsubmit = function() {
			return validateFrom(this);
		}
	}
}
addLoadEvent(prepareForms);




