
// initialize portal when the page is loaded
new Script.Action(function() {
    
    // find the page content container
    var pageContent = document.getElementById("page_content");
    
    // scroll to the top whenever page content arrives
    var scroll = function(loader) {
        var top = Geometry.getTop(pageContent);
        var vh = Geometry.getViewportHeight();
        var yoff = Geometry.getViewportYOffset();
        if (top < yoff) {
            // top of content is above the top of the viewport
            if (vh !== undefined && top < vh / 2) {
                // close enough to the top to scroll all the way there
                top = 0;
            }
            window.scrollTo(0, top);
        }
    };
    var scroller = new Object();
    scroller.loadedContent = scroll;
    scroller.unloadedContent = scroll;
    pageContent.contentLoader.addContentListener(scroller);

}).run();

Script.include("/js/css/selectors.js");
Script.include("/js/portal/menu_animation.js");
Script.include("/js/portal/menus.js");

// initialize menus
new Script.Action(function() {
    
    var $ = com.civicscience.css.selectors.$;
    var MenuBar = com.civicscience.portal.menus.MenuBar;
    var MenuBarAnimation = com.civicscience.portal.menus.MenuBarAnimation;
    
    var pageContent = $("#page_content");
    var pageLoader = pageContent.contentLoader;
    var pageUrl = pageLoader.getContentURL();
    
    var container = $(".nav_shell .menu_bar");
    if (container != null) {
        // create portal menu bar
        var menuBar = new MenuBar(container);
        menuBar.addContentChangeListener(function(url) {
            pageLoader.loadURL(url);
        });
        // update menu state in response to changing content URL
        pageLoader.addContentListener({
            loadedContent: function() {
                menuBar.setMenuPathForUrl(pageLoader.getContentURL());
            },
            unloadedContent: function() { }
        });
        if (pageUrl != null) {
            menuBar.setMenuPathForUrl(pageUrl);
        }
        new MenuBarAnimation(menuBar);
    }
    
}).requires(
        "com.civicscience.css.selectors.$",
        "com.civicscience.portal.menus.MenuBar",
        "com.civicscience.portal.menus.MenuBarAnimation"
    ).run();
