(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;



            $("#container > .nav .nav").css("right", "auto");

            oc = $("#container > .nav").offset();
            $(e).each(function(k, v){
                $(v).closest(".nav").width(1000).css("display", "block");

                widths = $(v).children().map(function(){
                    $(this).css("position", "absolute");
                    $(this).css("width", "auto");
                    w = $(this).width();
                    $(this).css("position", "");
                    return w;
                }).get();

                max = Math.max.apply(this, widths);
                max += 1;

                if (level == 1 && max < $(v).closest("li").outerWidth()) {
                    max = $(v).closest("li").outerWidth() - 10;
                }

                $(v).closest(".nav").width(max);

                on = $(v).closest(".nav").offset();
                if (on.left + max - oc.left > $("#container > .nav").outerWidth()) {
                    $(v).closest(".nav").css("left", $("#container > .nav").outerWidth() - (on.left + max - oc.left) - 1);
                }

                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 > $("#container > .nav").outerWidth()) {
                        next.css("left", -next.outerWidth());
                    }
                    else {
                        next.css("left", max);
                    }
                }

                $(v).closest(".nav").css("display", '');
            });
        }
        adjust_submenu("#container> .nav .nav.level-1 > ul", 1);
    });
})(jQuery);
