/*   ========================================================================
Name:		Common.js

Notes:		This Javascript file contains commonly used functions.

History:
mm/dd/yyyy	Author	Description
----------	------	----------------------------------------------------
04/16/2001	CAF		Created
========================================================================    */
var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);


//
// Basic page functions for OnLoad, OnUnload, and OnSubmit events.
//
function PageOnLoad() {
	return true;
}

function PageOnUnLoad() {
	return true;
}

function PageOnSubmit(thisForm) {
	if (thisForm.FilesToUpload != null)
		thisForm.FilesToUpload.value = GetFilesToUpload(thisForm);

	return true;
}

function GetFilesToUpload(thisForm) {
	var myArray = new Array();
	
	for (var i=0; i < thisForm.elements.length; i++)
		if (thisForm.elements[i].type == 'file' && thisForm.elements[i].value != '')
			myArray[myArray.length] = thisForm.elements[i].name;
	
	return myArray.join(',');
}

//
// Popup Window Functions
//
// Pops up a child window with the given window name and dimensions.
// Takes the optional arguments to set the menubar, resize, and scrollbars attributes of Window.
function popupWindow(winname,  w, h, menu, resize, scroll) {
	popupWindowURL("", winname,  w, h, menu, resize, scroll);
	return;
}
function popupWindowURL(url, winname,  w, h, menu, resize, scroll, x, y) {
	if (winname == null) winname = "newWindow";
	if (w == null) w = 600;
	if (h == null) h = 600;
	if (resize == null) resize = 1;
	
	menutype   = "nomenubar";
	resizetype = "noresizable";
	scrolltype = "noscrollbars";

	if (menu) menutype = "menubar";
	if (resize) resizetype = "resizable";
	if (scroll) scrolltype = "scrollbars";
	
	if (x == null || y == null) {
		cwin=window.open(url,winname, + "status," + menutype + "," + scrolltype + "," + resizetype + ",width=" + w + ",height=" + h);
	}
	else {
		cwin=window.open(url,winname,"top=" + y + ",left=" + x + ",screenX=" + x + ",screenY=" + y + "," + "status," + menutype + "," + scrolltype + "," + resizetype + ",width=" + w + ",height=" + h);
	}
	if (!cwin.opener) cwin.opener=self;
	
	// Allow an object to be passed to the new window
	if (arguments[9] && typeof arguments[9] == "object") cwin.initObj = arguments[9];
	
	cwin.focus();

	return cwin;
}
//need to eventually delete this function and make the features available in popupwindowURL()
function popupFullWindow(url, winname,  w, h) {
	if (winname == null) winname = "newWindow";
	if (w == null) w = 600;
	if (h == null) h = 600;
	
	menutype = "menubar";
	resizetype = "resizable";
	scrolltype = "scrollbars";
	
	cwin=window.open(url,winname,"status,menubar,resizable,scrollbars,toolbar,location" + ",width=" + w + ",height=" + h);
	
	if (!cwin.opener) cwin.opener=self;
	cwin.focus();

	return;
}



//
// Reads user cookie
//
function ReadCookie (CookieName) {
  var CookieString = document.cookie;
//  var CookieSet = CookieString.split (';');
  var CookieSet = splitArray(CookieString, ';');
  var SetSize = CookieSet.length;
  var CookiePieces
  var ReturnValue = "";
  var x = 0;

  for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++) {

//    CookiePieces = CookieSet[x].split ('=');
    CookiePieces = splitArray(CookieSet[x], '=');

    if (CookiePieces[0].substring (0,1) == ' ') {
      CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
    }

    if (CookiePieces[0] == CookieName) {
      ReturnValue = CookiePieces[1];
    }

  }

  return ReturnValue;
}




	
// Submits the form associated with "thiswin" window and displays the results in 
// "popupname" window of dimensions 'w' and 'h'.  Uses popupWindow function. 
function submitClose(thiswin, popupname, w, h, menu, resize, scroll) {
	if (popupname == null) popupname = "resultswindow";
	if (w == null) w = 600;
	if (h == null) h = 600;
	popupWindow(popupname, w, h, menu, resize, scroll);
	
	thiswin.document.forms[0].submit();
	
	thiswin.close();
}

// Checks(status true) or unchecks(status false) all the checkboxes associated with the form.
function CheckUncheck(status,field,form) {
	form = (form == null) ? 0 : form;
	for (i = 0; i < document.forms[form].length; i++) {
		if (field == null || field == document.forms[form].elements[i].name)
			document.forms[form].elements[i].checked = status
	}
}

//given a form checkbox name, this function will higlight all checkboxes of the name specified with the Status values specified
function CheckAll(CheckBox, Status) {
	if (CheckBox.length > 1) {
		for (var i=0; i < CheckBox.length; i++) {
			if (CheckBox[i].disabled == false) CheckBox[i].checked = Status;
	 	}
	} else {
		if (CheckBox.disabled == false) CheckBox.checked = Status;
	}
}

//If a checkbox is selected in a form, this will give a 
//confirmation as to whether they really want to check 
//the box or not. Clicking "Ok" will leave the checkbox alone. 
//Clicking "Cancel" will make the checkbox become unchecked.
//
//Inputs:	thisform (the form object identifier)
//		checkname (the name of the form variable for the checkbox)
function VerifyCheckBox(thisform, checkname) {
   if (thisform.elements[checkname].checked) {
	   if (confirm("Are you sure?")) {
		        thisform.elements[checkname].checked=true;
			return true;
		} else {
	   		thisform.elements[checkname].checked=false;
			return false;
		}
	}
}

