var defaultHeaderImage = (function () {
  let box = document.getElementById('BoxTop');
  for (let i = 0; i < box.getElementsByTagName('div').length; i++)
    if ((' '+box.getElementsByTagName('div')[i].className+' ').indexOf('bgImage') >= 0) {
      let spl = box.getElementsByTagName('div')[i].style.backgroundImage.split('"');
      if (spl.length == 3)
        return absolutePath(spl[1], self.location.href);
      break;
    }
  return '';
})();
var currentHeaderImage = defaultHeaderImage;
function loadHeader (src, vPos='center', loadWithoutEffect=false) {
  if (src == currentHeaderImage) return;
  currentHeaderImage = src;
  if (vPos == '')
    vPos = 'center';
  var img = new Image();
  img.onload = function () {
    var op = 0;
    var oldEl = null;
    var newEl = document.createElement('div');
    var box = document.getElementById('BoxTop');
    newEl.className = 'bgImage';
    if (vPos)
      newEl.style.backgroundPosition = 'center '+vPos;
    newEl.style.backgroundImage = "url('"+img.src+"')";
    for (let i = box.getElementsByTagName('div').length-1; i >= 0; i--)
      if ((' '+box.getElementsByTagName('div')[i].className+' ').indexOf('bgImage') >= 0) {
        oldEl = box.getElementsByTagName('div')[i];
        break;
      }
    if (oldEl) {
      newEl.style.opacity = 0;
      box.insertBefore(newEl, oldEl.nextSibling);
      if (loadWithoutEffect) {
        newEl.style.opacity = 1;
        box.removeChild(oldEl);
        return;
      }
    } else {
      box.insertBefore(newEl, box.firstChild);
      return;
    }
    var tmr = window.setInterval(function () {
      op += 0.01;
      if (op >= 1) {
        newEl.style.opacity = 1;
        box.removeChild(oldEl);
        img = null;
        window.clearInterval(tmr);
      } else
        newEl.style.opacity = op;
    }, 10);
  };
  img.src = src;
}
function searchHeaderImage (site, loadWithoutEffect) {
  try {
    let meta = site.document.getElementsByTagName('head')[0].getElementsByTagName('meta');
    for (let i = 0; i < meta.length; i++)
      if (meta[i].getAttribute('property') == 'og:image') {
        let newPath = absolutePath(meta[i].getAttribute('content'), site.location.href);
        if (currentHeaderImage != newPath)
          loadHeader(newPath, meta[i].getAttribute('position'), loadWithoutEffect);
        return;
      }
  } catch (e) { }
  loadHeader(defaultHeaderImage, loadWithoutEffect);
}
