﻿(function($) {
    $.fn.extend({
        changeOnFly: function(options) {
            //Set the default values
            var defaults = {
                delaySeconds: 1,
                ignoreFunctionKeys: true,
                onChange: function() { return true; }
            }

            var options = $.extend(defaults, options);

            return this.each(function() {
                var timeout;
                var o = options;
                var previous;

                $(this).keyup(function(event) {
                if (o.ignoreFunctionKeys) {
                        // esc
                        if (event.keyCode == 27)
                            return;
                        // return    
                        if (event.keyCode == 13)
                            return;
                        // left arrow    
                        if (event.keyCode == 37)
                            return;
                        // right arrow    
                        if (event.keyCode == 38)
                            return;
                        // up arrow    
                        if (event.keyCode == 39)
                            return;
                        //down arrow    
                        if (event.keyCode == 40)
                            return;
                    }

                    if (timeout != null) {
                        clearTimeout(timeout);
                    }
                    var text = $(this).val();
                    timeout = setTimeout(timeoutCallBack, o.delaySeconds * 1000);

                    function timeoutCallBack() {
                        if (previous != text) {
                            o.onChange.apply(this, [text]);
                            previous = text;
                        }
                    };
                });
            });
        }
    });

})(jQuery);  

