var DBG=false;
function util_hideShowFields(bShow, bShowWaitCursor) {
	util_hideShowCollection(document.body.all.tags("input"), bShow);
	util_hideShowCollection(document.body.all.tags("button"), bShow);
	util_hideShowCollection(document.body.all.tags("submit"), bShow);
	util_hideShowCollection(document.body.all.tags("select"), bShow);
	util_hideShowCollection(document.body.all.tags("textarea"), bShow);
	util_hideShowCollection(document.body.all.tags("radio"), bShow);
	util_hideShowCollection(document.body.all.tags("a"), bShow);
	if (bShowWaitCursor)
		cursor_wait();
}
function util_hideShowCollection(oCollection, bShow) {
	for (i = 0; i < oCollection.length; i++){
		oCollection[i].hidden= (!bShow);
	}
}
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit)  { // if too long...trim it!
		field.value = field.value.substring(0, maxlimit); // otherwise, update 'characters left' counter
	} else {
		getItem(countfield).value = maxlimit - field.value.length;
	}
}
function hasAtLeastOneChecked(sFriendlyName,sId) {
	var bRes= false;
	try {
		for (i=0;;i++) {
			var sId2=sId+""+i;
			var obj= getItem(sId2);
			if (obj==null) {
				break;
			}
			if (obj.checked) {
				bRes= true;
				break;
			}
		}
	} finally {
		if (!bRes) {
			alert("At least one " + sFriendlyName + " must be checked.");
			getItem(sId+"0").focus();
		}
	}
	return bRes;
}
function hasValue(sFriendlyName,sId) {
	var val= getItem(sId).value;
	val= val.trim();
	if (val.length>=1)
		return true;
	alert(sFriendlyName + " is a required field.");
	getItem(sId).focus();
	return false;
}
function isValidEmailAddress(sFriendlyName, sId) {
	  var value= getItem(sId).value.trim();
//     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var emailReg = "^[A-Za-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-zA-Z]{2,6}))$";
     var regex = new RegExp(emailReg,"gi");
     if (regex.test(value)) 
     	return true;
	alert(sFriendlyName + " is not a valid email address.");
	getItem(sId).focus();
	return (false)
  }
  
function cursor_wait() {
  document.body.style.cursor = 'wait';
}

function cursor_hand() {
  document.body.style.cursor = 'hand';
}

function cursor_clear() {
  document.body.style.cursor = 'default';
}


function strltrim() 
{
    return this.replace(/^\s+/,'');
}
	      
function strrtrim() 
{
    return this.replace(/\s+$/,'');
}

function strtrim() 
{
    return this.replace(/^\s+/,'').replace(/\s+$/,'');
}
	      
String.prototype.ltrim = strltrim;
String.prototype.rtrim = strrtrim;
String.prototype.trim = strtrim;

function IsNumeric(strString)
 //  check for valid numeric strings	
 {
 var strValidChars = "0123456789.-,";
 var strChar;
 var blnResult = true;

 if (strString.length == 0) return false;

 //  test strString consists of valid characters listed above
 for (i = 0; i < strString.length && blnResult == true; i++)
    {
    strChar = strString.charAt(i);
    if (strValidChars.indexOf(strChar) == -1)
       {
       blnResult = false;
       }
    }
 return blnResult;
}



/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

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 daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}


function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }



function removeCommas( strValue ) {
	 		    /************************************************
	 		    DESCRIPTION: Removes commas from source string.
	 
	 		    PARAMETERS:
	 		      strValue - Source string from which commas will
	 			be removed;
	 
	 		    RETURNS: Source string with commas removed.
	 		    *************************************************/
	 		      var objRegExp = /,/g; //search for commas globally
	 
	 		      //replace all matches with empty strings
	 		      return strValue.replace(objRegExp,'');
	 		    }
	 
	 
	 		      function addCommas( strValue ) {
	 		      /************************************************
	 		      DESCRIPTION: Inserts commas into numeric string.
	 
	 		      PARAMETERS:
	 			strValue - source string containing commas.
	 
	 		      RETURNS: String modified with comma grouping if
	 			source was all numeric, otherwise source is
	 			returned.
	 
	 		      REMARKS: Used with integers or numbers with
	 			2 or less decimal places.
	 		      *************************************************/
	 
	 
	 			var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');
	 
	 			  //check for match to search criteria
	 			  while(objRegExp.test(strValue)) {
	 			     //replace original string with first group match,
	 			     //a comma, then second group match
	 			     strValue = strValue.replace(objRegExp, '$1,$2');
	 			  }
	 			return strValue;
	 		      }
	 
	 
	 		      function  validateNumeric( strValue ) {
	 		      /******************************************************************************
	 		      DESCRIPTION: Validates that a string contains only valid numbers.
	 
	 		      PARAMETERS:
	 			 strValue - String to be tested for validity
	 
	 		      RETURNS:
	 			 True if valid, otherwise false.
	 		      ******************************************************************************/
	 			var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	 
	 			//check for numeric characters
	 			return objRegExp.test(strValue);
	 		      }
	 
	 
	 		    function validateNumFormat( strValue)
	 		    {
	 			var objRegExp  = /^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/;
	 			return objRegExp.test(strValue);                      
	 		     }

