var focused = false;
var poptimer;
var opWindows = new Array();
var currWindow = 0;		
var newwin;
var wintype;
var childTimer;
var windowName;
var areChildWindowsOpen;
var reloadRequired = false;
var correctHeight = 0;
var correctWidth = 0;
var openingTab = 'tab0';
var tabAutoSize = false;
var overrideFinishButton = false;
var currentGroup;
var currentGroupElements = new Array();
var formGroupElements 	= new Array();
var formGroupNames 		= new Array();
var tabDivs = new Array();
var closeAllWindows = false;
var windowHeightAdjustment = 0;
var cfcTarget = 'parent';

//minimize search window so it cannot be double-clicked on
function Minimize() 
{
window.innerWidth = 100;
window.innerHeight = 100;
window.screenX = screen.width;
window.screenY = screen.height;
alwaysLowered = true;
}

function forceFocus() {
	focused = true;
}
function focusForm() {
	if (focused) return;
	// If we are a popup, move it to the top
	if (window.name == 'pop') {
		//poptimer = setTimeout('window.close()',5000);
	}
	// If there is a form in the doc...
	if (document.forms) {
		
		// Wizard Handling where we want the focus to go to the Finish button
		// If it is available
		if (document.getElementById('wiz_finish') && !overrideFinishButton) {
			document.getElementById('wiz_finish').focus();
			return true;
		}
		// If there is something on the form
		if (document.getElementById('errorFocus') && document.getElementById('errorFocus').value == '')  {
			if (document.forms[0]==null) return;
			// If we are in a tab, get the correct start point
			ot = document.getElementById(openingTab + '_starting_element');
			var theElems = document.forms[0].elements
			var i=0;
			var gotStartElement = false;
			// loop over the elements until finding a non-hidden one
			for (i = 0; i < theElems.length; i++) {
			    var theElem = theElems[i];
			    if (ot) {
				    /**
				    * In order to get the correct focused element,
				    * cycle until we find the hidden field at the
				    * top of the tab
				    */
				    if (theElem.id == ot.id) {
					    gotStartElement = true;
					    continue;
				    }
				    if (!gotStartElement) continue;
			    }
			    if (theElem.type && theElem.type == "hidden") {
				    continue;
			    }
			    if (theElem.tabIndex > 1) {
				    continue;
			    }
			    if (theElem.type == 'text' && theElem.readOnly) {
					    continue;
			    }
			    if (theElem.disabled || theElem.className == 'disabled') continue;

				// focus on the first non-hidden element
                // focus NOT needed on Deletion
                var formMode = '';
                if ( document.getElementById('mode') )
					formMode = document.getElementById('mode').value
                if ( theElem.id.length > 0 && formMode != 'DELETE' ) {
					document.getElementById(theElem.id).focus();
                    //select NOT needed on Select List
                    if ( theElem.getAttribute('type') != 'select-one' && theElem.getAttribute('type') != 'select-multiple' && theElem.getAttribute('type') != null)
						document.getElementById(theElem.id).select();
                }
				break;

			}
		} else if (document.getElementById('errorFocus')) {
			var theElem = document.getElementById('errorFocus').value;
			if (document.getElementById(theElem)) {
				if (document.getElementById(theElem).getAttribute('type') == 'hidden') {
					var chkElem = theElem + 'CHK';
					if (document.getElementById(chkElem))
						theElem = chkElem;
					else
						theElem = 'month_' + theElem;
				}

				if (document.getElementById(theElem)) document.getElementById(theElem).focus(); 
			}
		}
	}
}
////////////////////////////////////////////////
// Functions to auto-open a text box to a bigger size
////////////////////////////////////////////////////
xbox_init = false;
xbox_obj = false;
function showMagicTextbox() {
	var obj = arguments[0];
	var olibHeight = (arguments[1]) ? arguments[1] : obj.offsetHeight * 3 ;

	xbox_obj = obj;
	olibWidth = obj.offsetWidth - 4;
	xbox_init = true;
	text = '<textarea id=xbox_data style="width:' + olibWidth + 'px;height:' + olibHeight + 'px;"></textarea>';
	text = '<div class=asearch_wrapper style="width:' + olibWidth + 'px;height:' + olibHeight + 'px;">' + text + '</div>'; 
	window.setTimeout('xbox_handler()',200)
	return overlib(text, HEIGHT,10,WIDTH,olibWidth,ANCHOR,obj.id, ANCHORY, -2);
}
function xbox_handler() {
	if (!document.getElementById('xbox_data'))
		return;
	if (xbox_init) {
		document.getElementById('xbox_data').value = xbox_obj.value;
		document.getElementById('xbox_data').focus();
		document.getElementById('xbox_data').onblur = function() { xbox_close(xbox_obj); };
	}
	xbox_init = false;
}		
function xbox_close(obj) {
	obj.value = document.getElementById('xbox_data').value;
	window.setTimeout('xbox_refocus_init()',200);

	return nd();
}
function xbox_refocus_init() {
	obj = xbox_obj;
	need_button = false;
	for (i=1;i<=obj.form.length;i++) {
		o = obj.form[( getIndex( obj ) + i )];
		if (!o)
			continue;
		
	    // If we find a field called _starting_element, we have moved into a new tab, 
		// so ignore every element until we find a submit or cancel button and 
		// put the focus there
		var regExp = /_starting_element/;
        if (regExp.test(o.id) && !need_button) {
			need_button = true;
			continue;
		}
		if (o.type == 'hidden')
			continue;
		if (need_button && o.type != 'button' && o.type != 'submit')
			continue;
		o.focus();
		return;
	}
}
/////////////////////////////////////////////////////////////////

function noaccnumPopUp(windowName,proProg,recid,extraArgs,accountNumField,poptype){
  if (poptype == 'search') { wintype = 'search'; }
  else { wintype = 'normal'; }
  
  var ctab = document.getElementById('currenttab').value;
  var cprog = document.getElementById('program').value;
  var sess = document.getElementById('SESSION').value;
  var unhooked = false;
  var accountNumber = document.getElementById(accountNumField).value;
  var URL = proProg + "?recid=" + recid + extraArgs + accountNumber + "&ctab=" + ctab + "&cprog=" + cprog + "&SESSION=" + sess;

  var argLength = URL.length - proProg.length;
  if (argLength > 900 && argLength < 1024)
  {
	  alert('Danger - arglength is ' + argLength + ', close to IIS maximum of 1024');
  }
   if (argLength > 1024)
  {
	  alert('Danger - arglength is ' + argLength + ',  greater than IIS maximum of 1024, Stopping Action');
	  return false;
  }

  w = window.availWidth;
  h = window.availHeight;
  var popW = 300, popH = 200;
  var leftPos = (w-popW)/2, topPos = (h-popH)/2;
  topPos=100;
  leftPos=200;
  minsize=10;
  if (windowName == 'fpdf')
  {
	  minsize=600;
  }
  if (windowName == 'UNDOCKED' || windowName == 'searchpop')
  {
	  windowName = rand(100);
	  unhooked = true;
  }
  if (unhooked)
  {
	window.open(URL, windowName ,"menubars=no,location=no,status=yes,top=" + topPos + ",left=" + leftPos + ",height=" + minsize + ",width=" + minsize + ",resizable=yes,scrollbars=yes");
  } else {
	opWindows[currWindow++] = window.open(URL, windowName ,"menubars=no,location=no,top=" + topPos + ",left=" + leftPos + ",height=" + minsize + ",width=" + minsize + ",resizable=yes,scrollbars=yes");
  }
}
   
