// ############################################################################
// ##
// ##  CUSTOM WEBSITE FUNCTIONS
// ##  (i.e. not standard white site functions)
// ##
// ############################################################################

// Put custom functions for your website here.
if ( !strRegionFormName ) {
	var strRegionFormName = "";
}

function SetRegionFormName(RegionFormName)
{
	strRegionFormName = RegionFormName;
}

// ======================================================================
// START Functions to display and filter State, Type & Region drop down lists
// ======================================================================
//construct state drop down list upon loading page
function BuildStateDropDown(varStateSelection)
{
	for(var i = 0; i < arrRegions.length; i++)
	{
		if(!SearchArray(arrStates, arrRegions[i][0]))
		{
			arrStates = arrStates.concat(new Array(arrRegions[i][0])); 
		}	
	}
	document.write("<input type=\"hidden\" name=\"statevalue\" value=\"\"><select name=\"state\" onChange=\"SelectState(document.forms[strRegionFormName].elements['state'].options[document.forms[strRegionFormName].elements['state'].selectedIndex].text,'');\">");
	if ( arrStates.length > 1 ) {		
		document.write("<option value=\"\">All states</option>");
	}
	for(var i = 0; i < arrStates.length; i++)
	{
		if(varStateSelection == arrStates[i])
		{
			document.write("<option value=\""+FindStateRegionIDS(arrStates[i])+"\" selected>"+arrStates[i]+"</option>");
		}
		else
		{
			document.write("<option value=\""+FindStateRegionIDS(arrStates[i])+"\">"+arrStates[i]+"</option>");
		}
	}
	document.write("</select>");
}

//construct region type drop down list
function BuildRegionTypeDropDown()
{
	document.write("<input type=\"hidden\" name=\"regiontypevalue\" value=\"\"><select name=\"regiontype\" onChange=\"SelectType(document.forms[strRegionFormName].elements['state'].options[document.forms[strRegionFormName].elements['state'].selectedIndex].text, document.forms[strRegionFormName].elements['regiontype'].options[document.forms[strRegionFormName].elements['regiontype'].selectedIndex].text,'');\");\"><option value=\"\">All areas</option>");
	document.write("</select>");
}

//construct region name drop down list
function BuildRegionNamesDropDown()
{
	document.write("<input type=\"hidden\" name=\"regionsvalue\" value=\"\"><select name=\"regions\" onChange=\"SetRegionValue(document.forms[strRegionFormName].elements['regions'].options[document.forms[strRegionFormName].elements['regions'].selectedIndex].value);\"><option value=\"\">All regions</option>");
	document.write("</select>");
}

// modify type and region drop down lists based on a state selection
function SelectState(strState, strSelectedType)
{
	document.forms[strRegionFormName].elements['statevalue'].value = strState;
	if ( strState ) {
		varQS = "statevalue=" + strState;
	}
	
	//build type array
	arrRegionType  = new Array();
	for(var i = 0; i < arrRegions.length; i++)
	{
		if(arrRegions[i][0] == strState)
		{
			if(!SearchArray(arrRegionType, arrRegions[i][1]))
			{
				arrRegionType = arrRegionType.concat(new Array(arrRegions[i][1])); 
			}	
		}
	}
	var rtoffset = 0;
	document.forms[strRegionFormName].elements['regiontype'].options.length = 1;
	document.forms[strRegionFormName].elements['regions'].options.length = 1;
	document.forms[strRegionFormName].elements['regiontypevalue'].value="";
	document.forms[strRegionFormName].elements['regionsvalue'].value="";
	SelectType('', '', '');
	SetRegionValue('');
	// clear type and region drop down lists
	//DeleteOptions(document.forms[strRegionFormName].elements['regiontype']);
	//DeleteOptions(document.forms[strRegionFormName].elements['regiontype']);
	//DeleteOptions(document.forms[strRegionFormName].elements['regiontype']);
	//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
	//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
	//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
	//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
//alert("SelectType Deleted and Area Type Regions");
	if ( arrRegionType.length > 1 ) {
		document.forms[strRegionFormName].elements['regiontype'].options[0] = new Option('All areas', '');
		document.forms[strRegionFormName].elements['regions'].options[0] = new Option('All regions', '');
		rtoffset = 1;
	} else if ( arrRegionType.length == 1 ) {
		SelectType(strState, arrRegionType[0]);
	}
	// populate drop down based on contents of array
	for(var i = 0; i < arrRegionType.length; i++)
	{
		insertOptionAt(document.forms[strRegionFormName].elements['regiontype'], new Option(arrRegionType[i], FindTypeRegionIDS(strState, arrRegionType[i])), i+rtoffset);
		if(strSelectedType == arrRegionType[i])
		{
			document.forms[strRegionFormName].elements['regiontype'].options[ i+rtoffset].selected = true;
		}
	}
}

