<?php

/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		QTG Event function handling
 *
 *    Update test statuses, add notes to test items
 *
*/

require_once('sabreQMS.qtglist.inc');




/*
 *	qtg_event_form()
 *
 *  Display the QTG Event Details, allowing users to edit from here if perms allow
 *
 *  If no edit perms, becomes display only
 */


function qtg_event_form($form, $form_state, $qtg_event_id = 0, $bEdit = False) {


  //$bAllowEdit = user_access('edit qtg event');
  $bAdmin = user_access('administer sabreQMS');

  $ckeditor_activated = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);
    // if not set, default to ON



  // qtg_event_id is required
  if ( !$qtg_event_id ) {
    drupal_set_message( t('QTG Event Not Found!  Invalid ID.'), 'warning');
    drupal_goto('search/qtg');
    return $form;
  }

  $event = _get_qtg_event($qtg_event_id);

  if ( $event == Null ) {
    drupal_set_message( t('QTG Event Not Found!'), 'warning');
    drupal_goto('search/qtg');
    return $form;
  }

  $goto_url = current_path();


  $event_tests = _get_qtg_event_tests($qtg_event_id);



  if ( $event->date_closed && !$bAdmin ) {

    $bEdit = False;
  }


  //------------ BUILD FORM ------------------


  $form['#after_build'][] = 'qtg_event_form_after_build';

  // storage field for the qtg_event_id (edit) -- hidden
  $form['qtg_event_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $qtg_event_id,   // for ADD mode, this is 0
    '#attributes' => array('id' => 'qms-qtg-event-id',
                           'class' => array('qms-hidden-field')),
  );

  $form['qtg_no_display'] = array(
    '#type' => 'item',
    '#markup' => '<div class="qms-report-no">' . $event->qtg_no . '</div>',
    '#suffix' => _st_format_record_timestamp_table($event),
  );

  //-----------------------------------------

  global $simulator_list;

  $form['qtg_event_table_begin'] = array(
    '#markup' => '<table class="qms-plain-table"><tr>',
  );

  $form['plan_group'] = array(
    '#type' => 'item',
    '#title' => t('Plan & Group'),
    '#markup' => $event->plan_name . ', ' . $event->group_name,
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );

  $form['simulator'] = array(
    '#type' => 'item',
    '#title' => t('Simulator'),
    '#markup' => $simulator_list->getName($event->simulator_id),
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );

  $form['date_closed'] = array(
    '#type' => 'item',
    '#title' => t('Date Closed'),
    '#markup' => ($event->date_closed ?
                    _st_format_date($event->date_closed, 'short') : '---' ),
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );

  $form['qtg_event_table_end'] = array(
    '#markup' => '</tr></table>',
  );

  $table_rows = array();
  $table_header = array(
      array( 'data' => t('Test'),
             //'field' => 'test_code',
             //'sort' => 'asc',
             'class' => array('qms-tbl-qtg-event-test-code'),
          ),
      array( 'data' => t('Description & Status History'),
             //'field' => 'test_desc',
             //'sort' => 'asc',
             'class' => array('qms-tbl-qtg-event-test-desc'),
          ),
      array( 'data' => t('Engine'),
             //'field' => 'engine_desc',
             //'sort' => 'asc',
             'class' => array('qms-tbl-qtg-event-engine'),
          ),
      array( 'data' => t('Status'),
             //'field' => 'engine_desc',
             //'sort' => 'asc',
             'class' => array('qms-tbl-qtg-event-test-status'),
          ),
    );
  if ( $bEdit ) {
    $table_header[] = array(
      'data' => t('Admin'),
      'class' => array('qms-tbl-qtg-event-admin'),
    );
  }


  if ( count($event_tests) ) {
    foreach($event_tests as $et) {

      $status_history = _get_qtg_test_status_history($qtg_event_id,
                                                     $et->qtg_test_id);

      $dr_links = _get_qtg_discrepancy_links($qtg_event_id, $et->qtg_test_id,
                                             current_path());
      $dr_text = '';

      if ( count($dr_links) ) {
        $dr_text = implode('<br />', $dr_links);
      }

      $row_data = array(
        $et->test_code,
        $et->test_desc,
        $et->engine_code,
        '<span class="qms-qtg-test-current-status">' .
          $et->test_status_desc .
        '</span>' .
          (count($dr_links) ? '<br />' . $dr_text : ''),
      );
      if ( $bEdit ) {

        $run_link = '';
        if ( isset($status_history[0]->test_status_code) &&
            (QMS_QTG_STATUS_NOT_RUN == $status_history[0]->test_status_code) ) {
          $run_link = l( t('Run'),
                           'qtg/test/status/run/' .
                            $qtg_event_id . '/' . $et->qtg_test_id,
                            array('attributes' =>
                              array('class' => array('qms-run-test-link'))));
        }
        $edit_link = _get_results_table_options(
                      'qtg/test/status',
                      $qtg_event_id . '/' . $et->qtg_test_id,
                      $bEdit, $goto_url);


        $row_data[] = array(
          'data' => $edit_link . $run_link,
          'class' => array('qms-tbl-qtg-event-admin'),
        );
      }

      $table_rows[] = array('data' => $row_data, 'class' => array('qms-qtg-test-row'));

      // there should always be at least 1 status history for each test
      if ( count($status_history) ) {
        foreach($status_history as $sh) {

          $nt = ($ckeditor_activated ?
                  _st_convert_symbols($sh->note_text) :
                  nl2br(_st_convert_symbols($sh->note_text)));

          $class = '';
          if ( strlen($nt) ) {
            $class = 'qms-qtg-test-status-date';
          }

          $row_data = array(
            '&nbsp;',  // nothing in the test_code col
            '<div class="' . $class . '">' .
              ( $sh->created_date ?
                t('Created') . ': ' .
                  _st_format_date($sh->created_date, 'short'):'') . ' ' .
              ( strlen($sh->created_user_name) ?
                      t('by') . ' ' . $sh->created_user_name : '') .
              (strlen($sh->updated_user_name) ?
                ('<br />' .
                  t('Updated') . ': ' .
                      _st_format_date($sh->updated_date, 'short') . ' ' .
                  t('by') . ' ' . $sh->updated_user_name) : '') .
            '</div>' . $nt,
            '&nbsp;',
            $sh->test_status_desc,
          );
          if ( $bEdit ) {
            $admin_edit_link = '';
            $admin_delete_link = '';
            if ( $bAdmin &&
                ($sh->test_status_code != QMS_QTG_STATUS_NOT_RUN) ) {
              $admin_edit_link = _get_results_table_options(
                                        'qtg/test/history',
                                        $sh->qtg_test_status_history_id,
                                        $bEdit, $goto_url);

              $admin_delete_link = l( t('Delete'),
                  "qtg/test/history/delete/" . $sh->qtg_test_status_history_id, 	         			  array('attributes' =>
                            array('class' => array('qms-qtg-delete-link'),
                   'query' => array('destination' => $goto_url)) ));
            }

            $row_data[] = array( 'data' => $admin_edit_link .
                                           $admin_delete_link,
                                 'class' => array('qms-results-admin'));
          }

          $table_rows[] = array('data' => $row_data);
        }
      }
    }
  }

  $qtg_tests_table = theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));

  $form['qtg_tests_table'] = array(
    '#markup' => $qtg_tests_table,
  );


    //-----------------------------------------

  $form['actions'] = array( '#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Done'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
  );

  if ( $bAdmin ) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#name' => 'delete',
      '#attributes' => array('class' => array('qms-btn-delete', 'qms-btn-extra')),
    );
  }

  $form['actions']['print'] = array(
    '#type' => 'button',
    '#value' => t('Print'),
    '#name' => 'print',
    '#attributes' => array('class' => array('qms-print', 'qms-btn-extra'),
                           'onclick' => 'window.print(); return false;'),
  );


  $next_report_link = '';
  $prev_report_link = '';


  // determine the next or previous in the search results list of the current page
  $results_cache_name = _get_qms_cache_name(QMS_QTG_SEARCH_RESULTS);
  $results_cache = cache_get($results_cache_name);

  $dest_url = ( $bEdit ? 'qtg/event/edit/' : 'qtg/event/view/');

  if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
    $search_results = $results_cache->data;
    $results_table_rows = $search_results->getResults();
    $prev_id = _st_array_key_relative($results_table_rows, $qtg_event_id, -1);
    if ( $prev_id !== False ) {
      $form['view_previous_link'] = array(
        '#type' => 'textfield',
        '#default_value' => $dest_url . $prev_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
    }
    $next_id = _st_array_key_relative($results_table_rows, $qtg_event_id, 1);
    if ( $next_id !== False ) {
      $form['view_next_link'] = array(
        '#type' => 'textfield',
        '#default_value' => $dest_url . $next_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
    }
  }


  if ( isset($form['view_previous_link']) ) {
    $form['actions']['view_previous'] = array(
      '#type' => 'submit',
      '#value' => t('View Previous'),
      '#name' => 'view_previous',
      '#attributes' => array('class' => array('qms-btn-previous', 'qms-btn-extra'),
                              'query' => array('destination' =>
                                                  $dest_url . $qtg_event_id)),
    );
  }

  if ( isset($form['view_next_link']) ) {
    $form['actions']['view_next'] = array(
      '#type' => 'submit',
      '#value' => t('View Next'),
      '#name' => 'view_next',
      '#attributes' => array('class' => array('qms-btn-next', 'qms-btn-extra'),
                              'query' => array('destination' =>
                                                  $dest_url . $qtg_event_id)),

    );
  }

  $qtg_status_list = new QTGStatusList();

  $form['strings'] = array(
    '#markup' => '<div id="qms-strings" class="qms-hidden">' .
                    $qtg_status_list->getName(QMS_QTG_STATUS_RAN) .
                 '</div>',
  );


  return $form;
}


