//DropMe - A MooTools Drop-Down Menu Script
//Requires MooTools Core 1.3 and MooTools More 1.3 with Element.Position and Assets

var DropMe = new Class({		
		
	Implements: [Options, Events],
		
	options: {
		trigger: '',
		target: '',
		offset: {
			x: 0,
			y: 0
		}
	},
		
	initialize: function(options) {
		
		this.setOptions(options);
		
		//initialise menu
		
		//hide the menu
		this.hideMe();
		
		//load the css layout by finding containing directory and pulling layout.css in as an asset
		$$('script').each(function(tag){
			scriptSrc = tag.get('src');
			
			if(scriptSrc != null && scriptSrc.contains('dropme.js')) {
				var srcCss = tag.get('src').replace('dropme.js','') + 'layout.css';
				var css = Asset.css(srcCss);
			}
		});
		
		//set the z-index to position menu behind the trigger
		var zIndexSet = $(this.options.trigger).getStyle('z-index').toInt() - 2;
		
		$(this.options.target).setStyle('z-index', zIndexSet);
		
		//position the menu
		$(this.options.target).position({
			relativeTo: $(this.options.trigger),
			position: 'topLeft',
			edge: 'topLeft',
			offset: { x: this.options.offset.x, y: this.options.offset.y }
		});
			
		//set events	
			
		$(this.options.trigger).addEvents({
		
			click: function(e){
				if (e) e.stop();
				if (!$(this.options.trigger).hasClass('menu-active')) this.showMe(); else this.hideMe();
			}.bind(this)
			
		});
			
		$(document.body).addEvents({
					
			click: function(e){
				if(!(e.target).getParents().contains($(this.options.target))) this.hideMe()
			}.bind(this)
					
		});
			
	},
		
	showMe: function() {
		$(this.options.trigger).addClass('menu-active');
		$(this.options.target).setStyle('display','block');
	},
		
	hideMe: function() {
		$(this.options.trigger).removeClass('menu-active');
		$(this.options.target).setStyle('display','none');
	}
		
});
