(function($) {

$.fn.dropdownbox = function(options) {

    var dropdownbox = jQuery(this);
    var header = dropdownbox.find(".jix_dropdownbox_header");
    var info = header.find(".jix_dropdownbox_header_info");
    var options = dropdownbox.find(".jix_checklist");

    var origheight;

    // Explicitly setup width to allow overflow hiding to work
    var fix_dimensions = function () {
        var header_w = header.outerWidth();
        // var icon_w = header.find(".jix_dropdownbox_header_icon").outerWidth();
        var icon_w = 21; // The above sometimes does not include the img width
        var width = header_w - icon_w;
        width -= parseInt(info.css('paddingLeft'));
        width -= parseInt(info.css('paddingRight'));
        info.css({ width: (width) + 'px' });

        if (!origheight) {
            origheight = options.height();
        }
    };

    // Print selection in info area
    var update_info = function () {
        var labels = $(this).checklist("labels");

        if( labels.length == 0 ) {
            info.text( dropdownbox.nextAll(".jix_dropdownbox_none_selected").text() );
        } else if( labels.length == 1) {
            info.text( $(labels[0]).text() );
        } else {
            var many = dropdownbox.nextAll(".jix_dropdownbox_many_selected");
            info.text( many.text().replace('%', labels.length) );
        }
    };

    if (dropdownbox.filter(":visible").length) {
        fix_dimensions();
    }

    header.click(function () {
        var header = $(this);
        var dropdownbox = header.closest(".jix_dropdownbox");
        var w = header.innerWidth();
        var offset = header.position();
        options.css({ top:  offset.top + header.outerHeight() + 'px' });
        options.css({ left: offset.left-1 + 'px' });
        options.css({width: w + 'px'});
        options.toggle();

        fix_dimensions();

        var h = Math.max(20, Math.min(origheight, $(window).height()-(options.position().top-$(window).scrollTop())-5));
        options.css({height: h + 'px'});
    })
    .mouseenter(function () { $(this).addClass("hover") })
    .mouseleave(function () { $(this).removeClass("hover") })
    ;

    options.bind("newstate", update_info).trigger("newstate");

    var leave_timeout;
    dropdownbox.hover(
        function () { options.filter(":visible").stop(false, true).show(); clearTimeout(leave_timeout); },
        function () { leave_timeout = setTimeout(function () { options.fadeOut(500) }, 500) }
    );
}

})(jQuery);
