$(document).ready(function() {

  // Change color of the 'Dashboard' menu entry
  $("#dashboardpage").css("color", "#03A9F3");

  // Check if IP was listed on blacklists with mxtoolbox.com and if IP was reported on abuseipdb.com
  $("#checkIPmxtoolbox").on("click", function() {
     var hostIPAddr = $("#hostIP").text();
     window.open("https://mxtoolbox.com/SuperTool.aspx?action=blacklist%3a"+hostIPAddr+"&run=toolpage" , "_blank");
  });

  $("#checkIPabuseipdb").on("click", function() {
     var hostIPAddr = $("#hostIP").text();
     window.open("https://www.abuseipdb.com/check/"+hostIPAddr+"", "_blank");
  });

  // Show real-time network usage
  var datanet = [];
  var datanet2 = [];
  var datasetnet;
  var transdiff = [];  transdiff[0] = 0;
  var recdiff = [];  recdiff[0] = 0;
  var totalPoints = 100;
  var updateInterval = 1000;
  var nownet = new Date().getTime();
  var startcheck = 0;

  function GetDatanet() {

    if (datanet.length >= totalPoints) {
        datanet.shift();
        datanet2.shift();
    }

    $.get('network-usage.php','',function(b,status) {
        if (!b) return;

        var nettransmitinit = b.transmit;
        transdiff[1]= nettransmitinit;

        if (startcheck == 0) {
            var nettransmit = 0;
        } else {
             var nettransdif = transdiff[1] - transdiff[0];
             var nettransmit = nettransdif.toFixed(2);
          }

        datanet.push([nownet+=updateInterval, nettransmit]);
        transdiff[0] = nettransmitinit;

        var netreceivedinit = b.receive;
        recdiff[1] = netreceivedinit;

        if (startcheck == 0) {
            var netreceived = 0;
        } else {
            var netrecdif = recdiff[1] - recdiff[0];
            var netreceived = netrecdif.toFixed(2);
          }

        datanet2.push([nownet, netreceived]);
        recdiff[0] = netreceivedinit;
        startcheck++;

        if (datasetnet) {
           $.plot($("#net-usage-placeholder"), datasetnet, optionsnet);
        }
    },'json');
  }

  function legendFormatternet(label, series) {
      return '<div style="font-size: 12px; font-weight: bold; color: #000000; text-align: center;" title="Network usage.">' + label + '</div>';
  };

  var optionsnet = {
      series: {
        lines: {
            show: true,
            lineWidth: 0.5,
            fill: true
        }
      },
      shadowSize: 0,
      xaxis: {
        mode: "time",
        tickSize: [2, "second"],
        tickFormatter: function (v, axis) {
            var date = new Date(v);
            if (date.getSeconds() % 20 == 0) {
                var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

                return hours + ":" + minutes + ":" + seconds;

            } else {
                return "";
            }
        },
        tickLength: 0,
        axisLabel: "Time",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 13,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 10
      },
      yaxis: {
        min: 0,
        tickFormatter: function (v, axis) {
              if ((v % 1) != 0) {
                  var nbdecin = v.toString().split(".");
                  var nbdec = nbdecin[1].length;
                  if (nbdec <= 2) {
                      return v + " KiB/s";
                  } else {
                      return "";
                    }
              } else { return v + " KiB/s"; }
        },
        tickDecimals: 2,
        tickLength: 0,
        axisLabel: "Network usage",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 13,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 6
      },
      legend: {
        labelFormatter: legendFormatternet
      },
      grid: {
        backgroundColor: "#ffffff",
        hoverable: true,
        clickable: true,
        borderWidth: 0.2
      },
      tooltip: true,
      tooltipOpts: {
        content: function(label, xval, yval) {
             var content = "%s: " + yval + " KiB/s";
             return content;
        }
      }
  };

  datasetnet = [
        { label: "Sending", data: datanet, color: "#7e36b5" },
        { label: "Receiving", data: datanet2, color: "#43c7cc" }
  ];

  GetDatanet();
  $.plot($("#net-usage-placeholder"), datasetnet, optionsnet);

  setInterval(function() {
     GetDatanet();
  }, updateInterval);

  setInterval(function() {
    datanet = [];
    datanet2 = [];
    datasetnet = [];
    totalPoints = 100;
    updateInterval = 1000;
    nownet = new Date().getTime();

    datasetnet = [
        { label: "Sending", data: datanet, color: "#7e36b5" },
        { label: "Receiving", data: datanet2, color: "#43c7cc" }
    ];

    GetDatanet();
    $.plot($("#net-usage-placeholder"), datasetnet, optionsnet);

  }, 600000);



  // Show real-time CPU usage
  var data = [];
  var data2 = [];
  var dataset;
  var totalPoints = 100;
  var updateInterval = 1000;
  var now = new Date().getTime();

  function GetData() {
    if (data.length >= totalPoints) {
        data.shift();
        data2.shift();
    }

    $.get('cpu-usage.php','',function(d,status) {
        if (!d) return;

        var usage = d.total;
        data.push([now+=updateInterval, usage]);

        var sysuse = d.system;
        data2.push([now, sysuse]);
        if (dataset)
            $.plot($("#cpu-usage-placeholder"), dataset, options);
    },'json');
  }

  function legendFormatter(label, series) {
      return '<div ' + 'style="font-size: 12px; font-weight: bold; color: #000000; text-align: center;" title="\'Total\' = total CPU usage, \'System\' = CPU usage generated by processes executing in kernel mode.">' + label + '</div>';
  };

  var options = {
      series: {
        lines: {
            show: true,
            lineWidth: 0.5,
            fill: true
        }
      },
      shadowSize: 0,
      xaxis: {
        mode: "time",
        tickSize: [2, "second"],
        tickFormatter: function (v, axis) {
            var date = new Date(v);
            if (date.getSeconds() % 20 == 0) {
                var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

                return hours + ":" + minutes + ":" + seconds;

            } else {
                return "";
            }
        },
        tickLength: 0,
        axisLabel: "Time",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 13,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 10
      },
      yaxis: {
        min: 0,
        max: 100,
        tickSize: 5,
        tickFormatter: function (v, axis) {
            if (v % 10 == 0) {
                return v + "%";
            } else {
                return "";
            }
        },
        tickLength: 0,
        axisLabel: "CPU usage",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 13,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 6
      },
      legend: {
        labelFormatter: legendFormatter
      },
      grid: {
        backgroundColor: "#ffffff",
        hoverable: true,
        clickable: true,
        borderWidth: 0.2
      },
      tooltip: true,
      tooltipOpts: {
        content: function(label, xval, yval) {
          var content = "%s " + yval + "%";
          return content;
        }
      }
  };

  dataset = [
        { label: "Total", data: data, color: "#2b66f0" },
        { label: "System", data: data2, color: "#ba3052" }
  ];

  GetData();
  $.plot($("#cpu-usage-placeholder"), dataset, options);

  setInterval(function() {
     GetData();
  }, updateInterval);


  setInterval(function() {
     data = [];
     data2 = [];
     dataset = [];
     totalPoints = 100;
     updateInterval = 1000;
     now = new Date().getTime();

     dataset = [
        { label: "Total", data: data, color: "#2b66f0" },
        { label: "System", data: data2, color: "#ba3052" }
     ];

     GetData();
     $.plot($("#cpu-usage-placeholder"), dataset, options);

  }, 600000);



  // Show real-time ram memory usage
  var dataram = [];
  var dataram2 = [];
  var datasetram;
  var totalPoints = 100;
  var updateInterval = 1000;
  var nowram = new Date().getTime();


  function GetDataRam() {
    if (dataram.length >= totalPoints) {
        dataram.shift();
        dataram2.shift();
    }

    $.get('ram-usage.php','',function(c,status) {
        if (!c) return;

        var ramusage = c.ram;
        dataram.push([nowram+=updateInterval, ramusage]);

        var swapusage = c.swap;
        dataram2.push([nowram, swapusage]);
        if (datasetram)
           $.plot($("#ram-usage-placeholder"), datasetram, optionsram);
    },'json');
  }

  function legendFormatterRam(label, series) {
      return '<div style="font-size: 12px; font-weight: bold; color: #000000; text-align: center;" title="RAM usage / SWAP space usage.">' + label + '</div>';
  };

  var optionsram = {
      series: {
        lines: {
            show: true,
            lineWidth: 0.5,
            fill: true
        }
      },
      shadowSize: 0,
      xaxis: {
        mode: "time",
        tickSize: [2, "second"],
        tickFormatter: function (v, axis) {
            var date = new Date(v);
            if (date.getSeconds() % 20 == 0) {
                var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

                return hours + ":" + minutes + ":" + seconds;

            } else {
                return "";
            }
        },
        tickLength: 0,
        axisLabel: "Time",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 13,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 10
      },
      yaxis: {
        min: 0,
        max: 100,
        tickSize: 5,
        tickFormatter: function (v, axis) {
            if (v % 10 == 0) {
                return v + "%";
            } else {
                return "";
            }
        },
        tickLength: 0,
        axisLabel: "RAM / SWAP usage",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 13,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 6
      },
      legend: {
        labelFormatter: legendFormatterRam
      },
      grid: {
        backgroundColor: "#ffffff",
        hoverable: true,
        clickable: true,
        borderWidth: 0.2
      },
      tooltip: true,
      tooltipOpts: {
        content: function(label, xval, yval) {
          var content = "%s " + yval + "%";
          return content;
        }
      }
  };

  datasetram = [
        { label: "RAM", data: dataram, color: "#10a368" },
        { label: "SWAP", data: dataram2, color: "#1d80a3" }
  ];

  GetDataRam();
  $.plot($("#ram-usage-placeholder"), datasetram, optionsram);

  setInterval(function() {
     GetDataRam();
  }, updateInterval);

  setInterval(function() {
    dataram = [];
    dataram2 = [];
    datasetram = [];
    totalPoints = 100;
    updateInterval = 1000;
    nowram = new Date().getTime();

    datasetram = [
        { label: "RAM", data: dataram, color: "#10a368" },
        { label: "SWAP", data: dataram2, color: "#1d80a3" }
    ];

    GetDataRam();
    $.plot($("#ram-usage-placeholder"), datasetram, optionsram);

  }, 600000);

  // Remove tooltip links immediately after the tooltip popup disappears
  $(".componentInfo,.reputationcheck").mouseenter(function() {
     $(".popuplinks").show();
  });

  $(".componentInfo,.reputationcheck").mouseleave(function() {
     $(".popuplinks").hide();
  });

});