//if any checkboxes are checked, this function will return a true. Otherwise false.
function IsChecked(CheckBox) {
	if (CheckBox.length > 1) {
		for (var i=0; i < CheckBox.length; i++) {
			if (CheckBox[i].checked) {
				return true;
			}
	 	}
		return false;
	} else {
		if (CheckBox.checked) {
			return true;
		} else {
			return false;
		}
	}
}

// Given a message this function will prompt the user with the message
// and submits the form if the user confirms
function VerifyAction(thisForm, message) {
	if (window.confirm(message)) {
		thisForm.submit;
	}
}

//given a textbox object, this function will perform an action when the max has been reached
function TabOver(Textbox,Max,Action) {
	if (Textbox.value.length >= Max) eval(Action);
}

//given a form radio, this function will clear all radio buttons
function ClearRadios(RadioField) {
	if (RadioField.length > 1) {
		for (var i=0; i < RadioField.length; i++) {
			RadioField[i].checked = 0;
	 	}
	} else {
		RadioField.checked = 0;
	}
}

//given a form radio name, this function will "check" the radio button of the name specified which matches the value passed
function SelectRadio(RadioField, RadioValue) {
	if (RadioField.length > 1) {
		for (var i=0; i < RadioField.length; i++) {
			if (RadioField[i].value == RadioValue) RadioField[i].checked = 1;
	 	}
	} else {
		if (RadioField.value == RadioValue) RadioField.checked = 1;
	}
}

//
// clears a form.  give it the number of the form on the page
//
function clear_text() {
	if (clear_text.arguments.length == 0) {
		k = 0;
	}
	else if (clear_text.arguments[0] < document.forms.length) { 
		k = clear_text.arguments[0];
	}
	else {  
		k = document.forms.length - 1;
	}
	for(n = 0; n < document.forms[k].elements.length; n++) { 
		if (document.forms[k].elements[n].type == "text") 
			  document.forms[k].elements[n].value = "";
	}
}	


//
// move items up and down on a select
//
function OrderSelect(theSelect, moveDir) {
	var tmpValue = "";
	var tmpText = "";

	for (loop=0; loop < theSelect.options.length; loop++) {
		if (theSelect.options[loop].selected == true) {
			if (moveDir == 1 && loop > 0) {
				tmpValue = theSelect.options[loop-1].value;
				tmpText = theSelect.options[loop-1].text;
				theSelect.options[loop-1].value = theSelect.options[loop].value;
				theSelect.options[loop-1].text = theSelect.options[loop].text;
				theSelect.options[loop].value = tmpValue;
				theSelect.options[loop].text = tmpText;
				theSelect.options[loop].selected = false;
				theSelect.options[loop-1].selected = true;
				break;
			}
			if (moveDir == -1 && loop < (theSelect.options.length -1)) {
				tmpValue = theSelect.options[loop+1].value;
				tmpText = theSelect.options[loop+1].text;
				theSelect.options[loop+1].value = theSelect.options[loop].value;
				theSelect.options[loop+1].text = theSelect.options[loop].text;
				theSelect.options[loop].value = tmpValue;
				theSelect.options[loop].text = tmpText;
				theSelect.options[loop].selected = false;
				theSelect.options[loop+1].selected = true;
				break;
			}
		}
	}
}

//
// assumes theCheckbox is an array
//
function CheckboxToList(theCheckbox, getAll, Sep) {
	var myCheckbox = theCheckbox;
	var ValueList = "";

	if (myCheckbox.form == null) myCheckbox = myCheckbox[0];
	if (getAll == null) getAll = false;
	if (Sep == null) Sep = ",";
	for (i = 0; i < myCheckbox.form.length; i++) {
		if (myCheckbox.form.elements[i].name == myCheckbox.name)
			if (myCheckbox.form.elements[i].checked == true || getAll)
				ValueList += myCheckbox.form.elements[i].value + Sep;
	}
	return ValueList;
}

//Toggles a checkbox that matches a value "CheckBoxValue" for checkbox object "CheckBox"
function ToggleChecked(CheckBox,CheckBoxValue) {
	if (CheckBox.length > 1) {
		for (var i=0; i < CheckBox.length; i++) {
			if (CheckBox[i].value == CheckBoxValue) {
				if (CheckBox[i].checked) {
					CheckBox[i].checked = false;
				} else {
					CheckBox[i].checked = true;
				}
				break;
			}
	 	}
	} else {
		if (CheckBox.value == CheckBoxValue) {
			if (CheckBox.checked) {
				CheckBox.checked = false;
			} else {
				CheckBox.checked = true;
			}
		}
	}
	return true;
}

//Determines if total amount of items checked in checkbox object "CheckBox" is greater than a limit
function CheckedPastLimit(CheckBox,Limit) {
	var CheckBoxCounter=0;
	if (CheckBox.length > 1) {
		for (var i=0; i < CheckBox.length; i++) 
			if (CheckBox[i].checked) CheckBoxCounter = CheckBoxCounter + 1;
	}
	if (CheckBoxCounter > Limit) {
		return true;
	} else {
		return false;
	}
}

