$(function(){
    var dropdown = $('.dropdown'),
        input = dropdown.find('input')
    input.focus(function(){
        $(this).parents('.dropdown').trigger('showOptions')
    }).blur(function(){
        $(this).parents('.dropdown').delay(100).trigger('hideOptions')
    }).click(function(){
        $(this).focus();
        return false;
    }).after('<span class="arrow">&nbsp;</span>')
    var arrow = dropdown.find('.arrow')
    arrow.click(function(){
        $(this).parents('.dropdown').trigger('toggleOptions')
        return false;
    })
    dropdown.bind('toggleOptions', function(){
        var self = $(this),
            options = self.data('options')
        if (options.is(':visible')) {
            self.trigger('hideOptions')
        } else {
            self.trigger('showOptions')
        }
    }).bind('hideOptions', function (){
        var options = $(this).data('options')
        if (options.is(':visible')) {
            options.slideUp('fast')
        }
        //console.log('hide', options)
    }).bind('showOptions', function(){
        $('.dropdowns').trigger('hideOptions')
        var self = $(this),
            options = self.data('options'),
            offset = self.offset()
            //console.log('show', offset, options)
        options.css({ left: offset.left + 'px', top: offset.top + self.height() - 1 + 'px', width: self.width() - 2 + 'px' }).show()//slideDown('fast')
    }).each(function(index, node){
        var self = $(node),
            options = self.find('.dropdown-options')
        $('body', document).append(options.remove())
        options.data('dropdown', self)
        self.data('options', options)
        self.find('.arrow').css('left', self.width() - 19 + 'px')
    })
    var optionsItems = $('.dropdown-options li')
    optionsItems.click(function(){
        var self = $(this),
            dropdown = self.parents('.dropdown-options').data('dropdown'),
            value = self.attr('option'),
            input = dropdown.find('input')
            input.val(value).change()
            dropdown.trigger('hideOptions')
        return false;
    }).hover(function(){
        $(this).addClass('hilighted')
    }, function(){
        $(this).removeClass('hilighted')
    })

    $(document).click(function(){
        $('.dropdown').trigger('hideOptions')
    })
})

