// js/class.vt_dollar.js

function class_vt_dollar()
{
	this.value = null;
	this.mark = '$';
	this.comma = ',';
	this.decimal = '.';
	
	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._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 = this.mark+'0'+this.decimal+'00';
			return;
		}
		
		this.value = parseFloat(this.value);
		if ( isNaN(this.value) )
		{
			this.formatted = this.mark+'0'+this.decimal+'00';
			return;
		}
		
		var is_negative = ( this.value < 0 );
		var work = Math.round(this.value*100) / 100;
		work = work.toFixed(2).split('.');
		var numbers = Math.abs(work[0]).toString().split('');
		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 = this.mark + commafied + this.decimal + work[1];
		if ( is_negative )
		{
			this.formatted = this._repl(this.formatted,'-','');
			this.formatted = '(' + this.formatted + ')';
		}
		return this.formatted;
	};
	
	this._strip = function()
	{
		if ( this.formatted == this.mark+'0'+this.decimal+'00' )
		{
			this.stripped = '0'+this.decimal+'00';
			return;
		}
		
		var str = ''+this.formatted;
		str = this._repl(str,this.mark,'');
		str = this._repl(str,this.comma,'');
		str = this._repl(str,this.decimal,'.');
		if ( str.indexOf(')') > 0 )
		{
			str = '-' + str;
			str = this._repl(str,'(','');
			str = this._repl(str,')','');
		}
		this.stripped = str;
		return this.stripped;
	};
} // function class_vt_dollar()

var VT_DOLLAR = new class_vt_dollar();

// class is now instantiated and has global scope, should be available to all other scripts

// end of file
