/*******************************************************************
 Monitor 4 specific javascript
 
Functions include (sorted alpha):

addMonthsToDate(aDate, numOfMonths)
acceptNumericsOnly(field)	- Removes any non-numeric values from field (can be used on keypress). Does allow ',' and '.'
checkDate(field)			- Checks for a valid date. Display error if invalid
checkNumericsOnly(field)	- Checks whether a fied is numeric using isNumeric(s). Displays error msg if not. Set value to 0 if no entry
checkPhone(field)			- Checks for a valid 7 or 10 digit phone number. Display error if invalid.
disable_iframe()
disableAllFormFields(form) 	- Disables all forms fields 
disableAllButtons(form) 	- Disables all buttons 
enable_iframe(s)
ensureZero(field)			- Make sure zeros '0' is in a field after onBlur
ensureDecimalZero(field)	- Make sure zeros '0.00' is in a field after onBlur
ensurePercentZero(field)	- Make sure zeros '0.0' is in a field after onBlur
formatCurrency(num			- formats a number as follows: EG. 1234567.89  to 1,234,567.89  or 1234 to 1,234.00
FormatDate(s)
formatNumber(num)			- Formats a number as follows: EG. 1234567  to 1,234,567 
formatUSPhoneNumber			- Formats a phone number for US mask handles either 7 or 10
getFieldType(field)			- returns the type of field ie. Hidden, 
initialize_iframe(i, i)
isDate(s)
isEmpty(s)					- Tests whether a string is empty
isNumeric(s)				- Validates whether a string is numeric (allows decimals too)
isUSPhoneNumber(s)			- Tests whether stirng is a valid US phone number
isWhitespace(s)				- Tests whether a string contains only whitespaces
isLeapYear(intYear)			- Returns T/F whether a year is a leap year
stripCharsInBag(s, bag)		- Strips all characters from string which are in the bag
stripCharsNotInBag(s, bag)	- Strips all characters from string not in the bag
stripWhitespace(s)			- Strips the whitespace characters from string
timeIsOut()					- Function to ensure every page times out actively
trimString(sInString)		- Trims leading and trailing spaces 
validateTextAreaSize(field, maxlimit)
validateTextAreaSizeOnBlur(field, maxlimit)

 *******************************************************************/
var whitespace = " \t\n\r";
var inSubmit = false;
var bypass = false;
var _mlmConfirmLoseChanges = 'Changes made will be lost, are you sure you want to proceed?';
var _mlmFileDeleteConfirmation = 'Are you sure you want to discard this document?';
var _mlmFileDeleteConfirmation2 = 'Are you sure you want to remove this document?';
var _mlmQuoteDeleteConfirmation = "Are you sure you want to delete this Quote and all of its Quote Options?";
var _mlmQuoteOptionDeleteConfirmation = "Are you sure you want to delete this Quote Option and all of its contents?";
var _mlmConfirmDeleteRow = 'Are you sure you want to delete this row?';
var _mlmConfirmDeleteSelectedRows = 'Are you sure you want to delete selected rows?';
var popupFrameConfig = new Object();

function checkDate(field) {
	if (!isDate(field)) {
		alert("This is not a Valid date");
		field.focus();
		return false;
	}
	return true
}

function validDateFormat(dtField) {
	var dateStr = dtField.value;
	if (checkDate(dtField)) {
		if (dateStr.length > 0 && dateStr != 'mm/dd/yyyy') {
			var yy = dateStr.substring(6);
			var dateObj = new Date(dateStr);
			// Ensure year is YYYY and not YY
			if (yy.length < 4) {
				if (dateObj.getYear() < 50) {
					dateObj.setYear(dateObj.getYear() + 2000);
				} else {
					dateObj.setYear(dateObj.getYear() + 1900);
				}
			}
			dateStr = convertDateAsString(dateObj);
			dtField.value = dateStr;
		}
		return true;
	} else {
		return false;
	}
}

function convertDateAsString(aDate) {
	var month = aDate.getMonth()+1;
	var monthStr = month.toString();
	if (monthStr.length == 1) {
		monthStr = "0" + monthStr;
	}
	var day = aDate.getDate();
	var dayStr = day.toString();
	if (dayStr.length == 1) {
		dayStr = "0"  + dayStr;
	}
	dateStr = monthStr + "/" + dayStr + "/" + aDate.getFullYear();
	return dateStr;
}

// Bypass phone check for now
function checkPhone(field) {
//	if (!isUSPhoneNumber(field.value)) {
//		alert("This is not a Valid Phone number");
//		field.focus();
//		return false;
//	}
	field.value = formatUSPhoneNumber(field.value);
	return true;
}

function isUSPhoneNumber(s) {
    var x;
	var delimiter = "-()";
    if (isWhitespace(s)) {
    	return false;
    }
    // Remove '-()' leaving only numbers
	x = stripCharsInBag(s, delimiter)
	if (x.length == 7 || x.length == 10) {
		return isInteger(x);
    }
    return false;
}

function formatUSPhoneNumber(s) {
	var delimiter = "-()";
    // Remove '-()' leaving only numbers
	x = stripCharsInBag(s, delimiter);
	if (x.length == 7) {
		return x.substring(0,3) + "-" + x.substring(3);
	} else if (x.length == 10) {
		return "(" + x.substring(0,3) + ")" + x.substring(3,6) + "-" + x.substring(6);
	}
	return s;
}

function stripCharsInBag(s, bag) {
	var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++) {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) 
        	returnString += c;
    }
    return returnString;
}

function stripCharsNotInBag(s, bag) {
	var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.
    for (i = 0; i < s.length; i++) {   
        var c = s.charAt(i);
        if (bag.indexOf(c) > -1) 
        	returnString += c;
    }
    return returnString;
}

function isWhitespace(s) {
	var i;
    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++) {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }
    // All characters are whitespace.
    return true;
}

function isEmpty(s) {
   if (s != null){
   		s = stripWhitespace(s);
   }
   return ((s == null) || (s.length == 0))
}

// Removes whitespace characters from s
function stripWhitespace (s) { 
  return stripCharsInBag (s, whitespace)
}

function isNumericsOnly(s) {
	var valid = "0123456789.,";
	return numberTest(s, valid);
}

function isInteger(s) {
	var valid = "0123456789,";
	return numberTest(s, valid);
}

function numberTest(s, valid) {
	var decimalCount = 0;
	var count = 0;
    var i;
    var x;
    var c;
    for (i = 0; i < s.length; i++) {   
        c = s.charAt(i);
        x = valid.indexOf(c);
        if (x == -1)
			return false;
		if (x > -1 && x < 10)
			count++;
    }
    if (count == 0 && s.length > 0)
    	return false;
    return true;
}

function acceptNumericsOnly(field) {
	if (!isNumericsOnly(field.value)) {
		var s = field.value;
		field.value = stripCharsNotInBag(s, "0123456789.,");
	}
}

function checkNumericsOnly(field) {
	if (!isNumericsOnly(field.value)) {
		alert("This is a NUMERIC Only field");
		field.focus();
	}
	var s = field.value;
	field.value = stripCharsInBag(s, ",");
}

function checkIntegerOnly(field) {
	if (!isInteger(field.value)) {
		alert("This field only allows Integer values");
		field.focus();
	}
	var s = field.value;
	field.value = stripCharsInBag(s, ",");
	if (field.value.length == 0) {
		field.value = 0;
	}
}

