(function($)
{

    $.fn.formatCurrency = function(settings)
    {
        settings = jQuery.extend({
            name: "formatCurrency",
            useHtml: false,
            global: true
        }, settings);

        return this.each(function()
        {
            var num = "0";
            num = $(this)[settings.useHtml ? 'html' : 'val']();
            num = num.replace(/\$|\,/g, '');
            if (isNaN(num))
                num = "0";
            sign = (num == (num = Math.abs(num)));
            num = Math.floor(num * 100 + 0.50000000001);
            cents = num % 100;
            num = Math.floor(num / 100).toString();
            if (cents < 10)
                cents = "0" + cents;
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
                num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));

            $(this)[settings.useHtml ? 'html' : 'val'](((sign) ? '' : '-') + '$' + num + '.' + cents);
        });
    };

    $.fn.currencyAsFloat = function()
    {
        var value = $(this).val().replace(/ /g, "").replace("$", "").replace(/,/g, "");
        value = $.trim(value);
        if (value.length == 0) {value = 0;}
        return parseFloat(value);
    }
    
    $.fn.inputCurrency = function(settings)
    {
        settings = jQuery.extend({
            name: "inputCurrency"
        }, settings);
            
        function checkCharacter(c, str, selectionStart, selectionEnd, isPaste)
        {                    
            var validChars = new String();
            validChars = "0123456789.-"
            
            if (validChars.indexOf(c) > -1)
            {
                //if the whole string is highlighted, it is safe to enter any valid character
                if( (selectionEnd - selectionStart) == str.length )
                {
                    return true;
                }
                
                if (c == "-" )
                {   
                    //negative sign can be entered into an empty string
                    //or selectionStart is at the beginning 
                    if( str.length == 0 || (selectionStart==0))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }                       
                }
                else if (c == "." )
                {  
                    //is the decimal point in between selectionStart and selectionEnd?
                    if( selectionStart <= str.indexOf(".") && selectionEnd > str.indexOf(".") )   
                    {
                        return true; 
                    }
                   
                    //is there already a decimal point                   
                    if( str.indexOf(".") > -1) 
                    { 
                        return false;
                    }                       
                    
                    if( !isPaste && (str.length - selectionEnd) > 2 )
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    if( str.indexOf(".") == -1)
                    {               
                        return true;
                    }
                    else
                    {    
                        //we are inserting a number before the decimal point                   
                        if( selectionEnd <= str.indexOf(".") )
                        {
                            return true;
                        }
                        else
                        {         
                            //is the decimal point in between selectionStart and selectionEnd?
                            if( selectionStart <= str.indexOf(".") && selectionEnd > str.indexOf(".") )
                            {
                                return true;
                            }
                            else
                            {
                                //only allow two digits after decimal point                        
                                return ( ( str.length - str.indexOf(".") ) <= 2 ) ? true : false;
                            }
                        }
                    }
                }
            }
            else
            {
                return false;
            }
        };

        function checkKey(element, event)
        {                       
            if (event.charCode == 0)
            {
                return true;
            }
            
            //to catch backspace on IPhone
            if (event.charCode == 8)
            {
                return true;
            }

            if (event.ctrlKey)
            {
                return true;
            }
            
            if( document.selection )
            {                            
	            var range = document.selection.createRange();
	            var stored_range = range.duplicate();
	            stored_range.expand("textedit");
    	        stored_range.setEndPoint( 'EndToEnd', range );
	            element.selectionStart = stored_range.text.length - range.text.length;
	            element.selectionEnd = element.selectionStart + range.text.length;
            }            
         
            var selectionStart = element.selectionStart;
            var selectionEnd = element.selectionEnd;              

            var key = event.charCode || event.keyCode || 0;
            character = String.fromCharCode(key);                
                        
            return checkCharacter( character, $(element).val(), selectionStart, selectionEnd, false );
        }
        
        function checkString(element, event)
        {        
            if( document.selection )
            {                            
	            var range = document.selection.createRange();
	            var stored_range = range.duplicate();
	            stored_range.expand("textedit");
    	        stored_range.setEndPoint( 'EndToEnd', range );
	            element.selectionStart = stored_range.text.length - range.text.length;
	            element.selectionEnd = element.selectionStart + range.text.length;
            }            
         
            var selectionStart = element.selectionStart;
            var selectionEnd = element.selectionEnd;  
        
            var str = $(element).val();            
            var newStr = new String();            
            var i=0;
            for(i=0; i<str.length; i++)
            {
                if( checkCharacter(str.charAt(i), newStr, selectionStart, selectionEnd, true) )
                {
                    newStr += str.charAt(i);
                }
            }
            $(element).val(newStr);
        }


        return this.each(function()
        {
            $(this)
	                .unbind(".inputCurrency")
				    .bind("keydown.inputCurrency", function(event) { checkKey(this, event); })
				    .bind("keypress.inputCurrency", function(event) { return checkKey(this, event); })
				    .bind("paste.inputCurrency", function(event) { var me = this; setTimeout(function() { checkString(me); }, 10); })
				    .bind("blur.inputCurrency", function(event) { $(this).formatCurrency(); } )
				    .bind("focus.inputCurrency", function(event) { var me = this; checkString(me); } )
        });
    };


})(jQuery);