function setActiveStyleSheet(title) {
   var i, a = document.getElementsByTagName("link");

   for (i = 0; i < a.length; i++) {
      if (a[i].getAttribute("rel").indexOf("style") != -1
      && a[i].getAttribute("title")) {
         if (a[i].getAttribute("title") == title)
            a[i].disabled = false;
         else
            a[i].disabled = true;
      }
   }
}

function getActiveStyleSheet() {
   var i, a = document.getElementsByTagName("link");

   for (i = 0; i < a.length; i++) {
      if (a[i].getAttribute("rel").indexOf("style") != -1
      && a[i].getAttribute("title")
      && !a[i].disabled)
         return a[i].getAttribute("title");
   }
   return null;
}

function getPreferredStyleSheet() {
   var i, a = document.getElementsByTagName("link");

   for (i = 0; i < a.length; i++) {
      if (a[i].getAttribute("rel").indexOf("style") != -1
      && a[i].getAttribute("rel").indexOf("alt") == -1
      && a[i].getAttribute("title"))
         return a[i].getAttribute("title");
   }
   return null;
}

function setCookie(name, value, days) {
   var expires;

   if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toGMTString();
   } else {
      expires = "";
   }

   document.cookie = name+"=" + value+expires + "; path=/";
}

function getCookie(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;
}

window.onload = function(e) {
   var styleCookie = getCookie("style");
   var style = styleCookie ? styleCookie : getPreferredStyleSheet();

   setActiveStyleSheet(style);
}

window.onunload = function(e) {
   var activeStyle = "" + getActiveStyleSheet();

   if (activeStyle != style)
      setCookie("style", activeStyle, 365);
}

var styleCookie = getCookie("style");
var style = styleCookie ? styleCookie : getPreferredStyleSheet();
setActiveStyleSheet(style);

