
let doe = document.documentElement;

function probeHref(elms) {
  //console.log("probeHref");
  for (let a of elms) {
    console.debug("probeHref: %s", a.href);
    if(a.getAttribute("aria-disabled"))
      // disabled a priori
      return;
    fetch(a.href)
    .then(function(response) {
      a.classList.remove("probe-2xx");
      if (response.ok)
        return;
      a.setAttribute("aria-disabled",true);
    })
    .catch(function(err) {
      console.error("%s: %s", a.href, err);
    });
  }
}

function toggle() {
  switch(document.cookie) {
  case 'dark':
      document.cookie = 'light';
      break;
  case 'light':
      document.cookie = '';
      break;
  default:
      document.cookie = 'dark';
      break;
  }
  console.log("uhu: %s", document.cookie);
  const lst = doe.classList;
  lst.remove('dark');
  lst.remove('light');
  lst.add(document.cookie);
}

// list tags with font-size in relation to frequency
// https://github.com/sebsauvage/Shaarli/blob/master/index.php#L1254
function computeTagFontsize(tag0) {
  if (!tag0)
    return;
  const fontMin = 8;
  const fontMax = 32;
  var countMaxLog = Math.log(1);
  const tags = tag0.getElementsByTagName('a');
  const counts = new Array(tags.length);
  const log = {};
  for (var i = tags.length - 1; i >= 0; i--) {
    const lbl = tags[i].getElementsByClassName('label')[0].textContent;
    if ('2018-01-15T12:52' == lbl) {
      counts[i] = 1;
      continue;
    }
    const elm = tags[i].getElementsByClassName('count')[0];
    const txt = elm.textContent;
    var v = log[txt];
    if (!v)
      log[txt] = v = Math.log(parseInt(txt, 10));
    counts[i] = v;
    countMaxLog = Math.max(countMaxLog, counts[i]);
  }
  log.length = 0;
  const factor = 1.0 / countMaxLog * (fontMax - fontMin);
  requestAnimationFrame(function() { // http://wilsonpage.co.uk/preventing-layout-thrashing/
    for (var i = tags.length - 1; i >= 0; i--) {
      const k = counts[i];
      var v = log[k];
      if (!v)
        // https://stackoverflow.com/a/3717340
        log[k] = v = Math.ceil(k * factor + fontMin) + 'pt';
      tags[i].style.fontSize = v;
    }
  });
}

// https://varvy.com/pagespeed/defer-images.html
function loadDeferredImages(imgsDefer) {
  // console.log('loadDeferredImages: ' + imgsDefer.length);
  for (var i = imgsDefer.length - 1; i >= 0 ; i--) {
    const v = imgsDefer[i].getAttribute('data-src');
    if (!v)
      continue;
    imgsDefer[i].setAttribute('src', v);
  }
}

