/*
	VERSION:
		1.0.1	Removed function 'createUID' and moved it to 'lib_constant.js'.
		1.0.0	Begin versioning.
*/

/* NUMBER PROTOTYPE METHODS ------------------------------------ */
Number.prototype.roundDecimals = function(decimals) {
	return Math.roundDecimals(this, decimals);
};
Number.prototype.truncate = function(n) {
	n = Math.convert(n);
	if(n > 0) {
		var s = this + "";
		if(s.length > n) {
			return this.substr(0, n);
		}
	}
	return this;
};

/* MATH STATIC METHODS ----------------------------------------- */
Math.convert = function(v) {
	//converts string formatted numbers and currency to type of Number
	//converts everything else to 0
	if(v == undefined || v == null || v == '') {
		return 0;
	}
	v = v + "";
	v = (v+"").replace(/\$|\¢|,/gi, ""); //remove currency signs and commas
	
	//checks for negative numbers formatted with parenthesis, i.e. "(1.50)" becomes -1.5
	if(v.search(/^\((.)*\)$/) != -1) {
		v = "-" + v.replace(/\(|\)/gi, "");
	}
	return (isNaN(v) || v == '' ? 0 : v - 0);
};
Math.formatNumber = function(n, decimals, useLeadZero, useParen, useCommas) {
	/**********************************************************************
	n - the number to format
	decimals - the number of decimal places to format the number to
	useLeadZero - true / false - display a leading zero for numbers between -1 and 1
	useParen - true / false - use parenthesis around negative numbers
	useCommas - put commas as number separators.
	**********************************************************************/

	if ( !Math.isNumeric(n) ) { return "NaN"; }

	var nStr = Math.abs(Math.roundDecimals(n, decimals)) + "";

	if(decimals > 0) { 
		// Add zeros after decimal if needed
		nStr = nStr.split(".");
		if(nStr.length < 2) { nStr.push(""); }

		for(var i = decimals-nStr[1].length-1; i >= 0; i--) {
				nStr[1] += "0";
		}
		nStr = nStr.join(".") + "";
	}
		
	if (!useLeadZero && nStr.indexOf(".") != -1 && n < 1 && n > -1) {
		nStr = nStr.substr(1, nStr.length-1);
	}
		
	if (useCommas && (n >= 1000 || n <= -1000)) {

		var iStart = nStr.indexOf(".");
		if (iStart < 0) {
			iStart = nStr.length;
		}
		iStart -= 3;
		for (iStart; iStart >= 1; iStart -= 3) {
			nStr = nStr.substr(0,iStart) + "," + nStr.substr(iStart);
		}
	}
	if (n < 0) {
		nStr = (!useParen ? "-" + nStr : "(" + nStr + ")");
	}
	return nStr;
};
Math.isNumeric = function(v) {
	if(isNaN(v+"") || v == null || v+"" == "") {
		return false;
	}
	return true;
};
Math.randomNumber = function(lBound, uBound) {
	return (Math.floor(Math.random() * (uBound - lBound)) + lBound);
};
Math.roundDecimals = function(n, decimals) {
	if(!this.isNumeric(n)) { return "NaN"; }
	var dec = this.convert(decimals);
	var n = this.round(n * this.pow(10, dec));
	return n / this.pow(10, dec);
};