var _chart = null;
var _CdeId = null;
var _apiUrl = null;
var _BioRadId = null;
var _toolType = null;
var _workMaterial = {};
var _initialHeaderId = null;
var _toolTypeMetaData = null;
var _initialHeaderAttachmentId = null;

$(document).ready(function () {
  if (location.pathname == "/") {
    route = "/AwaitingDispo";
  }
  else {
    route = location.pathname;
  }
  $('ul.nav.navbar-nav').find('a[href="' + route + '"]')
    .closest('li').addClass('alert-info');
});

function loadRunInfoAwaitingDisposition() {
  var row = $("#grid").igGrid("selectedRow");
  if (row == null)
    return;
  var data = $("#grid").igGrid("findRecordByKey", row.id);
  if (data == null)
    return;
  var targetURL = "RunInfo?tooltypeid=" + data.ToolTypeID + "&headerid=" + data.ID;
  window.location.href = targetURL;
}

function initAwaitingDisposition(apiUrl) {
  _apiUrl = apiUrl;
  $("#grid").igGrid({
    autoGenerateColumns: false,
    width: "70%",
    height: "100%",
    primaryKey: "PK",
    columns: [
      { key: "PK", dataType: "string", hidden: true, },
      { key: "ID", dataType: "number", hidden: true, },
      { key: "ToolTypeID", dataType: "number", hidden: true, },
      { headerText: "Tool Type", key: "ToolType", dataType: "string", width: "15%" },
      { key: "Tool", dataType: "string", width: "10%" },
      { key: "Reactor", dataType: "string", width: "10%" },
      { key: "RDS", dataType: "string", width: "10%" },
      { key: "PSN", dataType: "string", width: "10%" },
      { key: "Layer", dataType: "string", width: "10%" },
      { key: "Zone", dataType: "string", width: "10%" },
      { key: "InsertDate", dataType: "date", width: "10%", format: "dateTime" },
      { key: "Expiration", dataType: "date", width: "10%", format: "dateTime" }
    ],
    dataSource: _apiUrl + "/awaitingdispo/",
    responseDataKey: "Results",
    tabIndex: 1,
    features: [
      { name: "Selection", mode: "row", multipleSelection: false },
      { name: "Filtering", type: "local" },
      { name: "Sorting", type: "local" },
    ]
  });
  $("#RefreshButton").click(function () {
    $("#grid").igGrid("dataBind");
  });
  $("#OpenButton").click(loadRunInfoAwaitingDisposition);
  $("#grid").on("dblclick", "tr", loadRunInfoAwaitingDisposition);
};

function initExport(apiUrl, startTimeValue, endTimeValue) {
  _apiUrl = apiUrl;
  var endTime = new Date(endTimeValue);
  var startTime = new Date(startTimeValue);
  $.getJSON(_apiUrl + '/tooltypes', function (data) {
    $("#ToolType").igCombo({
      dataSource: data,
      responseDataKey: "Results",
      textKey: "ToolTypeName",
      valueKey: "ID",
      mode: "dropdown",
      width: 150
    });
  });
  $("#StartDateControl").igDatePicker({
    dateInputFormat: "date",
    value: startTime,
    width: 125,
    inputName: "StartDate",
  });
  $("#StartTimeControl").igTimePicker({
    dateInputFormat: "time",
    value: startTime,
    width: 110,
    inputName: "StartTime",
  });
  $("#EndDateControl").igDatePicker({
    dateInputFormat: "date",
    value: endTime,
    width: 125,
    inputName: "EndDate",
  });
  $("#EndTimeControl").igTimePicker({
    dateInputFormat: "time",
    value: endTime,
    width: 110,
    inputName: "EndTime",
  });
};

function loadHeaderGridRunHeaders() {
  var toolTypeID = -1; // $("#ToolType").igCombo("value");
  var gridCreated = $("#HeaderGrid").data("igGrid");
  if (gridCreated)
    $("#HeaderGrid").igGrid("destroy");
  clearFieldsGridRunHeaders();
  var headerURL = _apiUrl + "/tooltypes/" + toolTypeID + "/headertitles";
  $("#HeaderGrid").igGrid({
    autoGenerateColumns: false,
    primaryKey: "ID",
    height: "100%",
    width: "100%",
    features: [
      { name: "Paging", type: "local", recordCountKey: "TotalRows", pageSize: 25, pageSizeUrlKey: "pageSize", "pageIndexUrlKey": "page", showPageSizeDropDown: false },
      { name: "Selection", mode: "row", rowSelectionChanged: headerSelectionChangedRunHeaders },
      { name: "Filtering", type: "local" }
    ],
    columns: [
      { key: "ID", dataType: "number", hidden: true },
      { key: "ToolTypeID", dataType: "number", hidden: true },
      { key: "ToolTypeName", dataType: "string", width: "10%" },
      { key: "Title", dataType: "string", width: "40%" },
      { key: "Reactor", dataType: "string", width: "10%" },
      { key: "RDS", dataType: "string", width: "10%" },
      { key: "PSN", dataType: "string", width: "10%" },
      { key: "InsertDate", dataType: "date", format: "dateTime", width: "20%" }
    ],
    dataSource: headerURL,
    responseDataKey: "Results",
  });
}

function clearFieldsGridRunHeaders() {
  var gridCreated = $("#FieldsGrid").data("igGrid");
  if (gridCreated)
    $("#FieldsGrid").igGrid("destroy");
}

function headerSelectionChangedRunHeaders(evt, ui) {
  clearFieldsGridRunHeaders();
  var rowData = ui.owner.grid.dataSource.dataView()[ui.row.index];
  var url = _apiUrl + "/tooltypes/" + rowData.ToolTypeID + "/headers/" + ui.row.id + "/fields";
  $("#FieldsGrid").igGrid({
    autoGenerateColumns: false,
    primaryKey: "Column",
    height: "100%",
    width: "100%",
    features: [
      { name: 'Resizing' }
    ],
    columns: [
      { key: "Column", dataType: "string", width: "20%", columnCssClass: "FieldTitle", },
      { key: "Value", dataType: "string", }
    ],
    enableHoverStyles: false,
    dataSource: url,
    responseDataKey: "Results",
  });
}

function loadRunInfoRunHeaders() {
  var row = $("#HeaderGrid").igGrid("selectedRow");
  if (row == null)
    return;
  var data = $("#HeaderGrid").igGrid("findRecordByKey", row.id);
  if (data == null)
    return;
  var targetURL = "RunInfo?tooltypeid=" + data.ToolTypeID + "&headerid=" + data.ID;
  window.location.href = targetURL;
}

