/*
-----------------------------------------------
Numerical Script
-----------------------------------------------
*/

String.prototype.reverse = function() {
	var sRev = new String();
	var iCount = this.length;
	for (var iCount = this.length - 1; iCount >= 0; iCount--) {
		sRev += this.charAt(iCount);
	}
	return sRev
}

function Numerical(sNumerical) {
	if (typeof sNumerical == 'string') {
		this.value = parseFloat(sNumerical);
	}
	else // typeof rValue = 'float' or 'integer'
		this.value = sNumerical;
}
//Numerical.prototype._baseFormat = void 0; // not needed
Numerical.prototype.valueOf = function() {return this.value;}
Numerical.prototype.format = '###0.00';
Numerical.prototype.toString = function() {
	if (isNaN(this.value))
		return 'NaN';
	else if (typeof this.format == 'string') {
		var srTail = new String();
		var srHead = new String();
		var sTail, sHead;
		var sfHead, sfTail;
		var re = /([^#0\,\.]*)([#\,0]*)(\.{0,1})([#0]*)([^#0]*)/i;
		var reRes = this.format.match(re);
		sfHead = reRes[2];
		sfTail = reRes[4];
		if (sfTail != '') {
			sTail = new String(Math.round(this.value * Math.pow(10,sfTail.length))/Math.pow(10,sfTail.length));
			if (sTail.search(/\./i) >= 0) {
				sHead = sTail.replace(/\..*/i,'');
				sTail = sTail.replace(/.*\./i,'');
			}
			else {
				sHead = sTail;
				sTail = '';
			}
			while (sfTail != '') {
				if (sTail != '') {
					srTail += sTail.charAt(0);
					sTail = sTail.slice(1);
				}
				else if (sfTail.charAt(0) == '0') {
					srTail += '0';
				}
				sfTail = sfTail.slice(1);
			}
		}
		else {
			sHead = new String(Math.round(this.value));
		}
		var bThou = false;
		var iCount = 0;
		if (sfHead.search(/,/i) >= 0) {
			bThou = true;
			sfHead = sfHead.replace(/,/i,'');
		}
		sfHead = sfHead.reverse();
		sHead = sHead.reverse();
		while (sfHead != '') {
			if (sfHead.charAt(0) == '0') {
				iCount++;
				if (iCount == 4 && bThou) {
					srHead = ',' + srHead;
					iCount = 1;
				}
				if (sHead != '') {
					srHead = sHead.charAt(0) + srHead;
					sHead = sHead.slice(1);
				}
				else
					srHead = '0' + srHead;
				sfHead = sfHead.slice(1);
			}
			else {
				while (sHead != '') {
					iCount++;
					if (iCount == 4 && bThou) {
						srHead = ',' + srHead;
						iCount = 1;
					}
					srHead = sHead.charAt(0) + srHead;
					sHead = sHead.slice(1);
				}
				sfHead = '';
			}
		}
		return reRes[1] + srHead + reRes[3] + srTail + reRes[5];
	}
	else
		return this.value;
}

