// Getting rid of all the nav submenus that are open.
function closeNavMenus(navTabs) {
    navTabs.removeClass('open');
    navTabs.find('.section-name').removeClass('open highlighted');
    navTabs.find('ul.submenu').hide();
}


jQuery(document).ready(function() {

    var navMenuParentCats = jQuery('#navmenu li.parent');
    var navMenuFirstSubcats = navMenuParentCats.find('ul.submenu a:first-child');
    
    
    // Selectively highlight nav links on hover in the header
    // (Could be done with CSS, but at the cost of lots of DOM clutter.)
    navMenuFirstSubcats.mouseenter(function(evt) {
        jQuery(this).closest('.parent').find('a.section-name,span.section-name').addClass('highlighted');
    });
    navMenuFirstSubcats.mouseleave(function(evt) {
        jQuery(this).closest('.parent').find('a.section-name,span.section-name').removeClass('highlighted');
    });
    
    
    // Allow touch interaction with the nav links that have submenus. Desktop browsers just
    // use :hover for this interaction, but in touch interfaces that works quite unreliably.
    navMenuParentCats.bind('touchstart', function(evt) {
        closeNavMenus(navMenuParentCats);
        var navMenu = jQuery(this);
        navMenu.addClass('open');
        navMenu.find('a.section-name,span.section-name').addClass('open');
        navMenu.find('ul.submenu').css('display', 'block').show();
    });
    
    // Highlight the section title appropriately
    navMenuParentCats.find('a').bind('touchstart', function(evt) {
        var activeLink = jQuery(this);
        var sectionName = activeLink.closest('.parent').find('a.section-name,span.section-name');
        if (activeLink.is(':eq(0)')) {
            sectionName.addClass('highlighted');
        }
        else {
            sectionName.removeClass('highlighted');
        }
    });
    
    // Hide popup elements whenever there's a touch outside of them
    jQuery('body').bind('touchstart', function(evt) {
        var target = jQuery(evt.target);
        // Make sure the touch didn't happen on a nav menu parent
        if (target.closest('#navmenu li.parent').length == 0) {
            closeNavMenus(navMenuParentCats);
        }
    });
    
});
