// create the prototype on the String object
String.prototype.trim = function() {
  // skip leading and trailing whitespace
  // and return everything in between
  var x=this;
  x=x.replace(/^\s*/, "");
  x=x.replace(/\s*$/, "");
  return x;
}

/* This may duplicate the prototype.trim function and may need
 * to be removed. 
 */
function trimspaces(which) 
{
	while(''+which.value.charAt(which.value.length-1)==' ')
		which.value=which.value.substring(0,which.value.length-1);
}

function nospecialcharacters(myfield, e) {
	var key;
	var keychar;

	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;

	// regular characters
	else if ((("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_+=:',. ").indexOf(keychar) > -1))
	   return true;

	return false;
}

function urlEscape(value) {
  value = escape(value);
  value = value.replace(/\//g,"%2F");
  value = value.replace(/\?/g,"%3F");
  value = value.replace(/=/g,"%3D");
  value = value.replace(/&/g,"%26");
  value = value.replace(/@/g,"%40");
  return value;
}

function urlUnEscape(value) {
  return unescape(value);
}

function openWin(URL ,Wide,High ){
    popup = window.open(URL, 'popupULink', 'personalbar=no,toolbar=no,status=yes,scrollbars=yes,resizable=yes,menubar=no,width=' + Wide + ',height=' + High);
}


function isNumeric(sText) {
   var isNumber=true;
     var regexp = /(^(\d+)$)/;
     if (!regexp.test(sText)) {
          isNumber = false;
     }
     return isNumber;
}


function getLeft(pageElement, relativeToPage, elementWindow) {
  var left = null;
  if ( pageElement.offsetLeft != null ) {
    left = 0;
    do {
      left += pageElement.offsetLeft;
      pageElement = pageElement.offsetParent;
    } while ( pageElement != null );
  } else if ( pageElement.x ) {        // ns4 anchors and layers
    left = pageElement.x;
  } else if ( pageElement.location ) { // window objects
    left = 0;
  }
  if ( left != null && relativeToPage != true ) {
    if ( elementWindow == null ) elementWindow = window;
    if ( elementWindow.screenLeft != null &&
         elementWindow.document.body != null &&
         elementWindow.document.body.scrollLeft != null )
    {
      left += elementWindow.screenLeft - elementWindow.document.body.scrollLeft;
    } else if ( elementWindow.screenX != null &&
                elementWindow.outerWidth != null &&
                elementWindow.innerWidth != null &&
                elementWindow.pageXOffset != null )
    {
      left += elementWindow.screenX + (elementWindow.outerWidth-elementWindow.innerWidth) - elementWindow.pageXOffset;
    } else {
      left = null;
    }
  }
  return left;
}

function getTop(pageElement, relativeToPage, elementWindow) {
  var top = null;
  if ( pageElement.offsetTop != null ) {
    top = 0;
    do {
      top += pageElement.offsetTop;
      pageElement = pageElement.offsetParent;
    } while ( pageElement != null );
  } else if ( pageElement.y ) {        // ns4 anchors and layers
    top = pageElement.y;
  } else if ( pageElement.location ) { // window objects
    top = 0;
  }
  if ( top != null && relativeToPage != true ) {
    if ( elementWindow == null ) elementWindow = window;
    if ( elementWindow.screenTop != null &&
         elementWindow.document.body != null &&
         elementWindow.document.body.scrollTop != null )
    {
      top += elementWindow.screenTop - elementWindow.document.body.scrollTop;
    } else if ( elementWindow.screenY != null &&
                elementWindow.outerHeight != null &&
                elementWindow.innerHeight != null &&
                elementWindow.pageYOffset != null )
    {
      top += elementWindow.screenY + (elementWindow.outerHeight-24-elementWindow.innerHeight) - elementWindow.pageYOffset;
    } else {
      top = null;
    }
  }
  return top;
}

function getRight(pageElement, relativeToPage, elementWindow) {
  var right = null;
  var left = getLeft(pageElement, relativeToPage, elementWindow);
  if ( left != null ) {
    if ( pageElement.offsetHeight != null ) {
      right = left + pageElement.offsetWidth;
    } else if ( pageElement.clip && pageElement.clip.width ) { // ns4 layers
      right = left + pageElement.clip.width;
    } else if ( pageElement.location ) {                       // window objects
      if ( elementWindow == null ) elementWindow = window;
      if ( elementWindow.document.body != null ) {
        right = getRight(elementWindow.document.body, false, elementWindow) + elementWindow.document.body.scrollLeft;
      } else if ( elementWindow.outerWidth != null ) {
        right = left + elementWindow.outerWidth;
      }
    } else {
      right = left + 50;
    }
  }
  return right;
}

function getBottom(pageElement, relativeToPage, elementWindow) {
  var bottom = null;
  var top = getTop(pageElement, relativeToPage, elementWindow);
  if ( top != null ) {
    if ( pageElement.offsetHeight != null ) {
      bottom = top + pageElement.offsetHeight;
    } else if ( pageElement.clip && pageElement.clip.height ) { // ns4 layers
      bottom = top + pageElement.clip.height;
    } else if ( pageElement.location ) {                       // window objects
      if ( elementWindow == null ) elementWindow = window;
      if ( elementWindow.document.body != null ) {
        right = getBottom(elementWindow.document.body, false, elementWindow) + elementWindow.document.body.scrollTop;
      } else if ( elementWindow.outerHeight != null ) {
        right = left + elementWindow.outerHeight;
      }
    } else {
      bottom = top + 50;
    }
  }
  return bottom;
}

function getSelectedValue(obj) {
  if ( obj == null ) {
    alert('you passed a null object to getSelectedValue!');
  } else if ( 'select-one' == obj.type ) {
    // if the value is blank, but the text is not, use the text
    if ( '' == obj.options[obj.selectedIndex].value &&
         '' != obj.options[obj.selectedIndex].text )
    {
      return obj.options[obj.selectedIndex].text;
    } else {
      return obj.options[obj.selectedIndex].value;
    }
  } else if ( obj.length > 0 &&
              'radio' == obj[0].type ) {
    for ( var i=0; i < obj.length; i++ ) {
      if ( obj[i].checked == true ) {
        return obj[i];
      }
    }
  } else if ( obj.value != null ) {
    return obj.value;
  } else {
    alert("invalid object passed to getSelectedValue:[" + obj + "]");
  }
}

function setVisibility(visibility, objName)
  {
    var obj;
    if ( document.getElementById ) {
      if ( document.getElementById(objName) == null ) {
        alert("Couldn't find " + objName + " using getElementById!");
        return;
      } else {
        obj = document.getElementById(objName).style;
      }
    } else if ( document.layers ) {
      obj = document.layers[objName];
      if ( obj == null ) {
        alert("Couldn't find " + objName + " using document.layers!");
        return;
      }
    }
    if(visibility == null) {
      alert("No flag being passed");
    } else {
      obj.visibility = visibility;
    }

  }

// This function displays the selected
// objName will making options invisible
function setDisplayFromSelect(obj) {
  var selectField   = obj;
  var options       = obj.options;
  var selectedIndex = obj.selectedIndex;
  for (var i = 0; i < options.length; i++) {
    var objName = options[i].value;
    if (i == selectedIndex) {
      setDisplay('block', objName);
    } else {
      setDisplay('none', objName);
    }
  }
}

function setDisplay(display, objName)
  {
    var obj;
    if ( document.getElementById ) {
      if ( document.getElementById(objName) == null ) {
        //alert("Couldn't find " + objName + " using getElementById!");
        return;
      } else {
        obj = document.getElementById(objName).style;
      }
    } else if ( document.layers ) {
      obj = document.layers[objName];
      if ( obj == null ) {
        alert("Couldn't find " + objName + " using document.layers!");
        return;
      }
    }
    if(display == null) {
      alert("No flag being passed");
    } else {
      obj.display = display;
    }

  }
  
function toggleDisplay(obj){
	obj = document.getElementById(obj);
	if(obj.style.display == 'none'){
		obj.style.display = "block";
	}else{
		obj.style.display = "none";
	}
}

function checkNumeric(arg, errorMessage){
    if(!isNumeric(arg.value)) {
        alert(errorMessage);
        arg.value = "";
    }
}
   
function makeNumeric(inputElement) {
	var elementValue = inputElement.value;
	var newValue = "";
	
	for (i = 0; i < elementValue.length; i++) {
		var elementChar = elementValue.substring(i, i + 1);
		if ("1234567890".indexOf(elementChar) > -1) {
			newValue = newValue + elementChar;
		}
	}
	
	inputElement.value = newValue;
}

function makeNumeric(inputElement) {
	var elementValue = inputElement.value;
	var newValue = "";
	
	for (i = 0; i < elementValue.length; i++) {
		var elementChar = elementValue.substring(i, i + 1);
		if ("1234567890".indexOf(elementChar) > -1) {
			newValue = newValue + elementChar;
		}
	}
	
	inputElement.value = newValue;
}

function checkNotNull(arg, errorMessage, checkReturn){
// check return is there just in case you need a true or false returned
    if(checkReturn == 1){
        if(arg.value.length < 1){
            alert(errorMessage);
            return(false);
        }else{
            return(true);
        }
    }else{
        if(arg.value.length < 1){
            alert(errorMessage);
        }
    }
}

/**
 * Checks the length of a form field for form validation.  If the field is <= to maxLength, true is returned.  Otherwise, false is returned.
 */
function checkFieldLength(field,fieldName,maxLength) {
  var retValue = true;
  var fieldValue = __fixNewlinesTextarea(field.value);
  var fieldLength = fieldValue.length;
  if(fieldLength > maxLength) {
    alert("The value of the '" + fieldName + "' field is " + fieldLength + " characters.  Your entry may only be " + maxLength + " characters.");
    retValue = false;
  }
  return retValue;
}

function __fixNewlinesTextarea (val) {             
  // Adjust newlines so can do correct character counting for Database. Some Dbs count a newline as 2 characters.
  if (val.indexOf('\r\n')!=-1)
    ; // this is IE on windows. Puts both characters for a newline, just what MySQL does. No need to alter
  else if (val.indexOf('\r')!=-1)
    val = val.replace ( /\r/g, "\r\n" );        // this is IE on a Mac. Need to add the line feed
  else if (val.indexOf('\n')!=-1)
    val = val.replace ( /\n/g, "\r\n" );        // this is Firefox on any platform. Need to add carriage return
  else 
    ;                                           // no newlines in the textarea
  return val;
}

function popMenu(url) {
    window.open(url, "popup","topmargin=5,width=200,height=250,scrollbars=no,menubar=no,resizable=yes");
}

/**
 * Checks the length of a form field for form validation.  If the field is <= to maxLength, true is returned.  Otherwise, false is returned. It watches out for non-ascii entries.
 */
function checkAsciiFieldLength(field,fieldName,maxLength) {
  var retValue = true;
  var fieldLength = field.value.length;
  var asciiLen = 0;
  var nonAsciiLen = 0;
  for (i=0,n=fieldLength;i<n;i++) {
    if(field.value.charCodeAt(i)>=0 && field.value.charCodeAt(i)<=255)
    	asciiLen = asciiLen + 1;
    else
	    nonAsciiLen = nonAsciiLen + 1;
  }

	var totalLen = asciiLen + (nonAsciiLen*4);
	
	if(asciiLen > maxLength) {
    alert("The value of the '" + fieldName + "' field is " + fieldLength + " ascii characters.  Your entry may only be " + maxLength + " ascii characters.");
    return false;
	}
	if(totalLen > maxLength) {
    alert("The '" + fieldName + "' field has " + nonAsciiLen + " non-ascii characters and " + asciiLen + " ascii characters. " +
    			"As each non-ascii character is treated as 4 ascii characters, the calculated total length, " + totalLen + " exceeds " + maxLength + ". ");
    return false;
	}
	
  return retValue;
}



/**
 *  Check if a string is a valid email.
 */
function checkValidEmail(emailTxt) {
	//The following regular expression checks for just "email"
	if ( emailTxt == null )
	  emailTxt = "";
	    
	emailTxt = emailTxt.toLowerCase();
    var emailC = /^\w+([-+.]\w+)*@.+\.([a-zA-Z]{2}|[0-9]{2,3}|com|org|net|gov|edu|int|mil|biz|info|mobi|name|aero|jobs|pro|coop|travel|museum)$/;
	
	return  emailC.test(emailTxt);
}

/**
 *  Check if a string is a valid phone number.
 */
function checkValidPhone(phoneTxt) {
	//The following regular expression checks for phone number
    var phoneC = /^\d{3}-\d{3}-\d{4}$/; 
    	if ( phoneC.test(phoneTxt) ) {
	  return true;
	} else {
	  return false;
	}
}

/**
 *  Strip spaces at either ends of a string.
 */
function stripSpaces(str) {
    while (str.substring(0,1) == ' ') str = str.substring(1);
    while (str.substring(str.length-1,str.length) == ' ') str = str.substring(0,str.length-1);
    return str
}

/**
* this function finds a node with in another node. 
* For example: <div id="XXX"><IMG src="YYY"/></div>
* findNode(xxx, "IMG") returns IMG node.
*/
function findNode(theNode,theNodeName) {
  var retValue = null;
  var theNodeChildren = theNode.childNodes;
  for(var i = 0; i < theNodeChildren.length; i++) {
    var currentChild = theNodeChildren[i];
    if( currentChild.nodeName.toUpperCase() == theNodeName ) {
      retValue = currentChild;
    } else if(currentChild.hasChildNodes() == true) {
      //Use recursion until we find it
      currentChild = findNode(currentChild,theNodeName);        
      if( currentChild.nodeName.toUpperCase() == theNodeName ) {
        retValue = currentChild;
        break;
      }
    }
  }
  retValue = currentChild;
  if(retValue != null){
    return retValue;
  }
}

/**
 * Scrolling table with frozen headers
 */

/* Copyright Richard Cornford 2004 */
var finalizeMe = (function(){
	var global = this,base,safe = false,svType = (global.addEventListener && 2)||(global.attachEvent && 3)|| 0;
	function addFnc(next, f){function t(ev){if(next)next(ev);f(ev);};t.addItem = function(d){if(f != d.getFunc()){if(next){next.addItem(d);}else{next = d;}}return this;};t.remove = function(d){if(f == d){f = null;return next;}else if(next){next = next.remove(d);}return this;};t.getFunc = function(){return f;};t.finalize = function(){if(next)next = next.finalize();return (f = null);};return t;};
	function addFunction(f){if(base){base = base.addItem(addFnc(null, f));}else{base = addFnc(null, f);}};
	function ulQue(f){addFunction(f);if(!safe){switch(svType){case 2:global.addEventListener("unload", base, false);safe = true;break;case 3:global.attachEvent("onunload", base);safe = true;break;default:if(global.onunload != base){if(global.onunload)addFunction(global.onunload);global.onunload = base;}break;}}};
	ulQue.remove = function(f){if(base)base.remove(f);};
	function finalize(){if(base){base.finalize();switch(svType){case 3:global.detachEvent("onunload", base);break;case 2:global.removeEventListener("unload", base, false);break;default:global.onunload = null;break;}base = null;}safe = false;};
	ulQue(finalize);return ulQue;
})();


var InitializeMe = (function(){
	var global = this,base = null,safe = false;
	var listenerType = (global.addEventListener && 2)||(global.attachEvent && 3)|| 0;
	function getStackFunc(next, funcRef, arg1,arg2,arg3,arg4){function l(ev){funcRef((ev?ev:global.event), arg1,arg2,arg3,arg4);if(next)next = next(ev);return (funcRef = null);};l.addItem = function(d){if(next){next.addItem(d);}else{next = d;}};return l;};
	return (function(funcRef, arg1,arg2,arg3,arg4){if(base){base.addItem(getStackFunc(null, funcRef, arg1,arg2,arg3,arg4));}else{base = getStackFunc(null, funcRef, arg1,arg2,arg3,arg4);}if(!safe){switch(listenerType){case 2:global.addEventListener("load", base, false);safe = true;break;case 3:global.attachEvent("onload", base);safe = true;break;default:if(global.onload != base){if(global.onload){base.addItem(getStackFunc(null, global.onload));}global.onload = base;}break;}}});
})();
var queryStrings = (function(out){
    if(typeof location != 'undefined'){
        var temp = location.search||location.href||'';
        var nvp, ofSet;
        if((ofSet = temp.indexOf('?')) > -1){
            temp = temp.split("#")[0];
            temp = temp.substring((ofSet+1), temp.length);
            var workAr = temp.split('&');
            for(var c = workAr.length;c--;){
                nvp = workAr[c].split('=');
                if(nvp.length > 1){out[nvp[0]] = nvp[1];}
            }
        }
    }
    return out;
})({});

var TimedQue = (function(){
	var base, timer;
	var interval = 60;
	var newFncs = null;
	function addFnc(next, f){function t(){next = next&&next();if(f()){return t;}else{f = null;return next;}}t.addItem = function(d){if(next){next.addItem(d);}else{next = d;}return this;};t.finalize = function(){return ((next)&&(next = next.finalize())||(f = null));};return t;}
	function tmQue(fc){if(newFncs){newFncs = newFncs.addItem(addFnc(null, fc));}else{newFncs = addFnc(null, fc);}if(!timer){timer = setTimeout(tmQue.act, interval);}}
	tmQue.act = function(){var fn = newFncs, strt = new Date().getTime();if(fn){newFncs = null;if(base){base.addItem(fn);}else{base = fn;}}base = base&&base();if(base||newFncs){var t = interval - (new Date().getTime() - strt);timer = setTimeout(tmQue.act, ((t > 0)?t:1));}else{timer = null;}};
	tmQue.act.toString = function(){return 'TimedQue.act()';};
	tmQue.finalize = function(){timer = timer&&clearTimeout(timer);base = base&&base.finalize();newFncs = null;};
	return tmQue;
})();

var getElementWithId = (function(){if(document.getElementById){return (function(id){return document.getElementById(id);});}else if(document.all){return (function(id){return document.all[id];});}return (function(id){return null;});})();

function getSimpleExtPxIn(el){
	var temp, temp2, tick = 0, getBorders = retFalse, doCompStyle = retFalse,defaultView,objList = [];
	
	function retFalse() { return false; }
	
	retFalse.elTest = retFalse;
	retFalse.iY = retFalse.iX = retFalse.y = retFalse.x = retFalse.w = retFalse.h = retFalse.bb = retFalse.bt = retFalse.bl = retFalse.br = 0;
	
	function retThis() { return retThis; }
	
	function gCompStyleBorders(p, el) { doCompStyle(p, defaultView.getComputedStyle(el, '' )); }
	
	function doComputedStyleFloat(p, cs) {
		p.bt = (cs.getPropertyCSSValue('border-top-width').getFloatValue(5));
		p.bl = (cs.getPropertyCSSValue('border-left-width').getFloatValue(5));
		p.br = (cs.getPropertyCSSValue('border-right-width').getFloatValue(5));
		p.bb = (cs.getPropertyCSSValue('border-bottom-width').getFloatValue(5));
	}
	
	function doComputedStyleValue(p, cs) {
		p.bt = Math.ceil(parseFloat(s.getPropertyValue('border-top-width'))) | 0;
		p.bl = Math.ceil(parseFloat(s.getPropertyValue('border-left-width'))) | 0;
		p.br = Math.ceil(parseFloat(s.getPropertyValue('border-right-width'))) | 0;
		p.bb = Math.ceil(parseFloat(s.getPropertyValue('border-bottom-width'))) | 0;
	}
	
	function gClientBorders(p, el) {
		if (el.clientWidth || el.clientHeight) {
			p.bb = (el.offsetHeight - (el.clientHeight + (p.bt = el.clientTop | 0))) | 0;
			p.br = (el.offsetWidth - (el.clientWidth + (p.bl = el.clientLeft | 0))) | 0;
		}
	}
	
	function getInterfaceObj(el) {
		var lastTick = NaN;
		var offsetParent = getSimpleExtPxInFn(el.offsetParent) || retFalse;
		
		function p(doTick) {
			if (doTick) { tick = (1+tick)%0xEFFFFFFF; }
			if (tick != lastTick) {
				lastTick = tick;
				offsetParent();
				getBorders(p, el);
				p.iY = (p.y = (offsetParent.iY + (el.offsetTop | 0))) + p.bt;
				p.iX = (p.x = (offsetParent.iX + (el.offsetLeft | 0))) + p.bl;
				p.w = el.offsetWidth | 0;
				p.h = el.offsetHeight | 0;
			}
			
			return p;
		}
		
		p.elTest = function(elmnt) { return (elmnt == el); };
		p.iY = p.iX = p.w = p.h = p.y = p.x = p.bb = p.bt = p.bl = p.br = 0;
		return (objList[objList.length] = p);
	}
	
	function getSimpleExtPxInFn(el) {
		if ((!el) || (el == document)) { return retFalse; }

		for(var c = objList.length;c--;) {
			if (objList[c].elTest(el)) { return objList[c]; }
		}

		return getInterfaceObj(el);
	}
	
	function setSpecialObj(el) {
		var lastTick = NaN;
		
		function p(doTick) {
			if (doTick) { tick = (1+tick)%0xEFFFFFFF; }
			return p;
		}
		
		p.elTest = function(elmnt) { return (elmnt == el); };
		p.iY = p.iX = p.w = p.h = p.y = p.x = p.bb = p.bt = p.bl = p.br = 0;
		objList[objList.length] = p;
	}
	
	if ((typeof el.offsetParent != 'undefined') && (typeof el.offsetTop == 'number') && (typeof el.offsetWidth == 'number')) {
		if((typeof el.clientTop == 'number') && (typeof el.clientWidth == 'number')){
			getBorders = gClientBorders;
		} else if ((defaultView = document.defaultView) && defaultView.getComputedStyle && (temp = defaultView.getComputedStyle(el, '' )) && (((temp.getPropertyCSSValue)&&(temp2 = temp.getPropertyCSSValue('border-top-width')) && (temp2.getFloatValue) && (doCompStyle = doComputedStyleFloat)) || ((temp.getPropertyValue) && (doCompStyle = doComputedStyleValue)))){
			getBorders = gCompStyleBorders;
			temp2 = temp = null;
		}
		
		if (document.documentElement) {	setSpecialObj(document.documentElement); }
		if (document.body) { setSpecialObj(document.body); }
		
		return (getSimpleExtPxIn = getSimpleExtPxInFn)(el);
	} else {
		retThis.elTest = retFalse;
		retThis.iY = retThis.iX = retThis.y = retThis.x = retThis.w = retThis.h = retThis.bb = retThis.bt = retThis.bl = retThis.br = NaN;
		return (getSimpleExtPxIn = retThis);
	}
}

function getNewFILCFncStac(fnc){function getNewFnc(f){var next = null;function t(a){next = next&&next(a);return (f(a))?t:next;}t.finalize = function(){next = next&&next.finalize();return (f = null);};t.addItem = function(d){if(f != d){if(next){next.addItem(d);}else{next = getNewFnc(d);}}return this;};return t;}var base = getNewFnc(fnc);fnc = function(a){base = base&&base(a);};fnc.addItem = function(d){if(base){base.addItem(d)}else{base = getNewFnc(d);}};fnc.finalize = function(){return (base = base&&base.finalize());};return fnc;}

function GlobalEventMonitor(eventName, functinRef){
	var finalize, global = this;
	var monitors = {};
	var onName = ['on',''];
	function mainMonitor(eventName, functinRef){
		var monitor = monitors[eventName];
		if(monitor){
			monitor(functinRef);
		}else{
			setEventMonitor(eventName, functinRef);
		}
	}
	function setListener(eventName, longName, fncStack){
		global.addEventListener(eventName, fncStack, false);
		return true;
	}
	function setListener_aE(eventName, longName, fncStack){
		global.attachEvent(longName, fncStack);
		return true;
	}
	function oldHandler(f){return (function(e){f(e);return true;});}
	function retFalse(){return false;}
	function setEventMonitor(eventName, functinRef){
		var fncStack, longName;
		onName[1] = eventName;
		longName = onName.join('');
		function main(funcRef){
			if(funcRef){
				fncStack.addItem(funcRef);
				globalCheck();
			}
		}
		function globalCheck(){
			if(global[longName] != fncStack){
				if(global[longName]){
					fncStack.addItem(oldHandler(global[longName]));
				}
				global[longName] = fncStack;
			}
		}
		fncStack = getNewFILCFncStac(functinRef);
		if(setListener(eventName, longName, fncStack)){
			globalCheck = retFalse;
		}else{
			globalCheck();
		}
		finalize.addItem(fncStack.finalize);
		monitors[eventName] = main;
		functinRef = null;
	}
	if(!global.addEventListener){
		if(global.attachEvent){
			setListener = setListener_aE;
		}else{
			setListener = retFalse;
		}
	}
	finalizeMe((finalize = getNewFILCFncStac(
		function(){
			finalize = monitors = null;
		})
	));
	(GlobalEventMonitor = mainMonitor)(eventName, functinRef);
	functinRef = null;
}

var tableScroll = (function(){
	var global = this, finalise, tableList = {};
	var notOnScroll = true, notAbort = true;
	var testCellOrigX = 0;  // Used to get the testCell original X coordinate in case the size of the table changes due to applied styles
	var overrideStyles = {
		margin:[{keys:['margin','marginBottom','marginLeft','marginRight','marginTop'],value:'0px'}],
		padding:[{keys:['padding','paddingBottom','paddingLeft','paddingRight','paddingTop'],value:'0px'}],
		border:[
			{keys:['border','borderBottom','borderLeft','borderRight','borderTop'],value:'0px none #FFFFFF'},
			{keys:['borderWidth','borderLeftWidth','borderRightWidth','borderBottomWidth','borderTopWidth'],value:'0px'},
			{keys:['borderStyle','borderRightStyle','borderLeftStyle','borderBottomStyle','borderTopStyle'],value:'none'}
		],
		overflow:[{keys:['overflow'],value:'hidden'}],
		positionRel:[{keys:['position'],value:'relative'}],
		positionAbs:[{keys:['position'],value:'absolute'}],
		top:[{keys:['top'],value:'0px'}],
		left:[{keys:['left'],value:'0px'}],
		zIndex:[{keys:['zIndex'],value:2}],
		alignTextLeft:[{keys:['textAlign'],value:'left'}]
	};
	function setStyleProps(styleObj){
		var data, dArray;
		for(var c = 1;c < arguments.length;c++){
			if((data = overrideStyles[arguments[c]])){
				for(var d = data.length;d--;){
					dArray = data[d].keys;
					for(var e = dArray.length;e--;){
						styleObj[dArray[e]] = data[d].value;
					}
				}
			}
		}
		return true;
	}
	function setClass(el,val){
		if(el.setAttribute){el.setAttribute('class',val);}
		return (el.className = val);
	}
	function retFalse(){return false;}
	function TableScroll(id){
		var midAbsDiv, parent, vHeaderAbsStyle, vHeaderRelStyle, hHeaderAbsStyle, hHeaderAbsStyle2, hHeaderRelStyle, hHeaderRelStyle2;
		var midAbsDivStyle, midAbsinerDivStyle, inRelDivStyle, outRelDivDim;
		var lastScrollTop = NaN, lastScrollLeft = NaN, lastWidth = NaN, lastHeight = NaN, tableDim, table = getElementWithId(id);
		var midRelinerDivStyle, midRelinerDiv, testCellDim;
		var testCellOffset = 0;
		function position(){
				var nh,nw,size,th,tw,cellWidth,celHeight,st = midAbsDiv.scrollTop, sl = midAbsDiv.scrollLeft, h = outRelDivDim(true).h, w = outRelDivDim.w, vHeaderPos;
				if((size = ((w != lastWidth)||(h != lastHeight)))||(st != lastScrollTop)||(sl != lastScrollLeft)){
					// Sets the proper offset for the headers (so we don't get misaligned columns)
					/* May not need this - 20060418
					var setTableWidth = tableDim().iX; // Need to access the tableDim as a function to preset tableDim.w
					if (tableDim.w > w) {
						headerOffset = 1;
					} else {
						headerOffset = 5;
					}					
					*/
					headerOffset = 1;

					cellWidth = testCellDim().x - tableDim().iX;
					lastScrollLeft = sl;
					
					// IE does evaluates testCellDim().x before and after the page is loaded.
					// If the data for the table is too small to create a scrollbar, this creates a problem
					// which we handle with the if statement below.  testCellOffset is global so it is retained
					// whenever the page is resized (but not refreshed)
					if (testCellDim().x > testCellOrigX) { testCellOffset = testCellDim().x - testCellOrigX; }
					vHeaderPos = cellWidth - testCellOffset;
					
					hHeaderRelStyle.left = ((cellWidth + lastScrollLeft) * -headerOffset)+'px';//position
					hHeaderRelStyle2.left = '0px';  // Position the frozen column headers
					vHeaderRelStyle.top = (((celHeight = (testCellDim.y - tableDim.iY)) + (lastScrollTop = st)) * -1)+'px';
					
					if(size){
						vHeaderRelStyle.width = vHeaderAbsStyle.width =	midAbsDivStyle.left = hHeaderAbsStyle.left = vHeaderPos+'px';
						hHeaderAbsStyle2.left = '0px';  // Position the frozen column headers
						hHeaderRelStyle.height = hHeaderRelStyle2.height = hHeaderAbsStyle.height = hHeaderAbsStyle2.height = midAbsDivStyle.top = vHeaderAbsStyle.top = (celHeight+'px');
						
						inRelDivStyle.left = (cellWidth * -1)+'px';
						inRelDivStyle.top = (celHeight * -1)+'px';
						
						midRelinerDivStyle.width = midAbsinerDivStyle.width = ((tw = tableDim.w) - cellWidth)+'px';
						midRelinerDivStyle.height = midAbsinerDivStyle.height = ((th = tableDim.h) - celHeight)+'px';
						midAbsDivStyle.height = vHeaderAbsStyle.height = (((nh = ((lastHeight = h) - celHeight)) > celHeight)?nh:celHeight)+'px';
						midAbsDivStyle.width = hHeaderAbsStyle.width = (((nw = ((lastWidth = w) - cellWidth)) > cellWidth)?nw:cellWidth)+'px';
						
						hHeaderRelStyle.width = inRelDivStyle.width = tw + 'px';
						hHeaderAbsStyle2.width = hHeaderRelStyle2.width = vHeaderRelStyle.width;  // Set the frozen column headers to the width of the frozen columns content
						vHeaderRelStyle.height = inRelDivStyle.height = th + 'px';
            
            var outRelDiv = $$("div.tableBoxOuter");
            
            //resize the tableOuterBox div if content is smaller than the max allowable width (defined in stylesheet)
            if (tableDim.w <= outRelDivDim.w) {
              var scrollBarOffset = 17;
              var newOutRelDivSize = tableDim.w + scrollBarOffset;
              
              outRelDiv[0].setStyle({width: (newOutRelDivSize) + 'px'});
            }
            
            //resize the tableOuterBox div if content is smaller than the max allowable height (defined in stylesheet)
            if (tableDim.h <= outRelDivDim.h) {
              var scrollBarOffset = 17;
              var newOutRelDivSize = tableDim.h + scrollBarOffset;
              
              outRelDiv[0].setStyle({height: (newOutRelDivSize) + 'px'});
            }
					}
				}
				return notOnScroll;
		}
		function onScroll(){
			notOnScroll = false;
			position();
		}
		function onSize(){
			position();
			return true;
		}
		finalise.addItem(function(){
			testCellDim = midRelinerDivStyle = midRelinerDiv = 
			midAbsinerDivStyle =  tableDim = vHeaderAbsStyle = vHeaderRelStyle = hHeaderAbsStyle = hHeaderAbsStyle2 = hHeaderRelStyle = hHeaderRelStyle2 = inRelDivStyle = outRelDivDim = midAbsDiv = parent = table = null;
			})
		if(
			table&&
			(typeof table.scrollTop == 'number')&&
			(typeof table.offsetHeight == 'number')&&
			table.tagName&&
			table.appendChild&&
			table.cloneNode&&
			table.getAttribute&&
			table.getElementsByTagName&&
			(parent = table.parentNode)&&
			parent.insertBefore
		   ){
			InitializeMe(function(){
				var newTable, testCell;
				var vHeaderAbs, vHeaderRel, hHeaderAbs, hHeaderAbs2, hHeaderRel, hHeaderRel2, outRelDiv, midAbsinerDiv, inRelDiv;
				if(
					(notAbort)&&
					(testCell = table.getElementsByTagName('td')[0])&&
					(newTable = table.cloneNode(true))&&
					(outRelDiv = document.createElement('DIV'))&&
					(setClass(outRelDiv, 'tableBoxOuter'))&&
					(midAbsDiv = document.createElement('DIV'))&&
          (midAbsDiv.className = "midAbsDiv") &&
					(midRelinerDiv = document.createElement('DIV'))&&
          (midRelinerDiv.className = "midRelinerDiv") &&
					(midAbsinerDiv = document.createElement('DIV'))&&
          (midAbsinerDiv.className = "midAbsinerDiv") &&
					(inRelDiv = document.createElement('DIV'))&&
          (inRelDiv.className = "inRelDiv") &&
					(vHeaderAbs = document.createElement('DIV'))&&
          (vHeaderAbs.className = "vHeaderAbs") &&
					(vHeaderRel = document.createElement('DIV'))&&
          (vHeaderRel.className = "vHeaderRel") &&
					(hHeaderAbs = document.createElement('DIV'))&&
          (hHeaderAbs.className = "hHeaderAbs") &&
					(hHeaderAbs2 = document.createElement('DIV'))&&
          (hHeaderAbs2.className = "hHeaderAbs2") &&
					(hHeaderRel = document.createElement('DIV'))&&
          (hHeaderRel.className = "hHeaderRel") &&
					(hHeaderRel2 = document.createElement('DIV'))&&
          (hHeaderRel2.className = "hHeaderRel2") &&
					(setStyleProps(outRelDiv.style, 'positionRel', 'padding'))&&
					(midAbsDivStyle = midAbsDiv.style)&&
					(setStyleProps(midAbsDivStyle, 'positionAbs', 'padding', 'margin', 'border', 'zIndex', 'alignTextLeft'))&&
					(midRelinerDivStyle = midRelinerDiv.style)&&
					(setStyleProps(midRelinerDivStyle, 'positionRel', 'padding', 'margin', 'border', 'top', 'left'))&&
					(midAbsinerDivStyle = midAbsinerDiv.style)&&
					(setStyleProps(midAbsinerDivStyle, 'positionAbs', 'overflow', 'padding', 'margin', 'border', 'top', 'left'))&&
					(inRelDivStyle = inRelDiv.style)&&
					(setStyleProps(inRelDivStyle, 'positionRel', 'padding', 'margin', 'border', 'top', 'left'))&&
					(vHeaderAbsStyle = vHeaderAbs.style)&&
					(setStyleProps(vHeaderAbsStyle, 'positionAbs', 'overflow', 'padding', 'margin', 'border', 'top', 'left', 'zIndex'))&&
					(vHeaderRelStyle = vHeaderRel.style)&&
					(setStyleProps(vHeaderRelStyle, 'positionRel', 'padding', 'margin', 'border', 'top', 'left'))&&
					(hHeaderAbsStyle = hHeaderAbs.style)&&
					(setStyleProps(hHeaderAbsStyle, 'positionAbs', 'overflow', 'padding', 'margin', 'border', 'top', 'left', 'zIndex', 'alignTextLeft'))&&
					(hHeaderAbsStyle2 = hHeaderAbs2.style)&&
					(setStyleProps(hHeaderAbsStyle2, 'positionAbs', 'overflow', 'padding', 'margin', 'border', 'top', 'left', 'zIndex'))&&
					(hHeaderRelStyle = hHeaderRel.style)&&
					(setStyleProps(hHeaderRelStyle, 'positionRel', 'padding', 'margin', 'border', 'top', 'left'))&&
					(hHeaderRelStyle2 = hHeaderRel2.style)&&
					(setStyleProps(hHeaderRelStyle2, 'positionRel', 'padding', 'margin', 'border', 'top', 'left'))&&
					(setStyleProps(table.style, 'margin'))&&
					(midAbsDiv.appendChild(midRelinerDiv))&&
					(midRelinerDiv.appendChild(midAbsinerDiv))&&
					(midAbsinerDiv.appendChild(inRelDiv))&&
					(outRelDiv.appendChild(midAbsDiv))&&
					(vHeaderAbs.appendChild(vHeaderRel))&&
					(hHeaderAbs.appendChild(hHeaderRel))&&
					(hHeaderAbs2.appendChild(hHeaderRel2))&&
					(outRelDiv.appendChild(vHeaderAbs))&&
					(outRelDiv.appendChild(hHeaderAbs))&&
					(outRelDiv.appendChild(hHeaderAbs2))&&
					(parent.insertBefore(outRelDiv, table))&&
					(!isNaN((outRelDivDim = getSimpleExtPxIn(outRelDiv)).w))&&
					(inRelDiv.appendChild(table))&&
					(!isNaN((testCellDim = getSimpleExtPxIn(testCell)).w))&&
					(testCellOrigX = testCellDim().x) && 
					(!isNaN((tableDim = getSimpleExtPxIn(table)).w))&&
					(hHeaderRel.appendChild(newTable))&&
					(newTable = table.cloneNode(true))&&
					(hHeaderRel2.appendChild(newTable))&&
					(newTable = table.cloneNode(true))&&
					(vHeaderRel.appendChild(newTable))
				   ){
					midAbsDivStyle.overflow = 'scroll';
					if(midAbsDiv.addEventListener){
						midAbsDiv.addEventListener('scroll', onScroll, false);
					}else if(midAbsDiv.attachEvent){
						midAbsDiv.attachEvent('onscroll', onScroll);
					}else{
						midAbsDiv.onscroll = onScroll;
					}
					GlobalEventMonitor('resize', onSize);
					position();
					TimedQue(position);
				}else{
					notAbort = false;
				}
			});
		}else{
			notAbort = false;
		}
		return true;
	}
	function main(){
		var id;
		for(var c = 0;c < arguments.length;c++){
			id = arguments[c];
			if(notAbort&&!tableList[id]){
				tableList[id] = TableScroll(id);
			}
		}
	}
	if(
		(!global.queryStrings||!queryStrings['noTableScroll'])&&
		global.setTimeout&&
		global.document&&
		document.createElement
	){
		finalizeMe((finalise = getNewFILCFncStac(function(){
			finalise = tableList = null;
		})));
		return main;
	}else{
		return retFalse;
	}
})();

/**
  * End Scrolling Table methods
  */

var browserIsIE=(document.all)?true:false;

function getClientTimezoneOffset() {
   var rightNow = new Date();
   var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   var temp = date1.toGMTString();
   var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var temp = date2.toGMTString();
   var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
   
   return hoursDiffStdTime;
}

function setCookie(name, value, expires, path, domain, secure) {
  var expiresIsDate = (typeof(expires) == "object") ? true : false;
  document.cookie = name + "=" + escape(value) +
					((expiresIsDate) ? "; expires=" + expires.toGMTString() : "") +
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					((secure) ? "; secure" : "");
}

function truncateSelectOptions(select, clipWidth) {
  if (select) {
    var charWidth = (browserIsIE) ? 5.2 : 6.2;
    var selectWidth = dojo.style.getBorderBoxWidth(select);
    //var selectWidth = select.offsetWidth;
    var maxOptionWidth = 30;
    if(selectWidth > charWidth)
    {
      maxOptionWidth = parseInt(selectWidth / charWidth) - clipWidth;
      maxOptionWidth = (maxOptionWidth < 0) ? 0 : maxOptionWidth;
    }
    
      for (cntOptions = 0; cntOptions < select.options.length - 1; cntOptions++) {
        var option = select.options[cntOptions];
      
        if (option.text.length > maxOptionWidth) {
          option.text = option.text.substring(0, maxOptionWidth) + "...";
        }
      }
    
  }
}


/**
 * Formats phone as 000-000-0000 while the user types.
 * Implemented by adding onkeyup="formatPhone(this)" to the input tag.
 */
function formatPhone(obj) {
  if(obj.value && obj.value.length > 4 && obj.value.length%4 == 1) {
    if(obj.value.charAt(obj.value.length - 2) != '-') {
      var newStr = obj.value.substr(0, obj.value.length - 2);
      newStr += "-";
      newStr += obj.value.substr(obj.value.length - 2, obj.value.length );
      obj.value = newStr;
    }
  }
}

/**
 * Formats SSN as 000-00-0000 while the user types.
 * Implemented by adding onkeyup="formatSsn(this)" to the input tag.
 */
function formatSsn(obj) {
  if(obj.value && obj.value.length > 3 && obj.value.length < 8 && obj.value.length%3 == 1) {
    if(obj.value.charAt(obj.value.length - 1) != '-') {
      var newStr = obj.value.substr(0, obj.value.length - 1);
      newStr += "-";
      newStr += obj.value.substr(obj.value.length - 1, obj.value.length );
      obj.value = newStr;
    }
  }
}

/**
 * Formats Tax ID as 00-0000000 while the user types.
 * Implemented by adding onkeyup="formatTaxId(this)" to the input tag.
 */
function formatTaxId(obj) {
  if(obj.value && obj.value.length > 3 && obj.value.length < 5 && obj.value.length%3 == 1) {
    if(obj.value.charAt(obj.value.length - 2) != '-') {
      var newStr = obj.value.substr(0, obj.value.length - 2);
      newStr += "-";
      newStr += obj.value.substr(obj.value.length - 2, obj.value.length );
      obj.value = newStr;
    }
  }
}

/**
 * Stub function in case anyone is still using this old thing.  Please start using createPrototypeWindowUrl(). 
 *
 * @deprecated
 */
function createPrototypeWindow(windowId,windowTitleText,width,height,url) {
  return prototypeWindowUrl(windowId,windowTitleText,width,height,url);
}

/**
 * Sets the class for all Prototype Windows and Dialogs.
 */
var prototypeWindowClass = "icentris";

/**
 * Sets the speed for which all Prototype Windows' and Dialogs' background overlays appear.
 */
var effectDuration = 0.25;

/**
 * Creates a new Protoype Window and loads a URL in an iframe within the Window.
 *
 * Uses what iCentris has deemed the "standard" properties.  This function may need 
 * to change as requirements change in the future.  Use this as much as possible rather 
 * than creating your own to keep the look and feel consistent throughout the suite.
 *
 * windowId                   - An id assinged to the Window.
 * windowTitleText            - Text placed in the Window title bar.
 * width                      - A number value of the Window width.
 * height                     - A number value of the Window height.
 * url                        - URL loaded in the iframe of the Window.
 * additionalWindowParameters - Any other standard Prototype Window parameter hash map  (see Prototype Window documentation).  (optional)
 *
 * See http://prototype-window.xilinus.com/documentation.html for help with Prototype Windows.
 */
function prototypeWindowUrl(windowId,windowTitleText,width,height,url,additionalWindowParameters) {
  var windowParameters = $H({
    className:      prototypeWindowClass,
    minimizable:    false,
    maximizable:    false,
    title:          windowTitleText,
    width:          width,
    height:         height,
    destroyOnClose: true,
    url:            url,
    effectOptions:  {duration: effectDuration},
    modal:          true,
    zIndex:  999
  });
  if(additionalWindowParameters != null) {
    windowParameters.merge(additionalWindowParameters);
  }
  var prototypeWindow = new Window(windowId,windowParameters);
  prototypeWindow.toFront();
  //Adding true creates the transparent overlay and locks the rest of the screen behind the window.
  prototypeWindow.showCenter(windowParameters.modal);
  return prototypeWindow;
}

/**
 * Creates a new Protoype Window and displays HTML within the Window.
 *
 * Uses what iCentris has deemed the "standard" properties.  This function may need 
 * to change as requirements change in the future.  Use this as much as possible rather 
 * than creating your own to keep the look and feel consistent throughout the suite.
 *
 * windowId                   - An id assinged to the Window.
 * windowTitleText            - Text placed in the Window title bar.
 * width                      - A number value of the Window width.
 * height                     - A number value of the Window height.
 * html                       - HTML content displayed in the Window.
 * additionalWindowParameters - Any other standard Prototype Window parameter hash map  (see Prototype Window documentation).  (optional)
 *
 * See http://prototype-window.xilinus.com/documentation.html for help with Prototype Windows.
 */
function prototypeWindowHtml(windowId,windowTitleText,width,height,html,additionalWindowParameters) {
  var windowParameters = $H({
    id:             windowId,
    className:      prototypeWindowClass,
    minimizable:    false,
    maximizable:    false,
    destroyOnClose: true,
    title:          windowTitleText,
    width:          width,
    height:         height,
    effectOptions:  {duration: effectDuration},
    modal:          true,
    zIndex:  999    
  });
  if(additionalWindowParameters != null) {
    windowParameters.merge(additionalWindowParameters);
  }
  var prototypeWindow = new Window(windowParameters);
  prototypeWindow.setHTMLContent(html);
  prototypeWindow.toFront();
  prototypeWindow.setDestroyOnClose();
  //Adding true creates the transparent overlay and locks the rest of the screen behind the window.
  prototypeWindow.showCenter(windowParameters.modal);
  return prototypeWindow;
}

/**
 * Utilities related to Prototype Windows.
 */
var PrototypeWindowUtils = $H({
	/**
	 * Closes any prototype window if this is called from within the window.
	 */
  closeWindow: function() {
    var windowParent = window.parent;
    if (windowParent && windowParent.Windows ) {
      windowParent.Windows.closeAll();
    } else if (window.opener) {
      window.close();
    }
  }
})

/**
 * Creates a new Protoype Confirm Dialog with a message.
 *
 * Uses what iCentris has deemed the "standard" properties.  This function may need 
 * to change as requirements change in the future.  Use this as much as possible rather 
 * than creating your own to keep the look and feel consistent throughout the suite.
 *
 * message                    - The message to display.
 * okLabel                    - Label for the Ok button.  (optional)
 * cancelLabel                - Label for the Cancel button.  (optional)
 * width                      - A number value of the Dialog width.
 * buttonClass                - CSS class assigned to the buttons.  Can also use #myDialogId.ok_button and #myDialogId.cancel_button to change individual buttons.  (optional)
 * okFunction                 - Function that will be run when Ok button is clicked.
 * cancelFunction             - Function that will be run when Cancel button is clicked.  (optional)
 * additionalWindowParameters - Any other standard Prototype Window parameter hash map (see Prototype Window documentation).  (optional)
 *
 * See http://prototype-window.xilinus.com/documentation.html for help with Prototype Windows.
 */
function prototypeConfirm(message,okLabel,cancelLabel,width,buttonClass,okFunction,cancelFunction,additionalWindowParameters) {
  if(typeof(okFunction) != "function") {
    okFunction = function() {
      //Creating empty anonymous function if no function was passed in
    };
  }
  if(typeof(cancelFunction) != "function") {
    cancelFunction = function() {
      //Creating empty anonymous function if no function was passed in
    };
  }
  var windowParameters = $H({
    width:         width,
    className:     prototypeWindowClass,
    effectOptions: {duration: effectDuration}
  });
  if(additionalWindowParameters != null) {
    windowParameters.merge(additionalWindowParameters);
  }
  var prototypeConfirm = Dialog.confirm (
    message, {
      windowParameters: windowParameters,
      okLabel:     okLabel,
      cancelLabel: cancelLabel,
      buttonClass: buttonClass,
      onCancel:    cancelFunction,
      onOk:        function(win) {
        okFunction();
        //Must return true to close the Dialog
        return true;
      }
    }
  );
  return prototypeConfirm;
}

/**
 * Creates a new Protoype Alert Dialog with a message.
 *
 * Uses what iCentris has deemed the "standard" properties.  This function may need 
 * to change as requirements change in the future.  Use this as much as possible rather 
 * than creating your own to keep the look and feel consistent throughout the suite.
 *
 * message                    - The message to display.
 * okLabel                    - Label for the Ok button.  (optional)
 * width                      - A number value of the Dialog width.
 * buttonClass                - CSS class assigned to the buttons.  Can also use #myDialogId.ok_button and #myDialogId.cancel_button to change individual buttons.  (optional)
 * okFunction                 - Function that will be run when Ok button is clicked.  (optional)
 * additionalWindowParameters - Any other standard Prototype Window parameter hash map  (see Prototype Window documentation).  (optional)
 *
 * See http://prototype-window.xilinus.com/documentation.html for help with Prototype Windows.
 */
function prototypeAlert(message,okLabel,width,buttonClass,okFunction,additionalWindowParameters) {
  if(typeof(okFunction) != "function") {
    okFunction = function() {
      //Creating empty anonymous function if no function was passed in
    };
  }
  var windowParameters = $H({
    width:         width,
    className:     prototypeWindowClass,
    effectOptions: {duration: effectDuration}
  });
  if(additionalWindowParameters != null) {
    windowParameters.merge(additionalWindowParameters);
  }
  var prototypeAlert = Dialog.alert (
    message, {
      windowParameters: windowParameters,
      okLabel:       okLabel,
      buttonClass:   buttonClass,
      onOk:          function(win) {
        okFunction();
        //Must return true to close the Dialog
        return true;
      }
    }
  );
  return prototypeAlert;
}

/**
 * Creates a new Protoype AJAX Alert Dialog and loads a URL into the alert via AJAX.
 *
 * Uses what iCentris has deemed the "standard" properties.  This function may need 
 * to change as requirements change in the future.  Use this as much as possible rather 
 * than creating your own to keep the look and feel consistent throughout the suite.
 *
 * url                        - The URL to load via AJAX.
 * okLabel                    - Label for the Ok button.  (optional)
 * width                      - A number value of the Dialog width.
 * buttonClass                - CSS class assigned to the buttons.  Can also use #myDialogId.ok_button and #myDialogId.cancel_button to change individual buttons.  (optional)
 * okFunction                 - Function that will be run when Ok button is clicked.  (optional)
 * additionalWindowParameters - Any other standard Prototype Window parameter hash map  (see Prototype Window documentation).  (optional)
 *
 * See http://prototype-window.xilinus.com/documentation.html for help with Prototype Windows.
 */
function prototypeAjaxAlert(url,okLabel,width,buttonClass,okFunction,additionalWindowParameters) {
  if(typeof(okFunction) != "function") {
    okFunction = function() {
      //Creating empty anonymous function if no function was passed in
    };
  }
  var windowParameters = $H({
    width:         width,
    className:     prototypeWindowClass,
    effectOptions: {duration: effectDuration}
  });
  if(additionalWindowParameters != null) {
    windowParameters.merge(additionalWindowParameters);
  }
  var prototypeAlert = Dialog.alert (
    {url: url}, {
      windowParameters: windowParameters,
      okLabel:          okLabel,
      buttonClass:      buttonClass,
      onOk:             function(win) {
        okFunction();
        //Must return true to close the Dialog
        return true;
      }
    }
  );
  return prototypeAlert;
}

/**
 * Creates a new Protoype Info Dialog with a message.
 *
 * Uses what iCentris has deemed the "standard" properties.  This function may need 
 * to change as requirements change in the future.  Use this as much as possible rather 
 * than creating your own to keep the look and feel consistent throughout the suite.
 *
 * message                    - The message to display.
 * width                      - A number value of the Dialog width.
 * height                     - A number value of the Dialog height.
 * showProgress               - Boolean to add a progress image (info found in the css file)
 * additionalWindowParameters - Any other standard Prototype Window parameter hash map  (see Prototype Window documentation).  (optional)
 *
 * See http://prototype-window.xilinus.com/documentation.html for help with Prototype Windows.
 */
function prototypeInfo(message,width,height,showProgress,additionalWindowParameters) {
  var windowParameters = $H({
    width:         width,
    height:        height,
    className:     prototypeWindowClass,
    effectOptions: {duration: effectDuration}
  });
  if(additionalWindowParameters != null) {
    windowParameters.merge(additionalWindowParameters);
  }
  var prototypeInfo = Dialog.info (
    message, {
      windowParameters: windowParameters,
      showProgress: showProgress
    }
  );
  return prototypeInfo;
}

/**
 * Closes the current prototype window by hitting the iframe's parent and running the closeAll() function on its Windows object.
 */
var PrototypeWindows = $H({
  closeWindow:function() {
    window.parent.Windows.closeAll();
  }
});

// Example: Must be 18 years-old to join, so pass in '18' to compute the high range as "today - 18years"
function getMaximumYear(yearsOffset) {
  var currentYear = new Date().getFullYear();
  var offsetYear = currentYear - yearsOffset;
  return offsetYear;
}

// Returns an actual date object (that can be compared with another one)
// Date format MUST be mm/dd/yyyy
function getDate(strValue) {
  if(strValue.length > 0) {
      var split = strValue.split("/");
      var date = new Date(split[2], split[0] - 1, split[1]);
      
      return date;
  }

  return null;
}

var Listing = Class.create();

Listing.prototype={
	initialize: function(listingname, value, isTop, childListings) {
	   this._value = value;
	   this._div = $(listingname + "-div");
	   this._divOptions = new Array();
	   this._childListings = new Array();
	   this._isTop = false;
	   
	   if(isTop){this._isTop=isTop;}
	   if(childListings){this._childListings = childListings;}
	   
	   var optionsName=listingname;
	   var index = optionsName.indexOf('_');
	   while(index >= 0) {
	   	optionsName = optionsName.replace(/_/,'.');
	   	index = optionsName.indexOf('_');
	   }
	  this._divOptions = this._div.getElementsBySelector('ul li input[name="'+optionsName+'"]');
	  
	  if(this._isTop) {
	  	this._disableAll();
	  }
	  this._selectDefault(this._isTop);
	},
		
	selectOption: function(option, nonRecursive) {
     var options = this._divOptions;
     var enabled = false;
     var _recursive = true;
     if(nonRecursive){_recursive=false;}
     
     for ( var i = 0; i < options.length; i++ ) {
     	var childListing = this._childListings[options[i].value]
     	var optiondiv = $(options[i].name + "-" + options[i].alt + "-div");
     	var children = optiondiv.getElementsByTagName('INPUT');
        enabled = !enabled && options[i].value == option.value;
        
        options[i].checked = enabled;
		optiondiv.style.display = enabled ? "block" : "none";
		
		if(enabled && childListing) {
			var childListingDiv = childListing.getDiv();
			var childListingDivChildren = childListingDiv.getElementsByTagName('INPUT');
			children = this._removeIgnoreChildren(children, childListingDivChildren);
		}
		this._toggleList(children, enabled);
				
		children = optiondiv.getElementsByTagName('SELECT');
		if(enabled && childListing) {
			var childListingDiv = childListing.getDiv();
			var childListingDivChildren = childListingDiv.getElementsByTagName('SELECT');
			children = this._removeIgnoreChildren(children, childListingDivChildren);
		}
		this._toggleList(children, enabled);
		
		if(_recursive && enabled && childListing) {
			childListing._enable();
		}
     }
   },
   
   getDiv: function() {
		return this._div;
   },
   
   _disableAll: function() {
		var options = this._divOptions;
		for ( var i = 0; i < options.length; i++ ) {
			var optiondiv = $(options[i].name + "-" + options[i].alt + "-div");
			
			var children = optiondiv.getElementsByTagName('INPUT');
			this._toggleList(children, false);	
			
			children = optiondiv.getElementsByTagName('SELECT');
			this._toggleList(children, false);
		}
	},
	
	_selectDefault:function(isTop) {
	   var optionToSelect = 0;
	   if ( this._value ) {
	      for ( var i = 0; i < this._divOptions.length; i++ ) {
	         var option = this._divOptions[i];
	         option.disabled=false;
	         if ( option.value == this._value ) {
	            optionToSelect = i;
	         }
	      }
	   }
	   this.selectOption(this._divOptions[optionToSelect], !isTop);
	},
   
   _enable:function() {
		var optionToSelect = 0;
		for ( var i = 0; i < this._divOptions.length; i++ ) {
		   var option = this._divOptions[i];
		   option.disabled=false;
		   if ( option.checked) {
		      optionToSelect = i;
		   }
		}
		this.selectOption(this._divOptions[optionToSelect]);
	},
   
   _removeIgnoreChildren: function(mainSet, ignoreSet) {
   		var resultArray = new Array();
   		for(var i=0;i<mainSet.length;i++){
   			var found=false;
   			for(var j=0;j<ignoreSet.length;j++) {
   				if(mainSet[i] == ignoreSet[j]) {
   					found =true;
   					break;
   				}
   			}
   			if(!found){
   				resultArray[resultArray.length]=mainSet[i];
   			}
   		}
   		return resultArray;
   },
   
   _toggleList: function(children, enabled) {
		for ( var j = 0; j < children.length; j++ ) {
			if(enabled && $(children[j]).hasClassName('ignoreEnabling')) {
				continue;
			}
			children[j].disabled = !enabled;
			if(enabled && typeof(children[j].onchange) == "function") {
				children[j].onchange();
			}
        }
   }
}

function ZipLookup(prefix) {
  var locatingCity;
  var locatingState;
  var locatingCounty;
  var locatingPostalCode;

  if ( prefix ) {
    setLocatingFields(prefix);
  }

  function setLocatingFields(prefix) {
    locatingCity = $(prefix + '_city');
    locatingState = $(prefix + '_stateProvinceGeoId');
    locatingCounty = $(prefix + '_county');
    locatingPostalCode = $(prefix + '_postalCode');
  }

  function setPageValues(city,state,county,zip){
    locatingCity.value = city;
    locatingState.value = state;
    locatingCounty.value = county;
    locatingPostalCode.value = zip;
  }
  
  function cancelLocate() {
    locatingPostalCode.focus();
  }

  function getLocation() {
    var zip = locatingPostalCode.value;
    var country = "USA";
    this.newWindow = window.open("/esuite/control/getCityStateZip?postalCode="+zip+"&returnFunction=ziplookup.setPageValues&cancelFunction=ziplookup.cancelLocate&country="+country,null,"height=400,width=400,status=yes,toolbar=no,menubar=no,location=no");
  }
}

var ziplookup = new ZipLookup();


function isValidDate(dateValue, format) {
	// Default is the American format
	if (typeof format != "string") { format = "MM/DD/YYYY"; }

	// Create a literal regular expression based on format
	var reLiteral = format.replace(/([$^.*+?=!:|\/\\\(\)\[\]\{\}])/g, "\\$1");

	// Convert all the tokens to RE elements
	reLiteral = reLiteral.replace( "YYYY", "([0-9]{4})" );
	reLiteral = reLiteral.replace( "MM", "(0[1-9]|10|11|12)" );
	reLiteral = reLiteral.replace( "M", "([1-9]|10|11|12)" );
	reLiteral = reLiteral.replace( "DDD", "(00[1-9]|0[1-9][0-9]|[12][0-9][0-9]|3[0-5][0-9]|36[0-6])" );
	reLiteral = reLiteral.replace( "DD", "(0[1-9]|[12][0-9]|30|31)" );
	reLiteral = reLiteral.replace( "D", "([1-9]|[12][0-9]|30|31)" );
	reLiteral = reLiteral.replace( "ww", "(0[1-9]|[1-4][0-9]|5[0-3])" );
	reLiteral = reLiteral.replace( "d", "([1-7])" );

	// Anchor pattern to begining and end of string
	reLiteral = "^" + reLiteral + "$";

	// Dynamic RE that parses the original format given
	var re = new RegExp(reLiteral);
	
	// Test if date is in a valid format
	if (!re.test(dateValue))  return false;

	// Parse date to get elements and check if date is valid
	// Assume valid values for date elements not given.
	var year = 0, month = 1, date = 1, dayofyear = 1, week = 1, day = 1;

	// Capture tokens
	var tokens = format.match( /(YYYY|MM|M|DDD|DD|D|ww|d)/g );

	// Capture date values
	var values = re.exec(dateValue);

	// Match up tokens with date values
	for (var i = 0; i < tokens.length; i++) {
		switch (tokens[i]) {
		case "YYYY":
			year = Number(values[i+1]); break;
		case "M":
		case "MM":
			month = Number(values[i+1]); break;
		case "D":
		case "DD":
			date = Number(values[i+1]); break;
		case "DDD":
			dayofyear = Number(values[i+1]); break;
		case "ww":
			week = Number(values[i+1]); break;
		case "d":
			day = Number(values[i+1]); break;
		}
	}

	// Leap years are divisible by 4, but not by 100, unless by 400
	var leapyear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));

	// 31st of a month with 30 days
	if (date == 31 && (month == 4 || month == 6 || month == 9 || month == 11)) return false; 

	// February 30th or 31st
	if (date >= 30 && month == 2) return false; 

	// February 29th outside a leap year
	if (date == 29 && month == 2 && !leapyear) return false; 
	if (dayofyear == 366 && !leapyear)  return false;

	return true;
}

