/*******************************************************************************
FILE: RegExpValidate.js

TO INCLUDE THIS FILE:  this file will exist in a common/jscript folder.  You can include it
					   by either of the following conventions (relative or full url):
	<script language="JavaScript" src="../common/jscript/RegExpValidate.js"></script>
	<script language="JavaScript" src="http://domainname/common/jscript/RegExpValidate.js"></script>

DESCRIPTION: This file contains a library of validation functions
  using javascript regular expressions.  Library also contains functions that re-
  format fields for display or for storage.

  CONSTANT STRINGS:  (MKING added)
  list of a number of constant strings to be used for alert messages if validation fails

  VALIDATION FUNCTIONS:

  validateEmail - checks format of email address
  validateUSPhone - checks format of US phone number
  validateNumeric - checks for valid numeric value
  validateInteger - checks for valid integer value
  validateNotEmpty - checks for blank form field
  validateUSZip - checks for valid US zip code
  validateUSDate - checks for valid date in US format
  validateValue - checks a string against supplied pattern
  MKING added the following:
  validateSSN - checks if valid social security number format
  validateCurrency
  validateName
  validateUserName
  validateLength - checks if the length of the field is less than or equal to the input max length (useful for text areas)
  markMaxLengthOfString - will return a string with a marker indicating where the max length was exceeded
  checkMandatoryFields - loops thru the input array of mandatory fields and returns string of missing info
  SPFLIEGLER added the following:
  validateRadioButtonSelected - checks to see if a radio button was selected
  checkMandatoryFieldsBoolean - same as checkMandatoryFields but looks for true rather than a non empty string
  validateEmpty - Checks to verify if field is empty. (Calls validateNotEmpty)
  ADATTAROY added the following:
  validateCheckboxSelected - checks to see if at least one checkbox was selected
  validateRadioOrCheckboxSelected - checks to see if a radio button or at least one checkbox was selected
  SPFLIEGLER added the following:
  validateExactLength - returns true if length matches exactly, the passed in length
  validatePositiveInteger - checks for valid positive integer value, no negatives.
  SPFLIEGLER added the following:
  validateTime - validates a time format, non-military 1-12 hours.

  FORMAT FUNCTIONS:
  rightTrim - removes trailing spaces from a string
  leftTrim - removes leading spaces from a string
  trimAll - removes leading and trailing spaces from a string
  removeCurrency - removes currency formatting characters (), $
  addCurrency - inserts currency formatting characters
  removeCommas - removes comma separators from a number
  addCommas - adds comma separators to a number
  removeCharacters - removes characters from a string that match passed pattern

  MKING Note:  when adding different formats, each needs to be enclosed in parenthesis.  If copying
			   from ICFormatterForEN, don't forget to remove the extra / escape character.  Some of
			   the allowed formats are different than ICFormatter, but there should be no conflict.
			   These formats should be more strict if anything.  If add formats here, should add them
			   to ICFormatterForEN, and vice-versa.


AUTHOR: Karen Gayda  (downloaded from http://www.rgagnon.com/jsdetails/js-0063.html)
		Marhya King modified to use ICFormatterForEN acceptable formats

DATE: 03/24/2000
	  05/15/2002 mking modified  (modified to make compatible with ICFormatterForEN)
	  03/31/2003 ranjini modified (modified email format to include valid characters)
	  09/30/2003 scottp modified validatetexterrmsg to return ok if blank value sent
	  10/28/2004 scottp Added validateTime
	  12/09/2004 scottp Fixed validatetime to accept 0 as hour. Even though 12 hour clock, midnight comes back as 0
*******************************************************************************/

/*****************************************************************************************
The following are global strings to be used to display error messages when formatting fails
******************************************************************************************/
var strInvalidFormat = "You have entered an invalid format.  Make sure to remove starting and trailing spaces.";
var strUSPhoneValErrMsg = strInvalidFormat + "\n" +
		"Valid phone numbers are:\n" +
	    "(###) ###-####\n" +
		"### ### ####\n" +
		"###-###-####\n" +
		"###.###.####\n" +
		"##########";
var strSSNValErrMsg = strInvalidFormat + "\n" +
	"Valid SSN's are:\n" +
	"###-##-####\n" +
	"### ## ####\n" +
	"#########";
