function tree_toggle_button(state, count) {
    var button, image;
    button = [
        '<b>',
        '</b>'
    ]
    image = [
        '<img src="/media/default/images/',
        '_arrow_sm.gif"',
        ' />'
    ]
    if (state === 'collapsed') {
        button.splice(1, 0, 'Show all ' + count);
        image.splice(1, 0, 'down');
    } else {
        if (state === 'expanded') {
            button.splice(1, 0, 'Hide');
            image.splice(1, 0, 'up');
        }
    }
    button.splice(1, 0, image.join(''));
    return button.join('');
}

$(document).ready(function () {
    $('.collapsible_tree').each(function (i) {
        var target = $(this)
            show = 2;
        /*

        FIXME: For the 3rd level of categories. Conditionally include this so
        that it doesn't interfere when you only want a depth of 2.

        $('li:has(ul)', target).each(function (i) {
            var tree = $(this);
            $('li:has(ul)', tree).each(function (i) {
                var sub = $(this);
                sub.parent().parent().addClass('collapsible').addClass('collapsed');
                $('li:gt(' + show + ')', sub).hide();
            });
        });
        */

        target.children().filter(':not(.collapsible)').each(function () {
            var tree = $(this);
            tree.addClass('collapsible').addClass('collapsed');
            $('li:gt(' + show + ')', tree).hide();
        });

        $('.collapsible ul li:has(ul)', target).addClass('collapsible').addClass('collapsed');

        $('.collapsed').each(function () {
            var tree = $(this);
                count = tree.children('ul:first').children('li').length;
                hidden = tree.children('ul:first').children('li:visible').length;
            if (count !== hidden)
                tree.append('<div class="toggle">' + tree_toggle_button('collapsed', count) + '</div>');
        });

        $('.collapsible .toggle').click(function () {
            var button = $(this);
                collapsible = button.parent('.collapsible');
            if (collapsible.hasClass('collapsed')) {
                collapsible.removeClass('collapsed').addClass('expanded');
                button.siblings('ul').children('li:hidden').show();
                button.html(tree_toggle_button('expanded'));
            } else {
                if (collapsible.hasClass('expanded')) {
                    var count = button.siblings('ul').children().length;
                    collapsible.removeClass('expanded').addClass('collapsed');

                    button.siblings('ul').children('li:gt(' + show + ')').hide();
                    button.html(tree_toggle_button('collapsed', count));
                }
            }
        });

        $('.collapsible .toggle b').noselect();
    })
});