(function($){
    $(function(){
        // Adjust menus to be width of text and ensure submenus dont popup off screen
        function adjust_submenu(e, level) {        
            var widths, w, max, next, oc, on;
            
            oc = $("#nav .center").offset();            
            $(e).each(function(k, v){            
                $(v).closest(".nav").width(1000).css("display", "block");
                
                widths = $(v).children().map(function(){
                    $(this).css("position", "absolute");                    
                    w = $(this).width();
                    $(this).css("position", "");
                    return w;
                }).get();
                                
                max = Math.max.apply(this, widths);
                
                if (level == 1 && max < $(v).closest("li").outerWidth()) {
                    max = $(v).closest("li").outerWidth() - 14;
                }
                
                $(v).closest(".nav").width(max);
                
                next = $(v).find(".nav.level-" + (level + 1));                
                if (next.length > 0) {
                    adjust_submenu($(v).find(".nav.level-" + (level + 1) + " > ul"), level + 1);
                    
                    next.css("display", "block");
                    on = next.offset();
                    next.css("display", '');
                    
                    if (on.left + next.outerWidth() - oc.left > $("#nav .center").outerWidth()) {
                        next.css("left", -next.outerWidth());
                    }
                    else {
                        next.css("left", max);
                    }
                }
                
                $(v).closest(".nav").css("display", '');
            });    
        }
        adjust_submenu("#nav .nav.level-1 > ul", 1);    
    });
})(jQuery);
