/*global add_window_onload_function, add_window_onresize_function, document, $ */

var containerClass = "right-box-container left";
var leftBorderClass = "right-box-left-border";
var rightBorderClass = "right-box-right-border";

var minBrowserWidthForCascading = 959;

/**
 * Make sure that, if the right hand content falls below the center
 * content, the columns don't break in strange places.
 */

add_window_onload_function(function() {
	var a = document.getElementsByTagName("div");
	var allDivs = [];
	var i, l;
	
	for (i = 0, l = a.length; i < l; ++i) {
		if (a[i].className.indexOf("right-box") > -1) { allDivs[allDivs.length] = a[i];	}
	}

	var leftDiv  = document.createElement("div");
	var rightDiv = document.createElement("div");

	var totalHeight = 0;

	for (i = 0, l = allDivs.length; i < l; ++i) {
		totalHeight += allDivs[i].offsetHeight;
	}

	var optimalHeight = totalHeight * 0.5;
	
	var middleContent = $("middle-content");
	var middleContentContainer = $("middle-content-container");
	
	middleContent.appendChild(leftDiv);
	middleContent.appendChild(rightDiv);
	
	var currentHeight = 0;
	var divList = [ leftDiv, rightDiv ];
	var currentDiv = divList.shift();

  var rightColumnTopDiv = null;

	for (i = 0, l = allDivs.length; i < l; ++i) { 
    if ((currentHeight + allDivs[i].offsetHeight) >= optimalHeight) { 
			if (divList.length > 0) {
				currentDiv = divList.shift();
				rightColumnTopDiv = allDivs[i];
				currentHeight = 0;
			}
		}
		middleContent.removeChild(allDivs[i]);
		currentDiv.appendChild(allDivs[i]);			
		currentHeight += allDivs[i].offsetHeight;
	}
	
	if (currentHeight > optimalHeight) {
		currentDiv.removeChild(rightColumnTopDiv);
		leftDiv.appendChild(rightColumnTopDiv);
	}
	
	var rightBoxIsCascaded = null;
	
	var rightBoxBorders = function() { 
		if ($("container").offsetWidth < minBrowserWidthForCascading) {
			if (!rightBoxIsCascaded) {
				leftDiv.className  = containerClass + " " + leftBorderClass;
				rightDiv.className = containerClass + " " + rightBorderClass;
	
				var max_height = Math.max(leftDiv.offsetHeight, rightDiv.offsetHeight);
				leftDiv.style.height  = max_height + "px";
				rightDiv.style.height = max_height + "px";
				
				rightBoxIsCascaded = true;
			}
    } else {
			if (rightBoxIsCascaded === true || rightBoxIsCascaded === null) {
				leftDiv.className  = containerClass;
				rightDiv.className = containerClass;			
	
				leftDiv.style.height  = "";
				rightDiv.style.height = "";
				
				rightBoxIsCascaded = false;
			}
    }
	};
	
  add_window_onresize_function(rightBoxBorders);
	rightBoxBorders();
	
	middleContentContainer.className = "remove-margin";
});