function ensureZero(field) {
	if (field.value == null || field.value.length == 0) {
		field.value = '0';
	}
}
function ensureDecimalZero(field) {
	if (field.value == null || field.value.length == 0) {
		field.value = '0.00';
	}
}
function ensurePercentZero(field) {
	if (field.value == null || field.value.length == 0) {
		field.value = '0.0';
	}
}

function formatNumber(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num)) {
		alert("Please enter a valid numeric value")
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num)) {
		alert("Please enter a valid numeric value")
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if (cents<10)
	cents = "0" + cents;
	if (cents == "0")
		cents = "00";
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}

function validateTextAreaSize(field, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
		alert("The maximum number of characters allowed in this field is " + maxlimit)	
	}
}

function validateTextAreaSizeOnBlur(field, maxlimit) {
	if (field.value.length > maxlimit) {
		alert("The maximum number of characters allowed in this field is " + maxlimit);
		field.focus();			
	}
}

function showServletLoadingMessage() {

    var div = document.getElementById("mlm_" + this.id + "_loading_div");
    if (div == null) {
        div = document.createElement("DIV");

        document.body.appendChild(div);
        div.id = "mlm_" + this.id + "_loading_div";

        div.innerHTML = "<IMG src='./pages/images/loading.gif'/>";
        div.style.position = "absolute";
        div.style.color = "white";
        div.style.fontFamily = "Arial, Helvetica, sans-serif";
        div.style.fontWeight = "bold";
        div.style.fontSize = "11px";
    }
    div.style.top = document.body.scrollTop + "px";
    div.style.left = (document.body.offsetWidth - 100 - (document.all?20:0)) + "px";

    div.style.display = "";
}
/*********************************************************************
* The following section is code to disable specific key and mouse events
* (eg. right-click or CTRL-N
**********************************************************************/
// Returns the field type as a string
function getFieldType(theField) {
	if (theField.length && !theField.options) return theField[0].type;
	else return theField.type;
}

// Disable specific keys and combinations:
function keyEventHandler(e) {
	var ie = (navigator.appName == 'Microsoft Internet Explorer');

	if (ie) {
		var keyId = event.keyCode;
		var altPressed = event.altKey;
		var ctrlPressed = event.ctrlKey;
		var shiftPressed = event.shiftKey;
	   	var type = getFieldType(event.srcElement);
		
	} else {
		var keyId = e.keyCode;
		var altPressed = ((e.modifiers & Event.ALT_MASK) > 0);
		var ctrlPressed = ((e.modifiers & Event.CONTROL_MASK) > 0);
		var shiftPressed = ((e.modifiers & Event.SHIFT_MASK) > 0);
		var target = e.target;
		var type = target.type
	}	
	// Bypass if ctrl-alt-shift-]
	if (keyId == 221 && ctrlPressed && altPressed && shiftPressed) {
		alert("Right-Click bypass accepted");
		bypass = true;
		return;
	}

	// Stop alt-left arrow and alt-right arrow
	// alt-F11(122) F5 F3
	// ctrl-N(78)	ctrl-H(72)	alt-Home(36)
	// ctrl-L(76)	ctrl-O(79) F5(116)
	// F3(114)		ctrl-W(87)
	// shift-f10(121) f11(122)
	// Backspace not in text/textarea/or password fields
	if (   (keyId == 37 && altPressed) || (keyId == 39 && altPressed)
		|| (keyId == 122 || keyId == 116 || keyId == 114)
		|| (keyId == 78 && ctrlPressed) || (keyId == 72 && ctrlPressed)
		|| (keyId == 36 && altPressed)  || (keyId == 73 && ctrlPressed)
		|| (keyId == 76 && ctrlPressed) || (keyId == 121 && shiftPressed)
		|| (keyId == 87 && ctrlPressed) || (keyId == 79 && ctrlPressed)
		|| (keyId == 8 && ('text|textarea|password'.indexOf(type) == -1))) {
		alert("Sorry, Key Sequence is not available");		
		if (ie) {
			window.event.keyCode = 0;
			event.cancelBubble = true;
			event.returnValue = false;
		} else {
			e.preventDefault();
			e.stopPropagation();
			return false;
		}
	}
}

// Disables the right-click popup 
function mouseEventHandler(e) {

	if (bypass) {
		return;
	}

	if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
		return false;
	else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3  || event.button == 5)) {
		alert("Sorry, Right-Click is not available");
		return false;
	}
	return true;
}

//function noenter() {
//  return !(window.event && window.event.keyCode == 13);
//}

function noenter(e) {
  var whichCode = (window.event) ? e.keyCode : e.which;
  return !(whichCode == 13);
}


// Function to disable enter key issueing a submit request
// specific feature of IE browsers
function addEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert(evType + " event could not be attached.");
	}
}

function addKeyEvent() {
	var e = (document.addEventListener) ? 'keypress' : 'keydown';
	addEvent(document, e, keyEventHandler, false);
}
function addMouseEvent() {
	addEvent(document, 'mousedown', mouseEventHandler, false);
}

// addKeyEvent();
// addMouseEvent();

/*********************************************************************
* This section is used to integrate with RoboHelp
* 
**********************************************************************/
function helpCall() {
//	RH_ShowHelp(0, '../Help/WebHelp/Phoenix_Help_Project.htm', HH_DISPLAY_TOC, 0);
	var field = getElementByIdEnding("robo_helpId");
	if (field == null) {
		alert('Unable to locate help value.');
	} else {
		RH_ShowHelp(0, '../Help/WebHelp/Phoenix_Help_Project.htm', HH_HELP_CONTEXT, field.value);
	}
}

function helpCallToTOC() {
	RH_ShowHelp(0, '../Help/WebHelp/Phoenix_Help_Project.htm', HH_DISPLAY_TOC, 0);
}
/*********************************************************************
* 
* 
**********************************************************************/
function initialize_iframe(frameHeight, frameWidth) {
	var div = parent.document.getElementById("mlm_popup");
	var iframe = parent.document.getElementById("popupFrame");	
	iframe.width = "500px";
	iframe.height = "320px";
	div.width = "500px";
	div.height = "320px";
}

function timeIsOut() { 
    alert ("Your session has timed out. Please press OK to close this window.");
    //window.parent.header.document.getElementById("test").value = "close";
    //top.window.close();
    window.close();
} 



/*****************************************************************
 **     Popup formatting for size and position formatting for   **
 ** 	popups.							**
 **	Support functions: docType, winSize			**
 ** 	Main Function: open_iFrame				**
 **     							**
 ** 	Guy Blair - 9/20/05					**
 *****************************************************************/

function docType(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function winSize() {
	var myWidth,myHeight = 0;
	
	if ( typeof ( window.innerWidth ) == 'number' ) {
		myWidth = window.innerWidth; 
		myHeight = window.innerHeight;
	} else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
		myWidth = document.documentElement.clientWidth; 
		myHeight = document.documentElement.clientHeight;
	} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight )) {
		myWidth = document.body.clientWidth; 
		myHeight = document.body.clientHeight;
	}
	return [myWidth, myHeight];
}
// Prevents users from submitting the form more than once.  (clicking submit button multiple times).
function disableFurtherSubmits() {
	if (inSubmit) {
		return false;
	} else {
		inSubmit = true;
		return true;
	}
}

