(function($) {
  Drupal.behaviors.selectizeFields = {
    attach: function(context, settings) {
      if (typeof(settings.selectizeFields) !== 'undefined') {
        $.each(settings.selectizeFields, function(index, options) {
          var e = $('#' + index);
          var path = options.path || false;
          var widgetType = options.widgetType || false;
          if (typeof('path') !== 'undefined') {
            options.load = function(query, callback) {
              if (!query.length) return callback();
              var ajaxOpts = {
                url: '/' + path + '/' + encodeURIComponent(query),
                type: 'GET',
                error: function() {
                  callback();
                },
              };
              ajaxOpts.success = function(res) {
                var matches = [];
                $.each(res, function(value,text) {
                  matches.push({"value":value,"text":$(text).text().trim(),"rawText":text});
                });
                callback(matches);
              }
              $.ajax(ajaxOpts);
            };

            if (widgetType.match(/entityreference.*/)) {
              options.render = {
                option: function(item,escape) {
                    return item.rawText;
                },
                item: function(item,escape) {
                  return '<div>' + escape(item.text) + '</div>';
                }
              }
            }
            else if (widgetType === 'options_select') {
              options.onItemAdd = function(value,item) {
                if (value === '_none') {
                  this.clear();
                }
              }
            }

          }

          e.selectize(options);
        });
      }
    }
  };
  Drupal.behaviors.selectize = {
    attach: function(context, settings) {
      if (typeof settings.selectize != 'undefined') {
        $.each(settings.selectize.settings, function(index, value) {
          $('#' + index).selectize(JSON.parse(value));
        });
      }
    }
  }
})(jQuery);