function initRunHeaders(apiUrl) {
  _apiUrl = apiUrl;
  loadHeaderGridRunHeaders();
  $("#RefreshButton").click(function () {
    $("#HeaderGrid").igGrid("dataBind");
  });
  $("#OpenButton").click(loadRunInfoRunHeaders);
  $("#HeaderGrid").on("dblclick", "tr", loadRunInfoRunHeaders);
}

function loadHeaderGridRunInfo() {
  var toolTypeID = $("#ToolType").igCombo("value");
  $("#ToolTypeID").text(toolTypeID);
  hideDetailsDivRunInfo();
  disableHeaderButtonsRunInfo();
  $("#HeaderId").text("");
  $("#HeaderAttachmentId").text("");
  var gridCreated = $("#HeaderGrid").data("igGrid");
  if (gridCreated)
    $("#HeaderGrid").igGrid("destroy");
  $.ajax({
    type: "GET",
    url: _apiUrl + "/tooltypes/" + toolTypeID + "?sortby=grid",
    success: function (r) {
      if ((r.Results == null) || (r.Results.ToolType == null) || (r.Results.Metadata == null))
        ShowErrorMessage("Invalid tool type: " + toolTypeID);
      else {
        _toolType = r.Results.ToolType;
        _toolTypeMetaData = r.Results.Metadata;
        requestHeaderDataRunInfo();
      }
    },
    error: function (e) {
      DisplayWSMessage("error", "There was an error getting tooltype info.", e);
    }
  });
}

function disableHeaderButtonsRunInfo() {
  $("#GetDataButton").prop("disabled", true);
  $("#ReviewButton").prop("disabled", true);
  $("#RecipeParametersButton").prop("disabled", true);
  $("#ViewButton").prop("disabled", true);
  $("#PinButton").prop("disabled", true);
}

function enableHeaderButtonsRunInfo() {
  $("#GetDataButton").prop("disabled", false);
  $("#ReviewButton").prop("disabled", false);
  $("#RecipeParametersButton").prop("disabled", false);
  $("#ViewButton").prop("disabled", false);
  $("#PinButton").prop("disabled", false);
}

function hideDetailsDivRunInfo() {
  if (_chart !== null)
    _chart.destroy();
  $("#DetailsDiv").prop("hidden", true);
  $("#DataAttachmentFrame").prop("src", "");
}

function showDetailsDivRunInfo() {
  $("#DetailsDiv").prop("hidden", false);
  $("#ExportDiv").prop("hidden", true);
  if ((_toolType != null) && (_toolType.OIExportSPName != null) && (_toolType.OIExportSPName.length > 0)) {
    $("#ExportDiv").prop("hidden", false);
    $("#OIExportButton").prop("disabled", false);
    $("#OIExportResult").text('');
  }
  $("#DataAttachmentFrame").prop("hidden", true);
  $("#DataAttachmentDiv").prop("hidden", true);
  $("#HeaderAttachmentFrame").prop("hidden", true);
  $("#HeaderAttachmentDiv").prop("hidden", true);
  if (_toolType != null) {
    var visibleFrames = 0;
    if (_toolType.DisplayDataAttachment && _toolType.DisplayDataAttachment.length > 0) {
      if (!_toolType.DataGridAttributes || _toolType.DataGridAttributes.indexOf('div') === -1) {
        visibleFrames += 1;
        $("#DataAttachmentFrame").prop("hidden", false);
      }
      else
        $("#DataAttachmentDiv").prop("hidden", false);
    }
    if (_toolType.DisplayHeaderAttachment && _toolType.DisplayHeaderAttachment.length > 0) {
      if (!_toolType.HeaderGridAttributes || _toolType.HeaderGridAttributes.indexOf('div') === -1) {
        visibleFrames += 1;
        $("#HeaderAttachmentFrame").prop("hidden", false);
      }
      else
        $("#HeaderAttachmentDiv").prop("hidden", false);
    }
    var frameWidth = (98 / visibleFrames) + "%";
    $("#DataAttachmentFrame,#HeaderAttachmentFrame").css('width', frameWidth);
    if (_toolType.DataGridAttributes != null) {
      var dataGridAttributes = JSON.parse(_toolType.DataGridAttributes);
      if (dataGridAttributes.frame) {
        for (const property in dataGridAttributes.frame) {
          $("#DataAttachmentFrame").css(property, dataGridAttributes.frame[property]);
        }
      }
      if (dataGridAttributes.div) {
        for (const property in dataGridAttributes.div) {
          $("#DataAttachmentDiv").css(property, dataGridAttributes.div[property]);
        }
      }
    }
    if (_toolType.HeaderGridAttributes != null) {
      var headerGridAttributes = JSON.parse(_toolType.HeaderGridAttributes);
      if (headerGridAttributes.frame) {
        for (const property in headerGridAttributes.frame) {
          $("#HeaderAttachmentFrame").css(property, headerGridAttributes.frame[property]);
        }
      }
      if (headerGridAttributes.div) {
        for (const property in headerGridAttributes.div) {
          $("#HeaderAttachmentDiv").css(property, headerGridAttributes.div[property]);
        }
      }
    }
  }
}

function headerSelectionChangedRunInfo(evt, ui) {
  if (ui.row.index >= 0) {
    if ($("#HeaderId").text() == ui.row.id) {
      enableHeaderButtonsRunInfo();
      return;
    }
  }
  disableHeaderButtonsRunInfo();
  hideDetailsDivRunInfo();
  if (ui.row.index >= 0) {
    enableHeaderButtonsRunInfo();
    $("#HeaderId").text(ui.row.id);
    var rowData = ui.owner.grid.dataSource.dataView()[ui.row.index];
    $("#HeaderAttachmentId").text(rowData.AttachmentID);
  }
}

function cancelHandlerRunInfo(evt, ui) {
  return false;
}