var strZipValErrMsg = strInvalidFormat + "\n" +
	"Valid zips are:\n" +
	"#####\n" +
	"#####-####";
var strNameValErrMsg = strInvalidFormat + "\n  Valid names can contain alphabet characters of either case, " +
	"spaces, a single quote (for names like O'DONNELL), hyphens, commas and periods.";
var strUserNameValErrMsg = strInvalidFormat + "\n Valid usernames can contain alphabet characters of either case and numbers.";
var strEmailValErrMsg = strInvalidFormat + "\n Valid emails must contain at least one @ and a period after. No double periods are allowed.";
var strIntegerValErrMsg = strInvalidFormat + "\n Valid integers can contain digits between 0 and 9 and a negative sign.";
var strNumericValErrMsg = strInvalidFormat + "\n Valid numbers can contain digits between 0 and 9, a decimal point, and a negative sign.";
var strShortDateValErrMsg = strInvalidFormat + "\n  Valid short format dates are:\n" +
	"MM/DD/YYYY\n" +
	"MM-DD-YYYY\n" +
	"MM DD YYYY\n" +
	"MMDDYYYY";
var strMarkerMessage = "*****EXCEEDED MAX LENGTH*****";
var strExceedMaxLength = "Your entry has exceeded the maximum length of characters allowed. " +
			" The maximum length is indicated by the following message marker:\n" + strMarkerMessage + "\n. " +
			" Please modify your entry appropriately.";
var strMissingFields = "Please enter the following mandatory fields:\n";

//formatting type enumerations
	var eShortDate = 0;
	var eLongDate = 1;
	var eShortDateTime = 2;
	var eLongDateTime = 3;
	var eXMLDateTime = 4;
	var eSSN = 6;
	var eZip = 7;
	var ePhone = 8;
	var eNumber = 9;
	var eCurrency = 10;
	var eName = 11;		// No weird characters
	var eEmail = 12;

/****************END OF GLOBAL CONSTANTS******************************************************/

function validateRadioButtonSelected( oRadioButton ) {
/**********************************************************************
DESCRIPTION: Takes an input RadioButton and loops through buttons to determine if one is selected
			 Useful for validating mandatory fields selected.

PARAMETERS: oRadioButton is the radio button object

RETURNS: True if a radio button has been selected, false if not
*********************************************************************/

	return validateRadioOrCheckboxSelected(oRadioButton);

} // validateRadioButtonSelected

function validateCheckboxSelected( oCheckbox ) {
/**********************************************************************
DESCRIPTION: Takes an input checkbox and loops through it to determine if at least one is selected
			 Useful for validating mandatory fields selected.

PARAMETERS: oCheckbox is the checkbox object

RETURNS: True if at least one checkbox has been selected, false if not
*********************************************************************/

	return validateRadioOrCheckboxSelected(oCheckbox);

} // validateCheckboxSelected

function validateRadioOrCheckboxSelected( oRadioOrCheckbox ) {
/**********************************************************************
DESCRIPTION: Takes an input RadioButton or Checkbox and loops through
			 buttons/checkboxes to determine if one is selected
			 Useful for validating mandatory fields selected.

PARAMETERS: oRadioOrCheckbox is the radio button or checkbox object

RETURNS: True if a radio button or at least one checkbox has been selected, false if not
*********************************************************************/

	for (i=0; i < oRadioOrCheckbox.length ; i++) {
		if (oRadioOrCheckbox[i].checked) {
			return true;
		}
	}

	return false;

} // validateRadioOrCheckboxSelected

function checkMandatoryFieldsBoolean ( aMandFields) {
/**********************************************************************
DESCRIPTION:  loops through the array of mandatory fields.  If value is false, will add
			  name to list of invalid fields.  Returns this list (as a string)

PARAMETERS:  aMandFields is an array of mandatory fields.
			 first field corresponds to true/false, second corresponds to name to be displayed.
			 Used for radio buttons that will have true if one is selected, rather than a value.
			 For example,
				mand_fields = new Array([2]);
				mand_fields[0] = new Array(2);
				mand_fields[1] = new Array(2);
				mand_fields[0][0] = validateRadioButtonSelected( document.FeedbackForm.FindLooking );
				mand_fields[0][1] = validateRadioButtonSelected( document.FeedbackForm.UserFriendly );
				mand_fields[1][0] = "Did you find what you were looking for?";
				mand_fields[1][1] = "Was the site user friendly";
				var msg = checkMandatoryFields(mand_fields);
			    if (msg!="") { alert(strMissingFields + msg); }
*********************************************************************/
	var tmp="";
	//loop thru the array of info
	for (i=0; i < aMandFields[0].length; i++)
	{
		  if (!aMandFields[0][i])
		  {
			tmp = tmp + aMandFields[1][i] + "\n";
	      }
	}//for
	return tmp;

} // checkMandatoryFieldsBoolean

function validateEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if empty, otherwise false.
*************************************************/
	return !validateNotEmpty(strValue);
}


function checkMandatoryFields ( aMandFields) {
/**********************************************************************
DESCRIPTION:  loops through the array of mandatory fields.  If trimmed value is blank, will add
			  name to list of invalid fields.  Returns this list (as a string)

PARAMETERS:  aMandFields is an array of mandatory fields.
			 first field corresponds to the value, second corresponds to name to be displayed.
			 For example,
				mand_fields = new Array([2]);
				mand_fields[0] = new Array(2);
				mand_fields[1] = new Array(2);
				mand_fields[0][0] = window.document.fmSubmit.LicCountry.value;
				mand_fields[0][1] = window.document.fmSubmit.DateDue.value;
				mand_fields[1][0] = "Country";
				mand_fields[1][1] = "Date Case Due";
				var msg = checkMandatoryFields(mand_fields);
			    if (msg!="") { alert(strMissingFields + msg); }
*********************************************************************/
	var tmp="";
	//loop thru the array of info
	for (i=0; i < aMandFields[0].length; i++)
	{
		  if (trimAll(aMandFields[0][i])=="")
		  {
			tmp = tmp + aMandFields[1][i] + "\n";
	      }
	}//for
	return tmp;

}

function markMaxLengthOfString( strText, iMaxLength) {
/*****************************************************
DESCRIPTION:  inserts a message inside a string if it exceeds the input Max Length, at that position
			  (this is good for textareas)

PARAMETERS:
  strText - String to be tested for length and modified if exceeds
  iLength - max length of string

RETURNS:  if does not exceed max length, the original string will be returned.
		  if it exceeds max length, a marker will be inserted at that point.

EXAMPLE:  input strText = "This is just a test."
          input iMaxLength = 5
          returns "This *****EXCEEDED MAX LENGTH*****is just a test."
**********************************************************************************************/
  if (validateLength(strText, iMaxLength)) {
    return strText; }
  else {
	return strText.substring(0, iMaxLength) + strMarkerMessage + strText.substring(iMaxLength);
  }
}

function validateExactLength( strValue, iMaxLength) {
/************************************************
DESCRIPTION: Validates that a string is exactly
	equal to the input length

 PARAMETERS:
   strValue - String to be tested for validity
   iLength  - max length of string

RETURNS:
   True if valid, otherwise false.
*************************************************/
	return (strValue.length == iMaxLength);
}

function validateLength( strValue, iMaxLength) {
/************************************************
DESCRIPTION: Validates that a string is less than or
	equal to the input length

 PARAMETERS:
   strValue - String to be tested for validity
   iLength  - max length of string

RETURNS:
   True if valid, otherwise false.
*************************************************/
	if(strValue != "")
	{
		 var iActLength = strValue.length;
		 if(iActLength > iMaxLength) { return false; }
	 }
	return true;
}

/**************************************************
DESCRIPTION:  Validates a value based on the input
	format type.
 PARAMETERS:
   strValue - String to be tested for validity
   eFormat  - int value of the format type (defined
				in this file)
RETURNS:
   Error message if not valid, "" if valid.
*************************************************/
function validateTextErrMsg(strValue, eFormat) {

  if (validateNotEmpty(strValue)) {
	  switch (eFormat) {
		case  eShortDate : if (!validateUSDate( strValue)) return strShortDateValErrMsg; break;
		case  eLongDate : if (!validateUSDate( strValue)) return strShortDateValErrMsg; break; //not implemented
		case  eShortDateTime :  if (!validateUSDate( strValue)) return strShortDateValErrMsg; break; //not implemented
		case  eLongDateTime :  if (!validateUSDate( strValue)) return strShortDateValErrMsg; break; //not implemented
		case  eXMLDateTime :  if (!validateUSDate( strValue)) return strShortDateValErrMsg; break; //not implemented
		case  eSSN : if (!validateSSN( strValue)) return strSSNValErrMsg; break;
		case  eZip : if (!validateUSZip( strValue)) return strZipValErrMsg; break;
		case  ePhone : if (!validateUSPhone( strValue)) return strUSPhoneValErrMsg; break;
		case  eNumber : if (!validateNumeric( strValue)) return strNumericValErrMsg; break;
		case  eCurrency : if (!validateCurrency( strValue)) return "This is an invalid currency"; break;
		case  eName : if (!validateName( strValue)) return strNameValErrMsg; break;
		case  eEmail :  if (!validateEmail( strValue)) return strEmailValErrMsg; break;
	  }
  }

  return "";
}