//Returns the total amount of items checked in checkbox object "CheckBox"
function TotalChecked(CheckBox) {
	var CheckBoxCounter=0;
	if (CheckBox.length > 1) {
		for (var i=0; i < CheckBox.length; i++) 
			if (CheckBox[i].checked) CheckBoxCounter = CheckBoxCounter + 1;
	} else {
		if (CheckBox.checked) CheckBoxCounter = 1;
	}
	return CheckBoxCounter;
}

//Returns the total amount of items selecteded in SELECT object "DropDown"
function TotalSelected(DropDown) {
	var TotalSelectedCounter=0;
	for (loop=0; loop < DropDown.options.length; loop++) 
		if (DropDown.options[loop].selected == true) TotalSelectedCounter = TotalSelectedCounter + 1;
	
	return TotalSelectedCounter;
}

//
// move items up and down on a select
//
function SelectToList(theSelect, getAll, Sep) {
	var ValueList = "";

	if (getAll == null) getAll = false;
	if (Sep == null) Sep = ";";
	for (loop=0; loop < theSelect.options.length; loop++) {
		if (theSelect.options[loop].selected == true || getAll) {
			ValueList += theSelect.options[loop].value + Sep;
		}
	}
	return ValueList;
}

//
// Offers up an Alert if there was no selection made in a drop down.
// "DropDown" is the object reference to the Drop Down and "AlertMessage" is what shows up in the Alert window.
//
function IsSelected(DropDown,AlertMessage) {
	if (AlertMessage == null) AlertMessage = "Please select an item from the above list.";
	
	if (DropDown.selectedIndex < 0) {
		alert(AlertMessage);
		return false;
	} else {
		return true;
	}
}

//
// This function shifts a selected Option in a Drop Down either up or down.
// Offers up an Alert if there was no selection made in the drop down.
// "DropDown" is the object reference to the Drop Down
// "Direction" is which way the option is being shifted("up" or "down")
// "AlertMessage" is what shows up in the Alert window.
//
function DropDownItemShift(DropDown, Direction, AlertMessage) 
{ if (AlertMessage == null) AlertMessage = "Please select an item to shift Up or Down first.";
  if (Direction == null) Direction = "up";
  SelectedPosition = DropDown.selectedIndex;
  if (SelectedPosition != -1 && DropDown.options[SelectedPosition].value > "") {
    SelectedText = DropDown.options[SelectedPosition].text;
    SelectedValue = DropDown.options[SelectedPosition].value;
    if (DropDown.options[SelectedPosition].value > "" && SelectedPosition > 0 && Direction == "up") {
      DropDown.options[SelectedPosition].text = DropDown.options[SelectedPosition-1].text;
      DropDown.options[SelectedPosition].value = DropDown.options[SelectedPosition-1].value;
      DropDown.options[SelectedPosition-1].text = SelectedText;
      DropDown.options[SelectedPosition-1].value = SelectedValue;
      DropDown.selectedIndex--;
    } else if (SelectedPosition < DropDown.length-1 && DropDown.options[SelectedPosition+1].value > "" && Direction == "down") {
      DropDown.options[SelectedPosition].text = DropDown.options[SelectedPosition+1].text;
      DropDown.options[SelectedPosition].value = DropDown.options[SelectedPosition+1].value;
      DropDown.options[SelectedPosition+1].text = SelectedText;
      DropDown.options[SelectedPosition+1].value = SelectedValue;
      DropDown.selectedIndex++;
    }
  } else {
    alert(AlertMessage);
  }
}

function DropDownItemTransfer(SrcDropDown, DstDropDown, Move, AlertMessage) 
{ if (AlertMessage == null) AlertMessage = "Please select an item first.";
  if (Move == null) Move = 1;
  for (SrcIndex=0; SrcIndex < SrcDropDown.length; SrcIndex++) {
	  if (SrcDropDown.options[SrcIndex].selected)  {
		  //SrcIndex = SrcDropDown.selectedIndex;
		  DstLength = DstDropDown.length;
		  if (SrcIndex != -1 && SrcDropDown.options[SrcIndex].value > "") {
		    Text = SrcDropDown.options[SrcIndex].text;
		    Value = SrcDropDown.options[SrcIndex].value;
		    if (Move) {
				SrcDropDown.options[SrcIndex] = null;
				SrcIndex--;
			}
			DstDropDown.options[DstLength] = new Option (Text, Value, false, true);
		  } else {
		    alert(AlertMessage);
		  }
	  }
  }
  if (SrcDropDown.length > 0) SrcDropDown.options[0].selected=true;
}  

function DropDownItemRemove(DropDown, RequiredList, AlertMessage) 
{ if (AlertMessage == null) AlertMessage = "This will delete the selected item.";
  if (RequiredList == null) RequiredList = "";
  DelIndex = DropDown.selectedIndex;
  if (DelIndex != -1 && DropDown.options[DelIndex].value > "") {
    if (RequiredList.indexOf(DropDown.options[DelIndex].value) > -1) {
      alert ("You may not delete a required this item.");
    } else {
      if (confirm(AlertMessage)) {
        if (DropDown.length==1) {
          DropDown.options[0].text="";
          DropDown.options[0].value="";
        } else {
          DropDown.options[DelIndex]=null; 
        } 
      }
    }
  }
}

//MAC browsers usually can't handle setting a form value in javascript so we us this technique to 
//make the dropdown highlight the appropriate selection.
function SetDropDownSelection(DropDown,Value) {
	//loop through drop down values till you hit the right one and select it.
	for (j=0; j < DropDown.length; j++) {
		if (DropDown.options[j].value == Value) {
			DropDown.options[j].selected = 1;
		}
	}
	return;
}

