//
//	Returns true if all of the non-optional fields in the given
//	form have been assigned values.  If a value is missing, a
//	non-null error message is returned.  If a label attribute
//	is defined for that field, then it will be used in the
//	error message.  For example, the following code segment
//	validates a form with two required fields and one optional field:
//
//		form.field1.label    = "Field 1";
//		form.field2.label    = "Field 2";
//		form.field3.optional = true;
//
//		var err = validateForm(form);
//		if (err) alert(err);
//
function validateForm (form)
{

// Check for all required (non-optional), non-hidden field values

	for (i=0; i<form.length; i++) {
		var e = form.elements[i];
		var label = e.label ? e.label : e.name;

		if (isBlank(e.name) || e.optional)
			continue;

		if (e.type == "hidden")
			continue;

		if (e.type == "select-one" || e.type == "select-multiple") {
			if (e.selectedIndex == -1)
				return "Please Select A Value From The "
						+label+" Field.";
			continue;
		}

		if (isBlank(e.value))
			return "Please Enter A Value Into The "
					+label+" Field.";
	}

	return null;
}

//
//	Validates the given form and submits it with the given action URL
//	if succesful.  If a validation error occurs, an alert window
//	is displayed.
//
function validateAndSubmit (form, url)
{
	var err = validateForm(form);
	if (err) {
		alert (err);
		return;
	}
	submitForm (form, url);
}


//
//	Validate the given form, and alert if there is an error
//	If there was an error, return it. Otherwise return null
//
function validateAndAlert (form)
{
	var err = validateForm(form);
	if (err) {
		alert (err);
		return err;
	}
	else
		return null;
}


//
//	Submits the given form using the given action URL.
//	The current form action remains unchanged after this
//	function is executed.
//
function submitForm (form, url)
{
	var curAction = form.action;
	form.action = url;
	form.submit();
	form.action = curAction;
}

//
//	Submits the given form using the given action URL
//	and target.  The current form target remains unchanged
//	after this function is executed.
//
function submitFormTarget (form, url, target)
{
	var curTarget = form.target;
	form.target = target;
	submitForm(form, url);
	form.target = curTarget;
}

//
//
//	Clears the given form after confirming that operation with the user
//
function resetForm (form)
{
	var ok = confirm (
			"All values currently entered into the form\n"
			+"will be reset to their original values.\n"
			+"\n"
			+"Do you still want to proceed?");

	if (ok) {
		form.reset();
		formResetCheckBoxes (form);
	}
}

//
//	htmlString
//
//	Returns a qouted string escaped and suitable for HTML.
//