function openWindowUtil(url)
{
   	var windowUtil = window.open("","","resizable=yes,menubar=no,toolbar=no,scrollbars=yes,width=800,height=600,status=1") ;
   	setTimeout("", 10);
	  windowUtil.location = url;
} 

function openWindowUtil(url,windowName)
{
   	var windowUtil = window.open("",windowName,"resizable=yes,menubar=no,toolbar=no,scrollbars=yes,width=800,height=600,status=1") ;
   	setTimeout("", 10);
	  windowUtil.location = url;
}

function openWindowModalUtil(url,windowName)
{
   	var windowUtil = window.showModalDialog(url,"","dialogWidth=800,dialogHeight=600px") ;
   	setTimeout("", 10);
	  windowUtil.location = url;
}


function openWindowMaxUtil(url,windowName)
{
   	var windowUtil = window.open("",windowName,"resizable=yes,menubar=no,toolbar=no,scrollbars=yes,width=" + window.screen.availWidth + ",height="+ window.screen.availHeight + ",status=1") ;
   	setTimeout("", 10);
	  windowUtil.location = url;
    if (window.focus) {windowUtil.focus()}
} 

// ====================================================================

//       URLEncode and URLDecode functions

//

// Copyright Albion Research Ltd. 2002

// http://www.albionresearch.com/

//

// You may copy these functions providing that 

// (a) you leave this copyright notice intact, and 

// (b) if you use these functions on a publicly accessible

//     web site you include a credit somewhere on the web site 

//     with a link back to http://www.albionresarch.com/

//

// If you find or fix any bugs, please let us know at albionresearch.com

//

// SpecialThanks to Neelesh Thakur for being the first to

// report a bug in URLDecode() - now fixed 2003-02-19.

// ====================================================================

function URLEncode(plaintext )

{

            // The Javascript escape and unescape functions do not correspond

            // with what browsers actually do...

            var SAFECHARS = "0123456789" +                                                        // Numeric

                                                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +          // Alphabetic

                                                            "abcdefghijklmnopqrstuvwxyz" +

                                                            "-_.!~*'()";                                                          // RFC2396 Mark characters

            var HEX = "0123456789ABCDEF";

 

            var encoded = "";

            for (var i = 0; i < plaintext.length; i++ ) {

                        var ch = plaintext.charAt(i);

                if (ch == " ") {

                            encoded += "+";                                            // x-www-urlencoded, rather than %20

                        } else if (SAFECHARS.indexOf(ch) != -1) {

                            encoded += ch;

                        } else {

                            var charCode = ch.charCodeAt(0);

                                    if (charCode > 255) {

                                        alert( "Unicode Character '" 

                        + ch 

                        + "' cannot be encoded using standard URL encoding.\n" +

                                                          "(URL encoding only supports 8-bit characters.)\n" +

                                                                          "A space (+) will be substituted." );

                                                encoded += "+";

                                    } else {

                                                encoded += "%";

                                                encoded += HEX.charAt((charCode >> 4) & 0xF);

                                                encoded += HEX.charAt(charCode & 0xF);

                                    }

                        }

            } // for

 
			//alert("encoded => " + plaintext + " => " + encoded);
            return  encoded;

};

 

function URLDecode( encoded)