function GetMinMax(profilePoints, index) {
  var cd;
  var depth;
  var edited;
  var ceilingCD;
  var resistivity;
  var ceilingEdited;
  var maxDepth = 30;
  var ceilingResistivity;
  var resistivityMin = 99;
  var resistivityMax = -99;
  var concentrationMin = 99;
  var concentrationMax = -99;
  var resistanceEditedMin = 99;
  var resistanceEditedMax = -99;
  for (var i = 0; i < profilePoints.length; i++) {
    if (!profilePoints[i].Depth || !profilePoints[i].Edited || !profilePoints[i].Resistivity || !profilePoints[i].CD)
      continue;
    if (profilePoints[i].Edited.length < 1 || profilePoints[i].Resistivity.length < 1 || profilePoints[i].CD.length < 1)
      continue;
    depth = parseFloat(profilePoints[i].Depth);
    if (depth <= 0 || profilePoints[i].Raw == 0)
      continue;
    if (index > 0) {
      cd = parseFloat(profilePoints[i].CD);
      edited = parseFloat(profilePoints[i].Edited);
      resistivity = parseFloat(profilePoints[i].Resistivity);
    }
    else {
      cd = Math.log10(parseFloat(profilePoints[i].CD));
      edited = Math.log10(parseFloat(profilePoints[i].Edited));
      resistivity = Math.log10(parseFloat(profilePoints[i].Resistivity));
    }
    maxDepth = parseFloat(profilePoints[i].Depth);
    if (resistivity < resistivityMin)
      resistivityMin = resistivity;
    ceilingResistivity = Math.ceil(resistivity);
    if (ceilingResistivity > resistivityMax)
      resistivityMax = ceilingResistivity;
    if (edited < resistanceEditedMin)
      resistanceEditedMin = edited;
    ceilingEdited = Math.ceil(edited);
    if (ceilingEdited > resistanceEditedMax)
      resistanceEditedMax = ceilingEdited;
    if (cd < concentrationMin)
      concentrationMin = cd;
    ceilingCD = Math.ceil(cd);
    if (ceilingCD > concentrationMax)
      concentrationMax = ceilingCD;
  }
  decades = resistivityMax - resistivityMin;
  if (resistanceEditedMax - resistanceEditedMin > decades)
    decades = resistanceEditedMax - resistanceEditedMin;
  if (concentrationMax - concentrationMin > decades)
    decades = concentrationMax - concentrationMin;
  return { decades, maxDepth, concentrationMin, concentrationMax, resistanceEditedMin, resistanceEditedMax, resistivityMin, resistivityMax };
}

function appendDiv() {
  const div = document.createElement("div");
  div.innerHTML = `
    <table border = 1>
      <thead>
        <tr>
          <th>Day Shift</th>
          <th>State</th>
          <th>Loaded RDS</th>
          <th>Average Temperature</th>
          <th>Offset %</th>
          <th>Time Collected</th>
          <th>Hours</th>
          <th>&nbsp;</th>
          <th>Night Shift</th>
          <th>State</th>
          <th>Loaded RDS</th>
          <th>Average Temperature</th>
          <th>Offset %</th>
          <th>Time Collected</th>
          <th>Hours</th>
        </tr>
      </thead>
      <tbody id ="EpiProTempVerification"></tbody>
    </table>
    `;
  const element = document.getElementById("DataAttachmentDiv");
  element.appendChild(div);
  const tbody = document.getElementById("EpiProTempVerification");
  $.ajax({
    type: "GET",
    url: _apiUrl + '/InfinityQSV3/epi-pro-temp-verification/?night=44&night=46&night=52&night=54',
    success: function (r) {
      if (r == null)
        ShowErrorMessage("Invalid data");
      else {
        tbody.innerHTML = r;
      }
    },
    error: function (e, _ajaxOptions, ex) {
      DisplayWSMessage("error", "There was an error getting data.", e, ex);
    }
  });
}

function setChart(index, ctx, data) {
  var cd;
  var depth;
  var edited;
  var resistivity;
  var depthCollection = [];
  var rawCollection = []; // Black
  var resistivityCollection = []; // Green
  var concentrationCollection = []; // Blue
  var resistanceEditedCollection = []; // Red
  var yType = index > 0 ? 'linear' : 'logarithmic';
  // var resistivity = [{ x: 10, y: 20 }, { x: 15, y: null }, { x: 20, y: 10 }];
  var profilePoints = data.ProfileHeader.ProfilePoints;
  var minMax = GetMinMax(profilePoints, index);
  for (var i = 0; i < profilePoints.length; i++) {
    if (!profilePoints[i].Depth || !profilePoints[i].Edited || !profilePoints[i].Resistivity || !profilePoints[i].CD)
      continue;
    if (profilePoints[i].Edited.length < 1 || profilePoints[i].Resistivity.length < 1 || profilePoints[i].CD.length < 1)
      continue;
    depth = parseFloat(profilePoints[i].Depth);
    if (depth <= 0 || profilePoints[i].Raw == 0)
      continue;
    cd = parseFloat(profilePoints[i].CD);
    raw = parseFloat(profilePoints[i].Raw);
    edited = parseFloat(profilePoints[i].Edited);
    resistivity = parseFloat(profilePoints[i].Resistivity);
    if (cd === 0 || edited === 0 || resistivity === 0)
      continue;
    if (edited == 0 || resistivity == 0 || cd == 0)
      continue;
    depthCollection.push(depth);
    if (index > 0) {
      rawCollection.push(raw);
      concentrationCollection.push(cd);
      resistivityCollection.push(resistivity);
      resistanceEditedCollection.push(edited);
    }
    else {
      rawCollection.push(Math.log10(raw));
      concentrationCollection.push(Math.log10(cd));
      resistivityCollection.push(Math.log10(resistivity));
      resistanceEditedCollection.push(Math.log10(edited));
    }
  }
  var chartOptions = {
    plugins: {
      title: {
        display: true,
        text: yType,
      }
    },
    scales: {
      x: {
        display: true,
        position: 'bottom',
        grid: {
          display: false,
        },
        title: {
          text: 'Depth (µm)',
          display: true,
        },
      },
      raw: {
        type: yType,
        display: true,
        position: 'left',
        min: minMax.resistanceEditedMin,
        max: minMax.resistanceEditedMax,
        grid: {
          display: false,
        },
        title: {
          text: 'Resistance (Ω ohm)',
          display: true,
        },
      },
      resistanceEdited: {
        type: yType,
        display: true,
        position: 'left',
        min: minMax.resistanceEditedMin,
        max: minMax.resistanceEditedMax,
        grid: {
          display: false,
        },
        title: {
          text: 'Resistance Edited (Ω ohm)',
          display: true,
        },
      },
      resistivity: {
        type: yType,
        display: true,
        position: 'left',
        min: minMax.resistivityMin,
        max: minMax.resistivityMax,
        grid: {
          display: false,
        },
        title: {
          text: 'Resistivity (ρ ohm-cm)',
          display: true,
        },
      },
      concentration: {
        type: yType,
        display: true,
        position: 'right',
        min: minMax.concentrationMin,
        max: minMax.concentrationMax,
        grid: {
          display: false,
        },
        title: {
          text: 'CD (1/cm³)',
          display: true,
        },
      },
    }
  };
  _chart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: depthCollection,
      datasets: [
        {
          fill: false,
          yAxisID: "resistivity",
          borderColor: 'rgb(0, 255, 0)',
          backgroundColor: 'rgba(0, 255, 0, 1)',
          label: 'Resistivity (ρ ohm-cm)',
          data: resistivityCollection
        }, {
          fill: false,
          yAxisID: "resistanceEdited",
          borderColor: 'rgb(255, 0, 0)',
          backgroundColor: 'rgba(255, 0, 0, 1)',
          label: 'Resistance Edited (Ω ohm)',
          data: resistanceEditedCollection
        }, {
          fill: false,
          yAxisID: "raw",
          borderColor: 'rgb(0, 0, 0)',
          backgroundColor: 'rgba(0, 0, 0, 1)',
          label: 'Resistance (Ω ohm)',
          data: rawCollection
        }, {
          fill: false,
          yAxisID: "concentration",
          borderColor: 'rgb(0, 0, 255)',
          backgroundColor: 'rgba(0, 0, 255, 1)',
          label: 'CD (1/cm³)',
          data: concentrationCollection
        },
      ]
    },
    options: chartOptions,
  });
}

