﻿
whisperer = {};

whisperer = {

    TipingWhisperDelay: 500,

    AskJSON: function(jsonRequestUrl, text, resultHandler) {

        if (text != '') {
            $.getJSON(jsonRequestUrl, 'text=' + text, resultHandler);
        }
    },

    SetTimeout: function(code) {
        return window.setTimeout(code, whisperer.TipingWhisperDelay);
    },

    ClearTimeout: function(timer) {
        if (timer != null) {
            window.clearTimeout(timer);
        }
    }
}

whisperer.TipingProcessor = function(inputBoxId, resultElementId, selectedValueInputBoxId, jsonRequestUrl) {

    this.jInputBox = $("#" + inputBoxId);
    this.jResultElement = $("#" + resultElementId);

    this.jSelectedValueInputBox = $("<input name='" + selectedValueInputBoxId + "' type='hidden' />");
    this.jResultElement.parent().append(this.jSelectedValueInputBox);
    this.jsonRequestUrl = jsonRequestUrl;

    this.timer = null;
    this.afterFoundHandler = null;

    var instance = this;
    this.jInputBox.keyup(function() { instance.Activate(); instance.jSelectedValueInputBox.attr("value", ""); });
};

whisperer.TipingProcessor.prototype = {

    Activate: function() {

        whisperer.ClearTimeout(this.timer);
        var instance = this;
        this.timer = whisperer.SetTimeout(function() { instance.BeginRequest(); });
    },

    BeginRequest: function() {

        var instance = this;
        whisperer.AskJSON(this.jsonRequestUrl, this.jInputBox.val(), function(resp) { instance.EndRequest(resp); });
    },

    EndRequest: function(resp) {

        this.jResultElement.empty();

        if (resp != null) {

            var instance = this;
            $.each(resp, function(intIndex, objValue) {
                var clickElm = $("<li><a href='#'>" + objValue.objectName + "</a></li>");
                clickElm.click(function() { instance.Update(objValue.objectId, objValue.objectName); return false; });
                instance.jResultElement.append(clickElm);
            });
        }

        if (this.afterFoundHandler != null) {
            this.afterFoundHandler(instance.jResultElement);
        }
    },

    Update: function(id, name) {

        if (this.jSelectedValueInputBox != null) {
            this.jSelectedValueInputBox.attr("value", id);
        }
        this.jInputBox.attr("value", name);

        this.jResultElement.empty();
    },

    AfterFoundHandler: function(handler) {

        this.afterFoundHandler = handler;
    }
};
