// {{{ add_site_css(array_of_stylesheets)
function add_site_css(ss) {

  if(typeof(ss) != 'object')
    ss = new Array(ss);

  // Get list of known stylesheets to see if any in "ss" have already been used
  var knownCSS = new Hash();
  $$('link').each(function(el) {
    if(el.getAttribute('rel') != 'stylesheet') return;
    var href = el.getAttribute('href');
    if(!href) return;
    knownCSS.set(href, 1);
  });

  var newCSSList = new Array();
  $A(ss).each(function(s) {
    if(typeof(s) != 'object')
      s = {href:s};

    if(knownCSS.get(s['href']))
      return;

    newCSSList.push(s);
  });

  if(!newCSSList.length)
    return;

  ss = newCSSList;
  newCSSList = false;
  knownCSS   = false;

  var defstyle;
  var keep = new Array();
  $$('link').each(function(el) {
    if(el.getAttribute('rel') != 'stylesheet') return;
    var href = el.getAttribute('href');
    if(!href) return;

    if(defstyle) {
      // if(href.match('^/html/css/[a-z][a-z_]+.css$')) {
      // This is a link we added throw add_site_css():
      if(el.hasClassName('sitecss')) {
        defstyle = el;
      } else {
        keep.push(el.remove());
      }
    } else if(href.match(new RegExp('/html/(?:css/)?site.css'))) {
      defstyle = el;
    }
  });

  if(!defstyle) {
    defstyle = $$('head')[0].childElements()[0];
    if(!defstyle) {
      defstyle = new Element('title').update('');
      $$('head').appendChild(defstyle);
    }
  }

  $A(ss).each(function(s) {
    if(typeof(s) != 'object') s = {href:s};
    s['type'] = 'text/css';
    s['rel']  = 'stylesheet';
    var link = new Element('link', s);
        link.addClassName('sitecss');
    defstyle.insert({after:link});
    defstyle = link; // So we append after what we just appended
  });

  // Add back the stylesheets we removed:
  defstyle = $$('head')[0];
  keep.each(function(el) { defstyle.appendChild(el); });
} // }}}

// {{{ add_css(array_of_stylesheets)
function add_css(ss) {
  var head = $$('head')[0];

  if(typeof(ss) != 'object') ss = new Array(ss);

  $A(ss).each(function(s) {
    if(typeof(s) != 'object') s = {href:s};
    s = Object.extend(s, { type: 'text/css',
                           rel:  'stylesheet' });
    head.appendChild(new Element('link', s));
  });
} // }}}
