var country_chart;
var monthly_chart;
var secondary_monthly_chart;
var loaded = false;
var date = new Date();
var dateTo = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDay())
var dateFrom = dateTo - (18 * 31 * 24 * 3600 * 1000);
var selectedColor = 'rgba(51, 102, 153, 0.2)';
$(document).ready(function() {
   var i = 0;
   
   country_chart = new Highcharts.Chart({
      chart: {
         renderTo: 'country-stat-container',
         defaultSeriesType: 'column',
         marginBottom: 110,
         plotBackgroundImage: '/charts/stats_logo.png',
         plotBorderWidth: 1
      },
      credits: false,
      title: false,
      xAxis: {
         categories: country_data.countries,
         labels: {
            rotation: 270,
            align: 'right'
         }
      },
      yAxis: {
         title: false,
         min: 0,
         labels:{
            formatter: function (){
               return Highcharts.numberFormat(this.value, 0, ',', '.');
            }
         },
         tickInterval: 100000
      },
      legend: false,
      tooltip: {
         formatter: function() {
            return ''+
               this.x +': '+ Highcharts.numberFormat(this.y, 0, ',', ' ') +' .eu registrations';
         }
      },
      plotOptions: {
         column: {
            pointPadding: 0.2,
            borderWidth: 0
         }
      },
      series: [{
         data: country_data.totals
      }],
      exporting: {
         url: "/charts/chart-exporting-server/",
         filename: "eurid-country-reg-chart",
         buttons:{
            exportButton: {
               menuItems: null,
               onclick: function() {
                  this.exportChart({
                  });
               }
            }
         }
      }
   });
   
   //Filter data in main chart based on secondary chart
   var monthly_filtered_data = [];
   for(data in monthly_data){
      if(monthly_data[data].x >= dateFrom){
         monthly_data[data].color = null;
         monthly_filtered_data.push(monthly_data[data]);
      }else{
         //Not shown in main chart
         monthly_data[data].color = "#999";
      }
   }
   
   monthly_chart = new Highcharts.Chart({
      chart: {
         renderTo: 'monthly-stat-container',
         defaultSeriesType: 'column',
         marginBottom: 100,
         plotBackgroundImage: '/charts/stats_logo.png',
         events:{},
         plotBorderWidth: 1
      },
      credits: false,
      title: false,
      xAxis: {
         //type: 'datetime',
         labels: {
            rotation: 270,
            align: 'right',
            formatter: function (){
               //Only show labels at the start of the month
               if(Highcharts.dateFormat("%e", this.value) == "1"){
                  return Highcharts.dateFormat("%b %Y", this.value);
               }else{
                  return false;
               }
            }
         },
         tickInterval: 24 * 3600 * 1000,
         startOnTick: true,
         endOnTick: true,
         tickColor: '#FFFFFF'
      },
      yAxis: {
         title: false,
         min: 0,
         labels:{
            formatter: function (){
               return Highcharts.numberFormat(this.value, 0, ',', '.');
            }
         },
         tickInterval: 10000
      },
      legend: false,
      tooltip: {
         formatter: function() {
            return ''+
               Highcharts.dateFormat("%B %Y", this.x) +': '+ Highcharts.numberFormat(this.y, 0, ',', ' ') +' .eu registrations';
         }
      },
      plotOptions: {
         column: {
            borderWidth: 0
         }
      },
      series: [{
         data: monthly_filtered_data
      }],
      exporting: {
         url: "/charts/chart-exporting-server/",
         filename: "eurid-monthly-reg-chart",
         buttons:{
            exportButton: {
               menuItems: null,
               onclick: function() {
                  this.exportChart({
                  });
               }
            }
         }
      }
   });
   
   secondary_monthly_chart = new Highcharts.Chart({
      chart: {
         renderTo: 'secondary-monthly-stat-container',
         defaultSeriesType: 'column',
         marginTop: 5,
         marginBottom: 20,
         zoomType : 'x',
         plotBackgroundColor: selectedColor,
         plotBorderColor: "#ccc",
         plotBorderWidth: 3,
         events: {
            // listen to the selection event on the master chart to update the 
            // extremes of the detail chart
            selection: function(event) {
               var extremesObject = event.xAxis[0],
                  min = extremesObject.min,
                  max = extremesObject.max,
                  xAxis = this.xAxis[0],
                  detailData = [];
               // reverse engineer the last part of the data
               jQuery.each(this.series[0].data, function(i, point) {
                  point.update({color : "#999999"}, false);
                  if (point.x >= min && point.x <= max) {
                     point.update({color : null}, false);
                     detailData.push({
                  //      color: null,
                        x: point.x,
                        y: point.y
                     });
                  }
               });
               this.redraw();
               for(point in this.series[0].data){
                  this.series[0].data[point].onMouseOver();
               }
               // move the plot bands to reflect the new detail span
               xAxis.removePlotBand('mask-before');
               xAxis.addPlotBand({
                  id: 'mask-before',
                  from: Date.UTC(2006,0,1),
                  to: min,
                  color: '#fff'
               });
               xAxis.removePlotBand('mask-after');
               xAxis.addPlotBand({
                  id: 'mask-after',
                  from: max,
                  to: Date.UTC(2020,0,1),
                  color: '#fff'
               });
               monthly_chart.series[0].setData(detailData);
               return false;
            },
            load: function(){
               // move the plot bands to reflect the new detail span
               xAxis = this.xAxis[0];
               xAxis.removePlotBand('mask-before');
               xAxis.addPlotBand({
                  id: 'mask-before',
                  from: Date.UTC(2006,0,1),
                  to: dateFrom,
                  color: "#fff"
               });
               xAxis.removePlotBand('mask-after');
               xAxis.addPlotBand({
                  id: 'mask-after',
                  from: dateTo,
                  to: Date.UTC(2020,0,1),
                  color: "#fff"
               });

               
            }
         }
      },
      credits: false,
      title: false,
      xAxis: {
         categories: monthly_data.months,
         type: 'datetime',
         labels: {
            rotation: 0,
            align: 'center',
            formatter: function (){
               if(Highcharts.dateFormat("%b", this.value) == 'Jan'){
                  return Highcharts.dateFormat("%Y", this.value);
               }else{
                  return false;
               }
            }
         },
         tickInterval: 12 * 31 * 24 * 3600 * 1000
      },
      yAxis: {
         title: false,
         min: 0,
         labels: {
            formatter: function (){
               return Highcharts.numberFormat(this.value, 0, ',', '.');
            }
         },
         tickInterval: 50000
      },
      legend: false,
      tooltip: {
         enabled: false
      },
      plotOptions: {
         series:{
           pointWidth: 5 
         },
         column: {
            pointPadding: 0,
            borderWidth: 0
         }
      },
      series: [{
         data: monthly_data
      }],
      exporting: {
         enabled: false
      }
   });

   ns_chart = new Highcharts.Chart({
      chart: {
         renderTo: 'ns-stat-container',
         defaultSeriesType: 'line',
         marginBottom: 170,
         plotBackgroundImage: '/charts/stats_logo.png',
         plotBorderWidth: 1
      },
      symbols: [],
      colors: ['#4572A7'],
      credits: false,
      title: false,
      xAxis: {
         type: "datetime",
         //tickInterval: 'auto',
         tickPixelInterval: '30',
         labels: {
            rotation: 270,
            align: 'right',
            formatter: function(){
                return Highcharts.dateFormat('%d %b %y %H:%M', this.value)
            }
         },
         minorGridLineColor: '#E0E0E0',
         minorGridLineWidth: 1,
         minorTickLength: 0,
         minorTickInterval: "auto"

      },
      yAxis: {
         title: false,
         min: 0,
         labels:{
            formatter: function (){
               return Highcharts.numberFormat(this.value, 0, ',', '.');
            }
         }
         //tickInterval: 1000000
      },
      tooltip: {
         formatter: function() {
            return ''+
               Highcharts.dateFormat('%d %b %Y %H:%M',this.x) +': '+ Highcharts.numberFormat(this.y, 0, ',', ' ') +' queries';
         }
      },
      plotOptions: {
         area: {
            stacking: "normal"
         },
         series: {
            //color: "#4572a7",
            marker: false
         }
      },
      series: ns_in_time_data,
      exporting: {
         url: "/charts/chart-exporting-server/",
         filename: "eurid-ns-chart",
         buttons:{
            exportButton: {
               menuItems: null,
               onclick: function() {
                  this.exportChart({
                  });
               }
            }
         }
      },
    global: {
      useUTC: true
    }
   });

});

