<?php
// $Id$

/**
 * @file
 * In Drupal 6.19, autocomplete fields have a minor but annoying bug.
 * If there's a slash in the field auto search will ignore everything after.
 * 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 = $auto['page arguments'];
        $auto['page arguments'] = array($auto['page callback']);
        if ($args) $auto['page arguments'] += (is_array($args) ? $args : array($args));
        $auto['page callback'] = '_autocomplete_post_autocomplete';
        $took_over[] = $k;
      }
    }
    drupal_set_message("Autocomplete POST took over ". join(', ', $took_over));
  }
  else {
    drupal_set_message('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'])) {
    if ($router_item['access']) {
      $ri = array_slice($router_item['page_arguments'], 1);
      $ri[] = $_POST['search'];
      call_user_func_array($func, $ri);
    }
  }
}