/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it.
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/


function qtg_event_form_after_build($form, &$form_state) {

  drupal_add_library('system','ui.dialog');
  drupal_add_js(drupal_get_path('module', 'sabreTools') .
                  '/js/sabreTools.lib.js');
  drupal_add_js(drupal_get_path('module', 'sabreQMS') .
                  '/js/sabreQMS.qtgevent.js');
  return $form;
}


/*
 *	qtg_event_form_submit()
 *
 *  Overloads hook_form_submit()
 *  Final submit action for the discrepancy_form
 *  Stores input data to the db
 */

function qtg_event_form_submit($form, $form_state) {

  //---------------- Button Handlers --------------------

  $button_clicked = $form_state['triggering_element']['#name'];

  if ( isset($form['actions']['delete']['#name']) &&
       ($form['actions']['delete']['#name'] == $button_clicked) ){

    $qtg_event_id = isset($form_state['values']['qtg_event_id']) ?
                        (int) $form_state['values']['qtg_event_id'] : 0;

    if ( !$qtg_event_id && isset($form['qtg_event_id']['#default_value'])) {
      $qtg_event_id = $form['qtg_event_id']['#default_value'];
    }
    if ( $qtg_event_id ) {
      $_GET['destination'] = 'qtg/event/delete/' . $qtg_event_id .
                            '?destination=qtg/event/edit/' . $qtg_event_id;
    }
  }
  else if ( isset($form['actions']['submit']['#name']) &&
            ($form['actions']['submit']['#name'] == $button_clicked) ){

    $destination = drupal_get_destination();
    $goto_url = $destination['destination'];

    if( !strlen($goto_url) || ($goto_url == current_path()) ) {
      $goto_url = 'search/qtg';
    }
    drupal_goto($goto_url);

  }
  else if ( isset($form['actions']['view_previous']['#name']) &&
            ($form['actions']['view_previous']['#name'] == $button_clicked)) {

    $prev_link = isset($form_state['values']['view_previous_link']) ?
                  $form_state['values']['view_previous_link'] : '';
    if ( !strlen($prev_link) ) {
      $prev_link = isset($form['view_previous_link']) ?
                    $form['view_previous_link']['#default_value'] : '';
    }

    if ( strlen($prev_link) ) {
      $_GET['destination'] = $prev_link . '?destination=search/qtg';
    }
  }
  else if ( isset($form['actions']['view_next']['#name']) &&
            ($form['actions']['view_next']['#name'] == $button_clicked)) {

    $next_link = isset($form_state['values']['view_next_link']) ?
                  $form_state['values']['view_next_link'] : '';
    if ( !strlen($next_link) ) {
      $next_link = isset($form['view_next_link']) ?
                    $form['view_next_link']['#default_value'] : '';
    }
    if ( strlen($next_link) ) {
      $_GET['destination'] = $next_link . '?destination=search/qtg';
    }
  }
  else if ( $form['actions']['submit']['#name'] != $button_clicked ) {
    // if not delete & not done, then make sure its a submit click, otherwise, return
    return;
  }


}



/*
 *	qtg_event_delete_confirm()
 *
 *  Delete the qtg_event -- ADMIN ONLY
 */

