var complex = false;
var cookie;
var title;

if (document.getElementById && document.getElementsByTagName 
	      && typeof document.getElementsByTagName('head').item(0).innerHTML != 'undefined') {
		complex = true;
}

window.onload = function() {
	if (!complex) return;
	
	cookie = readCookie('style');
	title = cookie ? cookie : getPreferredStyleSheet();
  setupThemeSwitcher();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  createCookie('style', getActiveStyleSheet(), 365);
}

function setupThemeSwitcher() {
/* Should only be called after cookie has been initialized. */
  var themeSwitcher = document.createElement('select');
	themeSwitcher.setAttribute('id','themeSwitcher');
	themeSwitcher.onchange = function () {
	   setActiveStyleSheet(document.getElementById('themeswitcher').value);
		 window.focus();
		 return false;
	}

	var a, optionTextValue, optionNode, optionTextNode, preferredStyle;
	preferredStyle = cookie ? cookie : getPreferredStyleSheet();
  for (var i = 0; (a = document.getElementsByTagName('link')[i]); i++) {
	  optionTextValue = a.getAttribute('title');   
    optionNode = document.createElement('option');
		optionNode.setAttribute('value',optionTextValue);
		if (optionTextValue == preferredStyle) {
		   optionNode.setAttribute('selected','yes');
		}
		optionTextNode = document.createTextNode(optionTextValue);
		optionNode.appendChild(optionTextNode);
		themeSwitcher.appendChild(optionNode);
  }

  document.getElementById('navigation').appendChild(themeSwitcher);
}