function TextCounter(focusfield, field1, field2, countfield, maxlimit, CutoffText) {
	if (CutoffText == null) CutoffText=1;
	//if both fields are filled in assume there's gonna be a space in between
	if (field1.value.length > 0 && field2.value.length > 0) {
		if ((field1.value.length+field2.value.length+1) > maxlimit) {
			if (focusfield == 'field1') {
				if (CutoffText) field1.value = field1.value.substring(0, maxlimit-field2.value.length-1);
				countfield.value = maxlimit - (field1.value.length+field2.value.length+1);
				if (countfield.value < 0) {
					countfield.style.backgroundColor='#FFCCCC';
				} else {
					countfield.style.backgroundColor='#FFFFFF';
				}
			} else if (focusfield == 'field2') {
				if (CutoffText) field2.value = field2.value.substring(0, maxlimit-field1.value.length-1);
				countfield.value = maxlimit - (field1.value.length+field2.value.length+1);
				if (countfield.value < 0) {
					countfield.style.backgroundColor='#FFCCCC';
				} else {
					countfield.style.backgroundColor='#FFFFFF';
				}
			}
		// update our character counter
		} else {
			countfield.value = maxlimit - (field1.value.length+field2.value.length+1);
			if (countfield.value < 0) {
				countfield.style.backgroundColor='#FFCCCC';
			} else {
				countfield.style.backgroundColor='#FFFFFF';
			}
		}
	// no assumed space in between cause they're not both filled in, adjust accordingly
	} else {
		if ((field1.value.length+field2.value.length) > maxlimit) {
			if (focusfield == 'field1') {
				if (CutoffText) field1.value = field1.value.substring(0, maxlimit-field2.value.length);
				countfield.value = maxlimit - (field1.value.length+field2.value.length);
				if (countfield.value < 0) {
					countfield.style.backgroundColor='#FFCCCC';
				} else {
					countfield.style.backgroundColor='#FFFFFF';
				}
			} else if (focusfield == 'field2') {
				if (CutoffText) field2.value = field2.value.substring(0, maxlimit-field1.value.length);
				countfield.value = maxlimit - (field1.value.length+field2.value.length);
				if (countfield.value < 0) {
					countfield.style.backgroundColor='#FFCCCC';
				} else {
					countfield.style.backgroundColor='#FFFFFF';
				}
			}
		// update our character counter
		} else {
			countfield.value = maxlimit - (field1.value.length+field2.value.length);
			if (countfield.value < 0) {
				countfield.style.backgroundColor='#FFCCCC';
			} else {
				countfield.style.backgroundColor='#FFFFFF';
			}
		}
	}
}

//
// Keeps one field syncronized with another when called onChange.
// Can keep sets of display fields (_dispN) syncronized with main field.
// Can be used across forms by calling with "thisForm" set to each form.
//
function syncFields (thisForm, thisField, baseName) {
	var myValue = '';
	
	if (thisField.type == "text") {
		myValue = thisField.value;
	} else if (thisField.type == "textarea") {
		myValue = thisField.value;
	} else if (thisField.type == "hidden") {
		myValue = thisField.value;
	} else if (thisField.type == "select-one") {
		myValue = thisField.options[thisField.selectedIndex].value;
	} else {
		alert('Type not supported: ' + thisField.type);
		return;
	}
	
	var myName = baseName;
	for (myDispIndex = 0; myDispIndex <= 10; myDispIndex++) {
		if (thisForm[myName] != null) {
			if (thisForm[myName].type == "text") {
				thisForm[myName].value = myValue;
			} else if (thisForm[myName].type == "textarea") {
				thisForm[myName].value = myValue;
			} else if (thisForm[myName].type == "hidden") {
				thisForm[myName].value = myValue;
			} else if (thisForm[myName].type == "select-one") {
				for (loop=0; loop < thisForm[myName].options.length; loop++) {
					if (thisForm[myName].options[loop].value == myValue) {
						thisForm[myName].selectedIndex = loop;
						break;
					}
				}
			} else {
				alert('Type not supported: ' + thisForm[myName].type);
				return null;
			}
		}
		myName = baseName + '_disp' + myDispIndex;
	}

	return null;
}

//
// Clears certain fields in a form.
//
function clearFields (thisForm) {
	for (myField = 0; myField < thisForm.length; myField++) {
		if (thisForm[myField].type == "text" || thisForm[myField].type == "textarea") {
			thisForm[myField].value = '';
		} else if (thisForm[myField].type == "select-one") {
			thisForm[myField].selectedIndex = 0;
		}
	}

	return null;
}

//
// Copies (or optionally increments) value of field named fname_(i-1) if given field is fname_i.
//
function dittoPrevious(thisField,flagIncrement) {
	var thisForm = thisField.form;
	var fld = thisField.name;
	var tmpArray;
	if (thisField.type == "select-one" && thisField.selectedIndex != 0) return;
	if (thisField.type == "text" && thisField.value.length != 0) return;
	if (fld.charAt('_') == -1)  return;
	
	tmpArray = splitArray(fld, '_');
	if (tmpArray.length != 2) return;
	
	fld = tmpArray[0] + '_' + (tmpArray[1] - 1);
	if (thisForm[fld] == null) return;
	
	if (thisField.type == "select-one") {
		thisField.selectedIndex = thisForm[fld].selectedIndex;
	} else if (thisField.type == "text" && flagIncrement) {
		if (thisForm[fld].value.length && !isNaN(thisForm[fld].value))
			thisField.value = (parseInt(thisForm[fld].value) + 1);
	} else if (thisField.type == "text") {
		thisField.value = thisForm[fld].value;
	}
	return;
}