function detailSelectionChangedRunInfo(evt, ui) {
  if (_chart !== null)
    _chart.destroy();
  var toolTypeID = $("#ToolTypeID").text();
  var headerAttachmentId = $("#HeaderAttachmentId").text();
  var attachmentUrlBase = _apiUrl + '/tooltypes/' + toolTypeID;
  if (!headerAttachmentId || headerAttachmentId === '' || !_toolType.DataGridAttributes || _toolType.DataGridAttributes.indexOf('div') === -1) {
    $("#DataAttachmentFrame").prop("src", "");
    if (ui.row.index >= 0) {
      var rowData = ui.owner.grid.dataSource.dataView()[ui.row.index];
      var attachmentId = rowData.AttachmentID;
      if ((attachmentId == null) || (attachmentId === ''))
        return;
      $("#DataAttachmentFrame").prop("src", attachmentUrlBase + "/data/files/" + attachmentId + "/" + _toolType.DisplayDataAttachment);
    }
  }
  else {
    if (ui.row.index == 4)
      appendDiv();
    else {
      var ctx = document.getElementById('DataAttachmentCanvas');
      $.getJSON(attachmentUrlBase + "/header/files/" + headerAttachmentId + "/" + _toolType.DisplayHeaderAttachment, function (data) {
        setChart(ui.row.index, ctx, data);
      });
    }
  }
}

function loadHeaderAttachmentRunInfo() {
  if (_chart !== null)
    _chart.destroy();
  var toolTypeID = $("#ToolTypeID").text();
  $("#DataAttachmentFrame").prop("src", "");
  var attachmentId = $("#HeaderAttachmentId").text();
  if ((attachmentId == null) || (attachmentId === '') || (_toolType.DisplayHeaderAttachment == null) || (_toolType.DisplayHeaderAttachment === '')) {
    $("#HeaderAttachmentFrame").prop("src", "");
  } else {
    if (!_toolType.HeaderGridAttributes || _toolType.HeaderGridAttributes.indexOf('frame') === -1 || _toolType.HeaderGridAttributes.indexOf('controller') === -1)
      $("#HeaderAttachmentFrame").prop("src", _apiUrl + '/tooltypes/' + toolTypeID + "/header/files/" + attachmentId + "/" + _toolType.DisplayHeaderAttachment);
    else {
      var headerGridAttributes = JSON.parse(_toolType.HeaderGridAttributes);
      $("#HeaderAttachmentFrame").prop("src", _apiUrl + '/' + headerGridAttributes.frame.controller + '/' + toolTypeID + "/header/files/" + attachmentId + "/" + _toolType.DisplayHeaderAttachment);
    }
  }
}

function markAsReviewedRunInfo() {
  var toolTypeId = $("#ToolTypeID").text();
  var headerId = $("#HeaderId").text();
  $.ajax({
    type: "POST",
    url: _apiUrl + "/awaitingdispo/markasreviewed?tooltypeid=" + toolTypeId + "&headerid=" + headerId,
    success: function () {
    },
    error: function (e, ajaxOptions, ex) {
      DisplayWSMessage("error", "There was an error marking header as reviewed.", e, ex);
      $("#ReviewButton").prop("disabled", false);
    }
  });
}

function copySelected(attachmentID, title, data) {
  var allText = "";
  var headerText = "";
  var selectedRow = $("#HeaderGrid").data("igGridSelection").selectedRow();
  if (selectedRow !== null) {
    var rowData = $("#HeaderGrid").data("igGrid").dataSource.dataView()[selectedRow.index];
    for (const property in rowData) {
      if (property === "ID" || property === attachmentID || property === title)
        continue;
      allText = allText + property + '\t';
      headerText = headerText + rowData[property] + '\t';
    }
  }
  for (var i = 0; i < data.Results.length; i++) {
    if (i === 0) {
      for (const property in data.Results[i]) {
        if (property === "ID" || property === "InsertDate" || property === attachmentID || property === title)
          continue;
        allText = allText + property + '\t';
      }
      allText = allText + '\r';
    }
    allText = allText + headerText;
    for (const property in data.Results[i]) {
      if (property === "ID" || property === "InsertDate" || property === attachmentID || property === title)
        continue;
      allText = allText + data.Results[i][property] + '\t';
    }
    allText = allText + '\r';
  }
  copy(allText);
}

