//
// Author:	Martijn Polak <martijn.polak@amgate.com>
// Description: Number formatting functions for the num control
//

// -- Init -------------------------------------------------------------------------------------------------------------------------------------

// -- Number formatting ------------------------------------------------------------------------------------------------------------------------

// Automatically format a number depending on the decimals allowed
function autoFormatNum(numObject, decimals, mandatory) {
var orgValue = new String();
var newValue = new String();
var decValue = new String();
var preFix = new String();
var maxLen = (numObject.maxLength > 0 ? numObject.maxLength : 2147483647);

	orgValue = numObject.value.replace(/,/g, ".");

	if (!isNaN(orgValue) && (orgValue.length > 0)) {

		if (orgValue.substr(0, 1) == "-") {
			preFix = "-";
			orgValue = orgValue.substr(1);
		}

		if (orgValue.substr(0, 1) == "+") {
			preFix = "+";
			orgValue = orgValue.substr(1);
		}
		
		if (orgValue.substr(0, 1) == ".") orgValue = "0" + orgValue;
		
		var decPos = orgValue.indexOf(".");
		if (decPos > 0) {
			newValue = orgValue.substr(0, decPos);
		} else {
			newValue = orgValue;
		}
		
		if (newValue.length == 0) newValue = "0";

		if (decimals > 0) {

			if (newValue.length > (maxLen - (decimals + 1))) newValue = newValue.substr(0, newValue.length - (decimals + 1));

			if (decPos != -1) {

	 			decValue = orgValue.substr(decPos + 1, orgValue.length - decPos).replace(/\./g, "");
	 			var decDiff = decValue.length - decimals;
	
	 			if (decDiff <= 0) {
					if (decValue) newValue += "." + decValue;
				} else {
					newValue += "." + decValue.substr(0, decimals);
				}

			}

		} else {

			if (decPos == -1) {
				newValue = orgValue;
			}
			
		}

		numObject.value = preFix + newValue;

	} else {

		numObject.value = '';

	}

}