// This function will validate the length of the text in a HTML textarea field.
function checkTextLength(myTextArea,maxLength) {
	if (myTextArea.value.length > maxLength) {
		var msg = 'The text in this field is ' + myTextArea.value.length + ' characters long. '
		        + 'The maximun allowed is ' + maxLength	+ '.\nPlease modify your text and try again.';
		alert(msg);
		myTextArea.focus();
		return false;
	}
	return true;
}

// This function will put the focus on the first text field of the specified form
function FocusOnText(myFormName) {
	for (i = 0; i < document.forms.length; i++) {
		if (document.forms[i].name == myFormName) {
			for (j = 0; j < document.forms[i].elements.length; j++) {
				if (document.forms[i].elements[j].type == "text") {
					document.forms[i].elements[j].focus();
					break;
				}
			}
			break;
		}
	}
	return;
}

// To be used with our "Action" forms
function SubmitFormAction(myForm,myAction) {
	var tmpFormAction = null;

	for (myField = 0; myField < myForm.length; myField++) {
		if (myForm[myField].name == "Action") {
			if (myForm[myField].type == "hidden") {
				tmpFormAction = myForm[myField];
			} else if (myForm[myField].value == myAction && (myForm[myField].type == "submit" || myForm[myField].type == "button")) {
				tmpFormAction = myForm[myField];
				break;
			}
		}
	}

	if (tmpFormAction != null) {
		if (tmpFormAction.type == "hidden") {
			if (myAction != null) tmpFormAction.value = myAction;
			myForm.submit();
		} else {
			tmpFormAction.onclick();
		}
		return true;
	}

	return false;
}

function SubmitAction(myFormName,myActionValue,myWindowName,mySilent) {
	var thisForm = null;

	thisForm = (myWindowName == null) ?
		window.document[myFormName] : top[myWindowName].document[myFormName];

	if (thisForm == null) {
		if (!mySilent) alert('Form not found: ' + myWindowName + '.' + myFormName);
		return false;
	} else if (!SubmitFormAction(thisForm,myActionValue)) {
		if (!mySilent) alert('Action hidden field not found!');
		return false;
	}
	
	return true;
}

function ValueChangeSubmit(FormName,FieldName,Value) {
	var Form = document[FormName];
	var Field = Form[FieldName];
	Field.value = Value;
	Form.submit();
	return false;
}

function PrintThisPage() {
	var UserAgentString=navigator.userAgent.toLowerCase();
	if (window.print) {
		window.print();
	}
	else if (UserAgentString.indexOf("mac") != -1) {
		alert("Press 'Cmd+p' on your keyboard to print this page.");
	}
	else {
		alert("Press 'Ctrl+p' on your keyboard to print this page.")
	}
}

// Updates the display of the parent window when the child's data is updated.
function refreshOpener(refreshObject) {
	if (window.opener != null && ! isNaN(window.opener.document.forms.length)) {
		for (i=0; i < window.opener.document.forms.length; i++) {
			var tmpForm = window.opener.document.forms[i];

			if (tmpForm.elements['PageRefreshMethod'] != null && tmpForm.elements['PageRefreshByList'] != null) {
				var tmpArray = splitArray(tmpForm.elements['PageRefreshByList'].value, ',');	

				for (j=0; j < tmpArray.length; j++) {
					if (tmpArray[j].toString() == refreshObject) {
						if (tmpForm.elements['PageRefreshMethod'].value == 'Reload') {
							window.opener.location.reload();
						} else if (tmpForm.elements['PageRefreshMethod'].value == 'Submit' && tmpForm.elements['PageRefreshAction'] != null) { 
							tmpForm.elements['Action'][0].value = tmpForm.elements['PageRefreshAction'].value;
							tmpForm.submit();
						}
						break;
					}
				}
				break;
			}
		}
	}
	window.focus();
	return true;
}

// Toggles the display of an HTML token on/off
function ToggleTokenDisplay(myTokenId, myState) {
	var myToken = GetById(myTokenId);

	if (typeof myToken != 'object') return false;
	
	if (typeof myState == 'boolean' && myState == true) {
		myToken.style.display = '';
	} else if (typeof myState == 'boolean' && myState == false) {
		myToken.style.display = 'none';
	} else if (myToken.style.display == '') {
		myToken.style.display = 'none';
	} else {
		myToken.style.display = '';
	}

	return true;
}

// Used to create a simplified tree
function ToggleNextSibling(node) {
	var Pos;
	var ImageRoot;
	// Unfold the branch if it isn't visible
	if (node.nextSibling.style.display == 'none') {
		// Change the image (if there is an image)
		if (node.childNodes.length > 0) {
			if (node.childNodes.item(0).nodeName == "IMG") {
				Pos = node.childNodes.item(0).src.lastIndexOf('/');
				ImageRoot = node.childNodes.item(0).src.substring(0,Pos+1);
				node.childNodes.item(0).src = ImageRoot + 'Minimize.gif';
				node.childNodes.item(0).alt = 'Minimize';
			}
		}

		node.nextSibling.style.display = '';
		return 'opened';

	// Collapse the branch if it IS visible
	} else {
		// Change the image (if there is an image)
		if (node.childNodes.length > 0) {
			if (node.childNodes.item(0).nodeName == "IMG") {
				Pos = node.childNodes.item(0).src.lastIndexOf('/');
				ImageRoot = node.childNodes.item(0).src.substring(0,Pos+1);
				node.childNodes.item(0).src = ImageRoot + 'Maximize.gif';
				node.childNodes.item(0).alt = 'Maximize';
			}
		}

		node.nextSibling.style.display = 'none';
		return 'closed';
	}

}


