<?php
// $Id$

/**
 * @file
 * In Drupal 7.23, autocomplete fields have a minor but annoying bug.
 * Autocomplete will ignore any trailing slashes in your search.
 * This module overrides Drupal's autocomplete behavior to use ajax.POST
 * instead of passing the search as a path parameter. This allows any
 * character to be used in autocomplete fields without malfunction.
 */

/**
 * Implementation of hook_init().
 * Override Drupal's automplete behavior
 */
function autocomplete_post_init() {
  drupal_add_js(drupal_get_path('module', 'autocomplete_post') . '/autocomplete_post.js');
}

/**
 * Implementation of hook_menu_alter().
 * Override autocomplete paths with our helper function
 */
function autocomplete_post_menu_alter(&$items) {
  if (!module_exists('autocomplete_hack')) {
    $took_over = array();
    foreach ($items as $k=>$foo) {
      if (strpos($k, '/autocomplete') > -1) {
        $auto =& $items[$k];
        $args = !empty($auto['page arguments']) ? $auto['page arguments'] : array();
        $auto['page arguments'] = array($auto['page callback']);
        $auto['page arguments'] += (is_array($args) ? $args : array($args));
        $auto['page callback'] = '_autocomplete_post_autocomplete';
        $took_over[] = $k;
      }
    }
    drupal_set_message(t('Autocomplete POST took over %items', array('%items' => join(', ', $took_over))));
  }
  else {
    drupal_set_message(t('Autocomplete POST cannot be enabled at the same time as Autocomplete Hack.'), 'error');
    module_disable(array('autocomplete_post'));
  }
}

function _autocomplete_post_autocomplete($func) {
  if ($router_item = menu_get_item($_GET['q'])) {
    $access = $router_item['access_callback'];
    if ($access($router['access_arguments'])) {
      $ri = array_slice($router_item['page_arguments'], 1);
      $ri[] = $_POST['search'];
      call_user_func_array($func, $ri);
    }
  }
}
