// menu.js
// -------

$(document).ready(function() {
    
    $('#menu ul').hide()
        .prev().click(function(e) {
            var subs = $(this).parent().find('ul');
            
            if (subs.size() > 0 && subs.get(0)) {
                $('#menu ul:visible').slideUp(300).parent().removeClass('closed');
                
                var subMenu = subs.get(0);
                $(subMenu).slideDown(500).parent().addClass('selected opened');
                
                e.stopPropagation();
                e.preventDefault();
                return false;
            }
        })
        .parent().addClass('closed');
        
    // set the selected menu item
    var url = window.location.href;
    var re = /^.+\/([\w-_]+\.aspx.*)$/;
    
    var matches = url.match(re);
    if (matches && matches.length === 2) {
        var matchUrl;
        if (url.match(/\/image-(details|download)\.aspx/)) {
            matchUrl = "image-library.aspx";
        } else {
            matchUrl = matches[1];
        }
        
        var selector = '#menu a[@href$=' + matchUrl + ']';
        
        // only one link should match our selector:
        // set its parent <li> tag's class to 'selected' then
        // walk back up the DOM to set the parent's parent <li>
        // tag's class to selected too
        $(selector).parent().addClass('selected')
            .parent().show().parent().removeClass('closed')
            .addClass('selected opened');
    }
    
});
