﻿(function ($) {
    jQuery.fn.sbr_submenu = function (o) {
        var options = {
            width: $(this).width(),
            moreText: '&nbsp;'
        };

        if (this.length > 0)
            $(document).ready(function () { $(document.body).addClass('has-submenu'); });

        $.extend(options, o);
        return this.each(function () {
            var lis = $('li', this);
            var width = 0;
            var to = 0;

            // Grab width and make sure we need to add a more button
            var originalWidth = 0;
            $(lis[0]).addClass('first');
            lis.each(function () { originalWidth += $(this).outerWidth(); });
            if (originalWidth < options.width) return;

            var newLi = $('<li />', { 'class': 'nav-more-dd' }).html(options.moreText);
            var moreHolder = $('<ul />').css({ display: 'none' });
            $(this).prepend(newLi.append(moreHolder).append($('<div />')));

            newLi
                .mouseover(function () { clearTimeout(to); moreHolder.slideDown(200); })
                .mouseout(function () { to = setTimeout(function () { moreHolder.slideUp(50); }, 10); });

            var newWidth = options.width - newLi.outerWidth();
            var list = $('li.nav-list-secondary-item', this);

            list.each(function (i) {
                var w = width + $(this).outerWidth() + 10;
                if (w > newWidth)
                    moreHolder.append($(this).addClass('nav-more-dd-item'));
                else
                    width += $(this).outerWidth();
            });
            $('li.nav-more-dd-item:last').addClass('last');
        });
    };
})(jQuery);
