function fitStageIntoParentContainer() {
  
    var container = document.querySelector('#stage-parent');

    // now we need to fit stage into parent
    var containerWidth = container.offsetWidth;
    // to do this we need to scale the stage
    var scale = containerWidth / stageWidth;

    // stage. und layer. Test

    stage.width(stageWidth * scale);
    stage.height(stageHeight * scale);
    stage.scale({ x: scale, y: scale });

      stage.on('wheel', (e) => {
        //getConditions()
        e.evt.preventDefault();
        var oldScale = stage.scaleX();

        var pointer = stage.getPointerPosition();

        var mousePointTo = {
          x: (pointer.x - stage.x()) / oldScale,
          y: (pointer.y - stage.y()) / oldScale,
        };

        newScale = e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy; // Mouse Wheel Richtung > oder <
        scaleRatio = newScale;
        localStorage.setItem('zoomStage', newScale);
        //console.log("Scale Wert: "+scaleRatio+" x: "+stage.x() +" y: "+stage.y());

        //console.log("Pointer Wert  x: "+pointer.x+" y: "+pointer.y);
        if (newScale > 0.20 && newScale < 150){
          stage.scale({ x: newScale, y: newScale });
          //console.log("ZOOM");
        var newPos = {
          x: pointer.x - mousePointTo.x * newScale,
          y: pointer.y - mousePointTo.y * newScale,
        };

        stage.position(newPos);
        var pos = JSON.stringify(stage.position());
        localStorage.setItem("Position",pos);
        if(newScale <= 10 && big === 0) {
          big = 1;
          setConditions();
        }
        if(newScale > 10 && big === 1) {
          big = 0;
          setConditions();
        }
        }

        layer.batchDraw();      
      });
    
}

function fitStageReset() {
    localStorage.removeItem('xStage');
    localStorage.removeItem('yStage');
    localStorage.removeItem('Position');
    localStorage.removeItem('Scale');
    localStorage.removeItem('zoomStage');
    localStorage.removeItem('AbsolutePosition');
    location.reload();    
}

function getStageData() {
    localStorage.removeItem('xStage');
    localStorage.removeItem('yStage');
    localStorage.removeItem('Position');
    localStorage.removeItem('Scale');
    localStorage.removeItem('zoomStage');
    localStorage.removeItem('AbsolutePosition');
    location.reload();   
}

fitStageIntoParentContainer();
// adapt the stage on any window resize
window.addEventListener('resize', fitStageIntoParentContainer);

function getDistance(p1, p2) {
    return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}

function getCenter(p1, p2) {
      return {
        x: (p1.x + p2.x) / 2,
        y: (p1.y + p2.y) / 2,
      };
}

