var Holder = {
	current_element: null,
	
	set_current: function(element) {
		this.current_element = element;
	}
}

var Navigation = {
	currently_open: null,
	open_delay: 150,
	close_delay: 400,
	root_element: null,
	current_item: null,
	
	initialize: function(root, open_delay, close_delay) {
		var self = this;

		if (open_delay)  { this.open_delay  = open_delay;  }
		if (close_delay) { this.close_delay = close_delay; }
		
		root_element = root;
		
		root_element.select('li ul').each(function(ul) {
			ul.hide();
			ul.up().down().addClassName('sub-menu');
			
			self.observe_parent(ul.up());
		});
		
		$(document.body).observe('mousemove', function(e) {
			Holder.set_current(e.element());
		});
		
		this.select_current();
	},

	select_current: function() {
		var offset = 0;
		var current_link = $$('#navigation a').find(function(el) { 
			return el.href == document.location.href 
		} )
		
		if (current_link) {		
			this.current_item = current_link.ancestors().findAll(function(el) {
				return el.tagName == 'LI'
			} ).last();
		
			this.current_item.down().addClassName('current');
		
			offset = this.current_item.positionedOffset()[1] + 'px';
		
			$('arrow').setStyle({top: offset});
		}
	},
	
	okay_to_open: function(li) {
		return !(li == $('clinic-modalities') && (Holder.current_element == $('clinic').down()));
	},
	
	observe_parent: function(parent) {
		parent.observe('mouseover', function(e) {
			var self = this;

			// alert(self.id);
			
			setTimeout(function() {
				var ul = self.down().next();

				if (Navigation.in_child_of(Holder.current_element, self)) {
					self.down().addClassName('active');
					ul.appear({duration: 0.25});
				}
			}, 150);
		});

		parent.observe('mouseout', function(e) {
			var self = this;
			
			setTimeout(function() {
				var ul = self.down().next();

				if (!Navigation.in_child_of(Holder.current_element, self)) {
					ul.fade({duration: 0.25});
					self.down().removeClassName('active');
				}
			}, 400);

		});
	},
	
	find_parent_from_event: function(event) {
		return event.element().ancestors().find(function(el) {
			return el.tagName == 'LI';
		});
	},
	
	in_child_of: function(child, element) {
		var parent = element;
		
		return child.ancestors().find(function(el) {
			// console.log(el == parent);
			return el == parent;
		})
	}
};