function qtg_event_delete_confirm($form, $form_state, $qtg_event_id = 0) {
  try{

    $bAdmin = user_access('administer sabreQMS');

    if ( !$bAdmin ) {
      drupal_set_message(t('Administrator permissions required ' .
                           'to delete a QTG Event report.'));
      drupal_goto('qtg/event/edit/' . $qtg_event_id);
      return $form;
    }

    // get the qtg_no
    $event = array();
    $result = db_query("SELECT qtg_no FROM {qms_qtg_events}
                        WHERE qtg_event_id = :id",
                      array(':id' => $qtg_event_id));
    if ( $result->rowCount() ) {
      $event = $result->fetchObject();
    }

    // store the discrepancy_id and dr_no in hidden fields for the next step
    // storage field for the discrepancy_id (edit) -- hidden
    $form['qtg_event_id'] = array(
      '#type' => 'textfield',
      '#default_value' => $qtg_event_id,
      '#attributes' => array('id' => 'qms-qtg-event-id',
                              'class' => array('qms-hidden-field')),
    );
    // storage field for the trouble_call_id (edit) -- hidden
    $form['qtg_no'] = array(
      '#type' => 'textfield',
      '#default_value' => $event->qtg_no,
      '#attributes' => array('id' => 'qms-qtg-no',
                              'class' => array('qms-hidden-field')),
    );

    $title = t('Delete QTG Test Event Report') . '?';
    $question = t('Are you sure you want to delete?') .
                '<h2>' . $event->qtg_no . '</h2><br />' .
                t('This action cannot be undone.');
    $goto_if_canceled = 'qtg/event/edit/' . $qtg_event_id;
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    // force this here to avoid a problem with routing if cancelled
    //$_GET['destination'] = 'search/qtg';

    return confirm_form($form, $title,	$goto_if_canceled, $question,
                        $yes_btn, $no_btn);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_event_delete_confirm()' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}

/*
 *	qtg_event_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the qtg_event -- ADMIN ONLY
 */
function qtg_event_delete_confirm_submit($form, $form_state) {

  try {
    if ($form_state['values']['confirm']) {
      $qtg_event_id = $form_state['values'] ['qtg_event_id'];
      $qtg_no = $form_state['values']['qtg_no'];


      db_delete('qms_qtg_event_tests')
            ->condition('qtg_event_id', $qtg_event_id)
            ->execute();

      db_delete('qms_qtg_test_status_history')
            ->condition('qtg_event_id', $qtg_event_id)
            ->execute();

      db_update('qms_discrepancy_log')
            ->fields(array(
                      'qtg_event_id' => 0,
                      'qtg_test_id' => 0
                    ))
            ->condition('qtg_event_id', $qtg_event_id)
            ->execute();

      $num_rows = db_delete('qms_qtg_events')
            ->condition('qtg_event_id', $qtg_event_id)
            ->execute();

      $msg = ( ($num_rows == 1) ?
                $qtg_no . ' has been deleted.' :
                'Error occurred deleting' . $qtg_no . '.');
      drupal_set_message($msg, 'status');

      // remove the troublecall search results, but leave the search key so that the list gets refreshed
      // leave the search key cache intact

      // Reload the cache

      // determine cache name
      $search = (object) Null;
      $key_cache_name = _get_qms_cache_name(QMS_QTG_SEARCH_KEY);

      $key_cache = cache_get($key_cache_name);
      if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
        $search = $key_cache->data;

        // refresh the cached search results to reflect any changes
        _get_qtg_search_results($search);
      }

    }
    $_GET['destination'] = 'search/qtg';
    drupal_goto('search/qtg');
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_event_delete_confirm_submit()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}


/*
 *    qtg_test_status_form()
 *
 *    Update the status of a particular test for a QTG Test Event
 *
 */
function qtg_test_status_form($form, $form_state,
                              $qtg_event_id = 0, $qtg_test_id = 0,
                              $qtg_test_status_history_id = 0,
                              $bEdit = False) {

  $sh_entry = (object) Null;

  // special circumstance
  // Admins allowed to edit previous history entries.
  if ( $qtg_test_status_history_id ) {
    $sh_entry = _get_qtg_test_status_history_entry(
                                    $qtg_test_status_history_id);

    $qtg_event_id = $sh_entry->qtg_event_id;
    $qtg_test_id = $sh_entry->qtg_test_id;
  }

  $destination = drupal_get_destination();
  $goto_url = $destination['destination'];


  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = 'qtg/event/edit/' . $qtg_event_id;
  }

  $bAllowEdit = user_access('edit qtg event');
  if ( !$bAllowEdit ) {
    $bEdit = False;
  }


  if ( !$qtg_event_id || !$qtg_test_id ) {
    drupal_set_message( t('QTG Test Not Found!  Invalid IDs.'), 'warning');
    drupal_goto($goto_url);
    return $form;
  }

  $event = _get_qtg_event($qtg_event_id);

  if ( Null == $event ) {
    drupal_set_message( t('QTG Event Not Found!'), 'warning');
    drupal_goto($goto_url);
    return $form;
  }

  $test = _get_qtg_test($qtg_test_id);
  if ( Null == $test ) {
    drupal_set_message( t('QTG Test Not Found!'), 'warning');
    drupal_goto($goto_url);
    return $form;
  }

  $status_history = _get_qtg_test_status_history($qtg_event_id, $qtg_test_id);

  //$n_status = count($status_history);
  $curr_status = '';
  if ( isset($status_history[0]) ) {
    $curr_status = '<b>' .
                      $status_history[0]->test_status_desc .
                   '</b>';

    $form['current_status_code'] = array(
      '#type' => 'textfield',
      '#default_value' => $status_history[0]->test_status_code,
      '#attributes' => array('id' => 'qms-current-status-code',
                             'class' => array('qms-hidden-field')),
    );
  }

  $ckeditor_activated = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);

  //------------------ Build Form -----------------------

  $form['#after_build'][] = 'qtg_test_status_form_after_build';


  // storage field for the qtg_event_id (edit) -- hidden
  $form['qtg_event_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $qtg_event_id,   // for ADD mode, this is 0
    '#attributes' => array('id' => 'qms-qtg-event-id',
                           'class' => array('qms-hidden-field')),
  );
  // storage field for the qtg_event_id (edit) -- hidden
  $form['qtg_test_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $qtg_test_id,   // for ADD mode, this is 0
    '#attributes' => array('id' => 'qms-qtg-test-id',
                           'class' => array('qms-hidden-field')),
  );

  $form['qtg_no_display'] = array(
    '#type' => 'item',
    '#markup' => '<div class="qms-report-no">' . $event->qtg_no . '</div>',
    '#suffix' => _st_format_record_timestamp_table($event),
  );


  $form['event_table_begin'] = array(
    '#markup' => '<table class="qms-plain-table"><tr>',
  );

  $form['plan_group'] = array(
    '#type' => 'item',
    '#title' => t('Test Plan & Group'),
    '#markup' => $event->plan_name . ' - ' . $event->group_name,
    '#prefix' => '<td style="width:50%">',
    '#suffix' => '</td>',
  );

  global $simulator_list;

  $form['simulator'] = array(
    '#type' => 'item',
    '#title' => t('Simulator'),
    '#markup' => $simulator_list->getName($event->simulator_id),
    '#prefix' => '<td style="width:50%>',
    '#suffix' => '</td>',
  );


  $form['event_table_end'] = array(
    '#markup' => '</tr></table>',
  );


  $form['test_table_begin'] = array(
    '#markup' => '<table class="qms-plain-table"><tr>',
  );

  $form['test_code'] = array(
    '#type' => 'item',
    '#title' => t('Test Code'),
    '#markup' => $test->test_code,
    '#prefix' => '<td style="width:10%">',
    '#suffix' => '</td>',
  );

  $form['test_desc'] = array(
    '#type' => 'item',
    '#title' => t('Description'),
    '#markup' => $test->test_desc,
    '#prefix' => '<td style="width:40%">',
    '#suffix' => '</td>',
  );

  $form['engine'] = array(
    '#type' => 'item',
    '#title' => t('Engine'),
    '#markup' => $test->engine_code,
    '#prefix' => '<td style="width:25%">',
    '#suffix' => '</td>',
  );

  $dr_links = _get_qtg_discrepancy_links($qtg_event_id, $qtg_test_id,
                                             current_path());
  $dr_text = '';

  if ( count($dr_links) ) {
    $dr_text = implode('<br />', $dr_links);
  }

  $form['current_status'] = array(
    '#type' => 'item',
    '#title' => t('Current Status'),
    '#markup' => $curr_status . (count($dr_links) ? '<br />' . $dr_text : ''),
    '#prefix' => '<td style="width:25%">',
    '#suffix' => '</td>',
  );
  $form['test_table_end'] = array(
    '#markup' => '</tr></table>',
  );



  $table_rows = array();
  $table_header = array(
      array( 'data' => t('Status History'),
             'class' => array('qms-tbl-qtg-status-note'),
          ),
      array( 'data' => t('Status'),
             'class' => array('qms-tbl-qtg-status-desc'),
          ),
    );

  // there should always be at least 1 status history for each test
  foreach($status_history as $sh) {

    $nt = ($ckeditor_activated ?
            _st_convert_symbols($sh->note_text) :
            nl2br(_st_convert_symbols($sh->note_text)));

    $class = '';
    if ( strlen($nt) ) {
      $class = 'qms-qtg-test-status-date';
    }
    $highlight = '';
    if ( $qtg_test_status_history_id == $sh->qtg_test_status_history_id ) {
      $highlight = 'qms-qtg-history-current-row';
    }

    $row_data = array(
      '<div class="' . $class . '">' .
        t('Created') . ': ' . _st_format_date($sh->created_date, 'short') . ' ' .
        ( strlen($sh->created_user_name) ?
                t('by') . ' ' . $sh->created_user_name : '') . '<br />' .
        t('Updated') . ': ' . ( strlen($sh->updated_user_name) ?
                (_st_format_date($sh->updated_date, 'short') . ' ' .
                t('by') . ' ' . $sh->updated_user_name) : '') .
      '</div>' . $nt,
      $sh->test_status_desc,
    );
    $table_rows[] = array('data' => $row_data, 'class' => array($highlight));
  }

  $history_table = theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));

  $form['qtg_tests_table'] = array(
    '#markup' => $history_table,
  );

  if ( $bEdit ) {

    $form['form_div_begin'] = array(
      '#markup' => '<div class="qms-form-div">',
    );

    $status_list = _get_qtg_test_statuses();

    $form['status'] = array(
      '#type' => 'select',
      '#title' => (($qtg_test_status_history_id > 0) ?
                             t('Edit Status') :  t('New Status') ),
      '#options' => $status_list,
      '#default_value' => (($qtg_test_status_history_id > 0) ?
                            $sh_entry->test_status_code : 0 ),
      '#required' => True,
      '#attributes' => array('class' => array('qms-select'),
                             'id' => 'qms-status-select'),
      '#suffix' => '<div class="qms-desc">' .
                      t('Setting a "FAIL" status will generate
                         a new Discrepancy Report for this test.') . '<br>' .
                      t('The Notes field will be included in new report.') .
                    '</div>',
    );


    //-----------------------------------------

    $text_settings = array(
      'name' => 'note_text',
      'title' => t('Notes'),
      'text' =>	( ($qtg_test_status_history_id > 0) ?
                  $sh_entry->note_text : ''),
      'required' => True,
    );

    _st_add_text_editor($form, $text_settings);


    $form['form_div_end'] = array(
      '#markup' => '</div>',
    );
  }

  //------------------------- Action Buttons ---------------------
  $form['actions'] = array( '#type' => 'actions');

  if ( $bEdit ) {
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#name' => 'submit',
      '#attributes' => array('class' => array('qms-btn-submit')),
    );
  }

  $form['actions']['done'] = array(
    '#type' => 'button',
    '#value' => t('Done'),
    '#name' => 'done',
    '#attributes' => array('class' => array('qms-done'),
                           'onclick' => 'window.location="' .
                                            url($goto_url) .
                                         '"; return false;'),
  );

  $form['actions']['print'] = array(
      '#type' => 'button',
      '#value' => t('Print'),
      '#name' => 'print',
      '#attributes' => array('class' => array('qms-print', 'qms-btn-extra'),
                             'onclick' => 'window.print(); return false;'),
    );

  if ( $bEdit ) {
    // if in 'Edit' mode, the Done button is an extra button,
    // add the extra class so that button spacing is correct
    $form['actions']['done']['#attributes']['class'][] = 'qms-btn-extra';
  }


  //------------ hidden ---------------
  $form['report_changed'] = array(
    '#type' => 'textfield',
    '#default_value' => 0,
    '#attributes' => array('id' => 'qms-report-changed',
                           'class' => array('qms-hidden')),
  );
  $form['simulator_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $event->simulator_id,
    '#attributes' => array('id' => 'qms-simulatior-id',
                           'class' => array('qms-hidden')),
  );
  $form['date_closed'] = array(
    '#type' => 'textfield',
    '#default_value' => $event->date_closed,
    '#attributes' => array('id' => 'qms-date-closed',
                           'class' => array('qms-hidden')),
  );

  $form['qtg_test_status_history_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $qtg_test_status_history_id,
    '#attributes' => array('id' => 'qms-qtg-test-status-history-id',
                           'class' => array('qms-hidden')),
  );

  // if test status updated to fail, the test notes are prepended with
  // this test information to create the new DR
  /*
  $form['test_prepend'] = array(
    '#type' => 'textfield',
    '#default_value' => '<p>' . $test->test_code . '<br />' .
                         $test->test_desc . '<br />' .
                         $test->engine_code . '<br />' .
                         t('TEST FAILED') . '<br /></p>',
    '#attributes' => array('id' => 'qms-qtg-test-prepend',
                           'class' => array('qms-hidden')),
  );
   *
   */
  $form['test_prepend'] = array(
    '#type' => 'textarea',
    '#default_value' => '<p>' . $test->test_code . '<br />' .
                         $test->test_desc . '<br />' .
                         $test->engine_code . '<br />' .
                         t('TEST FAILED') . '<br /></p>',
    '#attributes' => array('id' => 'qms-qtg-test-prepend',
                           'class' => array('qms-hidden')),
    '#prefix' => '<div class="qms-hidden">',
    '#suffix' => '</div>',
  );

  $form['popup_dialog'] = array(
    '#type' => 'markup',
    '#markup' => '<div id="qms-message-box"></div>',
  );

  return $form;
}