function openPopup(windowName,proProg,recid,extraArgs,poptype){
  if (poptype == 'search') { wintype = 'search'; }
  else { wintype = 'normal'; }
  
  var ctab = document.getElementById('currenttab').value;
  var cprog = document.getElementById('program').value;
  var sess = escape(document.getElementById('SESSION').value);
  var unhooked = false;

  //////////123//////////
  //this grabs the value from a hidden field and will add it to the URL passed in
  //this passes the array of dependencies to the opening window
  var dependentAr='';
  var obj = document.getElementById('dependentAr' + recid);
  
  if (obj) //grid calls that have several possible records, id = dependentAr + the recid of each record
  {
	  dependentAr='&dependentAr=' + escape(obj.value);
  }
  else //non grid calls with single record, id = just dependentAr
  {
	  obj = document.getElementById('dependentAr');
	 
	  if (obj)
	  {
	      dependentAr='&dependentAr=' + escape(obj.value);
      }
  }

  var URL = proProg + "?POP=1&recid=" + recid + extraArgs + "&ctab=" + ctab + "&cprog=" + cprog + "&SESSION=" + sess + dependentAr;

  var argLength = URL.length - proProg.length;
  if (argLength > 900 && argLength < 1024)
  {
	  alert('Danger - arglength is ' + argLength + ', close to IIS maximum of 1024');
  }
   if (argLength > 1024)
  {
	  alert('Danger - arglength is ' + argLength + ',  greater than IIS maximum of 1024, Stopping Action');
	  return;
  }


  w = window.availWidth;
  h = window.availHeight;
  var popW = 300, popH = 200;
  var leftPos = (w-popW)/2, topPos = (h-popH)/2;
  topPos=100;
  leftPos=200;
  minHeight=10;
  minWidth=10;
  if (windowName == 'fpdf' || windowName == 'docpop')
  {
	  minHeight=768;
	  minWidth=1024;
	  unhooked = true;
  }
  if (windowName == 'UNDOCKED' || windowName == 'searchpop')
  {
	  windowName = rand(100);
	  unhooked = true;
  }
  if (unhooked)
  {
	window.open(URL, windowName ,"menubar=no,location=0,top=" + topPos + ",left=" + leftPos + ",height=" + minHeight + ",width=" + minWidth + ",resizable=yes,scrollbars=yes");
  } else {
  //following line enables status bar at bottom of window
	var childWin = windowName;
	opWindows[currWindow++] = window.open(URL, windowName ,"menubar=no,status=0,location=0,top=" + topPos + ",left=" + leftPos + ",height=" + minHeight + ",width=" + minWidth + ",resizable=yes,scrollbars=yes");
	areChildWindowsOpen = setInterval("checkForChildren()",1000);
  }
}
// ***********************************************************
// removed by KMN
// ***********************************************************
// Set the Main menu to reload or popups to auto close 
//function startUnload() {
//	if (window.name != 'main' && window.name != '') {
//		poptimer = setTimeout('window.close()',600000);
//	} else {
//		poptimer = setTimeout('refreshMe()',120000);
//	}
//}	

//function stopUnload() {
//	if (window.name != 'main') {
//		poptimer = clearTimeout(poptimer);
//	}
//}
// *********************************************************
//pop-up timer functions
// - timeout function for determining if a timer has been set or rescinded
// - function call in html looks like this: <body onLoad="poptimeOut('start',time);">
var timer;
var timerID;
var counter;
var rawtime;
function poptimeOut(motion,time) {
	if (window.name != 'main' && window.name != '') {
		if ((motion=='start')&&(time>0)) {
			counter=time;
			time = time*60000;
			rawtime = time;
			count = time/1000;
			timer = setTimeout('window.close()', time);
//   			timerID = setTimeout("countdown(time)",1000);
			if(timerID) { clearTimeout(timerID); }
			countDown();
			//self.status = time/60000 + " minutes until this window closes.";
		} else {
			clearTimeout(timer);
		}
	} else if (time==0) {
		return;
	} else {
	} 
}

/** 
	*countdown is a function to enable automatic update of status bar for poptimeout time
	*/
function countDown() {
    self.status = counter-- + ' minutes until this window closes.';
    if (counter != -1)
      timerID=setTimeout('countDown()',60000);
}
/**
  * forceReload is always called from a child window
  */
function forceReload() {
	reloadRequired=true;
}
/**
  * checkForChildren is called from an interval in openpopup
  * to see if child windows exist for this window
  */
function checkForChildren() {
	// Cycle through child windows checking the status
	// This is done once a second
	if (closeAllWindows)
	{
		if (window.opener) 
		{ 
			if (window.name!='main')
			{
				window.opener.closeAllWindows = true; 
				if (cfcTarget == 'parent')
					window.opener.close();
				else
					window.close();
			}
			else closeAllWindows = false;
		}
		else if (window.parent)
		{ 
			if (window.name!='main')
			{
				if (window.parent.opener)
				{
					window.parent.opener.closeAllWindows = true;
				}
				
				window.parent.close();
			}
			else closeAllWindows = false;
		}
	}
	for(i=0; i<opWindows.length; i++) {
		if (opWindows[i] && !opWindows[i].closed){
			return;
		}
	}

	// At this point, all child windows that were open 
	// have now been closed
	clearInterval(areChildWindowsOpen);
	// if reloadRequired = false, no updates were done so dont reload this page.
	if (reloadRequired == false) return;
	
	reloadRequired = false;
	// If this is a child window, force the parent to reload when we close this window
	if (window.opener)
	{
		if(window.opener.forceReload()) window.opener.forceReload();
	} else if (window.parent){
		// If its an iframe, theres a parent but no opener
		// This often breaks the cascading effect, but its
		// a resonble limitation
		//if(window.parent.forceReload()) window.parent.forceReload();
	} else {
		// No way to pass back status or we are on the bottom
		// level of the windows
	}
	window.location.reload();
}

/**
  * Function prevents orphan windows staying open
  * if the sidebar is used while children are open
  * meaning the parent/child relationship is lost
  */
function closeChildren() {
	// Cycle through child windows closing them
	for(i=0; i<opWindows.length; i++) {
		if (opWindows[i] && !opWindows[i].closed){
			opWindows[i].close();
		}
	}
}

// - child window function for stopping timer in parent window.  Implementation syntax:
// -  onLoad="childWindow()"
function childWindow() {
	if (window.name != 'main' && window.name != '' && window.opener) {
		if (window.opener)	{
			if (window.opener.poptimeOut) {
				window.opener.poptimeOut('stop',0);
				window.opener.status = '';
			}
		}
	}
}

//window resizing and moving functions
function resizeOuterTo(w,h) {
	top.resizeTo(w,h);
	return;
	
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			top.outerWidth=w;
			top.outerHeight=h;
		} else top.resizeTo(w,h);
	}
}

function is_ie7()
{
	var d, dom, nu='', brow='', ie, ie7;
	var ns4, release_date='', rv_full='';
	var win, old, lin, ie5mac, ie5xwin, konq, saf, op, op4, op5, op6, op7;

	d=document;
	n=navigator;
	nav=n.appVersion;
	nan=n.appName;
	nua=n.userAgent;

	ie=((nua.indexOf('MSIE')!=-1)&&!op);
	if (ie)
	{
		str_pos=nua.indexOf('MSIE');
		nu=nua.substr((str_pos+5),3);
		brow = 'Microsoft Internet Explorer';
	}
	ie7=(ie&&(nu.substring(0,1)==7));
	if (ie7) return true;
}

function windowSize(windowWidth,windowHeight) {

	var winMult = 1.2;
    var ie7 = is_ie7();
    
	windowHeight = windowHeight + windowHeightAdjustment;
	//alert('window'+windowWidth+'x'+windowHeight);
	//alert('screen'+screen.width+'x'+screen.height);
	if(windowWidth > 0) formWidth=windowWidth * winMult;
	if(windowHeight > 0) 
      {
		if (ie7==true)
		{
 			formHeight=(windowHeight + 30) * winMult;
		} else {
  			formHeight=windowHeight * winMult;
		}
	}

	/*
	 * In special cases we are going to override the
	 * height of the window, where we are using
	 * a grid in a popup window, we are going
	 * to modify the height to fit the appropriate
	 * number of lines defined by $GRPP, unless the
	 * number is greater than the window height
	 */

	if (document.getElementById('baseGRPP')) // Only appears on grid pages
	{
		grpp = document.getElementById('baseGRPP').value;
		if (grpp == 0)
			grpp = 15;
		formHeight = 350; //Base value for header and footer
		formHeight += (20 * grpp); // Add 20 pixels for each row
		maxFormHeight = screen.height - 100;
		
		if (formHeight > maxFormHeight)
		{
			formHeight = maxFormHeight;
		}
	} 
	resizeOuterTo(formWidth,formHeight);
	
	// now move the window so it is centered on the screen
	self.moveTo(screen.width/2 - formWidth/2,screen.height/2 - formHeight/2);

	// now Expand the tabframe inside so that it looks nice.
	// This currently only works in IE
	if (document.getElementById('tabFormatter'))  {
		if (document.getElementById('postgroup'))
		{
			document.getElementById('tabFormatter').style.height = windowHeight - 100;

		} else {
			document.getElementById('tabFormatter').style.height = windowHeight - 50;
		}
	}

	//this is a fix for ie7 with low res
	if (ie7==1)
	{
		window.resizeTo(formWidth,formHeight);
	}
}

