﻿/// <reference path="jquery-1.6.2.js"/>

$.fn.autocomplete = function (url, source, options) {
    var ac_input = this;
    var ac_timer;
    var ac_results;
    var ac_ajaxRequest;

    options = options || {}; // if nothing passed
    options.source = source; // put source for data and url in options object
    options.url = url;
    options.resultsClassName = options.resultsClassName || "ac_container"; // css class for div container
    options.loadDelay = options.loadDelay || 500; // default timeout before search
    //options.maxResults = options.maxResults || 20; //set in the controllers now
    options.qVar = options.qVar || "s";
    options.AjaxTimeout = options.AjaxTimeout || 3000;

    // Internal function to build results html
    function showResults(jsonObj) {
        $(ac_results).html("");

        if (jsonObj.Results.length == 0) {
            //No results
            $(ac_results).hide();
            return;
        }

        var ul = document.createElement("ul");

        $.each(jsonObj.Results, function () {
            var rItem = this;
            var li = document.createElement("li");

            if (options.valueControl != null && rItem.Value != null && rItem.Value.trim() != "")
                li.itemValue = rItem.Value;

            li.innerHTML = rItem.Text;
            ul.appendChild(li);
        });

        $(ac_results).append(ul);

        // Set up click handlers for items in list
        $(ul).find("li").click(function () {
            if (options.valueControl != null && this.itemValue != null) {
                // Set hidden control value
                $("#" + options.valueControl).val(this.itemValue);
            }
            // Set text box value
            $(ac_input).val(this.innerHTML).select();
            // Hide results ?
            $(ac_results).hide();
        });

        var pos = $(ac_input).offset();
        $(ac_results).css({
            top: (pos.top + $(ac_input).outerHeight()) + "px",
            width: parseInt($(ac_input).width()) + "px",
            left: pos.left + "px"
        });

        $(ac_results).show();
    }

    // Set up handler for autocomplete field
    this.each(function () {
        var input = this;

        $(input)
        .keydown(function (e) {
            var key = e.keyCode;

            if (key == 27 || key == 9 || key == 13) $(ac_results).hide(); // ESC/Tab/Enter key

            if (key == 9 || key == 13) return true; // Allow TAB, Enter
            if ((key > 8 && key < 32) || key == 38 || key == 40 || key == 46) return false;

            // Clear selected value if there is one
            if (options.valueControl != null) $("#" + options.valueControl).val("");

            if (ac_timer) window.clearTimeout(ac_timer);
            ac_timer = window.setTimeout(function () {
                var t = $(ac_input).val();
                if (t.length > 2) {
                    // ajax call
                    if (ac_ajaxRequest != null && ac_ajaxRequest.readyState != null && ac_ajaxRequest.readyState == 1) {
                        // Cancel active ajax call?
                        try {
                            ac_ajaxRequest.abort();
                        }
                        catch (e) { }
                        ac_ajaxRequest = null;
                    }

                    ac_ajaxRequest = $.ajax({ type: "POST",
                        url: options.url,
                        dataType: "json",
                        data: options.qVar + "=" + t,
                        processData: false,
                        error: function (req, status, err) {
                            // Error, hide results
                            $(ac_results).hide();
                        },
                        success: function (jsonDoc) {
                            if (jsonDoc != null) {
                                if (jsonDoc.Success != null && !jsonDoc.Success) {
                                    $(ac_results).hide();
                                }
                                else {
                                    showResults(jsonDoc);
                                }
                            }
                        },
                        timeout: options.AjaxTimeout
                    });

                }
            }, options.loadDelay);
        })  // input keydown
        .blur(function () {
            // NOTE - blur event handler prevents the click handler for the list items 
            window.setTimeout(function () {
                $(ac_results).hide()
            }, 100);
        }); // input blur

    });

    // Create results container div
    ac_results = document.createElement("div");
    $(ac_results).hide().css("position", "absolute").addClass(options.resultsClassName);
    $("body").append(ac_results);

    return this;
}

