// Javascript validation routines for Biscom Delivery Server

function frameBuster() {
	if (top.frames.length != 0) {
   		top.location=self.document.location;
	}
}

function gotoUrl(url) {
	location.href=url;
}

function textCounter(field, max) {
	if (field.value.length > max)
		field.value = field.value.substring(0, max);
}

// Get the current time and format it as HH:MM:SS AM|PM
function getCurrentTime() {
	var now = new Date();
	var hours = now.getHours();
	var ampm = "AM";
	if (hours > 12) {
		hours = hours - 12;
		ampm = "PM";
	}
	var minutes = now.getMinutes();
	if (minutes < 10) {
		// minutes below 10 are sent back as "1, 2, 3, ... 9"
		minutes = "0" + minutes;
	}

	var seconds = now.getSeconds();
	if (seconds < 10) {
		// seconds below 10 are sent back as "1, 2, 3, ... 9"
		seconds = "0" + seconds;
	}

	var currentTime = "(" + hours + ":" + minutes + ":" + seconds + " " + ampm + ")";
	return currentTime;
}

// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
   var newString  = '';
   var substring  = '';
   beginningFound = false;

   // copy characters over to a new string
   // retain whitespace characters if they are between other characters
   for (var i = 0; i < string.length; i++) {

      // copy non-whitespace characters
      if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {

         // if the temporary string contains some whitespace characters, copy them first
         if (substring != '') {
            newString += substring;
            substring = '';
         }
         newString += string.charAt(i);
         if (beginningFound == false) beginningFound = true;
      }

      // hold whitespace characters in a temporary string if they follow a non-whitespace character
      else if (beginningFound == true) substring += string.charAt(i);
   }
   return newString;
}

/* Cookie Functions */


// For now, the username is the email address -- so read the stored email and insert into the username field.
function cookieReadUsername(emailAddress, domainName) {
	var allCookies = document.cookie;
	var pos = allCookies.indexOf("email=");
	if (pos != -1) {
		var start = pos + 6;
		var end = allCookies.indexOf(";", start);
		if (end == -1) {
			end = allCookies.length;
		}
		var value = unescape(allCookies.substring(start, end));
		var domainNameValue = "";
		var setChecked = false;
		if (value.length > 0) {
			// Get the stored domain name
			var storedDomainName = "";
			pos = allCookies.indexOf("domain=");
			if (pos != -1) {
				start = pos + 7;
				end = allCookies.indexOf(";", start);
				if (end == -1) {
					end = allCookies.length;
				}
				storedDomainName = unescape(allCookies.substring(start, end));
			}

			// If the username is not null, then the remember me checkbox was checked
			// previously, so check it again.
			// If the user is coming from a delivery notification link, must first
			// check to see if the delivery user is the same as the "saved" user in
			// cookie. If so, then set the rememberMe checkbox to true, otherwise set it to false.
			// Domain name follows the same logic. Use stored domain name for all cases except
			// when coming from delivery notification link.
			if ((arguments.length > 0) && (emailAddress.length > 0) && (emailAddress.toLowerCase() != value.toLowerCase())) {
				setChecked = false;
				document.forms[0].username.value = emailAddress;
				domainNameValue = domainName;
			} else {
				setChecked = true;
				document.forms[0].username.value = value;
				domainNameValue = storedDomainName;
			}
		}
		
		// Set the domain name if the domain field is displayed
		if (document.forms[0].displayDomainName.value == "Y") {
			document.forms[0].domain.value = domainNameValue;
		}

		// Set the checkbox value
		document.forms[0].elements["rememberMe"].checked = setChecked;
		if ((value.length > 0) || (emailAddress.length > 0)) {
			// If username is filled in, then focus on the password field.
			var focusControl = document.forms[0].elements["password"];
			if (focusControl.type != "hidden" && !focusControl.disabled) {
				focusControl.focus();
			}
		}

	}
}


// Store the username as the "email address" for now -- because we are storing the email address from the registration page
function cookieStoreUsername() {
	var expiresDate = new Date(2050, 11, 31);
	var username = document.forms[0].username.value;
    document.cookie = "email=" + escape(username) + "; expires=" + expiresDate;

	// Store the domain value
	var domainName = "";
	if (document.forms[0].displayDomainName.value == "Y") {
		domainName = document.forms[0].domain.value;
	}
	document.cookie = "domain=" + escape(domainName) + "; expires=" + expiresDate;
}

