if(typeof ThreeScale.Analytics == 'undefined'){
  ThreeScale.Analytics = {};
}

(function($){
  ThreeScale.Analytics.Charts = function(elem, options){
    if(typeof options == 'undefined'){
      options = {};
    }

    this.h = ThreeScale.Helper.General;
    this.o = ThreeScale.Analytics.Charts;
    // Short cut to charts helper object
    this.c = ThreeScale.Helper.Charts;

    this.chart = null;
    this.dataEndPoint = options.dataEndPoint || '/stats/service/usage.json';
    // Render chart into which DOM element
    this.renderTo = elem || 'chart-1';
    this.$renderTo = $("#" + this.renderTo);

    this.chartOptions = this.c.defaultOptions;

    this.seriesColours = ['#0077CC', '#4655B2', '#97A6FF'];

    // Cache loading spinners
    this.$loading = $('.loading');
    this.$loadingChart = $('.chart-wrap .loading');

    this.metricID = null;

    // Set default period
    this.period = 'day';

    // Set since date
    this.since = this.h.currentDateDashed();

    this.reintitialise = false;

    // Bind event listeners
    this.listen();

    this.updateDataFromHTML();
  };


  ThreeScale.Analytics.Charts.prototype = {
    init: function(){
      $(window).trigger('apply-selectors');
    },

    initialiseChart: function(r){
      var o = this.chartOptions,
          that = this;

      o.chart.events = {
        load: function(){
          that.$loadingChart.fadeOut('slow');
        }
      };
      Highcharts.setOptions({
        global: {
          useUTC: true
        }
      });

      o.chart.renderTo = this.renderTo;

      // start date
      var d = this.h.dateParser(r.period.since, Stats.SearchOptions.period);
      // convert to timestamp
      o.plotOptions.series.pointStart = d.valueOf();

        o.plotOptions.series.pointInterval = this.c.periodToDate(Stats.SearchOptions.period);
        o.plotOptions.series.color = this.seriesColours[0];
        o.yAxis.title.text = false;
        o.yAxis.unit = r.metric.unit;
        o.yAxis.labels.formatter = this.value;


        // If no data, no need to display y-axis labels
        o.yAxis.labels.enabled = ((r.total == 0) ? false : true);

        var max = _.max(r.values);
        // o.chart.margin = [20, 20, 30, 90];
        // o.yAxis.labels.style = {fontSize: '10px'};

        o.tooltip.formatter = function() {
            var val, d, datum;
            switch (Stats.SearchOptions.period) {
            case 'year':
                d = '%b';
                break;
            case 'month':
                d = '%d %b';
                break;
            case 'week':
                d = '%d %b %I:%M%p';
                break;
            case 'day':
                d = '%I:%M%p';
                break;
            }
            d = Highcharts.dateFormat(d, this.x);

            datum = this.series.chart.options.yAxis;
            val = d + "<br />" + Highcharts.numberFormat(this.y, 0) + " " + pluralize(datum.unit, this.y);

            return val;
        };


      options = o;
      this.chart = new Highcharts.Chart(o);
      window.chart = this.chart;

      this.addSeries(r);
    },
    queryData: function(){
      Stats.SearchOptions.timezone = this.timezone;
      return Stats.SearchOptions;
    },

    updateDataFromHTML: function() {
      this.since = $('#current-date').attr("data-date");
      this.period = $('#current-period').attr("data-period");
      this.timezone = $('#current-timezone').attr("data-timezone");
    },

    extractMetricID: function(){
      if($(".metric-type-button").length > 0) {
        $(".metric-type-button");
      }
      $('#current-metric').attr("data-metric");
      // return value;
    },

    getData: function(){
      var that = this;

      $.ajax({
        dataType: 'json',
        data: that.queryData(),
        url: that.dataEndPoint,
        success: function(r) {
          /* If API successfully queired, and we have a response object then... */
          that.dealWithResponse(r);
        }
      });
    },

    addSeries: function(r) {
      this.chart.addSeries({
        data:r.values
        // identifier:client_id,
        // color:that.seriesColours[that.chart.series.length]
      });
    },

    addLineSeries: function(opt) {
      opt.type = 'line';
      this.chart.addSeries(opt);
    },

    dealWithResponse: function(r){
    },

    listen: function(){
      var that = this,
          $detailSelector = $('.detail-selector');

      $detailSelector.bind('metric-changed', function(event, id){
        that.metricID = id;
      });

      $('body').bind('metricTypeDidChange', function(event, id){
        that.metricID = id;
      });

      $(window).bind('apply-selectors', function(){
        that.reinitialise = true;
        that.$loading.fadeIn();
        that.updateDataFromHTML();
        that.updateChart();
      });

    },

    updateChart: function(){
      this.showLoading();
      this.getData();
      return true;
    },

    findSeries: function(id){
      var s = this.chart.series;
      for (var i = s.length - 1; i >= 0; i--){
        if(s[i].options.identifier == id){
          return s[i];
        }
      };
      return false;
    }
  };

})(jQuery);

// /*
//  Behaviour for usages static display
// */
//
/*
Array.prototype.sum = function(){
 for(var i=0,sum=0;i<this.length;sum+=this[i++]);
 return sum;
};
Array.prototype.max = function(){
 return Math.max.apply({},this);
};
Array.prototype.min = function(){
 return Math.min.apply({},this);
};
*/

(function($){
  $(document).ready(function() {
  // Chart options for cinstances chart
  if($('#signups-chart').length > 0) {

    var o = ThreeScale.Helper.Charts.defaultOptions;
    o.chart.defaultSeriesType = 'line';
    o.colors = ['#0077CC', '#4199D9', '#62b3f5', '#80cfff', '#9eebff', 'bcffff'];
    o.chart.renderTo = 'signups-chart';
    o.chart.margin = [20, 170, 40, 35];
    o.plotOptions.series.lineWidth = 2;
    o.plotOptions.series.marker.radius = 0;
    var date = (function(){
      var d    =  new Date(),
          date =  new Date(d.getYear(), d.getMonth());



      return date;
    })();
    o.plotOptions.series.pointStart = date.valueOf();
    o.plotOptions.series.pointInterval = 24 * 3600 * 1000;

    o.tooltip.formatter = function(){
      return Highcharts.dateFormat('%d %b', this.x) + "<br />" + Highcharts.numberFormat(this.y, 0) + " signups";
    };
    o.yAxis.minPadding = 25;
    var legend = {
      layout: 'vertical',
    	style: {
    		right: '0px',
    		left: 'auto',
    		bottom: 'auto',
    		top: '20px'
    	},
    	borderWidth: 0,
    	shadow: false,
    	symbolWidth: 16,
    	itemStyle: {
    		color: '#3E576F',
    		fontSize: '10px'
    	},
    	itemHoverStyle: {
    		color: '#000'
    	},
    	itemHiddenStyle: {
    		color: '#999'
    	}
    };
    o.legend = legend;

  };

  });
})(jQuery);