// modify region drop down list based on selection from type
function SelectType(strState, strType, strSelectedRegion)
{
	if (!strType)
	{
	// When there's only Metro regions, or no region types are given, some of the region types are not being displayed
	}
	else
	{
		document.forms[strRegionFormName].elements['regiontypevalue'].value = strType;
		if ( strType ) {
			varQS += "&regiontypevalue=" + strType;
		}
		
		// populate region array
		arrRegionNames = new Array();
		for(var i = 0; i < arrRegions.length; i++)
		{
			if(arrRegions[i][0] == strState && arrRegions[i][1] == strType)
			{
				if(!SearchArray(arrRegionNames, arrRegions[i][2]))
				{
					arrRegionNames = arrRegionNames.concat(new Array(arrRegions[i][2])); 
				}	
			}
		}
		i=null;
		// clear existing drop down list
		document.forms[strRegionFormName].elements['regions'].options.length = 1;
		document.forms[strRegionFormName].elements['regionsvalue'].value="";
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
//alert("All Regions Deleted Part 1");
		var roffset = 0;
		if ( arrRegionNames.length > 1 ) 
		{
			document.forms[strRegionFormName].elements['regions'].options[0] = new Option('All regions', '');
			roffset = 1;
		}
		
		// populate drop down based on contents of array
		for(var i = 0; i < arrRegionNames.length; i++)
		{
			var RegionID = FindRegionID(strState, strType, arrRegionNames[i]);
			insertOptionAt(document.forms[strRegionFormName].elements['regions'], new Option(arrRegionNames[i], RegionID), i+roffset);
//alert("Inserting Region Name: "+arrRegionNames[i]);
			if(strSelectedRegion == RegionID)
			{
				document.forms[strRegionFormName].elements['regions'].options[ i+roffset].selected = true;
			}
		} i=null;
	}
if ( strType == "All areas" )
	{
//alert("strType = all areas part 2"); 

//This is really being a bugga, and basically you need to run the DeleteOptions function many times to actually clear the options out - it seems that by populating it each time the Area Type is changed, some Options just don't really ever leave when they should?
		document.forms[strRegionFormName].elements['regions'].options.length = 1;
		document.forms[strRegionFormName].elements['regionsvalue'].value="";
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		//document.forms[strRegionFormName].elements['regions'].options[0] = new Option('All regions', '');
			roffset = 1;
	}
/*if ( strType == "Inactive" )
	{
//alert("strType = Inactive!"); 

//This is really being a bugga, and basically you need to run the DeleteOptions function many times to actually clear the options out - it seems that by populating it each time the Area Type is changed, some Options just don't really ever leave when they should?
		DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		DeleteOptions(document.forms[strRegionFormName].elements['regions']);
		document.forms[strRegionFormName].elements['regions'].options[0] = new Option('Inactive', 'Inactive');
			roffset = 1;
	}*/
}

function SetRegionValue(strRegionValue)
{
	document.forms[strRegionFormName].elements['regionsvalue'].value = strRegionValue;
//alert("strRegionValue="+strRegionValue);
//	if ( strRegionValue ) {
//		varQS += "&regionsvalue=" + strRegionValue;
//	}
//alert("part 1a");	
}

//clear the Club Search Form (search_club_inc.asp)
function ClearClubSearchForm()
{
	document.searchclubform.ClubName.value="";
	document.searchclubform.state.options.selectedIndex=0;
	document.searchclubform.Sport.options.selectedIndex=0;
	document.searchclubform.regiontype.options.selectedIndex=0; 
	document.searchclubform.Level.options.selectedIndex=0; 
	document.searchclubform.regions.options.selectedIndex=0; 
	document.searchclubform.FromLevelDate.value="";
	document.searchclubform.FromLevelDate.value="";
	document.searchclubform.ToLevelDate.value="";
	document.searchclubform.Overdue.options.selectedIndex=0;
	document.searchclubform.FromNextLevelDate.value="";
	document.searchclubform.ToNextLevelDate.value="";
	document.searchclubform.ResultsPerPage.options.selectedIndex=0;
	return false;
}

