// Get the currently selected radio button in the group.
function GetSelectedRadioButton(btngrp)
{
	for (var i=0; i < btngrp.length; i++)
		if (btngrp[i].checked)
			return i;
	return -1;
}

// Is the checkbox checked?
function IsCheckboxChecked(chkbox)
{
	return chkbox.checked;
}

// Is the email field valid? NOTE: this only checks validity of the text - not the destination.
function IsEmailFieldValid(oTextControl, bRequired/*=false*/)
// returns 0 for empty (only when required), -1 for invalid chars, 1 for success
{
	// Set up default values.
	if (typeof(bRequired) != "boolean")
		bRequired = false;
	if (bRequired && IsFieldEmpty(oTextControl))
	{
		oTextControl.focus();
		return 0;
	}
	
	// TODO: Make this smarter.
//debug...
//alert(oTextControl.name + ", " + oTextControl.value);
	if (!IsFieldEmpty(oTextControl) && 
		(oTextControl.value.indexOf('@') != -1) && (oTextControl.value.indexOf('.') != -1))
		return 1;
	else
		return -1;
}

// Is this field empty?
function IsFieldEmpty(oTextControl)
{
	if (oTextControl.value == "") 
		return true;
	else
		return false;
}

// Is this option in the select field selected?
function IsOptionSelected(selectname, skipzero)
{
	var startingpoint = 0;
	if (skipzero)
		startingpoint = 1;
	if (selectname.selectedIndex >= startingpoint) 
		return true;
	else
		return false;
}

// Is the phone field valid?
function IsPhoneFieldValid(oTextControl, bRequired/*=false*/)
// returns 0 for empty (only when required), -1 for invalid chars, 1 for success
{
  return ValidateText(oTextControl, bRequired, "0123456789-()");
}

// Is there a radio field selected in the group?
function IsRadioChecked(btngrp)
{
	if (GetSelectedRadioButton(btngrp) == -1) 
		return false;
	else
		return true;
}

// Is this URL valid? NOTE: this only checks validity of the text - not the destination.
function IsURLFieldValid(oTextControl, bRequired/*=false*/)
// returns 0 for empty (only when required), -1 for invalid chars, 1 for success
{
	// Set up default values.
	if (typeof(bRequired) != "boolean")
		bRequired = false;
		
	if (bRequired && IsFieldEmpty(oTextControl))
	{
		oTextControl.focus();
		return 0;
	}
		
	if (IsFieldEmpty(oTextControl) && 
	((oTextControl.value.indexOf("http://") == -1) || (oTextControl.value.indexOf(".") == -1)))
		return -1;
	else
		return 1;
}

// Validate text against the characters passed in (or our standard set).
function ValidateText(oTextControl, bRequired/*=false*/, szValidationChars/*=" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ0123456789-()"*/)
// returns 0 for empty (only when required), -1 for invalid chars, 1 for success
{
	// Set up default values.
	if (typeof(bRequired) != "boolean")
		bRequired = false;
	var szCheckOK = szValidationChars;
	if ((typeof(szCheckOK) != "string") || (szCheckOK == ""))
		szCheckOK = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ0123456789-().,/<>?;:|=+-_)(*&^%$#@!~\r\n\'\"";

	  // Must have something
	if (bRequired && IsFieldEmpty(oTextControl))
	{
	  oTextControl.focus();
	  return 0;
	}

	  // Validate against character set
	var szCheckStr = oTextControl.value;
	for (i = 0;  i < szCheckStr.length;  i++)
	{
	  ch = szCheckStr.charAt(i);
	  for (j = 0;  j < szCheckOK.length;  j++)
	    if (ch == szCheckOK.charAt(j))
	      break;
	  if (j == szCheckOK.length)
	  {
	  	oTextControl.focus();
	  	return -1;
	  }
	}

	return 1;
}

// Validate text against the numbers only.
function ValidateTextNumeric(oTextControl, bRequired/*=false*/)
// returns 0 for empty (only when required), -1 for invalid chars, 1 for success
{
  return ValidateText(oTextControl, bRequired, "0123456789");
}

// Form Validation Functions -------------------------------------------------

