var graceful = window.graceful || {};
graceful.Util = {
	// Tests if browser supports min width
	supportsMinWidth: function() {
		if (typeof(document.body.style.minWidth) != "undefined") {
			return true;
		}
		else {
			return false;
		}
	},
	loadPage: function() {
		if (!graceful.Util.supportsMinWidth()) {
			// If session cookie exists and isn't narrow, then set the layout. 
			// Why reset it if it isn't narrow? I can't remember... :(  
			var cookieBodyWidth = graceful.Util.readCookie("BodyWidth");
			if (cookieBodyWidth) {
				if (cookieBodyWidth != "narrow") {
					graceful.Util.setLayout();
				}
			}
			else {
				graceful.Util.setLayout();
			}
		}
	},
	resizePage: function() {
		if (!graceful.Util.supportsMinWidth()) {
			graceful.Util.setLayout();
		}
	},
	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') {
				c = c.substring(1,c.length);
			}
			if (c.indexOf(nameEQ) === 0) {
				return c.substring(nameEQ.length,c.length);
			}
		}
		return null;
	},
	// Apply class 'narrow' to body if browser window is less than 891px wide.
	// Also set a session cookie that client and server check to avoid visible resizing on every page load.
	setLayout: function() {
		if (document.body.clientWidth < 861) {
			document.body.className = "narrow";
			document.cookie = "BodyWidth=narrow; path=/";
		}
		else {
			document.body.className ="";
			document.cookie = "BodyWidth=standard; path=/; expires=Sat, 1 Jan 2000 00:00:00 UTC"; // Old date - browser should remove cookie
		}
	}
};
window.onload = graceful.Util.loadPage;
window.onresize = graceful.Util.resizePage;