//clear the Club Listing Report Form (club_listing_report.asp
function ClearClubListingReportForm()
{
	document.searchclubform.Sport.options.selectedIndex=0;
	document.searchclubform.state.options.selectedIndex=0;
	document.searchclubform.league.value="";
	document.searchclubform.regiontype.options.selectedIndex=0; 
	document.searchclubform.Level.options.selectedIndex=0; 
	document.searchclubform.regions.options.selectedIndex=0; 
	document.searchclubform.lgaID.value="";
	document.searchclubform.lgaText.value="";
	document.searchclubform.from_level.value="";
	document.searchclubform.to_level.value="";
	document.searchclubform.from_reg.value="";
	document.searchclubform.to_reg.value="";
	document.searchclubform.from_part.value="";
	document.searchclubform.to_part.value="";
	document.searchclubform.from_with.value="";
	document.searchclubform.to_with.value="";
	document.searchclubform.from_next.value="";
	document.searchclubform.to_next.value="";
	document.searchclubform.ResultsPerPage.options.selectedIndex=0;
	return false;
}


//clear the Select the LGA region when adding a club
function SelectLGA(strLGAID, strRegionID)
{
	document.forms['addclubform'].elements['Field042'].value = strLGAID;
	document.forms['addclubform'].elements['Field043'].value = strRegionID;
	document.forms['addclubform'].submit();
}

function SelectLGAEdit(strLGAID, strRegionID)
{
	document.forms['editclubform'].elements['Field042'].value = strLGAID;
	document.forms['editclubform'].elements['Field043'].value = strRegionID;
	document.forms['editclubform'].submit();
}

// insert new option at the end of list
function insertOptionAt (select, option, index ) {
    select.options[index] = option;
}

// remove all options for a select list
function DeleteOptions(varDropDownList)
{
    for (var i = 0; i < varDropDownList.options.length;  i++)
	{
		varDropDownList.options[i] = null;
	}
}

// return a comma separated list of all regionids for a particular state
function FindStateRegionIDS(varState)
{
	var strStateRegionIDs = '';
	var intCount = 0
	for(var i = 0; i < arrRegions.length; i++)
	{
		if(arrRegions[i][0] == varState) 
		{
			if(intCount > 0)
			{
				strStateRegionIDs += ','
			}
			strStateRegionIDs += arrRegions[i][3];
			intCount++;
		}
	}	
	return strStateRegionIDs;
}

// return a comma separated list of all regionids for a particular state and type value
function FindTypeRegionIDS(varState, varType)
{
	var strTypeRegionIDs = '';
	var intCount = 0
	for(var i = 0; i < arrRegions.length; i++)
	{
		if(arrRegions[i][0] == varState && arrRegions[i][1] == varType) 
		{
			if(intCount > 0)
			{
				strTypeRegionIDs += ', '
			}
			strTypeRegionIDs += arrRegions[i][3];
			intCount++;
		}
	}	
	return strTypeRegionIDs;
}

// locate the regionid for a particular state, type and region match
function FindRegionID(varState, varType, varRegionName)
{
	//alert("FindRegionID varState="+varState+" varType="+varType+" varRegionName="+varRegionName);
	var strRegionID = '';
	var intCount = 0
	for(var i = 0; i < arrRegions.length; i++)
	{
		if(arrRegions[i][0] == varState && arrRegions[i][1] == varType && arrRegions[i][2] == varRegionName) 
		{
			strRegionID = arrRegions[i][3];
		}
	}	
	//alert("FindRegionID strRegionID="+strRegionID);
	return strRegionID;
}

// search through an array to determine if value already exists
function SearchArray(arrTemp, strSearchValue)
{
	var isFound = false;
	for(var i = 0; i < arrTemp.length; i++)
	{
		if(arrTemp[i] == strSearchValue)
		{
			isFound = true;
			break;
		}
	}	
	return isFound;
}

// ====================================================================
// END Functions to display and filter State, Type & Region drop down lists
// ====================================================================

function OpenLocationLookup(strCityField, strPostField, strStateField, strForm, strWidth, strHeight)
{
	var strMessage = '';
	var strCity = document.forms[strForm].elements[strCityField].value
	var strPostcode = document.forms[strForm].elements[strPostField].value
	var strState = document.forms[strForm].elements[strStateField].options[document.forms[strForm].elements[strStateField].selectedIndex].value;
	
	if(strState == '')
	{
		strMessage = "State must be selected before perfoming a location lookup";
	}
	else if(strPostcode == '' && strCity == '')
	{
		strMessage = "Either City or Postcode must be entered before perfoming a location lookup";
	}
	
	if(strMessage == '')
	{
		if ( strPostField == "Field018" && strForm == "addclubform" ) {
			// to add "inactive" location option for add club Venue
			Popup('/location_lookup.asp?venue=1&form='+strForm+'&cityfield='+strCityField+'&postfield='+strPostField+'&statefield='+strStateField+'&cityvalue='+strCity+'&postvalue='+strPostcode+'&statevalue='+strState,strWidth,strHeight,'location_lookup','yes','yes','yes','yes','yes')
		} else {
			Popup('/location_lookup.asp?form='+strForm+'&cityfield='+strCityField+'&postfield='+strPostField+'&statefield='+strStateField+'&cityvalue='+strCity+'&postvalue='+strPostcode+'&statevalue='+strState,strWidth,strHeight,'location_lookup','yes','yes','yes','yes','yes')
		}
		return false;
	}
	else
	{
		alert(strMessage);
	}
	return false;
}


