<?php
/**
 * @file views_dependent_filters.module
 * Provides a Views exposed filter which makes other filters depend on values
 * in yet further filters for their visiblity and processing.
 * For example: if the 'node type' filter is set to 'article', show a filter for
 * a field that is only present on articles.
 */

/**
 * Implements hook_views_api().
 */
function views_dependent_filters_views_api() {
  return array(
    'api' => '3.0-alpha1',
    'path' => drupal_get_path('module', 'views_dependent_filters'),
  );
}

/**
 * After build form processor for the views exposed form.
 *
 * This is added by the exposed filter handler so that we can add a CTools
 * visiblity dependency.
 * We don't use Drupal core #states because as far as I can tell they don't
 * work here.
 * See also merlinofchaos's comment here: http://drupal.org/node/1406470
 */
function views_dependent_filters_exposed_form_after_build($form, $form_state) {
  // We may have multiple dependency info arrays from more than one copies
  // of the views_dependent_filters_handler_filter_dependent handler.
  foreach ($form_state['dependent_exposed_filters'] as $dependency_info) {
    // Build up the CTools #dependency item to put onto each dependent element.
    $form_dependency = array();
    foreach ($dependency_info['controllers'] as $filter_id => $controller_values) {
      // Regular form.
      $form_dependency['edit-' . $filter_id] = $controller_values;
      // better_exposed_filters form.
      foreach ($controller_values as $value) {
        $value = strtr(drupal_strtolower($value), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
        $key = 'edit-' . $filter_id . '-' . $value;
        $form_dependency[$key] = array(TRUE);
      }
    }

    // Set the dependency on each form element as required.
    foreach ($dependency_info['dependents'] as $dependent) {
			if(isset($form_state['groups'])){
				foreach ($form_state['groups'] as $g_key => $g_value) {
					if(isset($form['filters'][$g_key][$dependent])){
						dsm($form['filters'][$g_key][$dependent], '$form["filters"][$g_key][$dependent]');
			      $form['filters'][$g_key][$dependent]['#process'][] = 'ctools_dependent_process';
			      if (!isset($form['filters'][$g_key][$dependent]['#dependency'])) {
			        $form['filters'][$g_key][$dependent]['#dependency'] = array();
			      }
			      $form['filters'][$g_key][$dependent]['#dependency'] += $form_dependency;
						break;
					}
				}
			}else{
				dsm($form[$dependent], '$form[$dependent]');
	      $form[$dependent]['#process'][] = 'ctools_dependent_process';
	      if (!isset($form[$dependent]['#dependency'])) {
	        $form[$dependent]['#dependency'] = array();
	      }
	      $form[$dependent]['#dependency'] += $form_dependency;
			}
    }
  }

  return $form;
}
