$(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);
	});
	
	//blossom hack: 18-1-2011: closing after clicking
	$(this).find('li').click(function()
	{
		var menu = $(this).parent('ul');
		menu.removeClass("hover");
		menu.find('.open').removeClass("open");
		menu.css('visibility', 'hidden');
	});
			
	// 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);
	});

}
