﻿var autoCompleteAgent = new AutoCompleteAgent();

function AutoCompleteAgent() {
    this.timeOutHandler = 0;
    this.hideTimeoutHandler = 0;
}

$(document).ready(function() {
    autoCompleteAgent.initializeAutoCompletes();
    Sys.Application.add_load(function() { autoCompleteAgent.initializeAutoCompletes(); });
});

AutoCompleteAgent.prototype.initializeAutoCompletes = function() {
    var allAutoComplets = $(".AutoComplete").not("._INITIALIZED");
    allAutoComplets.each(function(index, el) {
        var autoComplete = $(el);
        autoComplete.addClass("_INITIALIZED");
        var panel = autoComplete.find("div.panel");

        panel.hover(
            function() { autoCompleteAgent.panelMouseOver(this); },
            function() { autoCompleteAgent.panelMouseOut(this); });
    });
}
AutoCompleteAgent.prototype.panelMouseOver = function(panel) {
    clearTimeout(autoCompleteAgent.hideTimeoutHandler);
    $(panel).attr("active", "true");
}
AutoCompleteAgent.prototype.panelMouseOut = function(panel) {
    panel = $(panel);
    panel.removeAttr("active");
    var textBox = panel.closest(".AutoComplete").find(":text");
    if (textBox.attr("active") != "true")
        autoCompleteAgent.hideTimeoutHandler = setTimeout(function() { panel.fadeOut('fast') }, 100);
}
AutoCompleteAgent.prototype.checkForExistingItem = function(control) {
    var panel = autoCompleteAgent.findItemsPanel(control);
    var valuebox = autoCompleteAgent.findSelectedValueBox(control);

    valuebox.val('');

    // find selected item if any item matches
    var textboxText = $.trim($(control).val().toLowerCase());
    $("div.item", panel).each(function(index, el) {
        var elText = $.trim($(el).attr("itemText").toLowerCase());
        if (elText == textboxText)
            valuebox.val($(el).attr('itemValue'));
    });
}
AutoCompleteAgent.prototype.textbox_keyUp = function(control, event) {
    control = $(control);
    var keyCode = autoCompleteAgent.getEventKeycode(event);
    if (keyCode != 38 && keyCode != 40 && keyCode != 13 && keyCode != 9) {
        autoCompleteAgent.setControlAsLoading(control);
        clearTimeout(autoCompleteAgent.timeOutHandler);
        autoCompleteAgent.timeOutHandler = setTimeout(function() { eval(control.attr('callbackCode')); }, parseInt(control.attr('requestDelay')));
    }
}
AutoCompleteAgent.prototype.setControlAsLoading = function(control) {
    control = $(control);
    control.css('background-image', "url('/images/spinner.gif')");
    control.css('background-repeat', 'no-repeat');
    control.css('background-position', 'right center');
}
AutoCompleteAgent.prototype.textbox_focus = function(control) {
    control = $(control);
    control.attr("active", "true");
    if (control.attr('expandOnFocus') == "true") {
        autoCompleteAgent.setControlAsLoading(control);
        eval(control.attr('callbackCode'));
    }
}
AutoCompleteAgent.prototype.textbox_blur = function(control) {
    control = $(control);
    control.removeAttr("active");
    var panel = autoCompleteAgent.findItemsPanel(control);

    if (panel.attr("active") != "true")
        autoCompleteAgent.hideTimeoutHandler = setTimeout(function() { panel.fadeOut('fast') }, 100);
}
AutoCompleteAgent.prototype.textbox_keyDown = function(control, event) {
    var keyCode = autoCompleteAgent.getEventKeycode(event);
    if (keyCode == 38 || keyCode == 40)
        autoCompleteAgent.moveUpDown(keyCode == 38, control);
    else if (keyCode == 13 || keyCode == 9)
        autoCompleteAgent.loadHighlightedItem(control);
}
AutoCompleteAgent.prototype.populateItems = function(result, control) {
    var panel = autoCompleteAgent.findItemsPanel(control);
    var textbox = $(control);
    var valuebox = autoCompleteAgent.findSelectedValueBox(control);
    textbox.css('background-image', 'none');

    panel.children().remove();
    panel.fadeIn('fast');

    var typedParts = textbox.val().split(' ');
    var items = result.split(textbox.attr("itemSeperator"));

    for (var i = 1; i < items.length; i = i + 2) {
        var text = items[i];
        var displayText = text;
        for (var j = 0; j < typedParts.length; j++) {
            if (typedParts[j].trim().length > 0) {
                var r = new RegExp(typedParts[j].replace("(", "\\(").replace(")", "\\)"), 'ig');
                displayText = displayText.replace(r, function($1) { return "¬" + $1 + "¬¬"; });
            }
        }
        displayText = displayText.replace(/¬¬/ig, "</span>");
        displayText = displayText.replace(/¬/ig, "<span class='highlight'>");

        var value = items[i + 1];

        var divItem = $("<div></div>").addClass('item').html(displayText);

        divItem.attr('itemValue', value);
        divItem.attr('itemText', text);

        divItem.mouseover(function() { $(this).addClass('highlighted'); });
        divItem.mouseout(function() { $(this).removeClass('highlighted'); });

        divItem.click(function() { autoCompleteAgent.listItem_Clicked(this); });

        panel.append(divItem);
    }

    autoCompleteAgent.alignPositions(panel, textbox);
    autoCompleteAgent.checkForExistingItem(control);
}