function submitFromBreadcrumb() {
	if (disableFurtherSubmits()) {
		var answer = true;
	    if (getElementByIdEnding("dataChangedFlag").value == "true" || hasAnyDataTableChanged()) {
			answer =  confirm(_mlmConfirmLoseChanges);
			if (answer) {
				disableAllFormFields(document.forms[0], document);
				clearDataChangedTracker();
			} else {
				initializeSubmitIndicator();
			}
	    } else {
			disableAllFormFields(document.forms[0], document);
	    }
	    return answer;
    } else {
    	return false;
    }
}
function initializeSubmitIndicator() {
	inSubmit = false;
}


/*****************************************************************
 **     Page State Functions
 *****************************************************************/
//Attaches data changes event on input fields
function registerEvents() {
    var fields = document.getElementsByTagName("INPUT");
    for (var i = 0; i < fields.length; i++)  {
    	if (fields[i].type != "hidden" 
    			&& !fields[i].disabled 
    			&& fields[i].style != "display:none"
    			&& fields[i].type != "submit"
    			&& fields[i].type != "button"
    			&& fields[i].type != "image"
    			&& !excludeFromDirtyCheck(fields[i].name)) {  
    		if (fields[i].id != null && fields[i].id.indexOf("_dtinput_") >= 0 ) { // do not add onchange event on datatable input fields used during edit/add mode.
    			continue;
    		}
	    	var event = fields[i].onchange;
	        fields[i].attachEvent('onchange', dataChanged);
	        if (fields[i].type == "checkbox" || fields[i].type == "radio") {
	            fields[i].attachEvent('onclick', dataChanged);
	        }
        }
    }
    fields = document.getElementsByTagName("TEXTAREA");
    for (var i = 0; i < fields.length; i++)  {
    	if (!fields[i].disabled) {  
        	fields[i].attachEvent('onchange', dataChanged);
        }
    }
    fields = document.getElementsByTagName("SELECT");
    for (var i = 0; i < fields.length; i++)  {
	    if (!fields[i].disabled && !excludeFromDirtyCheck(fields[i].name)) {  
	        fields[i].attachEvent('onchange', dataChanged);
        }
    }
}

function excludeFromDirtyCheck(id) {
	if (isUndefined(id)) {
		return false;
	} else if (id.indexOf('exdc') > 0) {
		return true;
	} else {
		return false;
	}
}
function dataChanged() {
    // getElementByIdEnding("dataChangedFlag").value = "true";
}

function loseDataNotification() {
 	var answer = true;
    if (getElementByIdEnding("dataChangedFlag").value == "true" || hasAnyDataTableChanged()) {
		answer =  confirm(_mlmConfirmLoseChanges);
		if (answer) {
			clearDataChangedTracker();
		} else {
			initializeSubmitIndicator();
		}
    }
    return answer;
}


//This table applies only to pages with datatable component.  It is used to track changes made to datatable via the edit/add mode.
function hasAnyDataTableChanged() {
	var val1=getElementByIdEnding("dirtyDataTable").value;
	var val2=getElementByIdEnding("dirtyDataTableField").value;
	if ((val1 != null && trimString(val1).length > 0) || (val2 != null && trimString(val2).length > 0)) {
		return true;
	} else {
		return false;
	}
}

function clearDataChangedTracker() {
	getElementByIdEnding("dataChangedFlag").value = "false";
	getElementByIdEnding("dirtyDataTable").value = "";
	getElementByIdEnding("dirtyDataTableField").value = "";
	
}

function showWarning(field) {
	getElementByIdEnding("warningFieldId").value = field.id;
}
 
// This is used in Document Management
function generalConfirmFileDelete() {
	return confirm(_mlmFileDeleteConfirmation);
}
// This is used in Submission documents
function generalConfirmFileDelete2() {
	return confirm(_mlmFileDeleteConfirmation2);
}
// This is used in Quote Management
function confirmQuoteDelete() {
	return confirm(_mlmQuoteDeleteConfirmation);
}
// This is used in Quote Management
function confirmQuoteOptionDelete() {
	return confirm(_mlmQuoteOptionDeleteConfirmation);
}

/*****************************************************************
 **     FormattedTextarea Component Functions
 *****************************************************************/


function enableFormattedTextareaButtons(id) {
	xGetElementById(id).disabled = false;
	disableFormattedTextareaButtons(id);
}
function formatTextSelection(type, id) {

	var txt = '';
	var prefix = '';
	var suffix= '';
	
	if (type==1) {
		prefix="<b>";
		suffix="</b>";
	} else if (type==2) {
		prefix="<i>";
		suffix="</i>";
	} else if (type==3) {
		prefix="<u>";
		suffix="</u>";
	}
	
	if (window.getSelection) {
		txt = window.getSelection();
	} else if (document.getSelection) {
		txt = document.getSelection();
	} else if (document.selection) {
		txt = document.selection.createRange().text;
	} else {
		xGetElementById(id).focus();
		return;
	}
	if ((txt == null) || (txt.length == 0)) {
		return;
	} else {
		var strValue = xGetElementById(id).value;
		strValue = strValue.replace(txt, prefix + txt + suffix);
		
		var obj = xGetElementById(id);
		obj.value = strValue;
		obj.focus();
		obj.click();
	}
}

function disableFormattedTextareaButtons(id) {
	var idEnding = "_formattedTextAreaButtons";
    for (var elem in document.all) {
        var lastIndex = elem.lastIndexOf(idEnding);
        if (lastIndex >= 0) {
            if (lastIndex == (elem.length - idEnding.length)) {
            	var obj = document.all(elem);
            	if (obj.id != id) {
            		obj.disabled = true;
            	}
            }
        }
    }
}

/*****************************************************************
 **     Utility Functions
 *****************************************************************/
function trimString(sInString) {
  if (sInString != null && sInString != "") {
	  sInString = sInString.replace( /^\s+/g, "" );// strip leading
	  return sInString.replace( /\s+$/g, "" );// strip trailing
  } else {
  	return sInString;
  }
}

function getElementByIdEnding(idEnding) {
	var elements = document.all ? document.all : document.getElementsByTagName('*');
	
    for (x=0; x<elements.length; x++) {
    	var elem = elements[x].id;
        var lastIndex = elem.lastIndexOf(idEnding);
        if (lastIndex >= 0) {
            if (lastIndex == (elem.length - idEnding.length)) {
            	return document.getElementById(elem);
            }
        }
    }
/* RETIRED FOR IE ONLY, THE ABOVE WORKS FOR IE AND FIREFORX
    for (var elem in document.all) {
        var lastIndex = elem.lastIndexOf(idEnding);
        if (lastIndex >= 0) {
            if (lastIndex == (elem.length - idEnding.length)) {
            return document.all(elem);
            }
        }
    }
    */
}
function getParentElementByIdEnding(idEnding) {

	var elements = parent.document.all ? parent.document.all : parent.document.getElementsByTagName('*');
	
    for (x=0; x<elements.length; x++) {
    	var elem = elements[x].id;
        var lastIndex = elem.lastIndexOf(idEnding);
        if (lastIndex >= 0) {
            if (lastIndex == (elem.length - idEnding.length)) {
            	return parent.document.getElementById(elem);
            }
        }
    }
/* RETIRED FOR IE ONLY, THE ABOVE WORKS FOR IE AND FIREFORX
    for (var elem in parent.document.all) {
        var lastIndex = elem.lastIndexOf(idEnding);
        if (lastIndex >= 0) {
            if (lastIndex == (elem.length - idEnding.length)) {
            return parent.document.all(elem);
            }
        }
    }
    */
}

