$(function() {
	
	$('.separator').prev().filter('[id]').each(function() {
		var element = $(this);
		var method = element.next().hasClass('vertical') ? 'width' : 'height';
		var size = $.cookie(element.attr('id') + '-size');
		if (size != undefined) {
			element
				.data('lastSize', element[method]())
				[method](parseInt(size));
		}
	}).resize(function() {
		var element = $(this);
		var method = element.next().hasClass('vertical') ? 'width' : 'height';
		$.cookie(element.attr('id') + '-size', element[method](), {expires: 30});
	});
	
	$(window).resize(onResize).resize();
	
	$('.separator').mousedown(function(evt) {
		evt.preventDefault();
		var prev = $(this).prev();
		var next = $(this).next();
		var direction = $(this).hasClass('horizontal') ? 'Y' : 'X';
		var size = direction == 'X' ? 'width' : 'height';
		var mousemove, mouseup;
		prev.data('startSize', prev[size]());
		next.data('startSize', next[size]());
		$(window)
			.data('startPos', evt['page' + direction])
			.mousemove(mousemove = function(evt) {
				var delta = evt['page' + direction] - $(window).data('startPos');
				if (delta < -prev.data('startSize') || delta > next.data('startSize')) return;
				if (Math.abs(delta) > 6) {
					prev.data('lastSize', prev.data('startSize'));
				}
				prev[size](prev.data('startSize') + delta);
				next[size](next.data('startSize') - delta);
				$(window).resize();
				prev.resize();
				next.resize();
		}).mouseup(mouseup = function() {
			$(window).unbind('mousemove', mousemove);
			$(window).unbind('mouseup', mouseup);
		});
	}).dblclick(function (evt) {
		var prev = $(this).prev();
		var size = $(this).hasClass('horizontal') ? 'height' : 'width';
		if (prev[size]() <= 0) {
			prev[size](prev.data('lastSize'));
		} else {
			prev.data('lastSize', prev[size]());
			prev[size](0);
		}
		$(window).resize();
		prev.resize();
	});
});

function onResize() {
	var verticals = $('.vertical');
	var horizontals = $('.horizontal');
	verticals.each(function(index, div) {
		div = $(div);
		var height = div.parent().height();
		height -= div.outerHeight() - div.height();
		div.parent().children().not('.vertical').each(function(index, child) {
			height -= $(child).outerHeight();
		});
		div.height(height);
	});
	horizontals.each(function(index, div) {
		div = $(div);
		var width = div.parent().width();
		width -= div.outerWidth() - div.width();
		div.parent().children().not('.horizontal').each(function(index, child) {
			width -= $(child).outerWidth();
		});
		div.width(width);
	});
}
