///////////////////////////////////////////////////////////////////////////////////////////////////
//	DLib Numerical JavaScript functions - copyright davidviner.com 2009 except where stated.
//
//	24.01.2009	5.5.0	DJV		Split out from utils.js.
//
///////////////////////////////////////////////////////////////////////////////////////////////////

DLibNumerical = function ()
{
	var _public =
	{
		///////////////////////////////////////////////////////////////////////////////////////////
		// Round to 2 decimal places
		///////////////////////////////////////////////////////////////////////////////////////////

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

		///////////////////////////////////////////////////////////////////////////////////////////
		// Add thousands separator. Based on code found at:
		// http://snipplr.com/view/3516/mootools--numberformat/
		///////////////////////////////////////////////////////////////////////////////////////////

		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';
/*
				var str = fld.value;
				var str2 = "";
				var gotDot = -1;

				for (i = 0; i < str.length; i++)
				{
					var ch = str.substring (i, i + 1);

					if ((ch >= "0" && ch <= "9") || ch == ".")
					{
						if (ch == ".")
						{
							if (gotDot == -1)
							{
								gotDot = i;
								str2 += ch;
							}
						}
						else
						{
							str2 += ch;
						}
					}
				}

				if (dp > 0 && gotDot == -1)
				{
					str2 += ".";
					gotDot = str2.length - 1;
				}

				if (dp > 0)
				{
					while ((str2.length - (gotDot + 1)) < dp)
						str2 += "0";

					while ((str2.length - (gotDot + 1)) > dp)
						str2 = str2.substring (0, str2.length - 1);
				}

				if (str2 == "" || str2.substring (0, 1) == '.')
					str2 = "0" + str2;

				fld.value = str2;*/
				fld.value = _public.dec (fld.value, dp);
			}
		}
	};

	return _public;
} ();

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