// make http and geo URIs (RFC 5870) clickable + microformat
function clickableTextLinks(elmsRendered) {
  // console.log('make http and geo URIs (RFC 5870) clickable + microformat');
  for (var i = elmsRendered.length - 1; i >= 0 ; i--) {
    const elm = elmsRendered[i];
    elm.innerHTML = elm.innerHTML
      .replace(/(https?:\/\/([^ \t\r\n"'<>]+[^ \t\r\n"'.:,;!?!()\[\]\{\}<>]))/gi, '<a rel="noreferrer" class="http" href="$1">$2</a>')
    // https://alanstorm.com/url_regex_explained/ \b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
    // .replace(/\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/gi, '<a rel="noreferrer" class="http" href="$1">$1</a>')
      .replace(/(https?:\/\/(www\.)?(youtu\.be|youtube\.com)\/[^'" ]+)/gi, 'https://mro.name/$1')
      .replace(/geo:(-?\d+.\d+),(-?\d+.\d+)(\?z=(\d+))?/gi, '<a class="geo" href="https://opentopomap.org/#marker=12/$1/$2" title="zoom=$4">geo:<span class="latitude">$1</span>,<span class="longitude">$2</span>$3</a>')
      .replace(/(#RFC(\d+)(#\S*[0-9a-z])?)/gi, '<a class="rfc" href="https://tools.ietf.org/html/rfc$2$3" title="RFC $2">$1</a>')
      .replace(/(urn:ietf:rfc:(\d+)(#\S*[0-9a-z])?)/gi, '<a class="rfc" href="https://tools.ietf.org/html/rfc$2$3" title="RFC $2">$1</a>')
      .replace(/(urn:isbn:([0-9-]+)(#\S*[0-9a-z])?)/gi, '<a class="isbn" href="https://de.wikipedia.org/wiki/Spezial:ISBN-Suche?isbn=$2" title="ISBN $2">$1</a>')
      .replace(/(urn:ean:([0-9-]+)(#\S*[0-9a-z])?)/gi, '<a class="ean" href="https://www.ean-suche.de/?q=$2" title="EAN $2">$1</a>')
      .replace(/(CVE-[0-9-]+-[0-9]+)/gi, '<a class="cve" href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=$1">$1</a>')
      .replace(/(@([a-z0-9._-]+@([a-z0-9_.-]+)))/gi, '<a class="rfc7565" href="' + cgi_url + '/activitypub/actor.xml?resource=acct:$2">$1</a>');
  }
}

function adjustIframeHeight(ifrm) {
  // https://www.dyn-web.com/tutorials/iframes/height/
  function getDocHeight(doc) {
    // stackoverflow.com/questions/1145850/
    const body = doc.body, html = doc.documentElement;
    return Math.max(body.scrollHeight, body.offsetHeight,
      html.clientHeight, html.scrollHeight, html.offsetHeight);
  }

  const doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
  requestAnimationFrame(function() { // http://wilsonpage.co.uk/preventing-layout-thrashing/
    // ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight(doc) + 4 + "px";
    // ifrm.style.visibility = 'visible';
  });
}

doe.classList.add('script-active');
doe.classList.remove('script-inactive');
const cgi_url = doe.getAttribute("data-seppo-cgi-url");
// const xml_base_pub = doe.getAttribute("data-xml-base-pub");
if (! (doe.classList.contains("logged-in") || doe.classList.contains("logged-out")) ) {
  doe.classList.add('logged-out'); // do in js early on load
  // check if we're logged-in (AJAX or Cookie?).
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(data0) {
    if (this.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
      if (this.status === 200) {
        doe.classList.add('logged-in');
        doe.classList.remove('logged-out');
      }
      // store the result locally and use as initial value for later calls to avoid a logged-in flicker?
    }
  }
  xhr.timeout = 1000;
  xhr.open('GET', cgi_url + '/session');
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.send();
}

// onload="document.getElementById('q').removeAttribute('autofocus');document.getElementById('post').setAttribute('autofocus', 'autofocus');"
// onload="document.form_post.post.focus();"

const highlight = "highlight";
const shaded    = "shaded";
// https://stackoverflow.com/a/69934481/349514
const smooth = { block: 'start', behavior: 'smooth'};
window.onpageshow = (event) => {
  const h0 = location.hash.replace(/.*#/,"");
  if(h0 == "")
    return;
  const hi = document.getElementById(h0);
  if(hi == null)
    return;
  if(/^#[0-9]+$/.test(location.hash)) {
    doe.classList.add(shaded);
    hi.classList.add(highlight);
  }
  hi.scrollIntoView(smooth);
};
window.onhashchange = (event) => {
  const ol = document.getElementById(event.oldURL.replace(/.*#/,""));
  ol.classList.remove(highlight);
  const hi = document.getElementById(event.newURL.replace(/.*#/,""));
  if(hi == null) {
    doe.classList.remove(shaded);
    return;
  }
  if(/^#[0-9]+$/.test(location.hash)) {
    doe.classList.add(shaded);
    hi.classList.add(highlight);
  }
  hi.scrollIntoView(smooth);
};

// Firefox 56+ doesn't fire that one in xslt situation: document.addEventListener("DOMContentLoaded", function(event) { console.log("DOM fully loaded and parsed"); });
var addlink;
document.onreadystatechange = function () {
  if(addlink !== undefined)
    return;
  // console.log('setup awesomeplete');
  // inspired by http://leaverou.github.io/awesomplete/#extensibility
  addlink = new Awesomplete('input[data-multiple]', {
    minChars: 3,
    maxItems: 15,
    filter:  function(text, input) { const m = input.match(/#(\S*)$/); return m !== null && Awesomplete.FILTER_CONTAINS(text, m[1]); /* match */ },
    item:    function(text, input) { const m = input.match(/#(\S*)$/); return m !== null && Awesomplete.ITEM(text, m[1]); /* highlight */ },
    replace: function(text) { const inp = this.input; inp.value = inp.value.replace(/#[^#]+$/, text) + " "; },
  });

  const xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE && this.status == 200)
      addlink.list = JSON.parse(this.response);
  };
  xhr.timeout = 1000;
  xhr.open('GET', cgi_url + '/../o/t/index.json');
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.send();

  document.getElementById('q').focus();
  computeTagFontsize(document.getElementById('tags'));
  loadDeferredImages(document.getElementsByTagName('img'));
  clickableTextLinks(document.getElementsByClassName('clickable'));
  probeHref(document.getElementsByClassName("probe-2xx"));
  {
    const ol = document.getElementById('entries').children;
    for (li of ol) {
      const ifrm = li.getElementsByTagName('iframe')[0];
      if (undefined != ifrm)
        ifrm.onload = adjustIframeHeight(ifrm);
    }
  }

 /*
  // https://koddsson.com/posts/emoji-favicon/
  const favicon = document.querySelector("html > head > link[rel=icon]");
  if (favicon) {
    const emoji = favicon.getAttribute("data-emoji");
    if (emoji) {
      const canvas = document.createElement("canvas");
      canvas.height = 64;
      canvas.width = 64;

      const ctx = canvas.getContext("2d");
      ctx.font = "64px serif";
      ctx.fillText(emoji, 0, 56);

      favicon.href = canvas.toDataURL();
    }
  }
 */
};