AutoCompleteAgent.prototype.listItem_Clicked = function(item) {
    item = $(item);
    var panel = autoCompleteAgent.findItemsPanel(item);
    var textbox = autoCompleteAgent.findTextBox(item);
    var valuebox = autoCompleteAgent.findSelectedValueBox(item);

    var selectedValue = item.attr('itemValue')
    // more items
    if (selectedValue.indexOf("#") == 0) {
        textbox.attr("pagecount", selectedValue.replace("#", ""));
        textbox.focus();
        var control = textbox.get(0);
        eval(textbox.attr('callbackCode'));
        return;
    }

    valuebox.val(selectedValue);
    panel.fadeOut('fast');
    textbox.val(item.attr('itemText'));

    if (textbox.attr('AutoPostBack') == 'true')
        setTimeout("__doPostBack('" + textbox.attr("controlid") + "','')", 0);
}
AutoCompleteAgent.prototype.alignPositions = function(panel, textbox) {
    var pos = textbox.position();
    panel.css({ top: pos.top + textbox.outerHeight(), left: pos.left });
}
AutoCompleteAgent.prototype.findItemsPanel = function(control) {
    var result = $(control).closest(".AutoComplete").find("div.panel");
    if (result.length == 0) alert('can not find panel inside auto complete');
    else return $(result.get(0));
}
AutoCompleteAgent.prototype.findTextBox = function(control) {
    var result = $(control).closest(".AutoComplete").find(":text");
    if (result.length == 0) alert('can not find textbox inside auto complete');
    else return $(result.get(0));
}
AutoCompleteAgent.prototype.findSelectedValueBox = function(control) {
    var result = $(control).closest(".AutoComplete").find(":hidden");
    if (result.length == 0) alert('can not find selected value box inside auto complete');
    else return $(result.get(0));
}
AutoCompleteAgent.prototype.moveUpDown = function(up, control) {

    var panel = autoCompleteAgent.findItemsPanel(control);

    panel.children().not("div.item").remove();

    var items = panel.children();
    if (items.length == 0) return;

    var highlighted = -1;
    var newHighlighted = -1;
    items.each(function(i, el) {
        if ($(el).is(".highlighted") && highlighted == -1) {
            highlighted = i;
        }
    });

    if (highlighted == -1) {
        if (up) newHighlighted = items.length - 1;
        else newHighlighted = 0;
    }
    else {
        if (up && highlighted == 0) return;
        if (!up && highlighted == items.length - 1) return;

        if (up) newHighlighted = highlighted - 1;
        else newHighlighted = highlighted + 1;

        // Hide old highlighted:
        $(items.get(highlighted)).removeClass('highlighted');
    }

    var selectedItem = $(items.get(newHighlighted));
    selectedItem.addClass('highlighted');

    // refine scroll
    panel.scrollTo(selectedItem);
}

AutoCompleteAgent.prototype.loadHighlightedItem = function(control) {
    var panel = autoCompleteAgent.findItemsPanel(control);
    $("div.highlighted", panel).click();
}

AutoCompleteAgent.prototype.getEventKeycode = function(event) {
    if (window.event)
        return window.event.keyCode; //IE
    else if (event)
        return event.which; //firefox
}