function ValidateField(strFormName, strFieldName, strValidationRule)
{
	// validate checkbox
	if(strValidationRule == 'Checked')
	{
		var isChecked = true;
		if(!document.forms[strFormName].elements[strFieldName].checked)
		{
			isChecked = false;
		}
		return isChecked;
	}
	if(strValidationRule == 'CheckedAll')
	{
		var isChecked = true;
		for(var i=0; i<document.forms[strFormName].elements[strFieldName].length; i++)
		{
			if( !document.forms[strFormName].elements[strFieldName][i].checked)
			{
				isChecked = false;
			}
		}
		return isChecked;
	}
	if(strValidationRule == 'CheckedAny')
	{
		var isChecked = false;
		for(var i=0; i<document.forms[strFormName].elements[strFieldName].length; i++)
		{
			if(document.forms[strFormName].elements[strFieldName][i].checked)
			{
				isChecked = true;
			}
		}
		return isChecked;
	}
	if(strValidationRule == 'Radio')
	{
		var isSelected = false;
		for(var i=0; i<document.forms[strFormName].elements[strFieldName].length; i++)
		{
			if(document.forms[strFormName].elements[strFieldName][i].checked)
			{
				isSelected = true;
			}
		}
		return isSelected;
	}
	// validate number (e.g. integer)
	if(strValidationRule == "Number")
	{
		if(Trim(document.forms[strFormName].elements[strFieldName].value) == '' || isNaN(Trim(document.forms[strFormName].elements[strFieldName].value)) || (Trim(document.forms[strFormName].elements[strFieldName].value) % 1))
		{
			return false;		
		}  
	}
	// validate decimal (e.g. money or percentage value)
	if(strValidationRule == "Decimal")
	{
		if(Trim(document.forms[strFormName].elements[strFieldName].value) == '' || isNaN(Trim(document.forms[strFormName].elements[strFieldName].value)) )
		{
			return false;		
		}  
	}
	// validate required field
	if(strValidationRule == "Required")
	{
		if(Trim(document.forms[strFormName].elements[strFieldName].value) == '')
		{
			return false;		
		}  
	}
	// validate drop down list
	if(strValidationRule == "Menuselect")
	{
		if(document.forms[strFormName].elements[strFieldName].selectedIndex == "0")
		{
			return false;		
		}  
	}	
	// return true is validation passes, otherwise false is returned
	return true;
}

// remove trailing white space characters from a string
function Trim(strValue)
{
   if(strValue != '')
   { 
      strValue = strValue.replace(/^\s+/, '').replace(/\s+$/, '');
   }   
   return strValue;
}


// ############################################################################
// ##
// ##  STANDARD WHITE SITE FUNCTIONS
// ##
// ############################################################################

// ####################################
// Navigation
// ####################################

// ====================
// Function:    NavPullDown
//
// Purpose:     Go to a URL that is selected from a form a pull-down form field
//
// Input:       strFormName - The ID of the form being used to select naviation
//              strFieldName - The ID of the field with URL select options
//
// Output:      Navigates to selected URL.
//
// Assumptions: -
//
// History:     DDSN created back in the Distant Past
// ====================
function NavFormSelect(strFormName,strFieldName)
{
	intSelected = document[strFormName].elements[strFieldName].options.selectedIndex;
	strURL = document[strFormName].elements[strFieldName].options[intSelected].value;
	document[strFormName].elements[strFieldName].options.selectedIndex = 0;
	if (strURL != "")
	{
		location.href = strURL;
	}
}

// ####################################
// Windows & Alerts
// ####################################

