$(document).ready(function () {
    $("#smartmenu>ul.menu").on("loaded", function() {

        var $mainMenu = $(this);

        /* add classes used by smartmenus */
        $mainMenu.addClass("sm sm-mint");

        /* remove Flare's "menu" class from menu proxy */
        $mainMenu.removeClass("menu");

        // smartmenus - neglect URL params when detecting the current item
        var urlParams = location.search.replace(/^\?/, '');
        if (urlParams) {

            // 1) temporary alter menu items' links so that any URL parameters are neglected when detecting the current item
            // get just the links that do not have any params in their href
            $mainMenu.find('a[href]:not([href*="?"])').each(function() {
                var $this = $(this),
                    href = $this.attr('href');
                $this.data('original-href', href).attr('href', href + '?' + urlParams);
            });

            // 2) after init restore original menu items' links
            $.SmartMenus.prototype.old_init = $.SmartMenus.prototype.init;
            $.SmartMenus.prototype.init = function(refresh) {
                this.old_init(refresh);

                // restore original links
                $mainMenu.find('a[href*="?"]').each(function() {
                    var $this = $(this),
                        originalHref = $this.data('original-href');
                    if (originalHref) {
                        $this.attr('href', originalHref);
                    }
                });
            };
        }

        /* initialise smartmenus */
        $mainMenu.smartmenus({
            markCurrentItem: true,
            markCurrentTree: true,
            keepHighlighted: true,
            keepInViewport: true,
            noMouseOver: true,
            hideOnClick: false,
            collapsibleShowFunction: null
        });

        $mainMenu.smartmenus("itemActivate", $mainMenu.find("a.current").eq(-1));

        // smartmenus - don't show the sub menus in collapsible mode unless the sub arrow is clicked
        $mainMenu.on('click', 'span.sub-arrow', function(e) {
                var obj = $mainMenu.data('smartmenus');
                if (obj.isCollapsible()) {
                    var $item = $(this).parent(),
                        $sub = $item.closest('li').dataSM('sub');
                    $sub.dataSM('arrowClicked', true);
                }
            }).bind({
                'beforeshow.smapi': function(e, menu) {
                    var obj = $mainMenu.data('smartmenus');
                    if (obj.isCollapsible()) {
                        var $menu = $(menu);
                        if (!$menu.dataSM('arrowClicked')) {
                            return false;
                        }
                        $menu.removeDataSM('arrowClicked');
                    }
                }
            });

    });
});