(function() {
  var DocsWidget, docs;

  DocsWidget = (function() {
    DocsWidget.host = "//support.3scale.net";

    DocsWidget.url = DocsWidget.host + "/search.json";

    DocsWidget.per_page = 10;

    function DocsWidget(element) {
      $((function(_this) {
        return function() {
          _this.widget = $(element);
          _this.widget.find('[data-role=search]').on('submit', function(event) {
            return _this.search(event.target);
          }).end().find('[data-role=close]').on('click', function() {
            return _this.close();
          });
          return _this.results = _this.widget.find('[data-role=results]');
        };
      })(this));
    }

    DocsWidget.prototype.el = function(name, attrs) {
      if (attrs == null) {
        attrs = {};
      }
      return $("<" + name + "/>", attrs);
    };

    DocsWidget.prototype.activate = function() {
      this.widget.addClass('active');
      return this.results.slideDown();
    };

    DocsWidget.prototype.deactivate = function() {
      this.widget.removeClass('active');
      return this.results.slideUp();
    };

    DocsWidget.prototype.search = function(form) {
      var query;
      query = $(form.q).val();
      $.ajax({
        url: DocsWidget.url,
        dataType: 'jsonp',
        data: {
          q: query,
          per_page: DocsWidget.per_page
        },
        success: (function(_this) {
          return function(data) {
            return _this.show(data);
          };
        })(this)
      });
      return false;
    };

    DocsWidget.prototype.result = function(attrs) {
      var result;
      if (attrs == null) {
        return;
      }
      result = [];
      result.push(this.el('li').append(this.el('a', {
        href: DocsWidget.host + attrs.path,
        html: attrs.title,
        target: '_blank'
      })));
      return result;
    };

    DocsWidget.prototype.show = function(data) {
      var i, item, len;
      this.empty();
      if (data.length > 0) {
        for (i = 0, len = data.length; i < len; i++) {
          item = data[i];
          this.results.append(this.result(item.page));
        }
      } else {
        this.results.append(this.el('li', {
          text: 'No results',
          "class": 'no-results'
        }));
      }
      return this.activate();
    };

    DocsWidget.prototype.empty = function() {
      return this.results.find('*').remove();
    };

    DocsWidget.prototype.reset = function() {
      var input;
      input = this.widget.find('input');
      input.val('');
      return input.focus();
    };

    DocsWidget.prototype.close = function() {
      this.deactivate();
      this.empty();
      return this.reset();
    };

    return DocsWidget;

  })();

  docs = new DocsWidget('#docs-widget');

}).call(this);
