/*
 * ------------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <choan@alice.0z0ne.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return 
 * ------------------------------------------------------------------------------
 */

/*
 * USO:
 * window.onload = styleSwap( {stylesheet_title: min_width_to_apply, ... } );
 */


function styleSwap(oConfig) {

	if (!document.getElementsByTagName) {
		return;
	}

	window.swapStyles = function(){swapStyles(oConfig);};
	
	var oldOnresize = window.onresize;
	if ('function' == typeof oldOnresize) {
		window.onresize = function() {
			oldOnresize();
			window.swapStyles();
		}
	} else {
		window.onresize = window.swapStyles;
	}

	window.swapStyles();

	function getViewportSize() {
		var x, y;
		if (self.innerHeight) { // MOS
			y = self.innerHeight;
			x = self.innerWidth;
		} else if (document.documentElement && document.documentElement.clientWidth) { // IE6 Strict
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
		} else if (document.body.clientHeight) { // IE quirks
			y = document.body.clientHeight;
			x = document.body.clientWidth;
		}
		return {x: x, y: y};
	}

	function swapStyles(oConfig) {
		var title;
		var width = getViewportSize().x;
		for (title in oConfig) {
			if (width >= oConfig[title]) {
				break;
			}
		}
		//alert(width + ' ergo ' + title);
		setStyle(title);
	}


	function setStyle(title) {
		var current;
		for (var i = 0; (current = document.getElementsByTagName('link')[i]); i++) {
			if (current.getAttribute('rel').indexOf('style') != -1) {
				current.disabled = true;
				if (current.getAttribute('title') == title) {
					current.disabled = false;
				}
			}
		}
	}

}