<?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 encode slashes
 * in a special way. This allows slashes to be used in autocomplete fields
 * like any other character.
 */

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

/**
 * Implementation of hook_menu_alter().
 * Override autocomplete paths with our helper function
 */
function autocomplete_hack_menu_alter(&$items) {
  if (!module_exists('autocomplete_post')) {
    $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_hack_autocomplete';
        $took_over[] = $k;
      }
    }
    drupal_set_message(t('Autocomplete Hack took over %items', array('%items' => join(', ', $took_over))));
  }
  else {
    drupal_set_message(t('Autocomplete Hack cannot be enabled at the same time as Autocomplete POST.'), 'error');
    module_disable(array('autocomplete_hack'));
  }
}

function _autocomplete_hack_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);
      array_push($ri, str_replace('~$~$~$~', '/', array_pop($ri)));
      call_user_func_array($func, $ri);
    }
  }
}