// Validate a typical form.
function frm_Validator(theForm, astrRequiredFieldNamesAND, astrRequiredFieldNamesOR, bAlert, strMessage)
{
	// Parameter checking...
	if (theForm == "undefined")
	{
		alert("There was a problem in the form. Please contact the webmaster - frm_Validator:theForm");
		return false;
	}

	// Loop through all elements checking them according to type.
//debug...
//alert(theForm.elements.length);
	var strInvalidFields = "";
	var bORListValid = false;
	for (nElementCount = 0; nElementCount < theForm.elements.length; ++nElementCount)
	{
//debug...
//alert("type = " + theForm.elements[nElementCount].type + " & name = " + 
//	theForm.elements[nElementCount].name);
//continue;

		// Skip the field names not stated in the AND list.
		var bANDFieldNameFound = false;
		for (var nIndexFieldNames = 0; (astrRequiredFieldNamesAND != null) && (nIndexFieldNames < astrRequiredFieldNamesAND.length); ++nIndexFieldNames)
		{
			if (astrRequiredFieldNamesAND[nIndexFieldNames] == theForm.elements[nElementCount].name)
			{
				bANDFieldNameFound = true;
				break;
			}
		}

		// Skip the field names not stated in the OR list.
		var bORFieldNameFound = false;
		for (var nIndexFieldNames = 0; (astrRequiredFieldNamesOR != null) && (nIndexFieldNames < astrRequiredFieldNamesOR.length); ++nIndexFieldNames)
		{
			if (astrRequiredFieldNamesOR[nIndexFieldNames] == theForm.elements[nElementCount].name)
			{
				// Check to ensure there is at least one with something in it.
				if (!IsFieldEmpty(theForm.elements[nElementCount]))
				{
					bORFieldNameFound = true;
					bORListValid = true;
				}
				break;
			}
		}
		
//debug...
//alert(theForm.elements[nElementCount].name + ": " + bANDFieldNameFound + " & " + bORFieldNameFound);
		if ((!bANDFieldNameFound) && (!bORFieldNameFound))
		{
//debug...
//alert("Skipping: " + theForm.elements[nElementCount].name);
			continue;
		}
		else
		{
//debug...
//alert("Using: " + theForm.elements[nElementCount].name);
		}

		// Now validate based on type.
		switch(theForm.elements[nElementCount].type)
		{
			case "checkbox":
				if (!IsCheckboxChecked(theForm.elements[nElementCount]))
					strInvalidFields += "\n" + theForm.elements[nElementCount].name;
				break;
			case "radio":
				// Note: I am not sure why I have to access it this way to get the array but so be it...
//				if (!IsRadioChecked(eval(theForm.elements[nElementCount]))
				if (!IsRadioChecked(eval("theForm." + theForm.elements[nElementCount].name)))
					strInvalidFields += "\n" + theForm.elements[nElementCount].name;
				// Since we just checked all the radio fields in this group but the 
				// elements array contains each one, loop through to past the last of 
				// this group.
				// NOTE: This conflicts with what the docs tell me but it works...
				while (theForm.elements[nElementCount + 1] != null)
				{
					if (theForm.elements[nElementCount + 1].name == theForm.elements[nElementCount].name)
						++nElementCount;
					else
						break;
				}
				break;
			case "select-one": // ???
				if (!IsOptionSelected(theForm.elements[nElementCount], true))
					strInvalidFields += "\n" + theForm.elements[nElementCount].name;
				break;
			case "text":
				// Fall through...
			case "textarea":
				var bTextAreaResult = true;
				if (theForm.elements[nElementCount].name.indexOf("email") != -1)
				{
//debug...
//alert(theForm.elements[nElementCount].name);
					if (IsEmailFieldValid(theForm.elements[nElementCount], true) <= 0)
						bTextAreaResult = false;
				}
				else if (ValidateText(theForm.elements[nElementCount], true) <= 0)
				{
//debug...
//alert(theForm.elements[nElementCount].name);
					bTextAreaResult = false;
				}
				if (!bTextAreaResult)
					strInvalidFields += "\n" + theForm.elements[nElementCount].name;
				break;
			default:
				// implement as needed...for now ignore...
//				button
//				event
//				fileupload
//				hidden
//				password
//				reset
//				submit
				break;
		}
	}

	// Handle the OR list not being validated.
	var strFinalMessage = "";
	if ((astrRequiredFieldNamesOR != null) && !bORListValid)
	{
		strFinalMessage += "At least one of the following fields must be valid:\n";
		for (var nIndexFieldNames = 0; (astrRequiredFieldNamesOR != null) && (nIndexFieldNames < astrRequiredFieldNamesOR.length); ++nIndexFieldNames)
			strFinalMessage += "\n" + astrRequiredFieldNamesOR[nIndexFieldNames];
	}
		
	// Any errors?
	if (strInvalidFields != "")
		strFinalMessage = strMessage + "\n" + strInvalidFields + "\n\n" + strFinalMessage;
		
	if (bAlert && (strFinalMessage != ""))
	{
		alert(strFinalMessage);
		return false;
	}
	else
		return true;
}

// Validate a standard logon form.
function frmLogon_Validator(theForm)
{
	// Uses field named "UserId".
	var nResult = ValidateText(theForm.UserId, true);
	if (nResult == 0)
	{
		alert("\"UserId\" is a required field.");
		return false;
	}
	else if (nResult == -1)
	{
		alert("Please enter only alpha-numeric characters in the \"UserId\" field.");
		return false;
	}
	
	// Uses field named "Password".
	nResult = ValidateText(theForm.UserPassword, true);
	if (nResult == 0)
	{
		alert("\"Password\" is a required field.");
		return false;
	}
	else if (nResult == -1)
	{
		alert("Please enter only alpha-numeric characters in the \"Password\" field.");
		return false;
	}

  return true;
}