function formOnSubmit() {
	if (disableFurtherSubmits()) {
		if (!isUndefined(popupFrameConfig)
			&& popupFrameConfig != null 
			&& popupFrameConfig.name != null 
			&& popupFrameConfig.name != "") {
			open_iFrame(popupFrameConfig.name,popupFrameConfig.width,popupFrameConfig.height,popupFrameConfig.position);
		}
		return true;
	} else {
		return false;
	}
}


function setupPopupFrameConfig(lname, lwidth, lheight, lposition) {
	popupFrameConfig.name = lname;
	popupFrameConfig.width = lwidth;
	popupFrameConfig.height = lheight;
	popupFrameConfig.position = lposition;
}

function setInitialFocus() {
	var field = getElementByIdEnding("fieldFocus");
	if (field.value != null && field.value != "") {
		var focusField = getElementByIdEnding(field.value);
		if (!isUndefined(focusField)) {
			if (!focusField.disabled && !focusField.readOnly) {
				focusField.focus();
				if ((focusField.tagName.toLowerCase() == "input" && focusField.type == "text") || focusField.tagName.toLowerCase() == "textarea") {
					focusField.click();
				}
			}
		}
		field.value = "";
	} else {
		var aForm = document.forms[0];
		if( aForm.elements[0]!=null) {
			var i;
			var max = aForm.length;
			for( i = 0; i < max; i++ ) {
				if( (aForm.elements[ i ].type == "text" || aForm.elements[ i ].type == "select-one") &&
					!aForm.elements[ i ].disabled &&
					!aForm.elements[ i ].hidden &&
					aForm.elements[ i ].style.display != "none" &&
					!aForm.elements[ i ].readOnly ) {
					try {
						aForm.elements[ i ].focus();
					} catch(err) {
						//do nothing
					}
					break;
				} 
			}
		}
	}
}

function setFocusToField(fieldId) {
	var field = getElementByIdEnding("fieldFocus");
	field.value=fieldId;
}

function setFieldErrorClass(fields) {
	if (fields != '') {
		var temp = new Array();
		temp = fields.split('|');
		for (i=0; i<temp.length; i++) {
			var arr = new Array();
			arr = temp[i].split('::');
			var field = document.all(arr[0]);
			if (field != null) {
				field.className = 'field_error_indicator';
				field.title = arr[1];
			}
		}
	}
}

function clearDiv(field) {
	var obj = document.all("divInfoMessage");
	obj.className='popup_messagebar_hidden';
}

function populateSelectList(selectElement, arrKey, arrDisplay) {
	selectElement.options.length = 0;
	var i;
	for(i = 0; i < arrKey.length; i++) {
		var no = new Option();
		no.value = arrKey[i];
		no.text = arrDisplay[i];
		selectElement.options[i] = no;
	}
}

function isNull(a) {
    return typeof a == 'object' && !a;
}

function isUndefined(a) {
    return typeof a == 'undefined';
} 

function disableAllFormFields(form, oDoc) {
	for (var j=0; j < form.elements.length; j++) {
		switch (getFieldType(form.elements[j])) {
			case "text" :
				disableWidget(form.elements[j]);
				break;
			case "button" :
				disableButtonWidget(form.elements[j]);
				break;
			case "image" :
				disableWidget(form.elements[j]);
				break;
			case "submit" :
				disableButtonWidget(form.elements[j]);
				break;
			case "textarea" :
				disableWidget(form.elements[j]);
				break;
			case "radio" :
				disableWidget(form.elements[j]);
				break;
			case "checkbox" :
				disableWidget(form.elements[j]);
				break;
			case "select-one" :
				disableWidget(form.elements[j]);
				break;
			case "select-multiple" :
				disableWidget(form.elements[j]);
				break;
		}
		
	}
            
	for (var j=0; j < oDoc.links.length; j++) {
		if (oDoc.links[j].disabled == false) {
			oDoc.links[j].orig_onclick = oDoc.links[j].onclick;
			oDoc.links[j].onclick = doNothing;
			oDoc.links[j].disabled = true;
		}
	}
	return true;
}

function disableAllButtons(form) {
	for (var j=0; j < form.elements.length; j++) {
		switch (getFieldType(form.elements[j])) {			
			case "button" :
				disableButtonWidget(form.elements[j]);
				break;
			case "submit" :
				disableButtonWidget(form.elements[j]);
		}
		
	}
            
	return true;
}

function doNothing() {
	return false;
}
// Disables form based upon field type; Receives form's name as a string
function enableAllFormFields(form, oDoc) {
	for (var j=0; j < form.elements.length; j++) {
		switch (getFieldType(form.elements[j])) {
			case "text" :
				enableWidget(form.elements[j]);
				break;
			case "submit" :
				enableButtonWidget(form.elements[j]);
				break;
			case "button" :
				enableButtonWidget(form.elements[j]);
				break;
			case "image" :
				enableWidget(form.elements[j]);
				break;
			case "textarea" :
				enableWidget(form.elements[j]);
				break;
			case "radio" :
				enableWidget(form.elements[j]);
				break;
			case "checkbox" :
				enableWidget(form.elements[j]);
				break;
			case "select-one" :
				enableWidget(form.elements[j]);
				break;
			case "select-multiple" :
				enableWidget(form.elements[j]);
				break;
		}
	}
	for (var j=0; j < oDoc.links.length; j++) {
		if (!isUndefined(oDoc.links[j].orig_onclick)) {
			oDoc.links[j].onclick = oDoc.links[j].orig_onclick;
			oDoc.links[j].disabled = false;
		}
	}
	return true;
}

function disableWidget(theField) {
	if (theField.disabled == false) {
		theField.disabled = true;
		theField.substituted = "true";
	}
}
function enableWidget(theField) {
	if (!isUndefined(theField.substituted)) {
		theField.disabled = false;
	}
}

function disableButtonWidget(theField) {
	if (theField.disabled == false) {
		theField.disabled = true;
		theField.substituted = "true";
		if (theField.className != null && theField.className.indexOf("popup") == -1) {
			theField.className = theField.className + " but_disable";
		}
	}
}
function enableButtonWidget(theField) {
	if (!isUndefined(theField.substituted)) {
		theField.disabled = false;
		if (theField.className != null) {
			theField.className = theField.className.replace(" but_disable", " ");
		}
	}
}


function replaceComma(str) {
	return str.replace(/,/g,"");
}

function remove(s, t) {
  /*
  **  Remove all occurrences of a token in a string
  **    s  string to be processed
  **    t  token to be removed
  **  returns new string
  */
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + remove(s.substring(i + t.length), t);
  return r;
  }
/*****************************************************************
 **     Cross-Browser Functions 
 ** Copyright 2001-2005 Michael Foster (Cross-Browser.com)
 ** Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
 *****************************************************************/
