/*
This file contains javascript functions that are used globally in various 
web pages throughout the web site.  NOTE: functions are ALPHABETICAL so
if you add a function to the file please place it accordingly and list it
below...

FUNCTIONS IN THIS FILE:
	CharacterLimiterCounter
	CheckboxArrayValidation
	CheckboxValidation
	ConcatDateFields
	CreateSubmitDataString
	DateValidation
	DigitValidation
	EmailAddressValidation
	EmptyValidation
	formvalidation_login
	FutureDateValidation
	GoToURL
	IsActualDate
	IsValidDate
	LengthValidation
	LimitTextArea	
	MembershipNumberValidation
	MinLengthValidation
	NewWindow
	PreventEnterKeySubmit
	RadioGroupValidation
	SelectValidation
	SpecialCharValidation
	StateValidation
	SubmitEnter
	SubmitFormOnlyOnce
	Trim
*/
	
// GLOBAL VARIABLES				// USED BY FUNCTION
var submitCount = 0;			// SubmitFormOnlyOnce
var g_aUSStates = new Array("AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY","AE","AP","AA");
var g_aCanadianStates = new Array("AB","BC","MB","NB","NF","NT","NS","ON","PE","PQ","SK","YT","QC","NL");
var g_aAustralianStates = new Array("AC","NW","NO","QL","SA","TS","VC","WT","SU");
var g_strAsiaCountries = new Array("BGD","BTN","BRN","KHM","TMP","HKG","IND","IOT","IDN","JPN","KAZ","LAO","MAC","MYS","MDV","MNG","MMR","NPL","PHL","KOR","LKA","TWN","THA","UZB","VNM");


/************************************************************************
* CharacterLimiterCounter
*	limits character count and shows dynamic count of characters as user 
*   is typing them in the text area
************************************************************************/
function CharacterLimiterCounter(field, maxlimit, cntfield) 
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		cntfield.value = maxlimit - field.value.length;
}


/************************************************************************
* CheckboxArrayValidation
*	shows a message (alertText) and returns false if no items in checkbox 
*   have been checked
************************************************************************/
function CheckboxArrayValidation(entered, alertText)
{
	var countChecked = 0;
	for (var i = 0; i < entered.length; i++)
	{
		// check to see if each is checked 
		if (entered[i].checked == true)
			// if any checked, validation passed 
			{ 
				return true;
			}
	}
	// if got to here, no checkboxes checked 
	if (alertText)
	{
		alert(alertText);
	} 
	return false;
}