function loadDetailsRunInfo() {
  showDetailsDivRunInfo();
  loadHeaderAttachmentRunInfo();
  var gridCreated = $("#DetailsGrid").data("igGrid");
  if (gridCreated)
    $("#DetailsGrid").igGrid("destroy");
  var title = "Title";
  var attachmentID = "AttachmentID";
  var headerId = $("#HeaderId").text();
  var toolTypeID = $("#ToolTypeID").text();
  var detailsURL = _apiUrl + "/tooltypes/" + toolTypeID + "/headers/" + headerId + "/data";
  var gridColumns = [
    { key: attachmentID, dataType: "string", hidden: true },
    { key: title, dataType: "string", hidden: true },
  ];
  for (var i = 0; i < _toolTypeMetaData.length; i++) {
    var f = _toolTypeMetaData[i];
    if ((f.Header == false) && (f.GridDisplayOrder > 0)) {
      var col = {
        key: f.ColumnName,
        headerText: f.DisplayTitle,
        width: "150px",
      };
      if (f.GridAttributes != null)
        jQuery.extend(col, JSON.parse(f.GridAttributes));
      if (col.formatter != null) {
        if (col.formatter == "boolToYesNo")
          col.formatter = boolToYesNo;
        else
          col.formatter = null;
      }
      gridColumns.push(col);
    }
  }
  $.getJSON(detailsURL, function (data) {
    var gridParms = {
      autoGenerateColumns: false,
      primaryKey: "ID",
      features: [
        { name: "Selection", mode: "row", rowSelectionChanging: detailSelectionChangedRunInfo },
        { name: "Resizing" },
        { name: "Sorting", type: "local" }
      ],
      columns: gridColumns,
      dataSource: data,
      dataSourceType: 'json',
      responseDataKey: "Results",
      dataBound: markAsReviewedRunInfo,
    };
    if ((_toolType != null) && (_toolType.DataGridAttributes != null)) {
      jQuery.extend(gridParms, JSON.parse(_toolType.DataGridAttributes));
    }
    $("#DetailsGrid").igGrid(gridParms);
    if ($("#chkCopyOnGet").is(':checked')) {
      copySelected(attachmentID, title, data);
    }
  });
}

function requestHeaderDataRunInfo() {
  var startDate = $("#StartDate").igDatePicker("value");
  var startTime = $("#StartTime").igTimePicker("value");
  var endDate = $("#EndDate").igDatePicker("value");
  var endTime = $("#EndTime").igTimePicker("value");
  var parms = {
    datebegin: new Date(
      startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),
      startTime.getHours(), startTime.getMinutes(), startTime.getSeconds()).toISOString(),
    dateend: new Date(
      endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),
      endTime.getHours(), endTime.getMinutes(), endTime.getSeconds()).toISOString(),
  }
  var headerId = 0;
  if (_initialHeaderId > 0) {
    headerId = _initialHeaderId;
    parms.headerid = headerId;
    $("#HeaderId").text(headerId);
    $("#HeaderAttachmentId").text(_initialHeaderAttachmentId);
    _initialHeaderId = -1;
  }
  if (!_toolType.DataGridAttributes || _toolType.DataGridAttributes.indexOf('pinButton') === -1)
    $("#PinButton").hide();
  else
    $("#PinButton").show();
  var headerURL = _apiUrl + "/tooltypes/" + _toolType.ID + "/headers?" + $.param(parms);
  var gridColumns = [
    { key: "ID", dataType: "number", hidden: true },
    { key: "AttachmentID", dataType: "string", hidden: true },
    { key: "Title", dataType: "string", hidden: true },
  ];
  for (var i = 0; i < _toolTypeMetaData.length; i++) {
    var f = _toolTypeMetaData[i];
    if ((f.Header == true) && (f.GridDisplayOrder > 0)) {
      var col = {
        key: f.ColumnName,
        headerText: f.DisplayTitle,
        width: "150px",
      };
      if (f.GridAttributes != null)
        jQuery.extend(col, JSON.parse(f.GridAttributes));
      if (col.formatter != null) {
        if (col.formatter == "boolToYesNo")
          col.formatter = boolToYesNo;
        else
          col.formatter = null;
      }
      gridColumns.push(col);
    }
  }
  var gridParms = {
    autoGenerateColumns: false,
    primaryKey: "ID",
    height: "100%",
    width: "100%",
    features: [
      { name: "Paging", type: "local", recordCountKey: "TotalRows", pageSize: 100, pageSizeList: [50, 100, 250, 500], pageSizeUrlKey: "pageSize", "pageIndexUrlKey": "page" },
      { name: "Selection", mode: "row", rowSelectionChanged: headerSelectionChangedRunInfo },
      { name: "Filtering", type: "local" },
      { name: 'Resizing' },
      { name: "Sorting", type: "local" }
    ],
    columns: gridColumns,
    dataSource: headerURL,
    responseDataKey: "Results",
  };
  if ((_toolType != null) && (_toolType.HeaderGridAttributes != null)) {
    jQuery.extend(gridParms, JSON.parse(_toolType.HeaderGridAttributes));
  }
  $("#HeaderGrid").igGrid(gridParms);
  if (headerId > 0) {
    loadDetailsRunInfo();
  }
}

function reviewButtonRunInfo() {
  var toolTypeId = $("#ToolTypeID").text();
  var headerId = parseInt($("#HeaderId").text());
  $("#ReviewButton").prop("disabled", true);
  $.ajax({
    type: "POST",
    url: _apiUrl + "/awaitingdispo/markasawaiting?tooltypeid=" + toolTypeId + "&headerid=" + headerId,
    success: function (e) {
      DisplayWSMessage("info", "Marked as awaiting disposition", e);
      $("#ReviewButton").prop("disabled", false);
    },
    error: function (e, ajaxOptions, ex) {
      DisplayWSMessage("error", "There was an error marking header as awaiting disposition.", e, ex);
      $("#ReviewButton").prop("disabled", false);
    }
  });
}

