jQuery(document).ready(function($){
  $.extend({
    get_school_classes: function() {
      var datacontainer = null;
      var xhr = $.ajax({
        type: 'POST',
        url: 'contents/plugins/eedu_portal/ajax.php',
        data: {action: 'get_classes_for_analytics'}
      }).done(function(data){
        try{
          data = JSON.parse(data);
          chartdata = genderchartdata = [];
          for(var cl in data.classes) {
            for(var key in data.category_mapping[cl]) {
              var ct = data.category_mapping[cl][key];
              var obj = genderobj = {};
              if(data.students[cl] != undefined && data.students[cl] != null) {
                if(data.students[cl][ct] != undefined && data.students[cl][ct] != null) {
                  obj.population = data.students[cl][ct];
                  obj.classname = data.classes[cl].class_name+" "+data.category[ct].category_name;
                  chartdata.push(obj);
                  genderobj.classname = obj.classname;
                  genderobj.male = (data.gender[cl][ct]['Male'] != undefined && data.gender[cl][ct]['Male'] != null) ? data.gender[cl][ct]['Male'] : 0;
                  genderobj.female = (data.gender[cl][ct]['Female'] != undefined && data.gender[cl][ct]['Female'] != null) ? data.gender[cl][ct]['Female'] : 0;
                  genderobj.na = (data.gender[cl][ct]['NA'] != undefined && data.gender[cl][ct]['NA'] != null) ? data.gender[cl][ct]['NA'] : 0;
                  genderchartdata.push(genderobj);
                }
              }
            }
          }
          $.updatechart(chartdata);
          $.updategenderchart(genderchartdata);
        }
        catch(err){
          console.log(err);
          console.log(data);
        }
        finally{
          console.log(data);
        }
      }).fail(function(){
        $.get_school_classes();
      })
      
    },

    updatechart: function(chartdata) {
      console.log(chartdata);
      am4core.ready(function() {

      // Themes begin
      am4core.useTheme(am4themes_animated);
      // Themes end

      // Create chart instance
      var chart = am4core.create("chartdiv", am4charts.XYChart);
      chart.scrollbarX = new am4core.Scrollbar();

      // Add data
      chart.data = chartdata;

      // Create axes
      var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
      categoryAxis.dataFields.category = "classname";
      categoryAxis.renderer.grid.template.location = 0;
      categoryAxis.renderer.minGridDistance = 30;
      categoryAxis.renderer.labels.template.horizontalCenter = "right";
      categoryAxis.renderer.labels.template.verticalCenter = "middle";
      categoryAxis.renderer.labels.template.rotation = 270;
      categoryAxis.tooltip.disabled = true;
      categoryAxis.renderer.minHeight = 110;

      var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.renderer.minWidth = 50;

      // Create series
      var series = chart.series.push(new am4charts.ColumnSeries());
      series.sequencedInterpolation = true;
      series.dataFields.valueY = "population";
      series.dataFields.categoryX = "classname";
      series.tooltipText = "[{categoryX}: bold]{valueY}[/]";
      series.columns.template.strokeWidth = 0;

      series.tooltip.pointerOrientation = "vertical";

      series.columns.template.column.cornerRadiusTopLeft = 10;
      series.columns.template.column.cornerRadiusTopRight = 10;
      series.columns.template.column.fillOpacity = 0.8;

      // on hover, make corner radiuses bigger
      var hoverState = series.columns.template.column.states.create("hover");
      hoverState.properties.cornerRadiusTopLeft = 0;
      hoverState.properties.cornerRadiusTopRight = 0;
      hoverState.properties.fillOpacity = 1;

      series.columns.template.adapter.add("fill", function(fill, target) {
        return chart.colors.getIndex(target.dataItem.index);
      });

      // Cursor
      chart.cursor = new am4charts.XYCursor();

      }); // end am4core.ready()
    },

    updategenderchart: function(chartdata) {
      am4core.ready(function() {

      // Themes begin
      am4core.useTheme(am4themes_animated);
      // Themes end

      // Create chart instance
      var chart = am4core.create("genderchartdiv", am4charts.XYChart);

      // Add percent sign to all numbers
      // chart.numberFormatter.numberFormat = "#.3'%'";

      // Add data
      chart.data = chartdata;

      // Create axes
      var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
      categoryAxis.dataFields.category = "classname";
      categoryAxis.renderer.grid.template.location = 0;
      categoryAxis.renderer.minGridDistance = 30;
      categoryAxis.renderer.labels.template.horizontalCenter = "right";
      categoryAxis.renderer.labels.template.verticalCenter = "middle";
      categoryAxis.renderer.labels.template.rotation = 270;
      categoryAxis.renderer.minHeight = 110;

      var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
      // valueAxis.title.text = "Class Population/Gender";
      valueAxis.title.fontWeight = 800;

      // Create series
      var series = chart.series.push(new am4charts.ColumnSeries());
      series.dataFields.valueY = "male";
      series.dataFields.categoryX = "classname";
      series.clustered = false;
      series.tooltipText = "Population of Male Students in {categoryX}: [bold]{valueY}[/]";

      var series2 = chart.series.push(new am4charts.ColumnSeries());
      series2.dataFields.valueY = "female";
      series2.dataFields.categoryX = "classname";
      series2.clustered = false;
      series2.columns.template.width = am4core.percent(50);
      series2.tooltipText = "Population of Female Students in {categoryX}: [bold]{valueY}[/]";

      var series3 = chart.series.push(new am4charts.ColumnSeries());
      series3.dataFields.valueY = "na";
      series3.dataFields.categoryX = "classname";
      series3.clustered = false;
      series3.columns.template.width = am4core.percent(30);
      series3.tooltipText = "Population of Other Students in {categoryX}: [bold]{valueY}[/]";

      chart.cursor = new am4charts.XYCursor();
      chart.cursor.lineX.disabled = true;
      chart.cursor.lineY.disabled = true;

      }); // end am4core.ready()
    }
  })

  $.get_school_classes();
})