<?php

/**
 * @file
 * Provides a views filter handler for adding values to another filter.
 */

/**
 * Implements hook_menu().
 */
function views_ajax_form_menu() {
  $items['views-ajax-form/%'] = array(
    'page callback' => 'views_ajax_form_ajax_callback',
    'page arguments' => array(1),
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE,
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implements hook_views_api().
 */
function views_ajax_form_views_api() {
  return array(
    'api' => 3,
  );
}

/**
 * Page callback: Returns an exposed form via AJAX.
 *
 * @param string $id
 *   The internal ID for the form information.
 *
 * @return array
 *   An array of AJAX commands.
 */
function views_ajax_form_ajax_callback($id) {
  $selector = "#views-ajax-form-placeholder-$id";

  // Retrieve either the form state, or the whole form HTML, from cache.
  if ($cache = cache_get($id, 'cache_views_ajax_form')) {
    if (is_array($cache->data)) {
      // If the cache data is an array, it's the form state. Use that to build
      // the form and render it to get the HTML to return.
      $form_state = $cache->data;
      $form = drupal_build_form('views_exposed_form', $form_state);
      $html = drupal_render($form);
    }
    else {
      $html = $cache->data;
    }
  }
  else {
    drupal_set_message(t('The filters could not be retrieved. This could mean the page has become out-dated. Please try re-loading the page to display the filters.'), 'error');
    $html = theme('status_messages');
  }

  // Save the HTML back into the cache so we don't have to re-render it in case
  // the view got cached. Since views results might get cached almost
  // indefinitely, we need to use a large value here (this is 30 days).
  cache_set($id, $html, 'cache_views_ajax_form', REQUEST_TIME + 2592000);

  $commands[] = ajax_command_replace($selector, $html);
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}
