(function() {
  $.fn.select2.defaults.set("theme", "bootstrap");

  decko.slotReady(function(slot) {
    return slot.find('select:not(._no-select2)').each(function(_i) {
      return decko.initSelect2($(this));
    });
  });

  decko.slotDestroy(function(slot) {
    return slot.find('select:not(._no-select2)').each(function(_i) {
      return $(this).deInitSelect2();
    });
  });

  $.extend(decko, {
    initSelect2: function(elem) {
      var i, len, opts, results, single_el;
      if (elem.length > 1) {
        results = [];
        for (i = 0, len = elem.length; i < len; i++) {
          single_el = elem[i];
          results.push(decko.initSelect2($(single_el)));
        }
        return results;
      } else {
        opts = {
          dropdownAutoWidth: "true",
          containerCssClass: ":all:",
          width: "auto"
        };
        elem.attr("id", decko.uniqSelect2Id(elem.attr("id")));
        if (elem.hasClass("tags")) {
          opts.tags = "true";
        }
        if (elem.data("minimum-results-for-search") != null) {
          opts.minimumResultsForSearch = elem.data("minimum-results-for-search");
        }
        return elem.select2(opts);
      }
    },
    uniqSelect2Id: function(id) {
      if (!($("[data-select2-id=" + id + "]").length > 0)) {
        return id;
      }
      return decko.uniqSelect2Id(id + "1");
    }
  });

  $(window).ready(function() {
    $('body').on('select2:select', '._go-to-selected', function() {
      var val;
      val = $(this).val();
      if (val !== '') {
        return window.location = decko.path(escape(val));
      }
    });
    return $('body').on("select2:select", "._submit-on-select", function(event) {
      return $(event.target).closest('form').submit();
    });
  });

  $.fn.extend({
    cloneSelect2: function(withDataAndEvents, deepWithDataAndEvents) {
      var $cloned, $old;
      $old = this.is('select') ? this : this.find('select');
      $old.deInitSelect2();
      $cloned = this.clone(withDataAndEvents, deepWithDataAndEvents);
      decko.initSelect2($old);
      if ($cloned.is('select')) {
        decko.initSelect2($cloned);
      } else {
        decko.initSelect2($cloned.find('select'));
      }
      return $cloned;
    },
    deInitSelect2: function() {
      this.select2("destroy");
      this.removeAttr("data-select2-id");
      return this.find("option").removeAttr("data-select2-id");
    }
  });

}).call(this);