var traffic;
var flow;
var navcar;
var navcardata;
var geojson;
var geolat;
var geolong;
var originalJson;
var pol;

function getNAVcar(){
  // var incidents = getTraffic()
  try {
    $.ajax({
        type: "POST",
        url: NavCARdata,
    }).done(function (newdata) {
        convertdata(newdata);
    });
    function convertdata(data) {
        navcardata = data;
        console.log(navcardata)
    }
    return navcardata
}
catch (err) {
    console.log('loading Gas Values from DB failed!');
}
  // pol = decode(navcar.body.routes[0].sections[0].polyline)
  // geolat = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LATITUDE;
  // geolong = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LONGITUDE;
  // var type = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].TRAFFIC_ITEM_DESCRIPTION[0].value;
      // roadclose = new vcs.vcm.layer.GeoJSON({
      //     name: "ROAD_CLOSURE",
      //     http://localhost:8083/CONSTRUCTION",
      //     data: geojson,
      //     projection: {
      //         epsg: 4326
      //     },
      //     altitudeMode : "relativeToGround",
      //     style: {
      //     image: {
      //       icon: {
      //         src: "./img/traffic/icons8-straßensperre-64.png",
      //         scale: 1
      //       }
      //     }
      //   },
      //   heightAboveGround: 0
      // })
      // framework.addLayer(roadclose)
      // roadclose.activate(true);


};
function getAccidents(type){
    // var incidents = getTraffic()
    console.log(traffic);
    // geolat = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LATITUDE;
    // geolong = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LONGITUDE;
    // var type = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].TRAFFIC_ITEM_DESCRIPTION[0].value;
    if (type == "ROAD_CLOSURE"){
        roadclose = new vcs.vcm.layer.GeoJSON({
            name: "ROAD_CLOSURE",
            url: ROAD_CLOSURE,
            data: geojson,
            projection: {
                epsg: 4326
            },
            altitudeMode : "relativeToGround",
            style: {
            image: {
              icon: {
                src: "./img/traffic/icons8-straßensperre-64.png",
                scale: 1
              }
            }
          },
          heightAboveGround: 0
        })
        framework.addLayer(roadclose)
        roadclose.activate(true);
    } else if (type == "CONSTRUCTION"){
        trafficlayer = new vcs.vcm.layer.GeoJSON({
            name: "CONSTRUCTION",
            url: CONSTRUCTION,
            data: geojson,
            projection: {
                epsg: 4326
            },
            altitudeMode : "relativeToGround",
            style: {
            image: {
              icon: {
                src: "./img/traffic/icons8-im-bau-50.png",
                scale: 0.5
              }
            }
          },
          heightAboveGround: 0
        })
        framework.addLayer(trafficlayer)
        trafficlayer.activate(true);
    }
    

};

function deleteAccidents(type){
  if (type == "CONSTRUCTION"){
    var layern = ["CONSTRUCTION"]
    var layers = framework.getLayers();

    for (var i = 0; i< layers.length; i++) {
      var layer = layers[i];
      if(layern.indexOf(layer.name) >= 0){
        layer.activate(false);
      } 
    }
    framework.removeLayerByName("CONSTRUCTION")
  } else if (type == "ROAD_CLOSURE"){
    var layerR = ["ROAD_CLOSURE"]
    var layers = framework.getLayers();

    for (var i = 0; i< layers.length; i++) {
      var layer = layers[i];
      if(layerR.indexOf(layer.name) >= 0){
        layer.activate(false);
      } 
    }
    framework.removeLayerByName("ROAD_CLOSURE")
  }
}

