<?php

function multipage_form_set_element_visibility(&$element, $visible, $next_page = TRUE) {
  multipage_form_restore_attributes($element);
  if (!$visible) {
    switch ($element['#type']) {
      case 'textfield':
      case 'textarea':
      case 'select':
        multipage_form_set_attribute($element, '#type', 'hidden');
        multipage_form_set_attribute($element, '#required', FALSE);
        break;

      case 'radios':
        // Radios elements cannot be hidden unless they have been processed.
        if ($next_page) {
          multipage_form_set_attribute($element, '#type', 'hidden');
          multipage_form_set_attribute($element, '#required', FALSE);
        }
        break;

      case 'radio':
      case 'checkbox':
        // We can't change these to hidden until right before the next page is rendered, otherwise
        // the value is lost sometimes.
        if ($next_page) {
          multipage_form_set_attribute($element, '#type', 'hidden');
        }
        break;

      case 'fieldset':
        multipage_form_set_attribute($element, '#type', NULL);
        break;

      case 'button':
        if ($next_page) {
          multipage_form_set_attribute($element, '#type', 'value');
        }
        break;

      case 'submit':
        if ($next_page) {
          multipage_form_set_attribute($element, '#type', 'button');
        }
        break;
    }
  }

  foreach (element_children($element) as $key) {
    multipage_form_set_element_visibility($element[$key], $visible, $next_page);
  }
}

/**
 * Set an attribute on an element array with storing the previous value which
 * may be reverted to using multipage_form_restore_attributes().
 *
 * @param $element
 *   The form element array to modify.
 * @param $key
 *   A key of the form element array.
 * @param $new_value
 *   The new value for the attribute.
 */
function multipage_form_set_attribute(&$element, $key, $new_value) {
  $element['#multipage_form_original_'. $key] = $element[$key];
  $element[$key] = $new_value;
}

/**
 * Restore any form attributes which have been set using
 * multipage_form_set_attribute().
 *
 * @param $element
 *   The form element array to restore.
 */
function multipage_form_restore_attributes(&$element) {
  foreach (array_filter(array_keys($element), create_function('$key', 'return (strpos($key, "#multipage_form_original_") === 0);')) as $key) {
    $element[str_replace('#multipage_form_original_', '', $key)] = $element[$key];
  }
}

function multipage_form_set_value(&$element, $value){
  if(!$element['#value']){
    $element['#value'] = $value;
  }
}