function cookieStoreEmail() {
	var expiresDate = new Date(2050, 11, 31);
	var email = document.forms[0].email.value;
	document.cookie = "email=" + escape(email) + "; expires=" + expiresDate;
}

function cookieRemoveEmail() {
	var expiresDate = new Date(1999, 12, 31);
	document.cookie = "email=; expires=" + expiresDate;
	document.cookie = "domain=; expires=" + expiresDate;
}

function cookieStoreSecureCheckbox() {
	var expiresDate = new Date(2010, 11, 31);
	var secureChecked = "unchecked";
	if (document.forms[0].secure.checked) {
		secureChecked = "checked";
	}
	document.cookie = "secureChecked=" + secureChecked + "; expires=" + expiresDate;
}

function cookieReadSecureCheckbox() {
	var allCookies = document.cookie;
	var pos = allCookies.indexOf("secureChecked=");
	if (pos != -1) {
		var start = pos + 14;
		var end = allCookies.indexOf(";", start);
		if (end == -1) {
			end = allCookies.length;
		}
		var value = allCookies.substring(start, end);
		if (value == 'checked') {
			document.forms[0].secure.checked = true;
		} else {
			document.forms[0].secure.checked = false;
		}
	}
}



function cookieReadEmail() {
	var allCookies = document.cookie;
	var pos = allCookies.indexOf("email=");
	if (pos != -1) {
		var start = pos + 6;
		var end = allCookies.indexOf(";", start);
		if (end == -1) {
			end = allCookies.length;
		}
		var value = unescape(allCookies.substring(start, end));
		document.forms[0].email.value = value;
		if (value.length > 0) {
			var focusControl = document.forms[0].elements["password"];
			if (focusControl.type != "hidden" && !focusControl.disabled) {
				focusControl.focus();
			}
		}
	}
}



/* Validation Functions */

function isEmpty(aTextField) {
	if ((aTextField.value.length==0) ||
		(aTextField.value==null)) {
		return true;
	} else {
		return false;
	}
}

function validatePassword(p1, p2) {
/*
	if ((p1.value.length < 1) && (p2.value.length < 1)) {
		alert("Passwords cannot be blank.");
		return false;
	}
*/
	if (p1.value != p2.value)	{
		alert("Passwords do not match.");
		return false;
	}
	return true;
}


function isValidPassword(password1, password2, min, max) {
	var msg = "";

	if (password1 != password2) {
		msg += "\n - Passwords do not match";
	}
	if ((password1.length < min) || (password2.length < min) || (password1.length > max) || (password2.length > max)) {
		msg += "\n - Passwords must be between " + min + " and " + max + " characters long";
	}

	return msg;
}