function htmlString(str) {

	if (str == "") {
		return '""';
	}

	var len = str.length;
	if (len >= 2 && str.charAt(0) == '"' && str.charAt(len - 1) == '"') {
		str = str.substr(1,len - 1);
	}

	var str2 = str.replace(/"/g,'&quot;');

	return '"' + str2 + '"';
}

//
//	Returns true if the given string is null or contains only whitespace
//
function isBlank (s)
{
	if (s == null)
		return true;

	for (var i=0; i<s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t'))
			return false;
	}

	return true;
}

var formCheckBoxOffImage = "/skipjack/images/checkbox/box-empty-16.gif";
var formCheckBoxOnImage = "/skipjack/images/checkbox/box-black-x-16.gif";

//
//	Toggles the value and image of the given image checkbox
//
function formToggleCheckBox (form, hiddenField, imageField)
{
	var fld = form[hiddenField];
	var img = form[imageField];

	for (i=0; i<formCheckBoxList.length; i++) {
		if (fld.name == formCheckBoxList[i].name) {
			if (fld.value == "on") {
				formSetCheckBox (fld, img, i, "off");
			} else {
				formSetCheckBox (fld, img, i, "on");
			}
			break;
		}
	}

	window.status = "";
}

var formFocusForm = null;
var formFocusField = null;
var formCheckBoxList = new Array();
var formCheckBoxDflt = new Array();
var formCheckBoxOnImage = new Array();
var formCheckBoxOffImage = new Array();

//
//	This function should be called whenever a form page is loaded.
//	It sets all checkbox images to the proper image and sets the
//	focus field (if defined).
//
function formPageLoad ()
{
	for (i=0; i<formCheckBoxList.length; i++) {
		fld = formCheckBoxList[i];
		form = fld.form;
		img = form[fld.name+'CheckBox'];
		formSetCheckBox (fld, img, i, fld.value);
	}	

	formRowSelectInit();

	if (formFocusForm != null && formFocusField != null) {
		var firstRadio = null;
		var setFocus = false;
		for (i=0; i<formFocusForm.length; i++) {
			var e = formFocusForm.elements[i];
			if (e.name != formFocusField)
				continue;

			if (e.type) {
				if (e.type == "radio") {
					if (firstRadio == null)
						firstRadio = e;

					if (e.checked == false)
						continue;

				} else if (e.type != "button"
				       &&  e.type != "select-one"
				       &&  e.type != "select-multiple") {
					e.select();
				}
			}

			e.focus();
			setFocus = true;

			break;
		}

		if (setFocus == false && firstRadio != null) {
			firstRadio.focus();
			setFocus = true;
		}

// If we didn't find any form field with the given name,
// check all of the anchors in the document to see if an image
// button was created with that name

		if (setFocus == false) {
			var id = formFocusField + "_ANCHOR";
			for (i=0; i<document.anchors.length; i++) {
				var a = document.anchors[i];
				if (a.name == id) {
					a.focus();
					setFocus = true;
					break;
				}
			}
		}
	}
}

//
//	Resets the each checkbox field defined for the given form
//	to its originally defined value
//
function formResetCheckBoxes (form)
{
	for (i=0; i<formCheckBoxList.length; i++) {
		fld = formCheckBoxList[i];
		if (fld.form.name == form.name) {
			img = form[fld.name+'CheckBox'];
			formSetCheckBox (fld, img, i, formCheckBoxDflt[i]);
		}
	}
}

//
//	Sets the image source for the given checkbox image field based on
//	the current value of the given checkbox hidden field
//
function formSetCheckBox (fld, img, i, value)
{
	fld.value = value;

	if (fld.value == "on") {
		if (img.src != formCheckBoxOnImage[i]) {
			img.src = formCheckBoxOnImage[i];
		}
	} else {
		if (img.src != formCheckBoxOffImage[i]) {
			img.src = formCheckBoxOffImage[i];
		}
	}
}

//
//	Returns the current value for the set of radio choices with
//	the given name.  If no value is currently selected, null]
//	is returned.
//
function formGetRadioValue (form, fldName)
{
	for (i=0; i<form.length; i++) {
		var e = form.elements[i];
		if (e.name == null || e.name != fldName || e.type != "radio")
			continue;

		if (e.checked)
			return e.value;
	}

	return null;
}

//
//	Sets the given radio choice to the given value
//
function formSetRadioValue (form, fldName, value)
{
	for (i=0; i<form.length; i++) {
		var e = form.elements[i];
		if (e.name == null || e.name != fldName || e.type != "radio")
			continue;

		if (e.value == value) {
			e.checked = true;
			return;
		}
	}
}

//
//	Show or hide all of the display elements associated with
//	the given form field.
//
function formFieldDisplay (form, fldName, enabled)
{
	formElementDisplay (fldName + "_LABEL_SPAN", enabled);
	formElementDisplay (fldName + "_FIELD_SPAN", enabled);
	formElementDisplay (fldName + "_INSTRUCTIONS_SPAN", enabled);
}

//
//	Show or hide the given display element
//
function formElementDisplay (name, enabled)
{
	var fld = document.getElementById (name);
	if (fld) {
		if (enabled == "on") {
			fld.style.display="block";
		} else {
			fld.style.display="none";
		}
	}
}

//
//	Displays the given URL in a new window with the given
//	name, width, height, resize and scrollbars features.
//	All other window features are disabled.
//
function showWindow (url, name, width, height, resize, scrollbars)
{
	var features = "menubar=no";
	features += ",toolbar=no";
	features += ",height="+height;
	features += ",width="+width;
	features += ",resizable="+resize;
	features += ",scrollbars="+scrollbars;

	var win = window.open ("", name, features);

	win.document.location = url;

	win.focus();
}

//
//	Displays the given URL in a new window with the given
//	name, width, height, resize and scrollbars features.
//	All other window features are disabled.
//
function showPopup (url, name, width, height, resize, scrollbars)
{
	var features = "menubar=no";
	features += ",toolbar=no";
	features += ",height="+height;
	features += ",width="+width;
	features += ",resizable="+resize;
	features += ",scrollbars="+scrollbars;

	var win = window.open ("", name, features);
	if(win == null) {
		return 1;
	}

	win.document.location = url;

	win.focus();
	return 0;
}

function showNewBrowser(url, name)
{
	var win = window.open ("", name);

	win.document.location = url;

	win.focus();
}

//
//	Pops-up a HTML window.
//	
//	"url" may be a Url to be displayed in the window, or an empty
//	string.  If "url" is an empty string, the string in the "text"
//	argument will be displayed in the window.
//
//	"name" uniquely names this window.  If another window with the
//	same name is already being displayed, it will be used.
//
//	"text" will be written to the window if "url" is an empty string.
//
//	"width" and "height" define the dimensions of the window.
//
//	"scroll" causes scrollbars to be displayed as needed when set to "yes".
//	scrollbars are omitted if set to "no".
//
//	"pos" may be set to one of: "center" or "default".  If set to "center",
//	the window will be centered on the screen.  If set to "default", it
//	will be displayed 50 pixels from the upper-left corner of the screen.
//
function popupWindow(url, name, text, title, width, height, scroll, pos)
{
	if (pos == "center") {
		LeftPosition=(screen.availWidth)?(screen.availWidth - width)/2 : 50;
		TopPosition=(screen.availHeight)?(screen.availHeight - height)/2 : 50;
	} else {
		LeftPosition=50;TopPosition=50
	}
	settings='width='+width+',height='+height+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
	win=window.open(url,name,settings);

	if (url == "") {
		win.document.open();
		win.document.write("<html><head><title>");
		win.document.write(title);
		win.document.write('</title></head><body bgcolor="gainsboro"><span class=helpText>');
		win.document.write(text);
		win.document.write("</span></body></html>");
	}
	if (win.focus) {
		win.focus();
	}
}


//
//	toggleTreeNode
//	
//	JavaScript function used to open/close branches of HTML trees
//
//

function toggleTreeNode(idx,treeName,openMargin,openImg,closedImg,treeNodeState,deferStateStore) {
      var img  = document.getElementById("_" + treeName + "_image_" + idx);
      var node = document.getElementById("_" + treeName + "_target_" + idx).style;
      if(!treeNodeState[idx]) {
         img.src = openImg.src;
	 node.marginLeft = openMargin;
         node.display="block";	
         treeNodeState[idx] = true;
      } else {
         node.display="none";
         img.src = closedImg.src;
         treeNodeState[idx] = false;
      }

      if (!deferStateStore)
	storeTreeState(treeName,treeNodeState);
}


//
//	storeTreeState
//

function storeTreeState(treeName, treeNodeState) {
	var state = "";
	for (i = 0; i < treeNodeState.length; i++)
	    state += "/" + i + (treeNodeState[i] ? "o" : "c");
	var img = document.getElementById(treeName + "Img");
	img.src = "/skipjack/tree/storeTreeState.tdf?treeName=" + treeName + "&treeState=" + state;
}

// 
// Calendar JavaScript Functions
//

function calendarSetDate(form, dayStyle, highlightStyle, day, month, year, hour, minute) {
	month = calendarFixInt(month);
	form.month.selectedIndex = month - 1;
	form.year.value = year;
	day = calendarFixInt(day);
	form.curDay.value = day;
	if (hour != null && minute != null) {
		setFormField(form,"hour", hour);
		setFormField(form,"minute", minute);
	}

	calendarDisplay(form.name, dayStyle, highlightStyle, day, month, year);
}


function calendarSetDay(form, dayStyle, highlightStyle, day) {
	var month = form.month.selectedIndex + 1;
	var year  = form.year.value;
	day = calendarFixInt(day);
		
	calendarSetDate(form,dayStyle,highlightStyle,day,month,year);
}

function calendarSetToday(form, dayStyle, highlightStyle) {

	var now   = new Date();
	var day   = now.getDate();
	var month = now.getMonth() + 1;
	var year  = now.getYear();

	// netscape bug work-around
	if (year <= 500) { year += 1900; }

	calendarSetDate(form,dayStyle,highlightStyle,day,month,year);
}


function calendarSelectDate(form, dayStyle, highlightStyle) {
	var year  = calendarFixYear(form, form.year.value);
	var month = form.month.selectedIndex + 1;
	var days  = getDaysInMonth(month,year);
	var day   = calendarFixInt(form.curDay.value);

	if (parseInt(day) > days)
		day = days;

	calendarDisplay(form.name, dayStyle, highlightStyle, day, month, year);
}


function calendarSetPreviousMonth(form, dayStyle, highlightStyle) {
	var year = calendarFixYear(form, form.year.value);
	var month = form.month.selectedIndex + 1;
	if (month > 1) {
		month--;
	} else {
		month = 12;
		year--;
		form.year.value = year;
	}

	var days  = getDaysInMonth(month,year);
	var day   = calendarFixInt(form.curDay.value);

	if (day > days) {
		day = days;
		form.curDay.value = day;
	}

	form.month.selectedIndex = month - 1;
	calendarDisplay(form.name, dayStyle, highlightStyle, day, month, year);
}

function calendarSetNextMonth(form, dayStyle, highlightStyle) {
	var year = calendarFixYear(form, form.year.value);
	var month = form.month.selectedIndex + 1;
	if (month < 12) {
		month++;
	} else {
		month = 1;
		year++;
		form.year.value = year;
	}

	var days  = getDaysInMonth(month,year);
	var day   = calendarFixInt(form.curDay.value);

	if (day > days) {
		day = days;
		form.curDay.value = day;
	}

	form.month.selectedIndex = month - 1;
	calendarDisplay(form.name, dayStyle, highlightStyle, day, month, year);
}

function calendarSetNextDay(form, dayStyle, highlightStyle) {
	var year  = calendarFixYear(form, form.year.value);
	var month = form.month.selectedIndex + 1;
	var days  = getDaysInMonth(month,year);
	var day   = calendarFixInt(form.curDay.value);

	if (day < days) {
		day++;
	} else {
		day = 1;
		if (month < 12) {
			month++;
		} else {
			month = 1;
			year++;
			form.year.value = year;
		}
		form.month.selectedIndex = month-1;
	}

	form.curDay.value = day;
	calendarDisplay(form.name, dayStyle, highlightStyle, day, month, year);
}

function calendarSetPreviousDay(form, dayStyle, highlightStyle) {
	var year  = calendarFixYear(form, form.year.value);
	var month = form.month.selectedIndex + 1;
	var day   = calendarFixInt(form.curDay.value);

	if (day > 1) {
		day--;
	} else {
		if (month > 1) {
			month--;
		} else {
			month = 12;
			year--;
			form.year.value = year;
		}
		form.month.selectedIndex = month-1;
		day = getDaysInMonth(month,year);
	}

	form.curDay.value = day;
	calendarDisplay(form.name, dayStyle, highlightStyle, day, month, year);
}

function calendarDisplay(calName, dayStyle, highlightStyle, day, month, year) {

	day	= parseInt(day);
	month   = parseInt(month);
	year	= parseInt(year);

	if (dayStyle == null) dayStyle = document[calName].getAttribute("dayStyle");
	if (highlightStyle == null) highlightStyle = document[calName].getAttribute("highlightStyle");
		
	var i   = 0;
	var now = new Date();

	var days	 = getDaysInMonth(month,year);
	var firstOfMonth = new Date (year, month-1, 1);
	var startingPos  = firstOfMonth.getDay();
	var span;
	days += startingPos;

	// MAKE BEGINNING NON-DATE BUTTONS BLANK
	for (i = 0; i < startingPos; i++) {
		span = document.getElementById(calName + "-span-"+i);
		span.style.display = "none";
		span.innerHTML = "";
	}

	// SET VALUES FOR DAYS OF THE MONTH
	for (i = startingPos; i < days; i++) {
		span = document.getElementById(calName + "-span-" + i);

		var curDay = (i - startingPos + 1);
		span.innerHTML = curDay;		
		span.className = dayStyle;
		span.style.display = "block";
	}

	// MAKE REMAINING NON-DATE BUTTONS BLANK
	for (i=days; i<42; i++)  {
		span = document.getElementById(calName + "-span-"+i);
		span.style.display = "none";
	}

	// GIVE FOCUS TO CORRECT DAY

	if (day > 0) {
		span = document.getElementById(calName + "-span-" + (day+startingPos-1));
		span.className = highlightStyle;
	}
}


function calendarGetCanonicalDate(form, day) {
	var year = form.year.value;
	var month = form.month.selectedIndex + 1;
	day = calendarFixInt(day);

	if (month < 10)
		month = "0" + month;

	if (day < 10)
		day = "0" + day;

	var time = "";
	if (form.hour != null && form.minute != null) {
		time = " " + form.hour.value + ":" + form.minute.value;
	}
	return year + "-" + month + "-" + day + time;
}

function calendarFixYear(form,year) {
	if (year == "08" || year == "008" || year == "0008")
		year = "8";
	else if (year == "09" || year == "009" || year == "0009")
		year = "8";

	if (year.length < 4) {
		if (parseInt(year) > 70)
			year = parseInt(year) + 1900;
		else
			year = parseInt(year) + 2000;
		form.year.value = year;
	}

	return year;
}

function calendarFixInt(i) {
	// work around octal parsing
	if (i == "08")
		i = 8;
	else if (i == "09")
		i = 9;

	return parseInt(i);
}


// returns the number of days in the given month

function getDaysInMonth(month,year)  {
	var days;
	if (month==1 || month==3 || month==5 || month==7 || month==8 ||
		month==10 || month==12)  days=31;
	else if (month==4 || month==6 || month==9 || month==11) days=30;
	else if (month==2)  {
		if (isLeapYear(year)) {
			days=29;
		}
		else {
			days=28;
		}
	}
	return (days);
}

function calendarSetDynamicDate(frame, form, destForm, fldName, linkID, specificValue) {
	var val = "";

	if (form["TimePeriod"]) {
		var opt = form["TimePeriod"].options[form["TimePeriod"].selectedIndex];
		if (opt) val = opt.getAttribute("label");
	}

	if (form["DynamicDate"]) {
		var date = formGetRadioValue(form, "DynamicDate");
		if (date == specificValue) {
			val += calendarGetCanonicalDate(form,form["curDay"].value);
		} else {
			val += date;
		}
	}

	// set the hidden field
	if (destForm && destForm[fldName]) destForm[fldName].value = val;

	// change the displayed value
	var link = document.getElementById(linkID);
	if (link) link.innerHTML = val;

	return true;
}


// check to see if year is a leap year
function isLeapYear (Year) {
	if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
		return (true);
	}
	else {
		return (false);
	}
}