function validateName( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains only
	legitmate characters, hyphes, apostrophe, comma, or period
  ex, Smith-O'Neil, Jr.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp  = /(^[a-zA-Z \'\-\,\.]*$)/;

  //check for valid format
  return objRegExp.test(strValue);
}

function validateUserName( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains only
	 alpha-numerics
  ex, Mking03

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp  = /(^[a-zA-Z0-9]*$)/;

  //check for valid format
  return objRegExp.test(strValue);
}


function validateSSN( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid social security number pattern
  ex, ######### or ###-##-#### or ### ## ####

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp  = /(^\d{3}\-\d{2}\-\d{4}$)|(^\d{3}\s+\d{2}\s+\d{4}$)|(^\d{9}$)/;

  //check for valid format
  return objRegExp.test(strValue);
}

function validateCurrency( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid currency pattern

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp  = /(^\d*\.\d*$)|(^\-\s*\d*\.\d*$)|(^\$\s*\d*\.\d*$)|(^\$\s*\-\s*\d*\.\d*$)|(^\-\s*\$\s*\d*\.\d*$)|(^\d*$)|(^\-\s*\d*$)|(^\$\s*\d*$)|(^\$\s*\-\s*\d*$)|(^\s*\-\s*\$\s*\d*$)/;

  //check for valid foprmat
  return objRegExp.test(strValue);
}

function validateEmail( strValue) {
/******************************************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: mking: must contain an @ and then at least a period after.
         allows for dashes, underscore, hyphens and commas in name.
         no double periods allowed.

		 rnair: Greater than or less than signs, open or close parentheses,
		 open or close brackets,slash, period, comma, semicolon, colon,
		 a whitespace character (space, tab, form feed, line feed), at sign,
		 or quote cannot appear in the first part of the email address.
		 The domain part of the email address can either be an IP address
		 or a name. For eg: rnair@[102.233.45.234] and rnair@mail.intracorp.com
		 are both valid email addresses.

*******************************************************************************/
var objRegExp  = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;



  return objRegExp.test(strValue);

}

function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern. First number must be 1-9 (no zeros)
  Ex. 	mking:  valid formats are as follows:
		(###) ###-####
		### ### ####
		###-###-####
		###.###.####
		##########


PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  =  /(^[1-9]\d{9}$)|(^[1-9]\d{2}\s+\d{3}\s+\d{4}$)|(^[1-9]\d{2}\-\d{3}\-\d{4}$)|(^\([1-9]\d{2}\)\s*\d{3}\-\d{4}$)|(^[1-9]\d{2}\.\d{3}\.\d{4}$)/;

  return objRegExp.test(strValue);
}

