var link;
for (var i = 0, a = undefined; (a = document.getElementsByTagName("link")[i]); i++) {
    // If this object is the link element that will hold the link to the enabled stylesheet, store the reference
    if (a.getAttribute("title") == "switch")
        link = a;
}

function setActiveStyleSheet(title) {
    var a;
    var href = '';
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
            if (a.getAttribute("title") == title) {
                href = a.href;
            }
        }
    }
    // Set href attribute of the link element
    link.setAttribute("href", href);
}

function setActiveStyleSheetByHref(href) {
    link.setAttribute("href", href);

    // Get the title of the stylesheet
    var title;

    var a;
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        var title = a.getAttribute("title");
        if (a.getAttribute("rel").indexOf("style") != -1 && title) {
            if (href.indexOf(a.getAttribute("href")) != -1 && title != 'switch') {
                title = a.getAttribute("title");
                // Title is of the shape colorN for N in {1,2,3,4}, so find N
                for (var j = 1; j < 5; j++) {
                    if (title == 'color' + j) {
                        setText(j);
                    }
                }
            }
        }
    }
}

function getActiveStyleSheet() {
    return link.getAttribute("href");
}

function getPreferredStyleSheet() {
    return link.getAttribute("href");
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+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;
}

window.onload = function(e) {
    var href = readCookie("stylesheet");
    if (href) {
        setActiveStyleSheetByHref(href);
    }
}

window.onunload = function(e) {
    var href = getActiveStyleSheet();
    createCookie("stylesheet", href, 365);
}

var href = readCookie("stylesheet");
if (href === undefined ) {
    // Make sure that browsers that have a cookie with data 
    // from the previous implementation refresh their cookie.
    href = getActiveStyleSheet();
    createCookie("stylesheet", href, 365);
}
if (href) {
    setActiveStyleSheetByHref(href);
}
