// Form Validation Functions  v1.1.6
// http://www.dithered.com/javascript/form_validation/index.html
// code by Chris Nott (chris@NOSPAMdithered.com - remove NOSPAM)


function getFormErrors(form) {
   var errors = new Array();
   
   // loop thru all form elements
   for (var elementIndex = 0; elementIndex < form.elements.length; elementIndex++) {
      var element = form.elements[elementIndex];
     
      // text and textarea types
      if (element.type == "text" || element.type == "textarea") {
         element.value = trimWhitespace(element.value)
         
         // required element
         if (element.required  && element.value == '') {
            errors[errors.length] = element.requiredError;
         }
         
         // maximum length
         else if (element.maxlength && isValidLength(element.value, 0, element.maxlength) == false) {
            errors[errors.length] = element.maxlengthError;
         }

         // minimum length
         else if (element.minlength && isValidLength(element.value, element.minlength, Number.MAX_VALUE) == false) {
            errors[errors.length] = element.minlengthError;
         }
         
         // pattern (credit card number, email address, zip or postal code, alphanumeric, numeric)
         else if (element.pattern && element.value != '') 
         {
            var blnPatternValid = true;
            
            switch (element.pattern.toLowerCase())
            {
              case 'visa':
              case 'mastercard':
              case 'american express':
              case 'diners club':
              case 'discover':
              case 'enroute':
              case 'jcb':
              case 'credit card':
                blnPatternValid = isValidCreditCard(element.value, element.pattern);
                break;
              case 'email':        
                blnPatternValid = isValidEmailStrict(element.value);
                break;
              case 'zip or postal code':
                blnPatternValid = (isValidZipcode(element.value) || isValidPostalcode(element.value))
                break;
              case 'zipcode':
                blnPatternValid = isValidZipcode(element.value);
                break;
              case 'postal code':
                blnPatternValid = isValidPostalcode(element.value);
                
                if(blnPatternValid)
                  reformatPostalCode(element);
                  
                break;
              case 'us phone number':
                if(element.prefix && element.suffix)
                {
                  blnPatternValid = isValidUSPhoneNumber(element.value, form[element.prefix].value, form[element.suffix].value)
                }
                else if(!element.prefix && !element.suffix)
                {
                  blnPatternValid = isValidUSPhoneNumber(element.value);
                  
                  if(blnPatternValid)
                    reformatPhoneNumber(element);
                }
                break;
              case 'date':
                blnPatternValid = isValidDate(element.value, true);
                break;
              case 'alphanumeric':
                blnPatternValid = isAlphanumeric(element.value, true);
                break;
              case 'numeric':
                blnPatternValid = isNumeric(element.value, true);
                break;
              case 'alphabetic':
                blnPatternValid = isAlphabetic(element.value, true);
                break;
            }
            
            if(blnPatternValid == false)
            {
              errors[errors.length] = element.patternError;
            }

/*            
            if ( ( (element.pattern.toLowerCase() == 'visa' || element.pattern.toLowerCase() == 'mastercard' || element.pattern.toLowerCase() == 'american express' || element.pattern.toLowerCase() == 'diners club' || element.pattern.toLowerCase() == 'discover' || element.pattern.toLowerCase() == 'enroute' || element.pattern.toLowerCase() == 'jcb' || element.pattern.toLowerCase() == 'credit card') && isValidCreditCard(element.value, element.pattern) == false) ||
              (element.pattern.toLowerCase() == 'email' && isValidEmailStrict(element.value) == false) ||
              (element.pattern.toLowerCase() == 'zip or postal code' && isValidZipcode(element.value) == false && isValidPostalcode(element.value) == false) ||
              (element.pattern.toLowerCase() == 'zipcode' && isValidZipcode(element.value) == false) ||
              (element.pattern.toLowerCase() == 'postal code' && isValidPostalcode(element.value) == false) ||
              (element.pattern.toLowerCase() == 'us phone number' && 
                 ( (element.prefix && element.suffix && isValidUSPhoneNumber(element.value, form[element.prefix].value, form[element.suffix].value) == false) || 
                    (!element.prefix && !element.suffix && isValidUSPhoneNumber(element.value) == false) ) ) ||
              (element.pattern.toLowerCase() == 'alphanumeric' && isAlphanumeric(element.value, true) == false) ||
              (element.pattern.toLowerCase() == 'numeric' && isNumeric(element.value, true) == false) ||
              (element.pattern.toLowerCase() == 'alphabetic' && isAlphabetic(element.value, true) == false) ) 
            {
              errors[errors.length] = element.patternError;
            }
*/            
         }
      }
      
      // password 
      else if (element.type == "password") {
         
         // required element
         if (element.required  && element.value == '') {
            errors[errors.length] = element.requiredError;
         }
         
         // maximum length
         else if (element.maxlength && isValidLength(element.value, 0, element.maxlength) == false) {
            errors[errors.length] = element.maxLengthError;
         }

         // minimum length
         else if (element.minlength && isValidLength(element.value, element.minlength, Number.MAX_VALUE) == false) {
            errors[errors.length] = element.minLengthError;
         }
      }
      
      // file upload
      if (element.type == "file") {
         
         // required element
         if (element.required  && element.value == '') {
            errors[errors.length] = element.requiredError;
         }
      }
      
      // select
      else if (element.type == "select-one" || element.type == "select-multiple" || element.type == "select") {

         // required element
         if (element.required && element.selectedIndex == -1) {
            errors[errors.length] = element.requiredError;
         }
         
		 // disallow empty value selection
         else if (element.disallowEmptyValue && element.options[element.selectedIndex].value == '') {
            errors[errors.length] = element.disallowEmptyValueError;
         }

      }
      
    // radio buttons
    else if (element.type == "radio") 
    {
      if(element.required && element.requiredError)
      {
        var checkedRadioButton = -1;
        
        var radiogroup = form.elements[element.name];
                    
        if(radiogroup.length == undefined)
        {
          if(element.checked)
            checkedRadioButton = 1;
        }  
        else            
        {
          for (var radioIndex = 0; radioIndex < radiogroup.length; radioIndex++)
          {
             if (radiogroup[radioIndex].checked == true) 
             {
                checkedRadioButton = radioIndex;
                break;
             }
          }
        }
        
        radiogroup = null;
        
        if (checkedRadioButton == -1)
        {
          errors[errors.length] = element.requiredError;
        }
      }
      
/* The followind section has been replaced by the code above because there was some
   problems with assigning the "required" property to a radio group.  The results where 
   unpredictable.  Sometimes the required property would be set and sometimes it would come
   back as undefined.
          
      var radiogroup = form.elements[element.name];
      
      // required element
      if (radiogroup.required)
      {
        var checkedRadioButton = -1;         
                    
        if(radiogroup.length == undefined)
        {
          if(radiogroup.checked)
            checkedRadioButton = 1;
        }  
        else            
        {
          for (var radioIndex = 0; radioIndex < radiogroup.length; radioIndex++)
          {
             if (radiogroup[radioIndex].checked == true) 
             {
                checkedRadioButton = radioIndex;
                break;
             }
          }
        }

        if (checkedRadioButton == -1 && !radiogroup.tested)
        {
          errors[errors.length] = radiogroup.requiredError;
          radiogroup.tested = true;
        }
      }
      radiogroup = null;
*/      
    }
  }
	return errors;
}