{

   // Replace + with ' '

   // Replace %xx with equivalent character

   // Put [ERROR] in output if %xx is invalid.

   var HEXCHARS = "0123456789ABCDEFabcdef"; 

   var plaintext = "";

   var i = 0;

   while (i < encoded.length) {

       var ch = encoded.charAt(i);

               if (ch == "+") {

                   plaintext += " ";

                           i++;

               } else if (ch == "%") {

                                    if (i < (encoded.length-2) 

                                                            && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 

                                                            && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {

                                                plaintext += unescape( encoded.substr(i,3) );

                                                i += 3;

                                    } else {

                                                alert( 'Bad escape combination near ...' + encoded.substr(i) );

                                                plaintext += "%[ERROR]";

                                                i++;

                                    }

                        } else {

                           plaintext += ch;

                           i++;

                        }

            } // while

   return plaintext;

};
function synchBttn() 
{
if (arguments.length > 1) 
{
for(var i=0; i < arguments.length; i++) 
{try{document.getElementById(arguments[i]).disabled=false;} catch (e) {}} 
}
}


function disableBttn() 
{
  if (arguments.length > 1) 
  {
    for(var i=0; i < arguments.length; i++) 
    {
      try{
        document.getElementById(arguments[i]).disabled=true;
      }   catch (e) {}
    } 
  }
}
function getDateObj(st) {
  var dtCh="/";
  var pos1=st.indexOf(dtCh);
  var pos2=st.indexOf(dtCh,pos1+1);
  var strMonth=st.substring(0,pos1);
  var strDay=st.substring(pos1+1,pos2);
  var strYear=st.substring(pos2+1);
  if ((strDay.charAt(0)=="0") && (strDay.length > 1)) {strDay=strDay.substring(1);}
  if (strMonth.charAt(0)=="0" && strMonth.length > 1) {strMonth=strMonth.substring(1)}
  return (new Date(strYear,strMonth-1,strDay));
}

// get current date in string formated as MM/DD/yyyy
function getCurrentDateString() {
  var cdt="";
  var d= new Date();
  
  //alert("month = " + d.getMonth());
  var mm=""+(d.getMonth()+1); //month start with 0 = Jan !!!
  
  if (mm.length < 2) {
     mm = "0" + mm; // add 0 in front eg. 09 for september
  }
  var dd= "" + d.getDate(); // remember to add "" to convert it to string
  
  //alert("dd = " + dd);  
  if (dd.length < 2) {
     dd = "0" + dd; // add 0 in front eg. 09 f
  }
  var yyyy=""+d.getFullYear();

  cdt=mm+"/"+dd+"/"+yyyy;
  return cdt;
}

function isInt(st) {
 var strNum = "0123456789";
 var i=0;
 var stChar=st.charAt(i);
 //if (stChar=="0") return false;
 for (i=0; i<st.length;i++){
   var stChar=st.charAt(i);
   if(strNum.indexOf(stChar)==-1) return false;
 } return true;
}
/*
 This function will replace all the string X to string Y in the argument, 
 it can not change the string X in certain place.
 Eg: The following will return "abcABCdefgh".
     replace("abc123defgh", "123", "ABC");
*/
function replace(argvalue, x, y) {

  if ((x == y) || (parseInt(y.indexOf(x)) > -1)) {
    errmessage = "replace function error: \n";
    errmessage += "Second argument and third argument could be the same ";
    errmessage += "or third argument contains second argument.\n";
    errmessage += "This will create an infinite loop as it's replaced globally.";
    alert(errmessage);
    return false;
  }
    
  while (argvalue.indexOf(x) != -1) {
    var leading = argvalue.substring(0, argvalue.indexOf(x));
    var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, 
	argvalue.length);
    argvalue = leading + y + trailing;
  }

  return argvalue;

}

function changeParentWindowUrl(newUrl){
   if (window.opener && !window.opener.closed) {
     window.opener.location = newUrl;
     //window.focus();
   }
}


// Original JavaScript code by Duncan Crombie: dcrombie@chirp.com.au
// Please acknowledge use of this code by including this header.

   // CONSTANTS
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function formatNumber(number, format, print) {  // use: formatNumber(number, "format")
    if (print) document.write("formatNumber(" + number + ", \"" + format + "\")<br>");

    if (number - 0 != number) return null;  // if number is NaN return null
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }
  
  function changeRole() { 
    //alert("changeRole " + window.form0.action);    
    window.form0.action = "homeAction.do";
    window.form0.submit();
    util_enableDisableButtons2(false, true);
    return true;
  }

function util_enableDisableButtons2(bEnable, bShowWaitCursor) {
//	document.body.disabled=true;
	util_enableDisableCollection2(document.body.all.tags("input"), bEnable);
	util_enableDisableCollection2(document.body.all.tags("button"), bEnable);
	util_enableDisableCollection2(document.body.all.tags("submit"), bEnable);
	util_enableDisableCollection2(document.body.all.tags("select"), bEnable);
	util_enableDisableCollection2(document.body.all.tags("a"), bEnable);
	if (bShowWaitCursor)
		cursor_wait();
}
function util_enableDisableCollection2(oCollection, bEnable) {
	for (i = 0; i < oCollection.length; i++){
		oCollection[i].disabled= !bEnable;
    oCollection[i].onclick = function(){return bEnable;}
	}
}

  
/**
 * call this function instead of directly navigating to the fileDownload action.
 * this method takes a requestion action/target uri and unlimited # of key,value params
 * NOTE: 
 *  -do not use targetFrame in your link component
 *
 * Example usages:
 * 	link with no key/value params:
 *  		<link text="${uix.current.Name}" onClick="return gl_fileDownload('fileDownload.do');" />
 *  	link with 1 key/value param:
 *			<link text="${uix.current.Name}" onClick="return gl_fileDownload('fileDownload.do','paramKey1','paramVal1');" />
 * 	link with N key/value params:
 *		  <link text="${uix.current.Name}" onClick="return gl_fileDownload('fileDownload.do','paramKey1','paramVal1',...,'paramKeyN','paramValN');" />
 **/  
