// stylesheet switcher code, slightly adapted from Paul Sowden's code at
// a list apart (http://www.alistapart.com/articles/alternate/)
// (needs horus.js and cookie.js loaded)

horus.stylesheet={
  set:
    function (title, opt) {
      var links=document.getElementsByTagName("link");

      for (var i=0; i<links.length; i++) {
	var link=links[i];
	var linktitle=link.getAttribute("title");

	if (link.getAttribute("rel").indexOf("style")>=0 && linktitle) {
	  link.disabled=true;
	  if (linktitle==title) link.disabled=false;
	}
      }

      if (!opt || opt!='RELOAD') {
	// do we have a menu to reset?
	if (opt) opt.resetposition();

	// why this nasty hackish stuff?
	//
	// 1. we need to reload the page because IE/Mac screws up rendering from the
	//    new stylesheet otherwise.
	//
	// 2. Opera 7 doesn't seem to store the new stylesheet cookie value unless and
	//    until the document is changed to another with a different URL (replacing
	//    the current URL with a variant doesn't do it - possibly linked to history
	//    processing?)
	//
	// As a standards-compliance aside, I use '&' rather than ';' as the CGI param
	// separator because ColdFusion is broken and doesn't recognise ';' as it
	// should.
	//
	if (horus.opera) {
	  var href=window.location.href;

	  if (href.search(/[?&;]_ss_=_ss_/)<0)
	    href+=(href.search(/\?/)<0 ? '?' : '&')+'_ss_=_ss_';
	  else if (href.search(/\?_ss_=_ss_$/)<0)
	    href=href.replace(/[&;]?_ss_=_ss_$/, '');
	  else
	    href=href.replace(/\?_ss_=_ss_$/, '');

	  setTimeout(function () { window.location.href=href }, 50);
	} else
	  if (horus.iemac || opt)
	    window.location.reload(true);
	  else
	    horus.matchheight();

      }
    },

  get:
    function () {
      var links=document.getElementsByTagName("link");

      for (var i=0; i<links.length; i++) {
	var link=links[i];
	var linktitle=link.getAttribute("title");

	if (link.getAttribute("rel").indexOf("style")>=0 && linktitle && !link.disabled)
	  return linktitle;

      }

      return null;
    },

  preferred:
    function () {
      var links=document.getElementsByTagName("link");

      for (var i=0; i<links.length; i++) {
	var link=links[i];
	var linkrel=link.getAttribute("rel");
	var linktitle=link.getAttribute("title");

	if (linkrel.indexOf("style")>=0 && linkrel.indexOf("alt")<0 && linktitle)
	  return linktitle;

      }

      return null;
    },

  load:
    function () {
      var cookie=horus.cookie('style');
      var title=cookie ? cookie : horus.stylesheet.preferred();
      horus.stylesheet.set(title, 'RELOAD');
    },

  save:
    function () {
      var title = horus.stylesheet.get();
      if (title) horus.cookie('style', title, 365);
    }

};

horus.stylesheet.load();
horus.afterload(horus.stylesheet.load);
horus.eventListener(window, 'unload', horus.stylesheet.save);