/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it.
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/*
 * qtg_test_status_form_after_build()
 *
 */
function qtg_test_status_form_after_build($form, &$form_state) {
  $sabreTools = drupal_get_path('module', 'sabreTools');
  drupal_add_js($sabreTools . '/js/sabreTools.lib.js');
  drupal_add_js($sabreTools . '/js/sabreTools.ckeditor.js');
  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.qtgteststatus.js');

  // WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
  if ( isset( $form['ckeditor_module_path'])  ) {
    global $base_url;
    drupal_add_js( $base_url . QMS_CKEDITOR_PATH_CONFIG);
    // need to specify preprocess == false otherwise 'Aggregate Javascript' setting in drupal
    // causes ckeditor not to load properly
    // adding scope to footer speeds up the page load
    drupal_add_js( $base_url . QMS_CKEDITOR_LIB, array('type' => 'file', 'scope' => 'footer', 'preprocess' => FALSE));
  }

  return $form;
}


/*
 *  qtg_test_status_form_validate()
 *
 */
function qtg_test_status_form_validate($form, $form_state) {

  $status = (int)$form_state['values']['status'];

  if ( !$status ) {
    form_set_error('status', t('New Status is a required field.'));
  }
  //$orig_status = (int)$form_state['values']['current_status_code'];
  //if ( $status == $orig_status) {
    // allow for this, do not block
    // allows for additional notes to be added

  //}

  if ($status == QMS_QTG_STATUS_FAIL) {
    $nt = _st_clean_ckeditor_text($form_state['values']['note_text_editor_value'],
      QMS_TEXTAREA_MAX);

    if ( $nt == '') {
      form_set_error('qms_note_text',
                      t('Note is a required field when setting a test status to FAIL.'));
    }
  }
}