function utilFileDownload(sActionUri) {
  try {
		// build url from method parameters
      var url= sActionUri+"?isPopup=yes&rnd="+new Date().getTime();
		var arglen= arguments.length;
		if (arglen==1) {
			// no further action required
		} else if (arglen%2==1) {
			for(var i=1; i < arglen; i+=2) {
				var key= arguments[i];
				var val= arguments[i+1];
//				alert("param["+i+"] key["+key+"] val["+val+"]");
				url+="&"+key+"="+val;
			}
		} else {
//			alert("invalid arguments supplied ["+arglen+"]");
			return false;
		}

//		alert(url);

		// open by navigating to the doc
      location.href=url;
		
      // open by using javascript window.open- disabled because it creates orphan window)
      //openWindow(window,url,"fileDownloadWnd",{width:800, height:600}, false, "document","");
	} catch (exception) {
//		alert(exception);
	}
  return false;
}  

/*
  call this function before you submit your form
  it will disable buttons on the form to prevent the user from double-submitting
*/  
function util_disableForm() {
  //alert('begin util_disableForm()');
  try {
     var frmEls = document.forms[0].elements;
     for (var loop=0; loop<frmEls.length; loop++){
        //alert('loop [' + loop + '] - ' + frmEls[loop].name + ' - ' + frmEls[loop].type);
        
        var type = frmEls[loop].type;
        if (( type == 'submit') || (type == 'button')){ 
          frmEls[loop].disabled = true;
        }
     }
  } catch (exception) { alert(exception);}
  
  //alert('begin util_disableForm()');
  return true;
}


// disable submit button and change the message  
// and submit the form
function util_submitAndDisableButton(objectElementId,message){
  //alert('util_submitAndDisableButton()');
  obj = document.getElementById(objectElementId);

  if (obj != null) {
    obj.disabled=true;
    obj.value=message;

    //alert('button type ' + obj.type);
    if (obj.type == 'button') {
      //alert('button type button submit form');
      obj.form.submit(); // submit if it is type button
    }
  }
  util_disableForm();
  cursor_wait(); // change cursor to wait
  return false;
}

// submit from search button and rename the button value to 'Searching ....'
function util_submitSearchButton(objectElementId){
  //alert('util_submitSearchButton()');
  return util_submitAndDisableButton(objectElementId,'Searching... Please Wait');
}

// submit from search button and rename the button value to 'Searching ....'
function util_submitSaveButton(objectElementId){
  //alert('util_submitSaveButton()');
  return util_submitAndDisableButton(objectElementId,'Saving... Please Wait');
}

// submit from search button and rename the button value to 'Searching ....'
function util_submitUpdateButton(objectElementId){
  return util_submitAndDisableButton(objectElementId,'Updating... Please Wait');
}

// submit from search button and rename the button value to 'Searching ....'
function util_submitExcelButton(objectElementId){
  return util_submitAndDisableButton(objectElementId,'Exporting to Excel... Please Wait');
}

// submit from search button and rename the button value to 'Searching ....'
function util_submitProjectButton(objectElementId){
  return util_submitAndDisableButton(objectElementId,'Exporting to MS Project... Please Wait');
}
function confirmClose()
{
  var agree=confirm("Are you sure you wish to close the window ?");
	if (agree)
	{
	  self.close();
	  return true ;
	}
	else
	  return false ;
} 
function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    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;
  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 formatDecimal(num) {
	return formatDecimal(num, 0);
}
function formatDecimal(num,iMaxDigits,iMinDigits) {
  var iDivisor= Math.pow(10,iMaxDigits);
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*iDivisor+0.50000000001);
  cents = num%iDivisor;
  num = Math.floor(num/iDivisor).toString();

  // ASSERT: num= integer part of result, cents= fractional part of result (as a positive integer)

  // add commas at appropriate locations
  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));

  var sSign= ((sign)?"":"-");
  cents= padLeft(cents.toString(),iMaxDigits,"0");
  if (iMinDigits!=undefined && iMinDigits>0)
	  cents= trimTrailingZeros(cents, iMinDigits);
  if (iMaxDigits>0)
	 return sSign + num + '.' + cents;
  else 
	 return sSign + num;
}
function padRight(sVal, iPad, sPadChar) {
  var iLen= sVal.length;
  while (sVal.length<iPad) {
	sVal= sVal+sPadChar;
  }
  return sVal;
}
function padLeft(sVal, iPad, sPadChar) {
  var iLen= sVal.length;
  while (sVal.length<iPad) {
	sVal= sPadChar+sVal;
  }
  return sVal;
}
function trimTrailingZeros(sVal, iMin) {
  sVal= sVal.replace(/0*$/,"");
  sVal= padRight(sVal,iMin,"0");
  return sVal;
}
/*
  Util for document type DropDownList with More Options.
  USEAGE:
  Parent Window: openSearchWindow(this, url)
  URL Prameters
  1. paramId to this which field the ID needs to be copied to the parent window
     Generally this field is of type Hidden and puts the PrimaryKey
  2. paramName is the dorpdownList name.
  3. taskName which could be empty.
  
*/
function openSearchWindow(obj, url) {
    var selectedText = obj.options[obj.selectedIndex].text;
    if (selectedText == 'More') {
        // alert('its is more fire the popup');
        openWindow(window, url, 'lovWindow', {width:1000, height:700}, false, 'dialog', '');
        return false;
    }
}

