(function() {
    function syncNav(page) {
        var navSpans = document.querySelectorAll('.site-navigation > span');
        for (var i = 0; i < navSpans.length; i++) {
            var r = navSpans[i].getAttribute('data-route');
            navSpans[i].classList.toggle('active', r === page);
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        var origNavigate = Router.navigate.bind(Router);
        Router.navigate = function(page, data) {
            origNavigate(page, data);
            setTimeout(function() { syncNav(page); }, 50);
        };

        var hash = window.location.hash.replace('#','').replace('/','') || 'home';
        syncNav(hash);

        /* Footer span routing */
        var footerSpans = document.querySelectorAll('#footer > span[data-route]');
        for (var i = 0; i < footerSpans.length; i++) {
            footerSpans[i].addEventListener('click', function() {
                Router.navigate(this.getAttribute('data-route'));
            });
        }

        /* Header nav span routing */
        var navSpans = document.querySelectorAll('.site-navigation > span[data-route]');
        for (var i = 0; i < navSpans.length; i++) {
            navSpans[i].addEventListener('click', function() {
                Router.navigate(this.getAttribute('data-route'));
            });
        }

        /* User interaction routing */
        var uiSpans = document.querySelectorAll('.user-interactions > span[data-route]');
        for (var i = 0; i < uiSpans.length; i++) {
            uiSpans[i].addEventListener('click', function() {
                Router.navigate(this.getAttribute('data-route'));
            });
        }
    });
})();

(function() {
    var cartBtn = document.querySelector('[data-action="open-cart"]');
    if (cartBtn) cartBtn.addEventListener('click', function() { Cart.openDrawer(); });
})();
