// Generated by CoffeeScript 1.3.3
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

define(['environ', 'mediator', 'jquery', 'underscore', 'backbone', './utils', './backbone-charts'], function(environ, mediator, $, _, Backbone, utils) {
  var DataFieldDistribution, DistributionChart, chartTmpl;
  chartTmpl = _.template('\
        <div class="area-container chart-container">\
            <div class=btn-toolbar>\
                <div class=btn-group>\
                    <button class="btn btn-mini fullsize" title="Toggle Fullsize"><i class=icon-resize-full alt="Toggle Fullsize"></i></button>\
                    <!--<button class="btn btn-mini outliers" title="Show Outliers" disabled><i class=icon-eye-open alt="Show Outliers"></i></button>-->\
                </div>\
                <div class=btn-group>\
                    <button class="btn btn-mini edit" title="Edit"><i class=icon-wrench alt="Edit"></i></button>\
                </div>\
                <div class=btn-group>\
                    <button class="btn btn-danger btn-mini remove" title="Remove"><i class=icon-remove alt="Remove"></i></button>\
                </div>\
            </div>\
            <div class=heading>\
                <span class="label label-info"></span>\
            </div>\
            <div class=editable>\
                <form class=form>\
                    <fieldset>\
                        <label>X-Axis <select name=x-axis></select></label>\
                        <label>Y-Axis <select name=y-axis></select></label>\
                        <label>Series <select name=series></select></label>\
                        <button class="btn btn-primary">Update</button>\
                    </fieldset>\
                </form>\
            </div>\
            <div class=chart>\
            </div>\
        </div>\
    ');
  DataFieldDistribution = (function(_super) {

    __extends(DataFieldDistribution, _super);

    function DataFieldDistribution() {
      this.render = __bind(this.render, this);
      return DataFieldDistribution.__super__.constructor.apply(this, arguments);
    }

    DataFieldDistribution.prototype.tagName = 'select';

    DataFieldDistribution.prototype.options = {
      enumerableOnly: false
    };

    DataFieldDistribution.prototype.initialize = function() {
      return this.collection.when(this.render);
    };

    DataFieldDistribution.prototype.render = function() {
      var model, _i, _len, _ref;
      this.$el.append('<option value=>---</option>');
      _ref = this.collection.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        model = _ref[_i];
        if (model.get('searchable')) {
          continue;
        }
        if (this.options.enumerableOnly && !model.get('enumerable')) {
          continue;
        }
        this.$el.append("<option value=\"" + model.id + "\">" + (model.get('name')) + "</option>");
      }
      return this.$el;
    };

    DataFieldDistribution.prototype.getSelected = function() {
      return this.collection.get(parseInt(this.$el.val()));
    };

    return DataFieldDistribution;

  })(Backbone.View);
  DistributionChart = (function(_super) {

    __extends(DistributionChart, _super);

    function DistributionChart() {
      return DistributionChart.__super__.constructor.apply(this, arguments);
    }

    DistributionChart.prototype.options = {
      editable: true
    };

    DistributionChart.prototype.events = {
      'mouseenter': 'showToolbar',
      'mouseleave': 'hideToolbar',
      'click .fullsize': 'toggleExpanded',
      'click .outliers': 'toggleOutliers',
      'click .edit': 'toggleEdit',
      'click .remove': 'removeChart',
      'submit': 'changeChart',
      'change .editable select': 'disableSelected'
    };

    DistributionChart.prototype.initialize = function() {
      var expanded;
      DistributionChart.__super__.initialize.apply(this, arguments);
      this.setElement(chartTmpl());
      this.$heading = this.$('.heading');
      this.$label = this.$heading.find('.label');
      this.$renderArea = this.$('.chart');
      this.$toolbar = this.$('.btn-toolbar');
      this.$fullsizeToggle = this.$('.fullsize');
      this.$form = this.$('.editable');
      if (this.options.editable === false) {
        this.$form.detach();
        return this.$toolbar.detach();
      } else {
        this.xAxis = new DataFieldDistribution({
          el: this.$el.find('[name=x-axis]'),
          collection: this.collection
        });
        this.yAxis = new DataFieldDistribution({
          el: this.$el.find('[name=y-axis]'),
          collection: this.collection
        });
        this.series = new DataFieldDistribution({
          el: this.$el.find('[name=series]'),
          enumerableOnly: true,
          collection: this.collection
        });
        if (this.model) {
          if (this.model.get('xAxis')) {
            this.$form.hide();
          }
          if ((expanded = this.model.get('expanded'))) {
            return this.expand();
          } else {
            return this.contract();
          }
        }
      }
    };

    DistributionChart.prototype.render = function() {
      return this.$el;
    };

    DistributionChart.prototype.renderChart = function(options) {
      var labelText, _base;
      if (this.chart) {
        if (typeof (_base = this.chart).destroy === "function") {
          _base.destroy();
        }
      }
      this.$label.detach();
      this.$heading.text(options.title.text);
      options.title.text = '';
      if (!options.series[0]) {
        this.$renderArea.html('<p class=no-data>Unfortunately, there is\
                    no data to graph here.</p>');
        return;
      }
      this.$form.hide();
      labelText = [];
      if (options.clustered) {
        labelText.push('Clustered');
      }
      if (labelText[0]) {
        this.$label.text(labelText.join(', ')).show();
        this.$heading.append(this.$label);
      }
      $.extend(true, options, this.chartOptions);
      options.chart.renderTo = this.$renderArea[0];
      this.chart = new Highcharts.Chart(options);
      return this;
    };

    DistributionChart.prototype.disableSelected = function(event) {
      var $target, value;
      $target = $(event.target);
      if (this.xAxis.el === event.target) {
        this.yAxis.$('option').prop('disabled', false);
        this.series.$('option').prop('disabled', false);
      } else if (this.yAxis.el === event.target) {
        this.xAxis.$('option').prop('disabled', false);
        this.series.$('option').prop('disabled', false);
      } else {
        this.xAxis.$('option').prop('disabled', false);
        this.yAxis.$('option').prop('disabled', false);
      }
      if ((value = $target.val()) !== '') {
        if (this.xAxis.el === event.target) {
          this.yAxis.$("option[value=" + value + "]").prop('disabled', true).val('');
          return this.series.$("option[value=" + value + "]").prop('disabled', true).val('');
        } else if (this.yAxis.el === event.target) {
          this.xAxis.$("option[value=" + value + "]").prop('disabled', true).val('');
          return this.series.$("option[value=" + value + "]").prop('disabled', true).val('');
        } else {
          this.xAxis.$("option[value=" + value + "]").prop('disabled', true).val('');
          return this.yAxis.$("option[value=" + value + "]").prop('disabled', true).val('');
        }
      }
    };

    DistributionChart.prototype.toggleExpanded = function(event) {
      var expanded;
      expanded = this.model.get('expanded');
      if (expanded) {
        this.contract();
      } else {
        this.expand();
      }
      return this.model.save({
        expanded: !expanded
      });
    };

    DistributionChart.prototype.resize = function() {
      var chartWidth;
      chartWidth = this.$renderArea.width();
      if (this.chart) {
        return this.chart.setSize(chartWidth, null, false);
      }
    };

    DistributionChart.prototype.expand = function() {
      this.$fullsizeToggle.children('i').removeClass('icon-resize-small').addClass('icon-resize-full');
      this.$el.addClass('expanded');
      return this.resize();
    };

    DistributionChart.prototype.contract = function() {
      this.$fullsizeToggle.children('i').removeClass('icon-resize-full').addClass('icon-resize-small');
      this.$el.removeClass('expanded');
      return this.resize();
    };

    DistributionChart.prototype.hideToolbar = function() {
      return this.$toolbar.fadeOut(200);
    };

    DistributionChart.prototype.showToolbar = function() {
      return this.$toolbar.fadeIn(200);
    };

    DistributionChart.prototype.toggleOutliers = function(event) {
      var series, _i, _len, _ref, _results;
      _ref = this.chart.series;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        series = _ref[_i];
        continue;
      }
      return _results;
    };

    DistributionChart.prototype.toggleEdit = function(event) {
      if (this.$form.is(':visible')) {
        return this.$form.fadeOut(300);
      } else {
        return this.$form.fadeIn(300);
      }
    };

    DistributionChart.prototype.removeChart = function(event) {
      var _base;
      if (this.chart) {
        if (typeof (_base = this.chart).destroy === "function") {
          _base.destroy();
        }
      }
      this.$el.remove();
      if (this.model) {
        return this.model.destroy();
      }
    };

    DistributionChart.prototype.update = function(url, data, fields, seriesIdx) {
      var key, value, _ref,
        _this = this;
      if (this.options.data) {
        _ref = this.options.data;
        for (key in _ref) {
          value = _ref[key];
          if (!data) {
            data = "" + key + "=" + value;
          } else {
            data = data + ("&" + key + "=" + value);
          }
        }
      }
      this.$el.addClass('loading');
      return Backbone.ajax({
        url: url,
        data: data,
        success: function(resp) {
          _this.$el.removeClass('loading');
          return _this.renderChart(utils.processResponse(resp, fields, seriesIdx));
        }
      });
    };

    DistributionChart.prototype.changeChart = function(event) {
      var _this = this;
      if (event) {
        event.preventDefault();
      }
      return this.collection.when(function() {
        var data, fields, series, seriesIdx, url, xAxis, yAxis;
        if (!(event != null)) {
          if ((xAxis = _this.model.get('xAxis'))) {
            _this.xAxis.$el.val(xAxis.toString());
          }
          if ((yAxis = _this.model.get('yAxis'))) {
            _this.yAxis.$el.val(yAxis.toString());
          }
          if ((series = _this.model.get('series'))) {
            _this.series.$el.val(series.toString());
          }
        }
        xAxis = _this.xAxis.getSelected();
        yAxis = _this.yAxis.getSelected();
        series = _this.series.getSelected();
        if (!xAxis) {
          return;
        }
        url = _this.model.get('_links').distribution.href;
        fields = [xAxis];
        data = 'dimension=' + xAxis.id;
        if (yAxis) {
          fields.push(yAxis);
          data = data + '&dimension=' + yAxis.id;
        }
        if (series) {
          seriesIdx = yAxis ? 2 : 1;
          data = data + '&dimension=' + series.id;
        }
        if (event && _this.model) {
          _this.model.set({
            xAxis: xAxis.id,
            yAxis: yAxis ? yAxis.id : void 0,
            series: series ? series.id : void 0
          });
        }
        return _this.update(url, data, fields, seriesIdx);
      });
    };

    return DistributionChart;

  })(Backbone.Chart);
  return {
    DistributionChart: DistributionChart
  };
});