function stageTouchController(){
    var lastCenter = null;
    var lastDist = 0;

    stage.on('touchmove', function (e) {
      stage.draggable(true);
      stage.listening(false);
      e.evt.preventDefault();
      var touch1 = e.evt.touches[0];
      var touch2 = e.evt.touches[1];

      if (touch1 && touch2) {
        // if the stage was under Konva's drag&drop
        // we need to stop it, and implement our own pan logic with two pointers
        if (stage.isDragging()) {
          stage.stopDrag();
        }

        var p1 = {
          x: touch1.clientX,
          y: touch1.clientY,
        };
        var p2 = {
          x: touch2.clientX,
          y: touch2.clientY,
        };

        if (!lastCenter) {
          lastCenter = getCenter(p1, p2);
          return;
        }
        var newCenter = getCenter(p1, p2);

        var dist = getDistance(p1, p2);

        if (!lastDist) {
          lastDist = dist;
        }

        // local coordinates of center point
        var pointTo = {
          x: (newCenter.x - stage.x()) / stage.scaleX(),
          y: (newCenter.y - stage.y()) / stage.scaleX(),
        };

        var scale = stage.scaleX() * (dist / lastDist);

        stage.scaleX(scale);
        stage.scaleY(scale);

        // calculate new position of the stage
        var dx = newCenter.x - lastCenter.x;
        var dy = newCenter.y - lastCenter.y;

        var newPos = {
          x: newCenter.x - pointTo.x * scale + dx,
          y: newCenter.y - pointTo.y * scale + dy,
        };

        stage.position(newPos);
        stage.batchDraw();

        //setConditions();
        //setConditionsCable();

        lastDist = dist;
        lastCenter = newCenter;
      }
    });

    stage.on('touchend', function () {
      stage.draggable(false);
      stage.listening(true);
      lastDist = 0;
      lastCenter = null;
    });

    var container = stage.container();

      // make it focusable

      container.tabIndex = 1;
      // focus it
      // also stage will be in focus on its click
      container.focus();

    const DELTA = 10;

      container.addEventListener('keydown', function (e) {
        if (e.keyCode === 39 || e.keyCode === 68) {
          stage.listening(false);
          stage.x(stage.x() - DELTA);
        } else if (e.keyCode === 40 || e.keyCode === 83) {
          stage.listening(false);
          stage.y(stage.y() - DELTA);
        } else if (e.keyCode === 37 || e.keyCode === 65) {
          stage.listening(false);
          stage.x(stage.x() + DELTA);
        } else if (e.keyCode === 38 || e.keyCode === 87) {
          stage.listening(false);
          stage.y(stage.y() + DELTA);
        } else {
          return;
        }
        e.preventDefault();

        layer.batchDraw();
      });
      container.addEventListener('keyup', function (e) {
        if (e.keyCode === 39 || e.keyCode === 68) {
          stage.listening(true);
        } else if (e.keyCode === 40 || e.keyCode === 83) {
          stage.listening(true);
        } else if (e.keyCode === 37 || e.keyCode === 65) {
          stage.listening(true);
        } else if (e.keyCode === 38 || e.keyCode === 87) {
          stage.listening(true);
        } else {
          return;
        }
        e.preventDefault();
        layer.batchDraw();
      });
}

stageTouchController();

function sideReload() {
  window.location.reload(false); 
}

function getStationInfos(id,color) {
  //console.log("getStationInfo Test: "+id+" Farbe: "+color);
  var res = id.split("station");
  var stationIdInfo = res[1];
  //console.log("Stations Listen ID: "+stationIdInfo);
  var stationName = "";
  for(i=0;i<anzahlStationen;i++) {
    if(jdo.Points[i].IdL == stationIdInfo) {
      stationName = jdo.Points[i].Name;
    }
  }
  document.getElementById("tooltipTest").innerHTML = "<h4 style='text-transform: uppercase;'><i class='fi-marker'></i> "+stationName+"</h4><b style='color:"+color+";text-transform: uppercase;'><i class='fi-alert'></i> Fehlertext Test</b><p style='padding-top:5px;'>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et...</p>";
}

function getLineInfos(id,color) {
  //console.log("getStationInfo Test: "+id+" Farbe: "+color);
  var res = id.split("line");
  var lineId = res[1];
  //console.log("Strang Listen ID: "+lineId);
  document.getElementById("tooltipTest").innerHTML = "<h4 style='text-transform: uppercase;'><i class='fi-share'></i> Strang ID: "+jco.Lines[lineId].Short+"</h4><b style='color:"+color+";text-transform: uppercase;'><i class='fi-x'></i> Fehlertext Test</b><p style='padding-top:5px;'>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et...</p>";
}