/*
 * Function resizes popup window back to defined size
 * if it is dragged or maximized
 */
function correctWindowSize(){
	if (correctHeight == 0)
	{
		return;
	}
	resizeOuterTo(correctWidth,correctHeight);
	self.moveTo(screen.width/2 - correctWidth/2,screen.height/2 - correctHeight/2);

	return;
}

var submitted=false;
function submitForm() {
	if (window.preSubmitForm) {
		response = preSubmitForm();
		if (response = false)
			return false;
	}
	if (!submitted) {
		if (document.getElementById('postgroup')){
			//alert('postgroup');
			document.getElementById('postgroup').style.display = 'none';
		} //else
			//alert('no postgroup');
		// set cursor to hourglass to give users something to look at
		obj = document.getElementById('maindiv');
		if (obj) obj.style.cursor='wait';
		return submitted=true;
	}
	alert('You only need to click the button once....');
	return false;
}

function moveToTop() {
	var i=0;
	if (window.name == 'main') return;
	for(i=0; i<opWindows.length; i++) {
		if (opWindows[i] && !opWindows[i].closed) {
			return; /* only on top if no children */
		}
	}
	window.focus();
	window.focusForm();
	//ontop = setTimeout('moveToTop()',1000);
}

function toggle(theElem){
	var i=0;
	var tabbutton;
    for (i=0;i<20;i++) {
		var allTabs = 'tab' + i;
		if(document.getElementById(allTabs)){
			if (document.getElementById(theElem) == document.getElementById(allTabs)) {
				document.getElementById(allTabs).style.display = '';
				var currenttab = document.getElementById('currenttab');
				currenttab.value = 'tab' + i;
				tabbutton = document.getElementById('tabbutton' + i);
				if (tabbutton) tabbutton.className='tabbutton_active';
				// Enable Any Divs inside the tab
				if (tabDivs!= '') {
					divs = tabDivs[i].split(',');
					for(j=0; j<divs.length; j++) {
						if (divs[j] == '') continue;
						document.getElementById(divs[j]).style.display = '';
					}
				}

			} else {
				document.getElementById(allTabs).style.display = 'none';
				if (document.getElementById('tabbutton' + i)) {
					tabbutton = document.getElementById('tabbutton' + i);
					tabbutton.className='tabbutton';
				}
				//disable any tabs inside the div
				if (tabDivs != '') {
					divs = tabDivs[i].split(',');
					for(j=0; j<divs.length; j++) {
						if (divs[j] == '') continue;
							document.getElementById(divs[j]).style.display = 'none';
					}
				}
			}
		}
    }
	//document.getElementById('loadTable').style.display = 'none';

	if (document.getElementById('formWidth'))
	{
		var  x = document.getElementById('formWidth').value;
		var  y = document.getElementById('formHeight').value;
		windowSize(x,y);
	}
	if (document.getElementById('openingtab'))
		document.getElementById('openingtab').value = theElem;
}

function doToggle() {

	if (document.getElementById('openingtab') && document.getElementById('openingtab').value != '')
	{
		toggle(document.getElementById('openingtab').value);
		openingTab = document.getElementById('openingtab').value;
		document.getElementById('openingtab').value = '';
		return true;
	}
	
	if (document.getElementById('currenttab'))
	{
		toggle(document.getElementById('currenttab').value);
	}
	//alert(document.body.clientHeight);
	//window.scrollTo(1,1);
}
function doErrors() {
	if (document.getElementById('errors'))
	{
		var em = document.getElementById('errors').value;
		if (em=='') return 0;
		alert(em);
	}
	return 1;
}
function checkWhenLostFocus() {
	if (window.name == 'treeframe') 
	{
		if(window.parent.main.checkWhenLostFocus) window.parent.main.checkWhenLostFocus();
		return;
	}
    var i = 0;
	for(i=0; i<opWindows.length; i++)
		if (opWindows[i] && !opWindows[i].closed) {
			opWindows[i].focus();
// following line commented out to fix mozilla problem where clicking on a window one level above
// a popup would cause form fields within the top pop-up to become inaccessible
//			opWindows[i].focusForm();
	}
}

function refreshParent() {
	if (window.name == 'main' || window.name == '')
	{
		return false;
	}
	//window.opener.document.location.reload();
	return true;
}

/**
  * Functions for generating random numbers
  */
rnd.today=new Date();
rnd.seed=rnd.today.getTime();

function rnd() {
        rnd.seed = (rnd.seed*9301+49297) % 233280;
        return rnd.seed/(233280.0);
};

function rand(number) {
        return Math.ceil(rnd()*number);
};


//new functions for auto-tab to next field
var field_length=0;
function TabNext(obj,event,len) {
	//added return on 7/2 to disable
	//return;
	if (event == "down") {
		field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != field_length) {
			field_length=obj.value.length;
			if (field_length == len) {
				if (obj.form[( getIndex( obj ) + 1 ) % obj.form.length].type != "hidden") {
					obj.form[( getIndex( obj ) + 1 ) % obj.form.length].focus();
				} else {
					obj.form[( getIndex( obj ) + 2 ) % obj.form.length].focus(); 
				}
				}
			}
		}
	}
function getIndex( input ) { 
	var index = -1, i = 0, found = false; 
	while ( i < input.form.length && index == -1 ) 
	if ( input.form[i] == input ) { 
		index = i; 
	} else { 
		i++; 
	} 
	return index; 
} 

//functions for auto-tab to next field
//var isNN = ( navigator.appName.indexOf( "Netscape" ) != -1 ); 
//
//function autoTab( input,len, e ) { 
//	var keyCode	= ( isNN ) ? e.which : e.keyCode; 
//	var filter	= ( isNN ) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46]; 
//	if( input.value.length >= len && !containsElement( filter, keyCode )) { 
//	input.value = input.value.slice( 0, len ); 
//	input.form[( getIndex( input ) + 1 ) % input.form.length].focus(); 
//	} 
//	return true; 
//} 
// 
//function containsElement( arr, ele ) { 
///	var found = false, index = 0; 
//	while( !found && index < arr.length ) 
//	if( arr[index] == ele ) { 
//		found = true; 
//	} else { 
//		index++; 
//	} 
//	return found; 
//} 
// 
//function getIndex( input ) { 
//	var index = -1, i = 0, found = false; 
//	while ( i < input.form.length && index == -1 ) 
//	if ( input.form[i] == input ) { 
//		index = i; 
//	} else { 
//		i++; 
//	} 
//	return index; 
//} 
//end functions for auto-tab to next field

//Calendar picker clear date code
//  Author: CCB
// Date: 05/26/05
function clear_calendar(str_target_mo,str_target_dd,str_target_yy) {
	document.getElementById(str_target_mo).value='';
	document.getElementById(str_target_dd).value='';
	document.getElementById(str_target_yy).value='';
}
/////////////////////////////////////////////////////////////
// This is the OLD calendar which should go away as soon as possible
////////////////////////////////////////////////////////////
//Calendar picker code
// Title: Timestamp picker
// Description: See the demo at url
// URL: http://us.geocities.com/tspicker/
// Script featured on: http://javascriptkit.com/script/script2/timestamp.shtml
// Version: 1.0
// Date: 12-05-2001 (mm-dd-yyyy)
// Author: Denis Gritcyuk <denis@softcomplex.com>; <tspicker@yahoo.com>
//
// 6/8/04 - Modified by CB for ADG
//					to split date values up
//					for use with a mm_dd_yyyy input system
//					with separate input boxes
//

