var preferredCssTitle = "text-size-small";
var textSizeCssTitlePrefix = "text-size-";

function createCookie(name, value, daysToExpiration) {
	if (daysToExpiration) {
		var date = new Date();
		date.setTime(date.getTime() + (daysToExpiration * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = name + "=" + (value ? value : "") + expires + "; path=/";
}

function readCookie(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;
}

function setActiveStyleSheet(title) {
	if (document.getElementsByTagName) {
		var links = document.getElementsByTagName("link");
		var link;
		for (var i = 0; link = links[i]; ++ i) {
			var linkTitle = link.getAttribute("title");
			
			if (linkTitle && linkTitle.indexOf(textSizeCssTitlePrefix) == 0) {
				link.disabled = true;
				if (link.getAttribute("rel").indexOf("stylesheet") > -1 &&
						linkTitle == title) {
					link.disabled = false;
				}
			}
		}
	}
	createCookie("style", title, 30);
}

function getActiveStyleSheet() {
	if (document.getElementsByTagName) {
		var links = document.getElementsByTagName("link");
		var link;
		for (var i = 0; link = links[i]; ++ i) {
			var linkTitle = link.getAttribute("title");
			
			if (linkTitle && linkTitle.indexOf(textSizeCssTitlePrefix) == 0 &&
					link.getAttribute("rel").indexOf("stylesheet") > -1 &&
					!link.disabled) {
				return linkTitle;
			}
		}
	}
	return null;
}

function applySavedStylesheet() {
	var cookieStyle = readCookie("style");
	var title = cookieStyle ? cookieStyle : preferredCssTitle;
	setActiveStyleSheet(title);
}

applySavedStylesheet();