/* stylesheet selector */

(function() {
  'strict';

  var valid_stylesheets = {
    'anonymous1': null,
    'anonymous2': null,
    'anonymous3': null
  };

  function set_sheet(sheet) {
    // sets the current stylesheet
    var active_stylesheet = document.getElementById('active_stylesheet');
    active_stylesheet.setAttribute('href', '/stylesheets/'+sheet+'.css');
  }

  function change_stylesheet() {
    // sets the current stylesheet to the current value of the stylesheet selector
    var selector = document.getElementById('sheet_selector');
    var selected_stylesheet = selector.options[selector.selectedIndex].value;
    set_sheet(selected_stylesheet);

    // set cookie
    var expiration = new Date();
    // expire a year from now
    expiration.setTime(expiration.getTime() + 365*24*60*60*1000);
    var cookie = 'stylesheet='+selected_stylesheet+'; expires='+expiration.toUTCString()+'; path=/';
    document.cookie = cookie;
  }

  function add_selector() {
    var selector_div = document.getElementById('sheet_selector_div');

    var selector = document.createElement('select');
    selector.id = 'sheet_selector';

    for (var sheet in valid_stylesheets) {
      var option = document.createElement('option');
      option.value = sheet;
      option.innerHTML = sheet;
      selector.appendChild(option);
    }

    selector.addEventListener('change', change_stylesheet);

    selector_div.appendChild(document.createTextNode('style: '));
    selector_div.appendChild(selector);

    // sync selector option to current stylesheet
    var active_stylesheet = document.getElementById('active_stylesheet');
    var match = /stylesheets\/(.*)\.css+$/.exec(active_stylesheet.href);
    if (!match) return;
    var current_sheet = match[1];
    if (current_sheet in valid_stylesheets) {
      selector.value=current_sheet;
    }
  }

  document.addEventListener('DOMContentLoaded', add_selector);
}());