//
// CFGRID and TableGrid cross compatability Functions by HAH and CAF
//
function IsGridRecordSelected(myGrid) {
	if (myGrid.SelectType != null) {
		if (TableGridIsRecordSelected(myGrid)) return true;
	} else {
		if (gridIsRecordSelected(myGrid)) return true;
	}
	alert('No record has been selected.');
	return false;
}

function GetGridPrimaryKey(myGrid) {
	if (myGrid.SelectType != null) {
		return myGrid.SelectedKey;
	} else {
		return gridGetKeyValue(myGrid);
	}
}

//
// CFGRID Functions by HAH and CAF
//
function gridIsRecordSelected(myGrid) {
	var myRecord = new String(myGrid.cf_getGridForm());
	if (myRecord == '') {
		return false;
	} else {
		return true;
	}
}

function gridGetKeyValue(myGrid,myKey) {
	if (! gridIsRecordSelected(myGrid)) return null;

	var myRecord = new String(myGrid.cf_getGridForm());
	var myKeyValuePairs = splitArray(myRecord,";");

	// Return the first key-value if no key given
	if (myKey == null) {
		loop=0;
	} else {
		for (loop=0; loop < myKeyValuePairs.length; loop+=2) {
			thisKey = myKeyValuePairs[loop].substring(myKeyValuePairs[loop].indexOf('=')+1,myKeyValuePairs[loop].length);
			if (thisKey == myKey) break;
		}
	}

	if (loop < myKeyValuePairs.length) {
		return myKeyValuePairs[loop+1].substring(myKeyValuePairs[loop+1].indexOf('=')+1,myKeyValuePairs[loop+1].length);
	}
	return null;
}

// Calendar Helper Functions
function openCalendar(strForm,strField,SubmitForm) {
	if (SubmitForm) SubmitForm = 1; else SubmitForm = 0;
	window.open('/Utilities/Calendar.html?form='+strForm+'&field='+strField+'&submitform='+SubmitForm+'&bgcolor=FFE4C4&txtcolor=black&hdrcolor=8FBC8F&todaycolor=FFFFFF&offset=0&format=s','cal','resizable,width=250,height=160');
	return false;
}

// Query functions to use with CF Queries
function Query(myColumnList,myRecordCount,myCurrentRow) {
	this.ColumnList = myColumnList;
	this.RecordCount = myRecordCount;
	this.CurrentRow = myCurrentRow;
}

function setSearchRec (thisForm, thisQuery, Move) {
	var thisValue;
	
	thisQuery.CurrentRow += Move;
	if (thisQuery.CurrentRow < 0) thisQuery.CurrentRow = 0;
	if (thisQuery.CurrentRow >= thisQuery.RecordCount) thisQuery.CurrentRow = thisQuery.RecordCount -1;
	for (myField = 0; myField < thisForm.length; myField++) {
		if (thisQuery[thisForm[myField].name.toUpperCase()] != null) {
			thisValue = thisQuery[thisForm[myField].name.toUpperCase()][thisQuery.CurrentRow];
			if (thisValue == null) thisValue = '';
			if (thisForm[myField].type == "text" || thisForm[myField].type == "textarea") {
				thisForm[myField].value = thisValue;
			} else if (thisForm[myField].type == "select-one") {
				thisForm[myField].selectedIndex = 0;
				for (loop=0; loop < thisForm[myField].options.length; loop++) {
					if (thisForm[myField].options[loop].value == thisValue) {
						thisForm[myField].selectedIndex = loop;
						break;
					}
				}
			}
		}
	}

	return null;
}


// Validation Stuff belongs in different file
// A function to validate the E-mail
 function validEmail(email) {
    invalidChars = " /:,;"

  if (email == "") {      // cannot be empty
   return false
  }
  for (i=0; i<invalidChars.length; i++) { // does it contain any invalid characters?
   badChar = invalidChars.charAt(i)
   if (email.indexOf(badChar,0) > -1) {
    return false
   }
  }
  atPos = email.indexOf("@",1)   // there must be one "@" symbol
  if (atPos == -1) {
   return false
  }
  if (email.indexOf("@",atPos+1) != -1) { // and only one "@" symbol
   return false
  }
  periodPos = email.indexOf(".",atPos)
  if (periodPos == -1) {     // and at least one "." after the "@"
   return false
  }
  if (periodPos+3 > email.length) {  // must be at least 2 characters after the "."
   return false
  }
  return true
}

// Function to validate if a string is empty
function isEmpty(inString) {
	if (inString == null || inString == "")
		return true;
		
	return false;
}

// Function to validate if a string is a number
function isNumeric(inString) {
	if (isEmpty(inString) || isNaN(parseFloat(inString)))
		return false;

	return true;
}

