/* The fancybox spinner has been bound to jQuery's ajaxStart (see application.js) */
/* Unbind it, since we don't need it for this view. */
$(document).unbind('ajaxStart');

ThreeScale.Analytics.TopUsers = {};
var co = ThreeScale.Analytics.Charts;
var h = ThreeScale.Helper.Charts;

co.prototype.dealWithResponse = function(r){
  this.initialiseChart(r);
  ThreeScale.Analytics.TopUsers.getTopUsers();
};

co.prototype.showLoading = function(){
  this.$renderTo.find('.loading').fadeIn('slow');
};


jQuery(document).ready(function(){
  ThreeScale.Analytics.TopUsers.service_id = $('#chart-1').attr('data-service-id');
  ThreeScale.Analytics.TopUsers.init();

});

(function($){
ThreeScale.Analytics.TopUsers = {
  h: ThreeScale.Helper.General,

  init: function(){
    this.$loadingTopUsers = jQuery('.data-sup .loading') || null;
    this.$topUsers = jQuery('#methods');
    // this.multi = (jQuery('#top-users').attr('data-multi') == 'true') ? true : false;
    var c = new ThreeScale.Analytics.Charts('chart-1', {dataEndPoint: this.resources.usage()});

    c.chartOptions.plotOptions.series.showInLegend = false;
    c.init();
    c.$loading = jQuery('.chart-wrap .loading');
    this.chart = c;
    this.updateCSVPath();
    this.listen();
  },

  // DRY this up. Perhaps created 'resources' object to be share by all stats pages.
  resources: {
    usage: function(){
     return '/stats/services/' + ThreeScale.Analytics.TopUsers.service_id + '/usage.json';
    },
    top_applications: function(){
     return '/stats/services/' + ThreeScale.Analytics.TopUsers.service_id + '/top_applications.json';
    }
  },

	updateCSVPath: function(){
		var link = $('.download-csv-button a');
		var url = this.resources.top_applications().replace('.json', '.csv') + "?" + $.param(this.chart.queryData());
		link.attr('href', url);
	},

  listen: function(){
    var that = this;

    $('div.paginate a').live('click', function(){
      $('div.paginate a').removeClass('current');
      $this = $(this);
      var value = $(this).attr('data-value');
      $this.addClass('current');
      $('div.data-sup ul').css({marginTop:-value});
      return false;
    });

    $(window).bind('apply-selectors', function(){
      $('#methods').html('');
      $('.stats-support .paginate').remove();
      that.updateCSVPath();
    });


    jQuery('#methods li.top-user').live('click', function(){
      var $this = jQuery(this);

      // Do nothing if data for selected app is loading.
      if($this.attr('disabled') == 'true'){
        return false;
      }

      var id = $this.attr('data-client'),
          series = that.chart.chart.get(id),
          $total = $this.find('small');

      if(series){
        if(series.visible){
          series.hide();
          $total.css('background', '#F6F6F6');
        } else {
          series.show();
          $total.css('background', $total.attr('colour'));
        }
      } else {
        var $loading = $("<em>LOADING</em>");
        $this.find('small').append($loading);
        $this.attr('disabled', 'true');

        $.ajax({
          dataType: 'json',
          data: Stats.SearchOptions,
          url: "/stats/applications/"+id+"/usage.json",
          success: function(r) {
              $this.removeAttr('disabled');
              $loading.remove();
              var str = Highcharts.numberFormat(r.total, 0) + " " + pluralize(r.metric.unit, r.total);
              var colour = h.pickColour(that.chart.chart.series.length);

              $total.html(str);
              $total.css('backgroundColor', colour);
              $total.attr('colour', colour);
              that.chart.addLineSeries({
                name: r.metric.name,
                data: r.values,
                lineColor: colour,
                id: r.application.id,
                marker: {fillColor: colour}
              });
          }
        });
        // that.getData(id, function(user,c){
        //
        //   var str = Highcharts.numberFormat(user.usage.data.sum(), 0) + " " + that.h.pluralise($('#current-metric').attr('data-metric-unit'));
        //   $total.html(str);
        //   $total.css('backgroundColor', c);
        //   $total.attr('colour', c);
        // });
      }
      return false;
    });

  },

  getData: function(id, fn){
    var that = this,
        params = this.chart.queryData();
        colour = h.pickColour(this.chart.chart.series.length);

    var data = that.topUserData;

    var user = (function(){
      var user;
      for (var i = data.length - 1; i >= 0; i--){
        if(data[i].client_id == id) {
          user = data[i];
          break;
        }
      };
      return user;
    })();

    that.chart.addLineSeries({
      name: user.usage.metric_name,
      data: user.usage.data,
      lineColor: colour,
      id: user.client_id,
      marker: {fillColor: colour}
    });
    if(fn) fn(user, colour);



    // $.ajax({
    //   dataType: 'json',
    //   data: params,
    //   url: "/stats/clients/"+id+"/usage.json",
    //   success: function(r) {
    //     that.chart.addLineSeries({
    //       name: r.metric_name,
    //       data:r.data,
    //       lineColor: colour,
    //       id: r.client.client_id,
    //       marker: {fillColor: colour}
    //     });
    //     if(fn) fn(r, colour);
    //   }
    // });
  },

  getTopUsers: function(){

    var that = this;
    $('div.methods-loading').show();
    $.ajax({
      dataType: 'json',
      data: that.chart.queryData(),
      url: ThreeScale.Analytics.TopUsers.resources.top_applications(),
      success: function(data) {
        var applications = data.applications;
        applications.sort(function(a,b){
          return a.value - b.value;
        })
        that.topUserData = applications;

        that.displayTopApps(applications);
      },
      complete: function(){
        $('div.methods-loading').fadeOut();
      }
    });
  },

  topItemLabel: function(u){
    var name = '';
    if(u.name != '' && u.name != null && u.account!=null && u.account.name!=null){
      name = "("+u.name+") " + u.account.name;
    } else {
      if(u.account!=null && u.account.name!=null && u.id!=null) {
        name = "("+u.id+") " + u.account.name;
      }
      else {
        // what is this u.client ?? connect?
        name = u.client.name;
      }
    }
    if(name.length > 37) {
      name = name.slice(0,34) + "...";
    }
    return name;
  },

  topItem: function(u){
    return item = ["<li data-client='"+u.id+"' class='top-user'>",
     this.topItemLabel(u), "<span><small>", this.h.numberPadding(u.value, 0), "&nbsp;",
     pluralize($('#current-metric').attr('data-metric-unit'), u.value), "</small></span>",
    "</li>"].join('');
  },

  displayTopApps:  function(apps){
    var u, item, html;

    $(".stats-notice").remove();
    $('#top-users ul').remove();

    if(apps.length == 0){
      var msg = "<div class='stats-notice'><p>There is no data for this period.</p></div>";

      this.$topUsers.append(msg);
    } else {
      // $list = $("<ul></ul>");
      var list = [];
      for (var x = apps.length - 1; x >= 0; x--){
        list.push(this.topItem(apps[x]));
      }

      // this.$topUsers.append($list);
      // this.$topUsers.prepend("<h2>Applications</h2>");
      html = "<h2>Applications</h2> \
             <div class='data-sup-wrap'><ul>" + list.join('') + "</ul></div>";

      this.$topUsers.append(html);
    }

    $('.data-sup:first').fadeIn();
  }

};

})(jQuery);
