/*-------------------------------------------------------------------------------
 * (c) Copyright IBM Corporation 1999, 2004. All rights reserved.
 *
 * Name:        wdt400br.js
 *
 * Description: script for field validation and formatting
 *
 * Last Modified: 2005/05/24
 *-----------------------------------------------------------------------------*/

var ValFailedArray = new Array();
var iCnt = 0;
var msgInvalid = "";

//Variables for controlling subfile input
var sfCurInputFld = null;         //The current input field
var sfCurInputFldOrigValue = "";  //The original value of the input field

/*-------------------------------------------------------------------------------
 * Function: goSetInvalid
 *-----------------------------------------------------------------------------*/
function goSetInvalid( field, status )
{
	var fieldName = field.name;
	if (field.name.indexOf("_iwcld") == 0)
		fieldName = field.name.substr(6);
			
	if( status )
	{
		var bFound = false;
		alert(fieldName + msgInvalid);
		for( i=0; i<ValFailedArray.length; i++ )
		{
			if( ValFailedArray[i] == fieldName)
			{
				bFound = true;
				break;
			}
		}
		// add to invalid array if error detected for the 1st time
		if( !bFound )
			ValFailedArray[iCnt++] = fieldName;
	}
	else
	{
		// field is good now, clear invalid entry in array
		for( i=0; i<ValFailedArray.length; i++ )
		{
			if( ValFailedArray[i] == fieldName )
			{
				//ValFailedArray.splice(i,1);
				var tempArray = new Array();
				ValFailedArray = tempArray.concat( ValFailedArray.slice(0,i),  ValFailedArray.slice(i+1) );
				iCnt--;
				break;
			}
		}
	}		
}
/*-------------------------------------------------------------------------------
 * Function: goCheckStr
 * Returns: the index of the first invalid character. 
 *-----------------------------------------------------------------------------*/
function goCheckStr( field, length )
{
	var invalidIndex = -1; 
	if (field.value == null) field.value = "";
	if( field.value.length > length )
	{
		msgInvalid = msg[5];
		goSetInvalid( field, true );
		invalidIndex = length; 
	}
	else
	{
		goSetInvalid( field, false );
	}
	return invalidIndex; 
}
/*-------------------------------------------------------------------------------
 * Function: goCheckNum
 * Returns: the index of the first invalid character. 
 *-----------------------------------------------------------------------------*/
function goCheckNum( e, length, dPos, cMinus, cDec )
{
	var allow = "0123456789+" + cDec + cMinus;
	//allow = allow + decsep;
	var val = e.value;
	var pos = dPos;
	var len = length;
	var rc = 0;
	var minusfound = false;
	var decfound = false;
	var dec = 0;
	var bval = "";
	var invalidIndex = -1;
	if (e.value == null) e.value = "";
	for(var j = 0; j <= val.length; j++)
	{
		c = val.substr(j, 1);
		if( allow.indexOf( c ) == -1)
		{
			rc = 1;
			invalidIndex = j;
			break;
		}
	}
	if( rc == 0 )
	{
		var haveSign = false; 
		for( var j = 0; j <= val.length; j++)
		{
			c = val.charAt(j);
			if( c >=0 || c<=9 || c == cDec || c == cMinus || c == '+' )
			{
				if( c == cDec && decfound == true)
				{
					rc = 2;
					invalidIndex = j;
					break;
				}
				if( c == cMinus && j!= 0 )
				{
					rc = 3;
					invalidIndex = j;
					break;
				}
				if( c == '+' && j!= 0 )
				{
					rc = 7;
					invalidIndex = j;
					break;
				}
				if( c == cDec )
					decfound = true;

				// only filter numeric and decimal
				if( (c != cMinus) && (c != '+') )
					bval += c;
				else {
					haveSign = true;
				}
			}
		}

		if (rc == 0) {
		// have decimal position
		if( pos != 0 )
		{
			dec = bval.indexOf(cDec);
			// decimal char exist
			if( dec != -1 )	
			{
				// check decimal length
					if( (bval.length - dec - 1) > pos ) {
					rc = 2;
						invalidIndex = parseInt(dec) + parseInt(pos) + parseInt(1);
					}
				// check numeric len before decimal
					if( dec > (len - pos) ) {
				        rc = 4;
						invalidIndex = parseInt(len) - parseInt(pos);
					}
			}
			else
			{
					if( bval.length > (len - pos) ) {
					rc = 4;
						invalidIndex = parseInt(len) - parseInt(pos);
					}
				}
			
				//Adjust index if have a sign
				if (invalidIndex > -1 && haveSign) {
					invalidIndex = parseInt(invalidIndex) + parseInt(1);
				}
			
		}
		else
		{
			dec = bval.indexOf(cDec);
			// decimal char exist
				if( dec != -1 )	{
				rc = 2;
					invalidIndex = dec;
				}
				else if( (bval.length) > len ) {
				rc = 4;
					invalidIndex = len;
				}
			
				//Adjust index if have a sign
				if (invalidIndex > -1 && haveSign) {
					invalidIndex = parseInt(invalidIndex) + parseInt(1);
				}			
			}
		}
	}
	
	if( rc != 0 )
	{
		msgInvalid = msg[rc];
		goSetInvalid( e, true );
	}
	else
	{
		goSetInvalid( e, false );
	}
	
	return invalidIndex;
}

/*-------------------------------------------------------------------------------
 * Function: goCheckTruncateStr
 *           Same as goCheckStr except it strips out the invalid characaters.
 *-----------------------------------------------------------------------------*/
function goCheckTruncateStr( field, length )
{
	var idx = -1;
	idx = goCheckStr(field, length);
	if (idx > -1) {
		var newval = field.value.substr(0, idx);
		field.value = newval;
	}
}

/*-------------------------------------------------------------------------------
 * Function: goCheckTruncateNum
 *           Same as goCheckNum except it strips out the invalid numeric characaters.
 *-----------------------------------------------------------------------------*/
function goCheckTruncateNum( e, length, dPos, cMinus, cDec )
{
	var idx = -1;
	idx = goCheckNum(e, length, dPos, cMinus, cDec);
	if (idx > -1) {
		var newval = e.value.substr(0, idx);
		e.value = newval;
	}
}

/*-------------------------------------------------------------------------------
 * Function: setCaretAtEnd
 *           Moves the caret to end of field.
 *-----------------------------------------------------------------------------*/
function setCaretAtEnd (field) {
  if (field.createTextRange) {
     var r = field.createTextRange();
     r.moveStart('character', field.value.length);
     r.collapse();
     r.select();
   }
   else if (field.setSelectionRange) { 
    field.focus();
    var length = field.value.length;
    field.setSelectionRange(length, length);
  }   
}

/*-------------------------------------------------------------------------------
 * Function: resetSFInputFocus
 *           Regains the focus for the current subfile field that is being edited.
 *-----------------------------------------------------------------------------*/
function resetSFInputFocus() {
      //Reset focus for current subfile field
      sfCurInputFld.focus();
	  //Move caret to end of field
      setCaretAtEnd(sfCurInputFld);            
}

/*-------------------------------------------------------------------------------
 * Function: setupIWCLHidden
 *           Setup the IWCL hidden field. The values in this field are used
 *           by the server side.
 *-----------------------------------------------------------------------------*/
function setupIWCLHidden(field, iwclHiddenName) 
{
    var fieldValue = field.value;
    if (field.type == 'checkbox') {
       fieldValue = "false";
       if (field.checked) {
          fieldValue = "true";
       }
    }    
    var hiddenValue = field.form.name + "," + field.name + "," + fieldValue; 

    //Save changed cell's name to hidden field
    var hidden = field.form.elements[iwclHiddenName];
    if (hidden == null) {
        hidden = document.createElement( "INPUT" );
        with ( hidden )
        {
            type  = "hidden";
            id    = iwclHiddenName;
            name  = iwclHiddenName;
        }
        field.form.appendChild(hidden);        
    }    
    hidden.value = hiddenValue; 
     
    //Copy hidden field to the submit form
    var submitForm = findSubmitForm();
    if (submitForm != null) {
       var hidden = submitForm.elements[iwclHiddenName];
       if (hidden == null) {
            hidden = document.createElement( "INPUT" );
            with ( hidden )
            {
                type  = "hidden";
                id    = iwclHiddenName;
                name  = iwclHiddenName;
            }
            submitForm.appendChild(hidden);        
       }
       hidden.value = hiddenValue; 
    }         
}

/*-------------------------------------------------------------------------------
 * Function: handleSFInputOnFocus
 *           Handles onFocus event for subfile input entries
 *-----------------------------------------------------------------------------*/
function doSFInputOnFocus(field, rawValue) 
{
   //Only reset if there is no current field
   if (sfCurInputFld == null) {

      //Save the current input field
      sfCurInputFld = field;

      //Restore the raw value so user can edit with having to deal 
      //with formatting (edit code) characters.
      sfCurInputFld.value = rawValue;

      //Save the original value so we can use it to detect a change in the 
      //field's value.
      sfCurInputFldOrigValue = rawValue;

	  //Move caret to end of field
      setCaretAtEnd(sfCurInputFld);      
   }  
}

/*-------------------------------------------------------------------------------
 * Function: handleSFInputOnBlur
 *           Handles onBlur event for subfile input entries
 *-----------------------------------------------------------------------------*/
function doSFInputOnBlur( field, length, dPos, cMinus, cDec, displayValue, iwclHidden,
				      formName, actionName, actionValue, 
					anchorName, actionNameEnc, wclhidden, 
					wclanchor) 
 
{
   //Only handle the current field.
   if (field != sfCurInputFld) {
      return;
   }

   var idx = -1;
   if (dPos == '' && cDec == '' && cMinus == '') {
      idx = goCheckStr(field, length);
   } 
   else {
      idx = goCheckNum(field, length, dPos, cMinus, cDec);
   }

   if (idx > -1) {
      //reset the focus after 100 ms   
      setTimeout('resetSFInputFocus()', 100);
   }
   else {
      if (sfCurInputFldOrigValue != sfCurInputFld.value) {
         //The field is valid, submit the changes
         doTbl(formName, actionName, actionValue, anchorName, actionNameEnc, wclhidden, wclanchor);
      }
      else {
         //The field is valid but there is no change... display the formatted value.
         sfCurInputFld.value = displayValue;
      }

      //Reset controls since the field is no longer in error.
      sfCurInputFld = null;
      sfCurInputFldOrigValue = "";
	}
}

/*-------------------------------------------------------------------------------
 * Function: handleSFInputOnBlur
 *           Handles onChange event for subfile checkbox and combo box.
 *-----------------------------------------------------------------------------*/
function doSFInputOnCheckComboChange( field, iwclHidden, formName, actionName, actionValue, 
					anchorName, actionNameEnc, wclhidden, wclanchor) 
 
{
    //doTbl requires the current subfile field.
    sfCurInputFld = field;
      
    //Submit the changes
    doTbl(formName, actionName, actionValue, anchorName, actionNameEnc, wclhidden, wclanchor);
}

/*-------------------------------------------------------------------------------
 * Function: findSubmitForm
 *           Find and return the form containing the submit button.
 *-----------------------------------------------------------------------------*/
function findSubmitForm() {
   var actionIsFound = false;
   var onsubmitIsFound = false;
   for (i=0; i < document.forms.length; i++) {
     var f = document.forms[i];
     for (j=0; f.attributes != null && j < f.attributes.length; j++) {
        var a = f.attributes[j];
        if (a.specified && a.nodeName == "action" && a.nodeValue.length > 0) {
		   actionIsFound = true;        
        }
        if (a.specified && a.nodeName == "onsubmit" && a.nodeValue.indexOf("isSubmitOK") > -1) {
		   onsubmitIsFound = true;        
        }        
        if (actionIsFound && onsubmitIsFound ) {
            return f;
         }
      }
   }
   return null;
}

/*-------------------------------------------------------------------------------
 * isSubmitOK
 *-----------------------------------------------------------------------------*/
function  isSubmitOK()
{
	if( ValFailedArray.length != 0 )
	{
		// promte user which field is invalid
		var fields = "";
		for( i=0; i<ValFailedArray.length; i++ )
		{
			fields += ValFailedArray[i] + " ";
		}
		alert( msg[6] + fields );
		return false;
	}
	else
	{
		return true;
	}
}