function show_calendar( str_target_mo, str_datetime_mo, str_target_dd, str_datetime_dd, str_target_yy, str_datetime_yy ) {
	var display_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	var arr_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	var week_days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
	var n_weekstart = 1; // day week starts from (normally 0 or 1)

    var charMonth, mm, yy;
    var dt_prev_yy_val, dt_next_yy_val;
    var dt_prev_month_val, dt_next_month_val;

    //Initializes date
	if ((str_datetime_dd == '') || (str_datetime_mo=='') || (str_datetime_yy=='')) { 
		str_datetime='';
	}
    else {
	    var str_datetime = str_datetime_dd + "-" + str_datetime_mo + "-" + str_datetime_yy;
	}
	var dt_datetime = (str_datetime == null  || str_datetime =='' ?  new Date() : str2dt(str_datetime));


    //Previous Month Date  --------------------------------
	var dt_prev_month = new Date(dt_datetime);
    //Prev Year
	dt_prev_yy_val = dt_prev_month.getYear();
	// Mozilla returns years after 1900
	// IE returns real year
	if (dt_prev_yy_val < 2000) {
		dt_prev_yy_val = 1900 + dt_prev_yy_val;
	}
    //Prev Month
    charMonth = dt_prev_month.toString();
	ARR= charMonth.split(" "); //month
    mm = 1;
    for ( var i=0; i < 12; i++ ) {
        if ( ARR[1] == arr_months[i] ) {
            mm = i + 1;
            break;
        }
    }
    if ( mm == 1 ) {
        dt_prev_month_val = 12
        dt_prev_yy_val--;
    }
    else {
	    dt_prev_month_val = mm - 1;
    }

	dt_prev_month = str2dt(1 + "-" + dt_prev_month_val + "-" + dt_prev_yy_val);
        

	//Next month Date  ------------------------------------
	var dt_next_month = new Date(dt_datetime);
    //Next Year
	var dt_next_yy_val = dt_next_month.getYear();
	if (dt_next_yy_val < 2000) {
		dt_next_yy_val = 1900 + dt_next_yy_val;
	}
    //Next Month
    charMonth = dt_next_month.toString();
	ARR= charMonth.split(" "); //month
    mm = 1;
    for ( var i=0; i < 12; i++ ) {
        if ( ARR[1] == arr_months[i] ) {
            mm = i + 1;
            break;
        }
    }
    if ( mm == 12 ) {
        dt_next_month_val = 1
        dt_next_yy_val++;
    }
    else {
	    dt_next_month_val = mm + 1;
    }

	dt_next_month = str2dt(1 + "-" + dt_next_month_val + "-" + dt_next_yy_val);


	var dt_firstday = new Date(dt_datetime);
	dt_firstday.setDate(1);
	dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);

	// html generation (feel free to tune it for your particular application)
	// print calendar header
	var str_buffer = new String (
		"<html>\n"+
		"<head>\n"+
		"	<title>Calendar</title>\n"+
		"</head>\n"+
		"<body bgcolor=\"White\">\n"+
		"<table class=\"clsOTable\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n"+
		"<tr><td bgcolor=\"#4682B4\">\n"+
		"<table cellspacing=\"1\" cellpadding=\"3\" border=\"0\" width=\"100%\">\n"+
		"<tr>\n	<td bgcolor=\"#4682B4\"><a href=\"javascript:window.opener.show_calendar('"+
		str_target_mo+"', '"+ dt_prev_month_val +"','"+str_target_dd+"','01','"+str_target_yy+"','" + dt_prev_yy_val + "');\">"+
		"<img src=\"/adg/supporting/images/cal_prev.gif\" width=\"16\" height=\"16\" border=\"0\""+
		" alt=\"previous month\"></a></td>\n"+
		"	<td bgcolor=\"#4682B4\" colspan=\"5\">"+
		"<font color=\"white\" face=\"tahoma, verdana\" size=\"2\">"
		+display_months[dt_datetime.getMonth()]+" "+dt_datetime.getFullYear()+"</font></td>\n"+
		"	<td bgcolor=\"#4682B4\" align=\"right\"><a href=\"javascript:window.opener.show_calendar('"
		+str_target_mo+"', '"+dt_next_month_val+"','"+str_target_dd+"','01','"+str_target_yy+"','"+dt_next_yy_val +"');\">"+
		"<img src=\"/adg/supporting/images/cal_next.gif\" width=\"16\" height=\"16\" border=\"0\""+
		" alt=\"next month\"></a></td>\n</tr>\n"
	);

	var dt_current_day = new Date(dt_firstday);
	// print weekdays titles
	str_buffer += "<tr>\n";
	for ( var n=0; n<7; n++ ) {
		str_buffer += "	<td bgcolor=\"#87CEFA\">"+"<font color=\"white\" face=\"tahoma, verdana\" size=\"2\">"+
		week_days[(n_weekstart+n)%7]+"</font></td>\n";
    }
	// print calendar table
	str_buffer += "</tr>\n";
	while ( dt_current_day.getMonth() == dt_datetime.getMonth()  ||  dt_current_day.getMonth() == dt_firstday.getMonth() ) {
		// print row header
		str_buffer += "<tr>\n";
		for ( var n_current_wday=0; n_current_wday < 7; n_current_wday++ ) {
				if ( dt_current_day.getDate() == dt_datetime.getDate() && dt_current_day.getMonth() == dt_datetime.getMonth() )
					// print current date
					str_buffer += "	<td bgcolor=\"#FFB6C1\" align=\"right\">";
				else if (dt_current_day.getDay() == 0 || dt_current_day.getDay() == 6)
					// weekend days
					str_buffer += "	<td bgcolor=\"#DBEAF5\" align=\"right\">";
				else
					// print working days of current month
					str_buffer += "	<td bgcolor=\"white\" align=\"right\">";

				if ( dt_current_day.getMonth() == dt_datetime.getMonth() ) {
					// print days of current month
					var month_val;
					month_val = dt_current_day.getMonth() + 1;
					if ( month_val < 10 ) {
						month_val = "0"+month_val;
					}

					var dd_val;
					dd_val = dt_current_day.getDate();
					if ( dd_val < 10 ) {
						dd_val = "0"+dd_val;
					}

					var yy_val;
					yy_val = dt_current_day.getFullYear();

					str_buffer += "<a href=\"javascript:window.opener.document.getElementById('"+str_target_mo+"').value='"+month_val+"';"+
					"window.opener.document.getElementById('"+str_target_dd+"').value='"+dd_val+"';"+
					"window.opener.document.getElementById('"+str_target_yy+"').value='"+yy_val+"';"+
					"window.opener.document.getElementById('"+str_target_mo+"').focus();" + 
					"window.close();\">"+
					"<font color=\"black\" face=\"tahoma, verdana\" size=\"2px\">";
                }
			    else {
					var month_val;
					month_val = dt_current_day.getMonth() + 1;
					if ( month_val < 10 ) {
						month_val = "0"+month_val;
					}

					var dd_val;
					dd_val = dt_current_day.getDate();
					if ( dd_val < 10 ) {
						dd_val = "0"+dd_val;
					}

					var yy_val;
					yy_val = dt_current_day.getFullYear();
					
					// print days of other months
					str_buffer += "<a href=\"javascript:window.opener.document.getElementById('"+str_target_mo+"').value='"+month_val+"';"+
					"window.opener.document.getElementById('"+str_target_dd+"').value='"+dd_val+"';"+
					"window.opener.document.getElementById('"+str_target_yy+"').value='"+yy_val+"';"+
					"window.opener.document.getElementById('"+str_target_mo+"').focus();" + 
					"window.close();\">"+
					"<font color=\"gray\" face=\"tahoma, verdana\" size=\"2px\">";
				}
				str_buffer += dt_current_day.getDate()+"</font></a></td>\n";
				dt_current_day.setDate(dt_current_day.getDate()+1);
		} //for
		// print row footer
		str_buffer += "</tr>\n";
	}
	// print calendar footer
	str_buffer +=
        "</tr>\n</td>\n</table>\n" +
		"</body>\n" +
		"</html>\n";

	var vWinCal = window.open("", "Calendar", "width=210,height=210,status=no,resizable=yes,top=200,left=200");
	vWinCal.opener = self;
	var calc_doc = vWinCal.document;
	calc_doc.write (str_buffer);
	calc_doc.close();
}
/////////////////////////////////////////////////////////////////////////////
// END OF OLD CALENDAR
////////////////////////////////////////////////////////////////////////////////
// datetime parsing and formatting routines. modify them if you wish other datetime format
function str2dt (str_datetime) {
//var re_date = /^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/;
var re_date = /^(\d+)\-(\d+)\-(\d+)$/;
	if ( !re_date.exec(str_datetime) )
		return alert("Invalid Datetime format: "+ str_datetime);
//	return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1, RegExp.$4, RegExp.$5, RegExp.$6));
	return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1));
}

function dt2dtstr (dt_datetime) {
	return (new String (
			dt_datetime.getDate()+"-"+(dt_datetime.getMonth()+1)+"-"+dt_datetime.getFullYear()+" "));
}

