// Copyright (c) 2006 - 2008 Gabriel Lanzani (http://www.glanzani.com.ar)
// Modified for KoldCast by Chau Tran (http://www.transvalence.com)
Autocompleter.SelectBox = Class.create();
Autocompleter.SelectBox.prototype = Object.extend(new Autocompleter.Base(), {
    initialize: function(select, options) {
        this.element = "<input type=\"text\" id=\"" + $(select).id + "_combo\" />"
        if (!$(select + "_combo"))
        new Insertion.Before(select, this.element)
        var inputClasses = Element.classNames(select);

        this.update = "<div id=\"" + $(select).id + "_options\" class=\"" + inputClasses + "\"></div>"
        if (!$(select + "_options"))
        new Insertion.Before(select, this.update)

        this.baseInitialize($(select).id + "_combo", $(select).id + "_options", options);
        this.select = select;
        this.selectOptions = [];

        $(this.element.id).setAttribute('readonly', 'readonly');
        this.element.readOnly = true;
        this.element.selectable = false;

        Element.hide(select);
        Element.addClassName(this.element.id, this.options.css);

        var optionList = $(this.select).getElementsByTagName('option');
        var nodes = $A(optionList);
        for (i = 0; i < nodes.length; i++) {
            if (!nodes[i].getAttribute("selected"))
                this.selectOptions.push("<li id=\"" + nodes[i].value + "\">" + nodes[i].innerHTML + '</li>');
            if (nodes[i].getAttribute("selected"))
                this.element.value = (nodes[i].innerHTML.length > 33) ? nodes[i].innerHTML.substring(0, 30) + '...': nodes[i].innerHTML;
        }

        Event.observe(this.element, "click", this.activate.bindAsEventListener(this));

        var self = this;

        this.options.afterUpdateElement = function(text, li) {
            var optionList = $(select).getElementsByTagName('option');
            var nodes = $A(optionList);

            var opt = nodes.find(function(node) {
                return (node.value == li.id);
            });
            $(select).selectedIndex = opt.index;

            // .setStyle({'color':'#000'});
            // if (li.up(1).previous(0).value.length > 33)
            // li.up(1).previous(0).value = li.innerHTML.substring(0, 30) + '...';
        }

    },

    getUpdatedChoices: function() {
        this.updateChoices(this.setValues());
    },

    setValues: function() {
        return ("<ul>" + this.selectOptions.join('') + "</ul>");
    },

    setOptions: function(options) {
        this.options = Object.extend({
            //MORE OPTIONS TO EXTEND THIS CLASS
            submit: false,
            //form Id to submit after change
            redirect: false,
            // redirects to option value
            debug: false,
            //show alerts with information
            css: 'combo'
            //css class for new element
        },
        options || {});
    }
})
