var arrRequiredElements = [];
var arrErrorFieldLookup = [];
var arrErrorFieldFlags = [];
arrErrorFieldLookup = new Hash({});

function initialize(whichForm) {
	arrRequiredElements = $$('input.required');
	arrRequiredElements.each(function(item, index){
		arrErrorFieldLookup.include(item.getProperty('id'), '');
	});
	
	arrRequiredElements.each(function(item, index){
		item.addEvent('blur', function(){
			//validateItem(item);
			validateItems(arrRequiredElements);
			setErrorMessage(item);
		});
	});
	$('btn_submit').addEvent('click', function(){
		arrRequiredElements.each(function(item, index){
			item.fireEvent('blur');
		});
	});
}

function setErrorMessage(whichItem){
	var boolIsValid = true;
	if (arrErrorFieldLookup.hasValue(false)) {
		boolIsValid = false;
	}
	if (boolIsValid) {
		$("errorMessage").set('text', null);
	} else {
		//$("errorMessage").set('text', 'There are problems with your form information. Please fix the issues with the appropriate fields below.');
		$("errorMessage").set('text', 'Please complete all of the fields indicated below.');
	}
}

function setElementErrorFlag (whichItem, flag){
	arrErrorFieldLookup.set(whichItem.getProperty('id'), flag);
}

function setErrorFieldIndicator(whichItem, flag) {
	var objParent = whichItem.getParent();
	if (flag) {
		objParent.removeClass('error');
	} else {
		objParent.addClass('error');
	}
}

function validateItems(theseItems) {
	theseItems.each(function(item, index){
		validateItem(item);
	});
}

function validateItem(whichItem) {
	switch(whichItem.type){
		case 'text':
		case 'password':
		case 'textarea':
		case 'select-one':
			if(whichItem.value != ''){
				if(whichItem.hasClass('email')){
					var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
					if(whichItem.value.toUpperCase().match(regEmail)){
						setElementErrorFlag(whichItem, true);
						setErrorFieldIndicator(whichItem, true);
					}else{
						setElementErrorFlag(whichItem, false);
						setErrorFieldIndicator(whichItem, false);
					}
				} else {
					setElementErrorFlag(whichItem, true);
					setErrorFieldIndicator(whichItem, true);
				}
			} else {
				setElementErrorFlag(whichItem, false);
				setErrorFieldIndicator(whichItem, false);
			}
			break;
	}
}

function validate(whichForm) {
	var boolIsValid = true;
	arrRequiredElements.each(function(item, index){
		validateItem(item);
	});
	if (arrErrorFieldLookup.hasValue(false)) {
		boolIsValid = false;
	}
	if (boolIsValid) {
		$("errorMessage").set('text', '');
	} else {
		$("errorMessage").set('text', 'Please complete all of the fields indicated below.');
	}
	return boolIsValid;
}