{% load sekizai_tags static i18n %}

{% addtoblock "css" %}
  <link href="{% static 'c3/c3.min.css' %}" rel="stylesheet" type="text/css">
{% endaddtoblock %}


<h3 class="mt-4">{% trans "Performance by Class Type" %}
  <a class="btn btn-sm btn-outline-secondary" href="{% url 'AveragesByClassTypeCSV' %}">{% trans "Download Data" %}</a>
</h3>


<div class="card">

  <div class="card-header">
    <ul class="nav nav-tabs card-header-tabs">
      <li class="nav-item">
        <a href="#" class="nav-link active classTypeButton" data-startDate="{{ limitMonthDates.12 }}">{% trans "Last 12 Months" %}</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link classTypeButton">{% trans "All Time" %}</a>
      </li>
    </ul>
  </div>

  <div class="card-body">
    <div id="ClassTypePerformance"></div>
  </div>

</div>

{% addtoblock "js" %}
  <script src="{% static 'd3/d3.min.js' %}"></script>
{% endaddtoblock %}
{% addtoblock "js" %}
  <script src="{% static 'c3/c3.min.js' %}"></script>
{% endaddtoblock %}
{% addtoblock "js" %}
<script type="text/javascript">
$(document).ready(function(){

  var avgAttendanceChart = null;
  var initialShowList = ['Average Registrations']
  var dataKey = 'type'

  function loadClassPerformanceChart(url) {

    $.getJSON(url, function(data) {

        xKeySet = {}
        for(var i in data) for(var k in data[i]) xKeySet[k] = true;

        xkeys = []
        for(var i in xKeySet) if (i != dataKey) xkeys.push(i);

        var hideList = xkeys.slice();

        for (var s in initialShowList) {
           var index = hideList.indexOf(initialShowList[s]);
           if (index > -1) hideList.splice(index, 1);
        }

        var chartData = {
          json: data,
          type: 'bar',
          hide: hideList,
          keys: {
            x: dataKey,
            value: xkeys,
          }
        }

        if(avgAttendanceChart == null) {
          avgAttendanceChart = c3.generate({
            bindto: '#ClassTypePerformance',
            data: chartData,
            axis: {
              x: {
                type: 'category' // this needed to load string x value
              }
            },
          });
        }
        else {
          avgAttendanceChart.load(chartData);
        }

    });
  }

  // Set the initial data on load
  loadClassPerformanceChart("{% url 'AveragesByClassTypeJSON' %}?startDate={{ limitMonthDates.12 }}");

  $('.classTypeButton').click(function(e){
      var startDate = $(this).attr('data-startDate');
      loadClassPerformanceChart("{% url 'AveragesByClassTypeJSON' %}?startDate=" + startDate);
      $('.classTypeButton').removeClass('active');
      $(this).addClass('active');
      e.preventDefault();
  });

});
</script>
{% endaddtoblock %}
