var freeFetchedText = null;
var makeupForm = null;
var chartAcceptanceData = null;
var chartAcceptance = null;
function createAcceptanceChart (id) {
  chartAcceptance = Highcharts.chart(id, {
    chart: {
      type: 'column'
    },
    yAxis: {
      title: {
        enabled: false
      }
    },
    xAxis: {
      categories: ['-5', '-4', '-3', '-2', '-1', '+1', '+2', '+3', '+4', '+5']
    },
    legend:{ enabled:false },
    title: {
      text: 'Zustimmung'
    },
    series: [
      {
        name: 'Umfrage, erste Iteration',
        color: 'black',
        data: [5,8,1,10,3,3,2,6,3,2]
      }
    ],
  });
};
window.showAcceptance = function (arr) {
  if (arr && makeupForm.showAcceptance.checked) {
    document.getElementById('Acceptance').style.display = 'block';
    if (arr == chartAcceptanceData) return;
    chartAcceptanceData = arr;
    chartAcceptance.series[0].setData(arr);
  } else if (document.getElementById('Acceptance'))
    document.getElementById('Acceptance').style.display = 'none';
};

function setMakeupForm (el, showingRelease) {
  makeupForm = el;
  if (showingRelease) {
    makeupForm.showingRelease = true;
    makeupForm.showComments.checked = false;
    makeupForm.showAccepted.checked = false;
    makeupForm.showDeletedContent.checked = false;
    makeupForm.showAcceptance.checked = false;
  }
  let inp = el.getElementsByTagName('input');
  for (let i = 0; i < inp.length; i++)
    inp[i].addEventListener('input', function () {
      makeupText(currentSite);
    }, false);
  el.genderSelect.addEventListener('input', function () {
    makeupText(currentSite);
  }, false);
  el.selectProgram.addEventListener('input', function () {
    filterProgram(currentSite);
  }, false);
  el.createRelease.addEventListener('click', function () {
    makeupForm.isRelease = true;
    dynFrame.getActiveCommunicator().el.src += ''; // reload
    el.createRelease.disabled = true;
  }, false);
}

function filterProgram (win) {
  let head = win.document.getElementsByTagName('head')[0];
  let sty = win.document.getElementById('programFilter');
  if (!sty) {
    sty = win.document.createElement('style');
    sty.setAttribute('type', 'text\/css');
    sty.setAttribute('id', 'programFilter');
    head.appendChild(sty);
  }
  switch (makeupForm.selectProgram.value) {
    case 'grundsatz':
      sty.innerHTML = '.eu { display: none; }'+"\n"
                     +'.bundestag { display: none; }';
      break;
    case 'eu':
      sty.innerHTML = '.grundsatz { display: none; }'+"\n"
                     +'.bundestag { display: none; }';
      break;
    case 'bundestag':
      sty.innerHTML = '.eu { display: none; }'+"\n"
                     +'.grundsatz { display: none; }';
      break;
  }
}

function makeupText (win) {
  let sty = win.document.getElementById('makeupStyle');
  if (!sty) {
    sty = win.document.createElement('style');
    sty.setAttribute('id', 'makeupStyle');
    win.document.getElementsByTagName('head')[0].appendChild(sty);
  }
  let css = '';
  if (makeupForm.showComments.checked) css += "body { padding-right:250px; }\n";
  else css += "commentnote { display: none; }\n";
  if (makeupForm.showAccepted.checked)
    css += ""
      +".accepted, commentnote.accepted div {\n"
      +" background-color: #CFC;\n"
      +"}\n"
      +".rejected, commentnote.rejected div {\n"
      +" background-color: #FCC;\n"
      +"}\n";
  switch (makeupForm.genderSelect.selectedIndex) {
    case 0:
      css += ""
        +".end-f::after { content: 'innen'; }\n"
        +".end-m::before { content: ' und '; }\n"
        +".or.end-m::before { content: ' oder '; }\n"
        +".dash.end-m::before { content: '- und '; }\n";
      break;
    case 1:
      css += ""
        +".end-f::after { content: '*innen'; }\n"
        +".end-m { display: none; }\n";
      break;
    case 2:
      css += ""
        +".end-f::after { content: ':innen'; }\n"
        +".end-m { display: none; }\n";
      break;
    case 3:
      css += ""
        +".end-f::after { content: 'Innen'; }\n"
        +".end-m { display: none; }\n";
      break;
    case 4:
      css += ""
        +".end-f { display: none; }\n";
      break;
    case 5:
      css += ""
        +".end-f::after { content: 'innen'; }\n"
        +".end-m { display: none; }\n";
      break;
  }
  if (!makeupForm.showDeletedContent.checked) css += "del, .rejected { display: none; }\n";
  sty.innerHTML = css;
}

