/*
    Behaviours for the "Refine List" text input found in the Browse Pages
*/

Site.Widgets.RefineInput = Class.create
(
    Site.Base,
    {
        initialize: function($super, input, list, options)
        {
            $super();
            
            
            this.setOptions
            (
                options,
                {
                    updateDelay: 0.4, //how long to wait after a key is pressed before the list is updated (seconds)
                    listFirstClassName: "first",
                    listLastClassName: "last",
                    neverShowClassName: "hidden"
                }
            );
            
            this.addBlocks("updateList");
            
            this.input = input;
            this.reconnect(list);


            this.addObservers("inputOnKeyUp");
            
            // the event we use is keyup, since it seems that IE/Win doesn't fire "keypress" when Delete is pressed (?)
            addEvent(this.input, "keyup", this.observers.inputOnKeyUp);
        },
        
        /* 
            when the list changes, we need a way to tell the widget what the "full list" is again. Thus, call this method when the list changes.
        */

        inputOnKeyUp: function(event)
        {
            if (this.timeout)
                window.clearTimeout(this.timeout);
                
            window.setTimeout(this.blocks.updateList, this.options.updateDelay * 1000);
        },
        
        reconnect: function(list, clear)
        {
            this.list = list;
            
            if (clear)
                this.setValue("");
            else
                this.updateList();
        },
        
        updateList: function()
        {
            this.list.select("li").each
            (
                function(li)
                {
                    if (this.input.value.strip() == "" || li.innerHTML.stripTags().unescapeHTML().toLowerCase().include(this.input.value.toLowerCase()))
                    {   
                        if (!(this.options.neverShowClassName && li.hasClassName(this.options.neverShowClassName)))
                        {        
                            li.show();
                        }
                    }
                    else
                    {
                        li.hide();
                    }
                },
                this
            );
        },
        
        clear: function(updateList)
        {
            this.setValue("");
        },
         
        setValue: function(value)
        {
            this.input.value = value;
            this.updateList();
        },
        
        destroy: function()
        {
            removeEvent(this.input, "keyup", this.observers.inputOnKeyUp);
        }
    },
    {
        
    }
);