/*
 *  qtg_test_status_form_submit()
 *
 */
function qtg_test_status_form_submit($form, $form_state) {

  $button_clicked = $form_state['triggering_element']['#name'];

  if ( $form['actions']['submit']['#name'] != $button_clicked ) {
    // if not delete & not done, then make sure its a submit click, otherwise, return
    return;
  }

  global $user;
  $id = '';

  $qtg_event_id = (int)$form_state['values']['qtg_event_id'];
  $qtg_test_id = (int)$form_state['values']['qtg_test_id'];
  $qtg_test_status_history_id =
          (int)$form_state['values']['qtg_test_status_history_id'];
  $simulator_id = (int)$form_state['values']['simulator_id'];
  $date_closed = (int)$form_state['values']['date_closed'];
  $new_status = (int)$form_state['values']['status'];
  $current_status = (int)$form_state['values']['current_status_code'];
  $note_text = $form_state['values']['note_text_editor_value'];
  $dr_text = _st_clean_ckeditor_text(
                  $form_state['values']['test_prepend'] . $note_text,
                  QMS_TEXTAREA_MAX);

  $prev_history = _get_qtg_test_status_history($qtg_event_id,
                                                     $qtg_test_id);

  $status_history = new stdClass();
  $status_history->test_status = $new_status;
  $status_history->qtg_event_id = $qtg_event_id;
  $status_history->qtg_test_id = $qtg_test_id;

  $status_history->note_text = _st_clean_ckeditor_text($note_text,
                                                        QMS_TEXTAREA_MAX);

  // if just running the test, update the 'NOT YET RUN' status to 'RAN'
  // for the same status history record.  Keeping a sep status for this is
  // useless
  // turn this into an update of the 'NOT YET RUN' to 'RAN TO BE GRADED'
  if ( (1 == count($prev_history)) &&
       (QMS_QTG_STATUS_RAN == $new_status)) {

    $qtg_test_status_history_id = $prev_history[0]->qtg_test_status_history_id;
  }

  if ( $qtg_test_status_history_id ) {
    $status_history->qtg_test_status_history_id = $qtg_test_status_history_id;
    $status_history->updated_date = REQUEST_TIME;
    $status_history->updated_by_user = $user->uid;
    $id = 'qtg_test_status_history_id';
  }
  else {
    $status_history->created_date = REQUEST_TIME;
    $status_history->created_by_user = $user->uid;
    $id = array();
  }

  if ( False == drupal_write_record('qms_qtg_test_status_history',
                                    $status_history, $id)) {
    drupal_set_message('An error occurred attempting to save qtg test status.');
    drupal_goto('qtg/test/status/edit/' . $qtg_event_id . '/' . $qtg_test_id);
    return;
  }

  db_update('qms_qtg_event_tests')
    ->fields(array('current_status' => $new_status))
    ->condition('qtg_event_id', $qtg_event_id)
    ->condition('qtg_test_id', $qtg_test_id)
    ->execute();

  if ( _qtg_event_tests_complete($qtg_event_id) ) {
    db_update('qms_qtg_events')
      ->fields(array('date_closed' => REQUEST_TIME))
      ->condition('qtg_event_id', $qtg_event_id)
      ->execute();
  }
  else {
    // test event not complete
    // if the test event is currently closed, re-open it
    if ( $date_closed ) {
      db_update('qms_qtg_events')
      ->fields(array('date_closed' => 0))
      ->condition('qtg_event_id', $qtg_event_id)
      ->execute();
    }
  }

  if ( (QMS_QTG_STATUS_FAIL == $new_status) &&
        ($current_status != $new_status) ) {
    // Create a discrepancy for this test using the note_text
    // do not create a dr if we are editing and the status has not changed

    // create a new DR for each PM task that is due
    $discrepancy = new stdClass();
    $baseno = _st_generate_report_base_no('DR');

    $discrepancy->dr_no = _st_generate_report_no('DR', $baseno);
    $discrepancy->tech_user_id = 0; //unassigned
    $discrepancy->simulator_id = $simulator_id;
    $discrepancy->discrepancy = $dr_text;
    $discrepancy->date_opened = REQUEST_TIME;
    $discrepancy->qtg_event_id = $qtg_event_id;
    $discrepancy->qtg_test_id = $qtg_test_id;

    $discrepancy->ata_chapter_id = QMS_ATACHAPTER_OTHER;
    $discrepancy->created_date = REQUEST_TIME;
    $discrepancy->updated_date = REQUEST_TIME;

    // added per FAA recommendation
    $discrepancy->mmi = 1;
    $discrepancy->clear_time = 30.00;

    drupal_write_record('qms_discrepancy_log', $discrepancy);  // add the DR

    // send out email notices for new DRs
    _discrepancy_add_update_post_processing($discrepancy->discrepancy_id);

    $msg = t('Discrepancy') . ' ' . $discrepancy->dr_no . ' ' .
            t('has been created.');

    drupal_set_message($msg);
  }


  drupal_set_message(t('QTG Test Status saved successfully.'));
  drupal_goto('qtg/event/edit/' . $qtg_event_id);
}



