/* menu-collapse.js */

// Makes the gallery menu collapsible with a nice effect
$(document).ready(function(){
    // Add an <a> tag to all list items without one
    $('div#menu > ul.gallery').find('li:not(:has(>a))').each(function(i){
        var sub_ul = $(this).children('ul').remove();
        $(this).wrapInner('<a></a>');
        $(this).append(sub_ul);
    });
    // Turn on collapse behavior for all li items with a child ul
    var parent_lis = $('div#menu ul.gallery').find('li > ul > li > ul').parent();
    parent_lis.children('ul').toggle();
    parent_lis.children('a').click(function(event){           // on click,
        if ($(this).attr('href')) {                           // if real link,
            window.location.href = $(this).attr('href');      // go to url
        }
        else {                                                // otherwise,
            $(this).parent().children('ul').toggle('fast');   // show/hide child
        }
        return false;
    });

    // Ensure parents of active link are expanded
    $('li a.active').parents('ul').show()
    // Show descendant ul of active link
    $('li a.active').parent().find('ul').show()
    // Turn off click behavior for parent li a
    $('li a.active').parents('ul').parents('li').children('a').unbind('click');

    // Images on the homepage expand the menu
    if (location.pathname == '/'){
        $('img').click(function(){
            parent_lis.children('ul').show('medium');
        });
    }
});