function xGetElementById(e)
{
  if(typeof(e)!='string') return e;
  if(document.getElementById) e=document.getElementById(e);
  else if(document.all) e=document.all[e];
  else e=null;
  return e;
}


/*****************************************************************
 **     Date Functions
 *****************************************************************/

function isDate(theField) {
	var DateToCheck = theField.value;
	if (DateToCheck == "") {
		return true;
	}
	if (DateToCheck == "mm/dd/yyyy") {
		return true;
	}
	var m_strDate = FormatDate(DateToCheck);
	if (m_strDate == "") {
		return false;
	}
	if (m_strDate.length < 10) {
		return false;
	}
	theField.value = m_strDate;
	return true;
}

// All dates are formatted as mm/dd/yyyy
function FormatDate(DateToFormat) {
	if (DateToFormat == "") {
		return "";
	}
	
	var strReturnDate;
	DateToFormat = DateToFormat.toLowerCase();
	var arrDate
	var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	var arrDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var Separator;
	
	while (DateToFormat.indexOf("st")>-1) {
		DateToFormat = DateToFormat.replace("st","");
	}
	
	while (DateToFormat.indexOf("nd")>-1) {
		DateToFormat = DateToFormat.replace("nd","");
	}
	
	while (DateToFormat.indexOf("rd")>-1) {
		DateToFormat = DateToFormat.replace("rd","");
	}
	
	while (DateToFormat.indexOf("th")>-1) {
		DateToFormat = DateToFormat.replace("th","");
	}
	
	if (DateToFormat.indexOf(".")>-1) {
		Separator = ".";
	}
	
	if (DateToFormat.indexOf("-")>-1) {
		Separator = "-";
	}

	if (DateToFormat.indexOf("/")>-1) {
		Separator = "/";
	}
	
	if (DateToFormat.indexOf(" ")>-1) {
		Separator = " ";
	}
	
	arrDate = DateToFormat.split(Separator);
	DateToFormat = "";
	for (var iSD = 0;iSD < arrDate.length;iSD++) {
		if (arrDate[iSD] != "") {
			DateToFormat += arrDate[iSD] + Separator;
		}
	}
	DateToFormat = DateToFormat.substring(0,DateToFormat.length-1);
	arrDate = DateToFormat.split(Separator);
	
	if (arrDate.length < 3) {
		return "";
	}
	
	var MONTH = arrDate[0];
	var DAY = arrDate[1];
	var YEAR = arrDate[2];
	var strDate = '';
	var valid = '0123456789';
	var strTemp = MONTH.toString() + DAY.toString() + YEAR.toString();
	
	if (!numberTest(strTemp, valid)) {
		return '';
	}
	if (MONTH > 12) {
		return '';
	}
	if (parseInt(MONTH)< 10 && MONTH.toString().length < 2) {
		strDate = "0";
	}
	strDate = strDate + MONTH + '/';
	if (parseInt(DAY)< 10 && DAY.toString().length < 2) {
		strDate = strDate + "0";
	}
	strDate = strDate + DAY + '/';
	strTemp = YEAR.toString();
	var strYear
	if (strTemp.length == 1) {
		strYear = '200' + YEAR;
		strDate = strDate + "200" + YEAR;
	} else if (strTemp.length == 2) {
		strYear = '20' + YEAR;
		strDate = strDate + "20" + YEAR;
	} else {
		strYear = YEAR.toString();
		strDate = strDate + YEAR;
	}
	
	if (parseInt(MONTH) == 2  && isLeapYear(parseInt(strYear))) {
		if (parseInt(DAY) > 29) {
			return '';
		}
	} else if (parseInt(DAY) > arrDays[MONTH-1]) {
		return '';
	}
	return strDate;
} 

function isLeapYear(intYear) {
	if (intYear % 100 == 0) {
		return (intYear % 400 == 0);
	} else {
		return ((intYear % 4) == 0);
	}
	return false;
}

function addMonthsToDate(aDate, numOfMonths) {
	var max = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var incr = numOfMonths;
	var newDate = aDate;
	var day = newDate.getDate();
	var month = newDate.getMonth();
	var year = newDate.getFullYear();
	var incrYrs = (incr - (incr % 12)) / 12;
	if (incrYrs > 0) {
		year = year + incrYrs;
		incr = incr - (12 * incrYrs);
	}
 	while(incr > 0) {
		incr--;
		month++;
 		if (month > 11) {
			month = 0;
			year++;
		}
	}
	newDate.setFullYear(year);
	if (day > max[month]) {
		if (isLeapYear(year) && day > 29 && month == 1) {
			newDate.setDate(29);
		} else {
			newDate.setDate(max[month]);
		}
	}
	newDate.setMonth(month);
	return newDate;
}


//End of Date Functions

/***********************************************
* Cool DHTML tooltip script II- ? Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
Tooltip.defaultInstanceName = "mlmTooltip";
function Tooltip() {
	this.id=Tooltip.defaultInstanceName;
	this.offsetfromcursorX=12 //Customize x offset of tooltip
	this.offsetfromcursorY=10 //Customize y offset of tooltip
	
	this.offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image
	this.offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).
	
	this.ie=document.all
	this.ns6=document.getElementById && !document.all
	
	if (this.ie||this.ns6)
	this.tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
	
	this.tipobjFrame=document.all? document.all["HelpShim"] : document.getElementById? document.getElementById("HelpShim") : ""
	this.pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : ""
//	document.onmousemove=this.positiontip()
}


Tooltip.prototype.ietruebody=function(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

Tooltip.prototype.ddrivetip=function(thetext, thewidth, thecolor){
	if (this.ns6||this.ie){
		var str = stripWhitespace(thetext);
		if (typeof thewidth!="undefined") this.tipobj.style.width=thewidth+"px";
		if (typeof thecolor!="undefined" && thecolor!="") this.tipobj.style.backgroundColor=thecolor;
		if (str == null || str.length == 0) {
			return true;
		}
		this.tipobj.innerHTML=thetext;
		this.tipobjFrame.style.width = this.tipobj.offsetWidth;
		this.tipobjFrame.style.height = this.tipobj.offsetHeight;
		this.enabletip();
		return false;
	}
}

Tooltip.prototype.enabletip=function(){
		var nondefaultpos=false
		var curX=(this.ns6)?e.pageX : event.clientX+this.ietruebody().scrollLeft;
		var curY=(this.ns6)?e.pageY : event.clientY+this.ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var winwidth=this.ie&&!window.opera? this.ietruebody().clientWidth : window.innerWidth-20
		var winheight=this.ie&&!window.opera? this.ietruebody().clientHeight : window.innerHeight-20
		
		var rightedge=this.ie&&!window.opera? winwidth-event.clientX-this.offsetfromcursorX : winwidth-e.clientX-this.offsetfromcursorX
		var bottomedge=this.ie&&!window.opera? winheight-event.clientY-this.offsetfromcursorY : winheight-e.clientY-this.offsetfromcursorY
		
		var leftedge=(this.offsetfromcursorX<0)? this.offsetfromcursorX*(-1) : -1000
		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<this.tipobj.offsetWidth){
			//move the horizontal position of the menu to the left by it's width
			this.tipobj.style.left=curX+20-this.tipobj.offsetWidth+"px";
			this.tipobjFrame.style.left=curX+20-this.tipobj.offsetWidth+"px";
			this.pointerobj.style.left=curX-this.offsetfromcursorX+"px";
			nondefaultpos=true;
		}
		else if (curX<leftedge) {
			this.tipobj.style.left="5px";
			this.tipobjFrame.style.left="5px";
		} else {
			//position the horizontal position of the menu where the mouse is positioned
			this.tipobj.style.left=curX+this.offsetfromcursorX-this.offsetdivfrompointerX+"px";
			this.tipobjFrame.style.left=curX+this.offsetfromcursorX-this.offsetdivfrompointerX+"px";
			this.pointerobj.style.left=curX+this.offsetfromcursorX+"px";
		}
		
		//same concept with the vertical position
		if (bottomedge<this.tipobj.offsetHeight){
			this.tipobj.style.top=curY-this.tipobj.offsetHeight-this.offsetfromcursorY+"px";
			this.tipobjFrame.style.top=curY-this.tipobj.offsetHeight-this.offsetfromcursorY+"px";
			this.pointerobj.style.top=curY+this.offsetfromcursorY+"px";
			nondefaultpos=true;
		} else{
			this.tipobj.style.top=curY+this.offsetfromcursorY+this.offsetdivfrompointerY+"px";
			this.tipobjFrame.style.top=curY+this.offsetfromcursorY+this.offsetdivfrompointerY+"px";
			this.pointerobj.style.top=curY+this.offsetfromcursorY+"px";
		}

		this.tipobj.style.visibility="visible"
		this.tipobjFrame.style.zIndex = this.tipobj.style.zIndex-1;
		this.tipobjFrame.style.display = "block"
		this.tipobjFrame.style.backgroundColor = "black";
			
		if (!nondefaultpos) {
			this.pointerobj.style.visibility="visible"
			this.pointerobj.src = "../images/arrow2.gif";
		} else {
			this.pointerobj.style.visibility="visible"
			this.pointerobj.src = "../images/arrow1.gif";
		}
}

Tooltip.prototype.hideddrivetip=function(){
	if (this.ns6||this.ie){
		this.tipobj.style.visibility="hidden"
		this.pointerobj.style.visibility="hidden"
		this.tipobjFrame.style.display = "none";
		this.tipobj.style.left="-1000px"
		this.tipobj.style.backgroundColor=''
		this.tipobj.style.width=''
	}
}

/**
* Binds this instance to window object using "Tooltip."+this.id as a key.
*/
Tooltip.prototype.bindById = function () {
    var key = "Tooltip." + this.id;
    window[key] = this;
}