// Check that an email address is valid based on RFC 821 (?)
function isValidEmail(address) {
   if (address != '' && address.search) {
      if (address.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
      else return false;
   }

   // allow empty strings to return true - screen these with either a 'required' test or a 'length' test
   else return true;
}

// Check that an email address has the form something@something.something
// This is a stricter standard than RFC 821 (?) which allows addresses like postmaster@localhost
function isValidEmailStrict(address) {
   if (isValidEmail(address) == false) return false;
   var domain = address.substring(address.indexOf('@') + 1);
   if (domain.indexOf('.') == -1) return false;
   if (domain.indexOf('.') == 0 || domain.indexOf('.') == domain.length - 1) return false;
   return true;
}


function checkEmail (strng) {
	var error="";
	if (strng == "") {
	   error = "\n - The Email Address field must be entered";
	}

    var emailFilter=/^.+@.+\..{2,4}$/;
    if (!(emailFilter.test(strng))) {
       error = "\n - The Email Address field is not valid";
    } else {
		//test email for illegal characters
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
		if (strng.match(illegalChars)) {
			error = "\n - The Email Address field contains illegal characters";
		}
    }
	return error;
}



function getInvalidEmails(strEmails) {
    var invalid = null;
    if (strEmails != null) {
    	var inData = strEmails.value;
    	if (inData.length != 0) {
		    /* extract all valid recognizable emails */
		    var emails = inData.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
	    	/* and the remainings */
		    var remains = inData;
		    if (emails != null) {
				for (var i=0; i<emails.length; i++) {
					remains = remains.replace(emails[i], "");
				}
		    }
		    /* whether remains contain potential characters to be an email */
		    invalid = remains.match(/[^\s|,;]+/gi);
		}
    }
    return invalid;
}



function validateAdminUserCreate(theForm, min_password_length, max_password_length) {
	var msg = "";
	if (theForm.email.value.length == 0) {
		msg += "\n - An email address must be entered";
	} else {
		msg += checkEmail(theForm.email.value);
	}
	msg += isValidPassword(theForm.password1.value, theForm.password2.value, min_password_length, max_password_length);

	if (!(theForm.roleRecipient.checked) && !(theForm.roleSender.checked) && !(theForm.roleReport.checked) && !(theForm.roleAdmin.checked)) {
		msg += "\n - At least one role must be selected";
	}

	if (msg != "") {
		msg = "The following problems occurred:" + msg;
		alert(msg);
		return false;
	} else {
		return true;
	}
}

function validateAdminUserPasswordReset(theForm, min_password_length, max_password_length) {
	var msg = "";

	msg += isValidPassword(theForm.password1.value, theForm.password2.value, min_password_length, max_password_length);

	if (msg != "") {
		msg = "The following problems occurred while updating user:" + msg;
		alert(msg);
		return false;
	} else {
		return true;
	}
}

function validateUserPasswordReset(theForm, min_password_length, max_password_length) {
	var msg = "";

	msg += isValidPassword(theForm.password1.value, theForm.password2.value, min_password_length, max_password_length);

	if (msg != "") {
		msg = "The following problems occurred:" + msg;
		alert(msg);
		return false;
	} else {
		return true;
	}
}

function validateUserRegister(theForm, min_password_length, max_password_length) {
	var msg = "";

	if (theForm.email.value.length == 0) {
		msg += "\n - The Email Address field must be entered";
	} else {
		msg += checkEmail(theForm.email.value);
	}

	msg += isValidPassword(theForm.password1.value, theForm.password2.value, min_password_length, max_password_length);

	if (msg != "") {
		msg = "The following registration problems occurred:" + msg;
		alert(msg);
		return false;
	} else {
		return true;
	}
}



function validateAdminUserUpdate(theForm) {

}

function validatePackageCreate(theForm) {
	var why = "";

	if (isEmpty(theForm.packageName)) {
	 	why += "\n - Package name must be entered";
	}

	if (! isEmpty(theForm.owners)) {
//		var invalid = getInvalidEmails(theForm.owners);
//		if (invalid != null) {
//	 		why += "\n - Please correct or remove the following invalid email addresses:";
//	 		for (var i=0; i<invalid.length; i++) {
//	 			why += "\n" + invalid[i];
//	 		}
//		}
	}

	if (why != "") {
		why = "There are problems with your package:" + why;
		alert(why);
		return false;
	} else {
		return true;
	}
}

// Check to see if the user enters any restricted characters or not
function validateGroupCreate(theForm, invalidGroupNameMsg) {
	var msg = "";
	var value = theForm.groupName.value;
	
	if (value.length == 0) {
		msg = "\n - Group name cannot be empty";
		alert(msg);
		return false;
 	}
 	
	if ((value.indexOf('\\') > -1) || (value.indexOf('/') > -1)
			|| (value.indexOf('<') > -1) || (value.indexOf('>') > -1)
			|| (value.indexOf('[') > -1) || (value.indexOf(']') > -1)
			|| (value.indexOf(':') > -1) || (value.indexOf(';') > -1)
			|| (value.indexOf('|') > -1) || (value.indexOf('=') > -1)
			|| (value.indexOf(',') > -1) || (value.indexOf('+') > -1)
			|| (value.indexOf('*') > -1) || (value.indexOf('?') > -1) || (value.indexOf('@') > -1)) {
	 	msg = invalidGroupNameMsg;
		alert(msg);
		return false;
	}

	return true;
}


// Check to see if the user has selected any files to delete
function validatePackageDeleteFiles(theForm) {
	var docIdArray = theForm.documentIdArray;
	var atLeastOneSelected = false;

	if (typeof docIdArray.length != "number") {
		// Only one checkbox -- check for that
		if (docIdArray.checked == true) {
			atLeastOneSelected = true;
		}
	} else {
		// More than one checkbox -- can loop through array
		for (var i=0; i < docIdArray.length ; i++ ) {
			if (docIdArray[i].checked == true) {
				atLeastOneSelected = true;
			}
		}
	}
	if (!atLeastOneSelected) {
		alert("You must select at least one file to delete to continue");
	}

	return atLeastOneSelected;
}

// Check to see if the user has selected at least one check box
function checkAtLeastOne(checkboxes, msg) {
	var atLeastOneSelected = false;

	if (typeof checkboxes.length != "number") {
		// Only one checkbox -- check for that
		if (checkboxes.checked == true) {
			atLeastOneSelected = true;
		}
	} else {
		// More than one checkbox -- can loop through array
		for (var i=0; i < checkboxes.length ; i++ ) {
			if (checkboxes[i].checked == true) {
				atLeastOneSelected = true;
			}
		}
	}
	if (!atLeastOneSelected) {
		alert(msg);
	}

	return atLeastOneSelected;
}

// Check to see if Dropdown Box is empty
function validateDropdownBox(dItem, msg) {
	if (dItem.selectedIndex == -1) {
		alert(msg);
		return false;
	} else {
		return true;
	}
}


function validateDelivery(theForm) {
	var why = "";

	if (isEmpty(theForm.recipientsTo) && isEmpty(theForm.recipientsCc) && isEmpty(theForm.recipientsBcc)) {
	 	why += "\n - At least one email address must be entered";
	} else {
//		var invalidTo = getInvalidEmails(theForm.recipientsTo);
//		if (invalidTo != null) {
//	 		why += "\n - Please correct or remove the following invalid recipient email addresses in the To field:";
//	 		for (var i=0; i<invalidTo.length; i++) {
//	 			why += "\n" + invalidTo[i];
//	 		}
//		}
//		var invalidCc = getInvalidEmails(theForm.recipientsCc);
//		if (invalidCc != null) {
//	 		why += "\n - Please correct or remove the following invalid recipient email addresses in the Cc field:";
//	 		for (var i=0; i<invalidCc.length; i++) {
//	 			why += "\n" + invalidCc[i];
//	 		}
//		}
//		var invalidBcc = getInvalidEmails(theForm.recipientsBcc);
//		if (invalidBcc != null) {
//	 		why += "\n - Please correct or remove the following invalid recipient email addresses in the Bcc field:";
//	 		for (var i=0; i<invalidBcc.length; i++) {
//	 			why += "\n" + invalidBcc[i];
//	 		}
//		}
	}

	if (isEmpty(theForm.name)) {
		why += "\n - A subject must be entered";
	}

	if (theForm.password1.value != theForm.password2.value) {
		why += "\n - Passwords do not match";
	}


	// Check notification email addresses
	if (!isEmpty(theForm.notificationEmails)) {
		var invalidNotificationEmails = getInvalidEmails(theForm.notificationEmails);
		if (invalidNotificationEmails != null) {
			why += "\ - Please correct or remove the following invalid email notification addresses:";
	 		for (var i=0; i<invalidNotificationEmails.length; i++) {
	 			why += "\n" + invalidNotificationEmails[i];
	 		}
		}
	}
	// Check for invalid dates (e.g. expiration date is < available date)
	if (!isEmpty(theForm.dateAvailable) && !isEmpty(theForm.dateExpires)) {
		var d1 = Date.parse(theForm.dateAvailable.value);
		var d2 = Date.parse(theForm.dateExpires.value);
		if (d1 > d2) {
			why += "\n - Expiration date occurs before available date";
		}
	}

	if (why != "") {
		why = "There are problems with your delivery:" + why;
		alert(why);
		return false;
	} else {
		return true;
	}
}

function toggleLayer(whichLayer) {
	if (document.getElementById) {
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = style2.display? "":"block";
	}
	else if (document.all) {
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = style2.display? "":"block";
	}
	else if (document.layers) {
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = style2.display? "":"block";
	}
}

function showLayer(whichLayer) {
	if (document.getElementById) {
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = "block";
	}
	else if (document.all) {
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = "block";
	}
	else if (document.layers) {
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = "block";
	}
}

function hideLayer(whichLayer) {
	if (document.getElementById) {
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = "";
	}
	else if (document.all) {
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = "";
	}
	else if (document.layers) {
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = "";
	}
}


/////////////////// Preview
function fdsEscape(str) {
	var retval = '';
	var i;
	var c;
	for (i = 0; i < str.length; i++) {
		c = str.charAt(i);
		if (c == '<') {
			retval += '&lt;';
		} else if (c == '>') {
			retval += '&gt;';
		} else if (c == '&') {
			retval += '&amp;';
		} else if (c == '\'' ) {
			retval += '&#39;';
		} else if (c == '"') {
			retval += '&quot;';
		} else {
			retval += c;
		}
	}
	return(retval);
}

function previewDelivery(appName)
{
	var srcDelivery = document.forms[0];

	// put focus on the new popup window
	preWin = window.open('', 'DeliveryPreview', 'height=400,width=550,resizable,scrollbars,status');
	preWin.focus();
	var preDoc = preWin.document;

	var htmlContent = "<html>\n";

	var subjectLine = fdsEscape(srcDelivery.name.value);

	htmlContent += "<head>\n<title>" + subjectLine + "</title>\n";
	htmlContent += "<link rel='stylesheet' href='/" + appName + "/stylesheets/fds.css'>\n";

	// onlbur will close the popup window
	htmlContent += "</head>\n<body>\n<br><br>\n"; // onblur='window.close()'>\n";

	htmlContent += "<table width='100%' cellspacing='10'>\n";
	htmlContent += "<tr><td class='noteblack' align='right'><a href='javascript:window.close()'>Close</a></td>\n";
	htmlContent += "<tr><td>\n";
	htmlContent += "<table class='preview'>\n";
	htmlContent += "<tr>\n";
	htmlContent += "<td><b>From: </b></td>\n";
	htmlContent += "<td>" + fdsEscape(srcDelivery.fromAddress.value) +"</td>\n";
	htmlContent += "</tr>\n";
	htmlContent += "<tr>\n";
	htmlContent += "<td><b>To: </b></td>\n";
	htmlContent += "<td>" + fdsEscape(srcDelivery.recipientsTo.value) +"</td>\n";
	htmlContent += "</tr>\n";
	htmlContent += "<tr>\n";
	htmlContent += "<td><b>Cc: </b></td>\n";
	htmlContent += "<td>" + fdsEscape(srcDelivery.recipientsCc.value) +"</td>\n";
	htmlContent += "</tr>\n";
	htmlContent += "<tr>\n";
	htmlContent += "<td><b>Bcc: </b></td>\n";
	htmlContent += "<td>" + fdsEscape(srcDelivery.recipientsBcc.value) +"</td>\n";
	htmlContent += "</tr>\n";
	htmlContent += "<tr>\n";
	htmlContent += "<td><b>Subject:&nbsp;</b></td>\n";
	htmlContent += "<td>" + subjectLine + "</td>\n";
	htmlContent += "</tr>\n"

	htmlContent += "<tr>\n<td colspan='2'>\n<hr>\n";

	// message body
	var message = fdsEscape(srcDelivery.message.value);
	var re = new RegExp ('\n', 'gi') ;
	message = message.replace(re, '<br>');
	htmlContent += message;

	htmlContent += "<p></p>\n";

	// Sender
	htmlContent += "Sender: " + fdsEscape(srcDelivery.senderInfo.value) + "\n";

	htmlContent += "<br>\n";

	// Link
	htmlContent += "Link: " + fdsEscape(srcDelivery.deliveryLink.value) + "\n";

	htmlContent += "<br><br><br>\n";
	htmlContent += fdsEscape(srcDelivery.permanentMessage.value) + "\n";
	htmlContent += "<hr>\n</td>\n</tr>\n";
	htmlContent += "</table>\n";

	// footer
	htmlContent += "</td></tr>\n";
	htmlContent += "<tr><td class='noteblack' align='right'><a href='javascript:window.close()'>Close</a></td></tr>\n";
	htmlContent += "<tr><td class='notered'>* The URL link in this preview is an example only -- it is not the actual link sent to recipients</td></tr>\n";
	htmlContent += "</table>\n";
	htmlContent += "</body>\n";
	htmlContent += "</html>\n";

	preDoc.write(htmlContent);
	preDoc.close();
}

function openJsp(jspURL, title) {
	// put focus on the new popup window
	preWin = window.open(jspURL, title, 'height=500,width=600,resizable,scrollbars,status');
	preWin.focus();
}

function moreLess(layer, text) {
	var obj;
	obj = document.getElementById(layer);
	if (obj != null && obj.style.display == "none") { obj.style.display = "block"; }
	else { obj.style.display = "none"; }
	obj = document.getElementById(text);
	if (obj != null && obj.innerHTML == "+") { obj.innerHTML = "-"; }
	else { obj.innerHTML = "+"; }
}

function toggleSelect(arr, value) {
	if (typeof arr.length == "number") {
		for (var i = 0; i < arr.length; i ++) {
			if (! arr[i].disabled) {	// no op on disabled
				arr[i].checked = value;
			}
		}
	} else {
		if (! arr.disabled) {	// no op on disabled
			arr.checked = value;
		}
	}
}


// Take in the two sizes (shrunk and expanded) and toggle the size between the two sizes
function resizeDeliveryField(form, element, rows_shrunk, rows_expanded) {
	if (element == form.recipientsTo) {
		form.recipientsTo.rows = (form.recipientsTo.rows == rows_shrunk)?rows_expanded:rows_shrunk;
	} else if (element == form.recipientsCc) {
		form.recipientsCc.rows = (form.recipientsCc.rows == rows_shrunk)?rows_expanded:rows_shrunk;
	} else if (element == form.recipientsBcc) {
		form.recipientsBcc.rows = (form.recipientsBcc.rows == rows_shrunk)?rows_expanded:rows_shrunk;
	} else if (element == form.name) {
		form.name.rows = (form.name.rows == rows_shrunk)?rows_expanded:rows_shrunk;
	} else if (element == form.secureMessage) {
		form.secureMessage.rows = (form.secureMessage.rows == rows_shrunk)?rows_expanded:rows_shrunk;
	} else if (element == form.message) {
		form.message.rows = (form.message.rows == rows_shrunk)?rows_expanded:rows_shrunk;
	}

}

///////////////AJAX
// Timestamp of cart that page was last updated with
var lastUpdateTime = 0;
var req;

/*
 * Returns a new XMLHttpRequest object, or false if the browser
 * doesn't support it
 */
function newXMLHttpRequest() {
	var xmlreq = false;

	// Create XMLHttpRequest object in non-Microsoft browsers
	if (window.XMLHttpRequest) {	/* if (typeof XMLHttpRequest != 'undefined') { */
		xmlreq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			// Try to create XMLHttpRequest in later versions of Internet Explorer
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			// Failed to create required ActiveXObject
			try {
				// Try version supported by older versions of Internet Explorer
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				// Unable to create an XMLHttpRequest by any means
				xmlreq = false;
			}
		}
	}

	return xmlreq;
}

