// function KeySequencer(scope) {
// 	scope.element.bind('keyup', function(e){
// 		if(scope.element.val()==""){
// 			scope.on_sequence_ready({val:scope.element.val()});
// 		}
// 	});
// 	scope.element.autocomplete(function(callback){
// 		scope.on_sequence_ready({val:scope.element.val()});
// 	},{
//         delay:scope.delay,
// 		minchars:scope.min_value_length
//     }).result(function(event,data,formatted){
// 		return false;
//     });
// };


function KeySequencer(scope) {
    var query_key_count = 0;
    var key_pressed = false;
    var do_action = null;
    var _oldVal = "";

    function set_value_changed_timer(callback) {
        query_key_count = 0;
        key_pressed = true;
        do_action = callback;
        on_key_timer();
    };

    function on_key_timer() {
        if (query_key_count++ < scope.thread_count) {
            setTimeout(on_key_timer, scope.thread_timeout);
        } else {
            try {
                if (key_pressed) do_action();
                key_pressed = false;
            } catch(e) {
               // log("Error running action");
            }
            
            key_pressed = false;
            query_key_count = false;
        }
    };


    function on_value_changed(event) {
        if(event.keyCode==13) return false;
        key_pressed = true;
        var val = $(this).val();  //  Capture the search value
        scope.on_sequence_changed({val:val});

        set_value_changed_timer(function() {
            //  As long as the values length is valid and not the old value
            if (String(val).length >= scope.min_value_length && _oldVal != val) {
                // _lastSearch=val;
                scope.on_sequence_ready({val:val});

            }

            //  Backup the old value for further comparison
            _oldVal = val;

        });

    };

    scope.element.bind('keyup', on_value_changed);
};
