<?php

/**
 *
 * Implements hook_form_FORM_ID_alter().
 *
 * The field_ui_field_edit_form is used for customizing the settings of
 * a field attached to an entity.
 */
function tripal_fields_layout_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // For entity fields added by Tripal Entities we don't want the
  // the end-user to change the cardinality and the required fields
  // such that record can't be saved in Chado.
  // TODO: this shouldn't be hardcoded here.  These settings
  // should be part of the field and handled by the tripal_entity module.
  if (in_array($form['#instance']['entity_type'], $dbs)) {
    $form['field']['cardinality']['#access'] = FALSE;
    $form['instance']['required']['#access'] = FALSE;
  }

  // TODO: don't the the maximum length be larger than the field size.
}
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * The field_ui_display_overview_form is used for formatting the display
 * or layout of fields attached to an entity.
 */
function tripal_fields_layout_form_field_ui_display_overview_form_alter(&$form, &$form_state, $form_id) {

  drupal_add_css(drupal_get_path('module','tripal_fields_layout') . '/theme/css/tripal_fields_layout_panels.css');

  $entity_type = $form['#entity_type'];
  $bundle_name = $form['#bundle'];

  // Get the bundle record.
  $bundle = db_select('tripal_bundle', 'tb')
    ->fields('tb')
    ->condition('name', $bundle_name)
    ->execute()
    ->fetchObject();

  if (module_exists('ds')) {
    drupal_set_message('Tripal is not compatible with the Display Suite (ds)
        module. If you would like to use Tripal-style panels for the layout
        of your pages please disable the Display Suite module. If you
        prefer to use the Display Suite module then disable the Tripal
        Fields Layout (tripal_fields_layout) module.', 'warning');
  }

  // Add a vertical tab fieldset at the bottom of the
  $form['overview_vert_tabs'] = array(
    '#type' => 'vertical_tabs'
  );
  $form['modes']['#group'] = 'overview_vert_tabs';
  $form['modes']['#weight'] = 1000;
  $form['te_add_panels'] = array(
    '#type' => 'fieldset',
    '#title' => 'Add a Panel',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'overview_vert_tabs'
  );

  // Make sure our default panels are in the database.
  _tripal_fields_layout_check_default_field_panels($bundle);

  // Add a Panel
  tripal_fields_layout_form_field_ui_display_overview_form_panel_add($form, $form_state);

  // Arrange Panels
  tripal_fields_layout_form_field_ui_display_overview_form_panel_arrange($form, $form_state, $bundle);

  // Configure Panels
  tripal_fields_layout_form_field_ui_display_overview_form_panel_configure($form, $form_state, $bundle);

  // Now add each panel as a region.
  $form['fields']['#regions'] = array();
  $panels = db_select('tripal_panels', 'tp')
    ->fields('tp')
    ->condition('bundle_id', $bundle->id)
    ->orderBy('weight', 'ASC')
    ->orderBy('label', 'ASC')
    ->execute();
  $panel_options = array();
  while ($panel = $panels->fetchObject()) {
    $settings = unserialize($panel->settings);
    $form['fields']['#regions'][$panel->name] = array(
      'title' => t($panel->label),
      'message' => t($settings['message']),
    );
    $panel_options[$panel->name] = $panel->label;
  }

  // Set the table headers to add a new 'region' column.
  $form['fields']['#header'] = array(
    t('Field'),
    t('Weight'),
    t('Parent'),
    t('Label'),
    array('data' => t('Format'), 'colspan' => 3),
    t('Region')
  );

  // Change the region callback for each field to place each field in the
  // proper "panel" region. Also, set the default region to be the base region.
  $fields = $form['fields'];
  $default_panel = 'te_base';

  foreach (element_children($fields) as $field_name) {
    $field_instance = field_info_instance($entity_type, $field_name, $bundle_name);
    $panel_id = db_select('tripal_panel_fields', 'tpf')
      ->fields('tpf', array('panel_id'))
      ->condition('field_id', $field_instance['id'])
      ->execute()
      ->fetchField();
    if ($panel_id) {
      $default_panel = db_select('tripal_panels', 'tp')
      ->fields('tp', array('name'))
      ->condition('panel_id', $panel_id)
      ->execute()
      ->fetchField();
    }
    $form['fields'][$field_name]['#region_callback'] = 'tripal_fields_layout_field_ui_row_region';
    $form['fields'][$field_name]['region'] = array(
      '#type' => 'select',
      '#options' => $panel_options,
      '#default_value' => $default_panel,
      '#attributes' => array(
        'class' => array('te-field-region'),
      )
    );
    $form['fields'][$field_name]['#field_instance_id'] = array(
      '#type' => 'value',
      '#value' => $field_instance['id']
    );
  }

  // Add validate and submit handlers. Rearrange the submit callbacks
  // so ours is first.
  $form['#validate'][] = 'tripal_fields_layout_field_ui_validate';
  $submit = $form['#submit'];
  $form['#submit'] = array('tripal_fields_layout_field_ui_submit');
  $form['#submit'] = array_merge($form['#submit'], $submit);
  //dpm($form);
}

/**
 * Add a Panel Form
 */
function tripal_fields_layout_form_field_ui_display_overview_form_panel_add (&$form, &$form_state) {
  $form_state['input']['panel_label'] = key_exists('panel_label', $form_state['input']) ? $form_state['values']['panel_label'] : NULL;
  $form['te_add_panels']['instructions'] = array(
    '#type' => 'item',
    '#markup' => t('You may add as many panels to your page layout as
        desired. Panels can be used to organize fields into categories....')
  );
  $form['te_add_panels']['panel_name'] = array(
    '#type' => 'hidden',
    '#title' => 'Panel Name',
    '#description' => t('The name is automatically generated for a label. it
        contains alphanumeric values and underscores and does not begin with
        a number.')
  );
  $form['te_add_panels']['panel_label'] = array(
    '#type' => 'textfield',
    '#title' => 'Panel Label',
    '#default_value' => '',
    '#description' => t('Please provide a human readable label for this
        panel. This is the name that will appear to site visitors.')
  );
  $form['te_add_panels']['add_button'] = array(
    '#type' => 'submit',
    '#value' => 'Add Panel',
    '#name' => 'add-panel-submit'
  );
}

/**
 * Arrange Panels Form
 */
function tripal_fields_layout_form_field_ui_display_overview_form_panel_arrange (&$form, &$form_state, $bundle) {
  $form['te_arrange_panels'] = array(
    '#type' => 'fieldset',
    '#title' => 'Arrange Panels',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'overview_vert_tabs'
  );
  $form['te_arrange_panels']['instructions'] = array(
    '#type' => 'item',
    '#markup' => t('Drag and drop the panel to change its order.')
  );
  $form['te_arrange_panels']['panel_items']['#tree'] = TRUE;
  // Get available panels
  $result = db_select('tripal_panels', 'tp')
  ->fields('tp', array('panel_id', 'name', 'label', 'weight'))
  ->condition('name', 'te_base', '<>')
  ->condition('name', 'te_disabled', '<>')
  ->condition('bundle_id', $bundle->id)
  ->orderby('weight', 'asc')
  ->execute();
  $has_panel = FALSE;
  foreach ($result as $item) {
    $form_state['input']['panel_items'][$item->panel_id]['newlabel'] = key_exists($item->panel_id, $form_state['input']) && $form_state['input'][$item->panel_id]['newlabel'] ? $form_state['values']['panel_items'][$item->panel_id]['newlabel'] : NULL;
    $form['te_arrange_panels']['panel_items'][$item->panel_id] = array(
      'label' => array(
        '#markup' => check_plain($item->label),
      ),
      'weight' => array(
        '#type' => 'weight',
        '#title' => t('Weight'),
        '#default_value' => $item->weight,
        '#delta' => 50,
        '#title_display' => 'invisible',
      ),
      'newlabel' => array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#size' => 10
      ),
      'rename' => array(
        '#type' => 'submit',
        '#value' => 'Rename',
        '#name' => "arrange-panel-rename-$item->panel_id",
      ),
      'remove' => array(
        '#type' => 'submit',
        '#value' => 'Remove',
        '#name' => "arrange-panel-remove-$item->panel_id",
      )
    );
    $has_panel = TRUE;
  }
  if ($has_panel) {
    $form['te_arrange_panels']['panel_items']['#theme_wrappers'] = array('tripal_fields_layout_form_arrange_panels');
    $form['te_arrange_panels']['save_button'] = array(
      '#type' => 'submit',
      '#value' => 'Save Panel Order',
      '#name' => 'order-panel-submit'
    );
  }
  else {
    $form['te_arrange_panels']['instructions']['#markup'] = t('You need to add some panel first.');
  }
}

/**
 * Configure Panels Form
 */
function tripal_fields_layout_form_field_ui_display_overview_form_panel_configure (&$form, &$form_state, $bundle) {
  $form['te_configure_panels'] = array(
    '#type' => 'fieldset',
    '#title' => 'Configure Panels',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'overview_vert_tabs'
  );

  // Add a dropdown for selecting panel to configure
  $form['te_configure_panels']['panel_select'] = array(
    '#type' => 'select',
    '#title' => t('Panel'),
    '#description' => t('Select a panel to change its layout. Fields can be grouped into a table if Table layout is selected.'),
    '#ajax' => array(
      'callback' => 'tripal_fields_layout_ajax_get_panel_setting_fieldset',
      'wrapper' => 'tripal-fields-layout-panel-setting',
      'effect' => 'fade'
    )
  );

  $form['te_configure_panels']['panel_items'] = array (
    '#tree' => TRUE,
    '#prefix' => '<div id="tripal-fields-layout-panel-setting">',
    '#suffix' => '</div>'
  );

  // Get available panels
  $panels = db_select('tripal_panels', 'tp')
  ->fields('tp', array('panel_id', 'name', 'label', 'weight', 'settings'))
  ->condition('name', 'te_disabled', '<>')
  ->condition('bundle_id', $bundle->id)
  ->orderby('weight', 'asc')
  ->execute();

  $has_panel = FALSE;
  $options = array(0 => 'Select a panel');
  $selected_panel = key_exists('values', $form_state) ? $form_state['values']['panel_select'] : 0;
  foreach ($panels as $panel) {
    $options[$panel->panel_id] = $panel->label;
    $has_panel = TRUE;
    if ($panel->panel_id != $selected_panel) {
      continue; // Display only the selected panel setting
    }
    $panel_settings = unserialize($panel->settings);
    $table_layout = key_exists('table_layout', $panel_settings) ? $panel_settings['table_layout'] : array();
    $form['te_configure_panels']['panel_items'][$panel->panel_id] = array(
      '#type' => 'fieldset',
      '#title' => check_plain($panel->label),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    //Add fields to each panel for changing configuration
    $fields = db_select('tripal_panel_fields', 'tpf')
    ->fields('tpf', array('field_id'))
    ->condition('panel_id', $panel->panel_id)
    ->execute();

    $has_field = FALSE;
    foreach ($fields AS $field) {
      $field_obj = db_select('field_config_instance', 'tci')
        ->fields('tci', array('field_name','data'))
        ->condition('id', $field->field_id)
        ->execute()
        ->fetchObject();
      $field_arr = unserialize($field_obj->data);
      $fname = $field_obj->field_name;
      if($fname == 'featureprop') {
        continue;
      }
      $flable = $field_arr['label'];
      $form['te_configure_panels']['panel_items'][$panel->panel_id][$fname] = array(
        '#type' => 'item',
        '#title' => $flable,
        '#weight' => $field_arr['display']['default']['weight']
      );
      $default_value = 0;
      if (in_array($fname, $table_layout)) {
        $default_value = 1;
      }
      $form['te_configure_panels']['panel_items'][$panel->panel_id][$fname]['table_group'] = array(
        '#type' => 'radios',
        '#options' => array(
          0 => 'Default',
          1 => 'Table',
        ),
        '#default_value' => $default_value,
      );
      $has_field = TRUE;
    }

    if (!$has_field) {
      $form['te_configure_panels']['panel_items'][$panel->panel_id]['no_field'] = array(
        '#markup' => 'No field in this panel.',
      );
    } else {
      $form['te_configure_panels']['panel_items'][$panel->panel_id]['#theme_wrappers'] = array('tripal_fields_layout_form_configure_panels');
    }

  }
  $form['te_configure_panels']['panel_select']['#options'] = $options;
  if ($has_panel) {
    $form['te_configure_panels']['save_button'] = array(
      '#type' => 'submit',
      '#value' => 'Save Panel Configuration',
      '#name' => 'configure-panel-submit'
    );
  }
  else {
    $form['te_configure_panels']['instructions']['#markup'] = t('You need to add some panel first.');
  }
}

/**
 * A helper function for checking if the default panels are in the database.
 */
function _tripal_fields_layout_check_default_field_panels($bundle) {
  // Make sure we have records for our default regions: te_base and te_hidden.
  // First check if the base region is in the database. If not, add it.
  $te_base = db_select('tripal_panels', 'tp')
    ->fields('tp')
    ->condition('name', 'te_base')
    ->condition('bundle_id', $bundle->id)
    ->execute()
    ->fetchObject();
  if (!$te_base) {
    $settings = array(
      'message' => 'Fields that should appear at the top of each page should be placed in the base panel. These fields are always present and help orient the user by at least indicating the necessary information to uniquely identiy the content.',
    );
    db_insert('tripal_panels')
      ->fields(array(
        'bundle_id' => $bundle->id,
        'name' => 'te_base',
        'label' => 'Base Content',
        'settings' => serialize($settings),
        'weight' => -9999999
      ))
      ->execute();
  }
  // Now add all fields to the default region if they are not assigned
  $panel_id = db_select('tripal_panels', 'tp')
    ->fields('tp', array('panel_id'))
    ->condition('name', 'te_base')
    ->condition('bundle_id', $bundle->id)
    ->execute()
    ->fetchField();
  if(property_exists($bundle, 'type')) {
    $fields = db_select('field_config_instance', 'fci')
      ->fields('fci', array('id'))
      ->condition('entity_type', $bundle->type)
      ->condition('bundle', $bundle->name)
      ->execute();
    foreach($fields AS $field) {
      $penal_field_id = db_select('tripal_panel_fields', 'tpf')
      ->fields('tpf', array('panel_field_id'))
      ->condition('field_id', $field->id)
      ->execute()
      ->fetchField();
      if (!$penal_field_id) {
        db_insert('tripal_panel_fields')
        ->fields(array(
          'panel_id' => $panel_id,
          'field_id' => $field->id
        ))
        ->execute();
      }
    }
  }
  // Next check if the hidden region is in the database. If not, add it.
  $te_base = db_select('tripal_panels', 'tp')
    ->fields('tp')
    ->condition('name', 'te_disabled')
    ->condition('bundle_id', $bundle->id)
    ->execute()
    ->fetchObject();
  if (!$te_base) {
    $settings = array(
      'message' => 'Place field here to hide them from display.',
    );
    db_insert('tripal_panels')
      ->fields(array(
        'bundle_id' => $bundle->id,
        'name' => 'te_disabled',
        'label' => 'Disabled',
        'settings' => serialize($settings),
        'weight' => 9999999
      ))
      ->execute();
  }
}

/**
 * Returns the region to which a row on the Field UI page belongs.
 *
 * @param $row
 *   The current row that is being rendered in the Field UI page.
 */
function tripal_fields_layout_field_ui_row_region($row) {
  $default_panel =  'te_base';
  $panel = '';

  $field_instance_id = $row['#field_instance_id']['#value'];

  // Get panel_id
  $panel_id = db_select('tripal_panel_fields', 'tpf')
  ->fields('tpf', array('panel_id'))
  ->condition('field_id', $field_instance_id)
  ->execute()
  ->fetchField();

  // Get panel name
  if ($panel_id) {
    $panel = db_select('tripal_panels', 'tp')
    ->fields('tp', array('name'))
    ->condition('panel_id', $panel_id)
    ->execute()
    ->fetchField();
  }

  // First get the panel
  if (!$panel) {
    $panel = $default_panel;
  }

  return $panel;

}
/**
 * Validates the field UI form to ensure proper panel assignments.
 *
 * @param $form
 * @param $form_state
 */
function tripal_fields_layout_field_ui_validate(&$form, &$form_state) {

}
/**
 * Responds to a submit from the field UI form for saving panel assignments.
 *
 * @param $form
 * @param $form_state
 */
function tripal_fields_layout_field_ui_submit($form, &$form_state) {
// Add a panel
  if ($form_state ['clicked_button'] ['#name'] == 'add-panel-submit') {
    tripal_fields_layout_action_add_panel($form, $form_state);
  }
  // Order panels
  else if ($form_state['clicked_button'] ['#name'] == 'order-panel-submit') {
    tripal_fields_layout_action_order_panels($form, $form_state);
  }
  // Rename a panel
  else if (preg_match('/^arrange-panel-rename-/', $form_state ['clicked_button'] ['#name'])) {
    tripal_fields_layout_action_rename_panel ($form, $form_state);
  }
  // Remove a panel
  else if (preg_match('/^arrange-panel-remove-/', $form_state ['clicked_button'] ['#name'])) {
    tripal_fields_layout_action_remove_panel ($form_state);
  }
  // Configure panels
  else if ($form_state['clicked_button'] ['#name'] == 'configure-panel-submit') {
    tripal_fields_layout_action_configure_panels($form, $form_state);
  }
  // Save fields for each panel
  else if ($form_state['clicked_button'] ['#name'] == 'op') {
    $bundle = $form_state['build_info']['args'][1];
    $fields = $form_state['values']['fields'];
    foreach($fields AS $field_name => $field_data){

      // Get field instance id
      $field_instance_id = $form['fields'][$field_name]['#field_instance_id']['#value'];

      // Get region panel_id
      $region = $field_data['region'];
      $panel_id = db_select('tripal_panels', 'tp')
        ->fields('tp', array('panel_id'))
        ->condition('name', $region)
        ->condition('bundle_id', $bundle->id)
        ->execute()
        ->fetchField();

      // Save
      $penal_field_id = db_select('tripal_panel_fields', 'tpf')
      ->fields('tpf', array('panel_field_id'))
      ->condition('field_id', $field_instance_id)
      ->execute()
      ->fetchField();

      if ($penal_field_id) {
        db_update('tripal_panel_fields')
        ->fields(array(
          'panel_id' => $panel_id,
        ))
        ->condition('panel_field_id', $penal_field_id)
        ->execute();
      }
      else {
        db_insert('tripal_panel_fields')
        ->fields(array(
          'panel_id' => $panel_id,
          'field_id' => $field_instance_id
        ))
        ->execute();
      }
    }
  }
}

/**
 * Add a new panel
 */
function tripal_fields_layout_action_add_panel (&$form, &$form_state) {
  // Check if a panel label is provided
  $label = $form_state ['values'] ['panel_label'];
  if (! $label) {
    form_set_error('panel_label', t ("Please provide a label for the new panel."));
  }
  // Generate a valide panel name using the label.
  // i.e. removing leading numbers and spaces
  $name = strtolower(preg_replace ('/^\d|\s+/', '_', $label));
  $bundle = $form_state['build_info']['args'][1];
  $name_exists = db_select('tripal_panels', 'tp')
  ->fields('tp', array('panel_id'))
  ->condition('name', $name)
  ->condition('bundle_id', $bundle->id)
  ->execute()
  ->fetchField();
  if ($name_exists) {
    form_set_error('panel_label', t('The name is used by another panel. Please use a different label.'));
  }
  else {
    $form_state ['values'] ['panel_name'] = $name;
    $bundle_id = $form_state['build_info']['args'][1]->id;
    $name      = $form_state['values']['panel_name'];
    $label     = $form_state['values']['panel_label'];
    $settings = array(
      'message' => 'Place field in this panel.',
    );
    db_insert('tripal_panels')
    ->fields(array(
      'bundle_id' => $bundle_id,
      'name' => $name,
      'label' => $label,
      'settings' => serialize($settings),
      'weight' => 0
    ))
    ->execute();
    form_set_value($form['te_add_panels']['panel_label'], '', $form_state);
  }
}

/**
 * Rename panel
 */
function tripal_fields_layout_action_rename_panel (&$form, &$form_state) {
  $button = $form_state ['triggering_element'] ['#name'];
  $panel_id = str_replace ('arrange-panel-rename-', '', $button);
  $newlabel = $form_state['values']['panel_items'][$panel_id]['newlabel'];
  if (!trim($newlabel)) {
    form_set_error ('panel_label', t ("Please provide a label to rename a panel.") );
  }
  else {
    db_update('tripal_panels')
    ->fields(array(
      'label' => $newlabel,
      'name' => strtolower(preg_replace ('/^\d|\s+/', '_', $newlabel))
    ))
    ->condition('panel_id', $panel_id)
    ->execute();
    form_set_value($form['te_arrange_panels']['panel_items'][$panel_id]['newlabel'], '', $form_state);
  }
}


/**
 * Remove panel
 */
function tripal_fields_layout_action_remove_panel (&$form_state) {
  $button = $form_state ['triggering_element'] ['#name'];
  $panel_id = str_replace ('arrange-panel-remove-', '', $button);
  db_delete('tripal_panels')
  ->condition ('panel_id', $panel_id)
  ->execute();
  db_delete('tripal_panel_fields')
  ->condition ('panel_id', $panel_id)
  ->execute();
}

/**
 * Order panel
 */
function tripal_fields_layout_action_order_panels (&$form, &$form_state) {
  $panels = $form_state['values']['panel_items'];
  foreach ($panels AS $id => $panel) {
    if (key_exists('weight', $panel)) {
      db_query('UPDATE {tripal_panels} SET weight = :weight WHERE panel_id = :id',
        array(
          ':weight' => $panel['weight'],
          ':id' => $id
        )
      );
    }
  }
}

/**
 *  Theme the Arrange Panels as a draggable table
 *
 * @param unknown $variables
 * @return unknown
 */
function theme_tripal_fields_layout_form_arrange_panels ($variables) {
  $element = $variables['element'];

  $rows = array();

  foreach (element_children($element) as $id) {

    // Add a custom class that can be identified by 'drupal_add_tabledrag'
    $element[$id]['weight']['#attributes']['class'] = array('tripal_panel-item-weight');

    $element[$id]['label']['#printed'] = FALSE;
    $element[$id]['weight']['#printed'] = FALSE;
    $element[$id]['newlabel']['#printed'] = FALSE;
    $element[$id]['rename']['#printed'] = FALSE;
    $element[$id]['remove']['#printed'] = FALSE;

    $rows[] = array(
      'data' => array(
        drupal_render($element[$id]['label']),
        drupal_render($element[$id]['weight']),
        drupal_render($element[$id]['newlabel']),
        drupal_render($element[$id]['rename']),
        drupal_render($element[$id]['remove'])
      ),
      // Add draggable to each row to support the tabledrag behaviour
      'class' => array('draggable'),
    );
  }

  // Create table header
  $header = array(t('Panel'), t('Weight'), array('data' => t('Rename'), 'colspan' => 2), t('Action'));

  // Create a unique id for drupal_add_tabledrag() to find the table object
  $table_id = 'tripal_panel-arrange_panel_table';

  // Create output
  $output = '';
  if (count($rows) > 0) {
    $output = theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array('id' => $table_id),
    ));
  }

  // Call to the drupal_add_tabledrag
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'tripal_panel-item-weight');

  return $output;
}

/**
 * Configure panels
 */
function tripal_fields_layout_action_configure_panels (&$form, &$form_state) {
  $panels = $form_state['values']['panel_items'];

  foreach ($panels AS $id => $panel) {
    $table_layout = array();
    foreach($panel AS $key => $value) {
      if (is_array($value) && key_exists('table_group', $value)) {
        if ($value['table_group'] == 1) {
          $table_layout[] = $key;
        }
      }
    }
    $panel_settings = db_select('tripal_panels', 'tp')
      ->fields('tp', array('settings'))
      ->condition('panel_id', $id)
      ->execute()
      ->fetchField();
    $new_settings = unserialize($panel_settings);
    $new_settings['table_layout'] = $table_layout;
    db_update('tripal_panels')
      ->fields(array(
        'settings' => serialize($new_settings)
      ))
      ->condition('panel_id', $id)
      ->execute();
  }
}

/**
 *  Theme the Configure Panels as a table
 *
 * @param unknown $variables
 * @return unknown
 */
function theme_tripal_fields_layout_form_configure_panels ($variables) {
  $element = $variables['element'];

  $rows = array();

  foreach (element_children($element) as $id) {

    $element[$id]['table_group']['#printed'] = FALSE;
    $rows[] = array(
      'data' => array(
        $element[$id]['#title'],
        drupal_render($element[$id]['table_group']),
      ),
    );
  }

  // Create table header
  $header = array(t('Field'), t('Layout'));

  // Create a unique id for drupal_add_tabledrag() to find the table object
  $table_id = 'tripal_panel-configure_panel_table-' . strtolower(preg_replace('/\s+/', '_', $element['#title']));
  $table_class = 'tripal_panel-configure_panel_table';

  // Create output
  $table = '';
  if (count($rows) > 0) {
    $table = theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array('id' => $table_id, 'class' => array($table_class)),
    ));
  }

  $collapsible_item = array('element' => array());
  $collapsible_item['element']['#children'] = '';
  $collapsible_item['element']['#description'] =
    '<div id="tripal_fields_layout-panel_configure-fieldset-instruction">
        Select a group to organize fields into table(s) in this panel.
     <div>'
    . $table;
  $collapsible_item['element']['#title'] = $element['#title'];
  // add 'collapsible' to the class setting to enable collapsible fieldset
  $collapsible_item['element']['#attributes']['class'] = array('tripal_fields_layout-panel_configure-fieldset');
  $output = theme('fieldset', $collapsible_item);
  return $output;
}