var formRowSelectOffImage = "/skipjack/images/checkbox/box-empty-16.gif";
var formRowSelectOnImage = "/skipjack/images/checkbox/box-black-x-16.gif";

var formRowSelectList  = new Array();
var formRowSelectField = new Array();
var formRowSelectTable = new Array();
var formRowSelectIndexList = new Array();

//
//	Registers a row selection list and associated parameters
//
function formRowSelectRegisterList (list, fld, tblName)
{
	formRowSelectList.push(list);
	formRowSelectField.push(fld);
	formRowSelectTable.push(tblName);
	formRowSelectIndexList.push(new Array());
}

function formRowSelectFind (list)
{
	for (i=0; i<formRowSelectList.length; i++) {
		try {
			if (formRowSelectList[i] == list)
				return i;

		} catch (ex) {}
	}

	return -1;
}

//
//	Registers a row selection list index value
//
function formRowSelectRegisterIndex (list, indexVal)
{
	i = formRowSelectFind (list);
	if (i < 0) { return; }

	try {
		iList = formRowSelectIndexList[i];
		iList.push (indexVal);
	} catch (ex) {}
}

//
//	Initializes all row selection columns based on the value
//	of the corresponding form parameter
//
function formRowSelectInit ()
{
	for (i=0; i<formRowSelectList.length; i++) {
		try {
			fld  = formRowSelectField[i];
			tbl  = formRowSelectTable[i];
			if (!fld.value || fld.value == "") {
				continue;
			}

			var a = fld.value.split(',');
			for (j=0; j<a.length; j++) {
				formRowSelectList[i].push(a[j]);

				imgName = tbl + "_RowCheckbox" + a[j];

				try { document.images[imgName].src
						= formRowSelectOnImage;
				} catch (ex1) {}
			}
		} catch (ex) {}
	}
}