function getFlow(){
  // var incidents = getTraffic()

  // geolat = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LATITUDE;
  // geolong = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LONGITUDE;
  // var type = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].TRAFFIC_ITEM_DESCRIPTION[0].value;
  try {
    $.ajax({
        type: "POST",
        url: FLOWdataUrl,
    }).done(function (newdata) {
        convertdata(newdata);
    });
    function convertdata(data) {
        flow = data;
        console.log(flow)
    }
    return flow
}
catch (err) {
    console.log('loading Gas Values from DB failed!');
}

};
function getNAV(){
  // var incidents = getTraffic()

  // geolat = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LATITUDE;
  // geolong = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LONGITUDE;
  // var type = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].TRAFFIC_ITEM_DESCRIPTION[0].value;
  try {
    $.ajax({
        type: "POST",
        url: NavCARdataUrl,
    }).done(function (newdata) {
        convertdata(newdata);
    });
    function convertdata(data) {
        navcar = data;
        console.log(navcar)
    }
    return navcar
}
catch (err) {
    console.log('loading Gas Values from DB failed!');
}

};
function getFlowtest(){
  // var incidents = getTraffic()

  // geolat = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LATITUDE;
  // geolong = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].LOCATION.GEOLOC.ORIGIN.LONGITUDE;
  // var type = traffic.body.TRAFFIC_ITEMS.TRAFFIC_ITEM[0].TRAFFIC_ITEM_DESCRIPTION[0].value;
  try {
    $.ajax({
        type: "POST",
        url: FLOWtestUrl,
    }).done(function (newdata) {
        convertdata(newdata);
    });
    function convertdata(data) {
        flow = data;
        console.log(flow)
    }
    return flow
}
catch (err) {
    console.log('loading Gas Values from DB failed!');
}

};
function drawFlow(){
  // document.getElementById("loadermain").style.display = "block";
  // url: "http://localhost:8083/FLOW",
  flowlayer = new vcs.vcm.layer.GeoJSON({
    name: "FLOW",
    url: TrafficFlow,
    data: geojson,
    projection: {
        epsg: 4326
    },
    altitudeMode : "relativeToGround",
    heightAboveGround: 0
})
framework.addLayer(flowlayer)
flowlayer.activate(true);
  // var mainlayer; 
  var layern = ["FLOW"]
  var layers = framework.getLayers();
  
//   for (var i = 0; i< layers.length; i++) {
//     var layer = layers[i];
//      if(layern.indexOf(layer.name) >= 0){
//        mainlayer = layer
      
//      } 
//   }
//   var objectlist = [];
//   var layerData = {}
//   var test = 0; 
//   var timeout = setInterval(function() {
//     if("l" in layerData) {
//       for (key in layerData.l) {
//         test +=1;
//         objectlist.push(layerData.l[key])
//       }
//       // document.getElementById("loadermain").style.display = "block";
//         clearInterval(timeout); 
//         isFinished = true;
//     } else{
//       layerData = getLayerforData("CarRoute")
//     }
// }, 1000);
// document.getElementById("loadermain").style.display = "none";

}
function deleteFlow(){
  var layern = ["FLOW"]
    var layers = framework.getLayers();

    for (var i = 0; i< layers.length; i++) {
      var layer = layers[i];
      if(layern.indexOf(layer.name) >= 0){
        layer.activate(false);
      } 
    }
    framework.removeLayerByName("FLOW")
}
function drawnavcar(){
  var layern = ["NAVCAR"]
  var layers = framework.getLayers();

  for (var i = 0; i< layers.length; i++) {
    var layer = layers[i];
    if(layern.indexOf(layer.name) >= 0){
      layer.activate(false);
    } 
  }
  framework.removeLayerByName("NAVCAR")
  navcarlayer = new vcs.vcm.layer.GeoJSON({
    name: "NAVCAR",
    url: NAVCAR,
    data: geojson,
    projection: {
        epsg: 4326
    },
    altitudeMode : "relativeToGround",
    heightAboveGround: 0
})
framework.addLayer(navcarlayer)
navcarlayer.activate(true);
}
function getTraffic() {
    try {
        $.ajax({
            type: "POST",
            url: getTrafficIncidentsUrl,
        }).done(function (newdata) {
            convertdata(newdata);
        });
        function convertdata(data) {
            traffic = data;
            console.log(traffic)
        }
        return traffic
    }
    catch (err) {
        console.log('loading Gas Values from DB failed!');
    }
};
function drawnavpub(){
  var layern = ["NAVPUB"]
  var layers = framework.getLayers();

  for (var i = 0; i< layers.length; i++) {
    var layer = layers[i];
    if(layern.indexOf(layer.name) >= 0){
      layer.activate(false);
    } 
  }
  framework.removeLayerByName("NAVPUB")
  navcarlayer = new vcs.vcm.layer.GeoJSON({
    name: "NAVPUB",
    url: NAVPUB,
    data: geojson,
    projection: {
        epsg: 4326
    },
    altitudeMode : "relativeToGround",
    heightAboveGround: 0
})
framework.addLayer(navcarlayer)
navcarlayer.activate(true);
}