function  validateNumeric( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:  MKING:  different than ICFormatter cause that only allows numbers, no decimals.  I will
		  keep this as-is.
******************************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:  MKING:  different than ICFormatter cause that doesn't allow neg numbers.  I will
		  keep this as-is.

******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validatePositiveInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid positive integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:

******************************************************************************/
  var objRegExp  = /(^\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateTime( strValue) {
/***************************************************
Description: Validate that a string is in a valid 12 hours
            time format. 99:99

Parameters:
    strValue - String to be tested for validity

Returns:
    True if valid, otherwise false
*****************************************************/
    var objRegExp = /(^\d{1}:\d{2}$)|(^\d{2}:\d{2}$)/;

    // check for valid time
    if (objRegExp.test(strValue)) {
        var iColonIndex = strValue.indexOf(":");
        var iHours = parseInt(strValue.substring(0, iColonIndex));
        var iMinutes = parseInt(strValue.substring(iColonIndex + 1));
        return ((iHours >= 0) && (iHours <=12) && (iMinutes >= 0) && (iMinutes <=59));
    }
    return false;

} // validateTime

function validateUSDate( strValue, blnEmptyValid ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 1 or 2 digit month, 1 or 2 digit day,
    4 digit year. Date separator can be space, -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mmddyyyy or mm dd yyyy
	When blnEmptyValid is not passed in (ie. undefined) empty strings are invalid dates.
	If blnEmptyValid is passed in then empty strings are valid dates if
	its true and invalid if its false.

PARAMETERS:
   strValue - String to be tested for validity
   blnEmptyValid - (Optional param) Boolean indicating if empty string
   					is considered valid or not

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
   MKING:  I removed allowance of . as seperator since would fail on server side if
   do icxmlrecordset.putformatteddata, but added the space as a possible seperator
*************************************************/
if (blnEmptyValid && validateEmpty(strValue))
{
	return true;
}
else
{
	//first test if in form mmddyyyy
	var objRegExp1 = /^\d{8}$/;
	if (objRegExp1.test(strValue)) {
	  return true; }
	//else check the other forms
	else {
	  var objRegExp = /^\d{1,2}(\-|\/|\s)\d{1,2}\1\d{4}$/;

	  //check to see if in correct format
	  if(!objRegExp.test(strValue))
	    return false; //doesn't match pattern, bad date
	  else{
	    //determine what the seperator is: a space, dash, or forward slash
	    var strSeparator = " ";
	    if (strValue.indexOf('-')!=-1) {
		strSeparator = "-";
	    } else if (strValue.indexOf("/")!=-1) {
		strSeparator = "/";
	    }

	    var arrayDate = strValue.split(strSeparator); //split date into month, day, year
	    //create a lookup for months not equal to Feb.
	    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
	                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31, '1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,'7' : 31,
	                        '8' : 31,'9' : 30}

	    var intDay = parseInt(arrayDate[1], 10);
	    var intYear = parseInt(arrayDate[2], 10);
	    var intMonth = parseInt(arrayDate[0], 10);

	    //I know these would give double error message (the one below and a generic incorrect format.
	    //But that is the easiest way to go.
		if (intMonth < 1 || intMonth > 12) {
		  alert("Invalid date: the month is out of range (1-12)");
		  return false;
		}
	    if (intYear < 1880 || intYear > 2200) {
		  alert("Invalid date: the year is out of range (1880-2200)");
		  return false;
		}

	    //check if month value and day value agree
	    if(arrayLookup[arrayDate[0]] != null) {
	      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0) {
	        return true; //found in lookup table, good date
	      } else { //not found, so do alert
	 	alert("Invalid date:  there are not that many days in the specified month");
	      	return false;
	      }
	    }

	    if (arrayDate[0]=='02' || arrayDate[0]=='2') {  //need to add this check to disallow things like 13/11/2002
	      //check for February
	      if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0) {
	        return true; //Feb. had valid number of days
	      } else {
	        alert("Invalid date:  there are not that many days in February");
	        return false;
	      }
	    }
	  }
	  return false; //any other values, bad date
	}
}
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.

PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);

 //check if string matches pattern
 return objRegExp.test(strValue);
}


function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.

PARAMETERS:
   strValue - String to be trimmed.

RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;

      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.

PARAMETERS:
   strValue - String to be trimmed

RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;

      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS:
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid
  numeric value in the rounded to 2 decimal
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;

    if( objRegExp.test(strValue)) {
      objRegExp.compile('^-');
      strValue = addCommas(strValue);
      if (objRegExp.test(strValue)){
        strValue = '(' + strValue.replace(objRegExp,'') + ')';
      }
      return '$' + strValue;
    }
    else
      return strValue;
}

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS:
  strValue - Source string from which commas will
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally

  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
  strValue - source string containing commas.

RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is
  returned.

REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match,
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS:
  strValue - source string containing number.

RETURNS: String modified with characters
  matching search pattern removed

USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd',
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );

 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}

function checkValidFormat(oField,eFormat) {

    var vVal = oField.value;
    var msg = validateTextErrMsg(vVal, eFormat);
    if (msg!="") {
      alert(vVal + ": " + msg);
      oField.value="";
      oField.focus();
      return false;
    } else {
      return true;
    }
}

