/* Styleswitcher Copyright 2008 Alex Monney
 *
 * Displays a way for the user to switch between alternate stylesheets
 * Place script after style sheet declarations.
 */

var StyleSwitch = new function(){
  var linkedelements = document.getElementsByTagName("link");
  var styles = [];
  var a;
  for(var i=0; a = linkedelements[i]; i++){
    if (a.getAttribute("rel").indexOf("style") != -1 &&
        a.getAttribute("title")){
      styles[styles.length] = a;
    }
  }

  this.setActive = function(title){
    for(var i=0; a = styles[i]; i++) {
      a.disabled = (a.getAttribute("title") == title) ? false : true;
    }
    CookieJar.create("style", title, 365);
  }
  this.getActive = function(){
    for(var i=0; a = styles[i]; i++) {
      if (!a.disabled) return a.getAttribute("title");
    }
    return null;
  }
  this.getPreferred = function(){
    for(var i=0; a = styles[i]; i++) {
      if (a.getAttribute("rel").indexOf("alt") == -1) return a.getAttribute("title");
    }
    return null;
  }

  this.getStyleList = function(){
    var stylestring = '<ul id="styleswitcher">';
    for(var i=0; a = styles[i]; i++) {
      var title =  a.getAttribute("title");
      stylestring += '<li><a href="" onclick="StyleSwitch.setActive(\'' + title + '\');return false" title="Switch to ' + title + ' version">' + title + ' version</a>';
    }
    stylestring += '</ul>';
    return stylestring;
  }

  this.appendto = function(addto){
    var ulel = document.createElement('ul');
        ulel.setAttribute('id', 'styleswitcher');
    for(var i=0; a = styles[i]; i++) (function(a){
      var title =  a.getAttribute("title");
      var liel = document.createElement('li');
      var ael  = document.createElement('a');
          ael.onclick = function(){StyleSwitch.setActive( title ); return false; };
          ael.setAttribute('href', '');
          ael.setAttribute('title', 'Switch to ' + title + ' version')
          ael.appendChild(document.createTextNode( title ));
      liel.appendChild(ael);
      ulel.appendChild(liel);
    })(a);
    document.getElementById(addto).appendChild(ulel);
  }
}();

var CookieJar = new function(){
  this.create = function(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=/";
  }
  this.read = function(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) {
  // append the list to the header
  StyleSwitch.appendto('header');
}

