var DropdownMenu = new Class({
    Implements:[Options, Events],
    
    options:
    {
        hideTimeoutLink:150,
        hideTimeoutMenu:500
    },
    
    menu:null, 
    dropdown:null,
    highlight:null,
    content:null,
    timeout:-1,
    
    initialize:function(element, dropdown, options)
    {
        var self = this;
        
        this.menu = $(element);
        if(!$chk(this.menu)){ return; }
        
        this.dropdown = $(dropdown);
        if(!$chk(this.dropdown)){ return; }
        
        this.highlight = this.dropdown.getElement(".highlight");
        if(!$chk(this.highlight)){ return; }
        
        this.content = this.dropdown.getElement(".content");
        if(!$chk(this.content)){ return; }
        
        if(options != undefined && options != null)
            this.setOptions(options);
        
        this.menu.getElements("ul.dropdown").each(function(dropdown){
            var link = dropdown.getPrevious("a");
            self.register_dropdown(link, dropdown);
        });
    },
    
    register_dropdown:function(link, dropdown)
    {
        var self = this;
        
        link.addEvent("mouseenter", function(e)
        {
            self.dropdown_timeout_clear();
            self.dropdown_show(link, dropdown);
        });
    },
    
    dropdown_show:function(link, dropdown)
    {
        var self = this; 
        
        var clone = dropdown.clone();
        clone.removeClass("dropdown");
        
        this.content.empty();
        this.content.grab(clone);
        
        var position = link.getCoordinates(this.menu);
        this.dropdown.setStyle("left", position.left);
        this.highlight.setStyle("left", position.width / 2 - 8);
        
        link.removeEvents("mouseleave");
        
        var closure_timeout = function(interval)
        {
            return setTimeout(function(){ self.dropdown_hide(link, dropdown); }, interval);
        };
        
        link.addEvent("mouseleave", function(e)
        {
            self.timeout = closure_timeout(self.options.hideTimeoutLink);
        });
        
        this.dropdown.removeEvents("mouseenter");
        this.dropdown.addEvent("mouseenter", function()
        {
            self.dropdown_timeout_clear();
            
            self.dropdown.removeEvents("mouseleave");
            self.dropdown.addEvent("mouseleave", function()
            {
                self.timeout = closure_timeout(self.options.hideTimeoutMenu);
            });
            
        });
        
        this.dropdown.removeClass("hidden");
    },
    
    dropdown_timeout_clear:function()
    {
        if(this.timeout >= 0)
        {
            clearTimeout(this.timeout);
            this.timeout = -1;
        }  
    },
    
    dropdown_hide:function(link, dropdown)
    {
        this.dropdown.addClass("hidden");
    }
});