function recipeParametersButtonRunInfo() {
  var selectedRow = $("#HeaderGrid").data("igGridSelection").selectedRow();
  if (selectedRow !== null) {
    loadDetailsRunInfo();
    $("#RecipeParametersButton").prop("disabled", true);
    var rowData = $("#HeaderGrid").data("igGrid").dataSource.dataView()[selectedRow.index];
    var stringified = JSON.stringify(rowData);
    stringified = stringified.replace(/"Tool":/gm, '"MesEntity":');
    stringified = stringified.replace(/"Equipment ID":/gm, '"MesEntity":');
    var jsonObject = JSON.parse(stringified);
    DisplayWSMessage("info", "Recipe Parameters", null);
    $("#ModalHeaderGrid").igGrid({
      dataSource: jsonObject,
      dataSourceType: 'json',
      features: [
        { name: 'Resizing' }
      ],
      columns: [
        { headerText: "Tool", key: "MesEntity", dataType: "string", width: "10%" },
        { key: "Reactor", dataType: "string", width: "10%" },
        { key: "RDS", dataType: "string", width: "10%" },
        { key: "PSN", dataType: "string", width: "10%" },
        { key: "Layer", dataType: "string", width: "10%" },
        { key: "Zone", dataType: "string", width: "10%" }
      ]
    });
    var gridCreated = $("#ModalBodyGrid").data("igGrid");
    if (gridCreated)
      $("#ModalBodyGrid").igGrid("destroy");
    $.getJSON('https://oi-prod-ec-api.mes.infineon.com/api/oiWizard/materials/rds/' + jsonObject.RDS, function (data) {
      $("#RecipeParametersButton").prop("disabled", false);
      var text = "";
      var seperator = '\t';
      for (var i = 0; i < data.rds.rdsLayers.length; i++) {
        text = text
          + data.rds.rdsLayers[i].EpiTime
          + seperator + data.rds.rdsLayers[i].EpiH2Flow
          + seperator + data.rds.rdsLayers[i].TCSFlow
          + seperator + data.rds.rdsLayers[i].DiluentAdjParam
          + seperator + data.rds.rdsLayers[i].EpiH2Flow
          + seperator + data.rds.rdsLayers[i].DopantFlow
          + seperator + data.rds.rdsLayers[i].FOffset
          + seperator + data.rds.rdsLayers[i].SOffset
          + seperator + data.rds.rdsLayers[i].ROffset
          + seperator + data.rds.rdsLayers[i].SuscEtch;
      }
      $("#textareaClipboard").val(text);
      $("#ModalBodyGrid").igGrid({
        dataSource: data.rds.rdsLayers,
        features: [
          { name: 'Resizing' }
        ],
        columns: [
          { headerText: "Dep Time", key: "EpiTime", dataType: "number", width: "10%" },
          { headerText: "H2", key: "EpiH2Flow", dataType: "number", width: "10%" },
          { headerText: "TCS", key: "TCSFlow", dataType: "number", width: "10%" },
          { headerText: "DIL", key: "DiluentAdjParam", dataType: "string", width: "10%" },
          { headerText: "SRC", key: "EpiH2Flow", dataType: "number", width: "10%" },
          { headerText: "INJ", key: "DopantFlow", dataType: "string", width: "10%" },
          { headerText: "F", key: "FOffset", dataType: "string", width: "10%" },
          { headerText: "S", key: "SOffset", dataType: "string", width: "10%" },
          { headerText: "R", key: "ROffset", dataType: "string", width: "10%" },
          { headerText: "Susc Etch", key: "SuscEtch", dataType: "string", width: "10%" },
        ],
        responseDataKey: "Results",
      });
    });
  }
}

function viewButtonRunInfo() {
  var selectedRow = $("#HeaderGrid").data("igGridSelection").selectedRow();
  if (selectedRow !== null) {
    $("#ViewButton").prop("disabled", true);
    loadDetailsRunInfo();
    var rowData = $("#HeaderGrid").data("igGrid").dataSource.dataView()[selectedRow.index];
    var stringified = JSON.stringify(rowData);
    stringified = stringified.replace(/"Tool":/gm, '"MesEntity":');
    stringified = stringified.replace(/"Equipment ID":/gm, '"MesEntity":');
    var jsonObject = JSON.parse(stringified);
    DisplayWSMessage("info", "View", null);
    $("#ModalHeaderGrid").igGrid({
      dataSource: jsonObject,
      dataSourceType: 'json',
      features: [
        { name: 'Resizing' }
      ],
      columns: [
        { headerText: "Tool", key: "MesEntity", dataType: "string", width: "10%" },
        { key: "Reactor", dataType: "string", width: "10%" },
        { key: "RDS", dataType: "string", width: "10%" },
        { key: "PSN", dataType: "string", width: "10%" },
        { key: "Layer", dataType: "string", width: "10%" },
        { key: "Zone", dataType: "string", width: "10%" }
      ]
    });
    var gridCreated = $("#ModalBodyGrid").data("igGrid");
    if (gridCreated)
      $("#ModalBodyGrid").igGrid("destroy");
    var headerId = $("#HeaderId").text();
    var toolTypeID = $("#ToolTypeID").text();
    var detailsURL = _apiUrl + "/tooltypes/" + toolTypeID + "/headers/" + headerId + "/data";
    $.getJSON(detailsURL, function (data) {
      var obj = {};
      var text = "";
      var seperator = jsonObject.RDS.length < 6 ? '\r' : '\t';
      for (var i = 0; i < data.Results.length && (jsonObject.RDS.length < 6 || i < 9); i++) {
        if (data.Results[i].Thickness) {
          text = text + data.Results[i].Thickness + seperator;
          obj['Point' + (i + 1)] = data.Results[i].Thickness;
        }
        else if (data.Results[i].Rs) {
          text = text + data.Results[i].Rs + seperator;
          obj['Point' + (i + 1)] = data.Results[i].Rs;
        }
      }
      if (text.length === 0)
        $("#textareaClipboard").val(text);
      else
        $("#textareaClipboard").val(text.substring(0, text.length - 1));
      $("#ModalBodyGrid").igGrid({
        dataSource: obj,
        dataSourceType: 'json',
        features: [
          { name: 'Resizing' }
        ],
        columns: [
          { headerText: "Point 1", key: "Point1", dataType: "string", width: "10%" },
          { headerText: "Point 2", key: "Point2", dataType: "string", width: "10%" },
          { headerText: "Point 3", key: "Point3", dataType: "string", width: "10%" },
          { headerText: "Point 4", key: "Point4", dataType: "string", width: "10%" },
          { headerText: "Point 5", key: "Point5", dataType: "string", width: "10%" },
          { headerText: "Point 6", key: "Point6", dataType: "string", width: "10%" },
          { headerText: "Point 7", key: "Point7", dataType: "string", width: "10%" },
          { headerText: "Point 8", key: "Point8", dataType: "string", width: "10%" },
          { headerText: "Point 9", key: "Point9", dataType: "string", width: "10%" },
        ]
      });
      $("#ViewButton").prop("disabled", false);
    });
  }
}

