$(document).ready(function() {
	$('.menu').hover(function() {
		$(this).children('a').addClass('hover');
		$(this).children('ul').show(); //slideDown('fast');
		$(this).parent().siblings().children('a').removeClass('hover');
		$(this).parent().siblings().children('ul').hide(); //fadeOut('fast');
	}, function() {
		$(this).children('a').removeClass('hover');
		$(this).children('ul').hide();//fadeOut('fast');
	});

	$('body').click(function(element) {
		if (!$(element).hasClass('menu'))
		{
			$('.submenu').hide(); //fadeOut('fast');
		}
	});

	$('.main-col .title').click(function() {
		if ($(this).hasClass('open'))
		{
			next = $(this).next();
			if ($(next).hasClass('data'))
			{
				$(next).slideUp();
				$(this).removeClass('open');
			}
		}
		else
		{
			next = $(this).next();
			if ($(next).hasClass('data'))
			{
				$(next).slideDown();
				$(this).addClass('open');

				divs = $('.main-col > div');
				l = divs.length;
				height = 0;
				for (i=0; i<l; i++)
				{
					if ($(divs[i]).hasClass('title'))
						height += $(divs[i]).attr('scrollHeight');
					else
					{
						if ($(divs[i-1]).hasClass('open'))
							height += $(divs[i]).attr('scrollHeight');
					}
				}
				totalHeight = $('.main-col').attr('scrollHeight');

				if (height >= totalHeight)
				{
					for (i=(l-1); i>=0; i--)
					{
						if ($(divs[i]).hasClass('title') && $(divs[i+1]).hasClass('data') && divs[i] != this && $(divs[i]).hasClass('open'))
						{
							height -= $(divs[i+1]).attr('scrollHeight');
							$(divs[i+1]).slideUp();
							$(divs[i]).removeClass('open');
							if (height < totalHeight)
								break;
						}
					}
				}
			}
		}
	});
});