function dt2tmstr (dt_datetime) {
	return (new String (
			dt_datetime.getHours()+":"+dt_datetime.getMinutes()+":"+dt_datetime.getSeconds()));
}

//end calendar picker code  -------------------------------

//code to change alpha chars to numeric for phone numbers
  function toNumeric(checkString)
  {
    var newString = "";
    var i = 0;
    var ch = "";
    for (i = 0; i < checkString.length; i++) {
      ch = checkString.substring(i, i+1);
      if ((ch >= "a" && ch <= "c") || (ch >= "A" && ch <= "C")) {
        newString += "2";
      }
      else if ((ch >= "d" && ch <= "f") || (ch >= "D" && ch <= "F")) {
        newString += "3";
      }
      else if ((ch >= "g" && ch <= "i") || (ch >= "G" && ch <= "I")) {
        newString += "4";
      }
      else if ((ch >= "j" && ch <= "l") || (ch >= "J" && ch <= "L")) {
        newString += "5";
      }
      else if ((ch >= "m" && ch <= "o") || (ch >= "M" && ch <= "O")) {
        newString += "6";
      }
      else if ((ch >= "p" && ch <= "s") || (ch >= "P" && ch <= "S")) {
        newString += "7";
      }
      else if ((ch >= "t" && ch <= "v") || (ch >= "T" && ch <= "V")) {
        newString += "8";
      }
      else if ((ch >= "w" && ch <= "z") || (ch >= "W" && ch <= "Z")) {
        newString += "9";
      }
      else if (ch >= "0" && ch <= "9") {
        newString += ch;
      }
      else if ((ch == "-") || (ch == "(") || (ch == ")") || (ch == " ")) {
        newString += ch;
      }
    }
    return newString;
  }
  //end alpha-numeric convert routine

// Enables/Disables Date Picker Fields
// argument 1 - the name of the field
// argument 2 - true to disable, false to enable
function datePickerDisable(field,disable) {
	objY = document.getElementById('year_' + field);
	objM = document.getElementById('month_' + field);
	objD = document.getElementById('day_' + field);
	objI = document.getElementById('image_' + field);
	objE = document.getElementById('eraser_' + field);
	if (!objY) return true;
	if (disable) {
		objY.disabled=true;
		objY.className='disabled';
		objM.disabled=true;
		objM.className='disabled';
		objD.disabled=true;
		objD.className='disabled';
		objI.src='/adg/supporting/images/invisible.gif';
		objI.height='1';
		objI.width='1';
		objE.src='/adg/supporting/images/invisible.gif';
		objE.height='1';
		objE.width='1';

	} else {
		objY.disabled=false;
		objY.className='';
		objM.disabled=false;
		objM.className='';
		objD.disabled=false;
		objD.className='';
		objI.src='/adg/supporting/images/calendar.gif';
		objI.height='16';
		objI.width='16';
		objI.className='';
		objE.src='/adg/supporting/images/calendar_delete.gif';
		objE.height='16';
		objE.width='16';
		objE.className='';

	}
}

//following three functions are for radioGroup radio buttons on forms
//function disableGroup(formName, groupName, booleanDisabled) {
function disableGroup(groupName, booleanDisabled) {
  // handle an empty group
  if (!document.groupedForm) return true;
  var formName = document.groupedForm;
  for (var i=0; i<formName.elements.length; i++) {
     if (formName.elements[i].id == groupName) {
      formName.elements[i].disabled = booleanDisabled;
    }
  }
}

function disableSpan(state,element,hide) {
	
	var rObj = document.getElementById('row_' + element);
	var lObj = document.getElementById('label_' + element);
	var IndObj = document.getElementById('img_dupe_' + element);
	var obj = document.getElementById(element);
	var cObj = document.getElementById(element + 'CHK');
	var sObj = document.getElementById(element + '[]');
	if (state == 'disable'){
		if (lObj)
			lObj.className = 'disabledLabel';
		//if (obj.getAttribute('type')=='radio') {
		//	var thisField = obj.getElementsByTagName('input')[x].getAttribute('id');
//			disableGroup(groupedForm,thisField,true);
		//	disableGroup(thisField,true);
		//}
		if (obj){
			obj.disabled=true;
			if (obj.getAttribute('type')=='text') {
				obj.className = 'disabled';
			}
		}
		if (cObj) 
			cObj.disabled = true;
		if (sObj) 
			sObj.disabled = true;

		// It might be a date field
		datePickerDisable(element,true);
		
		//May be a dupe icon
		if (IndObj)
			IndObj.src='/adg/supporting/images/duplicate_no_icon.gif';

		if (rObj && hide) {
			rObj.style.display = 'none';
			return;
		}
	

	} else {

		if (lObj)
			lObj.className = 'label';
		//if (obj.getAttribute('type')=='radio') {
		//	var thisField = obj.getElementsByTagName('input')[x].getAttribute('id');
//			disableGroup(groupedForm,thisField,true);
		//	disableGroup(thisField,true);
		//}
		if (obj) {
			obj.disabled=false;
			if (obj.getAttribute('type')=='text') {
				obj.className = '';
			}
		}
		if (cObj)
			cObj.disabled = false;
		if (sObj) 
			sObj.disabled = false;
			
		// It might be a date field
		datePickerDisable(element,false);
		
		//May be a dupe icon
		if (IndObj)
			IndObj.src='/adg/supporting/images/duplicate_icon.gif';

		if (rObj && hide) {
			rObj.style.display = '';
		}

	}
}

function enableSpan(div,groupe) {
	//alert('here');
	//div is the current element, the one we want to action
	//groupe is the starting name of all other elements in the same group, that we want to 
	//do the opposite to
	hide = false;
	var re = new RegExp(groupe,"g");
	
	for (f in formGroupNames) {
		if (isNaN(f)) continue;
		//alert ('here2');
		if (formGroupNames[f].search(re) >= 0){
			var elements = formGroupElements[f];
			for (e in elements) {
				if (formGroupNames[f] == div) 
					switchOnElement(elements[e]); //disableSpan('enable',elements[e],hide); //change made by Chris on 07/28/10
				else
					switchOffElement(elements[e]); //disableSpan('disable',elements[e],hide);
			}
		}
	}
	return;
}
//end radioGroup functions

// following function for single checkboxGroup enabling, also uses disableSpan and disableGroup functions above
function enableRSpan(field,div,hide) {
   	var obj = document.getElementById(field);
    if ( obj == null ) return;
	var re = new RegExp('^' + field,'g');
	for (f in formGroupNames) {
		if (isNaN(f)) continue;
		if(typeof(window[f]) == 'function') continue;
		if(typeof(formGroupNames[f]) == 'function') continue;
		if (formGroupNames[f].search(re) >= 0){
			var elements = formGroupElements[f];
			for (e in elements) {
				if (obj.checked == true)
					disableSpan('enable',elements[e],hide);
				else
					disableSpan('disable',elements[e],hide);
			}
		}
	}
}
// end checkboxGroup functions

function urlDecode(str){
    str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

var tab = 
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

/* the decodeBase64 function has been replaced with a faster one further down the common.js,
     but the encode remains the same  */

var END_OF_INPUT = -1;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}
function readBase64(){    
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}
function encodeBase64(str){
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT){
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT){
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT){
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            } else {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76){
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}
function readReverseBase64(){   
    if (!base64Str) return END_OF_INPUT;
    while (true){      
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    } 
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}



var digitArray = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
function toHex(n){
    var result = ''
    var start = true;
    for (var i=32; i>0;){
        i-=4;
        var digit = (n>>i) & 0xf;
        if (!start || digit != 0){
            start = false;
            result += digitArray[digit];
        }
    }
    return (result==''?'0':result);
}

function pad(str, len, pad){
    var result = str;
    for (var i=str.length; i<len; i++){
        result = pad + result;
    }
    return result;
}


/* An string prototype that removes leading and trailing spaces */
/* Use as x = y.trim(); */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim


function encodeHex(str){
    var result = "";
    for (var i=0; i<str.length; i++){
        result += pad(toHex(str.charCodeAt(i)&0xff),2,'0');
    }
    return result;
}

function decodeHex(str){
    str = str.replace(new RegExp("s/[^0-9a-zA-Z]//g"));
    var result = "";
    var nextchar = "";
    for (var i=0; i<str.length; i++){
        nextchar += str.charAt(i);
        if (nextchar.length == 2){
            result += ntos(eval('0x'+nextchar));
            nextchar = "";
        }
    }
    return result;
    
}