function pinButtonRunInfo() {
  var toolTypeId = $("#ToolTypeID").text();
  var selectedRow = $("#HeaderGrid").data("igGridSelection").selectedRow();
  if (selectedRow !== null) {
    loadDetailsRunInfo();
    $("#PinButton").prop("disabled", true);
    var rowData = $("#HeaderGrid").data("igGrid").dataSource.dataView()[selectedRow.index];
    var stringified = JSON.stringify(rowData);
    stringified = stringified.replace(/"Tool":/gm, '"MesEntity":');
    stringified = stringified.replace(/"Equipment ID":/gm, '"MesEntity":');
    var jsonObject = JSON.parse(stringified);
    $.ajax({
      type: "POST",
      url: _apiUrl + '/pin/' + toolTypeId + "/markAsPinned",
      data: jsonObject,
      success: function (e) {
        var gridCreated = $("#ModalBodyGrid").data("igGrid");
        if (gridCreated)
          $("#ModalBodyGrid").igGrid("destroy");
        DisplayWSMessage("info", "Marked as pinned", e);
        // DisplayWSMessage("info", stringified, e);
        $("#PinButton").prop("disabled", false);
        $.getJSON(_apiUrl + '/pin/' + toolTypeId + "/pinned?biorad_id=" + _BioRadId + "&cde_id=" + _CdeId + "&rds=" + jsonObject.RDS, function (data) {
          $("#ModalHeaderGrid").igGrid({
            dataSource: data,
            features: [
              { name: 'Resizing' }
            ],
            columns: [
              { key: "ID", dataType: "number", hidden: true, },
              { key: "ToolTypeID", dataType: "number", hidden: true, },
              { headerText: "Tool", key: "MesEntity", dataType: "string", width: "10%" },
              { key: "Reactor", dataType: "string", width: "10%" },
              { key: "RDS", dataType: "string", width: "10%" },
              { key: "PSN", dataType: "string", width: "10%" },
              { key: "Layer", dataType: "string", width: "10%" },
              { key: "Zone", dataType: "string", width: "10%" }
            ],
            responseDataKey: "Results",
          });
          var text = "";
          var seperator = '\t';
          for (var i = 0; i < data.Results.length; i++) {
            text = text
              + data.Results[i].Point1
              + seperator + data.Results[i].Point2
              + seperator + data.Results[i].Point3
              + seperator + data.Results[i].Point4
              + seperator + data.Results[i].Point5
              + seperator + data.Results[i].Point6
              + seperator + data.Results[i].Point7
              + seperator + data.Results[i].Point8
              + seperator + data.Results[i].Point9;
          }
          $("#textareaClipboard").val(text);
          $("#ModalBodyGrid").igGrid({
            dataSource: data,
            features: [
              { name: 'Resizing' }
            ],
            columns: [
              { key: "ID", dataType: "number", hidden: true, },
              { key: "ToolTypeID", dataType: "number", hidden: true, },
              { headerText: "Point 1", key: "Point1", dataType: "number", width: "10%" },
              { headerText: "Point 2", key: "Point2", dataType: "number", width: "10%" },
              { headerText: "Point 3", key: "Point3", dataType: "number", width: "10%" },
              { headerText: "Point 4", key: "Point4", dataType: "number", width: "10%" },
              { headerText: "Point 5", key: "Point5", dataType: "number", width: "10%" },
              { headerText: "Point 6", key: "Point6", dataType: "number", width: "10%" },
              { headerText: "Point 7", key: "Point7", dataType: "number", width: "10%" },
              { headerText: "Point 8", key: "Point8", dataType: "number", width: "10%" },
              { headerText: "Point 9", key: "Point9", dataType: "number", width: "10%" },
            ],
            responseDataKey: "Results",
          });
        });
      },
      error: function (e, ajaxOptions, ex) {
        DisplayWSMessage("error", "There was an error marking header as pinned.", e, ex);
        $("#PinButton").prop("disabled", false);
      }
    });
  }
}

function oiExportButtonRunInfo() {
  var headerId = $("#HeaderId").text();
  var toolTypeID = $("#ToolTypeID").text();
  $("#OIExportButton").prop("disabled", true);
  $.ajax({
    type: "POST",
    url: _apiUrl + "/tooltypes/" + toolTypeID + "/headers/" + headerId + "/oiexport",
    success: function (r) {
      $("#OIExportResult").text("Exported!");
    },
    error: function (e, ajaxOptions, ex) {
      DisplayWSMessage("error", "There was an error exporting.", e, ex);
      $("#OIExportButton").prop("disabled", false);
    }
  });
}

function setInitialDateTimesRunInfo(milliseconds) {
  if (!milliseconds) {
    var startDate = $("#StartDate").igDatePicker("value");
    var startTime = $("#StartTime").igTimePicker("value");
    var endDate = $("#EndDate").igDatePicker("value");
    var endTime = $("#EndTime").igTimePicker("value");
    var startDateTime = new Date(
      startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),
      startTime.getHours(), startTime.getMinutes(), startTime.getSeconds());
    var endDateTime = new Date(
      endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),
      endTime.getHours(), endTime.getMinutes(), endTime.getSeconds());
    milliseconds = Math.abs(endDateTime - startDateTime);
  }
  var startTime = new Date(Date.now() - milliseconds);
  $("#StartDate").igDatePicker({
    dateInputFormat: "date",
    value: startTime,
    width: 125
  });
  $("#StartTime").igTimePicker({
    dateInputFormat: "time",
    value: startTime,
    width: 110
  });
  var endTime = new Date(Date.now());
  $("#EndDate").igDatePicker({
    dateInputFormat: "date",
    value: endTime,
    width: 125
  });
  $("#EndTime").igTimePicker({
    dateInputFormat: "time",
    value: endTime,
    width: 110
  });
}

function initRunInfo(apiUrl, initialToolTypeID, initialHeaderId, initialHeaderAttachmentId) {
  _apiUrl = apiUrl;
  _initialHeaderId = initialHeaderId;
  _initialHeaderAttachmentId = initialHeaderAttachmentId;
  $.getJSON(_apiUrl + '/tooltypes', function (data) {
    for (var i = 0; i < data.Results.length; i++) {
      if (data.Results[i].ToolTypeName === "CDE") {
        _CdeId = data.Results[i].ID;
      }
      else if (data.Results[i].ToolTypeName === "BioRad") {
        _BioRadId = data.Results[i].ID;
      }
    }
    $("#ToolType").igCombo({
      dataSource: data,
      responseDataKey: "Results",
      textKey: "ToolTypeName",
      valueKey: "ID",
      mode: "dropdown",
      width: 150,
      itemsRendered: function (evt, ui) {
        loadHeaderGridRunInfo();
      },
      selectionChanged: loadHeaderGridRunInfo,
      initialSelectedItems: [{ value: initialToolTypeID }]
    });
  });
  setInitialDateTimesRunInfo(6 * 60 * 60 * 1000);
  $("#HeaderGrid").on("dblclick", "tr", loadDetailsRunInfo);
  $("#LoadHeadersButton").click(loadHeaderGridRunInfo);
  $("#GetDataButton").click(loadDetailsRunInfo);
  $("#ReviewButton").click(reviewButtonRunInfo);
  $("#RecipeParametersButton").click(recipeParametersButtonRunInfo);
  $("#ViewButton").click(viewButtonRunInfo);
  $("#PinButton").click(pinButtonRunInfo);
  $("#OIExportButton").click(oiExportButtonRunInfo);
  setInterval(function () {
    if ($("#chkAutoRefresh").is(':checked')) {
      setInitialDateTimesRunInfo(null);
      $("#LoadHeadersButton").click();
    }
  }, 180000);
};

