/**
* med.govt.nz | layout helpers
* mark@shift.co.nz
*/
var pageBox;
var mode = 'narrow';

window.onload = function() {
	redrawHomeLayout();
	resetPageBox();
	(checkMode() == 'narrow') ? switchStylesheet('narrow', applyNarrowMode)
						 	  : switchStylesheet('wide', applyWideMode);
}

window.onresize = switchMode;

function $(name) {
	return document.getElementById(name);
}

function redrawHomeLayout() {
	if ($('shortcut-box')) {
		tCol = $('welcome-box').offsetHeight;
		aCol = $('shortcut-box').offsetHeight + tCol;
		bCol = $('promo-box').offsetHeight + tCol;
		lHeight = (aCol > bCol) ? aCol : bCol;
		nHeight = $('news-box').offsetHeight;
		if (lHeight > nHeight) {
			$('news-box').style.height = (lHeight+15) + "px";
			toHeight = (lHeight - tCol);
		} else {
			toHeight = (nHeight - tCol)-15;
		}
		$('shortcut-box').style.height = (toHeight+10) + "px";
		$('promo-box').style.height = (toHeight+10) + "px";
	}
}

function resetPageBox() {
	pageBox = $('page-frame').offsetHeight;
}

function checkMode() {
	return (document.body.clientWidth > 975) ? 'wide' : 'narrow';
}

function getExtraElm() {
	elm = $('homepage-extra');
	if (!elm) elm = $('page-extra');
	return elm;
}

function applyWideMode() {
	resetPageBox();
	elm = getExtraElm();
	if (elm) {
		$('gutter').style.display = 'none';
		elm.style.height = pageBox+"px";
	} else {
		applyLayoutHeight();
	}
}

function applyNarrowMode() {
	resetPageBox();
	elm = getExtraElm();
	if (elm) elm.style.height = "auto";
	$('gutter').style.display = 'block';
	applyLayoutHeight();
}

function applyLayoutHeight() {
	nHeight = (document.all) ? $('page-frame').offsetHeight-14 : $('page-frame').offsetHeight;
	$('gutter').style.height = nHeight + "px";
	if (document.all) $('footer-swoosh').style.marginBottom = "-14px";
}

function switchStylesheet(toMode, applyMode) {
		if(toMode=='narrow')
		{
			$('layout-mode').href = $('layout-mode').href.replace(/wide/i,'narrow');
		}
		else
		{
			$('layout-mode').href = $('layout-mode').href.replace(/narrow/i,'wide');
		}
		mode = toMode;
		setTimeout(applyMode, 300);
}

function switchMode() {
	if(checkMode() != mode) {
		switch(mode) {
			case 'wide':   switchStylesheet('narrow', applyNarrowMode); break;
			case 'narrow': switchStylesheet('wide', applyWideMode); break;
		}
	}
}
