/*
 * Created by Niles Johnson, 2008, with thanks to
 * Paul Sowden at http://www.alistapart.com/stories/alternate/
 *
 * This implementation, different from Paul's, allows the page to load
 * as normal if the visitor has no style cookie set.
 */

function setActiveStyleSheet(title) {
    /*
      This is the function that sets the active stylesheet(s).
      It works by disabling all stylesheets that have a "title" attribute,
      and then enabling those stylesheets whose "title" attribute contain the
      given string (stored in the cookie)
      
      This enables two features:
       1.  A stylesheet with no "title" attribute will always stay enabled
       2.  If you want to enable one stylesheet for several, but not all styles,
       just make its title something that contains the names of all the styles
       you want it enabled for.
      
      This also creates one bug:
       If you choose the names of your styles so that the name of one contains
       the name of another, then you will have trouble.  This could be fixed
       by choosing a "separator" character, splitting the "title" attributes on
       that character and then checking for string equality, but for now I
       don't want to go to that trouble...
    */
    var i, a, main;
    var currstyle = '';
    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) {
	        //in a previous version, we just checked for string equality
	    if(a.getAttribute("title").indexOf(title) != -1) {
		//returns true if 'title' is anywhere in "title" attribute
		a.disabled = false;
		currstyle = title;
	    }
	}
    }
    // handle the case that the value of the cookie doesn't match any available style
    // in this case, we overwrite the cookie with one that expires immediately,
    // thereby deleting the cookie
    // note: there is one allowed exception, 'none', for disabling all stylesheets
    if(currstyle == '' && title != 'none') {
	createCookie("style",'',-1);
	window.location.reload();
    }
}

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;
}

function updateStyle(title) {
    createCookie("style",title,365);
    setActiveStyleSheet(title);
}

var cookie = readCookie("style");
if (cookie) {
    //setActiveStyleSheet(cookie);
    updateStyle(cookie);
}