function triggerFileDownload(fileName, url) {
  const anchorElement = document.createElement('a');
  anchorElement.href = url;
  anchorElement.download = fileName ?? '';
  anchorElement.click();
  anchorElement.remove();
}

function initIndex() {
}

function copy(copyText) {
  if (typeof copyText.select !== "undefined")
    copyText.select();
  if (typeof copyText.setSelectionRange !== "undefined")
    copyText.setSelectionRange(0, 99999); // For mobile devices
  if (typeof copyText.value !== "undefined")
    navigator.clipboard.writeText(copyText.value);
  else
    navigator.clipboard.writeText(copyText);
}

function clearWorkMaterial() {
  _workMaterial = {};
  $("#scan").val("");
  $("#layer1").show();
  $("#layer2").show();
  $("#layer3").show();
  $("#username").val("");
  $("#runDataSheet1").hide();
  $("#runDataSheet2").hide();
  $("#runDataSheet3").hide();
  $("#runDataSheet4").hide();
  $("#runDataSheet5").hide();
  $("#runDataSheet6").hide();
  $("#runDataSheet1").val("");
  $("#runDataSheet2").val("");
  $("#runDataSheet3").val("");
  $("#runDataSheet4").val("");
  $("#runDataSheet5").val("");
  $("#runDataSheet6").val("");
  var gridCreated = $("#cassetteGrid").data("igGrid");
  if (gridCreated)
    $("#cassetteGrid").igGrid("destroy");
}

function postWorkMaterial() {
  var row = $("#cassetteGrid").igGrid("selectedRow");
  if (row == null)
    return;
  var data = $("#cassetteGrid").igGrid("findRecordByKey", row.id);
  if (data == null)
    return;
  if (!_workMaterial['layer'])
    ShowErrorMessage("Select layer and try agian");
  else {
    _workMaterial['psn'] = data.PSN;
    _workMaterial['layer'] = data.Layer;
    _workMaterial['pocket'] = data.Pocket;
    _workMaterial['reactor'] = data.Reactor;
    _workMaterial['inSlotNumber'] = data.InSlotNumber;
    _workMaterial['runDataSheet'] = data.RunDataSheet;
    _workMaterial['outSlotNumber'] = data.OutSlotNumber;
    _workMaterial['inCassetteNumber'] = data.InCassetteNumber;
    _workMaterial['outCassetteNumber'] = data.OutCassetteNumber;
    var mesage = "Data Saved for {" + _workMaterial['scan'] + "} RDS {" + data.RunDataSheet + "} slot {" + data.OutSlotNumber + "}";
    $.post(_apiUrl + "/api/Reactors/", _workMaterial, function (data) {
      DisplayWSMessage("info", mesage + " use [" + data + "]", null);
    }).fail(function () {
      ShowErrorMessage("Error");
    });
  }
}

function initWorkMaterial(apiUrl) {
  _apiUrl = apiUrl;
  $("#runDataSheet1").hide();
  $("#runDataSheet2").hide();
  $("#runDataSheet3").hide();
  $("#runDataSheet4").hide();
  $("#runDataSheet5").hide();
  $("#runDataSheet6").hide();
};

function layer(layerNumber) {
  $("#layer1").hide();
  $("#layer2").hide();
  $("#layer3").hide();
  var scan = $("#scan").val();
  $("#layer" + layerNumber).show();
  var username = $("#username").val();
  _workMaterial['layer'] = layerNumber;
  if (!scan || scan === "" || scan.length < 3 || (scan[0] !== 'o' && scan[0] !== 'O')) {
    ShowErrorMessage("Invalid WM Out");
  }
  else if (!username || username === "" || username.length < 2) {
    ShowErrorMessage("Invalid username");
  }
  else {
    _workMaterial['scan'] = scan;
    _workMaterial['username'] = username;
    $.getJSON(_apiUrl + "/api/WorkMaterial/" + scan + "/", function (data) {
      if (data.Results.length === 0)
        ShowErrorMessage("No data found");
      else {
        $("#cassetteGrid").igGrid({
          dataSource: data,
          primaryKey: "OutSlotNumber",
          features: [
            { name: "Selection", mode: "row", multipleSelection: false, rowSelectionChanged: postWorkMaterial },
            { name: 'Resizing' },
            { name: "Filtering", type: "local" },
          ],
          responseDataKey: "Results",
        });
        var distinct = [];
        for (var i = 0; i < data.Results.length; i++) {
          if (distinct.indexOf(data.Results[i].RunDataSheet) > -1)
            continue;
          distinct.push(data.Results[i].RunDataSheet);
        }
        if (distinct.length > 0) {
          $("#runDataSheet1").val(distinct[0]);
          $("#runDataSheet1").show();
        }
        if (distinct.length > 1) {
          $("#runDataSheet2").val(distinct[1]);
          $("#runDataSheet2").show();
        }
        if (distinct.length > 2) {
          $("#runDataSheet3").val(distinct[2]);
          $("#runDataSheet3").show();
        }
        if (distinct.length > 3) {
          $("#runDataSheet4").val(distinct[3]);
          $("#runDataSheet4").show();
        }
        if (distinct.length > 4) {
          $("#runDataSheet5").val(distinct[4]);
          $("#runDataSheet5").show();
        }
        if (distinct.length > 5) {
          $("#runDataSheet6").val(distinct[4]);
          $("#runDataSheet6").show();
        }
        $("#cassetteGrid").on("dblclick", "tr", postWorkMaterial);
      }
    });
  }
};

function runDataSheet(runDataSheetIndex) {
  var runDataSheet = $("#runDataSheet" + runDataSheetIndex).val();
  _workMaterial['runDataSheet'] = runDataSheet;
  $("#cassetteGrid").igGridFiltering("filter", ([{ fieldName: "RunDataSheet", expr: runDataSheet, cond: "equals" }]));
};

function restartButton(apiUrl) {
  clearWorkMaterial();
};

// { "frame": { "controller": "SpreadingResistanceProfile", "height": "718px", "width": "698px" } }
// { "div": { "width": "698px", "position": "absolute", "top":"700px", "left": "800px" }, "height": "160px" }