{% extends "admin/base_site_gridpivot.html" %}
{% load i18n %}

{% block tools %}
{% if args.0 %}
  {% include "common/snippet_follow.html" %}
{% endif %}
{{block.super}}
{% endblock %}

{% block tabs %}
{% if args.0 %}
  {% tabs model %}
{% endif %}
{{block.super}}
{% endblock %}

{% block before_table %}{% if args.0 %}
<div id="graph" style="clear: both; height: 400px; padding: 10px; "></div>
{% endif %}{% endblock %}

{% block crosses %}
{% if args.0 %}$(function(){
  // Resize top graph
  var h = $(window).height();
  $("#graph").width($(window).width()-60).height(h>800 || h<550 ? 360 : h-450);
});{% endif %}

{% if args.0 or mode == "graph" %}
function drawGraphs(jsondata)
{
  $('#curerror').html("");
  {% if args.0 %}var margin = {top: 0, right: 100, bottom: 30, left: 50};
  {% else %}var margin = {top: 0, right: 0, bottom: 0, left: 50};
  {% endif %}var width = Math.max($({% if args.0 %}"#graph"{% else %}"#grid_graph"{% endif %}).width() - margin.left - margin.right, 0);
  var height = {% if args.0 %}$("#graph").height(){% else %}80{% endif %} - margin.top - margin.bottom;

  // Lookup table of displayed columns
  var fields = {};
  for (var i in cross_idx)
    fields[cross_idx[i]] = 0;

  // Define X-axis
  var domain_x = [];
  var bucketnamelength = 0;
  var date_style_with_hours = "{{request.DATE_STYLE_WITH_HOURS}}" === "True";
  for (var i in timebuckets)
  {
    domain_x.push(timebuckets[i]['name']);
    bucketnamelength = Math.max(timebuckets[i]['name'].length, bucketnamelength);
  }
  var x = d3.scale.ordinal()
    .domain(domain_x)
    .rangeRoundBands([0, width], 0);
  var x_width = x.rangeBand();
  {% if mode == "graph" and not args.0 %}graph.header(margin.left, x);{% endif %}

  // Define Y-axis
  var y = d3.scale.linear().rangeRound([height, 0]);

  // Draw all graphs
  $("#grid"){% if not args.0 %}.find(".graph"){% endif %}.each(function(index)
  {
    // Create a new SVG element
    $({% if args.0 %}$("#graph").get(0){% else %}this{% endif %}).html("");
    var svg = d3.select({% if args.0 %}$("#graph").get(0){% else %}this{% endif %})
      .append("svg")
      .attr("class","graphcell")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // Build the data for d3
    var max_y = 0;
    var data = [];
    for (var bckt in timebuckets)
    {
      var tmp = jsondata['rows'][index][timebuckets[bckt]['name']];
      data.push({
        'operation': jsondata['rows'][index]['operation'],
        'bucket': bckt,
        'proposed_start': tmp[0],
        'total_start': tmp[1],
        'proposed_end': tmp[2],
        'total_end': tmp[3],
        'proposed_production': tmp[4],
        'total_production': tmp[5]
        });
      if (tmp[1] > max_y && 1 in fields)
        max_y = tmp[1];
      else if (tmp[0] > max_y && 0 in fields)
        max_y = tmp[0];
      if (tmp[3] > max_y && 3 in fields)
        max_y = tmp[3];
      else if (tmp[2] > max_y && 2 in fields)
        max_y = tmp[2];
      if (tmp[5] > max_y && 5 in fields)
        max_y = tmp[5];
      else if (tmp[4] > max_y && 4 in fields)
        max_y = tmp[4];
    }

    // Update the scale of the Y-axis by looking for the max value
    y.domain([0,max_y]);

    // Number of bars to display
    var numbars = 0;
    var barnum = [0, 1, 2];
    if (0 in fields || 1 in fields)
      numbars++;
    else {
      barnum[1]--;
      barnum[2]--;
    }
    if (2 in fields || 3 in fields)
      numbars++;
    else
      barnum[2]--;
    if (4 in fields || 5 in fields)
      numbars++;

    // D3 visualization
    svg.selectAll("g")
      .data(data)
      .enter()
      .append("g")
      .attr("transform", function(d) { return "translate(" + x(timebuckets[d['bucket']]['name']) + ",0)"; })
      .each(function(d) {
        var bucket = d3.select(this);
        var top = y(0);
        if (d['total_start'] > d['proposed_start'] && 1 in fields)
        {
          top = y(d['total_start'] - d['proposed_start']);
          bucket.append("rect")
            .attr("width", x_width/numbars)
            .attr("x", barnum[0] * x_width / numbars)
            .attr("y", top)
            .attr("height", y(0) - top)
            .style("fill",'var(--frepple-color-produced-confirmed, #113C5E)')
            .on("click", function(d) {
                if (d3.event.defaultPrevented || d['total_start'] == 0) return;
                d3.select("#tooltip").style('display', 'none');

			          window.location ="{{ request.prefix }}"
			            +"/data/input/manufacturingorder/"
			            +"?noautofilter&operation__name="+admin_escape(d['operation'])
			            +"&startdate__lt="+timebuckets[d['bucket']]['enddate']
			            +"&startdate__gte="+timebuckets[d['bucket']]['startdate'];

                var coord = d3.mouse(document.body);
                d3.event.stopPropagation();
              });
        }
        if (d['proposed_start'] > 0 && (0 in fields || 1 in fields))
        {
          var newtop = y(d['total_start']);
          bucket.append("rect")
            .attr("width", x_width/numbars)
            .attr("x", barnum[0] * x_width / numbars)
            .attr("y", newtop)
            .attr("height", top - newtop)
            .style("fill",'var(--frepple-color-produced, #2B95EC)')
            .on("click", function(d) {
                if (d3.event.defaultPrevented || d['total_start'] == 0) return;
                d3.select("#tooltip").style('display', 'none');

			          window.location = "{{ request.prefix }}"
			            +"/data/input/manufacturingorder/"
			            +"?noautofilter&operation__name="+admin_escape(d['operation'])
			            +"&startdate__lt="+timebuckets[d['bucket']]['enddate']
			            +"&startdate__gte="+timebuckets[d['bucket']]['startdate'];

                var coord = d3.mouse(document.body);

                d3.event.stopPropagation();
              });
        }
        top = y(0);
        if (d['total_production'] > d['proposed_production'] && 5 in fields)
        {
          top = y(d['total_production'] - d['proposed_production']);
          bucket.append("rect")
            .attr("width", x_width / numbars)
            .attr("x", barnum[1] * x_width / numbars)
            .attr("y", top)
            .attr("height", y(0) - top)
            .style("fill","#0C3B00")
            .on("click", function(d) {
                if (d3.event.defaultPrevented || d['total_production'] == 0) return;
                d3.select("#tooltip").style('display', 'none');

			          window.location = "{{ request.prefix }}"
			            +"/data/input/manufacturingorder/"
			            +"?noautofilter&operation__name="+admin_escape(d['operation'])
			            +"&startdate__" + (date_style_with_hours ? 'lte=' : 'lt=') + timebuckets[d['bucket']]['enddate']
			            +"&enddate__" + (date_style_with_hours ? 'gt=' : 'gte=') + timebuckets[d['bucket']]['startdate'];

                var coord = d3.mouse(document.body);
                d3.event.stopPropagation();
              });
        }
        if (d['proposed_production'] > 0 && (4 in fields || 5 in fields))
        {
          var newtop = y(d['total_production']);
          bucket.append("rect")
            .attr("width", x_width / numbars)
            .attr("x", barnum[1] * x_width / numbars)
            .attr("y", newtop)
            .attr("height", top - newtop)
            .style("fill",'var(--frepple-color-inventory, #8BBA00)')
            .on("click", function(d) {
                if (d3.event.defaultPrevented || d['total_production'] == 0) return;
                d3.select("#tooltip").style('display', 'none');

			          window.location = "{{ request.prefix }}"
			            +"/data/input/manufacturingorder/"
			            +"?noautofilter&operation__name="+admin_escape(d['operation'])
			            +"&startdate__lt="+timebuckets[d['bucket']]['enddate']
			            +"&enddate__gt="+timebuckets[d['bucket']]['startdate'];

                var coord = d3.mouse(document.body);
                d3.event.stopPropagation();
              });
        }
        top = y(0);
        if (d['total_end'] > d['proposed_end'] && 3 in fields)
        {
          top = y(d['total_end'] - d['proposed_end']);
          bucket.append("rect")
            .attr("width", x_width / numbars)
            .attr("x", barnum[2] * x_width / numbars)
            .attr("y", top)
            .attr("height", y(0) - top)
            .style("fill",'var(--frepple-color-consumed-confirmed, #7B5E08)')
            .on("click", function(d) {
                if (d3.event.defaultPrevented || d['total_end'] == 0) return;
                d3.select("#tooltip").style('display', 'none');

			          window.location = "{{ request.prefix }}"
			            +"/data/input/manufacturingorder/"
			            +"?noautofilter&operation__name="+admin_escape(d['operation'])
			            +"&enddate__lte="+timebuckets[d['bucket']]['enddate']
			            +"&enddate__gt="+timebuckets[d['bucket']]['startdate'];

                var coord = d3.mouse(document.body);
                d3.event.stopPropagation();
              });
        }
        if (d['proposed_end'] > 0 && (2 in fields || 3 in fields))
        {
          var newtop = y(d['total_end']);
          bucket.append("rect")
            .attr("width", x_width/numbars)
            .attr("x", barnum[2] * x_width / numbars)
            .attr("y", newtop)
            .attr("height", top - newtop)
            .style("fill",'var(--frepple-color-consumed, #F6BD0F)')
            .on("click", function(d) {
                if (d3.event.defaultPrevented || d['total_end'] == 0) return;
                d3.select("#tooltip").style('display', 'none');

			          window.location = "{{ request.prefix }}"
			            +"/data/input/manufacturingorder/"
			            +"?noautofilter&operation__name="+admin_escape(d['operation'])
			            +"&enddate__lte="+timebuckets[d['bucket']]['enddate']
			            +"&enddate__gt="+timebuckets[d['bucket']]['startdate'];

                var coord = d3.mouse(document.body);
                d3.event.stopPropagation();
              });
        }
        // Invisible rectangle for the tooltip
      	bucket.append("rect")
	      .attr("height", height)
	      .attr("width", x_width)
	      .attr("fill-opacity", 0)
	      .on("click", function(d) {
	          if (d3.event.defaultPrevented || d['total_start'] == 0) return;
	          d3.select("#tooltip").style('display', 'none');

	          window.location = "{{ request.prefix }}"
	            +"/data/input/manufacturingorder/"
	            +"?noautofilter&operation__name="+admin_escape(d['operation'])
	            +"&startdate__lt="+timebuckets[d['bucket']]['enddate']
	            +"&enddate__gte="+timebuckets[d['bucket']]['startdate'];

	          var coord = d3.mouse(document.body);
	          d3.event.stopPropagation();
	        })
	      .on("mouseenter", function(d) {
	        graph.showTooltip(
	          '<div style="text-align:center; font-weight:bold">'
	          + timebuckets[d['bucket']]['name'] + '</div>'
	          + '<table><tr><td>{{_('proposed starts')|capfirst}}</td><td style="text-align:center">'
	          + grid.formatNumber(d['proposed_start'])
	          + '</td></tr><tr><td>{{_('total starts')|capfirst}}</td><td style="text-align:center">'
	          + grid.formatNumber(d['total_start'])
	          + '</td></tr><tr><td>{{_('proposed ends')|capfirst}}</td><td style="text-align:center">'
	          + grid.formatNumber(d['proposed_end'])
	          + '</td></tr><tr><td>{{_('total ends')|capfirst}}</td><td style="text-align:center">'
	          + grid.formatNumber(d['total_end'])
	          + '</td></tr><tr><td>{{_('proposed production')|capfirst}}</td><td style="text-align:center">'
	          + grid.formatNumber(d['proposed_production'])
	          + '</td></tr><tr><td>{{_('total production')|capfirst}}</td><td style="text-align:center">'
	          + grid.formatNumber(d['total_production'])
	          + '</td></tr></table>'
	          );
	        })
	      .on("mouseleave", graph.hideTooltip)
	      .on("mousemove", graph.moveTooltip);
      });

    // Display Y-Axis
    var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left")
      .tickFormat(d3.format("s"));
    {% if not args.0 %}
    svg.append("g")
      .attr("class", "miniaxis")
      .call(graph.miniAxis.bind(yAxis));
    {% else %}
    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

    // Display X-axis for a single operation
    var nth = Math.ceil(timebuckets.length / width * bucketnamelength * 10);
    var myticks = [];
    for (var i in timebuckets)
      if (i % nth == 0) myticks.push(timebuckets[i]['name']);
    var xAxis = d3.svg.axis()
      .scale(x)
      .tickValues(myticks)
      .orient("bottom");
    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    // Display legend
    var legend = svg.append("g");
    var codes = [
      ["{{_('approved and confirmed starts')|capfirst}}", 'var(--frepple-color-produced-confirmed, #113C5E)'],
      ["{{_('proposed starts')|capfirst}}", 'var(--frepple-color-produced, #2B95EC)'],
      ["{{_('approved and confirmed ends')|capfirst}}", 'var(--frepple-color-consumed-confirmed, #7B5E08)'],
      ["{{_('proposed ends')|capfirst}}", 'var(--frepple-color-consumed, #F6BD0F)'],
      ["{{_('approved and confirmed production')|capfirst}}", "#0C3B00"],
      ["{{_('proposed production')|capfirst}}", 'var(--frepple-color-inventory, #8BBA00)'],
      ];
    for (var i in cross_idx)
    {
      legend.append("rect")
        .attr("x", width + 82)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", codes[cross_idx[i]][1])
        .attr("transform", "translate(0," + (i*20+10) + ")");
      legend.append("text")
        .attr("x", width + 76)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(codes[cross_idx[i]][0])
        .attr("transform", "translate(0," + (i*20+10) + ")");
    }{% endif %}
    });
}
{% endif %}
{% if args.0 or mode == "table" %}
function crosses (cellvalue, options, rowdata)
{
  var result = '';
  var date_style_with_hours = "{{request.DATE_STYLE_WITH_HOURS}}" === "True";
  for (var i in cross_idx)
    switch(cross_idx[i])
    {
      case 0:
        if (cellvalue[0] != 0.0)
          result += grid.formatNumber(cellvalue[0]) +
            '<a href="{{ request.prefix }}/data/input/manufacturingorder/?noautofilter' +
            '&amp;operation__name=' + admin_escape(rowdata['operation']) +
            '&amp;startdate__gte=' + options['colModel']['startdate'] +
            '&amp;startdate__lt=' + options['colModel']['enddate'] +
            '&amp;status=proposed">&nbsp;<span class="context cross fa fa-caret-right"></span></a><br>';
        else
          result += '0<br>';
        break;
      case 1:
        if (cellvalue[1] != 0.0)
          result += grid.formatNumber(cellvalue[1]) +
            '<a href="{{ request.prefix }}/data/input/manufacturingorder/?noautofilter' +
            '&amp;operation__name='+ admin_escape(rowdata['operation']) +
            '&amp;startdate__gte=' + options['colModel']['startdate'] +
            '&amp;startdate__lt=' + options['colModel']['enddate'] +
            '">&nbsp;<span class="context cross fa fa-caret-right"></span></a><br>';
        else
          result += '0<br>';
        break;
      case 2:
        if (cellvalue[2] != 0.0)
          result += grid.formatNumber(cellvalue[2]) +
            '<a href="{{ request.prefix }}/data/input/manufacturingorder/?noautofilter' +
            '&amp;operation__name=' + admin_escape(rowdata['operation']) +
            '&amp;enddate__gte=' + options['colModel']['startdate'] +
            '&amp;enddate__lt=' + options['colModel']['enddate'] +
            '&amp;status=proposed">&nbsp;<span class="context cross fa fa-caret-right"></span></a><br>';
        else
          result += '0<br>';
        break;
      case 3:
        if (cellvalue[3] != 0.0)
          result += grid.formatNumber(cellvalue[3]) +
            '<a href="{{ request.prefix }}/data/input/manufacturingorder/?noautofilter' +
            '&amp;operation__name=' + admin_escape(rowdata['operation']) +
            '&amp;enddate__gte=' + options['colModel']['startdate'] +
            '&amp;enddate__lt=' + options['colModel']['enddate'] +
            '">&nbsp;<span class="context cross fa fa-caret-right"></span></a><br>';
        else
          result += '0<br>';
        break;
      case 4:
        if (cellvalue[4] != 0.0)
          result += grid.formatNumber(cellvalue[4]) +
            '<a href="{{ request.prefix }}/data/input/manufacturingorder/?noautofilter' +
            '&amp;operation__name=' + admin_escape(rowdata['operation']) +
            '&amp;startdate__' + (date_style_with_hours ? 'lte=' : 'lt=') + options['colModel']['enddate'] +
            '&amp;enddate__' + (date_style_with_hours ? 'gt=' : 'gte=') + options['colModel']['startdate'] +
            '&amp;status=proposed">&nbsp;<span class="context cross fa fa-caret-right"></span></a><br>';
        else
          result += '0<br>';
        break;
      case 5:
        if (cellvalue[5] != 0.0)
          result += grid.formatNumber(cellvalue[5]) +
            '<a href="{{ request.prefix }}/data/input/manufacturingorder/?noautofilter&amp;' +
            'operation__name=' + admin_escape(rowdata['operation']) +
            '&amp;startdate__' + (date_style_with_hours ? 'lte=' : 'lt=') + options['colModel']['enddate'] +
            '&amp;enddate__' + (date_style_with_hours ? 'gt=' : 'gte=') + options['colModel']['startdate'] +
            '">&nbsp;<span class="context cross fa fa-caret-right"></span></a><br>';
        else
          result += '0<br>';
        break;
      default:
        result += grid.formatNumber(cellvalue[cross_idx[i]]) + '<br>';
    }
  return result;
};
{% endif %}{% endblock %}

{% block extra_grid %}{% if args.0 or mode == "graph" %}loadComplete: drawGraphs,
{% endif %}{% endblock %}