/**
* Finds an instance by id.
*/
Tooltip.findInstance = function(id) {
    var key = "Tooltip." + id;
    return window[key];
}

/***********************************************
* Popup Window Functions
***********************************************/
function openNewWindow(url, name, width, height) {
	var posxy = winSize();
	var left = (posxy[0]-(width))/2;
	var top = (posxy[1]-(height+55))/2;
	opener = window.open(url, name, 'toolbar=no,location=no,directories=no,status=no,scrollbar=no,resizable=no,copyhistory=no,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
	storeWindowReference(opener);
	opener.focus();
}

function storeWindowReference(winRef) {
	len = window.parent.myOpenWinArr.length;
	if (len == 0) {
		window.parent.myOpenWinArr[len] = winRef;
	} else {
		isFound = false;
		for (i = 0; i < len; i++) {   
	        var c = window.parent.myOpenWinArr[i];
	        if (c != null && c == winRef) {
	        	isFound = true;
	        	break;
	        }
    	}
    	if (!isFound) {
			for (i = 0; i < len; i++) {   
		        var c = window.parent.myOpenWinArr[i];
		        if (c == null) {
		        	window.parent.myOpenWinArr[i] = winRef;
		        	isFound = true;
		        	break;
		        }
	    	}
    		if (!isFound) {
    			window.parent.myOpenWinArr[len] = winRef;
    		}
    	}
	}
}

function openNewWindowWithScrollbar(url, name, width, height) {
	var posxy = winSize();
	var left = (posxy[0]-(width))/2;
	var top = (posxy[1]-(height+55))/2;
	opener = window.open(url, name, 'toolbar=no,location=no,directories=no,status=no,scrollbar=yes,resizable=yes,copyhistory=no,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
	storeWindowReference(opener);
	opener.focus();
}

function closeNewWindow() {
	if (opener != null && opener != 'undefined') {
		opener.close();
	}
}

function closeErrorWindow() {
	len = window.parent.myOpenWinArr.length;
	if (len > 0) {
		for (i = 0; i < len; i++) {   
	        c = window.parent.myOpenWinArr[i];
	        if (typeof c != 'undefined' && c != null && !c.closed && c.name=='popUpWinErrorMess') {
	        	c.close();
	        	window.parent.myOpenWinArr[i] == null;
	        }
    	}
	}
}

// ********************************
// - Popup Submenu - 
//   Shows and hides a div at the cursor
//   position for icon extensions 
// ********************************

var xOffset = -10;
var yOffset = 7;

function showPopup (targetObjectId, rowCount, eventObj) {
    if(eventObj) {
		// hide any currently-visible popups
	    if(window.currentlyVisiblePopup) {
			changeObjectVisibility(window.currentlyVisiblePopup, 'hidden', '');
			window.currentlyVisiblePopup = false;
	    }
		divSize = rowCount * 30;
		// stop event from bubbling up any farther
		eventObj.cancelBubble = true;
		var truebody = (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
		var clientHeight = truebody.clientHeight;
		// move popup div to current cursor position 
		// (add scrollTop to account for scrolling for IE)
		var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
		var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);
		if (newYCoordinate+divSize > clientHeight) {
			newYCoordinate = clientHeight-divSize;
			newXCoordinate = newXCoordinate+15;
		}
		
		moveObject(targetObjectId, newXCoordinate, newYCoordinate);
		
		// and make it visible
		if( changeObjectVisibility(targetObjectId, 'visible') ) {
			// if we successfully showed the popup
			// store its Id on a globally-accessible object
			window.currentlyVisiblePopup = targetObjectId;
			return true;
		} else {
			// we couldn't show the popup, boo hoo!
			return false;
		}
    } else {
		// there was no event object, so we won't be able to position anything, so give up
		return false;
    }
} 


//Used for closing menu/div
function hideCurrentPopup() {
	resetPopupImage();
    // note: we've stored the currently-visible popup on the global object window.currentlyVisiblePopup
    if(window.currentlyVisiblePopup) {
		changeObjectVisibility(window.currentlyVisiblePopup, 'hidden', '');
		window.currentlyVisiblePopup = false;
    }
} 

function resetPopupImage() {
	var obj = xGetElementById("menu_selected_img");
	if (!isNull(obj) && !isUndefined(obj)) {
		obj.id="";
		obj.src="../images/icon_submenu.gif";
	}
}

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
		// W3C DOM
		return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
		// MSIE 4 DOM
		return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
		// NN 4 DOM.. note: this won't find nested layers
		return document.layers[objectId];
    } else {
		return false;
    }
} 

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
		styleObject.visibility = newVisibility;
		return true;
    } else {
		// we couldn't find the object, so we can't change its visibility
		return false;
    }
} 

function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
		styleObject.left = newXCoordinate;
		styleObject.top = newYCoordinate;
		return true;
    } else {
		// we couldn't find the object, so we can't very well move it
		return false;
    }
}