/*--------------------------------------------------------------
Function: normalizeNumber()

Returns a normalized version of the val parameter.

Throws a 64 if there are signs at both ends.
Throws a 33 if there is more than one decimal seperator included.

- Trims whitespace from the begin and end of val parameter.
- Removes any characters that are not digits, a negative sign at either end,
  or space embedded in digits.
- Replaces all embedded spaces with zeroes.
- Any valid negative sign (at either end) will always be moved to
  the first character.
----------------------------------------------------------------*/
function normalizeNumber(val)
{
  var normNumber = ""; //The normalized version of the number.
  var c;
  var decfound = false;
  var minusfound = false;

  // remove trailing and leading spaces
  val = trimLeadingSpaces( val );
  val = trimTrailingSpaces( val );

  // add in code to prevent having signs on both sides of value
  if ((val.charAt( 0 ) == "-" || val.charAt( 0 ) == "+" ) &&
      ( val.charAt( val.length-1 ) == "-" || val.charAt( val.length-1 ) == "+" ))
  {
    throw 64;
  }

  // checks each char to ensure valid dec and minus
  for( var j = 0; j < val.length; j++)
  {
    c = val.charAt(j);
    var number = c >= "0" && c <= "9";
    if( c >= '0' && c <= "9" || c == decsep || c == "-" || c == " ")
    {
      if (c == decsep && decfound == true)
      {
        throw 33;
      }

      // ignores any other signs not in first char pos
      if (( c == "-" && j != 0) && (c == "-" && j != val.length -1))
      {
        continue;
      }

      // only valid minus
      if (c == "-" && ( j == 0 || j == val.length - 1))
      {
        minusfound = true;
        continue;
      }

      if( c == decsep )
      {
        decfound = true;
      }

      normNumber += c;
    }
  }

  // trim trailing spaces that are embedded within following +/-
  normNumber = trimTrailingSpaces( normNumber );
  normNumber = replaceSpaceWithZero( normNumber );
  normNumber = trimLeadingZeroes( normNumber );

  if ( minusfound )
  {
    var normNumber = "-" + normNumber;
  }

  return normNumber;
}

/*-----------------------------------------------------------------------------
 * function trimLeadingChars( val , c )
 *       val : the string to apply trim on.
 *         c : the char which is to be removed.
 *   returns : the trimmed string.
 *-----------------------------------------------------------------------------*/
function trimLeadingChars( val , c )
{  var re ;
   /**
    * Regex -> /^[c]+/
    *           | |
    *           | +--- match one or more char set consisting of 'c'
    *           |
    *           +----- match the start of the line
    */
   if(c == ' ') { re = /^[ ]+/ ; }
   else if(c == '0') { re = /^[0]+/ ; }
   else { re = new RegExp('^[' + fixCharForRegex(c+'') + ']+') ; }
   return (val+'').replace(re,'') ;
}

/*-----------------------------------------------------------------------------
 * function trimTrailingChars( val , c )
 *       val : the string to apply trim on.
 *         c : the char which is to be removed.
 *   returns : the trimmed string.
 *-----------------------------------------------------------------------------*/
function trimTrailingChars( val, c )
{  var re ;
   /**
    * Regex -> /[c]+$/
    *            |  |
    *            |  +--- match end of the line
    *            |
    *            +----- match one or more char set consisting of 'c'
    */
   if(c == ' ') { re = /[ ]+$/ ; }
   else if(c == '0') { re = /[0]+$/ ; }
   else { re = new RegExp('[' + fixCharForRegex(c+'') + ']+$') ; }
   return (val+'').replace(re,'') ;
}

/*----------------------------------------------------------------------
  Function: trimLeadingSpaces
       Remove the leading spaces from the value.
 -----------------------------------------------------------------------*/
   function trimLeadingSpaces( val ){
      return trimLeadingChars( val, " " );
   }


/*----------------------------------------------------------------------
 Function: trimTrailingSpaces
        Remove the trailing spaces from the value.
 -----------------------------------------------------------------------*/
   function trimTrailingSpaces( val ){
      return trimTrailingChars( val, " " );
   }

/*-----------------------------------------------------------------------------
  Function: replace
	 extension of some string functions in Java that apparently are not
	 supported the same way in Javascript.
  ----------------------------------------------------------------------------*/
function replace(stringVal, oldChar, newChar){
	if ((stringVal.length == 0) || (oldChar == newChar)){
		return stringVal;
	} else  {
		var index = stringVal.indexOf(oldChar);
		var length = stringVal.length;
		while(index >= 0){
			stringVal = stringVal.substring(0, index) + newChar + stringVal.substring(index+1, length);
			index=stringVal.indexOf(oldChar);
		}
		
	}
	return stringVal;
}

	
/*-----------------------------------------------------------------------------
  Function: StringBuffer
  		Equivalent to Java's StringBuffer class
  ----------------------------------------------------------------------------*/
function StringBuffer(value){
	var strVal = "";

	if(!(/^\d+$/).test(value)){
		append(value);
	} else {
		strVal="";
	}	
	
	this.append=function(value){
		strVal+=value;
	}
	
	this.getString=function(){
		return strVal.toString();
	}
	
	this.getNumber=function(){
		return (strVal*1);
	}	
	
	this.length = function(){
		return strVal.toString().length;
	}
	
	function isChar(ch){
		var non_word = (/^\W{1}$/).test(ch); // letters, numbers, underscore
		var word = (/^\w{1}$/).test(ch);
		var non_space = (/^\S{1}$/).test(ch);
		var space = (/^\s{1}$/).test(ch);	
		var non_digit = (/^\D{1}$/).test(ch);			
		var digit = (/^\d{1}$/).test(ch);

		return (non_word || word || non_space || space || non_digit || digit);		
	}
	
	function getString(value){
		return value.toString();
	}
	
	function append(value){
		strVal=strVal+value;
		return strVal;
	}
		
	this.toString = function(){
		return getString(strVal);
	}
	
	this.charAt = function(index){
		return strVal.charAt(index);
	}
			
	this.setCharAt=function(index, ch){
		strVal = getString(strVal);
		var length=strVal.length;
		if(length > index && index >= 0 && isChar(ch)){
			if (strVal.charAt(index) != ch) {
				strVal = strVal.substring(0,index) + ch + strVal.substring(index+1, length);
			}
		}
	}
	
	this.insert = function(offset, value){
		strVal = getString(strVal);
		var length=strVal.length;
		if(length > offset && offset > 0){
			strVal = strVal.substring(0,offset) + value + strVal.substring(offset, length);

		} else if(length > offset && offset == 0){

			strVal = value + strVal;


		} else if (length == offset){
			append(value);
		}
		
	}
	
	this.setLength=function(len){
		strVal = strVal.substring(0, len);
	}
	

}
/*------------------------------------------------------------------------------------
    Function: checkValues
    VALUES(list of values) .e.g VALUES('A' 'B' 'C'), VALUES(0, 1, 2)
    - ensures the value is in the list of values
 ------------------------------------------------------------------------------------*/
function checkValues( elem, datatype, values, delimiter )
{
    var value = elem.value;
   	if (value == null) value = "";
    value = value.toUpperCase();

    if( datatype == "numeric" )
	{
		// For numeric fields, replace spaces with zeros
		// so that 1_2 will be recognized as 102 just as
		// 5250 does.
		value = normalizeNumber(value);
    }

	value = trimTrailingSpaces(value);

    // Check for VALUES by comparing elements value to the values
    // in it's 'values' attribute list.
    var y = 0;
    var temp;
    var found = false;
    var x = values.indexOf( delimiter );
    while( x != -1 )
    {
         temp = values.substring(y, x);
         // the trailing spaces are trimmed, normalizing with the value
         temp = trimTrailingSpaces (temp);
         temp = temp.toUpperCase();

         // if the field is numeric, make variables numeric for compare
         if( datatype == "numeric" )
         {
             temp = normalizeNumber(temp);
         }

         y = x + 1;
         if( value == temp )
         {
            found = true;
            break;
         }
         x = values.indexOf( delimiter, y );
         if (x == -1)
         {
         	if (y < values.length) x = values.length;
         }
    }
    if( !found )
    {
		msgInvalid = msg[8];
		goSetInvalid( elem, true );
		return -1;
    }
    else
    {
		goSetInvalid( elem, false );  
		return 0;
	}
} // end VALUES

/*-----------------------------------------------------------------------------------
   Function: checkStrRange
   Check for RANGE by comparing the elements value to the
   hi and lo value of the elements 'range' attribute.
   RANGE(lo hi) e.g. RANGE('A' 'Z')
   ensures the value falls between the lower and upper limit
-------------------------------------------------------------------------------------*/
function checkStringRange( elem, lo, hi )
{
	var value = elem.value;
	
	if (value == null) value = "";
	if (value.localeCompare(lo) < 0 ||
		value.localeCompare(hi) > 0)
    {
    	msgInvalid = setMessageParameters(msg[9], lo, hi);
		goSetInvalid( elem, true );
        return -1;
    }
    else
    {
		goSetInvalid( elem, false );      
        return 0;
    }
}


/*--------------------------------------------------------------------------------------
  setMessageParameters(message, parm1, parm2)
  -------------------------------------------------------------------------------------*/
function setMessageParameters(message, parm1, parm2)
{
    	var i;
    	var indx = -1;
    	var mesg = message;
    	while ((indx = mesg.indexOf("%")) > -1)
    	{
    		i = mesg.charAt(indx+1);
    		if (i == '1')
    		{
    			mesg = mesg.substring(0, indx) + parm1 + mesg.substring(indx+2);
    		}
    		else
    		{
    			mesg = mesg.substring(0, indx) + parm2 + mesg.substring(indx+2);
    		}
    	}
		return mesg;
}   	

/*--------------------------------------------------------------------------------------
  setMessageParameters(message, parm1, parm2, parm3)
  -------------------------------------------------------------------------------------*/
