// Automatically apply 'handheld' styles when the viewport width is small.
// This is a hack to work around mobile browsers that don't apply the
// 'handheld' media descriptor.
//
// For this site, it also enables the handheld styles when the window width
// shrinks such that the main content column is too wide for the screen.

var maxwidth;

function enableMobile() {
	//sheet = document.getElementById('handheld-sheet');
	//sheet.setAttribute('media', 'screen');
	for (i = 0; i < document.styleSheets.length; i++) {
		s = document.styleSheets[i];

		// Save the original media descriptors so that they can be
		// restored later
		if (!s.savedMediaDescriptors)
			s.savedMediaDescriptors = s.media.mediaText;

		is_handheld = s.media.mediaText.indexOf('handheld') != -1;
		is_screen = s.media.mediaText.indexOf('screen') != -1;
		if (is_screen) {
			s.media.deleteMedium('screen');
			s.media.appendMedium('unknown');
		}
		if (is_handheld) {
			s.media.appendMedium('screen');
		}
	}
}

function disableMobile() {
	for (i = 0; i < document.styleSheets.length; i++) {
		s = document.styleSheets[i];
		if (s.savedMediaDescriptors) {
			s.media.mediaText = s.savedMediaDescriptors;
		}
	}
}

function resizeContent() {
	if (window.innerWidth) {
		w = window.innerWidth;
	} else if (document.body.clientWidth) {
		w = document.body.clientWidth;
	}

	if (w <= maxwidth) {
		enableMobile();
	} else {
		disableMobile();
	}
}

function resizeInit() {
	maxwidth = document.getElementById('content').offsetWidth;
	resizeContent();
	Bytex64.DOM.addEventListener(window, 'resize', resizeContent);
}

Bytex64.DOM.addEventListener(window, 'load', resizeInit);

// Take a first whack based on the window width
if (window.innerWidth <= 480) {
	enableMobile();
}

