var _CdeId = null;
var _apiUrl = null;
var _BioRadId = null;
var _toolType = null;
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() {
  $("#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);
  $("#HeaderAttachmentFrame").prop("hidden", true);
  if (_toolType != null) {
    var visibleFrames = 0;
    if (_toolType.DisplayDataAttachment && _toolType.DisplayDataAttachment.length > 0) {
      visibleFrames += 1;
      $("#DataAttachmentFrame").prop("hidden", false);
    }
    if (_toolType.DisplayHeaderAttachment && _toolType.DisplayHeaderAttachment.length > 0) {
      visibleFrames += 1;
      $("#HeaderAttachmentFrame").prop("hidden", false);
    }
    var frameWidth = (98 / visibleFrames) + "%";
    $("#DataAttachmentFrame,#HeaderAttachmentFrame").css('width', frameWidth);
  }
}

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 detailSelectionChangedRunInfo(evt, ui) {
  $("#DataAttachmentFrame").prop("src", "");
  if (ui.row.index >= 0) {
    var rowData = ui.owner.grid.dataSource.dataView()[ui.row.index];
    var toolTypeID = $("#ToolTypeID").text();
    var attachmentUrlBase = _apiUrl + '/tooltypes/' + toolTypeID;
    var attachmentId = rowData.AttachmentID;
    if ((attachmentId == null) || (attachmentId === ''))
      return;
    if ((_toolType.DisplayDataAttachment == null) || (_toolType.DisplayDataAttachment === ''))
      return;
    $("#DataAttachmentFrame").prop("src", attachmentUrlBase + "/data/files/" + attachmentId + "/" + _toolType.DisplayDataAttachment);
  }
}

function loadHeaderAttachmentRunInfo() {
  var toolTypeID = $("#ToolTypeID").text();
  var attachmentId = $("#HeaderAttachmentId").text();
  var attachmentUrlBase = _apiUrl + '/tooltypes/' + toolTypeID;
  if ((attachmentId == null) || (attachmentId === '') || (_toolType.DisplayHeaderAttachment == null) || (_toolType.DisplayHeaderAttachment === '')) {
    $("#HeaderAttachmentFrame").prop("src", "");
  } else {
    $("#HeaderAttachmentFrame").prop("src", attachmentUrlBase + "/header/files/" + attachmentId + "/" + _toolType.DisplayHeaderAttachment);
  }
  $("#DataAttachmentFrame").prop("src", "");
}

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 loadDetailsRunInfo() {
  showDetailsDivRunInfo();
  loadHeaderAttachmentRunInfo();
  var gridCreated = $("#DetailsGrid").data("igGrid");
  if (gridCreated)
    $("#DetailsGrid").igGrid("destroy");
  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);
    }
  }
  var gridParms = {
    autoGenerateColumns: false,
    primaryKey: "ID",
    features: [
      { name: "Selection", mode: "row", rowSelectionChanging: detailSelectionChangedRunInfo },
      { name: "Resizing" },
      { name: "Sorting", type: "local" }
    ],
    columns: gridColumns,
    dataSource: detailsURL,
    responseDataKey: "Results",
    dataBound: markAsReviewedRunInfo,
  };
  if ((_toolType != null) && (_toolType.DataGridAttributes != null)) {
    jQuery.extend(gridParms, JSON.parse(_toolType.DataGridAttributes));
  }
  $("#DetailsGrid").igGrid(gridParms);
}

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;
  }
  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 - Work In Progress ***", 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 = "";
      for (var i = 0; i < data.rds.rdsLayers.length; i++) {
        text = text
          + data.rds.rdsLayers[i].EpiTime
          + "\t" + data.rds.rdsLayers[i].EpiH2Flow
          + "\t" + data.rds.rdsLayers[i].TCSFlow
          + "\t" + data.rds.rdsLayers[i].DiluentAdjParam
          + "\t" + data.rds.rdsLayers[i].EpiH2Flow
          + "\t" + data.rds.rdsLayers[i].DopantFlow
          + "\t" + data.rds.rdsLayers[i].FOffset
          + "\t" + data.rds.rdsLayers[i].SOffset
          + "\t" + data.rds.rdsLayers[i].ROffset
          + "\t" + data.rds.rdsLayers[i].SuscEtch
          + "\r"
      }
      $("#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 = "";
      for (var i = 0; i < data.Results.length && i < 9; i++) {
        if (data.Results[i].Thickness) {
          text = text + data.Results[i].Thickness + "\t";
          obj['Point' + (i + 1)] = data.Results[i].Thickness;
        }
        else if (data.Results[i].Rs) {
          text = text + data.Results[i].Rs + "\t";
          obj['Point' + (i + 1)] = data.Results[i].Rs;
        }
      }
      text = text + "\r";
      $("#textareaClipboard").val(text);
      $("#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 = "";
          for (var i = 0; i < data.Results.length; i++) {
            text = text
              + data.Results[i].Point1
              + "\t" + data.Results[i].Point2
              + "\t" + data.Results[i].Point3
              + "\t" + data.Results[i].Point4
              + "\t" + data.Results[i].Point5
              + "\t" + data.Results[i].Point6
              + "\t" + data.Results[i].Point7
              + "\t" + data.Results[i].Point8
              + "\t" + data.Results[i].Point9
              + "\r";
          }
          $("#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() {
  var startTime = new Date(Date.now() - 6 * 60 * 60 * 1000);//6 hours back from now
  $("#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();
  $("#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();
      $("#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() {
  var copyText = document.getElementById("textareaClipboard");

  // Select the text field
  copyText.select();
  copyText.setSelectionRange(0, 99999); // For mobile devices

  // Copy the text inside the text field
  navigator.clipboard.writeText(copyText.value);
}