String.prototype.repeat = function(multiplier) {
    var newString = '';

    for (var i = 0; i < multiplier; i++) {
        newString += this;
    }

    return newString;
} 

function numbersonly(myfield, e, dec)
{
	return formatPasses(myfield, e, dec, function (keychar, myField) {
		return ("0123456789".indexOf(keychar) > -1) ? true : false;
	});
}

function alphaonly(myfield, e, dec)
{
	return formatPasses(myfield, e, dec, function (keychar, myField) {
		return ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ".indexOf(keychar) > -1) ? true : false;
	});
}

function currencyFormat(myfield, e, dec)
{
  return formatPasses(myfield, e, dec, function (keychar, myField) {
		if((keychar == ".") && (myfield.value.indexOf(".") > -1)) return false;
		
		return ("0123456789.".indexOf(keychar) > -1) ? true : false;
	});
}

function formatPasses(myfield, e, dec, functionToCheck)
{
	var key, keychar;

	if (window.event) key = window.event.keyCode;
	else if (e) key = e.which;
	else return true;
	keychar = String.fromCharCode(key);
  
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) return true;

	// numbers
	else if (functionToCheck(keychar, myfield)) return true;
	else return false;
}

function executeCallbackFromDialog(callbackFunctionString, arg1, arg2, arg3 /*, arg4, etc... */ ) {
        if (!callbackFunctionString){
                alert("You must specify a callback function to execute as the 1st parameter.")
                return false;
        }
        
        var lastIndexOfDotOperator = callbackFunctionString.lastIndexOf('.');
        
        if(lastIndexOfDotOperator == -1) {
                alert("You must give the fully qualified path to your function.\n\nAll functions will have a parent. If function x() is defined in the global namespace of the parent window the callback string that you would pass is either 'parent.x' or 'opener.x' depending on wether the window is an iframe or an actual window.\n\nPlease try to avoid using the global namespace though. 'parent.personalEntry.x' is much more preferable than 'parent.x'.");
                return false;
        }
        var callbackParentString = callbackFunctionString.substring(0, lastIndexOfDotOperator);
        var callbackParent, callbackFunction;
        try { callbackParent = eval(callbackParentString); } 
        catch(e) {
                customErrorMsg("There was a problem evaluating the callbackParent. eval('"+callbackParentString+"')", e);
                return false;
        }

        try { callbackFunction = eval(callbackFunctionString); } 
        catch(e) {
                customErrorMsg("There was a problem evaluating the callbackFunction. eval('"+callbackFunctionString+"')", e);
                return false;
        }

        var argsCount = arguments.length;
        var argsToPass = new Array();
        // The first argument passed is the callback function, the rest are passed to the callback function.
        for (var i = 1; i < argsCount; i++) {
                argsToPass[argsToPass.length] = arguments[i];   
        }
        
        try { callbackFunction.apply(callbackParent, argsToPass); } 
        catch (e) {
                customErrorMsg("There was a problem executing the callbackFunction with the given parent and args. "+callbackFunctionString+"()", e);
        }
}

