
/**
 * Adds the custom autocomplete widget behavior.
 */
Drupal.apachesolr_autocomplete = {
  processOne: function(key, settings, context) {
    // Look for items with the data-apachesolr-autocomplete-id attribute.
    jQuery(".apachesolr-autocomplete[data-apachesolr-autocomplete-id='" + key + "']", context)
      .apachesolr_autocomplete(settings.path, {
      // Classnames for the widget.
      inputClass: "",
      loadingClass: "throbbing",
      // Do not select first suggestion by default.
      selectFirst: false,
      // Specify no matching as it wil be done on server-side.
      matchContains: false,
      matchSubset: false,
      // Maximum number of items to show in widget.
      max: 50,
      scroll: true,
      scrollHeight: 360,
      // Data returned from server is JSON-encoded.
      dataType: "json",
      // Function to parse returned json into elements.
      parse: function(data) {
        return jQuery.map(data, function(item) {
          return {
            data: item,          // Echo the input data.
            value: item.display, // This will be shown in the options widget.
            result: item.key     // The actual value to put into the form element.
          }
        });
      },
      // Return the HTML to display in the options widget.
      formatItem: function(item) {
        return item.display;
      }
    }).result(function(item, element) {
      // Handle selection of an element in the autocomplete widget.
      // We should submit the widget's parent form.
      jQuery(this).closest("form").submit();
    }).addClass('form-autocomplete'); // Add Drupal autocomplete widget's style.
  }
};
Drupal.behaviors.apachesolr_autocomplete = {
  attach: function(context) {
    // Check that settings exist.
    if (!Drupal.settings.apachesolr_autocomplete || !Drupal.settings.apachesolr_autocomplete.forms) {
      return;
    }

    // Cycle thru the settings array which contains:
    //   key => settingsArray
    // where
    //   key: the data-apachesolr-autocomplete-id HTML attribute to look for
    //        (which was added on the form_alter)
    //   settings: and
    jQuery.each(Drupal.settings.apachesolr_autocomplete.forms, function(key, settings) {
      Drupal.apachesolr_autocomplete.processOne(key, settings, context);
    });
  }
};