/**
 * Implements hook_theme().
 */
function tripal_fields_layout_theme($existing, $type, $theme, $path) {
  return array(
    'tripal_fields_layout_form_arrange_panels' => array(
      'render element' => 'element',
    ),
    'tripal_fields_layout_form_configure_panels' => array(
      'render element' => 'element',
    ),
    'tripal_fields_layout_generic' => array(
      'render element' => 'element',
      'template' => 'tripal_fields_layout_generic',
      'path' => "$path/theme/templates",
    ),
  );
}

/**
 * Implements hook_entity_view.
 */
function tripal_fields_layout_entity_view($entity, $type, $view_mode, $langcode) {
  switch ($type) {
    case 'TripalEntity':
      // Use the generic template to render the fields
      if ($view_mode == 'full') {

        $bundle = db_select('tripal_bundle', 'tb')
          ->fields('tb', array('id', 'name', 'label'))
          ->condition('name', $entity->bundle)
          ->execute()
          ->fetchObject();

        _tripal_fields_layout_check_default_field_panels($bundle);

        $results = db_select('tripal_panels', 'tp')
          ->fields('tp', array('panel_id','name', 'label', 'settings'))
          ->condition('bundle_id', $bundle->id)
          ->orderBy('tp.weight', 'ASC')
          ->execute();

        $panels = array();
        $fields = array();
        $disabled_panel_id = 0;
        foreach ($results AS $row) {
          if ($row->name == 'te_disabled') {
            $disabled_panel_id = $row->panel_id;
          }
          else {
            $panels[$row->panel_id] = $row;
            $fields[$row->panel_id] = array();
          }
        }

        // Organize fields into panels
        foreach (element_children($entity->content) as $field_name) {
          $field_instance = field_info_instance ($type, $field_name, $entity->bundle);
          // Get default panel_id
          $default_panel_id = db_select('tripal_panels', 'tp')
            ->fields('tp', array('panel_id'))
            ->condition('bundle_id', $bundle->id)
            ->condition('name', 'te_base')
            ->execute()
            ->fetchField();
          // Get panel_id for the field
          $panel_id = db_select('tripal_panel_fields', 'tpf')
            ->fields('tpf', array('panel_id'))
            ->condition('field_id', $field_instance['id'])
            ->execute()
            ->fetchField();
          $panel_id = $panel_id ? $panel_id : $default_panel_id;
          // Do not show disabled fields
          if ($panel_id != $disabled_panel_id) {
            $fields[$panel_id][$field_name] = $entity->content[$field_name];
          }
          // Unset the field
          unset ($entity->content[$field_name]);
        }
        drupal_add_css(drupal_get_path('module','tripal_fields_layout') . '/theme/css/tripal_fields_layout.css');
        $entity->content['tripal_fields_layout_generic'] = array(
          '#theme' => 'tripal_fields_layout_generic',
          '#panels' => $panels,
          '#fields' => $fields,
        );
      }

      break;
  }
}

/**
 * Implements hook_entity_view.
 */
function tripal_fields_layout_ajax_get_panel_setting_fieldset($form, &$form_state) {
  $panel_id = $form_state['values']['panel_select'];
  return  $form['te_configure_panels']['panel_items'];
}