//
// Must have included prototype and extend, for animation you must include scriptaculous
//

Object.extend(Element,
{
	getOffsets: function(element)
	{
		element = $(element);
		
		var left = element.offsetLeft || 0;
		var top = element.offsetTop || 0;
		
		while (element = element.offsetParent)
		{
			left += element.offsetLeft || 0;
			top += element.offsetTop || 0;
		}
		
		var offsets = { left: left || 0, top: top || 0 };
		return offsets;
	}
});

var NavBar = Class.create(
{
	initialize: function(el)
	{
		element = $(el);
		
		var children = element.childElements();
		
		for (var i = 0; i < children.size(); i++)
		{
			var link = children[i];
			if (link.tagName.toLowerCase() != 'a')
				continue;
			
			var menu = link.next();
			if (typeof(menu) != "undefined" && menu != null)
			{
				if (menu.tagName.toLowerCase() == 'div')
				{
					new DropDown(link, menu);
				}
			}
		}
	}
});

var DropDown = Class.create(
{
	initialize: function(el, menu)
	{
		element = $(el);
		this.link = el;
		this.dropdown = menu;
		
		this.options = {};
		this.options.delay = 0.2;
		this.options.queue = "dropdown:" + element.id;
		
		this.dropdown.hide();
		
		this.link.observe("mouseover", this.start.bind(this)).observe("mouseout", this.delay.bind(this));
		this.dropdown.observe("mouseover", this.pause.bind(this)).observe("mouseout", this.delay.bind(this));
		
		this.active = false;
	},
	
	start: function()
	{
		var offsets = Element.getOffsets(this.link);
		var dimensions = this.link.getDimensions();
		
		Element.setStyle(this.dropdown, {zIndex: 100, left: offsets.left + "px", top: (offsets.top + dimensions.height) + 'px', width: dimensions.width + 'px'});
		
		if (this.active)
		{
			// Just make sure we can see the dropdown
			this.dropdown.show();
		}
		else
		{
			new Effect.BlindDown(this.dropdown, {queue: {scope: this.options.queue, position: "end"}, duration: 0.2});
			//this.dropdown.show();
			this.active = true;
		}
		
		this.pause();
	},
	
	pause: function()
	{
		this.dropdown.setStyle({zIndex: 100});
		if (this.timeout)
			this.timeout.stop();
	},
	
	delay: function()
	{
		this.dropdown.setStyle({zIndex: 99});
		// Clear the timeout and reset it.
		if (this.timeout)
		{
			this.timeout.stop();
			this.timeout.registerCallback();
		}
		else
		{
			this.timeout = new PeriodicalExecuter(this.end.bind(this), this.options.delay);
		}
	},
	
	end: function()
	{
		if (this.active)
		{
			new Effect.BlindUp(this.dropdown, {queue: {scope: this.options.queue, position: "end"}, duration: 0.2});
			//this.dropdown.hide();
			this.active = false;
		}
		
		this.timeout.stop();
	}
});