function copier(from,to)
{
	var possCheckBox = to.substr(0,to.length - 3);
	d = document.getElementById(to);

	if (document.getElementById(to).type == 'checkbox' && document.getElementById(possCheckBox)) 
	{
		if (document.getElementById(from).value == 1) 
		{
			document.getElementById(to).checked = true;
			document.getElementById(possCheckBox).value=1;
		}
	} 
	else if (document.getElementById(to).type == 'radio')
	{
		if(to=='dupe_' + from);
			document.getElementById(to).checked = true;
	}
	else
	{
		document.getElementById(to).value = document.getElementById(from).value
	}
} 

function dupeAll() 
{
	var x = document.getElementsByTagName('*');

	for (var i=0;i<x.length;i++)
	{
		var idname = x[i].id;
		var dupeidname = 'dupe_'+idname;

		if ((dupeidname.length > 5)&&(document.getElementById(dupeidname))) 
		{
			var thefield = document.getElementById(dupeidname);

			if (thefield.value != '') 
			{
				copier(dupeidname,idname);			
			}
		}
	}
}

function hidedupeText() {
	if (document.getElementById('DUPES')) {
		document.getElementById('dupetext').style.display = 'block';
	} 
}


/*Rafael Raposo edited function*/
//function to change content
function changecontent(){
    if (!document.getElementById("fscroller"))
	  return;
  if (index>=fcontent.length)
    index=0
  if (DOM2){
    document.getElementById("fscroller").style.color="rgb("+startcolor[0]+", "+startcolor[1]+", "+startcolor[2]+")"
    document.getElementById("fscroller").innerHTML=begintag+fcontent[index]+closetag
    if (fadelinks)
      linkcolorchange(1);
    colorfade(1, 15);
  }
  else if (ie4)
    document.all.fscroller.innerHTML=begintag+fcontent[index]+closetag;
  index++
}

// Functions to switch form fields read-only/read-write using ADG Standardized styling
function switchOnElement(oSwitch,noDisable) {

	var pattern = /^row_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch))
			document.getElementById(oSwitch).style.display='';
		return;
	}

	var pattern = /^label_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch))
			document.getElementById(oSwitch).className='label';
		return;
	}
 	if (!document.getElementById(oSwitch))
		return;

	var pattern = /^search_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch))
		{
			document.getElementById(oSwitch).style.cursor='pointer';
			document.getElementById(oSwitch).src='/adg/supporting/images/search.gif';
		}
		return;
	}

	var pattern = /_date_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch)){
			datePickerDisable(oSwitch,false);
		}
		return;
	}

	if (noDisable)
		document.getElementById(oSwitch).readOnly=false;
	else
		document.getElementById(oSwitch).disabled=false;
	var pattern = /select/;
	otype = document.getElementById(oSwitch).type; 
	if (pattern.test(otype))
		document.getElementById(oSwitch).className='sselect';
	else
		document.getElementById(oSwitch).className='';
	//To enable a check box
	oChchk = oSwitch + 'CHK';
	if (document.getElementById(oChchk)) {
		document.getElementById(oChchk).disabled=false;
		document.getElementById(oChchk).className='';
	}
	//Enable associated label
	oChlab = 'label_' + oSwitch;
	if (document.getElementById(oChlab)) {
		document.getElementById(oChlab).className='label';
	}

	oChlab = 'search_' + oSwitch;
	if (document.getElementById(oChlab)) {
		document.getElementById(oChlab).style.cursor='pointer';
		document.getElementById(oChlab).src='/adg/supporting/images/search.gif';
	}
}
function switchOffElement(oSwitch,noDisable) {
	var pattern = /^row_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch))
			document.getElementById(oSwitch).style.display='none';
		return;
	}

	var pattern = /^label_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch))
			document.getElementById(oSwitch).className='disabledLabel';
		return;
	}

	var pattern = /^search_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch))
		{
			document.getElementById(oSwitch).style.cursor='default';
			document.getElementById(oSwitch).src='/adg/supporting/images/empty.gif';
		}
		return;
	}

	var pattern = /_date_/;
	if (pattern.test(oSwitch)) {
		if(document.getElementById(oSwitch)){
			datePickerDisable(oSwitch,true);
		}
		return;
	}

	if (!document.getElementById(oSwitch))
		return
	if (noDisable)
		document.getElementById(oSwitch).readOnly=true;
	else
		document.getElementById(oSwitch).disabled=true;
	if (document.getElementById(oSwitch).type == 'textarea')
		document.getElementById(oSwitch).className='disabled_ta';
	else
		document.getElementById(oSwitch).className='disabled';
	//To disable a check box
	oChchk = oSwitch + 'CHK';
	if (document.getElementById(oChchk)) {
		document.getElementById(oChchk).disabled=true;
		document.getElementById(oChchk).className='disabled';
	}
	// Gray out associated label
	oChlab = 'label_' + oSwitch;
	if (document.getElementById(oChlab)) {
		document.getElementById(oChlab).className='disabledLabel';
	}

	oChlab = 'search_' + oSwitch;
	if (document.getElementById(oChlab)) {
		document.getElementById(oChlab).style.cursor='default';
		document.getElementById(oChlab).src='/adg/supporting/images/empty.gif';
	}
}
var iSwitcherCounter = 0;
var arSwitcherParents = new Array();
var arSwitcherValues = new Array();
var arSwitcherChildren = new Array();
var arSwitcherDirection = new Array();
var arSwitcherIsRadio = new Array();
var arSwitcherHide = new Array();
var arSwitcherNoDisable = new Array();

switcher = setInterval("fieldSwitcher()",1000);
function fieldSwitcher() 
{
	for (i=0;i<arSwitcherParents.length;i++) 
	{
		if (!document.getElementById(arSwitcherParents[i]))
		{
			continue;
		}

		oEl = document.getElementById(arSwitcherParents[i]).value;
		// Cannot test value zero properly so pad it out to something else
		if (oEl==0 || oEl=='')
			oEl = '!0!';

		oIc = document.getElementById(arSwitcherParents[i]).checked;
		oValAr = arSwitcherValues[i].split(',');
		oDir = arSwitcherDirection[i];
		oCh = arSwitcherChildren[i];
		oIsRadio = arSwitcherIsRadio[i];
		oNoDisable = arSwitcherNoDisable[i];
		for (j=0;j<oCh.length;j++) 
		{
			turnOn = false;

			for (k=0;k<oValAr.length;k++) 
			{
				oVal = oValAr[k];
				if (oVal == '0')
					regoVal = '^!0!$';
				else
					regoVal = '^' + oVal + '$';

				var reVal = new RegExp(regoVal);

				if ((oIsRadio == 1 && oIc == true && oDir == 0) 
				|| (oIsRadio == 1 && oIc == false && oDir == 1))
				{
					turnOn = true;
				}

				if ((((reVal.test(oEl) && oVal != '') || (oVal == '' && oEl == '!0!')) && oDir == 1 && oIsRadio == 0) 
				|| ((!reVal.test(oEl) || (oVal == '' && oEl != '!0!')) && oDir == 0 && oIsRadio == 0)) 
				{
					turnOn = true;
				} 
			}

			if(turnOn) switchOnElement(oCh[j],oNoDisable);
			else switchOffElement(oCh[j],oNoDisable);
		}
	}
}

function setSwitcher(pName,pVal,pChildren,pDir,pIsRadio,hide,noDisable) 
{
	// Cannot test value zero properly so pad it out to something else
	if (pVal == '0')
		pVal = '!0!';

	if (pVal=='')
		pVal = '!0!'
	
	arSwitcherParents[iSwitcherCounter]   = pName;
	arSwitcherValues[iSwitcherCounter]    = pVal;
	arSwitcherIsRadio[iSwitcherCounter]   = pIsRadio;
	arSwitcherDirection[iSwitcherCounter] = pDir;
	obt = pChildren.split(',');
	arSwitcherChildren[iSwitcherCounter]  = obt;
	//arSwitcherHide[iSwitcherCounter]    = hide;
	arSwitcherNoDisable[iSwitcherCounter] = noDisable;
	
	iSwitcherCounter++;
}



// colorfade() partially by Marcio Galli for Netscape Communications.  ////////////
// Modified by Dynamicdrive.com

