if ( typeof Fractal === 'undefined' ) throw "Fractal core.js not loaded";

Fractal.MainNav = (function($){

    var MainNav = function( el ){
        this.el = el;
        this.sectionItems = this.el.find('.MainNav-item--section');
        this.sectionToggles = this.el.find('.MainNav-sectionToggle');
        this.subSectionToggles = this.el.find('.MainNav-subSectionToggle');
        this.subSectionLinks = this.el.find('.MainNav-sectionNav .MainNav-link');
        this.subSectionItems = this.el.find('.MainNav-sectionNav .MainNav-item');
    };

    MainNav.prototype = {

        init: function(){
            var self = this;
            this.subSectionToggles.on('click', function(){
                $(this).parent('li').toggleClass('is-open');
                return false;
            });
            this.sectionToggles.on('click', function(){
                self.sectionItems.removeClass('is-open').removeClass('is-current');
                $(this).parent('li').addClass('is-open').addClass('is-current');
            });
            Fractal.events.on('main-content-preload', function(e, url){
                var parser = document.createElement('a');
                parser.href = url;
                self.subSectionItems.removeClass('is-current');
                var pathParts = parser.pathname.split('/');
                pathParts.push(pathParts.pop().split('--')[0])
                self.subSectionLinks.filter('[href="' + pathParts.join('/') + '"]').parent('li').addClass('is-current');
            });
        }

    };

    return MainNav;

})(jQuery, window);