function fetchText (win) {
  let query = window.location.href.split('?').pop().split('&');
  for (let i = 0; i < query.length; i++) {
    query[i] = query[i].split('=');
    if (query[i].length == 2 && query[i][0] == 'program') {
      makeupForm.selectProgram.value = query[i][1];
    }
  }
  if (makeupForm.showingRelease) {
    makeupText(win);
    return;
  }
  if (freeFetchedText) freeFetchedText();
  var counterComments = 0;
  var release = false;
  if (makeupForm.isRelease) release = true;

  function deleteElementExtra (el) { // deletes an element from parent and in some special cases also recursively the parent, if it is empty afterwards.
    let p = el.parentElement;
    p.removeChild(el);
    let empty = true;
    for (let i = 0; i < p.childNodes.length; i++) {
      if (p.childNodes[i].nodeType == 1) {
        empty = false;
        break;
      }
      if (p.childNodes[i].nodeType == 3) {
        let str = p.childNodes[i].textContent;
        if (str.split(' ').join('').split("\n").join('') != '') {
          empty = false;
          break;
        }
      }
    }
    if (empty && (p.tagName.toLowerCase() == 'p' || p.tagName.toLowerCase() == 'h1' || p.tagName.toLowerCase() == 'h2' || p.tagName.toLowerCase() == 'h3' || p.tagName.toLowerCase() == 'li' || p.tagName.toLowerCase() == 'ul' || p.tagName.toLowerCase() == 'ol'))
      deleteElementExtra(p);
  }

  function interpretAcceptance (str) {
    let arr = str.split(',');
    if (arr.length != 10) return null;
    let accepted = false;
    let nPositiv = 0;
    let average = 0;
    let sum = 0;
    for (let j = 0; j < 10; j++) {
      arr[j] = parseInt(arr[j]);
      sum += arr[j];
      if (j < 5) {
        average += arr[j] * (j-5);
      } else {
        nPositiv += arr[j];
        average += arr[j] * (j-4);
      }
    }
    average /= sum;
    accepted = (average > 0) && (nPositiv >= sum / 3 * 2);
    return {
      arr: arr,
      average: average,
      accepted: accepted
    };
  }

  function iterateContent (el) {
    for (let i = el.childNodes.length-1; i >= 0; i--) {
      if (el.childNodes[i].nodeType == 8) { // comments
        if (release) {
          el.removeChild(el.childNodes[i]);
          continue;
        } else { // convert comment to element
          let insertEl = win.document.createElement('commentnote');
          let textbox = win.document.createElement('div');
          textbox.style.top = (counterComments % 3 - 2) * 0.4 + 'em';
          counterComments++;
          textbox.textContent = el.childNodes[i].nodeValue.trim();
          if (textbox.textContent.indexOf('Überarbeitung:') == 0) insertEl.className += ' redaction';
          insertEl.appendChild(textbox);
          el.insertBefore(insertEl, el.childNodes[i]);
          el.removeChild(el.childNodes[i+1]);
          if (textbox.textContent.indexOf('zustimmung="') == 0) {
            let zuEnd = textbox.textContent.indexOf('"', 12);
            insertEl.setAttribute('zustimmung', textbox.textContent.substring(12, zuEnd));
            textbox.textContent = textbox.textContent.substring(zuEnd+2, textbox.textContent.length);
          }
        }
      }
      if (el.childNodes[i].nodeType == 1) { // elements
        if (el.childNodes[i].tagName.toLowerCase() == 'del' && release) {
          deleteElementExtra(el.childNodes[i]);
          continue;
        }
        let str = el.childNodes[i].getAttribute('zustimmung');
        if (str !== null && str != '') {
          let acceptance = interpretAcceptance(str);
          if (acceptance) {
            el.childNodes[i].acceptance = acceptance;
            if (!acceptance.accepted && release) {
              deleteElementExtra(el.childNodes[i]);
              continue;
            }
            if (release)
              el.childNodes[i].removeAttribute('zustimmung');
            else {
              if (acceptance.accepted) el.childNodes[i].className += ' accepted';
              else el.childNodes[i].className += ' rejected';
            }
          }
        }
        iterateContent(el.childNodes[i]);
      }
    }
  }
  iterateContent(win.document.body);
  if (release) {
    document.getElementById('Codeblock').textContent = win.document.body.innerHTML;
    document.getElementById('Codeblock').style.display = 'block';
  } else 
    win.addEventListener('mousemove', function (ev) {
      let el = ev.target;
      let arr = null;
      while (el)
        if (el.acceptance) {
          arr = el.acceptance.arr;
          break;
        } else el = el.parentElement;
      parent.showAcceptance(arr);
    }, false);
  makeupText(win);
  filterProgram(win);

  /*
  if (!document.getElementById('loadTextBranch').checked) return;
  var backup = win.document.createElement('div');
  backup.getElementById = function (id) {
    var el = null;
    function searchId (p) {
      for (let i = 0; i < p.childNodes.length; i++)
        if (p.childNodes[i].nodeType == 1)
          if (p.childNodes[i].id == id) {
            el = p.childNodes[i];
            return;
          } else searchId(p.childNodes[i]);
    }
    searchId(backup);
    return el;
  };
  while (win.document.body.firstChild)
    backup.appendChild(win.document.body.firstChild);
  if (backup.getElementById('footer')) win.document.body.appendChild(backup.getElementById('footer'));
  win.document.body.className += ' commented';
  var release = false;
  if (window.location.href.indexOf('generateFinalHTML') >= 0) release = true;
  var counterComments = 0;
  freeFetchedText = function () {
    counterComments = 0;
    backup = null;
  }
  function scanEmbeddings (el) {
    let childs = new Array();
    for (let i = 0; i < el.childNodes.length; i++)
      childs.push(el.childNodes[i]);
    for (let i = 0; i < childs.length; i++)
      if (childs[i].nodeType == 1) scanEmbeddings(childs[i]);
      else if (childs[i].nodeType == 3) {
        let pos = 0;
        let lastReplacePos = 0;
        let replaceArr = new Array();
        while (pos < childs[i].textContent.length) {
          let start = childs[i].textContent.indexOf('[', pos);
          let stop = childs[i].textContent.indexOf(']', pos);
          if (stop >= 0) pos = stop+1;
          else {
            if (lastReplacePos > 0) replaceArr.push(win.document.createTextNode(childs[i].textContent.substring(lastReplacePos, childs[i].textContent.length)));
            break;
          }
          if (start >= 0 && start < stop) {
            let shortcode = childs[i].textContent.substring(start+1, stop);
            let insertEl = null;
            if (shortcode.toLowerCase().indexOf('quelle: ') == 0) {
              insertEl = win.document.createElement('footnote');
              let p = shortcode.indexOf(' #');
              if (p > 0 && shortcode.indexOf(' ##') == p) {
                let notename = shortcode.substring(p+3, (shortcode.indexOf(' ', p+3) >= 0)?shortcode.indexOf(' ', p+3):shortcode.length);
                insertEl.setAttribute('noteref', notename);
              } else {
                if (p > 0) {
                  let notename = shortcode.substring(p+2, (shortcode.indexOf(' ', p+2) >= 0)?shortcode.indexOf(' ', p+2):shortcode.length);
                  insertEl.setAttribute('notename', notename);
                  shortcode = shortcode.substring(0, p) + shortcode.substring(p+1+notename.length, shortcode.length);
                }
                insertEl.textContent = shortcode.substring(8, shortcode.length);
              }
            } else if (shortcode.toLowerCase().indexOf('kommentar: ') == 0) {
              insertEl = win.document.createElement('commentnote');
              let textbox = win.document.createElement('div');
              textbox.style.top = (counterComments % 3 - 2) * 0.4 + 'em';
              counterComments++;
              textbox.textContent = shortcode.substring(11, shortcode.length);
              if (textbox.textContent.indexOf('Überarbeitung:') == 0) insertEl.className += ' redaction';
              insertEl.appendChild(textbox);
            } else if (shortcode.toLowerCase().indexOf('zustimmung: ') == 0) {
              insertEl = win.document.createElement('acceptance');
              insertEl.textContent = shortcode.substring(12, shortcode.length);
            } else insertEl = backup.getElementById(shortcode);
            if (insertEl) {
              replaceArr.push(win.document.createTextNode(childs[i].textContent.substring(lastReplacePos, start)));
              replaceArr.push(insertEl);
              lastReplacePos = pos;
            }
          }
        }
        if (lastReplacePos > 0) {
          while (replaceArr.length > 0)
            el.insertBefore(replaceArr.shift(), childs[i]);
          el.removeChild(childs[i]);
        }
      }
  }
  var srcFile = win.document.getElementsByTagName('title')[0].textContent; //win.document.body.getAttribute('textsource');
  if (!srcFile) return;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let md = new Remarkable();
      let div = win.document.createElement('div');
      div.innerHTML = md.render(xhttp.responseText);
      scanEmbeddings(div);
      for (let i = div.childNodes.length-1; i >= 0; i--)
        win.document.body.insertBefore(div.childNodes[i], win.document.body.firstChild);
    }
  };
  let branch = 'master';
  if (document.getElementById('branchSelect'))
    branch = document.getElementById('branchSelect').value;
  let textPath = 'https:\/\/klimaliste-darmstadt-dieburg.de\/system\/php\/cors.php?path='+branch+'\/'+srcFile+'.txt&rand='+Math.round(Math.random()*10000000);
  if (win.location.href.indexOf('file:\/\/\/') == 0) textPath = '..\/text\/'+srcFile+'.txt';
  xhttp.open("GET", textPath, false);
  xhttp.send();

  let z = win.document.getElementsByTagName('acceptance');
  for (let i = 0; i < z.length; i++) {
    let arr = z[i].textContent.split(',');
    let accepted = false;
    if (arr.length == 10) {
      let nPositiv = 0;
      let average = 0;
      let sum = 0;
      for (let j = 0; j < 10; j++) {
        arr[j] = parseInt(arr[j]);
        sum += arr[j];
        if (j < 5) {
          average += arr[j] * (j-5);
        } else {
          nPositiv += arr[j];
          average += arr[j] * (j-4);
        }
      }
      z[i].arr = arr;
      average /= sum;
      accepted = (average > 0) && (nPositiv >= sum / 3 * 2);
      z[i].average = average;
    }
    z[i].accepted = accepted;
    z[i].textContent = '';
    let target = z[i].parentElement;
    if (target == win.document.body || target.acceptance) target = z[i].nextElementSibling;
    if (target) {
      target.acceptance = z[i];
      if (target.nodeType == 1) target.setAttribute('zustimmung', z[i].arr.join(','));
      if (release) {
        //if (!accepted) target.parentElement.removeChild(target);
      } else {
        if (accepted) target.className += ' accepted';
        else target.className = ' rejected';
      }
    }
  }
  if (release) {
    let comments = win.document.getElementsByTagName('commentnote');
    for (let i = comments.length-1; i >= 0; i--) {
      var a = '';
      if (comments[i].acceptance) a = 'zustimmung="'+comments[i].acceptance.arr.join(',')+'" ';
      let comment = document.createComment(' '+a+comments[i].textContent+' ');
      comments[i].parentElement.insertBefore(comment, comments[i]);
      comments[i].parentElement.removeChild(comments[i]);
    }
    while (win.document.getElementsByTagName('acceptance').length > 0)
      win.document.getElementsByTagName('acceptance')[0].parentElement.removeChild(win.document.getElementsByTagName('acceptance')[0]);
    //while (win.document.getElementsByTagName('del').length > 0)
    //  win.document.getElementsByTagName('del')[0].parentElement.removeChild(win.document.getElementsByTagName('del')[0]);
    document.getElementById('Codeblock').textContent = win.document.body.innerHTML;
    document.getElementById('Codeblock').style.display = 'block';
  } else
    win.addEventListener('mousemove', function (ev) {
      let el = ev.target;
      let arr = null;
      while (el)
        if (el.acceptance) {
          arr = el.acceptance.arr;
          break;
        } else el = el.parentElement;
      parent.showAcceptance(arr);
    }, false);
  */
};