function linkcolorchange(step){
  var obj=document.getElementById("fscroller").getElementsByTagName("A");
  if (obj.length>0){
    for (i=0;i<obj.length;i++)
      obj[i].style.color=getstepcolor(step);
  }
}

/*Rafael Raposo edited function*/
var fadecounter;
function colorfade(step) {
  if (!document.getElementById("fscroller"))
	  return;
  if(step<=maxsteps) {	
    document.getElementById("fscroller").style.color=getstepcolor(step);
    if (fadelinks)
      linkcolorchange(step);
    step++;
    fadecounter=setTimeout("colorfade("+step+")",stepdelay);
  }else{
    clearTimeout(fadecounter);
    document.getElementById("fscroller").style.color="rgb("+endcolor[0]+", "+endcolor[1]+", "+endcolor[2]+")";
    setTimeout("changecontent()", delay);
	
  }   
}

/*Rafael Raposo's new function*/
function getstepcolor(step) {
  var diff
  var newcolor=new Array(3);
  for(var i=0;i<3;i++) {
    diff = (startcolor[i]-endcolor[i]);
    if(diff > 0) {
      newcolor[i] = startcolor[i]-(Math.round((diff/maxsteps))*step);
    } else {
      newcolor[i] = startcolor[i]+(Math.round((Math.abs(diff)/maxsteps))*step);
    }
  }
  return ("rgb(" + newcolor[0] + ", " + newcolor[1] + ", " + newcolor[2] + ")");
}

////////////////////////////////////////////////////////////////////////////////////
// This section is for the new ajax driven calendar function.
// The popup is automatically anchored to the calendar image at the right side of the date field
////////////////////////////////////////////////////////////////////////////////////
document.write('<input type=hidden id=calendar_data_receiver>');
document.write('<div id=div_calendar_data></div>');
// Fires an ajax request asking for the search form to be popped up
var cal_anchor_id = '';
var cal_anchor_base = '';
function loadCalendarFromSource(anchor) {
	cal_anchor_id	= anchor.id;
	cal_anchor_base = anchor.id.substr(5);
	mfield = document.getElementById('month' + cal_anchor_base);
	m = mfield.value;
	dfield = document.getElementById('day' + cal_anchor_base);
	d = dfield.value;
	yfield = document.getElementById('year' + cal_anchor_base);
	y = yfield.value;
	loadCalendar(m,d,y);
}

function loadCalendar(m,d,y){
 	rawSendReq('div_calendar_data','/adg/adg/ajax/load_calendar.php','calDataReceiver()','anchor,month,day,year,ajax_session', cal_anchor_base + ',' + m + ',' + d + ',' + y + ',' + SESSION);
}

// Receives data for the basic search frame and pops up the overlib
//calendar_closer is a style defined in activecalendar.css
//using the font tag is stupid, but i cant get it to work in the stylesheet
function calDataReceiver() {
	text = decodeBase64(document.getElementById('calendar_data_receiver').value);
	title = 'Calendar';
	text = '<div style="border:1px solid black">' + text + '</div><div class=calendar_closer onClick="return&nbsp;nd()"><font color=white>Close</font></div>'; 
	return overlib(text, HEIGHT,100,WIDTH,150,ANCHOR,cal_anchor_id,ANCHORX,5);
}

function calPickedDate(y,m,d) {
	mfield = document.getElementById('month' + cal_anchor_base);
	mfield.value = m;
	dfield = document.getElementById('day' + cal_anchor_base);
	dfield.value = d;
	yfield = document.getElementById('year' + cal_anchor_base);
	yfield.value = y;
        yfield.focus();
        yfield.select();        
	cClick(); //This is part of the overlib suite to close the window
}

function printDiv(oid) {

	id = document.getElementById(oid);
	d = id.innerHTML;
	newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
	newwin.document.write('<HTML>\n<HEAD>\n')
	newwin.document.write('<TITLE>Print Page</TITLE>\n')
	newwin.document.write("<link rel='stylesheet' href='/adg/supporting/style/inquiry_print.css' type='text/css'>\n");
	newwin.document.write('<script>\n')
	newwin.document.write('function chkstate(){\n')
	newwin.document.write('if(document.readyState=="complete"){\n')
	newwin.document.write('window.close()\n')
	newwin.document.write('}\n')
	newwin.document.write('else{\n')
	newwin.document.write('setTimeout("chkstate()",2000)\n')
	newwin.document.write('}\n')
	newwin.document.write('}\n')
	newwin.document.write('function print_win(){\n')
	newwin.document.write('window.print();\n')
	newwin.document.write('chkstate();\n')
	newwin.document.write('}\n')
	newwin.document.write('<\/script>\n')
	newwin.document.write('</HEAD>\n')
	newwin.document.write('<BODY onload="print_win()">\n')
	newwin.document.write(d)
	newwin.document.write('</BODY>\n')
	newwin.document.write('</HTML>\n')
	newwin.document.close()
}

////////////////////////////////////////////////////////////////////////
// This section is for the left and right scrolling cell in the inquiry screen
//////////////////////////////////////////////////////////////////////

function cellScrollLeft(identifier) {
	startPoint = document.getElementById('d_o_' + identifier).innerHTML;
	if (startPoint <= 0) {
		document.getElementById('d_o_' + identifier).innerHTML = 0;
		return;
	}
	startPoint--;
	text = document.getElementById('d_h_' + identifier).innerHTML;
	t = text.substr(startPoint);
	document.getElementById('d_o_' + identifier).innerHTML = startPoint;
	document.getElementById('d_s_' + identifier).innerHTML = t;
}
function cellScrollRight(identifier,viewport) {
	startPoint = document.getElementById('d_o_' + identifier).innerHTML;
	text = document.getElementById('d_h_' + identifier).innerHTML;
	textlen = text.length;
	if (startPoint >= textlen) {
		document.getElementById('d_o_' + identifier).innerHTML = startPoint;
		return;
	}
	startPoint++;
	t = text.substr(startPoint);
	document.getElementById('d_o_' + identifier).innerHTML = startPoint;
	document.getElementById('d_s_' + identifier).innerHTML = t;
}

/////////////////////////////////////////////////////////////////////////
// This section is for the popup search for help in the grid and elsewhere
/////////////////////////////////////////////////////////////////////////
if (!document.getElementById('search_help_hidden_field'))
	document.write('<input type=hidden id=search_help_hidden_field>');

function loadSearchHelp(parent_tables,show) {
	rawSendReq(	'',
				'/adg/adg/ajax/grid_showsearch.php',
				'searchDataReceiver()',
				'parent_tables,show,ajax_session', 
				parent_tables + ',' + show + ',' + SESSION);
}

function searchDataReceiver() {
	text = decodeBase64(document.getElementById('search_help_hidden_field').value);
	return overlib(text, CSSCLASS,BGCLASS,'gridpopb',FGCLASS,'gridpopf', CENTERPOPUP,TIMEOUT,3000);
}


/* A new version of the decodeBase64 for speed rendering ajax data on internet explorer */
function decodeBase64(str) {
	return Base64.decode(str);
}