/*
  Will add the option to the dropdownList
*/
function addToParentList(obj, val) {
    var len = obj.length;
    var add = true;
    for (var i = 0; i < len; i++)
    {
        if (obj[i].value == val)
        {
            add = false;
            //alert('Dropdown already has the selected value');
            obj[i].selected = true;
            break;
        }
    }
    if (add)
    {
        obj[len] = new Option(val, val, '', true);
    }
}

/*
 functions used in pojectContacts.uix
*/
function addNewContact(objName) {
    var obj = document.getElementsByName(objName)[0];
    var val = obj.value;
    if (val.length == 0) {
        alert("Need to select a Role before adding to project");
    } else {
        var txt = obj.options[obj.selectedIndex].text;
        var url = "lovSearchRoleContact.do?param1=" + txt + "&amp;param2=" + val + "&amp;param3=addEvent";
        /*if(val == 21){
          var agObj = document.getElementsByName("agencyCd")[0];
          url = url+"&agencyCd="+agObj.value;
        }*/
        openWindow(window, url, 'lovWindow', {width:800, height:600}, false, 'dialog', '');
        return false;
    }
}

function makeAgencyVisible(rl) {
    var selVal = rl.value;
    var obj = document.getElementsByName("agencyCd");
    if(obj.length == 1)
    {
     var style1 = document.getElementById("agcy").style;
      if (selVal == 21) {
        style1.visibility = "visible";
      } else {
        style1.visibility = "hidden";
        }
    }else if(obj.length == 2)
    {
       var style1 = document.getElementById("agcy").style;
       var style2 = document.getElementById("agcy_uixr").style;
      if (selVal == 21) {
        style1.visibility = "visible";
        style2.visibility = "visible";
      } else {
        style1.visibility = "hidden";
        style2.visibility = "hidden";
      }
    }
   
}

function confirmSubmit()
{
    var agree = confirm("Are you sure that you want to remove the contact?");
    if (agree)
        return true;
    else
        return false;
}



// this function assume you have multi agencies project
function ptiOpenWindowNotification(url){
  try {
		//alert("url is = " + url);
    var popup=ptiIsPopup(url);
    
		// open by navigating to the doc
    if (!popup) {
      location.href=url;
		} else {
      url = url + "&isPopup=yes";
      //alert("url is = " + url);
      // open by using javascript window.open- disabled because it creates orphan window)
      openWindowMaxUtil(url,"lovWindow");
    }
	} catch (exception) {
//		alert(exception);
	}
  return false;
}

// decide wheater it is pop up or not
function ptiIsPopup(url) {
  var popup = false;
  if (url.indexOf('isMultiAgency=Y') != -1){
    popup=true;
  }
  if (url.indexOf('isMultiAgency=y') != -1){
    popup=true;
  }
  if (url.indexOf('isMultiAgency=yes') != -1){
    popup=true;
  } 
  //alert("found = " + url.indexOf('isMultiAgency=Y') + " popup = " + popup);
  return popup;
}


var util_global_reload=false;



function util_submitForm(sEvent) {
   try {
		// call local submitForm if it exists
		submitForm();
	} catch (exception) {}
	if (validateForm()) {
		if (sEvent!=undefined) {
			form0.event.value=sEvent;
		}
		form0.submit();
		util_enableDisableButtons(false, true);
		return true;
	} else {
		return false;
	}
}
function util_enableDisableButtons(bEnable, bShowWaitCursor) {
//	document.body.disabled=true;
	util_enableDisableCollection(document.body.all.tags("input"), bEnable);
	util_enableDisableCollection(document.body.all.tags("button"), bEnable);
	util_enableDisableCollection(document.body.all.tags("submit"), bEnable);
	util_enableDisableCollection(document.body.all.tags("select"), bEnable);
	util_enableDisableCollection(document.body.all.tags("a"), bEnable);
	if (bShowWaitCursor)
		cursor_wait();
}
function util_enableDisableCollection(oCollection, bEnable) {
	for (i = 0; i < oCollection.length; i++){
		oCollection[i].disabled= !bEnable;
	}
}
function util_enableDisableItem(sId, bEnable) {
	getItem(sId).disabled= !bEnable;
}
function getItem(sId) {
	var o= document.getElementById(sId);
	return o;
}
function getStringForId(sId) {
	var sVal= document.getElementById(sId).value;
	return sVal;
}
function getNumberForId(sId) {
	var sVal= document.getElementById(sId).value;
	if (sVal=='')
		return '';
	else
		return safeParseFloat(sVal);
}
function safeParseFloat(oValue) {
	if (oValue=="" || oValue==undefined)
		return "";
	oValue= stripCommas(oValue);
	return parseFloat(oValue);
}
function cleanNumber(iNum) {
// convert a number from NaN or blank to 0
	if (iNum=="")
		return 0;
	return iNum.replace(",","");
}
function round(dNum, iDigits) {
	var val;
	val=dNum*Math.pow(10,iDigits);
	val=Math.round(val);
	val=val/Math.pow(10,iDigits);
	return val;
}
function trimString(sValue) {
	return sValue.replace(/^\s*/,"").replace(/\s*$/,"");
}

