var DropdownMenu = Class.create({
	
	initialize : function(menu) {
		this.menu = $(menu);		
		this.doDomStuff();
		this.activeDropdown = null;
		this.hideAllDropdowns();
	},
	
	doDomStuff : function() {
		$$('#' + this.menu.id + ' .menuTitle').each(function(e) {
			e.observe('mouseover', this.categoryMouseOver.bindAsEventListener(this));
			e.observe('mouseout', this.categoryMouseOut.bindAsEventListener(this));
		}.bind(this));
		$$('#' + this.menu.id + ' .dropdown').each(function(e) {
			e.observe('mouseover', this.dropdownMouseOver.bindAsEventListener(this));
			e.observe('mouseout', this.dropdownMouseOut.bindAsEventListener(this));
		}.bind(this));
		if (this.menu.getStyle('position') != 'absolute') {
			this.menu.setStyle({
				position: 'relative'
			})
		}
	},
	
	hideAllDropdowns : function() {
		$$('#' + this.menu.id + ' .dropdown').each(function(e) {
			e.setStyle({display: 'none'});
		}.bind(this));
	},
	
	showDropdown : function(id) {
		var dropdown = this.activeDropdown.next('.dropdown'); 
		if (dropdown) {
			var title = this.activeDropdown;
			var position = title.positionedOffset();
			position.top += title.getHeight();
			position.left += removePx(title.getStyle('paddingLeft')) - removePx(dropdown.down('a').getStyle('paddingLeft'));
			dropdown.setStyle({
				display: 'block',
				left: position.left + 'px',
				top: position.top + 'px'
			});
		}
	},
	
	categoryMouseOver : function(event) {
		this.activeDropdown = event.element();
		this.stopHideTimeout();
		var id = event.element().getClassParam('title');
		this.hideAllDropdowns();
		this.showDropdown(id);		
	},
	
	categoryMouseOut : function(event) {
		this.setHideTimeout();		
	},
	
	dropdownMouseOver : function(event) {
		this.stopHideTimeout();		
	},
	
	dropdownMouseOut : function(event) {
		this.setHideTimeout();		
	},
	
	setHideTimeout : function() {
		this.timeout = setTimeout(this.hideAllDropdowns.bind(this), 20);
	},
	
	stopHideTimeout : function() {
		clearTimeout(this.timeout);
	}
});

Event.observe(document, 'dom:loaded', function() {
	window.dropdownMenu = new DropdownMenu('topMenu');	
});

