// JavaScript Document

// -=-=- add a trim function to the string object -=-=-=- //
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};
//pads left
String.prototype.lpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}
 
//pads right
String.prototype.rpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = str + padString;
    return str;
}

/// ARRAY CONTAINING A CROSS-REFERENCE OF DECIMAL NOTATION TO FRACTIONAL NOTATION
var fractionDecimals = new Array();
fractionDecimals["000"] = "";
fractionDecimals["125"] = "1/8";
fractionDecimals["250"] = "1/4";
fractionDecimals["375"] = "3/8";
fractionDecimals["500"] = "1/2";
fractionDecimals["625"] = "5/8";
fractionDecimals["750"] = "3/4";
fractionDecimals["875"] = "7/8";

/// IDENTIFIES THE INCREMENT SIZE FOR FRACTION CALCULATIONS...
var fractionIncrement = 125;	/// 125 = 1/8
var decimalPrecision = 3;


// -=-=-=-=-=-=--=-=-=-=-=-=--=-=-=-=-=-=--=-=-=-=-=-=--=-=-=-=-=-=--=-=-=-=-=-=--=-=-=-=-=-=--=-=-=-=-=-=- //
/// -=-=-=-= HELPER FUNCTION TO CONVERT DECIMAL VALUES TO FRACTIONAL VALUES -=-=-=-=-=- //
function gemConvertDecimalToFraction(value) {
	
	/// removes any non-digit, non-period characters from value
	var cleanString = value.toString().replace(/[^\d\.]*/g, "");
	
	if (cleanString.trim() == "" || new Number(cleanString) == 0) {
		return "";	
	}
	
	/// get the position of the decimal point
	var decimalPos = cleanString.indexOf(".");
	
	/// return the cleaned string if no decimal was present
	//if (decimalPos == -1)
	//	return cleanString;
		
	
	
	/// get the decimal part of the number, padded to desired precision
	var decimalValue = 0;
	var wholeNumber = 0;
	
	if (decimalPos == -1) {
		wholeNumber = new Number(cleanString);
		// leave decimal at 0
	}
	else {
		wholeNumber = new Number(cleanString.substr(0, decimalPos));
		decimalValue = new Number(cleanString.substr(decimalPos+1, decimalPrecision).rpad("0", decimalPrecision));	
	}
	
	/// get the fractional string
	var fString = fractionDecimals[decimalValue.toString().rpad("0", decimalPrecision)];
	var intString = "";
	
	/// if for some reason the fractional was not found, then simply re-append the decimal value....
	if (fString === undefined) {
		fString = "."+decimalValue.toString().rpad("0", decimalPrecision);	
		intString = wholeNumber.toString();		
	}
	/// otherwise append the fractional notation
	else if (fString.trim() != "" && wholeNumber > 0) {
		fString = "-"+fString;
		intString = (wholeNumber > 0) ? wholeNumber.toString() : "";
	}
	else if (wholeNumber > 0) {
		intString = wholeNumber.toString();
	}
	/// return a concatenated string
	return intString+fString+"\"";
	
}

