/* client-side functionality of StyledDropDown control */
function DropDownItem(text, value, domElem) {
    this.Text = text;
    this.Value = value;
    this.DOMElem = domElem;
}

Type.registerNamespace('Kaos.UI');

Kaos.UI.DropDown = function(element) {
    Kaos.UI.DropDown.initializeBase(this, [element]);

    this._imgTrigger = null;
    this._itemsBlock = null;
    this._valueContainer = null; // hidden field that contains selected value
    this._defaultText = null;
    this._disabled = null;
    this._maxItemsToDisplay = 13;
    this._items = new Array(); // array of DropDownItem objects
    this._lastAutoSearchText = new String("");
    this._lastAutoSearchTimer = null;
}

Kaos.UI.DropDown.prototype = {

    initialize: function() {

        Kaos.UI.DropDown.callBaseMethod(this, 'initialize');

        $addHandlers(this.get_element(),
            {
                blur: this._onBlur,
                click: this._onClick,
                keydown: this._onKeyDown
            },
            this);

        $addHandlers(this._imgTrigger,
            { click: this._onClick },
            this);
    },

    dispose: function() {
        $clearHandlers(this.get_element());
        Kaos.UI.DropDown.callBaseMethod(this, 'dispose');
    },

    registerItem: function(item) {
        Array.add(this._items, item);
        item.DOMElem.dropDownItem = item;
    },

    initializeItems: function() {
        for (var i = 0; i < this._items.length; i++) {
            $create(Kaos.UI.HoverBehavior,
                {
                    "hoverCssClass": "item_hover",
                    "normalCssClass": "item"
                },
                {}, {}, this._items[i].DOMElem);

            $addHandlers(this._items[i].DOMElem,
                {
                    mousedown: this._onItemClick
                },
                this);
        }

        if (this._maxItemsToDisplay < this._items.length) {
            this._itemsBlock.style["height"] = "200px";
            this._itemsBlock.style["overflow"] = "auto";
            this._itemsBlock.style["overflowX"] = "hidden";
            this._itemsBlock.className = "sdd_items scroll";
        }
    },

    selectValue: function(newText, newValue) {
        this._selectValueInternal(newText, newValue);
        this._onChange();
        this.collapse();
    },

    collapse: function() {
        this.get_element().parentNode.style.zIndex = 99;
        this.get_itemsBlock().style.display = "none";
        for (var j = 0; j < this._items.length; j++) {
            this._items[j].DOMElem.className = "item";
        }
    },

    clearAutocomplete: function() {
        this._lastAutoSearchText = new String("");
    },

    _selectValueInternal: function(newText, newValue) {
        oldValue = this._valueContainer.value;
        this.get_element().value = newText;
        this._valueContainer.value = newValue;

        if ((oldValue != newValue) && (this.get_element()._events["change"])) {
            for (var i = 0; i < this.get_element()._events["change"].length; i++) {
                this.get_element()._events["change"][i].handler(newValue);
            }
        }
    },

    resetValue: function() {
        this.get_element().value = this._defaultText;
        this._valueContainer.value = "";
    },

    _onItemClick: function(e) {
        this.selectValue(e.target.dropDownItem.Text, e.target.dropDownItem.Value);
        //this.get_element().focus();
    },

    // here I'm trying to handle situation when user is typing letters inside dropdown in order to ease finding the item he is looking for
    _onKeyDown: function(e) {
        var charCode = (e.charCode) ? e.charCode : e.keyCode;

        if (charCode == 13) {
            if (this.get_itemsBlock().style.display != "none") {
                this.collapse();
                e.preventDefault();
            }

            return;
        }

        var charDecoded = String.fromCharCode(charCode).toLowerCase();
        this._lastAutoSearchText += charDecoded;

        for (var i = 0; i < this._items.length; i++) {
            if (this._items[i].Text.toLowerCase().startsWith(this._lastAutoSearchText)) {
                this._selectValueInternal(this._items[i].Text, this._items[i].Value);

                for (var j = 0; j < this._items.length; j++) {
                    this._items[j].DOMElem.className = "item";
                }

                this._items[i].DOMElem.className = "item_hover";

                break;
            }
        }
        if (this._lastAutoSearchTimer) {
            clearTimeout(this._lastAutoSearchTimer);
        }
        this._lastAutoSearchTimer = setTimeout("$get('" + this.get_element().id + "').control.clearAutocomplete();", 300);
    },

    _onBlur: function(e) {

        var elementBounds = Sys.UI.DomElement.getBounds(this.get_itemsBlock());

        var eventX = 0;
        var eventY = 0;

        if (!e) {
            e = window.event;
        }
        if (e.pageX || e.pageY) {
            eventX = e.pageX;
            eventY = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            eventX = e.clientX + document.body.scrollLeft
			      + document.documentElement.scrollLeft;
            eventY = e.clientY + document.body.scrollTop
			      + document.documentElement.scrollTop;
        }
        else {
            eventX = mouseX;
            eventY = mouseY;
        }

        var minX = elementBounds.x;
        var maxX = elementBounds.x + elementBounds.width;
        var minY = elementBounds.y;
        var maxY = elementBounds.y + elementBounds.height;

        if (minX <= eventX && eventX <= maxX &&
        minY <= eventY && eventY <= maxY) {
            this.get_element().focus();
            return;
        }


        this.get_element().parentNode.style.zIndex = 99;
        this.get_itemsBlock().style.display = "none";
    },

    _onChange: function() {
        var handler = this.get_events().getHandler('change');
        if (handler) handler(this, Sys.EventArgs.Empty);
    },

    _onClick: function() {
        if (this._disabled) {
            return;
        }

        if (!isIE) {
            window.captureEvents(Event.MOUSEMOVE);
        }
        window.onmousemove = mouseMoveHandler;


        if (this.get_itemsBlock().style.display == "none") {
            //When on page there are two StyledDropDown they block each other
            this.get_element().parentNode.style.zIndex = 106;
            this.get_itemsBlock().style.display = "";
            var inputBounds = Sys.UI.DomElement.getBounds(this.get_element());
            var inputLocation = Sys.UI.DomElement.getLocation(this.get_element());
            this._itemsBlock.style["width"] = inputBounds.width + "px";
            this._itemsBlock.style["top"] = inputBounds.height + "px";
            if ((Sys.Browser.agent == Sys.Browser.InternetExplorer) &&
                (Sys.Browser.version == 6)) // workarounâ for bug in IE6 with incorrect mouseover event handling
            {
                for (var i = 0; i < this._items.length; i++) {
                    this._items[i].DOMElem.style["width"] = (inputBounds.width - 10) + "px";
                }
            }

            this.get_element().focus();
        }
        else {
            this.get_itemsBlock().style.display = "none";
        }
    },

    get_itemsBlock: function() { return this._itemsBlock; },

    set_itemsBlock: function(value) { this._itemsBlock = value; },

    get_disabled: function() { return this._disabled; },

    set_disabled: function(value) { this._disabled = value; },

    get_defaultText: function() { return this._defaultText; },

    set_defaultText: function(value) { this._defaultText = value; },

    get_valueContainer: function() { return this._valueContainer; },

    set_valueContainer: function(value) { this._valueContainer = value; },

    get_imgTrigger: function() { return this._imgTrigger; },

    set_imgTrigger: function(value) { this._imgTrigger = value; },

    add_change: function(handler) { this.get_events().addHandler('change', handler) }
}

Kaos.UI.DropDown.registerClass('Kaos.UI.DropDown', Sys.UI.Control);

var mouseX = 0;
var mouseY = 0;

var isIE = navigator.userAgent.indexOf("MSIE") >= 0;

function mouseMoveHandler(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
}