// ====================
// Function:    Popup
//
// Purpose:     Open a popup window with a series of option settings.
//
// Input:       strPage - The URL of the page to open in the popup window.
//              intWidth - The window width in pixels 
//              intHeight - The window height in pixels
//              strID - The ID of the popup window. (This is important if the
//                window may be called on by other functions or if there are
//                multiple popup windows in a site.)
//              strScrollbars - Switch visible scrollbars on/off ("yes"/"no")
//              strLocation - Switch visible location bar on/off ("yes"/"no")
//              strToolbar - Switch visible toolbar on/off ("yes"/"no")
//              strStatus - Switch visible status bar on/off ("yes"/"no")
//              strResizable - Window is resizable or not ("yes"/"no")
//
// Output:      Window opens containing the specified URL.
//
// Assumptions: -
//
// History:     DDSN created back in the Distant Past
// ====================
function Popup(strPage,intWidth,intHeight,strID,strScrollbars,strLocation,strToolbar,strStatus,strResizable)
{
	if (!strPage)
	{
		strPage = "/";
	}
	if (!intWidth)
	{
		intWidth = 500;
	}
	if (!intHeight)
	{
		intHeight = 320;
	}
	if (!strID)
	{
		strID = "PopupWindow";
	}
	if (!strScrollbars)
	{
		strScrollbars = "yes";
	}
	if (!strLocation)
	{
		strLocation = "no";
	}
	if (!strToolbar)
	{
		strToolbar = "no";
	}
	if (!strStatus)
	{
		strStatus = "no";
	}
	if (!strResizable)
	{
		strResizable = "yes";
	}
	//if (isLoaded == 0)
	//{
	//	location.reload();
	//}
	idPopup = window.open(strPage,strID,"width="+intWidth+",height="+intHeight+",scrollbars="+strScrollbars+",location="+strLocation+",toolbar="+strToolbar+",status="+strStatus+",resizable="+strResizable+",menubar=yes");

	if (window.focus)
	{
		idPopup.focus();
	}
	return false;
}

// ====================
// Function:    PopdownLink
//
// Purpose:     Open a link in a popup window in a specified main window and
//              close the popup window. If the specified link window does not
//              exist it is created. If no window is specified the link is
//              targeted to the original opener of the popup window.
//
// Input:       strURL - The URL of the page to open
//              strWindowID - The ID of the window in which to open the link
//
// Output:      Navigates to selected URL in selected window and closes current
//              window.
//
// Assumptions: -
//
// History:     DDSN created back in the Distant Past
//              2004 Multiple window targets added. (Previously could only
//                   target the opener.)
// ====================
function PopdownLink(strURL,strWindowID)
{
	if (!strWindowID)
{
		top.opener.location.href = strURL;
}
	else
{
		if (strWindowID.location)
	{
			strWindowID.location.href = strURL;
	}
		else
	{
			window.open(strURL,strWindowID);
	}
}
	top.close();
}

// ====================
// Function:    RequireKeywords
//
// Purpose:     Checks any search form to make sure keywords are entered before
//              the form can be submitted. 
//
// Input:       strFormName - The ID of the form with the keywords field in it
//              strFieldName - The ID of the keywords field within the form 
//
// Output:      Give an error if no keywords are presented.
//
// Assumptions: -
//
// History:     20040109 RW Created to replace local code in site templates.
// ====================
function RequireKeywords(strFormID,strFieldName)
{
	if (document.forms[strFormID].elements[strFieldName].value.length <= 3)
	{
		alert("Please alter your requested keyword(s) in the search form.\nThe search phrase must be 3 characters or more in length.")
		return false;
	}
}

// ====================
// Function:    CS
//
// Purpose:     Display a "coming soon" message for sections of a website that
//              have not been created yet. This function is sometimes used in
//              development to make links active before a site is finished.
//
//              Note: This is an evil funciton, it should not be used! It
//              encourages bad development habits.
//
// Input:       -
//
// Output:      Show a "coming soon" message.
//
// Assumptions: -
//
// History:     DDSN created back in the Distant Past
// ====================
function CS()
{
	alert("That function is coming soon.");
}

// ####################################
// Image Manipulation
// ####################################

// ====================
// Function:    ImageSwap
//
// Purpose:     Swap any image to another.
//
// Input:       strImageID - ID of the image being swapped
//              strNewImageSrc - Source of the new image being loaded
//
// Output:      Swaps images.
//
// Assumptions: Images with all specified IDs exist and are pre-loaded.
//
// History:     DDSN created back in the Distant Past
// ====================
function ImageSwap(strImageID,strNewImageSrc)
{
	if (document.images)
	{
		document.images[strImageID].src = eval(strNewImageSrc+".src");
	}
}

