$(document).ready(function() {

	var ANIMATION_STEP_TIME = 500;

	var ul = $("#ul");
	var ur = $("#ur");
	var ll = $("#ll");
	var lr = $("#lr");
	var phantom = $("#phantom");

	var lastClicked;

	ul.click(function() {
		highlightSection(phantom, ul, ur, ll, lr);
	});

	ur.click(function() {
		highlightSection(phantom, ur, ul, lr, ll);
	});

	ll.click(function() {
		highlightSection(phantom, ll, lr, ul, ur);
	});

	lr.click(function() {
		highlightSection(phantom, lr, ll, ur, ul);
	});

	function highlightSection(phantom, primary, vertical, horizontal, corner) {

		//Don't do anything if the user clicked the div that is already primary
		if (lastClicked == primary) return false;

		lastClicked = primary;

		$(".text").animate({ opacity:0 }, ANIMATION_STEP_TIME, function() {
			
			$(".text").css("display", "none");

			var large = 608;
			var medium = 468;
			var small = 28;

			var totalWidth = large + small;
			var totalHeight = medium + small;

			//Initialize the dimensions of the phantom div...
			phantom.css({width:primary.width(), height:primary.height()});

			//...Then animate it, using its step function to simultaneously 'animate' the four real divs.
			//stop() will cause the animation to smoothly transition if the user clicks on different divs while an animation is already running.
			phantom.stop().animate({ width:608, height:468 },
			{
				duration: ANIMATION_STEP_TIME,
				step: function() {
		
					var primaryWidth = phantom.width();
					var primaryHeight = phantom.height();
					var variableWidth = totalWidth - primaryWidth;
					var variableHeight = totalHeight - primaryHeight;

					if (primaryWidth > variableWidth) {
						vertical.css("width", variableWidth);
						corner.css("width", variableWidth);

						primary.css("width", primaryWidth);
						horizontal.css("width", primaryWidth);
					} else {
						primary.css("width", primaryWidth);
						horizontal.css("width", primaryWidth);

						vertical.css("width", variableWidth);
						corner.css("width", variableWidth);
					} 

					if (primaryHeight > variableHeight) {
						horizontal.css("height", variableHeight);
						corner.css("height", variableHeight);

						primary.css("height", primaryHeight);
						vertical.css("height", primaryHeight);
					} else {
						primary.css("height", primaryHeight);
						vertical.css("height", primaryHeight);

						horizontal.css("height", variableHeight);
						corner.css("height", variableHeight);
					}
				},
				complete: function() {
					primary.children(".content").css("display", "block").animate({ opacity:1 }, ANIMATION_STEP_TIME);
					vertical.children(".cv").css("display", "block").animate({ opacity:1 }, ANIMATION_STEP_TIME);
					horizontal.children(".horizontal").css("display", "block").animate({ opacity:1 }, ANIMATION_STEP_TIME);
					corner.children(".cv").css("display", "block").animate({ opacity:1 }, ANIMATION_STEP_TIME);
				}
			});
		});
	}
});

