
var SubMenu = new Class({
	element: null,
	button: null,
	focused: false,
	mousein: false,
	height: 0,
	
	initialize: function(el) {
		this.element = el;
		this.button = el.getPrevious();
		this.height = el.getSize().y;
		
		this.effectOut = new Fx.Tween(this.element, {
			property: 'height',
			transition: Fx.Transitions.Bounce.easeOut,
			link: 'ignore'
		});
		this.effectIn = new Fx.Tween(this.element, {
			property: 'height',
			transition: Fx.Transitions.Circ,
			link: 'ignore'
		});
		
		this.button
			.addEvent('mouseenter', this.onEnter.bind(this))
			.addEvent('mouseleave', this.onLeave.bind(this))
			.addEvent('focus', this.onFocus.bind(this))
			.addEvent('blur', this.onBlur.bind(this));
		
		this.element.getElements('a').each(function(el) {
			el
				.addEvent('focus', this.onFocus.bind(this))
				.addEvent('blur', this.onBlur.bind(this));
		}.bind(this));
		
		this.element
			.addEvent('mouseenter', this.onEnter.bind(this))
			.addEvent('mouseleave', this.onLeave.bind(this));
		
		this.hide();
	},
	
	onFocus: function() {
		this.scrollOut();
		this.focused = true;
	},
	
	onBlur: function() {
		if(!this.mousein) {
			this.scrollIn();
		}
		this.focused = false;
	},
	
	onEnter: function() {
		this.scrollOut();
		this.mousein = true;
	},
	
	onLeave: function() {
		if(!this.focused) {
			this.scrollIn();
		}
		this.mousein = false;
	},
	
	hide: function() {
		this.element
			.setStyle('height', 0)
			.setStyle('visibility', 'hidden');
		this.button.removeClass('active');
	},
	
	display: function() {
		this.element.setStyle('visibility', 'visible');
		this.button.addClass('active');
	},
	
	scrollIn: function() {
		this.effectIn.start(0).chain(this.hide.bind(this));
		this.effectOut.cancel();
	},
	
	scrollOut: function() {
		this.effectIn.cancel();
		this.display();
		this.effectOut.start(this.height);
	}
});


window.addEvent('domready', function() {
	$$('.menu ul').each(function(el) {
		new SubMenu(el);
	});
});


