// https://stackoverflow.com/questions/18191893/generate-pdf-from-html-in-div-using-javascript
// https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js
this.getSwatchColors = function(id, colors) {
  colors = colors || {};
  $("#" + id + " .swatch").each(function(i, el) {
    colors[el.className.split(" ").pop()] = $(el).css("background-color");
  });
  return colors;
};

this.createDoughnutChart = function(id, style, data) {
  var $chartArea = $("#" + id),
    chart = $chartArea.find('canvas.doughnut').get(0),
    ctx = chart.getContext("2d"),
    colors = getSwatchColors(style, {}),
    legend = "";
  _.each(data, function(el, i) {
    el.color = colors["_" + i];
    el.highlight = colors["_" + i + "h"];
    legend += [
      '<div class="entry">',
      '<span class="swatch" style="background-color:' + el.color + '"></span>',
      el.label,
      '</div>'
    ].join("");
  });

  var myDoughnut = new Chart(ctx).Doughnut(data, {
    animateRotate: false,
    animateScale: true,
    responsive: true,
    maintainAspectRatio: true,
    segmentStrokeWidth: 1,
    animationEasing: "easeOutCubic",
    animationSteps: 50,
    percentageInnerCutout: 50
  });
  $chartArea.find(".legend").append(legend);
  return myDoughnut;
};

this.createBarChart = function(id, style, data) {
  var $chartArea = $("#" + id),
    chart = $chartArea.find('canvas.bar').get(0),
    ctx = chart.getContext("2d"),
    colors = getSwatchColors(style),
    legend = "";
  _.each(data.datasets, function(el, i) {
    el.fillColor = colors["_" + i];
    el.highlight = colors["_" + i + "h"];
  });
  var myBar = new Chart(ctx).Bar(data, {
    scaleGridLineWidth: 1,
    scaleFontSize: 10,
    scaleShowHorizontalLines: false,
    scaleShowVerticalLines: false,
    scaleBeginAtZero: true,
    maintainAspectRatio: false
  });
  //$chartArea.find(".legend").append(legend);
};
$(function() {
  createDoughnutChart("email-delivery-chart", "doughnut-chart-email-swatches", [{
    value: 50,
    label: "Delivered Emails"
  }, {
    value: 50,
    label: "Bounced Emails"
  }]);

  createDoughnutChart("email-open-rate-chart", "doughnut-chart-email-swatches", [{
    value: 204,
    label: "Opened emails"
  }, {
    value: 96,
    label: "Ignored emails"
  }]);

  createDoughnutChart("email-click-through-chart", "doughnut-chart-email-swatches", [{
    value: 41,
    label: "Click through"
  }, {
    value: 163,
    label: "Viewed only"
  }]);

  createBarChart("click-through-breakdown-chart", "bar-chart-email-swatches", {
    labels: ["Direct", "Redirected"],
    datasets: [{
      data: [28, 72]
    }]
  });

  createBarChart("repeat-open-rate-chart", "bar-chart-email-swatches", {
    labels: ["Day 1", "Day 2", "Day 3", "Day 4"],
    datasets: [{
      data: [2300, 1300, 480, 94]
    }]
  });
});