/************************************************************************
* CheckboxValidation
*	shows a message (alertText) and returns false if checkbox has not been 
*	checked
************************************************************************/
function CheckboxValidation(entered, alertText)
{
	var strValue = entered.checked;
//alert('str'+strValue);
	if (strValue == false) 
	{
		if (alertText)
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}


/************************************************************************
* ConcatDateFields
* 	takes values from month, day and year fields and concatenates 
* 	them into MM/DD/YY(YY) format
************************************************************************/
function ConcatDateFields(fldMonth, fldDay, fldYear)
{
	var strDate = fldMonth.options[fldMonth.selectedIndex].value + "/" + fldDay.options[fldDay.selectedIndex].value + "/" + fldYear.options[fldYear.selectedIndex].value;
	return strDate;
}


/************************************************************************
* CreateSubmitDataString
* 	for the passed form returns a string of all form inputs in the 
*   format [field name]: [field value][new line]
************************************************************************/
function CreateSubmitDataString(theForm)
{
	var strValues = "";
	with (theForm)
	{
		// clear any current value
		submit_data.value = "";
		
		for (var i = 0; i < length; i++)
		{
			strValues = strValues + elements[i].name + ": ";
			if (elements[i].type == "select-one")
				strValues = strValues + elements[i].options[elements[i].selectedIndex].value + "\r\n";
			else
				strValues = strValues + elements[i].value + "\r\n";
		}
	}
	return strValues;
}


/************************************************************************
* DateValidation
* 	Accepts numeric month, date and year and determines if the date 
* 	specified is actually a valid calendar date
*	(eg: no such date as February, 31...)
************************************************************************/
function DateValidation(inputDate, inputMonth, inputYear, alertText)
{
	var bValid = true;
	var i_Date = parseInt(inputDate);
	var i_Month = parseInt(inputMonth);
	var i_Year = parseInt(inputYear);
	
	switch(i_Month) 
   	{
		case 2:
        //February
	        if (i_Year == Math.round(i_Year / 4) * 4)
	       	//leap year
			{
		       	if (i_Date > 29)
		       		bValid = false;
			}
           	else
			//non-leap year
			{
    	        if (i_Date > 28)
					bValid = false;									
			}
			break;
		case 4 :
        //April
        	if (i_Date > 30)
				bValid = false;
	        break;
        case 6:
		//June
	        if (i_Date > 30)
    			bValid = false;
		    break;		
        case 9:
        //September
	        if (i_Date > 30)
    			bValid = false;
			break;
        case 11:
        //November
        	if (i_Date > 30)
				bValid = false;
			break;
    }

	if (bValid == false)
	{
	  	alert(alertText);
		return false;
	}
	else
		return true;
}	


/************************************************************************
* DigitValidation
* 	verifies numeric value was entered and that it's length is between
* 	the passed min and max
************************************************************************/
function DigitValidation(entered, lenMin, lenMax, alertText)
{
	var strValue = Trim(entered.value);	
	var checkvalue=parseFloat(strValue);
	if ( (parseFloat(lenMin)==lenMin && strValue.length<lenMin) || (parseFloat(lenMax)==lenMax && strValue.length>lenMax) || strValue!=checkvalue || (strValue.indexOf(".")>0) )
	{
		if (alertText) 
			alert(alertText);
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}


/************************************************************************
* EmailAddressValidation
*	shows a message (alertText) and returns false if no e-mail address 
*	has been specified in the input text box (entered) or if the
*	address appears invalid due to a number of conditions checked
************************************************************************/
function EmailAddressValidation(entered, alertText)
{
	with (entered)
	{
		var len=value.length
		var apos=value.indexOf("@");
		var dotpos=value.lastIndexOf(".");
		var lastpos=value.length-1;
		// if length = 0
		// or "@" is the first character or doesn't exist
		// or "." doesn't follow "@" with at least 2 spaces between them
		// or there are more than 3 characters following the "."
		// or there are less than 2 characters following the "."
		if (len==0 || apos<1 || dotpos-apos<2 || lastpos-dotpos>4 || lastpos-dotpos<2) 
		{
			if (alertText) 
				alert(alertText);
			entered.focus();
			return false;
		}
		else 
			return true;
	}
}

/************************************************************************
* EmptyValidation
*	shows a message (alertText) and returns false if no data has been 
*	entered in the input text box (entered)
************************************************************************/
function EmptyValidation(entered, alertText)
{
	var strValue = Trim(entered.value);
	if (strValue == null || strValue == "" || strValue == "undefined")
	{
		if (alertText)
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}


/************************************************************************
* formvalidation_login
*	Error-checks userName and password and, if valid, submits form
************************************************************************/
function formvalidation_login(thisform)
{
	with (thisform)
	{
	    if (EmptyValidation(userName,"Please enter a value for the \" Email or Member#\" field.")==false) {return false;}
        if (EmptyValidation(password,"Please enter a password.")==false) {return false;}
        if(userName.value >= 0)
	    {
                if (DigitValidation(userName,16,16,"Invalid \" Member#\" - must be 16 digits.")==false) {return false;}
	    }
	    else
	    {
                if(EmailAddressValidation(userName, "Invalid Email ID")==false) {return false;}
	    }
        if (LengthValidation(password,5,8,"Password is not 5-8 characters in length, please change and re-submit.")==false) {return false;}

		url.value = window.location.href;
 
	    submit();
	    return true;
	}
}


/************************************************************************
* FutureDateValidation
*	Accepts string in date format ("mm/dd/yyyy") and verifies that date
*   is the current day OR occurs in the future.
************************************************************************/
function FutureDateValidation(inputDate, alertText)
{
	var t_day;
	var t_month;
	var t_year;
	var t_date;
	var i_day;
	var i_month;
	var i_year;
	var i_date;
	var now = new Date();
	var compareDate = new Date(inputDate);
	
	// create "yyyymmdd" string out of today's date
	t_day = now.getDate();
	if (t_day < 10)
		t_day = "0" + t_day.toString();
	else
		t_day = t_day.toString();
	t_month = now.getMonth() + 1;
	if (t_month < 10)
		t_month = "0" + t_month.toString();
	else
		t_month = t_month.toString();
	t_year = now.getFullYear().toString();
	t_date = t_year + t_month + t_day;

	// create "yyyymmdd" string out of input date
	i_day = compareDate.getDate();
	if (i_day < 10)
		i_day = "0" + i_day.toString();
	else
		i_day = i_day.toString();
	i_month = compareDate.getMonth() + 1;
	if (i_month < 10)
		i_month = "0" + i_month.toString();
	else
		i_month = i_month.toString();
	i_year = compareDate.getFullYear().toString();
	i_date = i_year + i_month + i_day;

	// if input date occurs before today's date
	if (i_date < t_date)
	{
		// show alert and return false (did not pass validation)
		alert(alertText);
		return false;
	}
	// otherwise, passed validation
	else
		return true;
}


/************************************************************************
* GoToURL
*	Redirects the main frame in a frameset to page or anchor specified
*	in value property of select or option item named "dest"
************************************************************************/
function GoToURL(form) {
        var myindex=form.dest.selectedIndex
        window.open(form.dest.options[myindex].value, target="_self"); //change these both to "yes" to get the toolbar
}


/************************************************************************
* IsValidDate
* 	Checks for the following valid date formats: 
* 	MM/DD/YYYY OR MM-DD-YYYY 
************************************************************************/
function IsValidDate(dateStr) {
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		return false;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			return false;
   		}
	}
	return true;  // date is valid
}


/************************************************************************
* IsValidDate - OLD DO NOT USE
* 	Checks for the following valid date formats: 
* 	MM/DD/YYYY OR MM-DD-YYYY 
*	Also separates date into month, day, and year variables 
************************************************************************/
/*
function IsValidDate(dateField) 
{ 

	var dateStr = dateField.value;

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 

	var matchArray = dateStr.match(datePat); // is the format ok? 
	if (matchArray == null) 
	{ 
		alert("\"Date of Birth\" must be in entered in the format mm/dd/yyyy.") 
		dateField.select();
		dateField.focus();
		return false; 
	} 

	var month = matchArray[1]; // parse date into variables 
	var day = matchArray[3]; 
	var year = matchArray[4]; 

	if (month < 1 || month > 12) 
	{ // check month range 
		alert("\"Date of Birth\" month must be between 1 and 12."); 
		dateField.select();
		dateField.focus();
		return false; 
	} 

	if (day < 1 || day > 31) 
	{ // check day range
		alert("\"Date of Birth\" day must be between 1 and 31."); 
		dateField.select();
		dateField.focus();
		return false; 
	} 
	
	return true; // date is valid 
} 
*/

/************************************************************************
* LengthValidation
*	shows a message (alertText) and returns false if the length of
*	the input text (entered) is too short or too long
************************************************************************/
function LengthValidation(entered, lenMin, lenMax, alertText)
{
	var strValue = Trim(entered.value);
	if (strValue.length < lenMin || strValue.length > lenMax)
	{
		if (alertText) 
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}


/************************************************************************
* LimitTextArea
*	limits number of characters entered into textarea input.
*	once character count exceeds limit, characters are trimmed 
*   as they are typed
************************************************************************/
function LimitTextArea(field, maxlimit) 
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
}


/************************************************************************
* MembershipNumberValidation
*	shows a message (alertText) and returns false if the membership
*	number (entered) does not meet the criteria set up in the function
************************************************************************/
function MembershipNumberValidation(entered, alertText)
{
	var strValue = Trim(entered.value);
	// requirements:
	//		- begin with '600663'
	//		- length of exactly 16 digits
	//		- numeric only
	if ((strValue.substring(0,6) != '600663') ||
		(strValue.length != 16) ||
		(strValue != parseFloat(value)) )
	{
		if (alertText) 
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}

/************************************************************************
* MinLengthValidation
*	shows a message (alertText) and returns false if the length of
*	the input text (entered) is too short
************************************************************************/
function MinLengthValidation(entered, lenMin, alertText)
{
	var strValue = Trim(entered.value);
	if (strValue.length < lenMin )
	{
		if (alertText) 
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}

/************************************************************************
* NewWindow
*	opens a new browser window with the specified url, window name
*	and other parameter specs
************************************************************************/
function NewWindow(URL, name, specs) 
{
	var anon_win = window.open(URL, name, specs);
}


/************************************************************************
* PreventEnterKeySubmit
*	used to prevent enter key in onkeypress events.  used to prevent 
*	forms from being submitted, bypassing form validation
************************************************************************/
function PreventEnterKeySubmit() 
{
  return !(window.event && window.event.keyCode == 13); 
}


/************************************************************************
* RadioGroupValidation
*	shows a message (alertText) and returns false if no selection has 
*	been made between the items in the radio group (groupName)
************************************************************************/
function RadioGroupValidation(groupName, alertText)
{
	var allEmpty = true;
	for (index = 0; index < groupName.length; index++)
	{
  		if (groupName[index].checked)
	  	{
	   		allEmpty = false; //found one to be selected
	    	break;            //get out of the loop
	  	}
	}
	if (allEmpty)
	{
		if (alertText)
			alert(alertText);
		return false;
	}
	else
		return true;
}

/************************************************************************
* SelectValidation
*	shows a message (alertText) and returns false if no data has been 
*	selected in the dropdown list (entered)
************************************************************************/
function SelectValidation(entered, alertText)
{
	var idx = entered.selectedIndex;

	with (entered.options[idx])
		{
		if ( (value == 0) || (value == "") || (value == null) )
		{
			if (alertText) 
			{
				alert(alertText);
			}
			entered.focus();
			return false;
		}
		else 
			return true;
	}
}


/************************************************************************
* SpecialCharValidation
* 	allows only certain characters to be entered (to prevent foreign
*   character issues)
************************************************************************/
function SpecialCharValidation(entered, alertText)
{
	var strValidate = entered.value;
	with (strValidate)
	{
		for (i = 0; i < length; i++)
		{
			ch = charAt(i);
			if ( !(ch >= 'a' && ch <= 'z') 
				&& !(ch >= 'A' && ch <= 'Z') 
				&& !(ch == ' ') 
				&& !(ch == ',')
				&& !(ch == '-')
				&& !(ch == '.') 
				&& !(ch == '\'')
				&& !(ch == '\/')
				&& !(ch == '(')
				&& !(ch == ')')
				&& !(ch == '@')
				&& !(ch == '_')
				&& !(ch >='0' && ch <='9'))
			{
				if (alertText) 
					alert(alertText);
				entered.focus();
				entered.select();
				return false;
			}
		}
	}
	return true;
}


/************************************************************************
* StateValidation
*	shows a message and returns false if no state has been selected 
*	in the state dropdown list (stateField) when the country selected
*	in the country dropdown list (countryField) is United States, Canada
*   or Australia.  if United States, Canada or Austraili is selected,
*   verify a valid State/Province/Territory is selected for the country.
* 	if the country is NOT one of the afforementioned, no state may be 
*   selected so an alert is shown and false is returned.
************************************************************************/
function StateValidation(countryField, stateField)
{
	var strCountry = countryField.value;
	var strState = stateField.options[stateField.selectedIndex].value;
	if ( ( (strCountry=="US") || (strCountry=="USA") ) ||
		 ( (strCountry=="CA") || (strCountry=="CAN") ) ||
		 ( (strCountry=="AU") || (strCountry=="AUS") ) )
	{
		if ( (strState == 0) || (strState=="") || (strState == null) )
		{
			alert("Please select a State/Province/Territory for US/Canada/Australia.");
			stateField.focus();
			return false;
		}
		else
		{
			switch (strCountry)
			{
				case "USA":
				{			     
				    for (i=0;i<g_aUSStates.length;i++) {
			                if (strState==g_aUSStates[i]) {
			                        return(true);
			                }
			        }
					alert("Please select a valid State for the United States.");
					stateField.focus()
					return false;
				}
				case "CAN":
				{			     
				    for (i=0;i<g_aCanadianStates.length;i++) {
			                if (strState==g_aCanadianStates[i]) {
			                        return(true);
			                }
			        }
					alert("Please select a valid Province for Canada.");
					stateField.focus()
					return false;
				}
				case "AUS":
				{			     
				    for (i=0;i<g_aAustralianStates.length;i++) {
			                if (strState==g_aAustralianStates[i]) {
			                        return(true);
			                }
			        }
					alert("Please select a valid Territory for Australia.");
					stateField.focus()
					return false;
				}
			}
		}				
		return true;
	}
	else
	{
		if ( (strState != 0) && (strState != "") && (strState != null) )
		{
			alert("Please review your State/Province/Territory and Country selections for accuracy.");
			stateField.focus();
			return false;
		}
		else
			return true;
	}
}


/************************************************************************
* SubmitEnter
*	used in onkeypress event of form inputs to allow enter key to 
*   kick off form submission process.  works with ie and netscape.
************************************************************************/
function SubmitEnter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return false;
	
	if (keycode == 13)
	   return true;
	else
	   return false;
}


/************************************************************************
* SubmitFormOnlyOnce
*	once the form's submit button is clicked, prevents the form from 
*   being submitted more than once.  
*   NOTE: Make sure to call this function AFTER all validation functions
************************************************************************/
function SubmitFormOnlyOnce()
{
   if (submitCount == 0)
   {
      submitCount++;
      return true;
   }
   else 
   {
      alert("This form has already been submitted.  Thanks!");
      return false;
   }
}

/************************************************************************
* Trim
*	Trims leading and trailing spaces and tabs. 
************************************************************************/
function Trim(sData) 
{
	var sTrimmed = String(sData);
	sTrimmed = sTrimmed.replace(/(^[ |\t]+)|([ |\t]+$)/g, '');
	return sTrimmed;
}



