/*
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
	CreateAMailTo
	CreateSubmitDataString
	DateValidation
	DigitValidation
	EmailAddressValidation
	EmptyValidation
	FutureDateValidation
	GoToURL
	IsActualDate
	IsValidDate
	LengthValidation
	LimitTextArea	
	MembershipNumberValidation
	MinLengthValidation
	NewWindow
	PreventEnterKeySubmit
	RadioGroupValidation
	SelectValidation
	StateValidation
	SubmitEnter
	SubmitFormOnlyOnce
	ToggleDisplay
	Trim
	WordLimiterCounter
	WordLimitValidation
*/
var submitCount = 0;
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");

function CharacterLimiterCounter(field, maxlimit, cntfield) {
/*limits character count and shows dynamic count of characters as user is typing them in the text area*/
	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;
}

function CheckboxArrayValidation(entered, alertText) {
/*shows a message (alertText) and returns false if no items in checkbox have been checked*/
	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;
}

function CheckboxValidation(entered, alertText) {
/*shows a message (alertText) and returns false if checkbox has not been checked*/
	var strValue = entered.checked;
	if (strValue == false) 
	{
		if (alertText)
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}

function ConcatDateFields(fldMonth, fldDay, fldYear) {
/*takes values from month, day and year fields and concatenates them into MM/DD/YY(YY) format*/
	var strDate = fldMonth.options[fldMonth.selectedIndex].value + "/" + fldDay.options[fldDay.selectedIndex].value + "/" + fldYear.options[fldYear.selectedIndex].value;
	return strDate;
}

function CreateAMailTo(user, domain, suffix){
/* creates mailto link and text for specified user@domain.suffix */
	document.write('<a href="' + 'mailto:' + user + '@' + domain + '.' + suffix + '">' + user + '@' + domain + '.' + suffix + '</a>');
}

function CreateSubmitDataString(theForm) {
/*for the passed form returns a string of all form inputs in the format [field name]: [field value][new line]*/
	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;
}

function DateValidation(inputDate, inputMonth, inputYear, alertText) {
/*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...)*/
	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;
}	

function DigitValidation(entered, lenMin, lenMax, alertText) {
/*verifies numeric value was entered and that it's length is between the passed min and max*/
	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;
}

function EmailAddressValidation(entered, alertText) {
/*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*/
	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;
	}
}

function EmptyValidation(entered, alertText) {
/*shows a message (alertText) and returns false if no data has been entered in the input text box (entered)*/
	var strValue = Trim(entered.value);
	if (strValue == null || strValue == "" || strValue == "undefined")
	{
		if (alertText)
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}

function FutureDateValidation(inputDate, alertText) {
/*Accepts string in date format ("mm/dd/yyyy") and verifies that date is the current day OR occurs in the future.*/
	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;
}

function GoToURL(form) {
/*Redirects the main frame in a frameset to page or anchor specified in value property 
of select or option item named "dest"*/
        var myindex=form.dest.selectedIndex
        window.open(form.dest.options[myindex].value, target="_self"); //change these both to "yes" to get the toolbar
}

function IsValidDate(dateStr) {
/*Checks for the following valid date formats: MM/DD/YYYY OR MM-DD-YYYY 
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
}

function LengthValidation(entered, lenMin, lenMax, alertText) {
/*shows a message (alertText) and returns false if the length of the input text (entered) is too short or too long*/
	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;
}

function LimitTextArea(field, maxlimit) {
/*limits number of characters entered into textarea input. once character count exceeds limit, characters 
are trimmed as they are typed*/
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
}

function MembershipNumberValidation(entered, alertText) {
/*shows a message (alertText) and returns false if the membership number (entered) does not meet the 
criteria set up in the function*/
	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;
}

function MinLengthValidation(entered, lenMin, alertText) {
/*shows a message (alertText) and returns false if the length of the input text (entered) is too short*/
	var strValue = Trim(entered.value);
	if (strValue.length < lenMin )
	{
		if (alertText) 
		{
			alert(alertText);
		} 
		entered.focus();
		entered.select();
		return false;
	}
	else 
		return true;
}

function NewWindow(URL, name, specs) {
/*opens a new browser window with the specified url, window name and other parameter specs*/
	var anon_win = window.open(URL, name, specs);
}

function PreventEnterKeySubmit() {
/*used to prevent enter key in onkeypress events.  used to prevent forms from being submitted, 
bypassing form validation*/
  return !(window.event && window.event.keyCode == 13); 
}

function RadioGroupValidation(groupName, alertText) {
/*shows a message (alertText) and returns false if no selection has been made between the items 
in the radio group (groupName)*/
	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;
}

function SelectValidation(entered, alertText) {
/*shows a message (alertText) and returns false if no data has been selected in the dropdown list (entered)*/
	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;
	}
}

function StateValidation(countryField, stateField) {
/* 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. */	
	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;
	}
}

function SubmitEnter(myfield,e) {
/*used in onkeypress event of form inputs to allow enter key to kick off form submission process.  works with ie and netscape.*/
	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;
}

function 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*/
   if (submitCount == 0)
   {
      submitCount++;
      return true;
   }
   else 
   {
      alert("This form has already been submitted.  Thanks!");
      return false;
   }
}

function ToggleDiv(divID, divState) 
/* Sets the visible state [divState = 0 (hide) or 1 (show)] of the div corresponding to the id passed in via divID */
{
	divState == 1 ? divDisplay = "block" : divDisplay = "none";
	document.getElementById(divID).style.display=divDisplay;
	//alert(divID + ': ' + document.getElementById(divID).style.display);
}

function Trim(sData) {
/*Trims leading/trailing spaces and tabs*/
	var sTrimmed = String(sData);
	sTrimmed = sTrimmed.replace(/(^[ |\t]+)|([ |\t]+$)/g, '');
	return sTrimmed;
}

function WordLimiterCounter(field, wordlimit, cntfield) {
/*1. Counts and displays (in cntfield) number of words entered in field
  2. Trims field to wordlimit if word count exceeds that number */
    var text=field.value + " ";
    if(wordlimit>0)
    {
        var iwhitespace = /^[^A-Za-z0-9]+/gi; // remove initial whitespace
        var left_trimmedStr = text.replace(iwhitespace, "");
        var na = rExp = /[^A-Za-z0-9]+/gi; // non alphanumeric characters
        var cleanedStr = left_trimmedStr.replace(na, " ");
        var splitString = cleanedStr.split(" "); 
		var word_count = splitString.length -1;
        cntfield.value=wordlimit-word_count;
		/*if (word_count > wordlimit)
		{
			var limitedText = splitString[0];
			for (var i = 1; i < wordlimit; i++)
				limitedText += " " + splitString[i];
			field.value = limitedText;
		}*/
    }
}

function WordLimitValidation(entered, wordsRemaining, alertText) {
/*shows a message (alertText) and returns false if wordsRemaining in field (entered) is less than zero */
	if (wordsRemaining < 0)
	{
		if (alertText){alert(alertText);}
		entered.focus();
		entered.select();
		return false;
	}
	else
		return true;
}