function formRowSelectToggle (selectList, indexVal)
{
	var i = formRowSelectFind (selectList);
	if (i < 0) { return; }

	var fld = formRowSelectField[i];
	var tbl = formRowSelectTable[i];
	var img = document.images[tbl + "_RowCheckbox" + indexVal];

	var found = 0;
	for (i=0; i<selectList.length; i++) {
		if (selectList[i] == indexVal) {
			selectList.splice(i,1);
			img.src = formRowSelectOffImage;
			found = 1;
			break;
		}
	}

	if (found == 0) {
		selectList.push(indexVal);
		img.src = formRowSelectOnImage;
	}

	fld.value = selectList;

	window.status = "";
}

//
//	Clears all currently selected items in the given list
//
function formRowSelectClearAll (selectList)
{
	var i = formRowSelectFind (selectList);
	if (i < 0) { return; }

	var tbl = formRowSelectTable[i];
	var fld = formRowSelectField[i];
	var iList = formRowSelectIndexList[i];

	for (i=0; i<iList.length; i++) {
		indexVal = iList[i];

		found = 0;
		for (j=0; j<selectList.length; j++) {
			if (selectList[j] == indexVal) {
				found = 1;
				break;
			}
		}
		if (found == 1) {
			selectList.splice (j,1);
			fld.value = selectList;
		}

		try {
			imgName = tbl + "_RowCheckbox" + indexVal;
			document.images[imgName].src = formRowSelectOffImage;
		} catch (ex) {}
	}
}