function setMessageParameters(message, parm1, parm2, parm3)
{
    	var i;
    	var indx = -1;
    	var mesg = message;
    	while ((indx = mesg.indexOf("%")) > -1)
    	{
    		i = mesg.charAt(indx+1);
    		if (i == '1')
    		{
    			mesg = mesg.substring(0, indx) + parm1 + mesg.substring(indx+2);
    		}
    		else if (i == '2')
    		{
    			mesg = mesg.substring(0, indx) + parm2 + mesg.substring(indx+2);
    		}
    		else 
    		{
    			mesg = mesg.substring(0, indx) + parm3 + mesg.substring(indx+2);
    		}    	
    	}
		return mesg;
}   	
/*-----------------------------------------------------------------------------------
  checkComp( elem ) helper function
 ------------------------------------------------------------------------------------*/
   function fixStringForComp(s)
   {  var str = s + '' ;
      if(str == "")
      {  str = '" "' ;
      }
      else if(str.search(/[^0-9]/g) != -1) /* if string is non-numeric then */
      {  str = str.replace(/["]/g,"\\\"") ;
         str = str.replace(/[']/g,"\\\'") ;
         str = '"' + str + '"' ;
      }
      return str ;
   }

/*-----------------------------------------------------------------------------------
    Check for COMP.  The comparison operator can be one of the following:
    EQ NE LT NL GT NG LE GE
    == != <  !< >  !> <= >=
    Note that comparison is being done on the client, in ASCII
    COMP(comparator value) e.g. COMP(EQ 'SOMEVALUE'), COMP(GT 10)
    ensures the value matches the comparison
------------------------------------------------------------------------------------*/
function checkStringComp( elem, compType, compareValue)
{
    var COMP = "EQ NE LT NL GT NG LE GE";
    var CMP  = "== != <  !< >  !> <= >=";
    var tmpCmp;
    var expr;
    var elemValue = elem.value;
    var y = COMP.indexOf( compType );

	if (elemValue == null) elemValue = "";
   	// trim trailing spaces for all values because the 5250 acts as if they're ignored
   	elemValue = trimTrailingSpaces(elemValue);
    compareValue = trimTrailingSpaces(compareValue);
   	msgInvalid = setMessageParameters(msg[10], compType, compareValue);

	// NE ""
	if (compType == "NE" && compareValue == "" && elemValue == "")
    {
	   	msgInvalid = setMessageParameters(msg[11]);
		goSetInvalid( elem, true );
        return -1;
    }

    // NG and NL require special processing since there
    // is no JavaScript equivalent
    if( compType != "NL" && compType != "NG" )
    {
         tmpCmp = CMP.substr( y, 2 ); // get JavaScript comparison operator

         var b ;
         try
         {
             expr = '"' + elemValue + '" ' + tmpCmp + ' "' + compareValue + '"' ; //46503
             b = eval( expr ) ;
             if(b == null) throw msg[12];
         }
         catch(any_exception) /* input data may be all blanks or may have symbols (like {+,",'} etc) */
         {
            var elemValuetmp = fixStringForComp(elemValue) ;
            var compareValuetmp = fixStringForComp(compareValue) ;
            var exprtmp = elemValuetmp + ' ' + tmpCmp + ' ' + compareValuetmp ;
            b = eval( exprtmp ) ;
         }

         if( b != true )
         {
			goSetInvalid( elem, true );
            return -1;
         }
         else
         {
			goSetInvalid( elem, false );  
         	return 0;
         }
     }
     else
     {
         if( compType == "NL" )
         {
             if( elemValue.localeCompare(compareValue) < 0 )
             {
				goSetInvalid( elem, true );
                return -1;
             }
             else
             {
             	goSetInvalid( elem, false );  
                return 0;
             }
         }
         else
         {
            if (elemValue.localeCompare(compareValue) > 0)
            {
				goSetInvalid( elem, true );
                return -1;
            }
            else
            {
           		goSetInvalid( elem, false );  
                return 0;
            }
         }
    }
} // end COMP

/**
 * Any plus or minus sign at the end are moved to the front
 */
function moveTrailingSignToFront(str)
{
	var finalStr = "";
	
	if (str.indexOf('-') > 0)
	{
		finalStr = '-' + str.substring(0, str.length-1);
	}
	else if (str.indexOf('+') > 0)
	{
		finalStr = '+' + str.substring(0, str.length-1);
	}
	else
		finalStr = str;
		
	return finalStr;
}

/**
 * Convert the incoming numeric string from decimalSymbol to '.'
 */
function convertDecimalPoint(str, decimalPoint)
{
	var tempStr = "";
	var decimalOffset = str.indexOf(decimalPoint);
	if (decimalOffset >= 0)
	{
		tempStr = str.substring(0, decimalOffset) + '.' + str.substring(decimalOffset+1);
	}
	else tempStr = str;
	
	return tempStr;
}

function checkNumericRange( elem, minValueStr, maxValueStr, dataLength, decimalPlaces, decimalSymbol )
{
	var strData = elem.value;
	var ok = false;
	var tempStr;
	var numeric;
	var decimalOffset;
	var maxValue;
	var minValue;
    msgInvalid = setMessageParameters(msg[9], minValueStr, maxValueStr);
	try
	{
		tempStr = moveTrailingSignToFront(strData);

		// If decimalSymbol is not '.', convert it to '.' before converting
		// the string to a Double.
		if (decimalSymbol != '.')
		{
			tempStr = convertDecimalPoint(tempStr, decimalSymbol);
		}
		// Convert the string data to a double value	
		numeric = parseFloat(tempStr);

		// If decimalSymbol is not '.', convert it to '.' before converting
		// the string to a Double.
		decimalOffset = maxValueStr.indexOf(decimalSymbol);
		if (decimalOffset >= 0) maxValueStr = convertDecimalPoint(maxValueStr, decimalSymbol);
		maxValueStr = moveTrailingSignToFront(maxValueStr);

		decimalOffset = minValueStr.indexOf(decimalSymbol);
		if (decimalOffset >= 0) minValueStr = convertDecimalPoint(minValueStr, decimalSymbol);
		minValueStr = moveTrailingSignToFront(minValueStr);

		// if min value is not set
		if (minValueStr == "")
		{
			maxValue = parseFloat(maxValueStr);
			if (numeric <= maxValue) ok=true;
		}
		// else if max value is not set
		else if (maxValueStr == "")
		{
			minValue = parseFloat(minValueStr);
			if (numeric >= minValue) ok=true;
		}
		else
		{
			minValue = parseFloat(minValueStr);
			maxValue = parseFloat(maxValueStr);
			if (numeric >= minValue && numeric <= maxValue) ok=true;
		}
	}
	catch (any_exception)
	{
		ok = false;
	}

    if (!ok)
    {
		goSetInvalid( elem, true );
        return -1;
    }

	goSetInvalid( elem, false );  
   	return 0;
}

function checkNumericComp( elem, compType, compareValue, dataLength, decimalPlaces, decimalSymbol )
{
	var strData = elem.value;
	var ok = false;
	var tempStr;
	var numeric;
	var decimalOffset;
	var compValue;
   	msgInvalid = setMessageParameters(msg[10], compType, compareValue);

	try
	{
		// NE ""
		if (compType == "NE" && compareValue == "" && strData == "")
	    {
		   	msgInvalid = setMessageParameters(msg[11]);
			goSetInvalid( elem, true );
	        return -1;
      	}

		tempStr = moveTrailingSignToFront(strData);

		// If decimalSymbol is not '.', convert it to '.' before converting
		// the string to a Double.
		if (decimalSymbol != ".")
		{
			tempStr = convertDecimalPoint(tempStr, decimalSymbol);
		}

		// Convert the string data to a double value	
		numeric = parseFloat(tempStr);
			
		// If decimalSymbol is not '.', convert it to '.' before converting
		// the string to a Double.
		decimalOffset = compareValue.indexOf(decimalSymbol);
		if (decimalOffset >= 0) compareValue = convertDecimalPoint(compareValue, decimalSymbol);
		compareValue = moveTrailingSignToFront(compareValue);
		compValue = parseFloat(compareValue);

		if (compType == "EQ")
		{
			if (numeric == compValue)	ok = true;
		}
		else if (compType == "NE")
		{
			if (numeric != compValue)	ok = true;
		}
		else if (compType == "LT")
		{
			if (numeric < compValue)	ok = true;
		}
		else if (compType == "NL" || compType == "GE")
		{
			if (numeric >= compValue)	ok = true;
		}
		else if (compType == "GT")
		{
			if (numeric > compValue)	ok = true;
		}
		else if (compType == "NG" || compType == "LE")
		{
			if (numeric <= compValue)	ok = true;
		}
	}
	catch (any_exception)
	{
		ok = false;
	}

	if (!ok)
	{
		goSetInvalid( elem, true );
		return -1;
	}

	goSetInvalid( elem, false );  
	return 0;
}
/******************************************************************
 * EditcodeEditwordFormatter
 ******************************************************************/

 function EditcodeEditwordFormatterClass() {
	
	/**
	* Editcode parameter type is none.
	*/
	var EDITCODEPARM_NONE       	= 0;

	/**
	* Editcode parameter type is '*'
	*/
	var EDITCODEPARM_ASTERISK   	= 1;
	/**
	* Editcode parameter type is the currency symbol
	*/
	var EDITCODEPARM_CURRENCY   	= 2;

	var editCode                	= '0';
	var editWord                	= "";
	var editCodeParmType        	= EDITCODEPARM_NONE;
	var currencySymbolStr          	= "$";
	var thousandSeparator			= ",";
	var dateSeparator            	= '/';
	var dataAttributes           	= null;
	var bBlankIfZero             	= false;
	var bFloatingMinus         	  	= false;
	var bAsteriskProtected     	  	= false;
	var bDateSeparator         	  	= false;
	var bShowNegative          	  	= true;
	var iEndZeroSuppressionIndex 	= -1;
	var iExpansionIndex         	= -1;
	var iFloatingCurrency       	= -1;
	var iFormattedLength       	  	= -1;
	var iStatusIndex           	  	= -1;
	var i_FieldLength          	  	= 0;
	var i_FieldPrecision       	  	= 0;
	var strEditWord            	  	= new String("");
	var qdecfmtJValue        	  	= false;
	this.Copyright = "(C) Copyright IBM Corp. 2002 All rights reserved.";
		



/*---------------------------------------------------------------------------
 * Function: convertEditCodeToEditWord
 *---------------------------------------------------------------------------*/
	function convertEditCodeToEditWord(iFieldLength, iFieldPrecision, cEditCode, iEditCodeParameterType){
		var iIndex; // int
		var strbufEditWord = new StringBuffer( iFieldLength );
		bAsteriskProtected = false;
	
		// Set date format slashes
		//------------------------
		if( cEditCode == 'Y' )
		{
			// Date edit code
			//---------------
			bDateSeparator = true;
			
			iIndex = iFieldLength > 4 ? iFieldLength + 2 : iFieldLength + 1;

			// Insert spaces for digits and commas for separators if required
			//---------------------------------------------------------------
			for( var i=1; i<=iIndex; ++i )
			{
				strbufEditWord.insert( 0, ' ');
			}
			
			// Set date format slashes
			//------------------------
			if( iFieldLength >= 8)
			{
				iIndex = strbufEditWord.length() - 1;
				strbufEditWord.setCharAt( iIndex - 4, '/' );
				strbufEditWord.setCharAt( iIndex - 7, '/' );
				strbufEditWord.setCharAt( iIndex - 9, '0' );
			}
			else if( iFieldLength >= 7 )
			{
				iIndex = strbufEditWord.length() - 1;
				strbufEditWord.setCharAt( iIndex - 2, '/' );
				strbufEditWord.setCharAt( iIndex - 5, '/' );
				strbufEditWord.setCharAt( iIndex - 7, '0' );
			}
			else if( iFieldLength >= 5 )       // 0n/nn/n, 0n/nn/nn
			{
				strbufEditWord.setCharAt( 0, '0' );
				strbufEditWord.setCharAt( 2, '/' );
				strbufEditWord.setCharAt( 5, '/' );
			}
			else if( iFieldLength >= 3 )              // 0n/n, 0n/nn
			{
				strbufEditWord.setCharAt( 0, '0' );
				strbufEditWord.setCharAt( 2, '/' );		
			}
			
			bBlankIfZero = false;
			bFloatingMinus = false;
			iStatusIndex = -1;
		
		}
		else if( cEditCode == 'W' )
		{
			// Date edit code
			//---------------
			bDateSeparator = true;
			
			iIndex = iFieldLength > 7 ? iFieldLength + 2 : iFieldLength + 1;
			
			// Insert spaces for digits and commas for separators if required
			//---------------------------------------------------------------
			for( var i=1; i<=iIndex; ++i )
			{
				strbufEditWord.insert( 0, ' ' );
			}
			
			// Set date format slashes
			//------------------------
			if( iFieldLength >= 8)      // nn0n/nn/nn
			{
				iIndex = strbufEditWord.length() - 1;
				strbufEditWord.setCharAt( iIndex - 2, '/' );
				strbufEditWord.setCharAt( iIndex - 5, '/' );
				strbufEditWord.setCharAt( iIndex - 7, '0' );
			}
			else if( iFieldLength >= 7 )    // nn0n/nnn
			{
				iIndex = strbufEditWord.length() - 1;
				strbufEditWord.setCharAt( iIndex - 3, '/' );
				strbufEditWord.setCharAt( iIndex - 5, '0' );
			}
			else if( iFieldLength >= 6 )      // nn0n/nn
			{
				iIndex = strbufEditWord.length() - 1;
				strbufEditWord.setCharAt( iIndex - 2, '/' );
				strbufEditWord.setCharAt( iIndex - 4, '0' );
			}
			else if( iFieldLength >= 5 )      // 0n/nnn
			{
				strbufEditWord.setCharAt( 0, '0' );
				strbufEditWord.setCharAt( 2, '/' );
			}
			else if( iFieldLength >= 3 )      //37577
			{
				strbufEditWord.setCharAt( 2, '/' );
			}
			
			bBlankIfZero = false;
			bFloatingMinus = false;
			iStatusIndex = -1;			
		}
		// Not editcode Y and W
		else
		{
			// Not date editcode
			//------------------
			iIndex = iFieldLength - iFieldPrecision;
			
			// Insert spaces for digits and commas for separators if required
			//---------------------------------------------------------------
			for( var i=1; i<=iIndex; ++i )
			{
				strbufEditWord.insert( 0, " " );
				
				if( i % 3 == 0 && i != iIndex &&
				( cEditCode=='1' || cEditCode=='2' ||
				cEditCode=='A' || cEditCode=='B' ||
				cEditCode=='J' || cEditCode=='K' ||
				cEditCode=='N' || cEditCode=='O'    ) )
				{
					strbufEditWord.insert( 0, "," );
				}
			}
			
			var tiEndZeroSuppressionIndex = strbufEditWord.length() - 1;
			if( iFieldPrecision == 0 )
			{
				--tiEndZeroSuppressionIndex;
			}
					
			if( tiEndZeroSuppressionIndex >= 0 )
			{
				if( iEditCodeParameterType == EDITCODEPARM_ASTERISK )
				{
					strbufEditWord.setCharAt( tiEndZeroSuppressionIndex, '*' );
				}
				else
				{
					strbufEditWord.setCharAt( tiEndZeroSuppressionIndex, '0' );
				}
			}
			else
			{
				tiEndZeroSuppressionIndex = 0;
			}
			
			if( iEditCodeParameterType == EDITCODEPARM_CURRENCY )
			{
				// Insert before the zero suppression character
				//---------------------------------------------
				strbufEditWord.insert( tiEndZeroSuppressionIndex, '$' );
			}
			else if( iEditCodeParameterType == EDITCODEPARM_ASTERISK )
			{
				bAsteriskProtected = true;
			}
			
			if( iFieldPrecision > 0 )
			{
				strbufEditWord.append( '.' );
				
				for( var i=0; i<iFieldPrecision; ++i )
				{
					strbufEditWord.append( ' ' );
				}
			}
		}		


	    switch( cEditCode )
	    {
	        case '2': case '4': case 'B': case 'D':
	        case 'K': case 'M': case 'O': case 'Q': case 'Z':
	            bBlankIfZero = true;
	            break;
	
	        default:
	            bBlankIfZero = false;
	            break;
	    }
	
	    bFloatingMinus = false;
	    switch( cEditCode )
	    {
	        case '1': case '2': case '3': case '4': case 'Y': case'W':
	            iStatusIndex = -1;
	            break;
	
	        case 'A': case 'B': case 'C': case 'D':
	            iStatusIndex = strbufEditWord.length();
	            strbufEditWord.append( "CR" );
	            break;
	
	        case 'J': case 'K': case 'L': case 'M':
	            iStatusIndex = strbufEditWord.length();
	            strbufEditWord.append( '-' );
	            break;
	
	        case 'N': case 'O': case 'P': case 'Q':
	            bFloatingMinus = true;
	            iStatusIndex = -1;
	            break;
	
	        case 'Z':
	            strbufEditWord = new StringBuffer( 0);
	            bShowNegative = false;
	            break;
	
	        default:
	            // Unsupported edit code equivalent to no editing
	            //-----------------------------------------------
	            strbufEditWord = new StringBuffer( 0);
	            break;
	    }
	    strEditWord = strbufEditWord.toString();
	
	    i_FieldPrecision   = iFieldPrecision;
	    iFloatingCurrency  = strEditWord.indexOf( '$' );
	
	    var iAsterisk = strEditWord.indexOf( '*' );
	    var iZero     = strEditWord.indexOf( '0' );
	
	    if( iAsterisk != -1 && iZero != -1 )
	    {
	        iEndZeroSuppressionIndex = iZero < iAsterisk ? iZero : iAsterisk;
	    }
	    else if( iAsterisk == -1 && iZero != -1 )
	    {
	        iEndZeroSuppressionIndex = iZero;
	    }
	    else if( iAsterisk != -1 && iZero == -1 )
	    {
	        iEndZeroSuppressionIndex = iAsterisk;
	    }
	
		return;
	}

/*-----------------------------------------------------------------------------	
 * Function: editwordSetup
 *-----------------------------------------------------------------------------*/
	function editwordSetup(eWord){
	    var iLength;
	    var	cDecimalPoint		 = "."
	    bBlankIfZero             = false;
	    bFloatingMinus           = false;
	    bAsteriskProtected       = false;
	    bDateSeparator           = false;
	    bShowNegative            = true;
	    iEndZeroSuppressionIndex = -1;
	    iExpansionIndex          = -1;
	    iFloatingCurrency        = -1;
	    iFormattedLength         = -1;
	    iStatusIndex             = -1;
	    i_FieldLength            = 0;
	    i_FieldPrecision         = 0;
	    if (eWord == null)  eWord = "";
		if (eWord == "")
	    {
	        strEditWord = "";
	        return strEditWord; 
	    }
	    strEditWord = eWord;
	    iLength = eWord.length; // used to be length();
	
	    // Strip the surrounding quotes first
	    //-----------------------------------
	    if( eWord.charAt( 0           ) == '\'' &&
	        eWord.charAt( iLength - 1 ) == '\''    )
	    {
	        //  'abc'   iLength = 5;
	        //  01234   subString(1, 4)
	        //-------------------------
	        strEditWord = eWord.substring( 1, iLength - 1 );
	    }
	    else
	    {
	        strEditWord = new String( eWord );
	    }

		// Find the first floating currency position
		//------------------------------------------
		iFloatingCurrency = strEditWord.indexOf( getCurrencySymbolStr() ); 

		if( iFloatingCurrency != -1 ) 
		{
			strEditWord = strEditWord.substring( 0, iFloatingCurrency ) + "$" +
	 					strEditWord.substring( iFloatingCurrency + getCurrencySymbolStr().length ); 
		}
	    // Change all thousand separators to the standard symbol
	    //------------------------------------------------------
    	if (getEditCode()!='0') 
		{
	    	strEditWord = replace( strEditWord, getThousandSeparator(), ',' );
		}
		
	    // Find the end-zero-suppression index: first '0' or '*'
	    // Zeros are printed after this index
	    //------------------------------------------------------
	    var iAsterisk = strEditWord.indexOf( '*' );
	    var iZero     = strEditWord.indexOf( '0' );
	
	    if( iAsterisk != -1 && iZero != -1 )
	    {
	        iEndZeroSuppressionIndex = iZero < iAsterisk ? iZero : iAsterisk;
	    }
	    else if( iAsterisk == -1 && iZero != -1 )
	    {
	        iEndZeroSuppressionIndex = iZero;
	    }
	    else if( iAsterisk != -1 && iZero == -1 )
	    {
	        iEndZeroSuppressionIndex = iAsterisk;
	    }
	
	    // A currency symbol just before the end-zero-suppression indicates
	    // that the currency symbol floats
	    //-----------------------------------------------------------------
	    if( iFloatingCurrency > 0 &&
	        iFloatingCurrency != iEndZeroSuppressionIndex - 1 )
	    {
	        iFloatingCurrency = -1;
	    }
	
	    // Find end of body section or start of status/expansion
	    //------------------------------------------------------
	    var iIndex = strEditWord.lastIndexOf(' ');
	
	    // If the last blank is just before the end-zero-suppression
	    // character, then the status starts after the
	    // end-zero-suppression character
	    //----------------------------------------------------------
	    if( iIndex == iEndZeroSuppressionIndex - 1 )
	    {
	        iStatusIndex = iEndZeroSuppressionIndex + 1;
	    }
	
	    // Otherwise, if the currency symbol is not in the first
	    // position, and the last space is just before it, then the status
	    // starts after the end-zero-suppression character
	    // ---------------------------------------------------------------
	    else if( iFloatingCurrency > 0 && iIndex == iFloatingCurrency - 1 )
	    {
	        iStatusIndex = iEndZeroSuppressionIndex + 1;
	    }
	
	    // Otherwise, the status starts after the last blank
	    //--------------------------------------------------
	    else
	    {
	        iStatusIndex = iIndex + 1;
	    }
	
	    // Check for zero suppression index outside of body section
	    //---------------------------------------------------------
	    if( iEndZeroSuppressionIndex >= iStatusIndex )
	    {
	        iEndZeroSuppressionIndex = -1;
	    }
	
	    // Check for floating currency index outside of body section
	    //----------------------------------------------------------
	    if( iFloatingCurrency >= iStatusIndex )
	    {
	        iFloatingCurrency = -1;
	    }
	
	    // Check for no expansion or status sections
	    //------------------------------------------
	    if( iStatusIndex > strEditWord.length )  
	    {
	        iStatusIndex    = -1;
	        iExpansionIndex = -1;
	    }
	    else
	    {
	        // '-' or 'CR' are the only status symbols allowed
	        // The expansion area begins after the status, i.e. after the first '-' or 'CR'
	        // or the begins after the body, which is the farthest
	        // right character that can be replaced by a digit.
	        //------------------------------------------------------
	        var iMinusIndex = strEditWord.indexOf( '-',  iStatusIndex );
	        var iCRIndex    = strEditWord.indexOf( "CR", iStatusIndex );
	
	        if( iMinusIndex == -1 && iCRIndex == -1 )
	        {
	            // No status section
	            //------------------
	            iExpansionIndex = iStatusIndex;
	            iStatusIndex    = -1;
	        }
	        else if( iMinusIndex < iCRIndex )
	        {
	            // Minus index is before the CR Index, or minus index is -1
	            //---------------------------------------------------------
	            iExpansionIndex = iMinusIndex == -1 ? iCRIndex + 2 : iMinusIndex + 1;
	        }
	        else
	        {
	            // CR index is before or equal to the Minus Index, or minus index is -1
	            //---------------------------------------------------------------------
	            iExpansionIndex = iCRIndex == -1 ? iMinusIndex + 1 : iCRIndex + 2;
	        }
	
	        // Check for expansion index outside of entire length
	        //---------------------------------------------------
	        if( iExpansionIndex > strEditWord.length - 1 )
	        {
	            iExpansionIndex = -1;
	        }
	    }

	    // See if we are using asterisk
	    //-----------------------------
	    if( iEndZeroSuppressionIndex != -1 &&
	        strEditWord.charAt( iEndZeroSuppressionIndex ) == '*' )
	    {
	        bAsteriskProtected = true;
	    }
	
	    // Field length equals the number of digit positions
	    //--------------------------------------------------
	    for( iIndex=0; iIndex<strEditWord.length; iIndex++ )
	    {
	        if( strEditWord.charAt( iIndex ) == ' ' )
	        {
	            ++i_FieldLength;
	        }
	    }
	
	    // Determine the precision length
	    //-------------------------------
	    iIndex = strEditWord.lastIndexOf( cDecimalPoint );

	    if( iIndex > -1 )
	    {
	        // Replace with standard symbol
	        //-----------------------------
	        // edit code is specified
	        if (getEditWord()==(""))	
	        {
	        	strEditWord = replace( strEditWord, cDecimalPoint, '.' );

	        }
	        // If the end-zero-suppression index is after the decimal
	        // point, increase the number of digit positions for the
	        // decimal point character
	        //-------------------------------------------------------
	        if( iEndZeroSuppressionIndex > iIndex )
	        {
	            ++i_FieldPrecision;
	        }
	
	        // Add the number of blanks after the decimal point to the precision
	        //------------------------------------------------------------------
	        for( ; iIndex < strEditWord.length; ++iIndex )
	        {
	            if( strEditWord.charAt( iIndex ) == ' ' )
	            {
	                ++i_FieldPrecision;
	            }
	        }
	    }
		return strEditWord; 
	}

/*----------------------------------------------------------------------------			
 * Function: formatBody
 *----------------------------------------------------------------------------*/
	/**
	 * Process to generate a formatted string
	 */
	function formatBody(cLeftFiller, bIsNegative, cDecimalPoint, strInput)
	{	
	    var fa   = getDataAttributes();
	    var iDataLength    = fa.getDataLength();
	    var iDecimalPlaces = fa.getDecimalPlaces();

	    // Count the number of leading zeroes
	    //-----------------------------------
	    var iNumberOfLeadingZeros = 0;
	
	    if( ( iDataLength != iDecimalPlaces ) ||
	        ( 'Y' == editCode)     )
	    {
	        for( iNumberOfLeadingZeros=0; iNumberOfLeadingZeros < strInput.length && strInput.charAt( iNumberOfLeadingZeros ) == '0';
	           ++iNumberOfLeadingZeros )
	        {
	        }
	
	        if ( iDataLength == iNumberOfLeadingZeros  &&  iDecimalPlaces == 0 )
	            --iNumberOfLeadingZeros;
	    }
	
	    // Determine where the end of the body is
	    // If there is no expansion, then use the status
	    // If there is no status, then it's the entire string length
	    //----------------------------------------------------------
	    var iEnd = iStatusIndex != -1 ? iStatusIndex : iExpansionIndex;
	
	    iEnd = iEnd != -1 ? iEnd : strEditWord.length;
	
	    // Point to the last character position
	    //-------------------------------------
	    --iEnd;
	
	
	    // Determine the pivot point
	    //--------------------------
	    var iPivot;
	
	    if( ( iDataLength == iDecimalPlaces )   &&
	        ('Y' != editCode) )
	    {
	        iPivot = iEnd - iDecimalPlaces - 1;
	    }
	
	    else
	    {
	        iPivot = iEndZeroSuppressionIndex != -1 ? iEndZeroSuppressionIndex : iEnd;
	    }

	    // Determine the number index
	    //---------------------------
	    var cCharacter;
	    var  iEditWordIndex;
	    var  iNumPtr = strInput.length - 2;
	    var strbufBody = new StringBuffer(0); //51595
	
	    // Determine adjustment for Fixed or floating currency symbol
	    //  (to determine filler to compensate for currency symbol)	
	    var iIndex = -1;
	    for( iEditWordIndex=iEnd;
	         iEditWordIndex>=0 && iNumPtr>=iNumberOfLeadingZeros;
	         --iEditWordIndex )
	    {
	        cCharacter = strEditWord.charAt( iEditWordIndex );
	        if( iEditWordIndex > iPivot )
	        {
	            if( cCharacter == ' ' )
	            {
	                strbufBody.insert( 0, strInput.charAt( iNumPtr-- ) );
	            }
	            else
	            {
	                insertCharacter( cCharacter, strbufBody );
	            }
	        }
	        else
	        {
	            // Don't take into account currency string lengths
	            // since they are all one unicode character wide
	            //------------------------------------------------
	
	            if( iEditWordIndex == iFloatingCurrency && iFloatingCurrency > -1 )
	            {
					continue;
	       		}
				else if( (  editCode=='1' || editCode=='3' || 	
							editCode=='A' || editCode=='C' || 
							editCode=='J' || editCode=='L' || 
							editCode=='M' || editCode=='N' || 
							editCode=='P' ) && 		
		  					(cCharacter == ' ' || cCharacter == '0' ))  
            	{
                	strbufBody.insert( 0, strInput.charAt( iNumPtr-- ) );
            	}	       		
	            else if( cCharacter == '0' )
	            {
	                strbufBody.insert( 0, strInput.charAt( iNumPtr-- ) );
	            }
	            else if( cCharacter == ' ')
	            {
	                if ( '0' == strInput.charAt( iNumPtr)  &&
	                     iDataLength == (iNumberOfLeadingZeros +1)   )
	                {
	                    strbufBody.insert( 0, ' ');
	                    iNumPtr--;
	                }
	                else
	                {
	                    strbufBody.insert( 0, strInput.charAt( iNumPtr-- ) );
	                }
	            }
	
	            else if( cCharacter == '*' )
	            {
	                // (eg. output '****' instead of '***0')
	
	                // For '*', if number is 0, and there are no significant digits
	                // to the left (eg. there only zeros to left), then
	                // output the '*', not the '0'.
	                // (The asterisk ends zero-suppression)
	
	
	                if ( '0' == strInput.charAt( iNumPtr)  &&
	                     iDataLength == (iNumberOfLeadingZeros +1)   )
	                {
	                    strbufBody.insert( 0, '*');
	                    iNumPtr--;
	                }
	                else
	                {
	                    strbufBody.insert( 0, strInput.charAt( iNumPtr-- ) );
	                }
	            }
	            else
	            {
	                insertCharacter( cCharacter, strbufBody );
	            }
	        }
	    }
	    
		if( iDecimalPlaces > 0 || editCode=='0' || editCode=='Y' || editCode=='W') 
		{	    
		    for( ; iEditWordIndex>iPivot; iEditWordIndex-- )
		    {
	    	    cCharacter = strEditWord.charAt( iEditWordIndex );
		        if( cCharacter == ' ' )
		        {
	    	        strbufBody.insert( 0, '0' );
	        	}
		        else
		        {
	    	        insertCharacter( cCharacter, strbufBody );
	        	}
	    	}
		}
		
	    // if body not empty, and
	    // have a floating currency symbol (not at leftmost position)
	    // or it is at the leftmost position but there is one or no whole digits,
	    // or it is at the leftmost position and followed by the zero (for Zero suppression)
	    //    and it's an edit code.  (maybe this only happens for 2 whole digits only)
	    //    (Currency is always  floating for edit code, never fixed.)
	    if ( strbufBody.length() > 0  &&
	         ( iFloatingCurrency > 0   ||
	           ( iFloatingCurrency == 0 && (iDataLength - iDecimalPlaces <= 1 ) ) ||
	           ( iFloatingCurrency == 0 && strEditWord.indexOf( '0' ) == 1 && editCode!='0' )
	       ) )
	    {
	        strbufBody.insert( 0, getCurrencySymbolStr() );
	    }
	    if( bFloatingMinus == true )
	    {
	        if( bIsNegative == true && strbufBody.length() > 0 )
	        {
	            strbufBody.insert( 0, fa.MINUS_SIGN );
	        }
	        else
	        {
	            strbufBody.insert( 0, cLeftFiller );
	        }
	    }

	    // Less filler to compensate for currency symbol
	    //----------------------------------------------
	    if( iFloatingCurrency > -1  && iFloatingCurrency <= iEditWordIndex )
	    {
	        --iEditWordIndex;
	    }
	    else if( iFloatingCurrency == 0 )
	    {
	        iIndex = 0;
	    }

		// an editword could be composed of "body" + "expansion",
		// strbufBody.length may not be length of the final formatted string, 
		// for the expansion part may be missing at this moment. 
		var expansionLength = 0;
		if (iExpansionIndex >= 0)
		{
			expansionLength = strEditWord.length-iExpansionIndex;		
		}
		if ( (strEditWord.charAt(0) == '0' && (strbufBody.length()+ expansionLength) < strEditWord.length-1) ||  
			 (strEditWord.charAt(0) == '0' && i_FieldLength < iDataLength ) ||					
			  strEditWord.charAt(0) != '0')														
		{
			for( ; iEditWordIndex>iIndex; --iEditWordIndex )
			{
	        	strbufBody.insert( 0, cLeftFiller );
	    	}
		}


	    // Fixed Currency Symbol:
	
	    // (Currency symbol is at leftmost position (0), but more than 1
	    //  whole digit.  (Case of 1 whole digit handled above by the
	    //  floating case code.)
	    // But, if it's leftmost position and it's for an edit code, and the
	    // zero-suppression (0) is next to it, then it also has been handled
	    // above by the floating code
	
	    // thus, condition is:
	    // If the currency symbol is in the fixed position, and
	    // there is more than 1 whole digit, and
	    // (it's not for an edit code, or the zero-suprress is NOT next to it)
	
	    if( iFloatingCurrency == 0 && iDataLength - iDecimalPlaces > 1
	        && ( editCode=='0'  ||
	             strEditWord.indexOf( '0' ) != 1 )
	      )
	    {
	        strbufBody.insert( 0, getCurrencySymbolStr() );
	    }
	    return strbufBody.toString();
	}

/*----------------------------------------------------------------------------		
 * formatExpansion function
 *----------------------------------------------------------------------------*/
	/**
	 * Process to generate a formatted string
	 */
	function formatExpansion()
	{
	    var strbufExpansion = new StringBuffer(0); //51595
	
	    if( iExpansionIndex != -1 )
	    {
	        // Replace all ampersands with spaces
	        //-----------------------------------
	        var cCharacter;
	
	        var  iEnd = strEditWord.length - 1;
	
	        for( var i=iExpansionIndex; i<=iEnd; ++i )
	        {
	            cCharacter = strEditWord.charAt( i );
	            strbufExpansion.append( cCharacter == '&' ? ' ' : cCharacter );
	        }
	    }
	
	    return strbufExpansion.toString();
	}	

/*----------------------------------------------------------------------------
 * formatNumeric function
 *----------------------------------------------------------------------------*/
	/**
	 * This takes a numeric string, strips out the decimal point, and moves
	 * a sign to the end of the string.  The final length is the field length
	 * plus one for the sign
	 *
	 */
	function formatNumeric( strInput, cDecimalPoint )
	{
	    var fa  = getDataAttributes();
	    var         cSign;
	    var          iDecimalPlaces = 0;    // decimal places in input string
	    var          iDecimalPosition;      // decimal point position in input string
	    var strbufOutput = null;		// StringBuffer type
	
	    // Find out what the sign character is
	    //------------------------------------
	    var iSignPosition = strInput.indexOf( fa.MINUS_SIGN );
	
	    if( iSignPosition != -1 )
	    {
	        cSign = fa.MINUS_SIGN;
	    }
	    else
	    {
	        iSignPosition = strInput.indexOf( fa.PLUS_SIGN );
	        cSign = fa.PLUS_SIGN;
	    }
	
	    // Remove the sign character from the string
	    // Create a string buffer
	    //------------------------------------------
	    if( iSignPosition != -1 )
	    {
	
	        strbufOutput = new StringBuffer (strInput.length);
	        // Get characters before the sign position if sign is at the end
	        if( iSignPosition != 0 )
	        {
	            strbufOutput.append( strInput.substring( 0, iSignPosition ) );
	        }
	
	        // Get characters after the sign position if sign is in the front
	        else //if( iSignPosition != strbufOutput.length() - 1 )
	        {
	            strbufOutput.append( strInput.substring( 1, strInput.length ) );
	        }
	    }
	    else
	    {
	        strbufOutput = new StringBuffer(strInput.length); //51595
	        strbufOutput.append(strInput);
	    }
	
	    // Remove any decimal character
	    // Since this is unicode, a decimal string will be only one character
	    //-------------------------------------------------------------------
	    iDecimalPosition = strbufOutput.toString().indexOf( cDecimalPoint );
	
	    if( iDecimalPosition != -1 )
	    {
	        // Remember the number of decimal places
	        //--------------------------------------
	        iDecimalPlaces = strbufOutput.length() - iDecimalPosition - 1;
	
	        // Generate a string so we can get substrings
	        //-------------------------------------------
	        var strOutput = strbufOutput.toString();
	
	        // Empty the output buffer
	        //------------------------
	        strbufOutput.setLength( 0 );
	
	        // Get characters before the decimal position
	        //-------------------------------------------
	        if( iDecimalPosition != 0 )
	        {
	            strbufOutput.append( strOutput.substring( 0, iDecimalPosition ) );
	        }
	        // Get characters after the decimal position
	        //------------------------------------------
	        if( iDecimalPosition != strOutput.length - 1 )
	        {
	            strbufOutput.append( strOutput.substring( iDecimalPosition+1, strOutput.length ) );
	        }
	    }
	    // Append zeros to the string until the number of
	    // decimal places is equal to the field precision
	    //-----------------------------------------------
	
	    var iNumberOfZeros;
	
	    // RpgLanguageMode: does not adjust value (by right
	    // or left shifting) to fit decimal place
	    // determined in the edit word.
	
	    // Gui Mode does.
	    iNumberOfZeros = fa.getDecimalPlaces() - iDecimalPlaces;
	    while( iNumberOfZeros-- > 0 )
	    {
	        strbufOutput.append( '0' );
	    }
	
	    // Prepend zeros to the string until the length
	    // of the string is equal to the field length
	    //---------------------------------------------
	    if (getEditCode() != '0'){
	        iNumberOfZeros = fa.getDataLength() - strbufOutput.length();
	    } else {
	        iNumberOfZeros = i_FieldLength - strbufOutput.length();
	    }
		
	    while( iNumberOfZeros-- > 0 )
	    {
	        strbufOutput.insert( 0, '0');
	    }

	    // Add the sign character back in
	    //-------------------------------
        // only if the value is negative, add the -ve sign
	    if (cSign == fa.MINUS_SIGN && 										
    		(parseFloat(strbufOutput.toString()) != 0.0) )
	    {	
		    strbufOutput.append( cSign );									
	    }																	
    	else if (cSign == fa.PLUS_SIGN)										
	    {																	
		    strbufOutput.append( cSign );									
    	}																	

	    return strbufOutput;
	}

	
/*----------------------------------------------------------------------------
 * formatStatus function
 *----------------------------------------------------------------------------*/
	/**
	 * Process to generate a formatted string
	 */
	function formatStatus( bNegative )
	{
		var strbufStatus = new StringBuffer(0); //51595
		
	    if( iStatusIndex != -1 )
	    {
	        // The end of the status section is the start of the
	        // expansion section, or if there isn't an expansion
	        // section, the end of the string
	        //--------------------------------------------------
	        var iEnd = iExpansionIndex == -1 ? strEditWord.length - 1: iExpansionIndex - 1;
	        var cCharacter;
	
	        // If the number is negative, replace all
	        // instances of ampersands with spaces
	        //---------------------------------------
	        if( bNegative == true )
	        {
	            for( var i=iStatusIndex; i<=iEnd; ++i )
	            {
	                cCharacter = strEditWord.charAt( i );
	                strbufStatus.append( cCharacter == '&' ? ' ' : cCharacter );
	            }
	        }
	
	        // Non-negative, fill all with spaces
	        //-----------------------------------
	        else
	        {
	            for( var i=iStatusIndex; i<=iEnd; ++i )
	            {
	                strbufStatus.append( ' ' );
	            }
	        }
	    }
	    return strbufStatus.toString();
	}

/*----------------------------------------------------------------------------
 * formatString function
 *----------------------------------------------------------------------------*/
	/**
	 * Return the formatted string given an unformatted string.
	 * The system's decimal point symbol is used to find the decimal point.  A number
	 * typed in by an end user can be formatted based on the end user's system's
	 * decimal point symbol.  Only a sign character, a decimal symbol character, and
	 * numerals are allowed in the input string.
	 * @param strInput String
	 * @return formatted string
	 */
	this.formatString=function formatString(strInput) // should be public :. leave function heading as is.
	{
	    var da  = getDataAttributes();
	    var iDecimalPlaces = da.getDecimalPlaces();
	    var iLength = da.getDataLength();
	
	    // if user has not entered anything or editcode is '0' and editword is "",
	    // then no need to format
	    if (strInput==null     ||
	        (strInput == "")   ||
	        (getEditCode()=='0'&& (getEditWord() == "")) )
	    {
	
	        return strInput;
	    }
	
	    if (getEditCode() == '0')
	    {
	        strEditWord = editwordSetup(getEditWord()); 
	    }
	    else
	    {
	        convertEditCodeToEditWord(da.getDataLength(), da.getDecimalPlaces(), getEditCode(), getEditCodeParmType());
	    }
	    
	    try
	    {
	        var iFieldPrecision = da.getDecimalPlaces();
	
	        // Obtain the system's decimal point character
	        //--------------------------------------------
	        var cDecimalPoint = da.getDecimalSymbol();
	
	        // Obtain the formatted numeric
	        //-----------------------------
	        var strbufValue = formatNumeric( strInput, cDecimalPoint );
	
	        // No output editing is required, so return the string in numeric form
	        //--------------------------------------------------------------------
	        if( strEditWord.length == 0 )
	        {
	            // Insert the decimal point
	            // Show negative is false only for Z edit code
	            // For Z edit code, do not display the decimal
	            //--------------------------------------------
	            if( iFieldPrecision > 0 && bShowNegative == true )
	            {
	                // There is always a sign character at the end of the string
	                // 123400+ becomes 1234.00+   length=7 fieldprecision = 2
	                //----------------------------------------------------------
	                strbufValue.insert( strbufValue.length() - iFieldPrecision - 1, cDecimalPoint );
				}
	
	            // Remove any trailing '+' signs
	            //------------------------------
	            if( strbufValue.charAt( strbufValue.length() - 1 ) == '+' )
	            {
	                strbufValue.setLength( strbufValue.length() - 1 );
	            }
	
	            // Remove any trailing '-' signs only if required
	            //-----------------------------------------------
	            else if( bShowNegative == false && strbufValue.charAt( strbufValue.length() - 1 ) == '-' )
	            {
	                strbufValue.setLength( strbufValue.length() - 1 );
	            }

				// Suppress leading decimal point for Z edit code if length == decimal places
				var strbufValueLen = strbufValue.length();	//51595
				if (editCode=='Z' && iLength==iDecimalPlaces && strbufValueLen>iLength) //51595
				{
					var s = strbufValue.getString().substring(strbufValueLen-iLength); //51595
					strbufValue = new StringBuffer(s.length);	//51595
					strbufValue.append(s);						//51595
				}
		
	            // Suppress leading zeros for Z edit code
	            //---------------------------------------
	            if( bShowNegative == false )
	            {
	            	
	                // replace leading zeros with blanks
	                //----------------------------------
	                for( var i=0; i<strbufValue.length(); ++i )
	                {
	                    if( strbufValue.charAt( i ) != '0' )
	                        break;
	                    else
	                        strbufValue.setCharAt( i, ' ' );
	                }
	            }
	
	            return strbufValue.toString();
	        }
	
		
	        // See if there this is a negative number
	        // by checking for a '-' at the end of the string
	        //-----------------------------------------------
	        var bIsNegative = strbufValue.charAt( strbufValue.length() - 1 ) == '-' ? true : false;

	        // Determine what the fill character is
	        //-------------------------------------
	        var cLeftFiller = bAsteriskProtected == true ? '*' : ' ';
	
	        // Generate a formatted string
	        //----------------------------
	        var strBody      = formatBody( cLeftFiller, bIsNegative, cDecimalPoint, strbufValue.toString() );
	        var strStatus    = formatStatus( bIsNegative );
	        var strExpansion = formatExpansion();
			var s = strBody + strStatus + strExpansion;
	        var strbufOutput = new StringBuffer( 0 ); 
	        strbufOutput.append(s);
	        
	        // Do the following if we are to blank out the zeros with the fill character
	        //--------------------------------------------------------------------------
	        if( bBlankIfZero == true )
	        {
	            // Find the number of '0's in the string
	            //--------------------------------------
	            var iIndex = -1;
	            var iCount = -1;
	
	            var strValue = strbufValue.toString();
	
	            do
	            {
	                ++iCount;
	                iIndex = strValue.indexOf( '0', iIndex + 1 );
	
	            } while( iIndex != -1 );
	
	            // If the entire field has zeros, blank it all out
	            //------------------------------------------------
	            if( iCount == strbufValue.length() - 1 )
	            {
					if ((editCode=='B' || editCode=='D' || editCode=='K' || editCode=='M') &&	
						editCodeParmType == EDITCODEPARM_ASTERISK )
					{
						for( var i=0; i<strbufOutput.length(); ++i ) 
						{
							strbufOutput.setCharAt( i, cLeftFiller );
						}
					}          
    	        	else
        	    	{
            	    	for( var i=0; i<strBody.length; ++i ) 
                		{
                    		strbufOutput.setCharAt( i, cLeftFiller );
                		}
	            	}
    	        }
	        }
	
	        var strOut = strbufOutput.toString();

	        // Replace all ampersands with spaces
	        //-----------------------------------
	        strOut = replace(strOut, '&' , ' ');


		// Convert data for qdecfmtJValue
		if (qdecfmtJValue && editCode!='0' && iDecimalPlaces>0)
		{
			strOut = convertToQdecfmtJValue(strOut, iDecimalPlaces, iLength, cDecimalPoint);
		}
		
		// if there is a currency symbol in the editWord,
		// and the currency symbol is not the default '$',
		// and strOut has '$' instead of the currency symbol,
		// then replace '$' with the currency symbol. This
		// situation only occurs when the currency symbol is
		// at an invalid position, e.g. 20#02050,500
		if (editCode == '0' && 
			(currencySymbolStr != "$") &&
			editWord.length > 0 && 
			editWord.indexOf(getCurrencySymbolStr())>=0 &&
			strOut.length > 0 &&
			strOut.indexOf(getCurrencySymbolStr()) < 0 &&
			strOut.indexOf('$') >= 0)
		{		
			// replace '$' with currencySymbolStr, we
			// cannot use String.replaceAll() for "$" has
			// special meaning, means end of line boundary 
			var idx = strOut.lastIndexOf('$');
			var idx2;
			while (idx >=0 )
			{	
				if (idx == 0 && strOut.length == 1)
					strOut = getCurrencySymbolStr();
				else if (idx == 0 && strOut.length > 1)
					strOut = getCurrencySymbolStr() + strOut.substring(1);
				else if (idx == strOut.length-1)
					strOut = strOut.substring(0, idx) + getCurrencySymbolStr();
				else
					strOut = strOut.substring(0, idx) + getCurrencySymbolStr() + strOut.substring(idx+1);
				idx = strOut.lastIndexOf('$');
				
				// check if this last '$' is the unconverted currency symbol or
				// it is part of the currency symbol. It is possible that the
				// currency symbol str is "RMB $".
				idx2 = getCurrencySymbolStr().indexOf('$');
				if (idx2 < 0)
					idx2 = 0;
				if (strOut.lastIndexOf(getCurrencySymbolStr())+idx2 == idx)
					break;
					
			}
		}

	        return strOut;
	    }
	    catch (e)
	    {
	    	msg = msg[13] + setMessageParameters(msg[14], (e.number & 0xffff), e.description);
	        return strInput;
	    }
	}	
	
	/* INTERNAL FUNCTIONS START HERE ----------------------------------------------*/
	
	/**
	 * Sets the dataAttributes property (com.ibm.etools.iseries.ui.Attributes) value.
	 * @param dataAttributes The new value for the property.
	 * @see #getDataAttributes
	 */
	this.setDataAttributes=function(a)
	{
	    dataAttributes = a;
	}

	function setDataAttributes(a)
	{
	    dataAttributes = a;
	}
	
// When qdecfmt is 'J', and when data is less than zero, 
// such as .23, then the formatted string should be 0.23.
// If value is .0, then the formatted string should be 0.0.
function convertToQdecfmtJValue(strOut, iDecimalPlaces, iLength, cDecimalPoint)
{
	if (iLength == iDecimalPlaces && (editCode=='N' || editCode!='O' || editCode!='P' || editCode!='Q'))
		return strOut;
		
	var decimalLoc = strOut.indexOf(cDecimalPoint);
	if (decimalLoc >= 1)
	{
		// change " .x" to "0.x"
		if (strOut.charAt(decimalLoc-1) == ' ')
		{
			if (decimalLoc >= 2)
				// change "  .x" to " 0.x"
				strOut = strOut.substring(0,decimalLoc-1) + "0" + strOut.substring(decimalLoc);
			else 
				// change " .x" to "0.x"
				strOut = "0" + strOut.substring(decimalLoc);
		}		
		// change " $.x" to "$0.x" 
/*		else if (getCurrencySymbolStr() == strOut.charAt(decimalLoc-1))
		{
			// change " -$.x" to "-$0.x"
			if (strOut.charAt(decimalLoc-2) == '-')
			{
				if (decimalLoc >= 4)
					// change "  -$.x" to " -$0.x"
					strOut = strOut.substring(0,decimalLoc-3) + "-" + getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
				else
					strOut = "-" + getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
			}
			else if (strOut.charAt(decimalLoc-2) == ' ')
			{
				if (decimalLoc >= 3)
					// change "  $.x" to " $0.x"
					strOut = strOut.substring(0,decimalLoc-2) + getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
				else
					strOut = getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
			}
		}
*/		
				// change " $.x" to "$0.x" 	
		else if (getCurrencySymbolStr() == strOut.substring(decimalLoc-getCurrencySymbolStr().length, decimalLoc))
		{
			// change " -$.x" to "-$0.x"
			if (strOut.charAt(decimalLoc-getCurrencySymbolStr().length-1) == '-')
			{
				if (decimalLoc >= getCurrencySymbolStr().length+3)
					// change "  -$.x" to " -$0.x"
					strOut = strOut.substring(0,decimalLoc-getCurrencySymbolStr().length-2) + "-" + getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
				else
					strOut = "-" + getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
			}
			else if (strOut.charAt(decimalLoc-getCurrencySymbolStr().length-1) == ' ')
			{
				if (decimalLoc >= getCurrencySymbolStr().length+2)
					// change "  $.x" to " $0.x"
					strOut = strOut.substring(0,decimalLoc-getCurrencySymbolStr().length-1) + getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
				else
					strOut = getCurrencySymbolStr() + "0" + strOut.substring(decimalLoc);
			}
		}
		
		// change "*.x" to "0.x"
		else if (strOut.charAt(decimalLoc-1) == '*')
		{
			// change "**.x" to "*0.x"
			if (decimalLoc >= 2)
				strOut = strOut.substring(0,decimalLoc-1) + "0" + strOut.substring(decimalLoc);
			else // change "*.x" to "0.x"
				strOut = "0" + strOut.substring(decimalLoc);
		}
		// change "-.x" to "-0.x" 
		else if (strOut.charAt(decimalLoc-1) == '-')
		{
			//change "*-.x" to "-0.x"
			if (decimalLoc >=2 && strOut.charAt(decimalLoc-2) == '*')
			{
				//change "**-.x" to "*-0.x"
				if (decimalLoc >= 3)
					strOut = strOut.substring(0,decimalLoc-2) + "-0" + strOut.substring(decimalLoc);
				else //change "*-.x" to "-0.x"
					strOut = "-0" + strOut.substring(decimalLoc);
			}
			else if (decimalLoc >=2 && strOut.charAt(decimalLoc-2) == ' ')
			{
				// change "  -.x" to " -0.x" 
				if (decimalLoc >= 3)
					strOut = strOut.substring(0,decimalLoc-2) + "-0" + strOut.substring(decimalLoc);
				else // change " -.x" to "-0.x"
					strOut = "-0" + strOut.substring(decimalLoc);
			}
		}

	}

	return strOut;
}



	/**
	 * Called by formatBody.
	 */
	function insertCharacter(cCharacter, strbufBody)
	{
	    var cInsert = ""+cCharacter;
	
		// if editword is specified, do not replace these special characters,
		// use the one in the editword.
		if (getEditWord() == "")  
		{
			switch( cCharacter )
	 		{
	  			case '&': cInsert = " ";                                    	break; 
	   			case '$': cInsert = getCurrencySymbolStr();                  	break; 
	    		case '/': cInsert = ""+getDateSeparator();                   	break; 
	    		case '.': cInsert = ""+getDataAttributes().getDecimalSymbol();	break; 
	    		case '-': cInsert = ""+getDataAttributes().MINUS_SIGN;    		break;
	    		case ',': cInsert = ""+getThousandSeparator();                	break; 
	    		default:  cInsert = ""+cCharacter;                              break; 
	 		}
	    }
	    strbufBody.insert( 0, cInsert );
	
	    return;
	}
	
	function setCurrencySymbolStr(symbol)
	{
	    currencySymbolStr = symbol;
	}
	
	this.setCurrencySymbolStr=function(symbol)
	{
	    currencySymbolStr = symbol;
	}	
	
	function getThousandSeparator()
	{
		return thousandSeparator;
	}
	
	this.getThousandSeparator=function()
	{
		return thousandSeparator;
	}	

	
	/**
	 * Sets the thousandSeparator property (char) value.
	 */
	function setThousandSeparator(thouSeparator)
	{
	    thousandSeparator = thouSeparator;
	}

	this.setThousandSeparator=function(thouSeparator)
	{
	    thousandSeparator = thouSeparator;
	}
		
	function getCurrencySymbolStr()	
	{
		return currencySymbolStr;
	}
	
	this.getCurrencySymbolStr=function() 
	{
		return currencySymbolStr;
	}
	
	function getEditWord()
	{
 	 	if (editWord == null) {
 	 		editWord = "";
    		}
  		return editWord;
	}
	
	this.getEditWord=function()
	{
 	 	if (editWord == null)
 	 		editWord = "";

  		return editWord;
	}	
	
	
	/**
	 * Gets the dataAttributes property (com.ibm.etools.iseries.ui.Attributes) value.
	 */
	function getDataAttributes()
	{
	    if (dataAttributes == null)
	    {
	        dataAttributes = new DataAttributes();
	    }
	
	    return dataAttributes;
	}

	this.getDataAttributes=function()
	{
	    if (dataAttributes == null)
	    {
	        dataAttributes = new DataAttributes();
	    }
	
	    return dataAttributes;
	}	
	
	/**
	 * Sets the editCode property (char) value.
	 */
	this.setEditCode=function(code)
	{
    		editCode = code.charAt(0);
	}
	
	function setEditCode(code)
	{
    		editCode = code.charAt(0);
	}
		
	/**
	 * Sets the editCodeParmType property (int) value.
	 */
	this.setEditCodeParmType=function(editCodeParameterType)
	{
		if ((/^\d$/).test(editCodeParameterType)){
			editCodeParmType = parseInt(editCodeParameterType);
		}
	}
	
	function setEditCodeParmType(editCodeParameterType)
	{
		if ((/^\d$/).test(editCodeParameterType)){
			editCodeParmType = parseInt(editCodeParameterType);
		}
	}

	/**
	 * Sets the editWord property (java.lang.String) value.
	 */
	this.setEditWord=function(eWord)
	{
	    if (eWord == null)
	        editWord = "";
	    else
	        editWord = eWord;
	}

	function setEditWord(eWord)
	{
	    if (eWord == null)
	        editWord = "";
	    else
	        editWord = eWord;
	}	
	/**
	 * Sets the dateSeparator property (char) value.
	 */
	this.setDateSeparator=function(dateSep)
	{
	    dateSeparator=dateSep;
	}	

	function setDateSeparator(dateSep)
	{
	    dateSeparator=dateSep;
	}	
	
	/**
	 * Gets the dateSeparator property (char) value.
	 */
	function getDateSeparator()
	{
	    return dateSeparator;
	}

	this.getDateSeparator=function()
	{
	    return dateSeparator;
	}	
	
	/**
	 * Gets the editCode property (char) value.
	 */
	function getEditCode()
	{
	    return editCode;
	}
	
	this.getEditCode=function()
	{
	    return editCode;
	}	
	
	/**
	 * Gets the editCodeParmType property (int) value.
	 */
	function getEditCodeParmType()
	{
	    return editCodeParmType;
	}
	
	this.getEditCodeParmType=function()
	{
	    return editCodeParmType;
	}	

	/**
	 * Gets the qdecfmtJValue property (boolean) value.
	 * When qdecfmtJValue is true, the zero suppression will work as if the
	 * JValue of QDECFMT system value is set.
	 */
	this.getQdecfmtJValue=function()
	{
	    return qdecfmtJValue;
	}

	function getQdecfmtJValue()
	{
	    return qdecfmtJValue;
	}	
	
	/**
	 * Sets the qdecfmtJValue property (char) value.
	 * @param value True for J value of QDECFMT system value is set,
	 * false for J value of QDECFMT system value is not set,
	 * @see #getQdecfmtJValue
	 */
	this.setQdecfmtJValue=function(value)
	{
	    qdecfmtJValue = value;
	}	

	function setQdecfmtJValue(value)
	{
	    qdecfmtJValue = value;
	}	
	/* INTERNAL FUNCTIONS END HERE ------------------------------------------------*/
}
	
/**
 * DataAttributes implements Attributes. It is a container for
 * the attributes of a field, such as JFormattedTextField,
 * JFormattedLabel and JFormattedComboBox.
 * It holds information on autoAdvance, data type, length of data,
 * size of decimal places, symbol for decimal point
 */
function DataAttributes()
{
	/**
	 * Data type is Character
	 */
	this.DATATYPE_CHARACTER    = 0;
	/**
	 * Data type is Numeric
	 */
	this.DATATYPE_NUMERIC      = 1;
	/**
	 * Minus Sign for negative number
	 */
	this.MINUS_SIGN			= '-';
	/**
	 * Plus Sign for positive number
	 */
	this.PLUS_SIGN	   		= '+';

	var  dataLength 		= 10;
	var  decimalPlaces  	= 0;
	var  dataType 		= this.DATATYPE_CHARACTER;
	var decimalSymbol 	= '.';
	
	var autoAdvance = false;
	var errorBeep	= true;
			
	
	/**
	 * Gets the autoAdvance property (boolean) value. The default value false.
	 * If autoAdvance is true, when the data length reaches the field length,
	 * the control is automatically set to the next component.
	 */
	this.getAutoAdvance=function()
	{
		return autoAdvance;
	}
	/**
	 * Gets the dataLength property (int) value. The default value is 10.
	 */
	this.getDataLength=function()
	{
		return dataLength;
	}
	/**
	 * Gets the dataType property (int) value. The default value is character.
	 */
	this.getDataType=function()
	{
		return dataType;
	}
	/**
	 * Gets the decimalPlaces property (int) value. The default value is 0.
	 */
	this.getDecimalPlaces=function()
	{
		return decimalPlaces;
	}
	/**
	 * Gets the decimalSymbol property (char) value. The default value is '.'
	 */
	this.getDecimalSymbol=function()
	{
		return decimalSymbol;
	}
	/**
	 * Gets the errorBeep property (boolean) value. The default value false.
	 * If errorBeep is true, the field will beep when the data is invalid.
	 */
	this.getErrorBeep=function()
	{
		return errorBeep;
	}
	
	
	/**
	 * Sets the autoAdvance property (boolean) value.
	 */
	this.setAutoAdvance=function(value) // boolean type
	{
		autoAdvance = value;
	
	}
	/**
	 * Sets the dataLength property (int) value.
	 */
	this.setDataLength=function(len)  //int type
	{
		dataLength=len;
	}
	/**
	 * Sets the dataType property (int) value.
	 */
	this.setDataType=function(type) //int type
	{
		dataType = type;
	}
	/**
	 * Sets the decimalPlaces property (int) value.
	 */
	this.setDecimalPlaces=function(decPlaces) //int type
	{
		decimalPlaces = decPlaces;
	}
	/**
	 * Sets the decimalSymbol property (char) value.
	 */
	this.setDecimalSymbol=function(dec)  // char type
	{
		decimalSymbol=dec;
	}
	/**
	 * Sets the errorBeep property (boolean) value.
	 */
	this.setErrorBeep=function(value) //boolean type
	{
		errorBeep = value;
	}
}



function DataAttributes(dataType, dataLength)
{
	/**
	 * Data type is Character
	 */
	this.DATATYPE_CHARACTER    = 0;
	/**
	 * Data type is Numeric
	 */
	this.DATATYPE_NUMERIC      = 1;
	/**
	 * Minus Sign for negative number
	 */
	this.MINUS_SIGN			  = '-';
	/**
	 * Plus Sign for positive number
	 */
	this.PLUS_SIGN	   		  = '+';

	var dataLength = dataLength;
	var decimalPlaces = 0;
	var dataType = dataType;
	var decimalSymbol = '.';
	
	var autoAdvance = false;
	var errorBeep	= true;
			
	
	/**
	 * Gets the autoAdvance property (boolean) value. The default value false.
	 * If autoAdvance is true, when the data length reaches the field length,
	 * the control is automatically set to the next component.
	 */
	this.getAutoAdvance=function()
	{
		return autoAdvance;
	}
	/**
	 * Gets the dataLength property (int) value. The default value is 10.
	 */
	this.getDataLength=function()
	{
		return dataLength;
	}
	/**
	 * Gets the dataType property (int) value. The default value is character.
	 */
	this.getDataType=function()
	{
		return dataType;
	}
	/**
	 * Gets the decimalPlaces property (int) value. The default value is 0.
	 */
	this.getDecimalPlaces=function()
	{
		return decimalPlaces;
	}
	/**
	 * Gets the decimalSymbol property (char) value. The default value is '.'
	 */
	this.getDecimalSymbol=function()
	{
		return decimalSymbol;
	}
	/**
	 * Gets the errorBeep property (boolean) value. The default value false.
	 * If errorBeep is true, the field will beep when the data is invalid.
	 */
	this.getErrorBeep=function()
	{
		return errorBeep;
	}
	
	
	/**
	 * Sets the autoAdvance property (boolean) value.
	 */
	this.setAutoAdvance=function(value) // boolean type
	{
		autoAdvance = value;
	}
	/**
	 * Sets the dataLength property (int) value.
	 */
	this.setDataLength=function(len)  //int type
	{
		dataLength=len;
	}
	/**
	 * Sets the dataType property (int) value.
	 */
	this.setDataType=function(type) //int type
	{
		dataType = type;
	}
	/**
	 * Sets the decimalPlaces property (int) value.
	 */
	this.setDecimalPlaces=function(decPlaces) //int type
	{
		decimalPlaces = decPlaces;
	}
	/**
	 * Sets the decimalSymbol property (char) value.
	 */
	this.setDecimalSymbol=function(dec)  // char type
	{
		decimalSymbol=dec;
	}
	/**
	 * Sets the errorBeep property (boolean) value.
	 */
	this.setErrorBeep=function(value) //boolean type
	{
		errorBeep = value;
	}
}


function errorHandler(e, URL, line){
	msg = msg[13] + setMessageParameters(msg[14], (e.number & 0xffff), e.description)
			+ setMessageParameters(msg[15], e, URL, e.line + line);
	return;
}

function getRawValue(field)
{
	return document.forms[0].elements[field.name.substr(6)].value;
}

function setRawValue(field)
{
	document.forms[0].elements[field.name.substr(6)].value=field.value;
}

function clientFormat(field, dataType, editcode, editparm, length, decimalPlaces, decimalSymbol, thousandSeparator, currencySymbolStr, dateSeparator, qdecfmtJValue)
{
	// set current value of field to hidden value
	document.forms[0].elements[field.name.substr(6)].value=field.value;

//document.write("value received is " + field.value+ '<br>');


	var errorOccurs = false;
	var fieldName = field.name;
	if (fieldName.indexOf("_iwcld") == 0)
		fieldName = field.name.substr(6);
	for( i=0; i<ValFailedArray.length; i++ )
	{
		if( ValFailedArray[i] == fieldName )
		{
			errorOccurs = true;
			break;
		}
	}
	if (errorOccurs)
	{
		return field.value;	
	}

	var rawvalue = field.value;
	if (rawvalue == null) rawvalue = "";
	var formatObj = new EditcodeEditwordFormatterClass();
	var da = formatObj.getDataAttributes();
	da.setDataType(dataType);	
	da.setDataLength(parseInt(length));
	da.setDecimalPlaces(parseInt(decimalPlaces));
	da.setDecimalSymbol(decimalSymbol);
	formatObj.setDataAttributes(da);
	if (thousandSeparator != null) formatObj.setThousandSeparator(thousandSeparator);
	if (currencySymbolStr != null) formatObj.setCurrencySymbolStr(currencySymbolStr);  
	if (dateSeparator != null) formatObj.setDateSeparator(dateSeparator);
	
	formatObj.setQdecfmtJValue(qdecfmtJValue);
	if (editcode.toUpperCase() == "NONE" )
	{
	 	output = rawvalue;
	}
	else if (editcode.toUpperCase() == "EDITWORD" )
	{
		formatObj.setEditWord(editparm);
		output = formatObj.formatString(rawvalue);
	}
	else
	{	
		formatObj.setEditCode(editcode);
		if (editparm == "*")
		{
			formatObj.setEditCodeParmType(1);
		}
		else if (editparm == "$")
		{
			formatObj.setEditCodeParmType(2);
		}
		else
		{
			formatObj.setEditCodeParmType(0);
		}
		output = formatObj.formatString(rawvalue);
	}

	return output;
}

/*----------------------------------------------------------------------------
 * limitText function
 * This limitText function is called only when Editcode/Editword formatting
 * is set in the field to limit the allowable characters and the number of
 * characters that can be typed.
 *----------------------------------------------------------------------------*/
function limitText(field, maxLen, cMinus, cDec, objEvent)
{
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (objEvent)
	   key = objEvent.which;
	else
	   return true;
	
	keychar = String.fromCharCode(key);

	// check control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;

	// accept numeric characters only
	else if ((("0123456789+"+cMinus+cDec).indexOf(keychar) > -1) && (field.value.length < maxLen))
	   return true;
	else
	   return false;
}


/*********************************************************** {COPYRIGHT-TOP} ***
* Licensed Materials - Property of IBM
* Tivoli Presentation Services 5.0
*
* (C) Copyright IBM Corp. 2002,2003 All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
************************************************************ {COPYRIGHT-END} ***
*******************************************************************************/

/*******************************************************************************
* This file contains all of the javascript functions used by the WCL renderers.
* The functions defined here must be stateless -- that is, no member variables
* can be defined, so all state information must be passed into the function
* as parameters.
*******************************************************************************/

////////////////////////////////////////////////////////////////////////////////
// form input component functions
////////////////////////////////////////////////////////////////////////////////

/** AWInputComponent **
 * action - the name of the action. do not encode because it is used as the
 *          value of a hidden input field.
 * formName - this encoded name of the form
 * wclhidden - the encoded name of the hidden field
 */
function frmAct(action, formName, wclhidden) {
   if (document != null && document.forms != null && formName != null) {
      var form = document.forms[formName];
      if (form != null) {
         eval( "form." + wclhidden + ".value = '" + action + "'" );
      }
   }
}

/** WComboBox **
 * textfield - the editable text field for the combobox
 * value - the value of the selected option
 * addOption - the value of the "add" option
 * comboImg - the image rendered next to the label of the dropdown
 * textImg - the image rendered next to the text field
 * statusName - the style class id for the status (normal, required, error)
 */
function editbx(textfield, value, addOption, comboImg, textImg, statusName) {
   if (textfield != null) {
      if (value != addOption) {
         textfield.disabled = true;
         textfield.className = "te1";
         if (comboImg != null) {
            comboImg.style.display = "inline";
         }
         if (textImg != null) {
            textImg.style.display = "none";
         }
      } else {
         textfield.disabled = false;
         if (statusName != null) {
            textfield.className = statusName;
         }
         if (comboImg != null) {
            comboImg.style.display = "none";
         }
         if (textImg != null) {
            textImg.style.display = "inline";
         }
      }
   }
}


/** WComboBox and WSelectionBox to cause an onChange in Netscape 7 with up and down arrow keys **
 * selObj - the selection object
 * event - the key event
 */
function chgEvt(selObj, event) {

   if(WClient.isBrowserMozilla() && WClient.isBrowserVersion7Up())
   {

      var wEvent = new WEvent(event);
      if(wEvent.getKeyCode() == 38 || wEvent.getKeyCode() == 40)
      {
         selObj.blur();
         selObj.focus();
      }
   }

}

////////////////////////////////////////////////////////////////////////////////
// complex component functions
////////////////////////////////////////////////////////////////////////////////

/** WTable **
 * formName - the encoded name of the form
 * anchorName - the name of the anchor used when the page is refreshed
 * wclanchor - the encoded name of the hidden field for the anchor
 */
function doAnchor(formName, anchorName, wclanchor) {
   var form = document.forms[formName];
   if (form != null && anchorName != null && wclanchor != null) {
      var aDate = new Date().getTime();
      eval("form." + wclanchor + ".value = '" + aDate + "'");

      // remove existing anchorName
      var index = form.action.indexOf( "#" );
      if ( index != -1 )
      {
          form.action = form.action.substring( 0, index );
      }
      form.action += '#' + anchorName;

      var inputName = "wclAnchorHash";
      var input  = document.getElementById( inputName );
      if ( !input )
      {
          input = document.createElement( "INPUT" );
          with ( input )
          {
              type  = "hidden";
              id    = inputName;
              name  = inputName;
          }
          form.appendChild( input );
      }
      input.value = anchorName;
   }
   return true;
}

/** WTable **
 * formName - the encoded name of the form
 * actionName - the name of the action being performed
 * actionValue - the name of the component performing the action
 * anchorName - the name of the anchor used when the page is refreshed
 * actionNameEnc - the encoded name of the action being performed
 * wclhidden - the encoded name of the hidden field
 * wclanchor - the encoded name of the hidden field for the anchor
 */
function doTbl(formName, actionName, actionValue, anchorName, actionNameEnc, wclhidden, wclanchor) {
   if (document != null && document.forms != null && formName != null) {
      var form = document.forms[formName];
      if (form != null) {
         if (actionName != null) {
            eval("form." + actionNameEnc + ".value = '" + actionValue + "'");
            eval("form." + wclhidden + ".value = '" + actionName + "'");
         }

         doAnchor(formName, anchorName, wclanchor);

		 //Copy last subfile change cell to iwcl hidden field. Note the name of the hidden
		 //field must not change. 
         if (sfCurInputFld != null) {
            setupIWCLHidden(sfCurInputFld, "iwclhidden"); 
         }
         
         form.submit();
      }
      return false;
   }
}

/** WTable **
 * toggles the background color for a row in the wtable
 */
function doTgl(inputElement) {
   if (inputElement != null)
   {
      var cells = inputElement.parentNode.parentNode.parentNode.childNodes;
      if (cells != null)
      {
         var suffix = cells[0].className.substring(cells[0].className.indexOf("s") > -1 ? 4 : 3);
         var style = "tbl" + (inputElement.checked ? "s" : "") + suffix;
         for (var i=0; i<cells.length; i++)
         {
            cells[i].className = style;
         }
      }
   }
   return true;
}

/** WTable **
 * toggles radio buttons in wtable
 */
function doRTgl(radioElement) {
   if (radioElement != null) {
      var radioGroup = radioElement.form.elements[radioElement.name];
      var done = false;
      if (!radioGroup.length)
         radioGroup = new Array(radioElement);
      for (var i=0; !done && i<radioGroup.length; i++) {
         if (radioGroup[i].parentNode.parentNode.className.indexOf("tbls2") == 0) {
            done = doTgl(radioGroup[i]);
            if (radioGroup[i] == radioElement)
               radioElement.checked = false;
         }
      }
      doTgl(radioElement);
   }
   return true;
}

/** WTable **
 * formName - the encoded name of the form
 * conditionsName - the encoded name of the conditions dropdown
 * startNumberName - the encoded name of the start number
 * endNumberName - the encoded name of the end number
 */
function numUpdate(formName, conditionsName, startNumberName, endNumberName) {
   var form = document.forms[formName];
     if (form != null) {
        var index = eval("form." + conditionsName + ".selectedIndex;");
        eval("form." + startNumberName+ ".parentNode.parentNode.parentNode.style.visibility=index == 0 ? 'hidden' : 'visible'");
        eval("form." + endNumberName + ".parentNode.parentNode.parentNode.style.visibility=index !=7 && index != 8? 'hidden' : 'visible'");
     }
   return true;
}

/** WTable **
 * formName - the encoded name of the form
 * conditionsName - the encoded name of the conditions dropdown
 * startDateName - the encoded name of the start date chooser
 * startTimeName - the encoded name of the start time chooser
 * endDateName - the encoded name of the end date chooser
 * endTimeName - the encoded name of the end time chooser
 */
function dateUpdate(formName, conditionsName, startDateName, startTimeName, endDateName, endTimeName) {
   var form = document.forms[formName];
     if (form != null) {
        var index = eval("form." + conditionsName + ".selectedIndex;");
        eval("form." + startDateName+ ".parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.visibility=index == 0 ? 'hidden' : 'visible'");
        eval("form." + startTimeName+ ".parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.visibility=index == 0 ? 'hidden' : 'visible'");
        eval("form." + endDateName+ ".parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.visibility=index !=3 ? 'hidden' : 'visible'");
        eval("form." + endTimeName+ ".parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.visibility=index !=3 ? 'hidden' : 'visible'");
     }
   return true;
}