// ====================
// Function:    ImageSwapFX
//
// Purpose:     Swap any image to another using an optional fade effect. Can
//              also be called with the transition effect disabled, i.e. just
//              swap the images.
//
// Input:       strImageID - ID of the image being swapped
//              strNewImageSrc - Source of the new image being loaded
//              blnDisableTrans - Switch the transition off or on (1/0)
//
// Output:      Swaps images with optional fade effect.
//
// Assumptions: - Images with all specified IDs exist and are pre-loaded.
//              - Requires fading transition style to be set first on image tag
//              - Only works for IE5.5+ but falls back nicely
//              - Javascript Globals: blnToggleTrans
//
// History:     2003 DDSN Created
//              2004 Updated with more standard naming structures
// ====================
function ImageSwapFX(strImageID,strNewImageSrc,blnDisableTrans)
{
	if (blnDisableTrans || !document.images[strImageID].filters || blnIE50)
	{
		if (document.images)
		{
			document.images[strImageID].src = eval(strNewImageSrc+".src");
		}
	}
	else
	{
		// After setting Apply, changes to the object are not displayed
		// until Play is called.
		document.images[strImageID].filters[0].Apply();

		if (blnToggleTrans)
		{
			blnToggleTrans = 0;
			document.images[strImageID].src = eval(strNewImageSrc+".src");
		}
		else
		{
			blnToggleTrans = 1;
			document.images[strImageID].src = eval(strNewImageSrc+".src");
		}
		document.images[strImageID].filters[0].Play();
	}
}

// ####################################
// Layer Manipulation
// ####################################

// ====================
// Function:    LayerVisibility
//
// Purpose:     Turn visibility of any layer on or off.
//
// Input:       strLayerID - ID of the layer being altered
//              strState = "visible" or "hidden"
//
// Output:      Turns specified layer on or off.
//
// Assumptions: Specified layer exists in document hierarchy.
//
// History:     DDSN created back in the Distant Past
// ====================
function LayerVisibility(strLayerID,strState)
{
	if (blnNS4)
	{
		if (document.layers[strLayerID])
		{
			document.layers[strLayerID].visibility = strState;
		}
	}
	else if (blnDOM)
	{
		if (document.getElementById(strLayerID))
		{
			document.getElementById(strLayerID).style.visibility = strState;
		}
	}
	else if (blnIE)
	{
		if (document.all[strLayerID])
		{
			document.all[strLayerID].style.visibility = strState;
		}
	}
}

// ####################################
// Printing
// ####################################