// Function to validate if a string is a date format: 01/01/2005 or 01-01-2005
function isDate(inString) {
	if (isEmpty(inString))
		return false;

	var tmpStringArray = inString.split('/');

	if (tmpStringArray.length != 3)
		tmpStringArray = inString.split('-');

	if (tmpStringArray.length != 3) return false;

	if (isNaN(tmpStringArray[0]) || isNaN(tmpStringArray[1]) || isNaN(tmpStringArray[2])) return false;
	if (tmpStringArray[0] < 1    || tmpStringArray[1] < 1    || tmpStringArray[2] < 0)    return false;
	if (tmpStringArray[0] > 12   || tmpStringArray[1] > 31   || tmpStringArray[2] > 9999) return false;

	if (isNumeric(Date.parse(tmpStringArray.join('/'))))
		return true;

	return false;
}

// Function to validate if a string is a date format(MM/YYYY or MM/YY): 01/2005 or 01-2005
function isDateAbbrev(inString) {
	if (isEmpty(inString))
		return false;
	var tmpStringArray = inString.split('/');

	if (tmpStringArray.length != 2)
		tmpStringArray = inString.split('-');

	if (tmpStringArray.length != 2) return false;
	
	if (isNaN(tmpStringArray[0]) || isNaN(tmpStringArray[1])) return false;
	if (tmpStringArray[0] < 1    || tmpStringArray[1] < 0)    return false;
	if (tmpStringArray[0] > 12   || tmpStringArray[1] > 9999) return false;

	return true;
}

//START OF DIRECTMAIL
// The following functions probably only exist in DirectMail code,
// but provide general purpose and are therefore stored here.

//Turns text box on for editing
//Will disable a secondary text box if specified.
function FocusOnBox(objectName,secondaryObject)
{   
	objectName.style.background='#FFFFFF';
	objectName.disabled=false;
	objectName.focus();
	
	if(typeof(secondaryObject) != 'undefined')
	{
		secondaryObject.style.background='#FFFFFF';
		secondaryObject.disabled=false;
	}
	
}
//Clears text box and disables it.
//Will disable a secondary text box if specified.
function FocusOffBox(objectName,secondaryObject)
{
	objectName.style.background='#DDDDDD';
	objectName.value='';
	objectName.disabled=true;
	
	//if(typeof(secondaryObject) != 'undefined')
	//{
	//	secondaryObject.style.background='#DDDDDD';
	//	secondaryObject.value='';
	//	secondaryObject.disabled=true;
	//}
}

function SubmitForm(formObject)
	{
		formObject.submit();
	}

function setParentValue(formObject)
{
//Pass the value of the current object to the parent.
var string = 'parent.document.CallForm.'+formObject.name+'.value=formObject.value';
eval(string);
}

//Returns any value in a dollar format.
function dollarFormat(dollarValue)
{
	//FORMAT THE TOTAL TO A DOLLAR TYPE FORMAT: $XX.XX
	//Round to the nearest hundredth.	
	dollarValue = (Math.round(dollarValue*100))/100;
   	//If the floor value is equal to the actual value then tac on a .00
	if (dollarValue == Math.floor(dollarValue))
		dollarValue = dollarValue + '.00';
	//If the floor value times ten is equal to the actual value times ten then tac on a 0.
    else if (dollarValue*10 == Math.floor(dollarValue*10)) 
        dollarValue = dollarValue + '0';
		
	return dollarValue;
}

//END OF DIRECTMAIL


// SOME FUNCTIONS USED WITH ONLOAD & ONUNLOAD

// Body onload utility (supports multiple onload functions)
function AddOnload(f)
{
	// if using jQuery use it's onload facility
	if (typeof window.jQuery != "undefined") {
		jQuery(document).ready(f);
	} else {
		// alert('test');
		if (typeof document.OnloadFunctions == 'undefined') {
			document.OnloadFunctions = new Array();
			if (window.onload)
				document.OnloadFunctions[0] = window.onload;
			window.onload = RunOnloadFunctions;
		}
		document.OnloadFunctions[document.OnloadFunctions.length] = f;
	}
}
function RunOnloadFunctions()
{
	for (var i=0;i<document.OnloadFunctions.length;i++)
		document.OnloadFunctions[i]();
}
// Clears all hidden Action Buttons to fix "back button issue"
function ActionButtonsReset() {
	if (window.document.forms != null)
		for (i = 0; i < window.document.forms.length; i++)
			if (window.document.forms[i].elements.length > 2 && window.document.forms[i].elements[1].name == 'Action' && window.document.forms[i].elements[1].type == 'hidden')
				window.document.forms[i].elements[1].value = 
					window.document.forms[i].elements[1].defaultValue;

	return;
}

// END FUNCTIONS USED WITH ONLOAD & ONUNLOAD



//
// DOM (document object model) Functions
//

// Get an element by ID even in some older browsers
function GetById(myId) {
	// Netscape 4
	if (ns4) {
		return document.layers[myId];
	}
	// Explorer 4
	else if (ie4) {
		return document.all[myId];
	}
	// W3C - Explorer 5+ and Netscape 6+
	else if (ie5 || ns6) {
		return document.getElementById(myId);
	}
	
	return null;
}

function GetParentByTagName(node,parentTagName) {
	parentTagName = parentTagName.toUpperCase();
    do{node = node.parentNode;
    }while (node && node.tagName != parentTagName);
    return node;
}

