(function(connector) {
  'use strict';

  var iframe;
  var flag;
  var col = 'light';
  //TODO color css
  //TODO abbrechen close anders

  var closeFlag = function(ev) {
    flag.classList.add('closing');
    setTimeout(function() {
      flag.style.opacity = 0;
      setTimeout(function() {
        flag.remove();
      },500);
    },3000);
  }

  var openFlag = function(ev) {
    flag = document.createElement('div');
    flag.id = 'flag-overlay';
    iframe = document.createElement('iframe');
    iframe.src= '';
    iframe.name = 'flag-iframe';
    flag.appendChild(iframe);
    document.body.appendChild(flag);

    var form = document.createElement('form');
    form.action = connector+"?col="+col;
    form.target = 'flag-iframe';
    form.method = 'POST';
    const screenshotTarget = document.body;

    /*html2canvas(screenshotTarget).then((canvas) => {
      const base64image = canvas.toDataURL("image/png");
      window.location.href = base64image;
    });*/
    var fields = {};
    fields['s'] = window.location.hostname;
    if(document.referrer) {fields['r'] = document.referrer;}
    if(window.location.href) {fields['u'] = window.location.href;}
    if(navigator.userAgent) {fields['a'] = navigator.userAgent;}
    fields['d'] = ''+window.screen.width+'x'+window.screen.height+' ('+window.screen.colorDepth+'bit)';

    for(var f in fields) {
      var inp = document.createElement('input');
      inp.type = 'hidden';
      inp.name = f;
      inp.value = fields[f]
      form.appendChild(inp);
    }

    form.style = 'display:none';
    document.body.appendChild(form);
    form.submit();
  }

  var panel = document.createElement('div');
  panel.id = 'flag-panel';

  var tab = document.createElement('span');
  tab.innerHTML = '&#9873;';
  tab.addEventListener('mouseenter',function(ev) {
    if(!panel.classList.contains('opened')) {
      panel.classList.add('opened');
    }
    panel.classList.toggle('open');
  });

  var button = document.createElement('button');

  button.innerHTML = 'Problem melden';
  button.addEventListener('click',openFlag);

  window.addEventListener("message", (event) => {
    //console.log(event);
    if(event.data == 'close') {
      closeFlag();
    }
  });

  var links = document.getElementsByClassName('flag-link');
  if(links.length > 0) {
    for(var l in links) {
      console.log(links);
      links[l].addEventListener('click',function(ev) {
        openFlag(ev);
        ev.preventDefault();
        return false;
      });
    }
  }

  panel.appendChild(tab);
  panel.appendChild(button);

  document.body.appendChild(panel);
})('https://troy-grunt.de/feedback');