function hasMinChars (value, chars) {
	if (value.length < chars) {
		return false;
	} else {
		return true;
	}
}

function numbersOnly (value) {
	if (!value.match(/^\d+$/))	{
		return false;
	} else {
		return true;
	}
}

function isEmailFormat (str) {
	var strLength = str.length
	var atIndex = str.indexOf("@")
	var dotIndex = str.indexOf(".")
	//	Check if @ is in string and not first character
	if (atIndex == -1 || atIndex == 0) {
		return false;
	}
	//	Check if . is in string and atleast 1 bigger than index of @ and that there are at least 2 characters after .
	if (dotIndex < atIndex + 2 || dotIndex > strLength - 3) {
		return false;
	}
	//	If it gets here the string must be good
	return true;			
}

function conditionValid (condition) {
	var formField = document.getElementById(condition[0]);	
	var type = formField.type;
	var value = null;
	switch (type) {
		case 'text':
			value = formField.value;
			break;
		case 'textarea':
			value = formField.value;
			break;
	}
	if (value != null) {
		var conditionType = condition[1];
		var conditionParam = condition[2];
		switch (conditionType) {
			case 'minChars':
				return hasMinChars(value, conditionParam);
				break;
			case 'emailFormat':
				return isEmailFormat(value);
				break;
			case 'numbersOnly':
				return numbersOnly(value);
				break;
		}
	}
	//	Condition processing failed, return valid;
	return true;
}

function updateDisplayValid (condition, valid) {
	var inputId = condition[0];
	var feedback = condition[3];
	var formField = document.getElementById(inputId);
	var tooltipBox = document.getElementById(inputId +'_tooltipBox');
	var tooltip = document.getElementById(inputId +'_tooltip');
	if (valid) {
		formField.className = 'form_field_default';
		if (tooltipBox) {
			tooltipBox.style.display = 'none';
		}
	} else {
		formField.className = 'form_field_invalid';
		if (tooltip) {
			tooltip.setAttribute('tip', feedback);
		}
		if (tooltipBox) {
			tooltipBox.style.display = 'block';
		}
	}
}

function hasInvalidField (invalidFields, condition) {
	for (var i = 0; i < invalidFields.length; i++) {
		if (invalidFields[i] == condition[0]) {
			return true;	
		}
	}
	return false
}

function checkForm (conditions) {
	var invalidFields = new Array();
	for (var i = 0; i < conditions.length; i++) {
		var condition = conditions[i];
		if (!hasInvalidField(invalidFields, condition)) {
			var valid = conditionValid(condition)
			updateDisplayValid(condition, valid);
			if (!valid) {
				//	Condition is not valid
				invalidFields.push(conditions[i][0]);
			}
		}
	}
	var submitButton = document.getElementById('submitButton');
	if (invalidFields.length == 0) {
		//	Enable form button
		submitButton.disabled = false;
	} else {
		//	Disable form button
		submitButton.disabled = true;
	}
}