//get ELEMENT_NODEs from between the textnodes
function firstChildELEMENT_NODE(parent) {
    var child = parent.firstChild;
    while(child && child.nodeType != 1)child = child.nextSibling;
    return child;
}
function nextSiblingELEMENT_NODE(el) {
    do{el = el.nextSibling;
    }while (el && el.nodeType != 1);
    return el;
}
function previousSiblingELEMENT_NODE(el) {
    do{el = el.previousSibling;
    }while (el && el.nodeType != 1);
    return el;
}


// Specialized DOM functions
function ClickInnerAnchor(node) {
	var myAnchors = node.getElementsByTagName('a');
	if (myAnchors.length) {
		// myAnchors[0].click();
		location.href = myAnchors[0].href;
	}
	return null;
}

//fix for SAFARI which returns 0 on every cellIndex
function getCellIndex(cell){
    var retval = cell.cellIndex;
    if(retval==0 || !retval){
        while(cell=previousSiblingELEMENT_NODE(cell)){
            retval++;
        }
    }
    return retval;
}
//fix for SAFARI which doesn't support tr.cells[]
function getCellData(row, cellIndex){
    return row.getElementsByTagName("td").item(cellIndex).firstChild.data;
}

//
// Some Utility functions
//
// Swaps one Character for Another
function SwapStr (str, fnd, rpl) {
  if (rpl.indexOf(fnd) != -1) return str;

  while ((pos = str.indexOf(fnd)) != -1) {
    str = str.substring(0,pos) + rpl + str.substring(pos+fnd.length,str.length);
  }

  return str;
}
// A JavaScript 1.0 version of split
function splitArray(joinedString, splitString) {
	var tempArray = new Array(0);
	var tempStart = 0;
	var tempEnd = 0;
	var arrayCounter = 0;

	while ((tempEnd = joinedString.indexOf(splitString,tempStart)) != -1) {
		tempArray[arrayCounter] = joinedString.substring(tempStart,tempEnd);
		tempStart = tempEnd +1;
		arrayCounter++;
	}
	tempArray[arrayCounter] = joinedString.substring(tempStart,joinedString.length);

	return tempArray;
}
// Returns todays date in proper format
function nowDate() {
	var myDate = new Date();
	return ((myDate.getMonth() + 1) + '/' + myDate.getDate() + '/' + (myDate.getYear() < 1900 ? myDate.getYear()+1900 : myDate.getYear()));
}
// Purely for timing
function Stats(){
    this.times=[(new Date()).getTime()];
    this.descs=[];
    this.addTime = function(desc){
        this.times[this.times.length]=(new Date()).getTime();
        this.descs[this.descs.length]=desc;
    };
    this.toString = function(){
        var str="";
        for(var i=0;i<this.times.length-1;i++){
            str+=(i+1)+". "
            +this.descs[i]+" : "
            +((this.times[i+1]-this.times[i])/1000)
            +"\n";
        }
        str+="\n   total time : "
        +((this.times[this.times.length-1]-this.times[0])/1000)
        +"\n\n\n";
        return str;
    };
    this.show = function(){
        if(document.forms.length>0)
            if(document.forms[0].elements['test'])
                document.forms[0].elements['test'].value+=this.toString();
    };
}
// Dump Properties of an Object
function dumpObjectToWindow(obj,noHTML) {
	var win = window.open();
	win.window.document.write('<PRE>\n'+dumpObjectProperties(obj,noHTML)+'\n</PRE>');
}
function dumpObjectProperties(obj,noHTML) {
	tmpValue = '';
	for (var prop in obj) {
		if (!noHTML || (prop != 'outerHTML' && prop != 'innerHTML' && prop != 'outerText' && prop != 'innerText'))
			tmpValue = tmpValue + prop + ' = "' + (((typeof obj[prop]) == 'function')?'function':obj[prop]) + '"\n';
	}
	return tmpValue;
}


//split a string s with the delimeter del
function split(s,del){
	arrS= new Array();
	var i=0;
	var j=0;
	var k=0;
	var delim=new String(del);
	
	//Is the delimeter in the string
	if(s.indexOf(delim)!=-1){
		for (i=0; i<s.length;i++){
			if(s.charAt(i)==delim){
				if(k==0){
					arrS[j]=s.substring(k,i);
				}else{
					arrS[j]=s.substring(k+1,i);
				}
				k=i;
				j++;
			}
		}
		arrS[j]=s.substring(k+1,s.length);
	}else{
		arrS[0]=s;
	}
	return arrS;
}

//Converts string to ProperCase with spaces and hyphens
function ProperCase(TextField){
	var i;
	var returnString = "";
	var tmpS=Trim(TextField.value.toLowerCase());
	var arrS= new Array();
	var arrS2 = new Array();
	
	//search each word in array arrS
	arrS=split(tmpS," ");
	
	for (i = 0; i < arrS.length; i++){ 
		var thisWord=arrS[i];
		//Check to see if word contains a hyphen
		if(thisWord.indexOf("-")!=-1){
			arrS2 = split(thisWord,"-");
			for(var j=0; j < arrS2.length; j++){
				var thisWord2=arrS2[j];
				returnString = returnString + thisWord2.charAt(0).toUpperCase() + thisWord2.substring(1,thisWord2.length)+"-";
			}
			returnString = returnString.substring(0,returnString.length-1)+" ";
		} else {
			returnString = returnString + thisWord.charAt(0).toUpperCase() + thisWord.substring(1,thisWord.length)+" ";
		}
	}
	TextField.value = returnString.substring(0,returnString.length-1);
	return;
}

function Trim(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
} 

