/*
 * Created By Scott Steil of Imperium Inc.
 *
 * 
 */

var ImpNav = new Class({
	initialize: function(ele, options){
		this.obj = $(ele);
		this.applyToSubCat(this.obj);
	},
	
	applyToSubCat: function(ele, parent){
		//check all items in the menu
		$(ele).getChildren('li').each(function(item){
			// loop on any submenus; add the submenu functionality and check child item 
			item.getChildren('ul').each(function(submenu){
				// build submenu item
				var temp = new ImpNavItem(submenu.getParent(), parent);
				// check children
				this.applyToSubCat(submenu, temp);
			}.bind(this));
		}.bind(this));
	}
});


var ImpNavItem = new Class({
	Implements: Options,
	options: {
		duration: 150,
		transition: Fx.Transitions.Quad.easeInOut
	},
	
	initialize: function(ele, parent, options){
		this.parent = parent;
		this.root = $(ele);
		if(!this.root) return false;
		
		this.link = this.root.getElement('span');
		this.menu = this.root.getElement('ul');
		if(!this.link || !this.menu) return false;
		
		this.setOptions(options);
		this.height = 0;
		this.opened = false;
		
		this.menu.setStyle('height', 0);
		// this is part of the code that shrinks the width on hide
		//this.menu.setStyle('display', "none");
		
		//if root level, add rollover event
		if(!this.parent) {
			this.link.addEvents({
				mouseenter: this.show.bind(this)
			});
		} 
		//else add click event
		else {
			this.link.addEvents({
				click: this.show.bind(this)
			});
		}
		
		this.root.addEvents({
			mouseleave: this.hide.bind(this)
		});
	},
	
	show: function() {
		if(this.opened)
			return this.hide();

		
		this.menu.setStyle('display', "block");
		this.menu.setStyle('visibility', "visible");
		
		var height = 0;
		var children = this.menu.getChildren('li');
		for(var i=0; i<children.length; i++) {
			height += $(children[i]).getSize().y;
		}
		
		this.opened = true;
		this.expand(height);
	},
	
	hide: function() {
		if(this.parent) {
			this.parent.expand( -this.height );
		}

		this.opened = false;
		this.height = 0;
		this.menu.set('tween', {
			duration: this.options.duration,
			events: {
				complete: function() { 
					// this is not called right now, ho do i fix?
					this.setStyle('display', "none"); 
				}.bind(this.menu)
			},
			transition: this.options.transition
		}).tween('height', '0px');
	},
	
	expand: function(height) {
		if(this.parent) {
			this.parent.expand(height);
		}
		
		this.height += height;
		this.menu.set('tween', {
			duration: this.options.duration,
			transition: this.options.transition
		}).tween('height', this.height+'px');
	}
});



window.addEvent('domready', function() {
	var nav = new ImpNav('nav');
});