function getCookie(Name) {
	//construct RE to search for target name/value pair
	var re=new RegExp(Name+"=[^;]+", "i");
	if (document.cookie.match(re)) //if cookie found
	return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
}

function setCookie(name, value) {
	var expireDate = new Date()
	//set "expstring" to either future or past date, to set or delete cookie, respectively
	var expstring= expireDate.setDate(expireDate.getDate()+365)
	document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}

//Main stylesheet switcher function.
function setStylesheet(themeTitle, fontTitle){
	selectedTheme = themeTitle
	selectedFont = fontTitle
	var i, cacheobj, altsheets=[""]
	for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) {
		//if this is an alternate stylesheet with title
		if ( cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet"
				&& cacheobj.getAttribute("title") ) {
			cacheobj.disabled = true
			//enable alternate stylesheet with title that matches parameter
			if ( cacheobj.getAttribute("title") == themeTitle
					|| cacheobj.getAttribute("title") == fontTitle )
				cacheobj.disabled = false //enable chosen style sheet
		}
	}
}

// Interface function to switch theme style sheets
// plus save "title" attr of selected stylesheet to cookie
function chooseStyle(styletitle){
	if (document.getElementById){
		setStylesheet(styletitle, selectedFont)
		setCookie("mytheme", styletitle)
	}
}

// Interface function to switch font style sheets
// plus save "title" attr of selected stylesheet to cookie
function chooseFont(styletitle){
	if (document.getElementById){
		setStylesheet(selectedTheme, styletitle)
		setCookie("myfont", styletitle)
	}
}

// Optional function that shows which style sheet is currently selected
// within group of radio buttons or select menu
function indicateSelected(element){
	//if element is a radio button or select menu
	if (selectedTheme!=null && (element.type==undefined || element.type=="select-one")){
		var element=(element.type=="select-one") ? element.options : element
		for (var i=0; i<element.length; i++){
			//if match found between form element value and cookie value
			if (element[i].value==selectedTheme) {
				if (element[i].tagName=="OPTION") //if this is a select menu
					element[i].selected=true
				else //else if it's a radio button
					element[i].checked=true
				break
			}
		}
	}
}

var selectedTheme=getCookie("mytheme")
var selectedFont=getCookie("myfont")

if (document.getElementById ) {
	if ( selectedTheme == null )
		selectedTheme = "default";
	if ( selectedFont == null )
		selectedFont = "default";
	
	setStylesheet(selectedTheme, selectedFont);
}