/*
Copyright (c) 2008 Fred Palmer fred.palmer_at_gmail.com

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
function StringBuffer()
{ 
    this.buffer = []; 
} 

StringBuffer.prototype.append = function append(string)
{ 
    this.buffer.push(string); 
    return this; 
}; 

StringBuffer.prototype.toString = function toString()
{ 
    return this.buffer.join(""); 
}; 

var Base64 =
{
    codex : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    encode : function (input)
    {
        var output = new StringBuffer();

        var enumerator = new Utf8EncodeEnumerator(input);
        while (enumerator.moveNext())
        {
            var chr1 = enumerator.current;

            enumerator.moveNext();
            var chr2 = enumerator.current;

            enumerator.moveNext();
            var chr3 = enumerator.current;

            var enc1 = chr1 >> 2;
            var enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            var enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            var enc4 = chr3 & 63;

            if (isNaN(chr2))
            {
                enc3 = enc4 = 64;
            }
            else if (isNaN(chr3))
            {
                enc4 = 64;
            }

            output.append(this.codex.charAt(enc1) + this.codex.charAt(enc2) + this.codex.charAt(enc3) + this.codex.charAt(enc4));
        }

        return output.toString();
    },

    decode : function (input)
    {
        var output = new StringBuffer();

        var enumerator = new Base64DecodeEnumerator(input);
        while (enumerator.moveNext())
        {
            var charCode = enumerator.current;

            if (charCode < 128)
                output.append(String.fromCharCode(charCode));
            else if ((charCode > 191) && (charCode < 224))
            {
                enumerator.moveNext();
                var charCode2 = enumerator.current;

                output.append(String.fromCharCode(((charCode & 31) << 6) | (charCode2 & 63)));
            }
            else
            {
                enumerator.moveNext();
                var charCode2 = enumerator.current;

                enumerator.moveNext();
                var charCode3 = enumerator.current;

                output.append(String.fromCharCode(((charCode & 15) << 12) | ((charCode2 & 63) << 6) | (charCode3 & 63)));
            }
        }

        return output.toString();
    }
}


function Utf8EncodeEnumerator(input)
{
    this._input = input;
    this._index = -1;
    this._buffer = [];
}

Utf8EncodeEnumerator.prototype =
{
    current: Number.NaN,

    moveNext: function()
    {
        if (this._buffer.length > 0)
        {
            this.current = this._buffer.shift();
            return true;
        }
        else if (this._index >= (this._input.length - 1))
        {
            this.current = Number.NaN;
            return false;
        }
        else
        {
            var charCode = this._input.charCodeAt(++this._index);

            // "\r\n" -> "\n"
            //
            if ((charCode == 13) && (this._input.charCodeAt(this._index + 1) == 10))
            {
                charCode = 10;
                this._index += 2;
            }

            if (charCode < 128)
            {
                this.current = charCode;
            }
            else if ((charCode > 127) && (charCode < 2048))
            {
                this.current = (charCode >> 6) | 192;
                this._buffer.push((charCode & 63) | 128);
            }
            else
            {
                this.current = (charCode >> 12) | 224;
                this._buffer.push(((charCode >> 6) & 63) | 128);
                this._buffer.push((charCode & 63) | 128);
            }

            return true;
        }
    }
}

function Base64DecodeEnumerator(input)
{
    this._input = input;
    this._index = -1;
    this._buffer = [];
}

Base64DecodeEnumerator.prototype =
{
    current: 64,

    moveNext: function()
    {
        if (this._buffer.length > 0)
        {
            this.current = this._buffer.shift();
            return true;
        }
        else if (this._index >= (this._input.length - 1))
        {
            this.current = 64;
            return false;
        }
        else
        {
            var enc1 = Base64.codex.indexOf(this._input.charAt(++this._index));
            var enc2 = Base64.codex.indexOf(this._input.charAt(++this._index));
            var enc3 = Base64.codex.indexOf(this._input.charAt(++this._index));
            var enc4 = Base64.codex.indexOf(this._input.charAt(++this._index));

            var chr1 = (enc1 << 2) | (enc2 >> 4);
            var chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            var chr3 = ((enc3 & 3) << 6) | enc4;

            this.current = chr1;

            if (enc3 != 64)
                this._buffer.push(chr2);

            if (enc4 != 64)
                this._buffer.push(chr3);

            return true;
        }
    }
};
var teaHandler = '';
function testEmailAddress(handler) {
	teaHandler = handler;
	fld = 'email_address' + handler;
	email_address = document.getElementById(fld).value;
	etr = 'email_test_response' + handler; 
	div = 'email_test_div' + handler;
	if (email_address == '') {
		alert('Please enter an email address to check');
		document.getElementById(fld).focus();
		return false;
	}
	if (echeck(email_address) == false)
		return false;
 	rawSendReq(div,'/adg/adg/ajax/check_email.php','teaDataReceiver()','email_address,response_field,ajax_session', email_address + ',' + etr + ',' + SESSION);
	return true;
} 
function teaDataReceiver() {
	response_id = 'email_test_response' + teaHandler;
	text = decodeBase64(document.getElementById(response_id).value);
	alert(text);
	return;
	title = 'Email Address Validation';
	text = '<div class=asearch_wrapper style="width:280px">' + text + '</div>'; 
	return overlib(text, CSSCLASS,BGCLASS,'asearch_bg',FGCLASS,'asearch_fg', CAPTIONFONTCLASS,'asearch_caption', CLOSEFONTCLASS,'asearch_close', HEIGHT,200,WIDTH,282,ANCHOR,anchor_id,ANCHORX,5,CAPTION,title,STICKY,CLOSECLICK,CLOSETEXT, 'X');
}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid Email Address")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid Email Address")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid Email Address")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid Email Address")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid Email Address")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid Email Address")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid Email Address")
		    return false
		 }

 		 return true					
	}

function addProgramToFavorites(alias) {
	rawSendReq('ajax_ok','/adg/adg/ajax/addfavorite.php','aptfReceiver()','alias,mode,ajax_session',alias + ',A,' + window.top.SESSION);
}
function aptfReceiver() {
	window.opener.reloadFavorites();
	alert('The Program Was Added To Favorites');
}
/************************************************
Function to google map an address
************************************************/
function googleMapMe(handler) {
	var addressline = '';
	var o = document.getElementById('non_us_address' + handler);
	if (o.value == 1){
		alert('Sorry, cannot map foreign addresses');
		return;
	}
	var o = document.getElementById('address_pobox' + handler);
	if (o.value > '') {
		alert('Sorry, cannot map PO Boxes');
		return;
	}
	
	var number = document.getElementById('address_number' + handler).value;
	var direction = document.getElementById('address_direction' + handler).value;
	var name = document.getElementById('address_name' + handler).value;
	var type = document.getElementById('address_type' + handler).value;
	var post = document.getElementById('address_post_directional' + handler).value;
	var extra = document.getElementById('address_extra' + handler).value;
	var city = document.getElementById('address_city' + handler).value;
	
	if (city.value == '') {
		alert('Sorry, cannot map address without a City');
		return;
	}
	var state = document.getElementById('address_state' + handler).value;
	if (state == '') {
		alert('Sorry, cannot map address without a State');
		return;
	}
	var zip = document.getElementById('zip_5' + handler).value;

	addressline =  number + ' ' + direction + ' ' + name + ' ' + type + ' ' + post + ' ' + extra + ' ,' + city + ' ,' + state;
	
	if (zip != '')
		addressline = addressline + ' ,' + zip;
	extraArgs = '&run=' + ADG_ROOT_DIR + '/adg/gmap_by_address.php&addressline=' + encodeBase64(addressline);
	openPopup('gmap','main.php',0,extraArgs);
	return true;

}
/************************************************
Function to google map an address
************************************************/
function googleLatLongMe(handler,text,prefix) {
	var addressline = '';
	var lat = document.getElementById(prefix + 'latitude' + handler).value;
	if (lat == 0){
		alert('Sorry, cannot map Latitude Zero');
		return;
	}
	if (lat < -180 || lat > 180){
		alert('Latitude must be between -180 and 180');
		return;
	}
	
	var longt = document.getElementById(prefix + 'longitude' + handler).value;
	if (longt == 0) {
		alert('Sorry, cannot map Longitude Zero');
		return;
	}
	if (longt < -180 || longt > 180){
		alert('Longitude must be between -180 and 180');
		return;
	}

	poptext = '';
	if (text != '') {
		poptext = document.getElementById(text + handler).value;
	}
	extraArgs = '&run=' + ADG_ROOT_DIR + '/adg/gmap_by_latlong.php&latitude=' + encodeBase64(lat) + '&longitude=' + encodeBase64(longt) + '&poptext=' + encodeBase64(poptext);
	openPopup('gmap','main.php',0,extraArgs);
	return true;

}
/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function str_pad (input, pad_length, pad_string, pad_type) {
    // Returns input string padded on the left or right to specified length with pad_string  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/str_pad    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // +      input by: Marco van Oort
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'
    var half = '', pad_to_go;
     var str_pad_repeater = function (s, len) {
        var collect = '', i;
 
        while (collect.length < len) {collect += s;}
        collect = collect.substr(0,len); 
        return collect;
    };
 
    input += '';    pad_string = pad_string !== undefined ? pad_string : ' ';
    
    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);        }
    }
 
    return input;
}

//this function will take a readonly field and strip the commas out and put the negative sign 
//on the left side of the number so we can do math on the new value
function formatRONumbers(num1,dec1)
{
	num1 = '' + num1;
	num1 = num1.replace(',','');
	str1 = num1.substr(num1.length - 1,1);

	if (str1 == '-') num1 = (num1.substr(0,(num1.length - 1)) * -1); 

	num1 = parseFloat(num1);
	num1 = num1.toFixed(dec1);

	return num1;
}

