<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ page_header }}</title>
<link href="https://unpkg.com/tabulator-tables@5.2/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@5.2/dist/js/tabulator.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
body {
  font-size: .875rem;
}
.feather {
  width: 16px;
  height: 16px;
  vertical-align: text-bottom;
}
.sidebar {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 100; /* Behind the navbar */
  padding: 48px 0 0; /* Height of navbar */
  box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}
@media (max-width: 767.98px) {
  .sidebar {
    top: 5rem;
  }
}
.sidebar-sticky {
  position: relative;
  top: 0;
  height: calc(100vh - 48px);
  padding-top: .5rem;
  overflow-x: hidden;
  overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
}
.sidebar .nav-link {
  font-weight: 500;
  color: #333;
}
.sidebar .nav-link .feather {
  margin-right: 4px;
  color: #727272;
}
.sidebar .nav-link.active {
  color: #2470dc;
}
.sidebar .nav-link:hover .feather,
.sidebar .nav-link.active .feather {
  color: inherit;
}
.sidebar-heading {
  font-size: .75rem;
  text-transform: uppercase;
}
.navbar-brand {
  padding-top: .75rem;
  padding-bottom: .75rem;
  font-size: 1rem;
  background-color: rgba(0, 0, 0, .25);
  box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
}
.navbar .navbar-toggler {
  top: .25rem;
  right: 1rem;
}
.navbar .form-control {
  padding: .75rem 1rem;
  border-width: 0;
  border-radius: 0;
}
.form-control-dark {
  color: #fff;
  background-color: rgba(255, 255, 255, .1);
  border-color: rgba(255, 255, 255, .1);
}
.form-control-dark:focus {
  border-color: transparent;
  box-shadow: 0 0 0 3px rgba(255, 255, 255, .25);
}
</style>
<script src="https://cdn.plot.ly/plotly-2.4.2.min.js"></script>
<script>
  var atypes = {{analysis_list}};
  var tableData = {{table_data}};
  function updateImages() {
    var rsel  = document.getElementById("SelectRegion");
    var RNAME = rsel.options[rsel.selectedIndex].value;
    var msel  = document.getElementById("SelectModel");
    var MNAME = msel.options[msel.selectedIndex].value;
    var psel  = document.getElementById("SelectPlot");
    var PNAME = psel.options[psel.selectedIndex].value;
{% for aname,analysis in analyses.items() -%}
{% for pname,plot in analysis.items() -%}
{% for item in plot -%}
{%- for mname,pattern in item.items() %}
    document.getElementById("{{pname}}_{{mname}}").src = "{{pattern}}".replace("MNAME",MNAME).replace("RNAME",RNAME);
{%- endfor -%}
{% endfor -%}
{% endfor -%}
{% endfor %}
    var model_names = {{model_names}};
    var ref_plots = {{ref_plots}};
    if (ref_plots.includes(PNAME)) {
      model_names.unshift("Reference");
      document.getElementById("divReference").style.opacity = 100;
    }else{
      document.getElementById("divReference").style.opacity = 0;
    }
    model_names.forEach((x, i) => document.getElementById("div" + x).src = x + "_" + RNAME + "_" + PNAME + ".png");
  };
  function formatterValue(cell, formatterParams, onRendered) {
    if (isNaN(Number.parseFloat(cell.getValue()))) {
        return cell.getValue();
    } else {
        return Number.parseFloat(cell.getValue()).toFixed(2);
    }
  };
  function setTable(region, analysis) {
    /* creates a nested dictionary of models and scalar names */
    var cols = ['source'];
    var o = tableData.reduce((a, b) => {
        a[b.source] = a[b.source] || {};
        if (b.region != region) return a;
        if (analysis) {
            if (b.analysis != analysis) return a;
        };
        a[b.source][b.name] = b.value;
        if (cols.indexOf(b.name) < 0) cols.push(b.name);
        return a;
    }, {});
    /* build columns dictionary for the table */
    var cols = cols.map(function (k) {
        return { title: k, field: k, headerVertical: true, formatter: formatterValue };
    });
    /* unnest the dictionary to put it how the tabulator wants it */
    var data = Object.keys(o).map(function (k) {
        return Object.assign({ 'source': k }, o[k]);
    });
    var table = new Tabulator("#scalartable", {
        data: data,
        layout: "fitDataTable",
        columns: cols
    });
    table.on("rowClick", function (e, row) {
        var rowData = row.getData();
        if (rowData["source"] != "Reference") {
          document.getElementById('SelectModel').value = rowData["source"];
          updateImages();
        }
        var cells = row.getCells();
        cells.forEach(function (cell, i) {
            for (const c of cell.getColumn().getCells()) {
                c.getElement().style.backgroundColor = "";
                c.getElement().style.fontWeight = "normal";
            }
        });
        row.getElement().childNodes[0].style.fontWeight = 'bold';
        cells.forEach(function (cell, i) {
            if (!isNaN(Number.parseFloat(cell.getValue()))) {
                for (const c of cell.getColumn().getCells()) {
                    if (c != cell && Number.parseFloat(c.getValue()) > Number.parseFloat(cell.getValue())) {
                        c.getElement().style.backgroundColor = "#d8daeb";
                    }
                    if (c != cell && Number.parseFloat(c.getValue()) <= Number.parseFloat(cell.getValue())) {
                        c.getElement().style.backgroundColor = "#fee0b6";
                    }
                }

            }
        });
    });
  };
  function clickMode(mode) {
    /* make the mode active */
    document.getElementById("singleModel").classList.remove('active');
    document.getElementById("allModels").classList.remove('active');
    document.getElementById(mode).classList.add('active');
    if (mode == "singleModel") {
      /* turn on/off appropriate divs */
      document.getElementById("divTable").style.display = "block";
      atypes.forEach((x, i) => document.getElementById("div" + x).style.display = "block");
      document.getElementById("divAllModels").style.display = "none";
    }else{
      document.getElementById("divTable").style.display = "none";
      atypes.forEach((x, i) => document.getElementById("div" + x).style.display = "none");
      document.getElementById("divAllModels").style.display = "block";
      atypes.forEach((x, i) => document.getElementById(x).classList.remove('active'));
    }
  };
  function clickAnalysis(analysis) {
    /* turn single model mode on */
    clickMode("singleModel");
    /* highlight the active analysis */
    document.getElementById("Overview").classList.remove('active');
    atypes.forEach((x, i) => document.getElementById(x).classList.remove('active'));
    document.getElementById(analysis).classList.add('active');
    /* turn on analysis div */
    if (analysis == "Overview"){
      atypes.forEach((x, i) => document.getElementById("div" + x).style.display = "block");
    }else{
      atypes.forEach((x, i) => document.getElementById("div" + x).style.display = "none");
      document.getElementById("div" + analysis).style.display = "block";
    }
    /* update the table */
    var rsel = document.getElementById("SelectRegion");
    var RNAME = rsel.options[rsel.selectedIndex].value;
    setTable(RNAME, (analysis=="Overview") ? null : analysis);
  };
  function updateRegion() {
    /* which analysis is active? */
    var analysis = "Overview"
    for (const a of atypes) {
      if(document.getElementById(a).classList.contains("active")){
        analysis = a;
        break;
      }
    }
    /* update the table */
    var rsel = document.getElementById("SelectRegion");
    var RNAME = rsel.options[rsel.selectedIndex].value;
    setTable(RNAME, (analysis=="Overview") ? null : analysis);
    updateImages();
  };
