/**
 * @title Currency Input jquery plugin
 * @author Chris Deemer
 * @created 3/3/2008
 * 
 * @descr currency formatter for an input field
 * 
 * @param {Object}
 *            options is an optional parameter used to override the plugin
 *            defaults
 * 
 * @dependencies jquery.js
 * @optionalDependencies jquery.metadata.js
 */
(function($) {

	$.fn.money = function(options) {

		var opts = $.extend({}, $.fn.money.defaults, options);

		return this.each(function() {
			$this = $(this);
			/*
			 * detects if metadata plugin is available and gets data from each
			 * element
			 */
			var o = $.metadata ? $.extend({}, opts, $this.data()) : opts;
			$this.attr('style', 'text-align:right;' + $this.attr('style'));
			// create onFocus event (strips $, commas and periods)
			$this.focus(function() {
				this.value = $.fn.money.unformat(this.value)
			});
			// bind key event to only allow numbers and op keystrokes(left &
			// right arrows, backspace, delete)
			$this.keypress(function(evt) {
				if (((evt.charCode >= 48 && evt.charCode <= 57)
						|| evt.charCode == 8 || evt.charCode == 46
						|| evt.charCode == 9 || evt.charCode == 37 || evt.charCode == 39)
						|| ((evt.keyCode >= 48 && evt.keyCode <= 57)
								|| evt.keyCode == 8 || evt.keyCode == 46
								|| evt.keyCode == 9 || evt.keyCode == 37 || evt.keyCode == 39)) {
					return true;
				} else {
					return false;
				}
			});
			// create onChange event (format)
			$this.change(function() {
				var unfmtd = this.value;
				this.value = $.fn.money.format(unfmtd, o);
			});
		});
	};

	$.fn.money.defaults = {
		defaultToZero: true,
		comma : false,
		dollarSign : false,
		decimal : false
	};

	/**
	 * @param {String}  amount
	 *  @param{Object} o : extended options with individualized metadata         
	 */
	$.fn.money.format = function(amount, o) {
		if(!amount) return;
		if(o.defaultToZero==true && amount.length==0){
			amount="0";
		}
		// trim leading zeros
		if (amount.length > 1) {
			amount = amount.replace(/^0+/, "");
		}

		if (o.comma == true) {
			amount += '';
			x = amount.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		} else {
			return amount;
		}
	};

	/**
	 * @param {String} amount
	 */
	$.fn.money.unformat = function(amount) {
		if(!amount) return;
		var comma = /,/g;
		var dollar = /\$/;
		var period = /\./;
		amount = amount.replace(comma, "");
		amount = amount.replace(dollar, "");
		amount = amount.replace(period, "");
		return amount;
	};
})(jQuery);