$(function(){

	$("ul.dropdown > li").dropdown();

});

$.fn.dropdown = function() 
{
	var closeTimer = false;
	//set same width to sub menus
	$(this).find('ul').each(function()
	{
		if ($(this).is(':hidden'))
			return true;
		var max_width = 0;
		$(this).find('li').each(function()
		{
			var width = $(this).width();
			if ($(this).find('img').length)
				width += 15;
			if (width > max_width)
				max_width = width;
		}).width(max_width);
	});
	
	// unbind for refreshing the menus on ajax
	$(this).unbind('mouseenter mouseleave').hover(function()
	{
		if (closeTimer)
		{
			clearTimeout(closeTimer);
			closeTimer = false;
		}
		$("ul.dropdown li").each(function()
		{
			$(this).removeClass("hover");
			$(this).find('.open').removeClass("open");
			$(this).find('ul:first').css('visibility', 'hidden');
		});
		
		$(this).addClass("hover");
		$('> .dir',this).addClass("open");
		$('ul:first',this).css('visibility', 'visible');
	},function()
	{
		var menu = $(this);
		closeTimer = setTimeout(function()
		{
			menu.removeClass("hover");
			menu.find('.open').removeClass("open");
			menu.find('ul:first').css('visibility', 'hidden');
		}, 500);
	});
	
	// when clicking around the link activating the link
	$(this).unbind('click.dropdown').bind('click.dropdown', function(event)
	{
		var target = $(event.target);
		if (target.is("li"))
		{
			var anchor = target.find('> a');
			if (anchor.length)
			{
				var href = anchor.attr('href');
				if (href && href != "#" && href != "javascript:void(0);")
					location.href = href;
			}
		}
	});
}
