var styleResponseTimeout;

function setActiveStyleSheet(title, index)
{
    var a, main;
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); i++)
    {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
            a.disabled = a.getAttribute("title") != title;
    }
    if (index >= 0 && http)
    {
        if (styleResponseTimeout)
            window.clearTimeout(styleResponseTimeout);
        http.open('get', 'AJAXSetStyle?stty=' + index);
        http.onreadystatechange = handleSetStyleResponse;
        http.send(null);
    }
}

function handleSetStyleResponse()
{
    if (http.readyState == 4 && http.status == 200)
    {
        var response = http.responseText;
        document.getElementById("set-style-result").style.visibility = 'visible';
        document.getElementById("set-style-result").innerHTML = response ? response : '';
        styleResponseTimeout = window.setTimeout('hideSetStyleResponse()', 4000);
    }
}

function hideSetStyleResponse()
{
    document.getElementById("set-style-result").style.visibility = 'hidden';
    document.getElementById("set-style-result").innerHTML = '';
}

function getActiveStyleSheet()
{
    var a;
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); i++)
    {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
    }
    return null;
}

function getPreferredStyleSheet()
{
    var a;
    for (var i = 0; (a = document.getElementsByTagName("link")[i]); i++)
    {
        if (a.getAttribute("rel").indexOf("style") != -1
                && a.getAttribute("rel").indexOf("alt") == -1
                && a.getAttribute("title")
                ) return a.getAttribute("title");
    }
    return 'standard';
}

function createCookie(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 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;
}

function loadStyle()
{
    var cookie = readCookie("style");
    var title = cookie ? cookie : getPreferredStyleSheet();
    setActiveStyleSheet(title, -1);
}