function setupPopupMenu(rowCount, formClientId, hiddenFieldName, clientIds, urls, disabledFlags, onclicks, labels) {	
	var arrClientId = clientIds.split("|");
	var arrUrl = urls.split("|");
	var arrLabel = labels.split("|");
	var arrDisabled = disabledFlags.split("|");
	var arrOnclick = onclicks.split("|");
	
	var htmlScript = "<table cellpadding='0' cellspacing='0' onMouseOver='trackTableHighlight(event, \"#e6e6ff\")'>";
	for (var x=0; x<rowCount; x++) {
		var retIncluded = false;
		htmlScript = htmlScript + "<tr ";

		if (arrDisabled[x] == "0") {
			htmlScript = htmlScript + " onclick=\"hideCurrentPopup();";
			if (arrOnclick[x] != "0") {
				if (arrOnclick[x].indexOf('return ')== -1) {
					htmlScript = htmlScript + "disableAllFormFields(document.forms[0], document);" + arrOnclick[x];
				} else {
					retIncluded = true;
					var fun = arrOnclick[x].substring(arrOnclick[x].toLowerCase().indexOf("return ")+ 7);				
					htmlScript = htmlScript + 'if (' + fun + ') {disableAllFormFields(document.forms[0], document);';
				}
			} else {
				htmlScript = htmlScript + "disableAllFormFields(document.forms[0], document);"
			}
			htmlScript = htmlScript + "if (disableFurtherSubmits()) { document.forms['";
			htmlScript = htmlScript + formClientId;
			htmlScript = htmlScript + "']['";
			htmlScript = htmlScript + hiddenFieldName;
			htmlScript = htmlScript + "'].value='";
			htmlScript = htmlScript + arrClientId[x];
			htmlScript = htmlScript + "'; document.forms['";
			htmlScript = htmlScript + formClientId;
			htmlScript = htmlScript + "'].submit();} return false;";
		}
		if (retIncluded) {
			htmlScript = htmlScript + '}';
		}
		htmlScript = htmlScript + "\"";
		htmlScript = htmlScript + "><td class='submenu_icon'>";
		htmlScript = htmlScript + "<img src='";
		htmlScript = htmlScript + arrUrl[x];
		htmlScript = htmlScript + "'/>";
		if (arrDisabled[x] == "0") {
		 	htmlScript = htmlScript + "</td><td class='submenu_text width180px'>";
		} else {
			htmlScript = htmlScript + "</td><td class='submenu_text_disable width180px'>";
		}
		htmlScript = htmlScript + arrLabel[x];
		htmlScript = htmlScript + "</td></tr>";
	}
	htmlScript = htmlScript + "</table>";
	document.getElementById('nameFieldPopup').innerHTML=htmlScript;
}

/********************************************************************************
* AutoFormat Functions
*********************************************************************************/

function negativeNumberFormat(fld, e) {
	return numberInput(fld, e, '-0123456789');
}

function numberFormat(fld, e) {
	return numberInput(fld, e, '0123456789');
}

function currencyFormat(fld, e) {
	return numberInput(fld, e, '-0123456789.');
}

function numberInput(fld, e, strCheck) {
	var key = '';
	var len = len2 = 0;
	var whichCode;
	if (window.Event) {
	//firefox
		whichCode = e.which;
		if (whichCode==0 || whichCode == 8) return true;
	} else {
	//ie
		whichCode = e.keyCode;
	}
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (key=="") {
		alert('1');
		return true;
	}
	if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	}
	if (strCheck.indexOf('.') == -1 && key == "." && fld.value.indexOf(".") != -1) {
		return false;
	}
	if (key == "-" && fld.value.indexOf("-") != -1) {
		return false;
	}

	return true;
}

function maskNumber(obj, e) {
	var whichCode = (window.Event) ? e.which : e.keyCode;
	var strCheck = '-0123456789.abcdefghimn';  // abc.. is the number key representation on the keyboard.
	key = String.fromCharCode(whichCode);
	if (whichCode == 96   // '0' on the number pad
		|| whichCode == 8   // backspace
		|| (strCheck.indexOf(key) != -1
		&& obj.value != "" 
		&& obj.value != "-"
		&& obj.value.length > 0)) {
		if (obj.value.lastIndexOf(".") != -1) {
			val = obj.value.substring(0,obj.value.lastIndexOf("."));
			dec = obj.value.substring(obj.value.lastIndexOf("."));
			if (val != "") {
				var isNegative = false;
				if (val.indexOf('(') != -1) {
					val = val.replace('(','');
					isNegative = true;
				}
				if (val != "-0") {
					if (val == "-") {
						obj.value = "-0" + dec;
					} else {
						obj.value = formatNumber(val) + dec;
					}
				}
				if (isNegative) {
					obj.value = "(" + obj.value
				}
			}
		} else {
				val = obj.value;
				var isNegative = false;
				if (val.indexOf('(') != -1) {
					val = val.replace('(','');
					isNegative = true;
				}
				if (val.indexOf(')') != -1) {
					val = val.replace(')','');
					isNegative = true;
				}
				if (val != "" && val != "-0") {
					if (val != "-") {
						obj.value = formatNumber(val);
					}
				} 
				if (isNegative) {
					obj.value = "(" + obj.value + ")"
				}
		}
		if (obj.value.length > 0 && (obj.value.charAt(0) == '-' || obj.value.charAt(0) == '(')) {
			obj.style.color="red";
		} else {
			obj.style.color="black";
		}
	var fld = getElementByIdEnding("dataChangedFlag");
	if (isUndefined(fld)) {
		fld = getParentElementByIdEnding("dataChangedFlag");
	}
	if (!isUndefined(fld)) {
		fld.value = "true";
	}
	}
}

function completeDecimal(obj) {
	if (obj.value.lastIndexOf(".") != -1) {
		if (obj.value.lastIndexOf(".") == 0) {	
			obj.value = "0" + obj.value;
		}
		if (obj.value.charAt(obj.value.length-1) == '.') {
			obj.value = obj.value.substring(0, obj.value.length-1);
		}
	}
	if (obj.value.length > 0 && (obj.value.charAt(0) == '-' || obj.value.charAt(0) == '(')) {
		if (obj.value.charAt(0) == '-') {
			obj.value = "(" + obj.value.substring(1,obj.value.length) + ")";
		}
		obj.style.color="red";
	} else {
		obj.style.color="black";
	}
}

function formatNegativeNumber(obj) {
	if (obj.value.length > 0 &&(obj.value.charAt(0) == '-' || obj.value.charAt(0) == '(')) {
		if (obj.value.charAt(0) == '-') {
			obj.value = "(" + obj.value.substring(1,obj.value.length) + ")";
		}
		obj.style.color="red";
	} else {
		obj.style.color="black";
	}
}

function phoneFormat(fld, e) {
	var key = '';
	var len = len2 = 0;
	var strCheck = '0123456789';
	var browser=navigator.appName;
	if (browser.indexOf('Netscape') != -1) {
		var whichCode = e.which;
	} else if (browser.indexOf('Microsoft') != -1)  {
		var whichCode = e.keyCode;
	} else {
		var whichCode = e.keyCode;
	}
	//var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return false;  // Enter
	if (whichCode == 8) return true;  // Delete (Bug fixed)

	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	}

	len = fld.value.length;
	if (len == 0) {
		fld.value = '(' + key;
		return false;
	}
	if (len == 3) {
		fld.value = fld.value + key + ')';
		return false;
	}
	if (len == 4) {
		fld.value = fld.value+')';
	}
	if (len == 8) {
		fld.value = fld.value + '-' + key;
		return false
	}
	if (len == 9) {
		fld.value = fld.value+'-';
	}
	return true;
}

