///////////////////////////////////////////////////////////////////////////////////////////////////
//	DLib Numerical JavaScript functions - copyright davidviner.com 2009 except where stated.
//
//	04.07.2009	5.5.1	DJV		Removed commented out code. Added documentation.
//
///////////////////////////////////////////////////////////////////////////////////////////////////

//C////////////////////////////////////////////////////////////////////////////////////////////////
// Numerical functions.
// @DLibNumerical
///////////////////////////////////////////////////////////////////////////////////////////////////

DLibNumerical = function ()
{
	var _public =
	{
		//F////////////////////////////////////////////////////////////////////////////////////////
		// Round to the specified number of decimal places.
		// @dec	double	The formatted value.
		// @num	double	The number to format.
		// @dp	int		The number of decimal places.
		///////////////////////////////////////////////////////////////////////////////////////////

		dec : function (num, dp)
		{
			var p = Math.pow (10, dp);
			var n = Math.round (num * p) / p;
			return n.toFixed (dp);
		},

		//F////////////////////////////////////////////////////////////////////////////////////////
		// Round to specified dec places but add thousands separators. Based on code found at:
		// http://snipplr.com/view/3516/mootools--numberformat/
		// @tDec	string	The formatted number.
		// @num		double	The number to format.
		// @dp		int		The number of decimal places.
		///////////////////////////////////////////////////////////////////////////////////////////

		tDec : function (num, dp)
		{
			// Returns matches[1] as sign, matches[2] as numbers and matches[3] as decimals

			var matches = /(-)?(\d+)(\.\d+)?/.exec ((isNaN (num) ? 0 : num) + '');
			var remainder = matches [2].length > 3 ? matches[2].length % 3 : 0;

			return (matches [1] ? matches [1] : '') +
				(remainder ? matches [2].substr (0, remainder) + ',' : '') +
				matches [2].substr (remainder).replace (/(\d{3})(?=\d)/g, "$1" + ',') +
				(dp ? '.' + (+ matches[3] || 0).toFixed (dp).substr (2) : '');
		},

		///////////////////////////////////////////////////////////////////////////////////////////
		// Used by formfields.php numberInput function.
		///////////////////////////////////////////////////////////////////////////////////////////

		numberInput : function (fld, dp, md)
		{
			var fs = fld.style;

			if (md == 1) // Focus
			{
				fs.textAlign = 'center';
			}
			else
			if (md == 2) // Blur
			{
				fs.textAlign = 'right';
				fld.value = _public.dec (fld.value, dp);
			}
		}
	};

	return _public;
} ();

///////////////////////////////////////////////////////////////////////////////////////////////////


