
/**
Text utility class.
A collection of useful text manipulation methods with no external dependencies.
*/
function TextUtil() {}

/**
Add commas to input number every three digits.
Provides robust input handling by using extractFloat() on the input data.  As a
result, non-numeric parts of the input will be discarded.  Commas are not added
to the fractional part of the input.
@param String amount Input number
@return String Number formatted with commas, eg '1,342,342'
@see extractFloat()
*/
TextUtil.addCommas = function(str)
{
	// Pre-process input
	if( ! str )
		return '';
	var inputValue = TextUtil.extractFloat(str);
	var minus = '';
	if( inputValue < 0 )
		minus = '-';
	inputValue = Math.abs(inputValue);

	// Break string into whole and fraction parts
	var parts = String( inputValue ).split('.');
	var whole = parts[0];
	var fraction = parts[1];

	// Add commas to whole part
	var output = [];
	while(whole.length > 3)
	{
		var tmp = whole.substr(whole.length-3);
		output.unshift(tmp);
		whole = whole.substr(0, whole.length-3);
	}
	if(whole.length > 0)
		output.unshift(whole);
	whole = output.join(',');

	// Build and return string
	if( ! fraction )
		return minus + whole;
	else
		return minus + whole + '.' + fraction;
}


/**
Extract floating point number from input string.
Pulls out the first number anywhere in the input string, but can't handle
the scientific format.
@param String Input string containing a float somewhere
@return float First floating point number in string, 0.0 if none found.
*/
TextUtil.extractFloat = function(str)
{
	var output = String(str);
	output = String( output.match(/-?[\d.,]+/) );
	output = output.replace(/,/g, '');
	output = parseFloat(output);
	if( ! output )
		output = 0.0;

	return output;
}


/**
Extract integer from input string.
Pulls out the first number anywhere in the input string and returns it as an
integer.  If the first number is a float, it is rounded to the nearest integer.
@param {String} input
@return float First integer in string, 0 if none found.
*/
TextUtil.extractInt = function(str)
{
	return Math.round( TextUtil.extractFloat(str) );
}


/**
Format input float into currency string, rounding to the nearest cent
if required.  Correctly handles rounding of negative values and lots of crazy
input.
@param amount Price to format
@param prefix Prefix string to use, defaults to '$'
@return String Formatted price, eg '$3.50'
*/
TextUtil.formatPrice = function( amount, prefix )
{
	if( ! prefix )
		prefix = '$';

	var value = TextUtil.extractFloat(amount);
	value = Math.round(value*100) / 100;
	var minus = '';
	if(value < 0)
		minus = '-';
	value = Math.abs(value);

	var dollars = Math.floor(value);
	var cents = Math.round( (value - dollars) * 100);
	cents = String(cents);
	if( cents.length == 1 )
		cents = '0'+cents;

	dollars = TextUtil.addCommas( dollars );
	if( dollars  == '' )
		dollars = '0';

	return minus + prefix + dollars + '.' + cents;
}