//-- Set point in the map
function setPoint(location, pointd){

  var datapoint = {
    slat:"",
    slon:"",
    sloc:"",
    }

    datapoint.slat = pointd.lat
    datapoint.slon = pointd.lon
    datapoint.sloc = location

    var layern = [location + "point"]
    var layers = framework.getLayers();
    // hide layer if it already exists
    for (var i = 0; i< layers.length; i++) {
      var layer = layers[i];
      if(layern.indexOf(layer.name) >= 0){
        layer.activate(false);
        
      } 
    }
    // delete layer if it already exists
   framework.removeLayerByName(location + "point")
    // visualizing with vcs GeoJson function
    pointlayer = new vcs.vcm.layer.GeoJSON({
        name: location + "point",
        url: addPointurl + "?slat=" + pointd.lat + "&slon=" + pointd.lon + "&sloc=" + location,
        data: geojson,
        projection: {
            epsg: 4326
        },
        altitudeMode : "relativeToGround",
        style: {
        image: {
          icon: {
            src: "./templates/locationSM.png",
            scale: 0.5
          }
        }
      },
      heightAboveGround: 0
    })
    framework.addLayer(pointlayer)
    pointlayer.activate(true);
}
// Test Funktion
function setRouteCar(){
  var resetBtn = document.getElementById("buttonCar");
  resetBtn.disabled = true;
  resetBtn.innerHTML = '<div id="loaderCar" class="loader"></div>'
  // var loaderBtn = document.getElementById("loaderCar");
  // loaderBtn.display = "block";

  pointsoe="";
  var datapoint = {
    slat:"",
    slon:"",
    sloc:"Start",
    elat:"",
    elon:"",
    eloc:"End"
    }

      datapoint.slat = document.getElementById('Spunktlat').value
      datapoint.slon = document.getElementById('Spunktlon').value
      datapoint.sloc = "Start"
      datapoint.elat = document.getElementById('Epunktlat').value
      datapoint.elon = document.getElementById('Epunktlon').value
      datapoint.eloc = "End"
  
      var layern = ["CarRoute"]
      var layers = framework.getLayers();
      // hide layer if it already exists
      for (var i = 0; i< layers.length; i++) {
        var layer = layers[i];
        if(layern.indexOf(layer.name) >= 0){
          layer.activate(false);
          
        } 
      }
      // delete layer if it already exists
     framework.removeLayerByName("CarRoute")
      // visualizing with vcs GeoJson function
      pointlayer = new vcs.vcm.layer.GeoJSON({
          name: "CarRoute",
          url: routecalcurl + "?slat=" + datapoint.slat + "&slon=" + datapoint.slon + "&sloc=" + datapoint.sloc + "&elat=" + datapoint.elat + "&elon=" + datapoint.elon + "&eloc=" + datapoint.eloc,
          data: geojson,
          projection: {
              epsg: 4326
          },
          altitudeMode : "relativeToGround",
          style: {
          image: {
            icon: {
              src: "./templates/locationSM.png",
              scale: 0.5
            }
          }
        },
        heightAboveGround: 0
      })
      framework.addLayer(pointlayer)
      pointlayer.activate(true);


      // var mainlayer; 
      var layern = ["CarRoute"]
      var layers = framework.getLayers();
      
      for (var i = 0; i< layers.length; i++) {
        var layer = layers[i];
         if(layern.indexOf(layer.name) >= 0){
           mainlayer = layer
          
         } 
      }
      var objectlist = [];
      var layerData = {}
      var test = 0; 
      var timeout = setInterval(function() {
        if("l" in layerData) {
          for (key in layerData.l) {
            test +=1;
            objectlist.push(layerData.l[key])
          }
            console.log(test)
            console.log(objectlist)
            calcTime(objectlist,"Routeduration");
            clearInterval(timeout); 
            isFinished = true;
        } else{
          layerData = getLayerforData("CarRoute")
        }
    }, 1000);

}
function setRoutePublic(){
  document.getElementById("PubRouteShow").innerHTML = "";
  var resetBtn = document.getElementById("buttonPub");
  resetBtn.disabled = true;
  resetBtn.innerHTML = '<div id="loaderCar" class="loader"></div>'

  pointsoe = "";
  var datapoint = {
    slat:"",
    slon:"",
    sloc:"Start",
    elat:"",
    elon:"",
    eloc:"End"
    }
    var testingThing;
    datapoint.slat = document.getElementById('Spunktlat').value
    datapoint.slon = document.getElementById('Spunktlon').value
    datapoint.sloc = "Start"
    datapoint.elat = document.getElementById('Epunktlat').value
    datapoint.elon = document.getElementById('Epunktlon').value
    datapoint.eloc = "End"

    var layern = ["PublicRoute"]
    var layers = framework.getLayers();
    // hide layer if it already exists
    for (var i = 0; i< layers.length; i++) {
      var layer = layers[i];
      if(layern.indexOf(layer.name) >= 0){
        layer.activate(false);
        
      } 
    }
    // delete layer if it already exists
   framework.removeLayerByName("PublicRoute")
    // visualizing with vcs GeoJson function
    pointlayer = new vcs.vcm.layer.GeoJSON({
        name: "PublicRoute",
        url: navpublict2url + "?slat=" + datapoint.slat + "&slon=" + datapoint.slon + "&sloc=" + datapoint.sloc + "&elat=" + datapoint.elat + "&elon=" + datapoint.elon + "&eloc=" + datapoint.eloc,
        data: testingThing,
        projection: {
            epsg: 4326
        },
        altitudeMode : "relativeToGround",
        style: {
        image: {
          icon: {
            src: "./templates/locationSM.png",
            scale: 0.5
          }
        }
      },
      heightAboveGround: 0
    })

    framework.addLayer(pointlayer)
    pointlayer.activate(true);
    

    // --- get the Data from the geoJson
    //======in progress

    // var mainlayer; 
    var layern = ["PublicRoute"]
    var layers = framework.getLayers();
    
    for (var i = 0; i< layers.length; i++) {
      var layer = layers[i];
       if(layern.indexOf(layer.name) >= 0){
         mainlayer = layer
        
       } 
    }
    var objectlist = [];
    var layerData = {}
    var test = 0; 
    var timeout = setInterval(function() {
      if("l" in layerData) {
        for (key in layerData.l) {
          test +=1;
          objectlist.push(layerData.l[key])
        }
          console.log(test)
          console.log(objectlist)
          calcTime(objectlist,"RoutedurationPub");
          clearInterval(timeout); 
          isFinished = true;
      } else{
        layerData = getLayerforData("PublicRoute")
      }
  }, 1000);
    // var newmain = mainlayer.options.commonLayer.source
    ////["00c943b2-de4c-4898-bf4b-680b49cd0643"].I
    //var testing = Object.getOwnPropertyNames(newmain.l).sort()
  

  
    
    

    
}

