$(function () {
    var args = window['uoa_expandable_args'] ? window['uoa_expandable_args'] : {};
    args = $.extend({
        selector:  '.expandable',
        spacer:    '/global/js/expandable/spacer.gif',
        expanded:  '/global/js/expandable/expanded.gif',
        collapsed: '/global/js/expandable/collapsed.gif'
    }, args);

    $(args['selector'] +  '  ul').css('list-style-type', 'none');
    $(args['selector'] +  '  ul').css('display', 'none');
    $(args['selector'] + ' > ul').css('display', 'block');

    var $spacer = $('<img>').attr({
        src: args['spacer'],
        alt: ' '
    });

    var $expanded = $('<img>').attr({
        src: args['expanded'],
        alt: 'click to collapse',
        title: 'click to collapse',
        'class': 'expandable-expanded'
    });

    var $collapsed = $('<img>').attr({
        src: args['collapsed'],
        alt: 'click to expand',
        title: 'click to expand',
        'class': 'expandable-collapsed'
    });

    // Find the expanded uls and prefix them with the collapsed icon
    // The collapsed icon will replace itself with the expanded one on demand.
    $(args['selector'] + ' ul:visible li:has(ul)').prepend($collapsed.clone(true));

    // Use the spacer icon to ensure that those list items that don't expand
    // still line up
    $(args['selector'] + ' ul:visible li:not(:has(ul))').prepend($spacer.clone(true));

    $('.expandable-expanded').live('click', function() {
        $(this).siblings('ul').css('display', 'none');
        $(this).replaceWith($collapsed.clone());
    });

    $('.expandable-collapsed').live('click', function() {
        $(this).siblings('ul').css('display', 'block');
        $(this).replaceWith($expanded.clone());
    });
});
