// Style Sheet Switcher version 1.1 Oct 10th, 2006
// Original Author: Dynamic Drive: http://www.dynamicdrive.com
// Usage terms: http://www.dynamicdrive.com/notice.htm

//
// cookie functions
//

function getCookie(Name) {
  var re = new RegExp(Name + "=[^;]+", "i"); //construct RE to search for target name/value pair
  if (document.cookie.match(re)) //if cookie found
    return document.cookie.match(re)[0].split("=")[1] //return its value
  return null
}

function setCookie(name, value, days) {
  //console.log('setting', name, value, days);
  var expireDate=new Date()
      //set "expstring" to either future or past date, to set or delete cookie, respectively
  var expstring=(typeof days!="undefined")?expireDate.setDate(expireDate.getDate()+parseInt(days)):expireDate.setDate(expireDate.getDate()-5)
  document.cookie=name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}

function deleteCookie(name) {
  setCookie(name, "", -1)
}

//
// Setting functions (localStorage with cookie fallbacK)
//

function getSetting(Name) {
  if (typeof(Storage) !== "undefined") {
    return localStorage.getItem(Name);
  }
  var re = new RegExp(Name + "=[^;]+", "i"); //construct RE to search for target name/value pair
  if (document.cookie.match(re)) //if cookie found
    return document.cookie.match(re)[0].split("=")[1] //return its value
  return null
}

function setSetting(name, value, days) {
  //console.log('setting', name, value, days);
  if (typeof(Storage) !== "undefined") {
    localStorage.setItem(name, value)
  } else {
    var expireDate=new Date()
        //set "expstring" to either future or past date, to set or delete cookie, respectively
    var expstring=(typeof days!="undefined")?expireDate.setDate(expireDate.getDate()+parseInt(days)):expireDate.setDate(expireDate.getDate()-5)
    document.cookie=name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
  }
}

function deleteSetting(name) {
  if (typeof(Storage) !== "undefined") {
    localStorage.removeItem(name);
  }
  // can't hurt to clear both
  setCookie(name, "", -1)
}

// Try to migrate cookies to localStorage
function convertCookies() {
  var cookies=['endchan_favorites', 'endchan_nsfwRecentImage', 'eos_boardfilter', 'eos_useFav',
    'myAutoRefresh', 'myHideDel', 'myUseLocalTime', 'myUseMegud', 'mylayout', 'mysheet']
  var days=365*10; // remember this settings for 10 years

  for(var i in cookies) {
    var cname=cookies[i]
    var cval=getCookie(cname)
    // cookie always stomps localSettings
    deleteCookie(cname) // can't do this after setSetting because it may set a cookie and you'd lose the setting
    if (cval!==null) {
      setSetting(cname, cval, days)
    }
  }

  // read all cookies
  var cookieParts = document.cookie.split(";")
  for (var i = 0; i < cookieParts.length; i++) {
    var name_value = cookieParts[i],
        equals_pos = name_value.indexOf("="),
        name       = unescape( name_value.slice(0, equals_pos) ).trim(),
        value      = unescape( name_value.slice(equals_pos + 1) );
    // is this a showHide cookie
    if (name.substr(0, 4)==='hide') {
      deleteCookie(name)
      setSetting(name, value, days)
    }
  }
}

function getMyPosts() {
  var postsMade=getSetting('myPosts')
  var myPosts
  try {
    myPosts=JSON.parse(postsMade)
  } catch (e) {
    console.log('failed to parse', postsMade)
    myPosts=[]
  }
  if (myPosts===null) myPosts=[]
  return myPosts
}

//
// selectors
//

function setStylesheet(title, type, randomize) { //Main stylesheet switcher function. Second parameter if defined causes a random alternate stylesheet (including none) to be enabled
  var i, cacheobj, altsheets = [""]
  //console.log('got', document.getElementsByTagName("link").length);
  /*
  for (i = 0;
    (cacheobj = document.getElementsByTagName("link")[i]); i++) {
    //console.log('rel', cacheobj.getAttribute("rel").toLowerCase(), '==', type, 'title', cacheobj.getAttribute("title"));
    if (cacheobj.getAttribute("rel").toLowerCase() == type+" stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title
      cacheobj.disabled = true
      altsheets.push(cacheobj) //store reference to alt stylesheets inside array
      //console.log(cacheobj.getAttribute("title"), '==', title);
      if (cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter
        cacheobj.disabled = false //enable chosen style sheet
    }
  }
  */
  var customCssElem=document.getElementById('custom'+type+'StyleSheet');
  if (title) {
    customCssElem.href="/.static/themes/"+type+"s/"+title.toLowerCase()+"_"+type+"s.css";
    customCssElem.disabled=false;
  } else {
    customCssElem.href="";
    customCssElem.disabled=true;
  }

  /*
  if (typeof randomize != "undefined") { //if second paramter is defined, randomly enable an alt style sheet (includes non)
    var randomnumber = Math.floor(Math.random() * altsheets.length)
    altsheets[randomnumber].disabled = false
  }
  */
  return (typeof randomize != "undefined" && altsheets[randomnumber] != "") ? altsheets[randomnumber].getAttribute("title") : "" //if in "random" mode, return "title" of randomly enabled alt stylesheet
}

