am5.ready(function() {

am5.addLicense("AM5C387765625");

var downloadChart = am5.Root.new("downloadChart");

	try {
		downloadChart.setThemes([
			am5themes_Animated.new(downloadChart),
			am5themes_Dark.new(downloadChart)
		]);
	}
	catch(e) {
		downloadChart.setThemes([
			am5themes_Animated.new(downloadChart)
		]);
	}


var chart = downloadChart.container.children.push(am5xy.XYChart.new(downloadChart, {
  panX: false,
  panY: false,
  paddingLeft: 0,
  wheelX: "panX",
  wheelY: "zoomX",
  layout: downloadChart.verticalLayout
}));


var legend = chart.children.push(
  am5.Legend.new(downloadChart, {
    centerX: am5.p50,
    x: am5.p50
  })
);

var xRenderer = am5xy.AxisRendererX.new(downloadChart, {
  minGridDistance: 30, 
  minorGridEnabled: true
})

xRenderer.labels.template.setAll({
  rotation: -90,
  centerY: am5.p50,
  centerX: am5.p100,
  paddingRight: 15
});

var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(downloadChart, {
  categoryField: "label",
  renderer: xRenderer,
  tooltip: am5.Tooltip.new(downloadChart, {})
}));

xRenderer.grid.template.setAll({
  location: 1
})

var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(downloadChart, {
  renderer: am5xy.AxisRendererY.new(downloadChart, {
    strokeOpacity: 0.1
  })
}));

function makeSeries(data, name, fieldName, color) {
  var series = chart.series.push(am5xy.ColumnSeries.new(downloadChart, {
    name: name,
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: fieldName,
    categoryXField: "label"
  }));

  series.columns.template.setAll({
    tooltipText: "{categoryX}: {valueY}",
    width: am5.percent(90),
    tooltipY: 0,
    strokeOpacity: 0
  });

  series.data.setAll(data);
  series.appear();

  series.columns.template.setAll({ cornerRadiusTL: 5, cornerRadiusTR: 5, strokeOpacity: 0 });
  legend.data.push(series);
}
	
var load = function() {

	am5.net.load("/app/api/downloads/" + $('#chartType').val() + "/" + $('#downloadProduct').val()).then(function(result) {

	  var data  = am5.JSONParser.parse(result.response);
	
	  xAxis.data.setAll(data.resource);
	  makeSeries(data.resource, "", "value", 0xff6347);
	  chart.appear(1000, 100);
	
	}).catch(function(result) {
	  console.log("Error loading " + result.xhr);
	});
}

$('#downloadProduct').change(function(e) {
	chart.series.removeIndex(0).dispose();
	legend.data.removeIndex(0).dispose();
	load();
});

$('#chartType').change(function(e) {
	chart.series.removeIndex(0).dispose();
	legend.data.removeIndex(0).dispose();
	load();
});

load();

});