//
//	Selects all rows in the given list
//
function formRowSelectSelectAll (selectList)
{
	var i = formRowSelectFind (selectList);
	if (i < 0) { return; }

	var tbl = formRowSelectTable[i];
	var fld = formRowSelectField[i];
	var iList = formRowSelectIndexList[i];

	for (i=0; i<iList.length; i++) {
		indexVal = iList[i];

		found = 0;
		for (j=0; j<selectList.length; j++) {
			if (selectList[j] == indexVal) {
				found = 1;
				break;
			}
		}
		if (found == 0) {
			selectList.push (indexVal);

			if (fld.value == "") {
				fld.value = indexVal;
			} else {
				fld.value = fld.value + "," + indexVal;
			}
		}

		try {
			imgName = tbl + "_RowCheckbox" + indexVal;
			document.images[imgName].src = formRowSelectOnImage;
		} catch (ex) {}
	}
}

//
// 	Completely wipes out a form, preserving only
//	the form attributes.
//

function clearForm (form) {
	if (navigator.product == "Gecko") {
		for (var i = 0; i < form.elements.length; i++) {
			delete form[form.elements[i].name];
			delete form.elements[i];
		}
	}

	form.innerHTML = "";
}

//
//	Sets the given form field to the given value.  If the
//	field does not exist, then a hidden field with the same name
//	is automatically added to the form.
//
function setFormField (form, fld, val, append)
{

	if (append != null && append == true) {
		form.innerHTML += "<input type=hidden name='" + fld + "' value=" + htmlString(val) + ">";
		return;
	}

	if (!form[fld]) {
		form.innerHTML += "<input type=hidden name='" + fld + "'>";
	}

	if (form[fld].type == "select-one" || form[fld].type == "select-multiple") {
		for (i = 0; i < form[fld].options.length; i++)
			if (form[fld].options[i].value == val) {
				form[fld].selectedIndex = i;
			}
	} else {

		try {
			form[fld].value = val;
		} catch (ex) {
			alert ("Failed To Set '" + form.name + "." + fld + "'");
		}
	}
}

//
//	Sets the given form field to the given value and returns
//	the original value.  If the field does not exist, then a
//	hidden field with the same name is automatically added to
//	the form and the default value is returned as the original
//	value.
//
function getAndSetFormField (form, fld, val, dflt)
{
	var origVal = dflt;

	if (form[fld]) { origVal = form[fld].value; }

	setFormField (form, fld, val);

	return origVal;
}

function toggleGroupBox(name, hiddenIcon, shownIcon)
{
	var e      = document.getElementById(name + "_hideShow");
	var hidden = false;
	var src    = hiddenIcon;
	var disp   = "none";
	if (e && e.src.indexOf(hiddenIcon) > -1) {
		src  = shownIcon;
		disp = "block";
	    	if (navigator.product == ("Gecko")) disp = "table-cell";
	}
	if (e) {
		e.src = src;
		e = document.getElementById(name + "_contentCell");
		if (e) e.style.display = disp;
	}
}

//
// Copies all fields from one form into another
//

function formCopyValues(form, destForm, append) {
    if (append == null) append = true;
    
    for (var i = 0; i < form.elements.length; i++) {
	var e = form.elements[i];
	if (e.type == "select-one" || e.type == "select-multiple") {
	    for (var j = 0; j < e.options.length; j++) {
		if (e.options[j].selected) setFormField(destForm, e.name, e.options[j].value, append);
	    }
	} else if (e.type == "radio") {
	    if (e.checked) setFormField(destForm, e.name, e.value, append);
	} else if (e.type == "checkbox") {
	    if (e.checked) setFormField(destForm, e.name, e.value, append);
	} else {
	    setFormField(destForm, e.name, e.value, append);
	}
    }
}

//
// Code to support AJAX modal dialogs with remote form transactions.
//
//

function findLeafFrames(win) {
	var leaves = new Array();

	if (!win) return leaves;

	if (typeof(win.frames) == "undefined" || 
	    typeof("win.frames.length") == "undefined" || 
	    win.frames.length == 0 || 
	    typeof(win.frames[0]) == "undefined") { leaves[0] = win; return leaves; }

	var foundReal = false;

	for (var i = 0; i < win.frames.length; i++) {
		if (typeof(win.frames[i]) == "undefined") continue;
		if (win.frames[i].name.toUpperCase().indexOf("IFRAME") != -1) continue;

		foundReal = true;
		var l2 = findLeafFrames(win.frames[i]);
		for (var j = 0; j < l2.length; j++) { 
			leaves[leaves.length] = l2[j];
		}
	}

	if (!foundReal) leaves[0] = win;

	return leaves;
}

function findRemoteDialogFrame(wrapperId) {
	var leaves = findLeafFrames(top);

	for (var i = 0; i < leaves.length; i++) {
		if (leaves[i].document.getElementById('wrapper_' + wrapperId)) return leaves[i];
	}

	return null;
}

