// js/class.vt_percent.js

function class_vt_percent()
{
	this.value = null;
	this.mark = '%';
	this.comma = ',';
	this.decimal = '.';
	this.precision = 1;
	
	this.formatted = null;
	this.stripped = null;
	
	this.prepare = function()
	{
		this.value = arguments[0] || 0;
		if ( typeof this.value != 'number' )
		{
			this.formatted = this.value;
			this.value = this._strip();
		}
		if ( typeof arguments[1] == 'object' )
		{
			var opts = arguments[1];
			this.mark = typeof opts.mark != 'undefined' ? opts.mark : '%';
			this.comma = typeof opts.comma != 'undefined' ? opts.comma : ',';
			this.decimal = typeof opts.decimal != 'undefined' ? opts.decimal : '.';
			this.precision = typeof opts.precision != 'undefined' ? parseInt(opts.precision) : 1;
			if ( this.precision < 0 ) this.precision = 0;
		}
		this._format();
		this._strip();
		this.value = parseFloat(this.stripped);
		return this.value;
	};
	
	this.prepare_from_id = function()
	{
		var _id = arguments[0] || '';
		if ( _id.substring(0,1) != '#' ) _id = '#' + _id;
		var _val = $(_id).val() || 0;
		if ( typeof arguments[1] == 'object' )
		{
			return this.prepare(_val, arguments[1]);
		}
		else
		{
			return this.prepare(_val);
		}
	};
	
	this._repl = function(str,a,b){
		return str.split(a).join(b);
	};
	
	this._format = function()
	{
		if ( !this.value )
		{
			this.formatted = '0'+this.decimal+'0'+this.mark;
			return;
		}
		
		this.value = parseFloat(this.value);
		if ( isNaN(this.value) )
		{
			this.formatted = '0'+this.decimal+'0'+this.mark;
			return;
		}
		
		var work, numbers, fraction;
		if ( this.precision > 0 )
		{
			var tens = Math.pow(10,this.precision);
			work = Math.round(this.value*tens) / tens;
			work = work.toFixed(this.precision).split('.');
			numbers = work[0].toString().split('');
			fraction = this.decimal + work[1];
		}
		else
		{
			work = Math.round(this.value);
			numbers = work.toString().split('');
			fraction = '';
		}
		var loop = 0;
		var commafied = '';
		while ( numbers.length > 0 )
		{
			commafied = numbers.pop() + commafied;
			loop++;
			if ( !(loop%3) && numbers.length )
			{
				commafied = this.comma + commafied;
			}
		}
		this.formatted = commafied + fraction + this.mark;
		return this.formatted;
	};
	
	this._strip = function()
	{
		if ( this.formatted == '0'+this.decimal+'0'+this.mark )
		{
			this.stripped = '0'+this.decimal+'0';
			return;
		}
		
		var str = this.formatted;
		str = this._repl(str,this.mark,'');
		str = this._repl(str,this.comma,'');
		str = this._repl(str,this.decimal,'.');
		this.stripped = str;
		return this.stripped;
	};
} // function class_vt_percent()

var VT_PERCENT = new class_vt_percent();

// class is now instantiated and has global scope, should be available to all other scripts

// end of file
