/*
Script: LavishMenu.js
	Add a Lavish menu effect to UL elements.

License:
	MIT-style license.

Copyright:
	Copyright (c) 2009 [Drew Gauderman](http://www.aspinvision.com)

Code & Documentation:
	[ASP Invision]http://www.aspinvision.com).

Inspiration:
	- http://devthought.com/blog/projects-news/2007/01/cssjavascript-true-power-fancy-menu/


Hot to use:

	//simple, but class and type
	$$('.lavishmenu ul').lavishmenu();

	//by id
	$('lavishmenu').lavishmenu();

	//advanced with options
	$$('.partners ul,.quicklinks ul').lavishmenu({
		'backgroundColor': '#fff',
		'opacity': 1
	});

*/

var LavishMenu = new Class({

	Implements: [Options],

	options: {
		'activestyles': {
			'background-color': '#90aed0',
			'opacity': 0.5
		},
		'styles': {
			'background-color': '#000',
			'opacity': 0.5
		}
	},

	// do initialize
	initialize: function( menu, options) {
		//input custom options
		this.setOptions(options);

		//make sure its an element
		this.menu = $(menu);

		//make sure link is above the background
		this.menu.getElements('li').setStyles({'z-index': 10,'position': 'relative'});

		//get active menu item
		this.active = $pick(this.menu.getElement('li.active'), this.menu.getElement('li'));

		//li element
		this.liHover = new Element('li', {'class': 'liHover', 'html': '<div></div>'}).setStyles({
			'position': 'absolute',
			'opacity': 0,
			'z-index': 1
		});

		//add li slider
		this.menu.adopt(this.liHover).getElements('li').each(function(li) {
			li.addEvents({
				'mouseenter': function() {
					this.goto(li);
				}.bind(this),
				'mouseleave': function() {
					if (active = this.menu.getElement('li.active'))
						this.goto(active);
					else
						this.liHover.morph({'opacity': 0});
				}.bind(this)
			});
		}.bind(this));

		if (active = this.menu.getElement('li.active')) this.goto(active, true);
		
		window.addEvent('resize', function() {
			if (active = this.menu.getElement('li.active')) this.goto(active, true);
		}.bind(this));
	},

	goto: function(el, noMorph) {
		if (el.hasClass('liHover')) return;
		var coord = el.getCoordinates();
		var styles = {
			'top': coord.top - (Browser.Engine.trident ? 2 : 0) - el.getStyle('margin-top').toInt(),//
			'left': coord.left + (Browser.Engine.trident ? 1 : 0) - el.getStyle('margin-left').toInt(),
			'height': 40,
			'width': 180
		};

		$extend(styles, (el.hasClass('active') == true ? this.options.activestyles : this.options.styles));

		this.liHover[(noMorph == true ? 'setStyles' : 'morph')](styles);
	}
});

Element.implement({
	lavishmenu: function(options) {
		window.addEvent('load', function() {
			new LavishMenu(this, options);
		}.bind(this));
	}
});
