var dsep = ",";
var gsep = " ";


function FormatNumber(num, rounding) {
	if (num >= 0) {
		var high = Math.floor(num);
		var low = Math.round((num - high) * Math.pow(10, rounding)); // Result is '-Infinity' on first try
		low = Math.round((num - high) * Math.pow(10, rounding)); // Needed for IE calculation BUG
		
		if (low == 100) { high += 1; low = 0; }	 // .9999999999 comes out as 100	

		return fn(high, false, 0, rounding) + ((rounding > 0) ? (dsep + fn(low, true, 0, rounding)) : '');
	} else if (num < 0) {
		return '-' + FormatNumber(-num, rounding);
	} else {
		return num;
	}			
}

function fn(num, isdec, dig, rounding) {
	var n = Math.floor(num / 10);
	var r = num % 10;
	var th = !isdec && dig % 3 == 0 && dig > 0;

	if (!isdec && n == 0 || isdec && dig == rounding - 1) {
		return r + (th ? gsep : '');
	} else {
		return fn(n, isdec, dig - (-1), rounding) + r + (th ? gsep : '');
	}
}

function AFMoney(control, rounding) {
	if (control.value.length > 0) {
		var num = toFloat(control.value);
		if (!isNaN(num)){	
			control.value = FormatNumber(num, rounding);
		}
	}	
	return true;		
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function toFloat(value) {

	if(value.length == 0) return 0;

	var ds = dsep;
	var gs = gsep;

	var jsdsep=(1/2).toString().charAt(1);

	value = trim(value.replace(/\xA0/g, ' '));
	value = value.replace(/\&nbsp\;/g,' ');

	if (value.indexOf(' ') > 0) gs = ' ';
	if (value.indexOf(',') == value.lastIndexOf(',') && value.lastIndexOf(',') > 0) ds = ',';
	if (value.indexOf('.') == value.lastIndexOf('.') && value.lastIndexOf('.') > 0) ds = '.';
	if (value.indexOf('.') < value.lastIndexOf(',') && value.indexOf('.') > 0) { gs = '.'; ds = ','; }
	if (value.indexOf(',') < value.lastIndexOf('.') && value.indexOf(',') > 0) { gs = ','; ds = '.'; }

	if (ds != gs) {
		var rx = new RegExp('(\\' + gs + ')', 'g');
		value = value.replace(rx, '');
	}				

	var rx = new RegExp('(\\' + ds + ')', 'g');
	value = value.replace(rx, jsdsep);

	value = value.replace(/k/i, '000');	
	value = value.replace(/m/i, '000000');	
	value = value.replace(/g/i, '000000000');	
	value = value.replace(/\ /g, '');
	return parseFloat(value);
}