function stripCommas(sValue) {
	return sValue.replace(new RegExp(",","g"),"").replace(new RegExp("\\$"),"").replace(new RegExp("%"),"");
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

/* Start of ESC keydown for info popup */
addEvent(document, 'keydown', closeInfo, false);

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("Handler could not be attached");
    }
}

function closeInfo(e){
  
  if (e.which) { // all browsers
    if (e.which == 27)
     nd();
    return;
  }
  if (window.event.keyCode) { // IE
   if (window.event.keyCode == 27)
     nd();
   return;
  }
 }
/*End of the event attaching*/

function checkLengthfix(a0,a1,a2)
{
elementLength=a0.value.length;
if(elementLength>a1)
{
a0.value=a0.value.substr(0,a1);
return true;
}
if(elementLength<a1)
{
return true;
}
if(a2.type=='change')
return true;
if(a2)
{
if((a2.which<32)
||((a2.which==118)&&(a2["ctrlKey"])))
{
 return true;

}
}
return true;
}
//----------------------------- 
//This code is for the prompting the user if there is any modification to the from
//------------------------------
function LTrim(str) {
    if (str == null) {
        return null;
    }
    for (var i = 0; str.charAt(i) == " "; i++);
    return str.substring(i, str.length);
}
function RTrim(str) {
    if (str == null) {
        return null;
    }
    for (var i = str.length - 1; str.charAt(i) == " "; i--);
    return str.substring(0, i + 1);
}
function Trim(str) {
    return LTrim(RTrim(str));
}
function LTrimAll(str) {
    if (str == null) {
        return str;
    }
    for (var i = 0; str.charAt(i) == " " || str.charAt(i) == "\n" || str.charAt(i) == "\t"; i++);
    return str.substring(i, str.length);
}
function RTrimAll(str) {
    if (str == null) {
        return str;
    }
    for (var i = str.length - 1; str.charAt(i) == " " || str.charAt(i) == "\n" || str.charAt(i) == "\t"; i--);
    return str.substring(0, i + 1);
}
function TrimAll(str) {
    return LTrimAll(RTrimAll(str));
}
//-------------------------------------------------------------------
// isNull(value)
//   Returns true if value is null
//-------------------------------------------------------------------
function isNull(val) {
    return(val == null);
}

//-------------------------------------------------------------------
// isBlank(value)
//   Returns true if value only contains spaces
//-------------------------------------------------------------------
function isBlank(val) {
    if (val == null) {
        return true;
    }
    for (var i = 0; i < val.length; i++) {
        if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n") && (val.charAt(i) != "\r")) {
            return false;
        }
    }
    return true;
}

//-------------------------------------------------------------------
// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
function isInteger(val) {
    if (isBlank(val)) {
        return false;
    }
    for (var i = 0; i < val.length; i++) {
        if (!isDigit(val.charAt(i))) {
            return false;
        }
    }
    return true;
}

//-------------------------------------------------------------------
// isNumeric(value)
//   Returns true if value contains a positive float value
//-------------------------------------------------------------------
function isNumeric(val) {
    return(parseFloat(val, 10) == (val * 1));
}

//-------------------------------------------------------------------
// isArray(obj)
// Returns true if the object is an array, else false
//-------------------------------------------------------------------
function isArray(obj) {
    return(typeof(obj.length) == "undefined")?false:true;
}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) {
    if (num.length > 1) {
        return false;
    }
    var string = "1234567890";
    if (string.indexOf(num) != -1) {
        return true;
    }
    return false;
}

//-------------------------------------------------------------------
// setNullIfBlank(input_object)
//   Sets a form field to "" if it isBlank()
//-------------------------------------------------------------------
function setNullIfBlank(obj) {
    if (isBlank(obj.value)) {
        obj.value = "";
    }
}

//-------------------------------------------------------------------
// setFieldsToUpperCase(input_object)
//   Sets value of form field toUpperCase() for all fields passed
//-------------------------------------------------------------------
function setFieldsToUpperCase() {
    for (var i = 0; i < arguments.length; i++) {
        arguments[i].value = arguments[i].value.toUpperCase();
    }
}

//-------------------------------------------------------------------
// disallowBlank(input_object[,message[,true]])
//   Checks a form field for a blank value. Optionally alerts if
//   blank and focuses
//-------------------------------------------------------------------
function disallowBlank(obj) {
    var msg = (arguments.length > 1)?arguments[1]:"";
    var dofocus = (arguments.length > 2)?arguments[2]:false;
    if (isBlank(getInputValue(obj))) {
        if (!isBlank(msg)) {
            alert(msg);
        }
        if (dofocus) {
            if (isArray(obj) && (typeof(obj.type) == "undefined")) {
                obj = obj[0];
            }
            if (obj.type == "text" || obj.type == "textarea" || obj.type == "password") {
                obj.select();
            }
            obj.focus();
        }
        return true;
    }
    return false;
}

