var Selectbox = {
    prepare: function(o) {     // make the custom html snippet into a selectbox
        // Add a <ul> for the selection
        o.appendChild(new Element('ul').addClassName('selection'));
         
        // Expand and fold on click
        o.observe('click', function(){Selectbox.toggle(o);});

        // Append 'option' classname to all option items, and make them clickable
        o.select('.options li').each(function(option) {
                if (!option.hasClassName('group')) {
                    option.addClassName('option');
                    option.observe('click', function(){Selectbox.select(o,option);});
                }
            });

        // Add 'hover' on mouse over (and remove on mouse out) to all <li> items
        o.select('ul, li').each(function(item) {
                item.observe('mouseover', function(){item.addClassName('hover')});
                item.observe('mouseout', function(){item.removeClassName('hover')});
            });

        // Keep the selection current
        Selectbox.updateSelection(o);
    },

    toggle:function(o) {     // Toggle selectbox expansion by adding or removing the 'expanded' class name
        if(o.hasClassName('expanded')) {
            o.removeClassName('expanded');
        } else {
            // Place options list
            var top = o.cumulativeOffset().top + o.getDimensions().height - 1;
            var left = o.cumulativeOffset().left;
            o.select('ul.options')[0].setStyle({top:top+'px', left:left+'px'});
            // show options
            o.addClassName('expanded');
        }
    },
        
    updateSelection: function(o) {    // Update the 'selection' list according to selected item on the options list
        var selectionElement = o.select('ul.selection')[0];
        // Remove all current children on the selection element
        selectionElement.childElements().each(Element.remove);
        // Look for a selected item
        var sel = o.select('.options li.selected');
        if(sel.length) {
            // There is at least one selected item
            var clone = $(sel[0].cloneNode(true));
            clone.classNames().each(function(className){clone.addClassName(className);});
            selectionElement.appendChild(clone);
        } else {
            // No selection
            var selectboxRel = o.getAttribute('rel');
            selectionElement.appendChild(new Element('li').update(selectboxRel.length ? selectboxRel : '&nbsp;'));
        }
    },
        
    select: function(o,i) {    //select a given item...
        // Deselect other items
        o.select('li.option').each(function(option){option.removeClassName('selected');});
        i.addClassName('selected');
        Selectbox.updateSelection(o);
    }
}

// Loop through all elements with 'selectbox' class on init and prepare it for our purposes.
document.observe('dom:loaded', function(){$$('.selectbox').each(Selectbox.prepare)});