dragElement(document.getElementById("mainDataSheet"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    localStorage.setItem("mainDataSheetX", elmnt.style.left);
    localStorage.setItem("mainDataSheetY", elmnt.style.top);
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

if (localStorage.getItem("mainDataSheetX")) {
  document.getElementById("mainDataSheet").style.left = localStorage.getItem("mainDataSheetX");
  document.getElementById("mainDataSheet").style.top = localStorage.getItem("mainDataSheetY");
}

function mainDataSheetPositionReset() {
  localStorage.removeItem("mainDataSheetX");
  localStorage.removeItem("mainDataSheetY");
  document.getElementById("mainDataSheet").style.left = "";
  document.getElementById("mainDataSheet").style.right = "25px";
  document.getElementById("mainDataSheet").style.top = "25px";
}

document.getElementById("mousovertext").innerHTML = "OGE Masterkarte<br />Version 0.9.7";

setInterval(() => {
  if (swapShiftKey === 0) {
    //document.getElementById("loadingMap").innerHTML = "<div class='spinner-wrapper'><span class='spinner-text'>Update der Daten...</span><span class='spinner'></span></div>";        
    cableReset();
  }
}, (updateInterval*60000));

stage.on('dragstart', function () {
  layer.listening(false);
  var pos = JSON.stringify(stage.position());
  localStorage.setItem("Position",pos);
  var sca = JSON.stringify(stage.scale());
  localStorage.setItem("Scale",sca);
  console.log("AUS");
});
stage.on('dragend', function () {
  layer.listening(true);
  var pos = JSON.stringify(stage.absolutePosition());
  localStorage.setItem("AbsolutePosition",pos);
  var pos = JSON.stringify(stage.position());
  localStorage.setItem("Position",pos);
  var sca = JSON.stringify(stage.scale());
  localStorage.setItem("Scale",sca);
  layer.batchDraw();
  console.log("EIN");
});

function stationButtonChange() {
  var el = document.getElementById("buttonStation");
  if(el.style.opacity > 0.6) {  
    console.log("Aus");  
    el.style.border = "none";
    el.style.opacity = 0.4;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }
  else {
    console.log("Ein");
    el.style.border = "2px solid #63de17";
    el.style.opacity = 1;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }
}

function ustationButtonChange() {

  var el = document.getElementById("buttonUStation");
  if(el.style.opacity > 0.6) {  
    console.log("Aus");  
    el.style.border = "none";
    el.style.opacity = 0.4;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }
  else {
    console.log("Ein");
    el.style.border = "2px solid #63de17";
    el.style.opacity = 1;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }

}

function pstationButtonChange() {

  var el = document.getElementById("buttonPStation");
  if(el.style.opacity > 0.6) {  
    console.log("Aus");  
    el.style.border = "none";
    el.style.opacity = 0.4;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }
  else {
    console.log("Ein");
    el.style.border = "2px solid #63de17";
    el.style.opacity = 1;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }

}

function diensteButtonChange() { 

  var el = document.getElementById("buttonDienste");
  if(el.style.opacity > 0.6) {  
    console.log("Aus");  
    el.style.border = "none";
    el.style.opacity = 0.4;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }
  else {
    console.log("Ein");
    el.style.border = "2px solid #63de17";
    el.style.opacity = 1;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }

}

function kabelButtonChange() {

  var el = document.getElementById("buttonKabel");
  if(el.style.opacity > 0.6) {  
    console.log("Aus");  
    el.style.border = "none";
    el.style.opacity = 0.4;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }
  else {
    console.log("Ein");
    el.style.border = "2px solid #63de17";
    el.style.opacity = 1;
    document.getElementById("ebenenSpeichernButton").style.opacity = 1;
  }

}

function ebenenSpeichern() {
  var ebenenNamen = ["buttonStation","buttonUStation","buttonPStation","buttonDienste","buttonKabel"];
  var ebenenTemp = [];
  for (x = 0;x < 5; x++){
    var el = document.getElementById(ebenenNamen[x]);
    if(el.style.opacity > 0.6) { 
      ebenenTemp.push(1);
    }
    else{
      ebenenTemp.push(0);
    } 
  }
  localStorage.setItem("ebenenLayer",ebenenTemp);
  cableReset();
}

function ebenenZuruecksetzen() {
  var ebenenNamen = ["buttonStation","buttonUStation","buttonPStation","buttonDienste","buttonKabel"];
  document.getElementById("ebenenSpeichernButton").style.opacity = 0;
  ebenenLayer = localStorage.getItem("ebenenLayer");
  ebenenLayer = ebenenLayer.replaceAll(",","");
  //console.log("Layer "+ebenenLayer);
  for (x = 0;x < 5; x++){
    if (parseInt(ebenenLayer[x]) > 0) {
      //console.log("Layer "+x+" Ein - " +ebenenLayer[x]);
      var el = document.getElementById(ebenenNamen[x]);
      el.style.border = "2px solid #63de17";
      el.style.opacity = 1;
    }
    else {
      //console.log("Layer "+x+" Aus - " +ebenenLayer[x]);
      var el = document.getElementById(ebenenNamen[x]);
      el.style.border = "none";
      el.style.opacity = 0.4;
    }
  }
}

setTimeout(() => {
  ebenenZuruecksetzen(); 
}, 5000); 