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);
    if (arr.length == 10)
      chartAcceptance.xAxis[0].update({categories: ['-5', '-4', '-3', '-2', '-1', '+1', '+2', '+3', '+4', '+5']});
    else if (arr.length == 3)
      chartAcceptance.xAxis[0].update({categories: ['Nein', 'Enthaltung', 'Ja']});
    else throw 'Unknown vote system!';
  } 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;
    default:
      sty.innerHTML = '';
      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('#').shift().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 isInProgram (className, program) {
    let programs = ['grundsatz', 'eu', 'bundestag'];
    if (program == 'alles') return true;
    let spl = className.split(' ');
    let hasProgram = false;
    let hasGivenProgram = false;
    for (let i = 0; i < spl.length; i++) {
      if (programs.includes(spl[i])) hasProgram = true;
      if (spl[i] == program) hasGivenProgram = true;
    }
    return !hasProgram || hasGivenProgram;
  }

  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) {
    if (str == '?')
      return {
        arr: null,
        average: Number.NaN,
        accepted: false
      };
    let arr = str.split(',');
    let accepted = false;
    let average = 0;
    if (arr.length == 10) {
      let nPositiv = 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);
    } else if (arr.length == 3) {
      arr[0] = parseInt(arr[0]);
      arr[1] = parseInt(arr[1]);
      arr[2] = parseInt(arr[2]);
      accepted = arr[0] < arr[2];
      average = (arr[2] - arr[0]) / (arr[0]+arr[1]+arr[2]);
    } else return;
    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 (release && ((el.childNodes[i].tagName.toLowerCase() == 'del') || (!isInProgram(el.childNodes[i].className, makeupForm.selectProgram.value)))) {
          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.arr) el.childNodes[i].className += ' pending';
              else if (acceptance.accepted) el.childNodes[i].className += ' accepted';
              else el.childNodes[i].className += ' rejected';
            }
          }
        }
        str = el.childNodes[i].getAttribute('ref');
        if (release) {
          el.childNodes[i].removeAttribute('ref');
          el.childNodes[i].removeAttribute('date');
          el.childNodes[i].removeAttribute('autor');
        } else if (str !== null && str != '') {
          let a = win.document.createElement('a');
          a.href = str;
          a.textContent = '🗨';
          a.style.position = 'relative';
          a.style.float = 'left';
          a.style.width = '0px';
          a.style.left = '-35px';
          a.style.textDecoration = 'none';
          el.childNodes[i].insertBefore(a, el.childNodes[i].firstChild);
        }
        iterateContent(el.childNodes[i]);
        if ((el.tagName.toLowerCase() == 'div') && ((' '+el.className+' ').indexOf(' thema ') >= 0) && (el.childNodes[i].tagName.toLowerCase() == 'div')) { // Themensektion, anklickbaren Header erzeugen
          let flapoutHeader = document.createElement('div');
          flapoutHeader.className = 'flapout';
          flapoutHeader.setAttribute('onclick', 'toggleFlapout(this)');
          let spl = el.childNodes[i].className.split(' ');
          for (let j = 0; j < spl.length; j++)
            switch (spl[j]) {
              case 'einleitung':
                flapoutHeader.textContent = 'Einleitung in das Thema';
                flapoutHeader.className += ' open';
                el.childNodes[i].className += ' open';
                break;
              case 'problem':
                flapoutHeader.textContent = 'Problembeschreibung';
                break;
              case 'forderungen':
                flapoutHeader.textContent = 'Forderungen';
                flapoutHeader.className += ' open';
                el.childNodes[i].className += ' open';
                break;
              case 'fortschritt':
                flapoutHeader.textContent = 'Fortschritt';
                break;
              case 'beispiel':
                flapoutHeader.textContent = 'Beispiel';
                break;
              case 'kosten':
                flapoutHeader.textContent = 'Kosten';
                break;
              case 'ziel':
                flapoutHeader.textContent = 'Ziel';
                break;
              case 'verteidigung':
                flapoutHeader.textContent = 'Entkräften von Gegenargumenten';
                break;
              case 'relevanz':
                flapoutHeader.textContent = 'Relevanz';
                break;
              case 'quellen':
                flapoutHeader.textContent = 'Weitere Quellen';
                break;
            }
          el.insertBefore(flapoutHeader, el.childNodes[i]);
        }
      }
    }
  }
  iterateContent(win.document.body);
  let scr = document.createElement('script');
  scr.setAttribute('type', 'text/javascript');
  function toggleFlapout (el) {
    let i = 0;
    while (el.parentElement.childNodes[i] != el) i++;
    do
      i++;
    while (el.parentElement.childNodes[i].nodeType != 1);
    let spl = el.parentElement.childNodes[i].className.split(' ');
    let j = spl.indexOf('open');
    if (j >= 0) spl.splice(j, 1);
    else spl.push('open');
    el.parentElement.childNodes[i].className = spl.join(' ');
    spl = el.className.split(' ');
    j = spl.indexOf('open');
    if (j >= 0) spl.splice(j, 1);
    else spl.push('open');
    el.className = spl.join(' ');
  }
  scr.innerHTML = toggleFlapout.toString();
  win.document.body.appendChild(scr);
  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);
};
