var Navigation = new Class({
    
    initialize: function(id){
        this.container = $(id);
        this.sections = this.container.getElements('div#navigation div.wrapper > div');
        this.subsections = this.container.getElements('div#sub-navigation div.wrapper > div');
        this.timer = 0;
        
        this.selected = {
            section: this.sections.filter(function(el){ return el.hasClass('in'); })[0],
            subsection: this.subsections.filter(function(el){ return el.hasClass('visible'); })[0]
        };
        
        this.container.addEvents({
            'mouseleave': (function(){
                this.timer = this.reset.delay(2000, this);
            }).bind(this),
            'mouseenter': (function(){
                $clear(this.timer);
            }).bind(this)
        });
        
        this.sections.addEvent('mouseenter', (function(e){
            $clear(this.timer);
            return this.select(e);
        }).bind(this));
    },
    
    off: function(){
        $each({ section: 'in', subsection: 'visible'}, function(style, area){
            this[area + 's'].each(function(el){
                el.removeClass(style);
            }, this);
        }, this);
    },
    
    reset: function(){
        return this.select({ target: this.selected.section });
    },
    
    select: function(e){
        if (!e.target.id) return false;
        this.off();
        var section = e.target.addClass('in');
        var subsection = $(section.id.replace('section', 'pages'));
        if (subsection) subsection.addClass('visible');
    }
    
});

window.addEvent('domready', function(){
    new Navigation('nav'); 
});