function calcTime(list,location){
  var daystime = 0;
  var minutestime = 0;
  var secondstime = 0;
  var hourstime = 0;
  for (var i = 0; i< list.length; i++) {
    daystime += parseFloat(list[i].I.daysDifference)
    minutestime += parseFloat(list[i].I.minutesDifference)
    secondstime += parseFloat(list[i].I.secondsDifference)
    hourstime += parseFloat(list[i].I.hoursDifference)
    if (location == "RoutedurationPub"){
      if (i == 0){
        var newPoint = document.createElement("div");
        newPoint.className = "Travelpoint"; 
        newPoint.innerHTML = "Startpunkt"
          // var textnode = document.createTextNode(list[i].I.arrivalPlace.name);
          document.getElementById("PubRouteShow").appendChild(newPoint);

      }
    if (list[i].I.transportInfo.mode == "pedestrian"){

      var newDiv = document.createElement("div");
      newDiv.className = "walkingshape"; 
      newDiv.innerHTML = "zu Fuß"
      document.getElementById("PubRouteShow").appendChild(newDiv);
      if (list[i].I.arrivalPlace.name){
        var newPoint = document.createElement("div");
        newPoint.className = "Travelpoint"; 
        newPoint.innerHTML = list[i].I.arrivalPlace.name
          // var textnode = document.createTextNode(list[i].I.arrivalPlace.name);
          document.getElementById("PubRouteShow").appendChild(newPoint);
      }
      

    } else if (list[i].I.transportInfo.mode == "subway"){
      var newDiv = document.createElement("div");
      newDiv.className = "subwayshape"; 
      newDiv.innerHTML = "mit U-Bahn"
      document.getElementById("PubRouteShow").appendChild(newDiv);

      var newPoint = document.createElement("div");
      newPoint.className = "Travelpoint"; 
      newPoint.innerHTML = list[i].I.arrivalPlace.name
        // var textnode = document.createTextNode(list[i].I.arrivalPlace.name);
        document.getElementById("PubRouteShow").appendChild(newPoint);
    } else if (list[i].I.transportInfo.mode == "bus"){
      var newDiv = document.createElement("div");
      newDiv.className = "busshape"; 
      newDiv.innerHTML = "mit Bus"
      document.getElementById("PubRouteShow").appendChild(newDiv);
      var newPoint = document.createElement("div");
      newPoint.className = "Travelpoint"; 
      newPoint.innerHTML = list[i].I.arrivalPlace.name
        // var textnode = document.createTextNode(list[i].I.arrivalPlace.name);
        document.getElementById("PubRouteShow").appendChild(newPoint);
    }else if (list[i].I.transportInfo.mode == "cityTrain"){
      var newDiv = document.createElement("div");
      newDiv.className = "subwayshape"; 
      newDiv.innerHTML = "mit S-Bahn"
      document.getElementById("PubRouteShow").appendChild(newDiv);
      var newPoint = document.createElement("div");
      newPoint.className = "Travelpoint"; 
      newPoint.innerHTML = list[i].I.arrivalPlace.name
        // var textnode = document.createTextNode(list[i].I.arrivalPlace.name);
        document.getElementById("PubRouteShow").appendChild(newPoint);
    }

  }
    // test +=1;
    // objectlist.push(layerData.l[key])
  }
  if (hourstime > 59) {
    var days  = Math.floor(hourstime / 24);
    daystime += parseFloat(days);
    var hours = hourstime - days * 24;
    hourstime = parseFloat(hours)
  }
  if (minutestime > 59) {
    var hours  = Math.floor(minutestime / 60);
    hourstime += parseFloat(hours);
    var minutes = minutestime - hours * 60;
    minutestime = parseFloat(minutes)
  }
  if (secondstime > 59) {
    var minutes  = Math.floor(secondstime / 60);
    minutestime += parseFloat(minutes);
    var seconds = secondstime - minutes * 60;
    secondstime = parseFloat(seconds)
  }
  if (hourstime == 0){
    document.getElementById(location).value = minutestime + " min " + secondstime + " sek";
  } else if (daystime == 0){
    document.getElementById(location).value = hourstime + " h " + minutestime + " min " + secondstime + " sek";
  } else{
    document.getElementById(location).value = daystime + " d " + hourstime + " h " + minutestime + " min " + secondstime + " sek";
  }
  if (location == "RoutedurationPub"){

  var resetBtn = document.getElementById("buttonPub");
  resetBtn.disabled = false;
  resetBtn.innerHTML = "Route berechnen (Öffis)"
  
  var newPoint = document.createElement("div");
  newPoint.className = "Travelpoint"; 
  newPoint.innerHTML = "Endpunkt"
    // var textnode = document.createTextNode(list[i].I.arrivalPlace.name);
    document.getElementById("PubRouteShow").appendChild(newPoint);
  // var textnode = document.createTextNode("Endpunkt");
  // document.getElementById("PubRouteShow").appendChild(textnode);
  // var newDiv = document.createElement("div");
  // newDiv.className = "walkingshape";
  // var loaderBtn = document.getElementById("loaderPub");
  // loaderBtn.display = "none"; 

  // document.getElementById("PubRouteShow").appendChild(newDiv);
  } else if (location == "Routeduration"){

  var resetBtn = document.getElementById("buttonCar");
  resetBtn.disabled = false;
  resetBtn.innerHTML = "Route berechnen (Auto)"
  // var loaderBtn = document.getElementById("loaderCar");
  // loaderBtn.display = "none"; 

  }

  
};


function getLayerforData(name){
  var layern = [name]
    var layers = framework.getLayers();
  var mainlayer2
  for (var i = 0; i< layers.length; i++) {
    var layer = layers[i];
     if(layern.indexOf(layer.name) >= 0){
       mainlayer2 = layer
       return mainlayer2.options.commonLayer.source
     } 
  }
}

function CheckboxCheck(type) {
  if (type == "CONSTRUCTION"){
    var checkBox = document.getElementById("baucheck");

    if (checkBox.checked == true){
      console.log("test an")
      getAccidents('CONSTRUCTION')
    } else {
      console.log("test off")
      deleteAccidents('CONSTRUCTION')
    }
  } else if (type == "ROAD_CLOSURE"){
    var checkBox = document.getElementById("Streetcheck");

    if (checkBox.checked == true){
      getAccidents('ROAD_CLOSURE')
    } else {
      deleteAccidents('ROAD_CLOSURE')
    }
  } else if (type == "FLOW"){
    var checkBox = document.getElementById("flowcheck");

    if (checkBox.checked == true){
      drawFlow()
    } else {
      deleteFlow()
    }
  }

}