// ====================
// Function:    LoadVBPrinter
//
// Purpose:     Load Visual Basic printing commands for VB enabled browsers.
//
// Input:       -
//
// Output:      Loads (writes out) visual basic printing functions.
//
// Assumptions: Javascript Globals: blnIE, blnCanPrint, blnMac
//
// History:     DDSN created back in the Distant Past
// ====================
//function LoadVBPrinter()
//{
	if (blnIE && !blnCanPrint && !blnMac) with (document)
	{
		writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
		writeln('<' + 'SCRIPT LANGUAGE="VBScript">');
		writeln('Sub window_onunload');
		writeln('    On Error Resume Next');
		writeln('    Set WB = nothing');
		writeln('End Sub');
		writeln('Sub vbPrintPage');
		writeln('    OLECMDID_PRINT = 6');
		writeln('    OLECMDEXECOPT_DONTPROMPTUSER = 2');
		writeln('    OLECMDEXECOPT_PROMPTUSER = 1');
		writeln('    On Error Resume Next');
		writeln('    WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
		writeln('End Sub');
		writeln('<' + '/SCRIPT>');
	}
//}

// ====================
// Function:    PrintPage
//
// Purpose:     Opens the print dialog window or shows a fallback message for
//              unsupported browsers
//
// Input:       -
//
// Output:      Opens the print dialog window or shows a fallback message for
//              unsupported browsers.
//
// Assumptions: Javascript Globals: blnCanPrint, blnIE, blnMac
//
// History:     DDSN created back in the Distant Past
// ====================
function PrintPage()
{
	if (blnCanPrint)
	{
		window.print();
	}
	else if (blnIE && !blnMac)
	{
		vbPrintPage();
	}
	else
	{
		alert("Your web browser does not appear to support the automatic\nPrint function. To print this page, please select the \"Print\"\noption from the \"File\" menu of your web browser.");
	}
}


// Load Visual Basic printing commands for VB enabled browsers
//LoadVBPrinter()

// ####################################
// Fun Stuff / Easter Eggs
// ####################################

// Take a HTML string and lay it out nicely. This is not intended to be an
// advanced function, but it does make unreadable HTML code created by
// various HTML editors much easier to use.
function MakePrettyHTML(objHTML)
{
	allHTML = objHTML;

	// add quotes around tag attributes
	allHTML = allHTML.replace(/</g," <");
	var arrInp = allHTML.split(/[<>]{1}/);
	var xx = "";
	for(i=0; i<arrInp.length; i++)
	{
		if ( ( i % 2) == 1)
		{
			x0 = "<" + arrInp[i].replace(/(\s\w+\s*=\s*)([^\"][^\s\>]*)/g, "$1\"$2\"") + ">";
		}
		else
		{
			x0 = arrInp[i];
		}
		xx += x0;
	}
	allHTML = xx;
	allHTML = allHTML.replace(/ </g,"<");
	
	allHTML = allHTML.replace(/<img/gi,"||<img");
	allHTML = allHTML.replace(/<br>/gi,"||<br>");
	allHTML = allHTML.replace(/<\/a>/gi,"||</a>");
	allHTML = allHTML.replace(/<em>/gi,"||<em>");
	allHTML = allHTML.replace(/<strong>/gi,"||<strong>");
	allHTML = allHTML.replace(/<b>/gi,"||<b>");
	allHTML = allHTML.replace(/<i>/gi,"||<i>");
	allHTML = allHTML.replace(/<\/td>/gi,"||</td>");
	allHTML = allHTML.replace(/<\/li>/gi,"||</li>");

	allHTML = allHTML.replace(/></gi,">\n<");

	allHTML = allHTML.replace(/\|\|<img/gi,"<img");
	allHTML = allHTML.replace(/\|\|<br>/gi,"<br>");
	allHTML = allHTML.replace(/\|\|<\/a>/gi,"</a>");
	allHTML = allHTML.replace(/\|\|<em>/gi,"<em>");
	allHTML = allHTML.replace(/\|\|<strong>/gi,"<strong>");
	allHTML = allHTML.replace(/\|\|<b>/gi,"<b>");
	allHTML = allHTML.replace(/\|\|<i>/gi,"<i>");
	allHTML = allHTML.replace(/\|\|<\/td>/gi,"</td>");
	allHTML = allHTML.replace(/\|\|<\/li>/gi,"</li>");

	allHTML = allHTML.replace(/<p/gi,"<p");
	allHTML = allHTML.replace(/<\/p>/gi,"</p>");
	allHTML = allHTML.replace(/ <\/p>/gi,"</p>");
	allHTML = allHTML.replace(/<h1/gi,"<h1");
	allHTML = allHTML.replace(/<h2/gi,"<h2");
	allHTML = allHTML.replace(/<h3/gi,"<h3");
	allHTML = allHTML.replace(/<h4/gi,"<h4");
	allHTML = allHTML.replace(/<h5/gi,"<h5");
	allHTML = allHTML.replace(/<h6/gi,"<h6");
	allHTML = allHTML.replace(/<ul/gi,"<ul");
	allHTML = allHTML.replace(/<ol/gi,"<ol");
	allHTML = allHTML.replace(/<blockquote/gi,"<blockquote");
	allHTML = allHTML.replace(/<img/gi,"<img");
	allHTML = allHTML.replace(/<font/gi,"<font");
	allHTML = allHTML.replace(/<\/font>/gi,"</font>");
	allHTML = allHTML.replace(/<a /gi,"<a ");
	allHTML = allHTML.replace(/<strong/gi,"<strong");
	allHTML = allHTML.replace(/<\/strong>/gi,"</strong>");
	allHTML = allHTML.replace(/<b/gi,"<b");
	allHTML = allHTML.replace(/<\/b>/gi,"</b>");
	allHTML = allHTML.replace(/<i/gi,"<i");
	allHTML = allHTML.replace(/<\/i>/gi,"</i>");
	allHTML = allHTML.replace(/<em/gi,"<em");
	allHTML = allHTML.replace(/<\/em>/gi,"</em>");
	allHTML = allHTML.replace(/<br>/gi,"<br>\n");
	allHTML = allHTML.replace(/<\/h1>/gi,"</h1>\n");
	allHTML = allHTML.replace(/<\/h2>/gi,"</h2>\n");
	allHTML = allHTML.replace(/<\/h3>/gi,"</h3>\n");
	allHTML = allHTML.replace(/<\/h4>/gi,"</h4>\n");
	allHTML = allHTML.replace(/<\/h5>/gi,"</h5>\n");
	allHTML = allHTML.replace(/<\/h6>/gi,"</h6>\n");
	allHTML = allHTML.replace(/<\/p>/gi,"</p>\n");
	allHTML = allHTML.replace(/<table(.*)>/gi,"<table$1>");
	allHTML = allHTML.replace(/<tbody/gi,"  <tbody");
	allHTML = allHTML.replace(/<tr/gi,"  <tr");
	allHTML = allHTML.replace(/<td/gi,"    <td");
	allHTML = allHTML.replace(/<\/tr>/gi,"  </tr>");
	allHTML = allHTML.replace(/<\/table>/gi,"</table>");
	allHTML = allHTML.replace(/<\/tbody>/gi,"  </tbody>");
	allHTML = allHTML.replace(/<li>/gi,"  <li> ");
	allHTML = allHTML.replace(/<\/li>/gi,"</li>\n");
	allHTML = allHTML.replace(/<\/ul>/gi,"</ul>\n");
	allHTML = allHTML.replace(/<\/ol>/gi,"</ol>\n");
	allHTML = allHTML.replace(/<\/blockquote>/gi,"</blockquote>\n");

	return allHTML;
}

// ====================
// Function:    ExportElement
//
// Purpose:     	export a piece of html as a "excell" file i.e. start downloading a file with ".xls" extension and html content. It is assumed that export_table.asp 
//			file exists in your document root. This file is just grab value from Request("ExportTableBody") variable and add corresponding header.
//
// Input:       	- DOM id of any html element
//
// Output:      	If given "id" and "export_table.asp" exist than standard "download" dialog should appear on your screen.
//
// History:     	20050707 GR created
// ====================
function ExportElement( elementId ) {
	var el = document.getElementById(elementId);
	if ( el ) {
		var body = el.innerHTML;
		if ( ! document.exportElement ) {
			el.innerHTML = '<form name="exportElement" method="post" action="/export_table.asp"><input type="hidden" name="ExportTableBody"></form>' + body;
		}
		document.exportElement.ExportTableBody.value = body;
		document.exportElement.submit();
	}
}

// only allow numric values to be entered into a field
function NumericValuesOnly(thisField)
{
	var strFieldValue = thisField.value;
	
	if(isNaN(strFieldValue))
	{
		if(strFieldValue.length > 1)
		{
			strFieldValue = strFieldValue.substring(0, strFieldValue.length-1);
		}
		else
		{
			strFieldValue = "";
		}
	}
	
	strFieldValue = strFieldValue.replace(" ", "");
	
	thisField.value = strFieldValue;
}

//Function used to Export the Excel Table from report/search results.
// It needs to incorporate code to handle the condition of having too many bytes of data coming from the form and causing "Request Object, ASP 0107 (0x80004005)" error

function ExportTable()
{
  //Set the limit for field size.
  var FormLimit = 102399;

  //Get the value of the large input object.
  var TempVar = new String;
  TempVar = document.exporttable.ExportTableBody.value;
  // GR 20080910 - remove hiperlinks
  TempVar = TempVar.replace(/\<a[^\>]*?\>/g, "");
  TempVar = TempVar.replace(/\<\/a\>/g, "");
  document.exporttable.ExportTableBody.value = TempVar;
  
//alert("Formlimit = "+FormLimit + "TempVar="+TempVar);

  //If the length of the object is greater than the limit, break it
  //into multiple objects.
  if (TempVar.length > FormLimit)
//alert("Formlimit = "+FormLimit + "ExportTableBody value="+TempVar.length);
  {
	document.exporttable.ExportTableBody.value = TempVar.substr(0, FormLimit);
	TempVar = TempVar.substr(FormLimit);
//alert("TempVar.substr(FormLimit) = "+TempVar.substr(FormLimit));					

	while (TempVar.length > 0)
	{
//alert("TempVar.length = "+TempVar.length);										
	  var objHidden = document.createElement("TEXTAREA");
	  objHidden.name = "BigTextArea";
	  objHidden.style.visibility="hidden";
	  objHidden.value = TempVar.substr(0, FormLimit);
//alert("ObjHidden name= "+objHidden.name);
	  document.exporttable.appendChild(objHidden);
	  TempVar = TempVar.substr(FormLimit);
	}
  }	
	document.exporttable.submit();
	return false;
}

// to make any form readonly
function ReadOnlyForm(strFormName, bgColour) {
	var f = document.forms[strFormName];
	if ( f ) {
		for ( var i=0; i<f.elements.length; i++) {
			var e = f.elements[i];
			e.readOnly = true;
			e.disabled = true;
			if ( !bgColour ) {
				bgColour = "#EDEDED";
			}
			e.style.backgroundColor = bgColour;
		}
	}
}

// ####################################
// Fun Stuff / Easter Eggs
// ####################################

// No easter eggs currently present. :-)

