window.addEvent('domready', function() {
	new MenuMouseOver();
});

MenuMouseOver = new Class({
	sliderElement: null,
	animator: null,
	closeTimer: null,
	currentMenu: null,
	
	initialize: function() {
		var menuItems = $$('div.menu a.l1');
		this.sliderElement = new Element('div', { 'id': 'menu-l1-slider' }).setStyle('width', '0px').inject($(document.body), 'top');
		this.sliderElement.set('morph', { 'duration': 200 });
		menuItems.addEvent('mouseover', this.onMouseOver.bindWithEvent(this));
		menuItems.addEvent('mouseout', this.onMouseOut.bindWithEvent(this));
	},
	
	onMouseOver: function(event) {
		if (this.closeTimer) {
			clearTimeout(this.closeTimer);
		}
		
		var targetMenu = $(event.target);
		if (targetMenu.get('tag') != 'a') {
			targetMenu = targetMenu.getParent('a.l1');
		}
		
		if (targetMenu == this.currentMenu) {
			return;
		}
		
		if (!this.isSliderElementVisible()) {
			this.showSliderElementAt(targetMenu);
		}
		
		this.currentMenu = targetMenu;
		this.sliderElement.morph({
			'left': targetMenu.getPosition().x + 'px',
			'width': targetMenu.getSize().x + 'px'
		});
	},
	
	onMouseOut: function(event) {
		this.closeTimer = setTimeout(this.closeSlider.bind(this), 50);
	},
	
	closeSlider: function() {
		this.currentMenu = null;
		this.sliderElement.morph({'width': 0});
	},
	
	isSliderElementVisible: function() {
		return (this.sliderElement.getSize().x > 0);
	},
	
	showSliderElementAt: function(target) {
		this.sliderElement.setStyles({
			'width': 0,
			'height': '61px',
			'left': target.getPosition().x,
			'top': target.getPosition().y
		});
	}
});
