/*
Script: AutoFormat.js
	Automatically formats input elements as a number or currency
	Requires Mootools Core (mootools-core.js) from www.MooTools.net

License:
	MIT-style license.

Authors:
	Richard Bailey
	
Example Declaration: 
  window.addEvent('domready', function(){ 
        new AutoFormat($('zip'), {
            decimal: true, 
            currency: true, 
            minimum:10, 
            maximum:1000000
        }) 
  });

*/


var AutoFormat = new Class({
    Implements: [Options, Events],
    
   	options: {
		currency: false,
		decimal: false,
		minimum: 0, 
		maximum: null
	},

    
    initialize: function(control, options){
		this.setOptions(options);
		
        if (this.options.decimal) {
          this.reg = /^\d|delete|-$/;
        } else {
          this.reg = /^\d|-$/;
        }
        
        //this calls the proper function as part of this object exposing 
        //the object properties to the function 
        var self = this;
		this.fire = function(e){
			self.fireEvent(e.type)[e.type].apply(self, [e, this]);
		};
    	
		$$(control).addEvents({
			keypress: this.fire,
			focus: this.fire,
			blur: this.fire
		});
   
    },
    keypress: function(e, element){
        //Filter for the proper keys
        if (!e.key.test(this.reg)) {
            e.stop();
            element.highlight('#f88');
            
        //Only allow one decimal
        } else if (e.key == "delete" && element.get("value").contains(".")) {
            e.stop();
            element.highlight('#f88');
            
        //If the next key would make the value too large, stop it
        //This doesn't work for a minimum value since typing 1 would instantly
        //be smaller then a minimum value of 10
        } else if (this.options.maximum && ((element.get("value") + e.key) >  this.options.maximum)) {
            e.stop();
            element.highlight('#f88');
        }
             
    },
    
    
    focus: function(e, element){
        //Remove any formatting
        var val = element.get('value');
        while (val.match(/[^0-9\.-]/)) {
            val = val.replace(/[^0-9\.-]/, ''); 
        }
        element.set('value', val);
        
        //Set the cursor to the end of the field
        var pos = val.length
        var range = element.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    },
    
    blur: function(e, element){
        val = element.get('value');
        
        //Make sure the value meets the minimum size requirements
        if (val < this.options.minimum && val.length > 0) {
            element.highlight('#f88');
            alert("Value is too small.  Must be larger than " + this.options.minimum);
            element.focus();
        } else {
        
            //Format the value
            element.set('value', this.formatNumber(val, this.options.currency));            
        }
        
    },
    
    //Formats a series of numbers with commas and dollar signs
    formatNumber: function(val, currency){
        var rval = "", counter = 0
        if (val.length > 0) {
            //Find the rightmost starting point.  Either the decimal location 
            //or the end of the string
            //loop through all the characters appending it to the textbox adding a 
            //comma every 3 characters
            var sp = val.indexOf(".")
            if (sp == -1) sp = val.length;

            for (var t = sp ; t > 0; t--) {
                rval = val.charAt(t) + rval;
                if (counter % 3 == 0 && counter > 0) rval = ',' + rval;
                counter++;
            }
            rval = val.charAt(0) + rval;
            if (val.length > sp) rval = rval + val.substr(sp + 1, val.length-sp-1);
            if (currency) rval = "$" + rval;
        }
        return rval;
    }
    
});