// Check that the number of characters in a string is between a max and a min
function isValidLength(string, min, max) {
	if (string.length < min || string.length > max) return false;
	else return true;
}

// Check that a credit card number is valid based using the LUHN formula (mod10 is 0)
function isValidCreditCard(number) {
	number = '' + number;
	
	if (number.length > 16 || number.length < 13 ) return false;
	else if (getMod10(number) != 0) return false;
	else if (arguments[1]) {
		var type = arguments[1];
		var first2digits = number.substring(0, 2);
		var first4digits = number.substring(0, 4);
		
		if (type.toLowerCase() == 'visa' && number.substring(0, 1) == 4 &&
			(number.length == 16 || number.length == 13 )) return true;
		else if (type.toLowerCase() == 'mastercard' && number.length == 16 &&
			(first2digits == '51' || first2digits == '52' || first2digits == '53' || first2digits == '54' || first2digits == '55')) return true;
		else if (type.toLowerCase() == 'american express' && number.length == 15 && 
			(first2digits == '34' || first2digits == '37')) return true;
		else if (type.toLowerCase() == 'diners club' && number.length == 14 && 
			(first2digits == '30' || first2digits == '36' || first2digits == '38')) return true;
		else if (type.toLowerCase() == 'discover' && number.length == 16 && first4digits == '6011') return true;
		else if (type.toLowerCase() == 'enroute' && number.length == 15 && 
			(first4digits == '2014' || first4digits == '2149')) return true;
		else if (type.toLowerCase() == 'jcb' && number.length == 16 &&
			(first4digits == '3088' || first4digits == '3096' || first4digits == '3112' || first4digits == '3158' || first4digits == '3337' || first4digits == '3528')) return true;
		
    // if the above card types are all the ones that the site accepts, change the line below to 'else return false'
    else return true;
	}
	else return true;
}