function showRemoteDialog(url, wrapperId, frame, closeOnSuccess, successFunc, successParam, elem, xOffset, yOffset) {
	var tx = new Transaction();

	tx.setContentType("text/html");

	// create the container in the containing div

	if (frame == null) frame = window;
	tx.frame = frame;

	if (closeOnSuccess == null) closeOnSuccess = true;

	var containerId = 'dialogDiv_' + wrapperId;

	tx.container = frame.document.getElementById(containerId);

	if (tx.container == null) {
		tx.container = frame.document.createElement("div");
		tx.container.style.display = 'none';
		tx.container.id = containerId;
		frame.document.body.appendChild(tx.container);
	}

	// create the background divs in all other leaf frames

	var leaves = findLeafFrames(top);
	tx.leaves = leaves;
	var bgId   = 'bgdiv_' + wrapperId;

	for (var i = 0; i < leaves.length; i++) {
		if (leaves[i] == frame) continue;		
		var bg = leaves[i].document.getElementById(bgId);

		if (bg == null) {
			bg = leaves[i].document.createElement("div");
			bg.className = 'modalBackground';
			bg.style.display = 'none';
			bg.id = bgId;
			leaves[i].document.body.appendChild(bg);
		}
	}
		
	if (elem == null) {
		elem = tx.container.ownerDocument;
		tx.centerDialog = true;
	} else {
		tx.centerDialog = false;
	}

	if (xOffset == null) xOffset = 0;
	if (yOffset == null) yOffset = 0;

	tx.execute(url, function(tx2) {
		var cont = tx2.container;
		cont.innerHTML = tx2.responseText;

		// gray out the backgrounds

		for (var i = 0; i < tx2.leaves.length; i++) {
			var bg = tx2.leaves[i].document.getElementById('bgdiv_' + wrapperId);	

				if (bg == null) {
				alert("Could not find remote dialog in frame '"
					+ tx2.leaves[i].name
					+ "' with wrapperID = '"
					+ wrapperId
					+ "'. This probably means the "
					+ "wrapperID was not properly "
					+ "defined in the FormAction.");
				showHTMLPopup(tx2.responseText);
				hideRemoteDialog(wrapperId);
				return;
			}

			bg.style.left  = 0;
			bg.style.top   = 0;
			bg.style.width  = tx2.leaves[i].document.body.scrollWidth;
			bg.style.height = tx2.leaves[i].document.body.scrollHeight;
			bg.style.display = 'block';
		}

		var dialog = cont.ownerDocument.getElementById('wrapper_' + wrapperId);

		// put it in the upper left for now - this prevents screen flashing due to scroll bars

		dialog.style.left = -1000;
		dialog.style.top  = -1000;

		// we have to make these visible before calculating the position, or it just does not work

		dialog.style.display = 'block';
		cont.style.display = 'block';

		var form = cont.ownerDocument.getElementById("form_" + wrapperId);
		form.successFunc    = successFunc;
		form.successParam   = successParam;
		form.closeOnSuccess = closeOnSuccess;
		form.wrapperId      = wrapperId;

		var ff = dialog.getAttribute("focusField");
		if (ff != null && ff != "") {
			if (form[ff]) form[ff].focus();
		}

		var x, y;
		if (tx2.centerDialog) {
			xOffset = tx2.frame.document.body.scrollLeft + xOffset - (top.document.body.clientWidth - tx2.frame.document.body.clientWidth);
			yOffset = tx2.frame.document.body.scrollTop + yOffset - (top.document.body.clientHeight - tx2.frame.document.body.clientHeight);
			var x2 = xOffset + (top.document.body.offsetWidth - dialog.offsetWidth) / 2;
			var y2 = yOffset + (top.document.body.offsetHeight - dialog.offsetHeight) / 2;
			x = x2 < 0 ? 0 : x2;
			y  = y2 < 0 ? 0 : y2;
		} else {
			x = findPosX(elem) + xOffset;
			y  = findPosY(elem) + yOffset;	
		}

		dialog.style.left = x;
		dialog.style.top  = y;

		var ifr = form.ownerDocument.getElementById('iframe_' + wrapperId);	
		if (ifr != null) {
			ifr.style.left  = x;
			ifr.style.top   = y;
			ifr.style.width  = dialog.offsetWidth;
			ifr.style.height = dialog.offsetHeight;
			ifr.style.display = 'block';
		}

		}
	);
}

function execRemoteDialog(url, wrapperId, form) {

	var frame = findRemoteDialogFrame(wrapperId);

	if (frame == null) {
		alert("Could not locate remote dialog frame for dialog '" + wrapperId + "'.");
		return;
	}

	var origForm = frame.document.getElementById('form_' + wrapperId);
	if (form == null) form = origForm;
	
	// handle empty url, which just calls the success func

	if (url == "") {
		var success = true;
		if (origForm.successFunc != null) {
			success = origForm.successFunc(frame, form, origForm.successParam);
		}

		if (success && origForm.closeOnSuccess) hideRemoteDialog(wrapperId);
		return;
	}

	// if the url is non-empty, call the transaction

	var tx = new Transaction();

	for (var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if (e.type == "select-one" || e.type == "select-multiple") {
			for (var j = 0; j < e.options.length; j++) {
				if (e.options[j].selected) tx.setParam(e.name, e.options[j].value);
			}
		} else if (e.type == "radio") {
			if (e.checked) tx.setParam(e.name, e.value);
		} else {
			tx.setParam(e.name, e.value);
		}
	}

	tx.setContentType("transaction/map");
	tx.frame = frame;
	tx.form  = form;
	tx.closeOnSuccess  = origForm.closeOnSuccess;
	tx.successFunc     = origForm.successFunc;
	tx.successParam	   = origForm.successParam;

	tx.execute(url, function(tx2) {
		var map = tx2.getResultMap();
		if (map["tx.status"] != "100 Transaction Successful") {
		    var e = frame.document.getElementById("message_" + wrapperId);
		    if (e) {
			e.style.display = 'block'; 
			e.innerHTML = map["tx.status"] + "<br>" + map["tx.errorMsg"];
		    } else {
			alert(map["tx.status"] + "<br>" + map["tx.errorMsg"]);
		    }
		} else if (map["output.ajaxSuccess"] == "true" && tx2.closeOnSuccess) {
			hideRemoteDialog(wrapperId);
			if (tx2.successFunc != null) {
				tx2.successFunc(tx2.frame, tx2.form, tx2.successParam);
			}
		} else {
		    var e = frame.document.getElementById("message_" + wrapperId);
		    if (e) {
			e.style.display = 'block'; 
			e.innerHTML = map["output.ajaxMessage"];
		    } else {
			alert(map["output.ajaxMessage"]);
		    }	
		    if (map["output.ajaxSuccess"] == "true" && tx2.successFunc != null) {
				tx2.successFunc(tx2.frame, tx2.form, tx2.successParam);
		    }
		}
	});
}

