// Styleswitcher script to allow the use of alternative stylesheets
// Uses a cookie called 'style-CoventryCityCouncil' to store the preferred stylesheet
// Based upon an article by Paul Snowden - http://www.alistapart.com/articles/alternate/
// Levered in to Coventry City Council's website by Chris Dibben in the Web Services Team

/*
Updated 18 March 2008 by Dave Collins (david.collins@hikisolutions.co.uk)
Improved the code so that the cookie is only saved when the user chooses an alternative instead of every time the window closes.
Also fixed an issue with IE where it did not load the stylesheet correctly until the page was reloaded.
*/

// get the currently active stylesheet (defunct)
function getActiveStyleSheet() 
{
  var i, a;
  for(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;
}

// get the default stylesheet
function getPreferredStyleSheet() 
{
    var i, a;
    for(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 null;
}

// Set the cookie
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=/";
}

// Get the cookie
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;
}

// renamed setActiveStyleSheet so no HTML updates are needed.
function hiki_SetStyleSheet(title)
{
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) 
    {
            if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) 
            {
                a.disabled = true;
                if(a.getAttribute("title") == title) a.disabled = false;
            }
    }
}

// Replaces the old function, saves the cookie here.
function setActiveStyleSheet(title) 
{    
    hiki_SetStyleSheet(title);
    createCookie("style-CoventryCityCouncil", title, 365);
    //window.location.reload();
}


// when the page loads
window.onload = function(e) 
{
    var cookie = readCookie("style-CoventryCityCouncil");
    var title = cookie ? cookie : getPreferredStyleSheet();
    hiki_SetStyleSheet(title);
}
