// Generated by CoffeeScript 1.6.2
(function() {
  "use strict";
  var calculateData, chart, dateToString, daysBetween, isoDateTextToDate, lang;

  chart = null;

  window.ma_app = window.ma_app || {};

  window.ma_app.drawGraph = function(raw_data) {
    var chart_resize, data, heightMin, heightOther, nvd3data, percent, prev_width, rec, txt, _i, _len, _ref;

    data = calculateData(raw_data);
    heightOther = 120;
    heightMin = 100;
    prev_width = -1;
    _ref = data.data;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      rec = _ref[_i];
      percent = Math.round(rec.value / data.days_total * 100, 0);
      rec.days = rec.days + " (" + percent + "%)";
    }
    d3.select("#header2").text();
    txt = dateToString(data.day_start1);
    txt = txt + " - " + dateToString(data.day_end1);
    txt = data.subheader + " (" + txt + ")";
    d3.select("#header2").text(txt);
    txt = d3.select("#header3").text();
    txt = txt.replace("XPCS", data.days_total);
    if (data.company !== "") {
      txt = txt + ", " + data.company;
    }
    d3.select("#header3").text(txt);
    nvd3data = [];
    nvd3data[0] = {};
    nvd3data[0].key = "toimituspv";
    nvd3data[0].values = data.data;
    chart_resize = function() {
      var h;

      h = window.innerHeight - heightOther;
      if (h < heightMin) {
        h = heightMin;
      }
      if (window.innerWidth < 800) {
        if (prev_width >= 800 || prev_width < 0) {
          chart.staggerLabels(true);
        }
      } else {
        if (prev_width < 800 || prev_width < 0) {
          chart.staggerLabels(false);
        }
      }
      prev_width = window.innerWidth;
      d3.select("#chart1 svg").style("height", h);
      return chart.update();
    };
    nv.addGraph(function() {
      chart = nv.models.discreteBarChart();
      chart.x(function(d) {
        return d.days;
      });
      chart.y(function(d) {
        return d.value;
      });
      chart.tooltips(true);
      chart.showValues(true);
      chart.color(['darkgreen', 'limegreen', 'yellow', 'yellow', 'orange', 'orange', 'red']);
      chart.valueFormat(d3.format(',.0f'));
      chart.yAxis.axisLabel(lang("Toimituksia (kpl)"));
      chart.xAxis.axisLabel(lang("Toimituspäiväero (pv)"));
      chart.margin({
        left: 50,
        top: 10,
        bottom: 70,
        right: 0
      });
      chart.yAxis.axisLabelDistance(40);
      /*chart.staggerLabels = () ->
        console.log("staggerLabels: "+window.innerWidth)
        if window.innerWidth < 800
          return true #false = alareunan labelit menee vuorotellen eri riveille
        else
          return false
      */

      if (data.days_max >= 10) {
        chart.yAxis.tickFormat(d3.format(",.0f"));
      } else {
        chart.yAxis.tickFormat(d3.format(",.1f"));
      }
      d3.select("#chart1 svg").datum(nvd3data).transition().duration(600).call(chart);
      nv.utils.windowResize(chart_resize);
      chart_resize();
      return chart;
    });
  };

  lang = function(txt) {
    return txt;
  };

  window.ma_app.exampleDataX = function() {
    return {
      subheader: "Tulopäivä - Viim. vahv. pv",
      data: [
        {
          days: lang("Etuajassa"),
          value: 8
        }, {
          days: lang("Ajallaan"),
          value: 14
        }, {
          days: "1-2",
          value: 2
        }, {
          days: "3-7",
          value: 4
        }, {
          days: "8-14",
          value: 7
        }, {
          days: "15-30",
          value: 0
        }, {
          days: lang("yli 30"),
          value: 4
        }
      ]
    };
  };

  isoDateTextToDate = function(txtDate) {
    var day, month, year;

    year = txtDate.substring(0, 4);
    month = txtDate.substring(5, 7) - 1;
    day = txtDate.substring(8, 10);
    return new Date(year, month, day);
  };

  daysBetween = function(d1, d2) {
    var days;

    days = d1 - d2;
    days = days / 86400000;
    return days;
  };

  dateToString = function(d) {
    var day, month, year;

    day = d.getDate();
    month = d.getMonth();
    year = d.getFullYear();
    return day + "." + month + "." + year;
  };

  calculateData = function(data) {
    var company, companyCount, d1, d2, difference, i, rec, ret, _, _i, _j, _k, _len, _len1, _ref, _ref1;

    ret = {};
    if (data.Use_First_Confirmed_Date === 1) {
      ret.subheader = lang("Tulopäivä - Ensimmäinen vahv. pv");
    } else {
      ret.subheader = lang("Tulopäivä - Viimeinen vahv. pv");
    }
    ret.data = [];
    for (i = _i = 0; _i <= 6; i = ++_i) {
      ret.data[i] = {};
      ret.data[i].value = 0;
    }
    ret.data[0].days = lang("Etuajassa");
    ret.data[1].days = lang("Ajallaan");
    ret.data[2].days = "1-2";
    ret.data[3].days = "3-7";
    ret.data[4].days = "8-14";
    ret.data[5].days = "15-30";
    ret.data[6].days = lang("yli 30");
    ret.day_start1 = 0;
    ret.day_start2 = 0;
    ret.day_end1 = 0;
    ret.day_end2 = 0;
    companyCount = 0;
    company = "";
    _ref = data.Confirmed_Arrival_Date;
    for (i = _j = 0, _len = _ref.length; _j < _len; i = ++_j) {
      _ = _ref[i];
      if (i === 0) {
        companyCount = 1;
        company = data.Supplier_Name[i];
      } else if (company !== data.Supplier_Name[i]) {
        companyCount = companyCount + 1;
      }
      if (data.Use_First_Confirmed_Date === 1) {
        data.Confirmed_Arrival_Date[i] = data.First_Confirm_Deliv_Date[i];
      }
      if ((data.Confirmed_Arrival_Date[i] = "0000.00.00")) {
        data.Confirmed_Arrival_Date[i] = data.Requested_Delivery_Date[i];
      }
      d1 = isoDateTextToDate(data.Date_Of_Arrival[i]);
      d2 = isoDateTextToDate(data.Confirmed_Arrival_Date[i]);
      difference = daysBetween(d1, d2);
      if (difference < 0) {
        ret.data[0].value += 1;
      } else if (difference === 0) {
        ret.data[1].value += 1;
      } else if (difference >= 1 && difference <= 2) {
        ret.data[2].value += 1;
      } else if (difference >= 3 && difference <= 7) {
        ret.data[3].value += 1;
      } else if (difference >= 8 && difference <= 14) {
        ret.data[4].value += 1;
      } else if (difference >= 15 && difference <= 30) {
        ret.data[5].value += 1;
      } else {
        ret.data[6].value += 1;
      }
      if (d1 < ret.day_start1 || ret.day_start1 === 0) {
        ret.day_start1 = d1;
      }
      if (d2 < ret.day_start2 || ret.day_start2 === 0) {
        ret.day_start2 = d2;
      }
      if (d1 > ret.day_end1 || ret.day_end1 === 0) {
        ret.day_end1 = d1;
      }
      if (d1 > ret.day_end2 || ret.day_end2 === 0) {
        ret.day_end2 = d2;
      }
    }
    ret.company = "";
    if (companyCount === 1) {
      ret.company = company;
    }
    ret.days_total = 0;
    ret.days_max = 0;
    _ref1 = ret.data;
    for (_k = 0, _len1 = _ref1.length; _k < _len1; _k++) {
      rec = _ref1[_k];
      ret.days_total = ret.days_total + rec.value;
      if (rec.value > ret.days_max) {
        ret.days_max = rec.value;
      }
    }
    return ret;
  };

  window.ma_app.exampleData = function() {
    return {
      Use_First_Confirmed_Date: 1,
      Confirmed_Arrival_Date: ["2013.07.24", "2013.06.18", "2013.06.18", "2013.06.18", "2013.06.18", "2013.06.20"],
      First_Confirm_Deliv_Date: ["2013.01.02", "2012.11.27", "2012.11.27", "2012.11.27", "2012.11.27", "2012.11.29"],
      Requested_Delivery_Date: ["2013.07.24", "2013.06.18", "2013.06.18", "2013.06.18", "2013.06.18", "2013.06.20"],
      Date_Of_Arrival: ["2013.06.20", "2013.06.20", "2013.06.20", "2013.06.20", "2013.06.18", "2013.08.07"],
      Supplier_Name: ["Helsingin Rauta Oy", "Helsingin Rauta Oy", "Helsingin Rauta Oy", "Helsingin Rauta Oy", "Helsingin Rauta Oy", "Helsingin Rauta Oy"]
    };
  };

  /*
  # example code from multiBarChart.html
  
  test_data = stream_layers(3, 10 + Math.random() * 100, .1).map((data, i) ->
    #var test_data = stream_layers(3,1,.1).map(function(data, i) { //for testing single data point
    key: "Stream" + i
    values: data
  )
  
  console.log "td", test_data
  
  negative_test_data = new d3.range(0, 3).map((d, i) ->
    key: "Stream" + i
    values: new d3.range(0, 11).map((f, j) ->
      y: 10 + Math.random() * 100 * ((if Math.floor(Math.random() * 100) % 2 then 1 else -1))
      x: j
    )
  )
  
  chart = undefined
  nv.addGraph ->
    #chart = nv.models.multiBarChart().barColor(d3.scale.category20().range()).margin(bottom: 100).transitionDuration(300).delay(0).rotateLabels(45).groupSpacing(0.1)
    chart = nv.models.multiBarChart()
    chart.multibar.hideable true
    chart.reduceXTicks(false).staggerLabels true
    chart.xAxis.axisLabel("Current Index").showMaxMin(true).tickFormat d3.format(",.6f")
    chart.yAxis.tickFormat d3.format(",.1f")
    d3.select("#chart1 svg").datum(negative_test_data).call chart
    nv.utils.windowResize chart.update
    chart.dispatch.on "stateChange", (e) ->
      nv.log "New State:", JSON.stringify(e)
    return chart
  */


}).call(this);

/*
//@ sourceMappingURL=graph.map
*/