function hideRemoteDialog(wrapperId) {
	var ids = new Array();
	ids[0] = 'dialogDiv_' + wrapperId;
	ids[1] = 'bgdiv_' + wrapperId;
	ids[2] = 'wrapper_' + wrapperId;
	ids[3] = 'message_' + wrapperId;
	ids[4] = 'iframe_' + wrapperId;
	
	var leaves = findLeafFrames(top);

	for (i = 0; i < leaves.length; i++) {
		for (var j in ids) {
			var e = leaves[i].document.getElementById(ids[j]);
			if (e) e.style.display = 'none';
		}
	}
}

//
// New tree routines
//
//

function treeToggle(TreeNodeID, deferStateStore) {

	if (TreeNodeID == -1) return true;

	var img       = document.getElementById("_treeNode_img_" + TreeNodeID);
	var content   = document.getElementById("_treeNode_content_" + TreeNodeID);

	var div       = document.getElementById("_treeNode_div_" + TreeNodeID);
	var state     = div.getAttribute("NodeState");
	var openImg   = div.getAttribute("OpenImg");
	var closedImg = div.getAttribute("ClosedImg");
	var url       = div.getAttribute("DynamicLoadURL");

	if (!div) return true;
	
	newState = "OPEN";
	if (state == "OPEN") {
	    newState = "CLOSED";
	    if (content) content.style.display = 'none';
	    if (img) img.src = closedImg;
	} else {
	    if (content) content.style.display = 'block';
	    if (img) { img.src = openImg; }
	}
	    
	div.setAttribute("NodeState", newState);
	    
	if (!deferStateStore) {
	    var tx = new Transaction();
	    
	    tx.setParam("TreeNodeID", TreeNodeID);
	    tx.setParam("State", newState);
	    
	    tx.execute('/skipjack/tree/setNodeState.tdf', function() {});
	}

	var loadingMsg = document.getElementById("_treeLoadingMsg_" + TreeNodeID);

	if (loadingMsg && url != null && url != "") {
	    var secs = content.getAttribute("RefreshInterval");
	    if (secs != null) secs *= 1000;
	    
	    treeUpdateNode(TreeNodeID, url, secs, true);
	}

	return false;
}

function treeUpdateNode(TreeNodeID, url, millis, immediate) {
	if (typeof(url) != "undefined" && url != null && url != "" && url != 'undefined') {
	    var tx = new Transaction();
	    tx.setContentType("text/html");
	    tx.setParam("TreeNodeID", TreeNodeID);
	    tx.TreeNodeID = TreeNodeID;
	    
	    var completion = function(tx2) {
		var elem = document.getElementById("_treeNode_content_" + tx2.TreeNodeID);
		if (elem) { elem.innerHTML = tx2.responseText; }
	        };

	    if (millis != null && millis > 0) {
		tx.executeInterval(url, completion, millis, immediate);
	    } else {
		tx.execute(url, completion);
	    }
	}
}

function treeContextClick(menuId, e) {	
    if (!e) var e = window.event;
    
    var t;
    if (e.target)t = e.target; 
    else if (e.srcElement) t = e.srcElement; 
    else return;
    
    if (t.nodeType == 3) t = t.parentNode; 
	
    if (e.button && (e.button == 2 || e.button == 3)) {
	showContextMenu(menuId,t);
	return false;
    }
	
    if (e.which && (e.which == 2 || e.which == 3)) {
	showContextMenu(menuId,t);
	return false;
    }

    return true;
}

function treeNodeEdit(form) {
    showPopup("/skipjack/tree/editNode.form?TreeNodeID=" + form["TreeNodeID"].value, "EditTreeNode", 500,300,"no", "no");
}


function treeNodeAdd(form, nodeType, allowDup, contentFrame, menuFrame, url) {
    if (typeof(nodeType) == "undefined" || nodeType == null) {
	nodeType = "LINK";
    }

    if (typeof(url) == "undefined" || url == null || url == "") {
	url  = "/skipjack/tree/addNodeForm.tdf?NodeType=" + nodeType + "&ParentNodeID=" + form["TreeNodeID"].value + "&AllowDup=" + allowDup;
    }
	
    showRemoteDialog(url, 'addNode', contentFrame, true, function(frame, form, menuFrame) { var loc = menuFrame.location; menuFrame.location= loc; }, menuFrame);
}


function treeNodeDelete(form, itemLabel, contentFrame, menuFrame) {
    showRemoteDialog("/skipjack/tree/deleteNodeForm.tdf?ItemLabel=" + escape(itemLabel) + "&TreeNodeID=" + form["TreeNodeID"].value, 'deleteNode', contentFrame, true, function(frame, form, menuFrame) { var loc = menuFrame.location; menuFrame.location= loc; }, menuFrame);
}


