/*
	DropIT

	Copyright (c) 2010 t_ouwejan

	Dependencies: MooTools core
	Inspiration: UvumiTools Dropdown Menu (thx guys!)
*/

var DropIt = new Class({
	Implements:Options,
	menu: null,
	paddingTop: 20,
	options:{
		dropItTransition:Fx.Transitions.Expo.easeOut,
		dropItSpeed: 600,
		dropDeadTransition:Fx.Transitions.Expo.easeOut,
		dropDeadSpeed: 500
	},
	
	initialize: function(menu,options){
		this.menu = menu;
		this.setOptions(options);
		
		if(Browser.Engine.webkit){
			window.addEvent('domready',this.create.delay(200,this));
		}else{
			window.addEvent('domready',this.create.bind(this));
		}
	},
	
	create: function() {
		this.menu = $(this.menu);
		
		var menuItems = this.menu.getElements('div');
		menuItems.each(function(item){
			
			item.getParent().setStyle('width', item.getFirst().getCoordinates().width);
			
			item.store('menuHeight',item.getChildren('ul')[0].getCoordinates().height);
			item.store('menuHeadingHeight',item.getCoordinates().height);
			item.store('menuTop', item.getCoordinates().top);
			
			var targetTop = item.retrieve('menuTop')-item.retrieve('menuHeight')
			if (targetTop <=this.paddingTop) targetTop = this.paddingTop;
			
			item.store('targetTop', targetTop);
			item.store('dropItAnim',  new Fx.Morph(item, {duration: this.options.dropItSpeed, transition: Fx.Transitions.Back.easeOut}));
			item.store('dropDeadAnim',  new Fx.Morph(item, {duration: this.options.dropDeadSpeed, transition: Fx.Transitions.Sine.easeOut}));
			
			// fix first animation delay in webkit based browsers
			// to make sure that the anim is started correctly
			var dropIt = this.dropIt.bind(item);
			var dropDead = this.dropDead.bind(item);
			dropIt();
			dropDead();
			
			item.addEvent('mouseenter',dropIt);
			item.addEvent('mouseleave',this.dropDead);
		}.bind(this));
	},
	
	dropIt:function() {
		this.retrieve('dropDeadAnim').cancel();
		this.setStyle('z-index', 1100);
		
		this.retrieve('dropItAnim').start({
			'top': this.retrieve('targetTop'),
			'height': this.retrieve('menuHeight')+this.retrieve('menuHeadingHeight')
		});
	},
	
	dropDead: function() {
		this.retrieve('dropItAnim').cancel();
		this.setStyle('z-index', 1);
		this.retrieve('dropDeadAnim').start({
			'top': this.retrieve('menuTop'),
			'height': this.retrieve('menuHeadingHeight')
		});
	}
	
});