// layout/color
function chooseStyle(styletitle, type) { //Interface function to switch style sheets plus save "title" attr of selected stylesheet to cookie
  var days=365*10; // remember this setting for 10 years
  if (document.getElementById) {
    setStylesheet(styletitle, type)
    if (type==="layout") {
      setSetting("mylayout", styletitle, days)
    } else {
      setSetting("mysheet", styletitle, days)
    }
  }
}

/*
function indicateSelected(element) { //Optional function that shows which style sheet is currently selected within group of radio buttons or select menu
  if (selectedtitle != null && (element.type == undefined || element.type == "select-one")) { //if element is a radio button or select menu
    var element = (element.type == "select-one") ? element.options : element
    for (var i = 0; i < element.length; i++) {
      if (element[i].value == selectedtitle) { //if match found between form element value and cookie value
        if (element[i].tagName == "OPTION") //if this is a select menu
          element[i].selected = true
        else //else if it's a radio button
          element[i].checked = true
        break
      }
    }
  }
}
*/


//
// Management
//

var sheets={
  'layout': [
    'Darkend',
    'Center',
    'NaggerDeath',
    'EndGD',
    'KC',
    'Yotsuba B',
    '2ch',
  ],
  'color': [
    'Darkend',
    'DarkDili',
    'Tomorrow',
    'Yotsuba',
    'Yotsuba B',
    'EndGD',
    '2ch',
  ],
};

function buildSheets(type, def) {
  var helem=document.querySelector('head');
  /*
  for(var i in sheets[type]) {
    var file=sheets[type][i];
    var sheet=document.createElement('link');
    sheet.rel=type+' stylesheet';
    sheet.type='text/css';
    sheet.href="/.static/themes/"+type+"s/"+file.toLowerCase()+"_"+type+"s.css";
    sheet.title=file;
    // chrome glitches if you don't add them disabled
    sheet.disabled=true;
    //console.log('initialized', type, file);
    helem.appendChild(sheet);
  }
  */
  var sheet=document.createElement('link');
  sheet.rel=type+' stylesheet';
  sheet.type='text/css';
  sheet.id='custom'+type+'StyleSheet';
  sheet.disabled=true;
  if (def) {
    var tdef=def.toLowerCase()
    tdef=tdef.replace(/ /g, '_')
    sheet.href="/.static/themes/"+type+"s/"+tdef+"_"+type+"s.css";
  }
  sheet.title='User selected '+type+' style sheet';
  // chrome glitches if you don't add them disabled
  //sheet.disabled=true;
  helem.appendChild(sheet);
  if (def) {
    sheet.disabled=false;
  }
}

convertCookies()
var selectedlayout = getSetting("mylayout")
var selectedcolor = getSetting("mysheet")
buildSheets('layout', selectedlayout);
buildSheets('color', selectedcolor);

function buildSelect(type) {
  var selem=document.querySelector('select[name=switch'+type+'control]');
  if (!selem) {
    console.log('no', type, 'select');
    return;
  }
  //console.log(altsheets);
  var opt=document.createElement('option');
  var titletype=type;
  titletype[0]=titletype[0].toUpperCase();
  opt.value='';
  opt.appendChild(document.createTextNode(titletype));
  selem.appendChild(opt);
  opt=document.createElement('option');
  opt.value='';
  opt.appendChild(document.createTextNode('Default/none'));
  selem.appendChild(opt);

  for(var i in sheets[type]) {
    //===undefined?'None':altsheets[i].title
    var title=sheets[type][i];
    //console.log('registering', type, title);
    var opt=document.createElement('option');
    opt.value=title;
    if (type==='layout') {
      //console.log(type, selectedlayout, '==', title);
      if (selectedlayout===title) {
        //opt.selected=true;
        title=title+'*';
      }
    } else {
      //console.log(type, selectedtitle, '==', title);
      if (selectedcolor===title) {
        //opt.selected=true;
        title=title+'*';
      }
    }
    if (opt.selected) console.log('selected');
    opt.appendChild(document.createTextNode(title));
    selem.appendChild(opt);
  }
}

document.addEventListener("DOMContentLoaded", function(event) {
  // shouldn't need this hack any more
  /*
  var images = document.querySelectorAll('img')
  //console.log('found', images.length, images)
  for(var i = 0; i < images.length; i++) {
    var image = images[i]
    image.onerror = function() {
      console.log('error loading', this.src, 'removing')
      this.remove()
    }
  }
  */
  var c=document.querySelector('select[name=switchlayoutcontrol]');
  if (c) {
    buildSelect('layout');
    buildSelect('color');
  }
});

//
// Do shit
//


/*
console.log('layout is', selectedlayout);
if (selectedlayout != null) {
  //load user chosen style sheet from cookie if there is one stored
  setStylesheet(selectedlayout, "layout")
} else {
  // need to disable all additional layouts
  setStylesheet('none', "layout")
}

console.log('color is', selectedcolor);
if (selectedcolor != null) {
  //load user chosen style sheet from cookie if there is one stored
  setStylesheet(selectedcolor, "color")
} else {
  // need to disable all additional colors
  setStylesheet('none', "color")
}
*/

// font sizes can be dealt with zoom
// font choices can be managed through user style sheets