// Check that an email address is valid based on RFC 821 (?)
function isValidEmail(address) {
	if (address != '' && address.search) {
      if (address.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
      else return false;
	}
	
   // allow empty strings to return true - screen these with either a 'required' test or a 'length' test
   else return true;
}

// Check that an email address has the form something@something.something
// This is a stricter standard than RFC 821 (?) which allows addresses like postmaster@localhost
function isValidEmailStrict(address) {
	if (isValidEmail(address) == false) return false;
	var domain = address.substring(address.indexOf('@') + 1);
	if (domain.indexOf('.') == -1) return false;
	if (domain.indexOf('.') == 0 || domain.indexOf('.') == domain.length - 1) return false;
	return true;
}

// Check that a US zip code is valid
function isValidZipcode(zipcode) {
	zipcode = removeSpaces(zipcode);
	if (!(zipcode.length == 5 || zipcode.length == 9 || zipcode.length == 10)) return false;
   if ((zipcode.length == 5 || zipcode.length == 9) && !isNumeric(zipcode)) return false;
   if (zipcode.length == 10 && zipcode.search && zipcode.search(/^\d{5}-\d{4}$/) == -1) return false;
   return true;
}

// Check that a Canadian postal code is valid
function isValidPostalcode(postalcode) {
	if (postalcode.search) {
		postalcode = removeSpaces(postalcode);
		if (postalcode.length == 6 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/) != -1) return true;
		else if (postalcode.length == 7 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]-\d[a-zA-Z]\d$/) != -1) return true;
		else return false;
	}
	return true;
}

// Check that a US or Canadian phone number is valid
function isValidUSPhoneNumber(areaCode, prefixNumber, suffixNumber) {
   if (arguments.length == 1) {
      var phoneNumber = arguments[0];
      phoneNumber = phoneNumber.replace(/\D+/g, '');
      var length = phoneNumber.length;
      if (phoneNumber.length == 10) {
         var areaCode = phoneNumber.substring(0, length-7);
         var prefixNumber = phoneNumber.substring(length-7, length-4);
         var suffixNumber = phoneNumber.substring(length-4);
      }
      else return false;
   }
   else if (arguments.length == 3) {
      var areaCode = arguments[0];
      var prefixNumber = arguments[1];
      var suffixNumber = arguments[2];
   }
   else return true;

   if (areaCode.length != 3 || !isNumeric(areaCode) || prefixNumber.length != 3 || !isNumeric(prefixNumber) || suffixNumber.length != 4 || !isNumeric(suffixNumber))
   {
     return false;
   }
   else
   {
     return true;
   }
}

function isValidDate(strValue)
 {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 4 digit year, 2 digit month, 
    2 digit day. Date separator can be ., -, or /.
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. yyyy/mm/dd or yyyy/mm-dd or yyyy.mm.dd
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/

  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var strSeparator = strValue.substring(4,5) //find date separator
    var arrayDate = strValue.split(strSeparator); //split date into year, month, day
    //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}
    var intDay = parseInt(arrayDate[2],10); 

    //check if month value and day value agree
    if(arrayLookup[arrayDate[1]] != null)
    {
      if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
        return true; //found in lookup table, good date
    }
    
    //check for February
    var intYear = parseInt(arrayDate[0],10);
    var intMonth = parseInt(arrayDate[1],10);
        
    if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
      return true; //Feb. had valid number of days
  }
  return false; //any other values, bad date
}

// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) 
{

  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; 
 
  //check for numeric characters 
  return objRegExp.test(string);

/* The following code was the initial code found in this file.
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
*/	
}

// Remove characters that might cause security problems from a string 
function removeBadCharacters(string) {
	if (string.replace) {
		string.replace(/[<>\"\'%;\)\(&\+]/, '');
	}
	return string;
}

// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}

// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;
	
	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {
		
		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {
			
			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}
		
		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}

// Returns a checksum digit for a number using mod 10
function getMod10(number) {
	
	// convert number to a string and check that it contains only digits
	// return -1 for illegal input
	number = '' + number;
	number = removeSpaces(number);
	if (!isNumeric(number)) return -1;
	
	// calculate checksum using mod10
	var checksum = 0;
	for (var i = number.length - 1; i >= 0; i--) {
		var isOdd = ((number.length - i) % 2 != 0) ? true : false;
		digit = number.charAt(i);
		
		if (isOdd) checksum += parseInt(digit);
		else {
			var evenDigit = parseInt(digit) * 2;
			if (evenDigit >= 10) checksum += 1 + (evenDigit - 10);
			else checksum += evenDigit;
		}
	}
	return (checksum % 10);
}


// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
// stripCharsNotInBag (s, bag)         Removes all characters NOT in string bag from string s.
// stripWhitespace (s)                 Removes all whitespace characters from s.
// stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.
// reformat (TARGETSTRING, STRING,     Function for inserting formatting characters or
//   INTEGER, STRING, INTEGER ... )       delimiters into TARGETSTRING.                                       
// reformatZIPCode (ZIPString)         If 9 digits, inserts separator hyphen.
// reformatPostalCode (PostalString)   If 6 alphanumeric characters insert space (J8P 2L6).
// reformatSSN (SSN)                   Reformats as 123-45-6789.
// reformatPhoneNumber (PhoneNumber)           Reformats as (123) 456-789.
// Trim                                 Removes leading & traiing spaces.
// LTrim                                Removes leasding spaces.
// RTrim                                Removes trailing spaces.
// LPad	(Value, numOfZeros)				Left pads value with zeros specified


// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number 
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123) 456-7890" make this function call:
//   reformat("1234567890", "(", 3, ") ", 3, "-", 4)
//
// * To reformat a 9-digit U.S. Social Security number from
//   "123456789" to "123-45-6789" make this function call:
//   reformat("123456789", "", 3, "-", 2, "-", 4)
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call function stripCharsNotInBag to remove the unwanted 
// characters, THEN call function reformat to delimit as desired.
//
// EXAMPLE:
//
// reformat (stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}


// takes ZIPString, a string of 5 or 9 digits;
// if 9 digits, inserts separator hyphen

function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}


// takes PostalString, a string of 6 alphanumeric characters

function reformatPostalCode (theField)
{
  var PostalCodeDelimiters = " ";
  var normalizedPostal = stripCharsInBag(theField.value, PostalCodeDelimiters)

  normalizedPostal = normalizedPostal.toUpperCase();
  
  if (normalizedPostal.length == 6)
    theField.value = reformat (normalizedPostal, "", 3," ", 3);
}


// takes PhoneNumber, a string of 10 digits
// and reformats as (123) 456-789

function reformatPhoneNumber (theField)
{
  var phoneNumberDelimiters = "()- ";
  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)

  theField.value = reformat(normalizedPhone, "(", 3, ") ", 3, "-", 4);
}


	/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function LTrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;


      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function Trim(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return RTrim(LTrim(str));
}


// takes SSN, a string of 9 digits
// and reformats as 123-456-789

function reformatSSN (SSN)
{   return (reformat (SSN, "", 3, "-", 3, "-", 3))
}


function reformatFullDate (FullDate)
{
  return (reformat (FullDate, "", 4, "/", 2, "/", 2));
}


// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag 
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}


/************************************************
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.
*************************************************/
function formatCurrency(strValue)
{
  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;
}


/************************************************
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.
*************************************************/
function addCommas( strValue ) 
{
  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;
}