function treeNodeRename(form, itemLabel, allowDup, contentFrame, menuFrame) {
    showRemoteDialog("/skipjack/tree/renameNodeForm.tdf?ItemLabel=" + escape(itemLabel) + "&TreeNodeID=" + form["TreeNodeID"].value + "&AllowDup=" + allowDup, 'renameNode', contentFrame, true, function(frame, form, menuFrame) { var loc = menuFrame.location; menuFrame.location= loc; }, menuFrame);
}

function treeToggleMenu(menuId, t) {
	if (t) { showContextMenu(menuId,t); }
}

function treeNodeToggleAll(rootID, newState, thisNode) {
	var nodes = new Array();
	
	var root = document.getElementById("_treeNode_content_" + rootID);
	var divs = root.getElementsByTagName("div");

	var nodeID;

	if (thisNode) {
		nodeID = rootID;

		var div       = document.getElementById("_treeNode_div_" + nodeID);
		var state     = div.getAttribute("NodeState");

		if (state != newState) {
			nodes[nodes.length] = nodeID;
			treeToggle(nodeID, true);
		}
	}

	for (var i = 0; i < divs.length; i++) {
		if (divs[i].id.indexOf("_treeNode_content_") == 0) {
			nodeID = divs[i].id.substring(18);

			var div       = document.getElementById("_treeNode_div_" + nodeID);
			var state     = div.getAttribute("NodeState");

			if (state != newState) {
				nodes[nodes.length] = nodeID;
				treeToggle(nodeID, true);
			}
		}
	}

	
	var tx = new Transaction();
	    
	for (var i = 0; i < nodes.length; i++) {
		tx.setParam("TreeNodeID", nodes[i]);
	}
	tx.setParam("State", newState);
	    
	tx.execute('/skipjack/tree/setNodeState.tdf', function() {});
	
}

function treeNodeExpand(rootID, thisNode) {
	window.setTimeout('treeNodeToggleAll(' + rootID + ', "OPEN", ' + thisNode + ');', 10);
}

function treeNodeCollapse(rootID, thisNode) {
	window.setTimeout('treeNodeToggleAll(' + rootID + ', "CLOSED", ' + thisNode + ');', 10);
}

function treeNodeDragStart(dragNode, dragTree, e) {
	if (!e) var e = window.event;
	var t;
	if (e.target)t = e.target; 
	else if (e.srcElement) t = e.srcElement; 
	else return true;
	
	if (t.nodeType == 3) t = t.parentNode; 
	
	document.dragNode    = dragNode;
	document.dragTree    = dragTree;
	document.onmousemove = treeNodeDragHandle;
	document.onmouseup   = treeNodeDragFinish;

	if (e.stopPropagation) { e.stopPropagation(); };
	e.cancelBubble = true;

	return false;
}



function treeNodeDragHandle(e) {
	if (!e) var e = window.event;
	var t;
	if (e.target)t = e.target; 
	else if (e.srcElement) t = e.srcElement; 
	else return true;
	
	if (t.nodeType == 3) t = t.parentNode; 

	var dragNode = document.dragNode;
	var dragTree = document.dragTree;

	if (!t.id || t.id.indexOf("_treeNode_div_") != 0) return true;	 

	var dragDiv = document.getElementById('_' + dragTree + '_dragDiv');
	if (dragDiv) { 
		dragDiv.style.top     = findPosY(t) + t.offsetHeight;
		dragDiv.style.left    = findPosX(t);
		dragDiv.style.width   = dragNode.offsetWidth;
		dragDiv.style.display = 'block';
	}

	return false;

	/**
	// find which column we are in 
	var i = 0;
	var newCol = 0;
	var newColLeft = -1;
	var newColTop  = -1;
	var colLeft;
	for (i = tableInfo.leftCols; i < tableInfo.headerRow().cells.length; i++) {
	colLeft = findPosX(tableInfo.headerRow().cells[i]);	
	if (colLeft < e.clientX) {
	    newColLeft = colLeft;
	    newCol = i - tableInfo.leftCols;
	}
	if (newColLeft == -1)
	    newColLeft = colLeft;
	if (newColTop == -1)
	    newColTop = findPosY(tableInfo.headerRow().cells[i]);
	}

	colLeft = colLeft + tableInfo.headerRow().cells[i-1].offsetWidth;
	if (colLeft < e.clientX) {
	newColLeft = colLeft;
	newCol++;
	}

	if (dragCol < newCol)
	newCol--;

	tableInfo.dragDiv.style.left = newColLeft - tableInfo.borderWidth;
	tableInfo.dragDiv.style.top  = newColTop;
	tableInfo.dragDiv.style.height = tableInfo.tableElem.offsetHeight - (newColTop - findPosY(tableInfo.tableElem)) - tableInfo.borderWidth;
	if (tableInfo.dragDiv.style.display == 'none')
	tableInfo.dragDiv.style.display = '';

	document.dragTargetCol = newCol;

	*/

	return false;
}

function treeNodeDragFinish(e) {
	document.onmousemove = null;
	document.onmouseup   = null;

	if (document.dragDiv) {
		document.dragDiv.style.display = 'none';
	}

	document.dragDiv  = null;
	document.dragTree = null;
}

function showHTMLPopup(html) {
	var features = "menubar=no";
	features += ",toolbar=no";
	features += ",height=500";
	features += ",width=600";
	features += ",resizable=yes";
	features += ",scrollbars=yes";
	
	var win = window.open ("", "HTMLWindow", features);
	
	win.document.write(html);

	win.focus();
}