//var reqMessage;

/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes it XML response to the given handler function.
 *
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandler_ob(req, responseXmlHandler, id, v1, v2, v3) {
	//reqMessage += "state: " + req.readyState + "\n";
	// If the request's status is "complete"
	if (req.readyState == 4) {
		// Check that we received a successful response from the server
		if (req.status == 200) {
			/* alert(req.getAllResponseHeaders()); */
			// Pass the XML payload of the response to the handler function.
			responseXmlHandler(id, v2, v3);
			//alert(reqMessage);
		} else {
			// An HTTP problem has occurred
			alert("HTTP error "+req.status+": "+req.statusText);
		}
	} else if (req.readyState == 1) {
		document.getElementById(id).innerHTML = v1;
	}
}

/*
 * Adds the specified item to the shopping cart, via Ajax call
 * itemCode - product code of the item to add
 */
function processStatus_ob(method, svrName, id, v1, v2, v3) {
	var url = "/" + svrName + "/AdminProcessSubmit.do?method=" + method;
	req = newXMLHttpRequest();

	//alert(req);
	//reqMessage = "";

	// Open a connection to the server
	req.open("POST", url, true);

	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	// Return an anonymous function that listens to the XMLHttpRequest instance
	req.onreadystatechange = function() { getReadyStateHandler_ob(req, updateProcessStatus_ob, id, v1, v2, v3); };

	// Send the request
	req.send(null);
}