//-------------------------------------------------------------------
// disallowModify(input_object[,message[,true]])
//   Checks a form field for a value different than defaultValue.
//   Optionally alerts and focuses
//-------------------------------------------------------------------
function disallowModify(obj) {
    var msg = (arguments.length > 1)?arguments[1]:"";
    var dofocus = (arguments.length > 2)?arguments[2]:false;
    if (getInputValue(obj) != getInputDefaultValue(obj)) {
        if (!isBlank(msg)) {
            alert(msg);
        }
        if (dofocus) {
            if (isArray(obj) && (typeof(obj.type) == "undefined")) {
                obj = obj[0];
            }
            if (obj.type == "text" || obj.type == "textarea" || obj.type == "password") {
                obj.select();
            }
            obj.focus();
        }
        setInputValue(obj, getInputDefaultValue(obj));
        return true;
    }
    return false;
}

//-------------------------------------------------------------------
// commifyArray(array[,delimiter])
//   Take an array of values and turn it into a comma-separated string
//   Pass an optional second argument to specify a delimiter other than
//   comma.
//-------------------------------------------------------------------
function commifyArray(obj, delimiter) {
    if (typeof(delimiter) == "undefined" || delimiter == null) {
        delimiter = ",";
    }
    var s = "";
    if (obj == null || obj.length <= 0) {
        return s;
    }
    for (var i = 0; i < obj.length; i++) {
        s = s + ((s == "")?"":delimiter) + obj[i].toString();
    }
    return s;
}

//-------------------------------------------------------------------
// getSingleInputValue(input_object,use_default,delimiter)
//   Utility function used by others
//-------------------------------------------------------------------
function getSingleInputValue(obj, use_default, delimiter) {
    switch (obj.type) {
        case 'radio': case 'checkbox': return(((use_default)?obj.defaultChecked:obj.checked)?obj.value:null);
        case 'text': case 'hidden': case 'textarea': return(use_default)?obj.defaultValue:obj.value;
        case 'password': return((use_default)?null:obj.value);
        case 'select-one':
            if (obj.options == null) {
                return null;
            }
            if (use_default) {
                var o = obj.options;
                for (var i = 0; i < o.length; i++) {
                    if (o[i].defaultSelected) {
                        return o[i].value;
                    }
                }
                return o[0].value;
            }
            if (obj.selectedIndex < 0) {
                return null;
            }
            return(obj.options.length > 0)?obj.options[obj.selectedIndex].value:null;
        case 'select-multiple':
            if (obj.options == null) {
                return null;
            }
            var values = new Array();
            for (var i = 0; i < obj.options.length; i++) {
                if ((use_default && obj.options[i].defaultSelected) || (!use_default && obj.options[i].selected)) {
                    values[values.length] = obj.options[i].value;
                }
            }
            return (values.length == 0)?null:commifyArray(values, delimiter);
    }
    alert("FATAL ERROR: Field type " + obj.type + " is not supported for this function");
    return null;
}

//-------------------------------------------------------------------
// getSingleInputText(input_object,use_default,delimiter)
//   Utility function used by others
//-------------------------------------------------------------------
function getSingleInputText(obj, use_default, delimiter) {
    switch (obj.type) {
        case 'radio': case 'checkbox':     return "";
        case 'text': case 'hidden': case 'textarea': return(use_default)?obj.defaultValue:obj.value;
        case 'password': return((use_default)?null:obj.value);
        case 'select-one':
            if (obj.options == null) {
                return null;
            }
            if (use_default) {
                var o = obj.options;
                for (var i = 0; i < o.length; i++) {
                    if (o[i].defaultSelected) {
                        return o[i].text;
                    }
                }
                return o[0].text;
            }
            if (obj.selectedIndex < 0) {
                return null;
            }
            return(obj.options.length > 0)?obj.options[obj.selectedIndex].text:null;
        case 'select-multiple':
            if (obj.options == null) {
                return null;
            }
            var values = new Array();
            for (var i = 0; i < obj.options.length; i++) {
                if ((use_default && obj.options[i].defaultSelected) || (!use_default && obj.options[i].selected)) {
                    values[values.length] = obj.options[i].text;
                }
            }
            return (values.length == 0)?null:commifyArray(values, delimiter);
    }
    alert("FATAL ERROR: Field type " + obj.type + " is not supported for this function");
    return null;
}

