/*	Loosely based on <http://www.alistapart.com/stories/alternate/styleswitcher.js>,
	with a whole lot of updating
*/

function setActiveStyleSheet(title) {
	linksFound = document.getElementsByTagName("link")
	for (i=0; i<linksFound.length; i++) {
		thisLink = linksFound[i]
    	if (thisLink.getAttribute("rel").indexOf("style") > -1 && thisLink.getAttribute("title")) {
			thisLink.disabled = true
			if (thisLink.getAttribute("title") == title) {
				thisLink.disabled = false
			}
		}
	}
}

function getActiveStyleSheet() {
	linksFound = document.getElementsByTagName("link")
	for (i=0; i<linksFound.length; i++) {
		thisLink = linksFound[i]
    	if (thisLink.getAttribute("rel").indexOf("style") > -1 && thisLink.getAttribute("title") && !thisLink.disabled) {
			return thisLink.getAttribute("title")
		}
	}
}

function getPreferredStyleSheet() {
	linksFound = document.getElementsByTagName("link")
	for (i=0; i<linksFound.length; i++) {
		thisLink = linksFound[i]
		if (thisLink.getAttribute("rel").indexOf("style") > -1 && thisLink.getAttribute("rel").indexOf("alt") == -1 && thisLink.getAttribute("title")) {
		 	return thisLink.getAttribute("title")
		}
	}
}

function cookieVal(cookieName) {
	thisCookie = document.cookie.split("; ")
	for (i=0; i<thisCookie.length; i++) {
		if (cookieName == thisCookie[i].split("=")[0]) {
			return thisCookie[i].split("=")[1]
		}
	}
	return ""
}

window.onload = function() {
	thisCookie = cookieVal("style")
	if (thisCookie) {
		title = thisCookie
	}
	else {
		title = getPreferredStyleSheet()
	}
	setActiveStyleSheet(title)
}

window.onunload = function() {
	expireDate = new Date
	expireDate.setYear(expireDate.getFullYear()+1)
	document.cookie = "style="+getActiveStyleSheet()+"; expires="+expireDate.toGMTString()+"; path=/"
}