/*
 * Update shopping-cart area of page to reflect contents of cart
 * described in XML document.
 */
function updateProcessStatus_ob(id, v2, v3) {
	var contact = req.responseXML.getElementsByTagName("contact")[0];
	var generated = contact.getAttribute("generated");
	if (generated > lastUpdateTime) {
		var tagName, content, value;
		for (var i=0; i<contact.childNodes.length; i++) {
			if (contact.childNodes[i].firstChild) {
				tagName = contact.childNodes[i].tagName;
				value = contact.childNodes[i].firstChild.nodeValue;
				if (tagName.match("id")) {
					content = document.getElementById(id);
					if (content != null) {
						if (value.match("1")) {
							content.innerHTML = v2;
						} else {
							content.innerHTML = v3;
						}
					}
				} else {
					content = document.getElementById(tagName);
					if (content != null) {
						content.innerHTML = value;
					}
				}
			}
		}
		lastUpdateTime = generated;
	} else {
		alert("Generated: " + generated + "\nLast: " + lastUpdateTime);
	}
}

//////////////////////////////////////////////// new
function startStopIcons(bStartClickable, bStopClickable, mthdName, svrName, idTimer, idOperations) {
	var opContent = "";
	if (bStartClickable) {
		opContent += "<a href=\"javascript:processStatus('" + mthdName + "', '" + svrName + "', '" + idTimer + "', '" + idOperations + "');\">\n";
	}
	opContent += "<img src='/" + svrName + "/images/misc/icon-misc-start";
	if (! bStartClickable) {
		opContent += "_d";
	}
	opContent += ".gif' border=0 alt='Start' title='Start'>\n";
	if (bStartClickable) {
		opContent += "</a>\n";
	}

	opContent += "&nbsp;&nbsp;\n";

	if (bStopClickable) {
		opContent += "<a href=\"javascript:processStatus('" + mthdName + "', '" + svrName + "', '" + idTimer + "', '" + idOperations + "');\">\n";
	}
	opContent += "<img src='/" + svrName + "/images/misc/icon-misc-stop";
	if (! bStopClickable) {
		opContent += "_d";
	}
	opContent += ".gif' border=0 alt='Stop' title='Stop'>\n";
	if (bStopClickable) {
		opContent += "</a>\n";
	}
	return opContent;
}

