/* JavaScript script for generalized utilities for use with 
 * HTML forms.
 *
 * Contains:
 *     validateForm(formId)
 *     clearForm(formId)
 */




/* Generalized client-side validation function for HTML forms.
 *
 * Given a form id, the function checks the values of any
 * input with an id containing the string '_req'.  If the validation
 * passes, true is returned, otherwise false.  
 * The textarea fields are checked the same way.
 * Radio buttons and check boxes are checked as well.  If any one 
 * of the options has an id containing '_req' then one of the 
 * options must be selected in order for validation to pass.
 *
 * If there is a failure, an alert box is displayed requesting the
 * user fill in the field.  The field name is displayed, so the
 * names of the fields should be human readable. Since a space (' ')
 * is not allowed in the name of the field, this function will 
 * replace underscores ('_') with spaces for display.
 */
function validateForm(formId) 
{
	var form = document.getElementById(formId);
	if (form) 
	{
		// for user display.
		str="Please enter a value for ";
		
		// required radio or checkbox groups without selections made.
		var choices = new Array();
		// required radio or checkbox groups with selections made.
		var picked = new Array();
		
		var inputs = form.getElementsByTagName('input');
		if (inputs) {
			for (var i = 0; i < inputs.length; ++i) 
			{
				// text inputs...
				if (inputs[i].type == 'text' && inputs[i].id.match('_req'))
				{
					// validate (does it have text?)
					if (!hasText(inputs[i].value))
					{
						// if not, display a message with 
						// the cleaned up name and return false.
						str = str + cleanText(inputs[i].name);
						alert(str);
						return false;
					}
				}

				if ((inputs[i].type == 'radio' || inputs[i].type == 'checkbox') && inputs[i].id.match('_req'))
				{
					// strip the name down so that it's matchable to 
					// other inputs from the same group (necessary b/c of PHP)
					var iName = stripText(inputs[i].name);
					if (!inputs[i].checked)
					{
						// if not checked and in neither list, add to choices.
						if (!findChoice(iName, choices) &&
							!findChoice(iName, picked))
						{
							choices.push(iName);
						}
					}
					else
					{
						// if selected and in choices, remove it.
						if (findChoice(iName, choices))
						{
							choices = removeChoice(iName, choices);
						}
						
						// if selected and not in picked, add it.
						if (!findChoice(iName, picked))
						{
							picked.push(iName);
						}
					}
				}
			}//endfor
		}

		// if any required radio/checkbox groups have no 
		// selections made, display an alert and exit.
		if (choices.length > 0)
		{
			str = str + cleanText(choices.pop());
			alert(str);
			return false;
		}

				
		var areas = form.getElementsByTagName('textarea');
		if (areas) 
		{
			// text areas...
			for (var i = 0; i < areas.length; ++i) 
			{
				// required...
				if (areas[i].id.match('_req'))
				{
					// validate (does it have text?)
					if (!hasText(areas[i].value))
					{
						// if not, display a message with 
						// the cleaned up name and return false.
						str = str + cleanText(areas[i].name);
						alert(str);
						return false;
					}
				}
			}//endfor
		}
	}
	// validation passed.
	return true;
}//end validateForm


/* Checks if the given string is blank.
 * Returns false if so, otherwise true.
 */
function hasText(str) 
{
	if (str == '')
	{
		return false;
	}
	return true;
}//end validateText


/* Cleans text up for display in an alert box.
 * Replaces underscores ('_') with spaces (' ').
 */
function cleanText(str)
{
	str = str.replace(/_/g, " ");
	return str;
}//end cleanText


/* Cleans text up for tracking radio/checkbox groups.
 * Removes square brackets ('[', ']') and numbers ('0' ... '9')
 */
function stripText(str)
{
	str = str.replace(/\d/g, "");
	str = str.replace("[", "");
	str = str.replace("]", "");
	return str;
}//end stripText


/* Finds choice in array, returns true if found.
 * False otherwise.
 */
function findChoice(choice, array)
{
	for (var i = 0; i < array.length; ++i) 
	{
		if (array[i] == choice)
		{
			return true;
		}
	}//endfor
	return false;
}//end removeChoice


/* Removes choice from array if found,
 * Otherwise simply returns array.
 */
function removeChoice(choice, array)
{
	var newArray = Array();
	for (var i = 0; i < array.length; ++i) 
	{
		if (array[i] != choice)
		{
			newArray.push(array[i]);
		}
	}//endfor
	return newArray;
}//end removeChoice




/* Clears a form completely.
 * The default "Reset" function returns the form
 * to the values that were listed on the form when
 * it was created.  This function will completely
 * clear every input (text, radio, and checkbox) and
 * text area in the form.
 * Returns false to prevent the form from taking any
 * further action.
 */
function clearForm(formId) 
{
	var form = document.getElementById(formId);
	if (form) 
	{	
		// inputs...
		var inputs = form.getElementsByTagName('input');
		if (inputs) {
			for (var i = 0; i < inputs.length; ++i) 
			{
				// clear all text...
				if (inputs[i].type == 'text')
				{
					inputs[i].value = "";
				}

				// uncheck all groups...
				if ((inputs[i].type == 'radio' || inputs[i].type == 'checkbox') && inputs[i].id.match('_req'))
				{
					inputs[i].checked = false;
				}
			}//endfor
		}
		
		// textareas...
		var areas = form.getElementsByTagName('textarea');
		if (areas) 
		{
			for (var i = 0; i < areas.length; ++i) 
			{
				// clear all text...
				areas[i].value = "";
			}//endfor
		}
	}
	// return false to prevent further action.
	return false;
}//end validateForm
