/**
 * Copyright 2010 Allvesta, LLC
 *
 * This file and all of the source code contained within are the intellectual 
 * property of Allvesta, LLC. Any reproduction, description (either
 * written or verbal), or derivative of this code is strictly prohibited without
 * the written consent of Allvesta, LLC.
 *
 * -------------------------------------------------------------------------------
 *
 * Description: Number javascript functions.
 *      Author: Daniel Jennings (dsj@allvesta.com)
 *    Revision: A
 *  References: None
 *       Notes: None
 */


/**
 * Add commas to a number.
 * @param nStr Number string.
 * @return Number string with commas inserted.
 */
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
} //end method addCommas


/**
 * Convert a given number to a currency string
 * @param num Float value to convert
 * @param dollarSign Optional flag indicating whether or not to append string with dollar sign. Defaults to true
 * @return Current representation of the passed in value.
 *
 * NOTE: Modified from http://javascript.internet.com/forms/currency-format.html
 */
function convertToCurrency(num, dollarSign) {
	//determind if dollar sign is given
	if ((dollarSign == null) || (dollarSign == true)) {
		dollarSign = "$";
	}
	else {
		dollarSign = "";
	}

	//convert number to a string
	num = num.toString().replace(/\$|\, /g, '');
	if (isNaN(num)) {
		num = "0";
	}
	
	//determine sign of the number
	sign = (num == (num = Math.abs(num)));

	//convert number
	num = Math.floor(num*100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	
	//handle centers
	if (cents < 10) {
		cents = "0" + cents;
	}
	
	//add commas
	for (var ii=0; ii<Math.floor((num.length - (1+ii))/3); ii++) {
		num = num.substring(0,num.length-(4*ii+3)) + ',' + num.substring(num.length-(4*ii+3));
	}
	
	//return converted number
	return (((sign)?'':'-') + dollarSign + num + '.' + cents);
} //end function convertToCurrency


/**
 * Strip all non-digits.
 * @param str String to parse.
 * @return String with only digits remaining.
 */
function stripNonDigits(str) { 
   return str.replace(/[^\d]/g, ""); 
}