/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes it XML response to the given handler function.
 *
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandler(req, responseXmlHandler, mthdName, svrName, idTimer, idOperations) {
	if (req.readyState == 4) {
		if (req.status == 200) {
			responseXmlHandler(mthdName, svrName, idTimer, idOperations);
		} else {
			alert("HTTP error "+req.status+": "+req.statusText);
		}
	} else if (req.readyState == 1) {
		document.getElementById(idTimer).innerHTML = "<img src='/" + svrName + "/images/misc/icon-misc-indicator.gif' border=0 title='please wait...' alt='please wait...'>";
		document.getElementById(idOperations).innerHTML = startStopIcons(false, false, mthdName, svrName, idTimer, idOperations);
	}
}

function processStatus(mthdName, svrName, idTimer, idOperations) {
	var url = "/" + svrName + "/AdminProcessSubmit.do?method=" + mthdName;
	req = newXMLHttpRequest();
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.onreadystatechange = function() { getReadyStateHandler(req, updateProcessStatus, mthdName, svrName, idTimer, idOperations); };
	req.send(null);
}

function updateProcessStatus(mthdName, svrName, idTimer, idOperations) {
	var contact = req.responseXML.getElementsByTagName("contact")[0];
	var generated = contact.getAttribute("generated");
	if (generated > lastUpdateTime) {
		var tagName, content, value;
		for (var i=0; i<contact.childNodes.length; i++) {
			if (contact.childNodes[i].firstChild) {
				tagName = contact.childNodes[i].tagName;
				value = contact.childNodes[i].firstChild.nodeValue;
				if (tagName.match("id")) {
					content = document.getElementById(idOperations);
					if (content != null) {
						if (value.match("1")) {
							content.innerHTML = startStopIcons(false, true, mthdName, svrName, idTimer, idOperations);
						} else {
							content.innerHTML = startStopIcons(true, false, mthdName, svrName, idTimer, idOperations);
						}
					}
				} else {
					content = document.getElementById(tagName);
					if (content != null) {
						content.innerHTML = value;
					}
				}
			}
		}
		lastUpdateTime = generated;
	} else {
		alert("Generated: " + generated + "\nLast: " + lastUpdateTime);
	}
}

function showHide(sectionID) {
	if (document.all || document.getElementById) {
		var section, sectionLink;
		if (document.all) {
			section = document.all(sectionID + 'XZ');
			sectionLink = document.all(sectionID).getElementsByTagName("a").item(0);
		} else {
			section = document.getElementById(sectionID + 'XZ');
			sectionLink = document.getElementById(sectionID).getElementsByTagName("a").item(0);
		}

		if (section.style.display == "none") {
			section.style.display = "block";
			sectionLink.blur();
			sectionLink.className = "z";
		} else {
			section.style.display = "none";
			sectionLink.blur();
			sectionLink.className = "x";
		}
	} else { // Browser is Netscape 4
		return false;
	}
}