function maskPhone(fld,e) {
	if (fld.value.length > 0 && fld.value.indexOf('(') == -1) {
		fld.value = "(" + fld.value.substring(0);
	}
	if (fld.value.length >5 && fld.value.indexOf(')') == -1) {
			fld.value = fld.value.substring(0,4) + ")" + fld.value.substring(5);
	}
	if (fld.value.length >9 && fld.value.indexOf('-') == -1) {
		fld.value = fld.value.substring(0,8) + "-" + fld.value.substring(9);
	}
	var fld = getElementByIdEnding("dataChangedFlag");
	if (fld == null) {
		fld = getParentElementByIdEnding("dataChangedFlag");
	}
	fld.value = "true";
}

function dateInput(fld, e) {
	if (fld.value == 'mm/dd/yyyy') {
		fld.value = '';
	}
	var key = '';
	var len = len2 = 0;
	var strCheck = '0123456789';
	var browser=navigator.appName;
	if (browser.indexOf('Netscape') != -1) {
		var whichCode = e.which;
	} else if (browser.indexOf('Microsoft') != -1)  {
		var whichCode = e.keyCode;
	} else {
		var whichCode = e.keyCode;
	}
	//var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return false;  // Enter
	if (whichCode == 8) return true;  // Delete (Bug fixed)

	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	}

	return true;
}

function maskDate(fld,e) {
	var browser=navigator.appName;
	if (browser.indexOf('Netscape') != -1) {
		var whichCode = e.which;
	} else if (browser.indexOf('Microsoft') != -1)  {
		var whichCode = e.keyCode;
	} else {
		var whichCode = e.keyCode;
	}
	//var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 39) return true;  // right arrow
	if (whichCode == 37) return true;  // left arrow
	if (whichCode == 46) return true;  // delete
	if (whichCode == 13) return true;  // Enter
	if (whichCode == 8) return true;  // backspace (Bug fixed)
	cnt = 0;
	for (var j = 0; j < fld.value.length; j++) {
		if (fld.value.charAt(j) == "/") {
			cnt++;
		}
		if (cnt ==2) {
			break;
		}
	}
	if (cnt < 2) {
		fld.value = fld.value.replace("/", "");
		fld.value = fld.value.replace("/", "");
		if (fld.value.length >2) {
			fld.value = fld.value.substring(0,2) + "/" + fld.value.substring(2);
		}
		if (fld.value.length >5 && fld.value.charAt(5) != '/') {
			fld.value = fld.value.substring(0,5) + "/" + fld.value.substring(5);
		}
	}
}

// email kireol at yahoo.com
// autoMask - an adaption of anyMask
// <input type=text name=ssn onkeypress="return autoMask(this,event, '###-##-####');">
// this will force #'s, not allowing alphas where the #'s are, and auto add -'s
function autoMask(field, event, sMask) {
        //var sMask = "**?##?####";

    var KeyTyped = String.fromCharCode(getKeyCode(event));
    var targ = getTarget(event);
    keyCount = targ.value.length;
    if (!isUndefined(getElementByIdEnding("dataChangedFlag"))) {
		getElementByIdEnding("dataChangedFlag").value = "true";
	}
	if(keyCount == sMask.length)
	{
		return false;
	}
      if ((sMask.charAt(keyCount+1) != '#') && (sMask.charAt(keyCount+1) != 'A' ) )
      {
         field.value = field.value + KeyTyped + sMask.charAt(keyCount+1);
         return false;
      }

        if (sMask.charAt(keyCount) == '*')
                return true;

        if (sMask.charAt(keyCount) == KeyTyped)
        {
                return true;
        }

        if ((sMask.charAt(keyCount) == '#') && isNumeric(KeyTyped))
           return true;

        if ((sMask.charAt(keyCount) == 'A') && isAlpha(KeyTyped))
         return true;

      if ((sMask.charAt(keyCount+1) == '?') )
      {
         field.value = field.value + KeyTyped + sMask.charAt(keyCount+1);
         return true;
      }
      if (KeyTyped.charCodeAt(0) < 32) return true;
    return false;
}
 function getTarget(e) {
  // IE5
   if (e.srcElement) {
        return e.srcElement;
   }
    if (e.target) {
        return e.target;
   }
 }

  function getKeyCode(e) {
 //IE5
 if (e.srcElement) {
        return e.keyCode
 }
  // NC5
  if (e.target) {
   return e.which
  }
 }

 function isNumeric(c)
{
        var sNumbers = "01234567890";
        if (sNumbers.indexOf(c) == -1)
                return false;
        else return true;

}

function isAlpha(c)
{
        var lCode = c.charCodeAt(0);
        if (lCode >= 65 && lCode <= 122 )
          {
                return true;
         }
        else
        return false;
}

function isPunct(c)
{
        var lCode = c.charCodeAt(0);
        if (lCode >= 32 && lCode <= 47 )
          {
                return true;
         }
        else
        return false;

}

/********************************************************************************
* JSF Component Script Functions
*********************************************************************************/
function saveScrollPosition(tableId) {
	var scrollpos_Hidden = getElementByIdEnding('scrollposition_hidden');
	if (!isNull(scrollpos_Hidden) && !isUndefined(scrollpos_Hidden)) {	
		var scrollarea_position = getElementByIdEnding('scrollarea_' + tableId);
		scrollpos_Hidden.value = tableId + "|" + scrollarea_position.scrollTop;
	}
	return true;
}

//the following three methods are used exclusively by datatable; to check whether they are dirty or not.
function setDataTableFieldToDirty(dataTableId) {
	var element = getElementByIdEnding("dirtyDataTableField");
	if (element.value == null || element.value == "") {
		element.value = dataTableId + "!";
	} else {
		if (element.value.indexOf(dataTableId + "!") == -1) {
			element.value = element.value + dataTableId + "!";
		}
	}
}

function removeDataTableFieldDirty(dataTableId) {
	var element = getElementByIdEnding("dirtyDataTableField");
	if (element.value != null && element.value.indexOf(dataTableId + "!") > -1) {
		var str = dataTableId + "!";
		element.value = element.value.replace(str,"");
	} 
}

function setDataTableToDirty(dataTableId) {
	var element = getElementByIdEnding("dirtyDataTableField");
	if (element.value != null && element.value.indexOf(dataTableId + "!") > -1) {
		var element2 = getElementByIdEnding("dirtyDataTable");
		if (element2.value == null || element2.value == "") {
			element2.value = dataTableId + "!";
		} else {
			if (element2.value.indexOf(dataTableId + "!") == -1) {
				element2.value = element2.value + dataTableId + "!";
			}
		}
		var str = dataTableId + "!";
		element.value = element.value.replace(str,"");
	}
}
function sortClick(fld, val, e) {
	if (e.shiftKey) {
		fld.value = val + ":SHIFT";
	} else {
		fld.value = val;
	}
}