//-------------------------------------------------------------------
// setSingleInputValue(input_object,value)
//   Utility function used by others
//-------------------------------------------------------------------
function setSingleInputValue(obj, value) {
    switch (obj.type) {
        case 'radio': case 'checkbox': if (obj.value == value) {
        obj.checked = true;
        return true;
    } else {
        obj.checked = false;
        return false;
    }
        case 'text': case 'hidden': case 'textarea': case 'password': obj.value = value;return true;
        case 'select-one': case 'select-multiple':
        var o = obj.options;
        for (var i = 0; i < o.length; i++) {
            if (o[i].value == value) {
                o[i].selected = true;
            }
            else {
                o[i].selected = false;
            }
        }
        return true;
    }
    alert("FATAL ERROR: Field type " + obj.type + " is not supported for this function");
    return false;
}

//-------------------------------------------------------------------
// getInputValue(input_object[,delimiter])
//   Get the value of any form input field
//   Multiple-select fields are returned as comma-separated values, or
//   delmited by the optional second argument
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
function getInputValue(obj, delimiter) {
    var use_default = (arguments.length > 2)?arguments[2]:false;
    if (isArray(obj) && (typeof(obj.type) == "undefined")) {
        var values = new Array();
        for (var i = 0; i < obj.length; i++) {
            var v = getSingleInputValue(obj[i], use_default, delimiter);
            if (v != null) {
                values[values.length] = v;
            }
        }
        return commifyArray(values, delimiter);
    }
    return getSingleInputValue(obj, use_default, delimiter);
}

//-------------------------------------------------------------------
// getInputText(input_object[,delimiter])
//   Get the displayed text of any form input field
//   Multiple-select fields are returned as comma-separated values, or
//   delmited by the optional second argument
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
function getInputText(obj, delimiter) {
    var use_default = (arguments.length > 2)?arguments[2]:false;
    if (isArray(obj) && (typeof(obj.type) == "undefined")) {
        var values = new Array();
        for (var i = 0; i < obj.length; i++) {
            var v = getSingleInputText(obj[i], use_default, delimiter);
            if (v != null) {
                values[values.length] = v;
            }
        }
        return commifyArray(values, delimiter);
    }
    return getSingleInputText(obj, use_default, delimiter);
}

//-------------------------------------------------------------------
// getInputDefaultValue(input_object[,delimiter])
//   Get the default value of any form input field when it was created
//   Multiple-select fields are returned as comma-separated values, or
//   delmited by the optional second argument
//   (Doesn't support input types: button,file,password,reset,submit)
//-------------------------------------------------------------------
function getInputDefaultValue(obj, delimiter) {
    return getInputValue(obj, delimiter, true);
}

//-------------------------------------------------------------------
// isChanged(input_object)
//   Returns true if input object's value has changed since it was
//   created.
//-------------------------------------------------------------------
function isChanged(obj) {
    return(getInputValue(obj) != getInputDefaultValue(obj));
}

//-------------------------------------------------------------------
// setInputValue(obj,value)
//   Set the value of any form field. In cases where no matching value
//   is available (select, radio, etc) then no option will be selected
//   (Doesn't support input types: button,file,password,reset,submit)
//-------------------------------------------------------------------
function setInputValue(obj, value) {
    var use_default = (arguments.length > 1)?arguments[1]:false;
    if (isArray(obj) && (typeof(obj.type) == "undefined")) {
        for (var i = 0; i < obj.length; i++) {
            setSingleInputValue(obj[i], value);
        }
    }
    else {
        setSingleInputValue(obj, value);
    }
}

//-------------------------------------------------------------------
// isFormModified(form_object,hidden_fields,ignore_fields)
//   Check to see if anything in a form has been changed. By default
//   it will check all visible form elements and ignore all hidden
//   fields.
//   You can pass a comma-separated list of field names to check in
//   addition to visible fields (for hiddens, etc).
//   You can also pass a comma-separated list of field names to be
//   ignored in the check.
//-------------------------------------------------------------------
function isFormModified(theform, hidden_fields, ignore_fields) {
    if (hidden_fields == null) {
        hidden_fields = "";
    }
    if (ignore_fields == null) {
        ignore_fields = "";
    }
    var hiddenFields = new Object();
    var ignoreFields = new Object();
    var i,field;
    var hidden_fields_array = hidden_fields.split(',');
    for (i = 0; i < hidden_fields_array.length; i++) {
        hiddenFields[Trim(hidden_fields_array[i])] = true;
    }
    var ignore_fields_array = ignore_fields.split(',');
    for (i = 0; i < ignore_fields_array.length; i++) {
        ignoreFields[Trim(ignore_fields_array[i])] = true;
    }
    for (i = 0; i < theform.elements.length; i++) {
        var changed = false;
        var name = theform.elements[i].name;
        if (!isBlank(name)) {
            var type = theform.elements[i].type;
            if (!ignoreFields[name]) {
                if (type == "hidden" && hiddenFields[name]) {
                    changed = isChanged(theform[name]);
                }
                else if (type == "hidden") {
                    changed = false;
                }
                else {
                    changed = isChanged(theform[name]);
                }
            }
        }
        if (changed) {
            return true;
        }
    }
    return false;
}

/*End of the code prompting the user */