function customErrorMsg(message, error) {
        alert(message+"\n\nError Name:"+error.name+"\nError Message: "+error.message ); 
}

function getUtf8ByteCount(value) {
	var countMe = __fixNewlinesTextarea(value);
	var escapedStr = encodeURI(countMe);
	if (escapedStr.indexOf("%") != -1) {
	    var count = escapedStr.split("%").length - 1;
	    if (count == 0) count++;  //perverse case; can't happen with real UTF-8
	    var tmp = escapedStr.length - (count * 3);
	    count = count + tmp;
	} else {
	    count = escapedStr.length;
	}
	return count;
}

function areCookiesEnabled() {
  var theCookie = "" + document.cookie;
  var ind = theCookie.indexOf("JSESSIONID");
  return ind!=-1;
}

function errorOnDisabledCookies() {
  if ( !areCookiesEnabled() ) {
    location.replace('nocookies?originalRequest=' + location.href);
  }
}

/** Will resize the element to scroll after a number of row elements is add */
function scrollAtXRows(element, rowElementName, rowCount) {
   if (!rowCount) rowCount = 5;
   var container = $(element);
   var rows = container.getElementsByTagName(rowElementName);
   if( rows && rows.length >= rowCount) {
      container.addClassName("scrollAtXRows");
   } else {
      container.removeClassName("scrollAtXRows");
   }
 }

//Used for ic:checkbox tag, to assign the value of bean depending on
//whether the checkbox is checked or not.

function transformCheckBoxValue(checkboxId, hiddenFieldId, onValue, offValue ) {
	var checkbox1 = $(checkboxId);
	var hiddenField = $(hiddenFieldId);
	if(checkbox1.checked == true) {
		hiddenField.value = onValue;
	} else {
		hiddenField.value = offValue;
	}
}