/*
 *    qtg_run_test_callback()
 *
 *    updates a test status to 'Run' without going through an edit form
 */
function qtg_run_test_callback($qtg_event_id, $qtg_test_id) {
  try {
//    if ( !$qtg_event_id && !$qtg_test_id ) {
//      drupal_goto('search/qtg');
//      return;
//    }
//
//    $goto_url = 'qtg/event/edit/' . $qtg_event_id;
//
//    if ( $qtg_event_id && !$qtg_test_id ) {
//      drupal_goto($goto_url);
//      return;
//    }

    if ( False == _qtg_test_ran($qtg_event_id, $qtg_test_id) ) {

      $prev_history = _get_qtg_test_status_history($qtg_event_id,
                                                     $qtg_test_id);
      $id = '';



      global $user;
      $new_status = QMS_QTG_STATUS_RAN;

      $status_history = new stdClass();
      $status_history->test_status = $new_status;
      $status_history->qtg_event_id = $qtg_event_id;
      $status_history->qtg_test_id = $qtg_test_id;

      $status_history->note_text = '';

      // edit the existing status 'NOT YET RUN' to 'RAN'
      if ( 1 == count($prev_history)) {

        $status_history->qtg_test_status_history_id =
                $prev_history[0]->qtg_test_status_history_id;
        $id = 'qtg_test_status_history_id';
        $status_history->updated_date = REQUEST_TIME;
        $status_history->updated_by_user = $user->uid;
      }
      else {
        $status_history->created_date = REQUEST_TIME;
        $status_history->created_by_user = $user->uid;
        $id = array();
      }

      if ( False == drupal_write_record('qms_qtg_test_status_history',
                                        $status_history, $id)) {
        drupal_set_message(
             'An error occurred attempting to save qtg test status.');
        drupal_goto($goto_url);
        return;
      }

      db_update('qms_qtg_event_tests')
        ->fields(array('current_status' => $new_status))
        ->condition('qtg_event_id', $qtg_event_id)
        ->condition('qtg_test_id', $qtg_test_id)
        ->execute();

      db_update('qms_qtg_events')
        ->fields(array('date_closed' => 0))
        ->condition('qtg_event_id', $qtg_event_id)
        ->execute();


      //drupal_set_message(t('QTG Test Status Updated.'));
    }
    //drupal_goto($goto_url);

    return drupal_json_output(array(
        'response' => True,
    ));
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_run_test_callback()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}


/*
 *	qtg_test_status_delete_confirm()
 *
 *  Delete the qtg test status -- ADMIN ONLY
 */

function qtg_test_status_delete_confirm($form, $form_state,
                                        $qtg_test_status_history_id = 0) {
  try{

    $bAdmin = user_access('administer sabreQMS');

    $status_history =
       _get_qtg_test_status_history_entry($qtg_test_status_history_id);

    // get the qtg_no
    $event = _get_qtg_event($status_history->qtg_event_id);

    if ( Null == $event ) {
      drupal_set_message( t('QTG Event Not Found!'), 'warning');
      drupal_goto($goto_url);
      return;
    }

    $test = _get_qtg_test($status_history->qtg_test_id);
    if ( Null == $test ) {
      drupal_set_message( t('QTG Test Not Found!'), 'warning');
      drupal_goto($goto_url);
      return;
    }

    // store the id and dr_no in hidden fields for the next step
    // storage field for the discrepancy_id (edit) -- hidden
    $form['qtg_test_status_history_id'] = array(
      '#type' => 'textfield',
      '#default_value' => $qtg_test_status_history_id,
      '#attributes' => array('id' => 'qms-qtg-test-status-history-id',
                              'class' => array('qms-hidden')),
    );
    $form['qtg_event_id'] = array(
      '#type' => 'textfield',
      '#default_value' => $status_history->qtg_event_id,
      '#attributes' => array('id' => 'qms-qtg-event-id',
                              'class' => array('qms-hidden')),
    );
    $form['qtg_test_id'] = array(
      '#type' => 'textfield',
      '#default_value' => $status_history->qtg_test_id,
      '#attributes' => array('id' => 'qms-qtg-test-id',
                              'class' => array('qms-hidden')),
    );
    $form['qtg_no'] = array(
      '#type' => 'textfield',
      '#default_value' => $event->qtg_no,
      '#attributes' => array('id' => 'qms-qtg-no',
                              'class' => array('qms-hidden')),
    );
    $form['test_code'] = array(
      '#type' => 'textfield',
      '#default_value' => $test->test_code,
      '#attributes' => array('id' => 'qms-qtg-test-code',
                              'class' => array('qms-hidden')),
    );
    $form['engine_type'] = array(
      '#type' => 'textfield',
      '#default_value' => $test->engine_code,
      '#attributes' => array('id' => 'qms-qtg-test-engine-type',
                              'class' => array('qms-hidden')),
    );
    $form['test_status_desc'] = array(
      '#type' => 'textfield',
      '#default_value' => $status_history->test_status_desc,
      '#attributes' => array('id' => 'qms-qtg-test-status',
                              'class' => array('qms-hidden')),
    );

    $title = t('Delete QTG Test Status') . '?';
    $question = t('Are you sure you want to delete?') .
                '<h2>' . $event->qtg_no . '<br />' .
                         $test->test_code . '<br />' .
                         $test->engine_code . '<br />' .
                         $status_history->test_status_desc .
                 '</h2><br />' .
                t('This action cannot be undone.');
    $goto_if_canceled = 'qtg/event/edit/' . $status_history->qtg_event_id;
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    // force this here to avoid a problem with routing if cancelled
    //$_GET['destination'] = 'search/qtg';

    return confirm_form($form, $title,	$goto_if_canceled, $question,
                        $yes_btn, $no_btn);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_test_status_delete_confirm()' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}

/*
 *	qtg_test_status_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the qtg test status -- ADMIN ONLY
 */
function qtg_test_status_delete_confirm_submit($form, $form_state) {

  try {
    if ($form_state['values']['confirm']) {


      $qtg_test_status_history_id =
              (int)$form_state['values']['qtg_test_status_history_id'];
      $qtg_event_id =
              (int)$form_state['values']['qtg_event_id'];
      $qtg_test_id =
              (int)$form_state['values']['qtg_test_id'];
      $qtg_no = $form_state['values']['qtg_no'];
      $test_code = $form_state['values']['test_code'];
      $engine_type = $form_state['values']['engine_type'];
      $status_desc = $form_state['values']['test_status_desc'];
      $curr_status = '';

      $prev_history = _get_qtg_test_status_history($qtg_event_id, $qtg_test_id);

      if ( 1== count($prev_history)) {
        // test was updated to run,
        // convert only history entry to 'NOT YET RUN' and do not delete anything
        db_update('qms_qtg_test_status_history')
           ->fields(array(
              'test_status' => QMS_QTG_STATUS_NOT_RUN,
              'updated_date' => 0,
              'updated_by_user' => 0,
           ))
           ->condition('qtg_test_status_history_id',
                        $qtg_test_status_history_id)
           ->execute();
      }
      else {
        db_delete('qms_qtg_test_status_history')
            ->condition('qtg_test_status_history_id',
                        $qtg_test_status_history_id)
            ->execute();
      }



      $query = db_select('qms_qtg_test_status_history', 'sh');
      $query->condition('qtg_event_id', $qtg_event_id);
      $query->condition('qtg_test_id', $qtg_test_id);
      $query->fields('sh', array('test_status'));
      $query->orderBy('created_date', 'desc');
      $query->range(0, 1); // limit to 1

      $result = $query->execute();
      if ( $result->rowCount() ) {
        $curr_status = $result->fetchField();
      }

      db_update('qms_qtg_event_tests')
           ->fields(array('current_status' => $curr_status))
           ->condition('qtg_event_id', $qtg_event_id)
           ->condition('qtg_test_id', $qtg_test_id)
           ->execute();

      $msg = $qtg_no . '<br />' .
             $test_code . '<br />' .
              $engine_type . '<br />';
      $msg .= $status_desc . t(' status has been deleted.');
      drupal_set_message($msg, 'status');

      // remove the troublecall search results, but leave the search key so that the list gets refreshed
      // leave the search key cache intact

    }
    $goto_url = 'qtg/event/edit/' . $qtg_event_id;
    //$_GET['destination'] =  $goto_url;
    drupal_goto( $goto_url);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_event_delete_confirm_submit()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}



//---------------------- DB Retrieval Functions -------------------

/*
 * _get_qtg_event()
 * Returns a qtg event object
 */

function _get_qtg_event($qtg_event_id = 0) {
  try{

    $qtg_event = (object) Null;

    if ( !$qtg_event_id ) { return $qtg_event; }

    $query = db_select('qms_qtg_events', 'ev');
    $query->innerJoin('qms_qtg_test_plans', 'p',
                              'ev.qtg_test_plan_id = p.qtg_test_plan_id');
    $query->innerJoin('qms_qtg_groups', 'g',
                              'ev.qtg_group_id = g.qtg_group_id');
    $query->condition('ev.qtg_event_id', $qtg_event_id);

    $query->fields('ev', array('qtg_event_id', 'qtg_no', 'date_closed',
                              'created_date', 'updated_date', 'updated_by_user'))
          ->fields('p', array('qtg_test_plan_id', 'plan_name', 'simulator_id'))
          ->fields('g', array('qtg_group_id', 'group_name'));

    $result = $query->execute();

    if ( $result->rowCount() ) {
      $qtg_event = $result->fetchObject();
      $qtg_event->created_by_user = Null;
          // define this field for the _st_format_record_timestamp_table() function
    }
    return $qtg_event;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_event()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}


/*
 * _get_qtg_event_tests()
 * Returns an array of tests linked to the QTG event record
 */

function _get_qtg_event_tests($qtg_event_id = 0) {
  try{

    $tests = array();

    if ( !$qtg_event_id ) { return $tests; }

    $query = db_select('qms_qtg_event_tests', 'et');
    $query->innerJoin('qms_qtg_tests', 't', 'et.qtg_test_id = t.qtg_test_id');
    $query->innerJoin('qms_qtg_test_defs', 'td',
                      't.qtg_test_def_id = td.qtg_test_def_id');
    $query->innerJoin('qms_qtg_engine_types', 'e', 't.engine_type = e.engine_type');
    $query->innerJoin('qms_qtg_test_statuses', 'st',
                                  'et.current_status = st.test_status_code');
    $query->condition('et.qtg_event_id', $qtg_event_id);

    $query->fields('et', array('qtg_test_id', 'current_status'))
          ->fields('td', array('qtg_test_def_id', 'test_code', 'test_desc'))
          ->fields('e', array('engine_code', 'engine_desc'))
          ->fields('st', array('test_status_desc'));
    $query->orderBy('t.qtg_test_def_id', 'ASC')
          ->orderBy('t.engine_type', 'ASC');


    $result = $query->execute();

    if ( $result->rowCount() ) {
      $tests = $result->fetchAll();
    }
    return $tests;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_event_tests()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}




/*
 * _get_qtg_test_status_history()
 * Returns an array of tests linked to the QTG event record
 */

function _get_qtg_test_status_history($qtg_event_id = 0, $qtg_test_id = 0) {
  try{

    $status_history = array();

    if ( !$qtg_event_id || !$qtg_test_id ) { return $status_history; }

    $query = db_select('qms_qtg_test_status_history', 'sh');

    $query->innerJoin('qms_qtg_test_statuses', 'st',
                                  'sh.test_status = st.test_status_code');
    //$query->leftJoin('users', 'u', 'sh.created_by_user = u.uid');
    $query->condition('sh.qtg_event_id', $qtg_event_id);
    $query->condition('sh.qtg_test_id', $qtg_test_id);

    $query->fields('sh', array('qtg_test_status_history_id',
                                'qtg_event_id', 'qtg_test_id', 'note_text',
                                'created_date', 'created_by_user',
                                'updated_date', 'updated_by_user'))
          ->fields('st', array('test_status_code', 'test_status_desc'));
    $query->orderBy('created_date', 'desc');
    $query->distinct();

    $result = $query->execute();

    if ( $result->rowCount() ) {
      $status_history = $result->fetchAll();
      $i = 0;
      foreach($status_history as $sh) {
        if ( $status_history[$i]->created_by_user > 0 ) {
          $status_history[$i]->created_user_name =
                    _get_user_name($status_history[$i]->created_by_user);
        }
        else { $status_history[$i]->created_user_name = ''; }

        if ( $status_history[$i]->updated_by_user > 0 ) {
          $status_history[$i]->updated_user_name =
                    _get_user_name($status_history[$i]->updated_by_user);
        }
        else { $status_history[$i]->updated_user_name = ''; }

        $i++;
      }
    }
    return $status_history;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_status_history()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}

/*
 * _get_qtg_test_status_history()
 * Returns an array of tests linked to the QTG event record
 */

function _get_qtg_test_status_history_entry($qtg_test_status_history_id = 0) {
  try{

    $status_history = (object) Null;

    if ( !$qtg_test_status_history_id ) { return $status_history; }

    $query = db_select('qms_qtg_test_status_history', 'sh');

    $query->innerJoin('qms_qtg_test_statuses', 'st',
                                  'sh.test_status = st.test_status_code');
    //$query->leftJoin('users', 'u', 'sh.created_by_user = u.uid');
    //$query->leftJoin('users', 'u2', 'sh.updated_by_user = u2.uid');
    $query->condition('sh.qtg_test_status_history_id',
                      $qtg_test_status_history_id);

    $query->fields('sh', array('qtg_test_status_history_id',
                                'qtg_event_id', 'qtg_test_id', 'note_text',
                                'created_date', 'created_by_user',
                                'updated_date', 'updated_by_user'))
          ->fields('st', array('test_status_code', 'test_status_desc'));
    //$query->fields('u', array('name'));
    //$query->addField('u2', array('name'), 'updated_user_name');

    $result = $query->execute();

    if ( $result->rowCount() ) {
      $status_history = $result->fetchObject();

      if ( $status_history->created_by_user > 0 ) {
        $status_history->created_user_name =
                  _get_user_name($status_history->created_by_user);
      }
      else { $status_history->created_user_name = ''; }

      if ( $status_history->updated_by_user > 0 ) {
        $status_history->updated_user_name =
                  _get_user_name($status_history->updated_by_user);
      }
      else { $status_history->updated_user_name = ''; }
    }
    return $status_history;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_status_history_entry()' .
             $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}



/*
 * _get_qtg_test_statuses()
 * Returns an array of statuses
 */

function _get_qtg_test_statuses() {
  try{

    $status_list = array();


    $query = db_select('qms_qtg_test_statuses', 's');

    $query->fields('s', array('test_status_code', 'test_status_desc'));
    $query->condition('test_status_code', 1, '>');
    $query->orderBy('test_status_code', 'asc');

    $result = $query->execute();

    if ( $result->rowCount() ) {
      $status_list[0] = '- ' . t('Select') . ' -';
      foreach($result as $row) {
        if ( (int)$row->test_status_code > 1 ) {
          $status_list[$row->test_status_code] = $row->test_status_desc;
        }
      }
    }
    return $status_list;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_status_history()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}


/*
 * _qtg_event_tests_complete()
 *
 * IN:  $qtg_event_id
 * RETURN:  BOOL (True | False)
 *    True - all tests in QTG Event have been graded (pass or fail)
 *    False - one or more tests for this event remain unresolved
 *                  (not yet run, ran to be graded, rerun);
 */

function _qtg_event_tests_complete($qtg_event_id = 0) {
  try{

    if ( !$qtg_event_id ) { return False; }

    $open_statuses = array(
          QMS_QTG_STATUS_NOT_RUN,
          QMS_QTG_STATUS_RAN,
          QMS_QTG_STATUS_RERUN,
    );

    // THIS WILL NOT WORK in the PDO module
//    $sql = "SELECT qtg_test_id
//            FROM {qms_qtg_event_tests}
//            WHERE qtg_event_id = :id
//            AND current_status IN (" .
//            QMS_QTG_STATUS_NOT_RUN . ', ' .
//            QMS_QTG_STATUS_RAN . ', ' .
//            QMS_QTG_STATUS_RERUN . ") LIMIT 1";

    $query = db_select('qms_qtg_event_tests', 'et');
    $query->condition('et.qtg_event_id', $qtg_event_id);
    $query->condition('et.current_status', $open_statuses, 'IN');
    $query->fields('et', array('qtg_test_id'));
    $query->range(0,1); // LIMIT to 1 record
    $result = $query->execute();

    if ( $result->rowCount() ) {
      // open statuses found for this event, not complete
      return False;
    }
    // QTG event complete
    return True;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_qtg_event_tests_complete()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}


/*
 * _qtg_test_ran()
 *
 * IN:  $qtg_event_id, $qtg_test_id
 * RETURN:  BOOL (True | False)
 *    True - test was set to 'RAN'
 *    False - test 'Not Yet Run'
 */

function _qtg_test_ran($qtg_event_id = 0, $qtg_test_id = 0) {
  try{

    if ( !$qtg_event_id || !$qtg_test_id ) { return False; }



    // THIS WILL NOT WORK in the PDO module
//    $sql = "SELECT qtg_test_id
//            FROM {qms_qtg_event_tests}
//            WHERE qtg_event_id = :id
//            AND current_status IN (" .
//            QMS_QTG_STATUS_NOT_RUN . ', ' .
//            QMS_QTG_STATUS_RAN . ', ' .
//            QMS_QTG_STATUS_RERUN . ") LIMIT 1";

    $query = db_select('qms_qtg_test_status_history', 'h');
    $query->condition('qtg_event_id', $qtg_event_id);
    $query->condition('qtg_test_id', $qtg_test_id);
    $query->condition('test_status', QMS_QTG_STATUS_RAN);
    $query->fields('h', array('qtg_test_status_history_id'));
    $query->range(0,1); // LIMIT to 1 record
    $result = $query->execute();

    if ( $result->rowCount() ) {
      // RAN status found
      return True;
    }
    // RAN status not found
    return False;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_qtg_test_ran()' . $e->getMessage(),
             array(), WATCHDOG_ERROR);
  }
}
