﻿(function ($) {

    var data = new Array();
    var maxCounter = 50;
    var checkDelay = 10;

    var isStart = false;

    var methods = {

        init: function (delay, onType, onTyped) {
            return this.each(function () {

                var id = $(this).attr("id");
                var dummy = new Object();
                dummy.id = id;
                dummy.name = "";
                dummy.isTyping = false;
                dummy.notChangedCounter = 0;
                dummy.onType = onType;
                dummy.onTyped = onTyped;
                data.push(dummy);
            });

            checkDelay = delay;
        },
        start: function () {
            isStart = true;
            setTimeout(CheckTyping, checkDelay);

        },
        destroy: function () {
            data = new Array();
            maxCounter = 50;
            checkDelay = 10;
            isStart = false;

        }

    };


    $.fn.Instant = function (method) {
        if (methods[method]) {


            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.Quicklist');
        }
    };


    function CheckTyping() {
        if (!isStart)
            return;

        $.each(data, function (index, item) {

            //Changed?
            var text = $("#" + item.id).val();

            if (item.name != text) {

                item.isTyping = true;
                item.notChangedCounter = 0;

                item.name = text;

                // Callback
                item.onType(text);


            }
            else if (item.notChangedCounter >= 0) {
                item.notChangedCounter++;
            }

            if (item.notChangedCounter > maxCounter && item.name != "") {
                item.isTyping = false;
                item.notChangedCounter = -1;
                item.onTyped(text);
                $("body").trigger({ type: "onTyped", text: text });
            }

        });

        setTimeout(CheckTyping, checkDelay);

    }

    //  ...
    // end of closure
})(jQuery);
