// 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', 'serrano', 'charts', 'forms/controls'], function(environ, mediator, $, _, Backbone, Serrano, Charts, Controls) {
  var ConceptItemView, QueryView, QueryViewFilterList, QueryViewsAccordian, QueryViewsPanel, QueryViewsSearchForm;
  QueryView = (function(_super) {

    __extends(QueryView, _super);

    function QueryView() {
      this.update = __bind(this.update, this);

      this.hide = __bind(this.hide, this);

      this.show = __bind(this.show, this);
      return QueryView.__super__.constructor.apply(this, arguments);
    }

    QueryView.prototype.template = _.template('\
            <div class="area-container queryview">\
                <h3 class=heading>\
                    {{ name }} <small>{{ category }}</small>\
                </h3>\
                <div class=btn-toolbar>\
                    <button data-toggle=detail class="btn btn-small"><i class=icon-info-sign></i> Info</button>\
                    <button data-toggle=hide class="btn btn-small"><i class=icon-minus></i> Hide</button>\
                </div>\
                <div class=details>\
                    <div class=description>{{ description }}</div>\
                </div>\
                <form class=form-inline>\
                </form>\
            </div>\
        ');

    QueryView.prototype.events = {
      'click [data-toggle=hide]': 'toggleHide',
      'click [data-toggle=detail]': 'toggleDetail',
      'submit form,button,input,select': 'preventDefault'
    };

    QueryView.prototype.deferred = {
      update: true
    };

    QueryView.prototype.initialize = function() {
      var attrs, cat,
        _this = this;
      QueryView.__super__.initialize.apply(this, arguments);
      attrs = {
        name: this.model.get('name'),
        category: (cat = this.model.get('category')) ? cat.name : '',
        description: this.model.get('description')
      };
      this.setElement(this.template(attrs));
      this.$form = this.$('form');
      this.$heading = this.$('.heading');
      this.$details = this.$('.details');
      mediator.subscribe('queryview/show', function(id) {
        if (_this.model.id === id) {
          return _this.show();
        }
      });
      mediator.subscribe('queryview/hide', function(id) {
        if (_this.model.id === id) {
          return _this.hide();
        }
      });
      return this.render();
    };

    QueryView.prototype.preventDefault = function(event) {
      return event.preventDefault();
    };

    QueryView.prototype.toggleDetail = function() {
      if (this.$details.is(':visible')) {
        return this.$details.slideUp(300);
      } else {
        return this.$details.slideDown(300);
      }
    };

    QueryView.prototype.toggleHide = function(event) {
      event.preventDefault();
      return mediator.publish('queryview/hide', this.model.id);
    };

    QueryView.prototype.render = function() {
      var $controls, attrs, chart, control, controlClass, fields, model, options, _i, _len, _ref,
        _this = this;
      fields = new Backbone.Collection(this.model.get('fields'));
      this.controls = [];
      this.charts = [];
      options = {
        label: fields.length === 1 ? false : true
      };
      _ref = fields.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        model = _ref[_i];
        options.model = model;
        $controls = $('<div></div>');
        attrs = model.attributes;
        if (attrs.simple_type === 'boolean') {
          controlClass = Controls.BooleanControl;
        } else if (attrs.enumerable) {
          controlClass = Controls.EnumerableControl;
        } else if (attrs.searchable) {
          controlClass = Controls.SearchableControl;
        } else if (attrs.simple_type === 'number') {
          controlClass = Controls.NumberControl;
        } else {
          controlClass = Controls.Control;
        }
        if (model.get('_links').distribution) {
          chart = new Charts.DistributionChart({
            editable: false,
            data: {
              context: null
            }
          });
        } else {
          chart = null;
        }
        this.controls.push((control = new controlClass(options)));
        this.charts.push([model, chart]);
        $controls.append(control.render());
        this.$form.append($controls);
        if (chart) {
          this.$form.append(chart.render());
        }
      }
      mediator.subscribe(Serrano.DATACONTEXT_SYNCED, function(model) {
        var conditions, _j, _len1, _ref1, _results;
        if (model.isSession()) {
          _ref1 = _this.controls;
          _results = [];
          for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
            control = _ref1[_j];
            if ((conditions = model.getNodes(control.model.id)) && conditions[0]) {
              _results.push(control.set(conditions[0]));
            } else {
              _results.push(void 0);
            }
          }
          return _results;
        }
      });
      this.update();
      return this.$el;
    };

    QueryView.prototype.show = function() {
      var $parent, control, _i, _len, _ref;
      this.resolve();
      $parent = $('#discover-area');
      this.$el.prependTo($parent);
      _ref = this.controls;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        control = _ref[_i];
        control.show();
      }
      return this;
    };

    QueryView.prototype.hide = function() {
      var offset, reset,
        _this = this;
      reset = {
        top: 'auto',
        left: 'auto',
        zIndex: 'auto',
        position: this.$el.css('position')
      };
      offset = this.$el.offset();
      this.$el.css({
        top: offset.top,
        left: offset.left,
        position: 'fixed',
        zIndex: -1
      });
      this.$el.animate({
        top: -this.$el.height()
      }, {
        duration: 600,
        easing: 'easeOutQuad',
        complete: function() {
          return _this.$el.detach().css(reset);
        }
      });
      this.pending();
      return this;
    };

    QueryView.prototype.update = function() {
      var chart, model, url, _i, _len, _ref, _ref1;
      _ref = this.charts;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        _ref1 = _ref[_i], model = _ref1[0], chart = _ref1[1];
        if (chart) {
          url = model.get('_links').distribution.href;
          chart.update(url, null, [model]);
        }
      }
    };

    return QueryView;

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

    __extends(ConceptItemView, _super);

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

    ConceptItemView.prototype.tagName = 'li';

    ConceptItemView.prototype.events = {
      'click a': 'click'
    };

    ConceptItemView.prototype.initialize = function() {
      var _this = this;
      mediator.subscribe('queryview/show', function(id) {
        if (id === _this.model.id) {
          return _this.$el.addClass('active');
        } else {
          return _this.$el.removeClass('active');
        }
      });
      return mediator.subscribe('queryview/hide', function(id) {
        if (id === _this.model.id) {
          return _this.$el.removeClass('active');
        }
      });
    };

    ConceptItemView.prototype.render = function() {
      if (!this.model.get('published')) {
        this.$el.addClass('staff-only').attr('data-placement', 'right');
      }
      return this.$el.html("<a href=#>" + (this.model.get('name')) + "</a>");
    };

    ConceptItemView.prototype.click = function(event) {
      event.preventDefault();
      return mediator.publish('queryview/show', this.model.id);
    };

    return ConceptItemView;

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

    __extends(QueryViewsAccordian, _super);

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

    QueryViewsAccordian.prototype.id = 'data-filters-accordian';

    QueryViewsAccordian.prototype.className = 'accordian';

    QueryViewsAccordian.prototype.groupTemplate = _.template('\
            <div class=accordian-group>\
                <div class=accordian-heading>\
                    <a class=accordian-toggle data-toggle=collapse href="#category-{{ id }}">{{ name }}</a>\
                    <i class=icon-filter></i>\
                </div>\
                <div id="category-{{ id }}" class="accordian-body collapse">\
                    <ul class="nav nav-list"></ul>\
                </div>\
            </div> \
        ');

    QueryViewsAccordian.prototype.initialize = function() {
      var _this = this;
      this.$el.addClass('loading');
      return this.collection.when(function() {
        _this.$el.removeClass('loading');
        _this.render();
        return _this.collection.each(function(model, i) {
          if (model.get('queryview')) {
            return new QueryView({
              model: model
            });
          }
        });
      });
    };

    QueryViewsAccordian.prototype.render = function() {
      var $group, $list, attrs, cat, cats, id, model, models, name, sub, subcats, subtree, tree, view, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref;
      tree = {
        categories: []
      };
      _ref = this.collection.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        model = _ref[_i];
        if (!model.get('queryview')) {
          continue;
        }
        attrs = model.attributes;
        cat = null;
        sub = {
          id: null
        };
        if (attrs.category) {
          if (attrs.category.parent) {
            cat = attrs.category.parent;
            sub = attrs.category;
          } else {
            cat = attrs.category;
          }
        }
        if (!(subtree = tree[cat.id])) {
          tree.categories.push(cat);
          subtree = tree[cat.id] = {
            categories: []
          };
        }
        if (!(models = subtree[sub.id])) {
          if (sub.id) {
            subtree.categories.push(sub);
          }
          models = subtree[sub.id] = [];
        }
        models.push(model);
      }
      cats = _.sortBy(tree.categories, 'order');
      if (tree[null]) {
        cats.push(null);
      }
      for (_j = 0, _len1 = cats.length; _j < _len1; _j++) {
        cat = cats[_j];
        if (!cat) {
          cat = {
            id: null,
            name: 'Other'
          };
        }
        $group = $(this.groupTemplate(cat));
        this.$el.append($group);
        $list = $group.find('.accordian-body ul');
        subtree = tree[cat.id];
        subcats = _.sortBy(subtree.categories, 'order');
        if (subtree[null]) {
          subcats.push(null);
        }
        for (_k = 0, _len2 = subcats.length; _k < _len2; _k++) {
          sub = subcats[_k];
          if (sub) {
            id = sub.id;
            name = sub.name;
          } else {
            id = null;
            name = 'Other';
          }
          $list.append("<li class=nav-header>" + name + "</li>");
          $list.append("<li class=divider>" + name + "</li>");
          models = subtree[id];
          for (_l = 0, _len3 = models.length; _l < _len3; _l++) {
            model = models[_l];
            view = new ConceptItemView({
              model: model
            });
            $list.append(view.render());
          }
        }
        if (subcats.length === 1) {
          $list.find('.nav-header').remove();
          $list.find('.divider').remove();
        }
      }
      if (cats.length === 1) {
        $group.find('.accordian-heading').remove();
        $group.find('.accordian-body').removeClass('collapse');
      }
      return this.$el;
    };

    return QueryViewsAccordian;

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

    __extends(QueryViewsSearchForm, _super);

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

    QueryViewsSearchForm.prototype.template = _.template('\
            <form id=data-filters-search class=form-search action=>\
                <input type=text class=search-query placeholder=Search>\
            </form>\
        ');

    QueryViewsSearchForm.prototype.events = {
      'keyup input': 'autocomplete',
      'submit': 'search'
    };

    QueryViewsSearchForm.prototype.initialize = function() {
      return this.setElement(this.template());
    };

    QueryViewsSearchForm.prototype.autocomplete = function() {};

    QueryViewsSearchForm.prototype.search = function() {};

    return QueryViewsSearchForm;

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

    __extends(QueryViewsPanel, _super);

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

    QueryViewsPanel.prototype.template = _.template('\
            <div id=data-filters-panel class="panel panel-left scrollable-column closed">\
                <div class="inner panel-content"></div>\
                <div class=panel-toggle></div>\
            </div>\
        ');

    QueryViewsPanel.prototype.initialize = function(options) {
      var content;
      this.setElement(this.template());
      content = this.$('.panel-content');
      this.browser = new QueryViewsAccordian({
        collection: this.collection
      });
      if (options.enableSearch) {
        this.form = new QueryViewsSearchForm({
          collection: this.collection
        });
        content.append(this.form.el);
      }
      content.append(this.browser.el);
      $('body').append(this.$el);
      return this.$el.panel();
    };

    return QueryViewsPanel;

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

    __extends(QueryViewFilterList, _super);

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

    QueryViewFilterList.prototype.events = {
      'click [data-toggle=clear]': 'clear'
    };

    QueryViewFilterList.prototype.template = _.template('\
            <div id=data-filters-list-panel class="panel panel-right scrollable-column closed">\
                <div class="inner panel-content"></div>\
                <div class=panel-toggle></div>\
            </div>\
        ');

    QueryViewFilterList.prototype.initialize = function(options) {
      var _this = this;
      this.setElement(this.template());
      this.$content = this.$('.panel-content');
      $('body').append(this.$el);
      this.$el.panel();
      mediator.subscribe(Serrano.DATACONTEXT_SYNCING, function() {
        return _this.$content.addClass('loading');
      });
      return mediator.subscribe(Serrano.DATACONTEXT_SYNCED, function(model) {
        if (model.isSession()) {
          return _this.render(model);
        }
      });
    };

    QueryViewFilterList.prototype._parse = function(node, html) {
      var child, _i, _len, _ref;
      if (html == null) {
        html = [];
      }
      if (node.children) {
        html.push("<ul><li class=nav-header>" + node.type + "'ed</li>");
        _ref = node.children;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          child = _ref[_i];
          this._parse(child, html);
        }
        html.push("</ul>");
      } else {
        if (!html.length) {
          html.push("<ul>");
        }
        html.push("<li>" + node.language + "</li>");
        if (!html.length) {
          html.push("</ul>");
        }
      }
      return html;
    };

    QueryViewFilterList.prototype.render = function(model) {
      var node, ul;
      this.$content.removeClass('loading');
      node = model.get('language');
      this.$content.html('<h4>Applied Filters</h4>');
      if (!node || _.isEmpty(node)) {
        this.$content.append('<div class=muted>No filters are applied</div>');
      } else {
        ul = $(this._parse(node).join('')).addClass('unstyled nav-list');
        this.$content.append(ul);
      }
      this.$content.append('\
                <div class=actions>\
                    <button data-route="review/" class="btn btn-small btn-primary">View Results</button>\
                    <button data-toggle=clear class="btn btn-small btn-danger pull-right" title="Clear All">\
                        <i class="icon-ban-circle icon-white"></i></button>\
                </div>\
            ');
      return this.$el;
    };

    QueryViewFilterList.prototype.clear = function(event) {
      event.preventDefault();
      return mediator.publish(Serrano.DATACONTEXT_CLEAR);
    };

    return QueryViewFilterList;

  })(Backbone.View);
  return {
    View: QueryView,
    Panel: QueryViewsPanel,
    SearchForm: QueryViewsSearchForm,
    Accordian: QueryViewsAccordian,
    List: QueryViewFilterList
  };
});