</script>
</head>
<body>
<header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="#">{{ page_header }}</a>
<button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</header>
<div class="container-fluid">
<div class="row">
<nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
<div class="position-sticky pt-3">

<!-- Model select -->
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Model</span>
</h6>
<select id="SelectModel" class="form-select" aria-label="ModelSelect" onclick="updateImages()">
{% for name in model_names %}
<option value="{{name}}">{{name}}</option>
{% endfor %}
</select>

<!-- Region select -->
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Region</span>
</h6>
<select id="SelectRegion" class="form-select" aria-label="RegionSelect" onclick="updateRegion()">
{% for label, name in regions.items() %}
<option value="{{label}}">{{name}}</option>
{% endfor %}
</select>

<!-- Mode select -->
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Mode</span>
</h6>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" id="singleModel" aria-current="page" href="#" onclick="clickAnalysis('Overview')">
Single Model (All Plots)
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="allModels" aria-current="page" href="#" onclick="clickMode('allModels')">
All Models (By Plot)
</a>
</li>

<!-- Analyses -->
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Analysis Types</span>
</h6>
<ul class="nav flex-column mb-2">
<li class="nav-item">
<a class="nav-link" id="Overview" aria-current="page" href="#" onclick="clickAnalysis('Overview')">
All
</a>
</li>
{% for name in analyses %}
<li class="nav-item">
<a class="nav-link" id="{{name}}" href="#" onclick="clickAnalysis('{{name}}')">{{name}}</a>
</li>
{% endfor %}
</ul>

<!--- Data Information -->
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Data Information</span>
</h6>
<ul class="nav flex-column mb-2">
{% for label, value in data_information.items() %}
<li class="nav-item">
<a class="nav-link">
<div class="fw-bold">{{label}}</div>
{{value}}
</a>
</li>
{% endfor %}
</ul>

</div>
</nav>

<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">

<!--- Table of Scalars -->
<div id="divTable">
<br><h2>Scalar Table</h2>
<div id="scalartable"></div>
</div>

<!--- Analyses -->
{% for aname,analysis in analyses.items() %}
<div id="div{{aname}}">
<br><h2>{{aname}}</h2>
{% for pname,plot in analysis.items() -%}
{% for item in plot -%}
{% for mname,pattern in item.items() %}
<img id="{{pname}}_{{mname}}" src="{{pattern}}" width="49%">
{% endfor -%}
{% endfor -%}
{% endfor %}
</div>
{% endfor %}

<!--- All models mode -->
<div id="divAllModels">
  <br><h2>All Models</h2>
  <select id="SelectPlot" class="form-select" aria-label="PlotSelect" onclick="updateImages()">
{% for plot in all_plots %}
    <option value="{{plot}}">{{plot}}</option>
{% endfor %}
  </select>
  <img id="divReference" src="Reference_None_mean.png" width="32%">
{% for mname in model_names %}
  <img id="div{{mname}}" src="{{mname}}_None_mean.png" width="32%">
{% endfor %}
</div>

<script>
  clickAnalysis("Overview");
  updateImages();
</script>
</main>

</div>
</div>
</body>
</html>
