<?php
// $ID$

/*
 *	Reporting functions for sabreQMS module
 */

require_once( drupal_get_path('module', 'sabreTools') . '/sabreTools.class.yearlist.inc');

require_once('sabreQMS.discrepancylist.inc');
require_once('sabreQMS.qtglist.inc');
require_once('sabreQMS.scheduler.tasks.inc');

/*
 * display_reports_menu()
 *
 */
function display_reports_menu() {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
    return;
  }
  // clear out selections, if they exist
  unset($_SESSION['dew_selected']);
  unset($_SESSION['qtg_selected']);
  unset($_SESSION['return_url']);

  $content =
    '<dl class="admin-list">'.
    '<dt><a href="' . url('reports/discrepancy_early_warning') . '">Discrepancy Early Warning</a></dt>' .
    '<dd>Discrepancies within 5 days of needing to be closed.</dd>' .
    '<dt><a href="' . url('reports/activity24') . '">24 Hour Activity Report</a></dt>' .
    '<dd>Discrepancies that have been updated within the past 24 hours (by simulator).</dd>' .
    '<dt><a href="' . url('reports/activity72') . '">72 Hour Activity Report</a></dt>' .
    '<dd>Discrepancies that have been updated in the past 72 hours (by simulator).</dd>' .
    '<dt><a href="' . url('reports/open_discrepancies') . '">Open Discrepancies</a></dt>' .
    '<dd>Discrepancies that remain open (by simulator).</dd>' .
    '<dt><a href="' . url('reports/open_mmi') . '">Open MMI Discrepancies</a></dt>' .
    '<dd>Open MMI Discrepancies (by simulator).</dd>' .
    '<dt><a href="' . url('reports/qtgexpiring') . '">QTG Tests Expiring</a></dt>' .
    '<dd>QTG Tests within 15 days of expiring.</dd>' .
    '<dt><a href="' . url('qmssettings/prevmaintlist') . '">PM Events</a></dt>' .
    '<dd>Preventative Maintenance Events & Schedules</dd>' .
    '<dt><a href="' . url('reports/simulator_downtime') . '">Simulator Downtime/Uptime</a></dt>' .
    '<dd>Simulator Downtime/Uptime (by simulator and date range).</dd>' .
    '<dt><a href="' . url('reports/simulator_reliability') . '">Simulator Reliability</a></dt>' .
    '<dd>Simulator Reliability (by simulator and year).</dd>';

  global $user;
  if ( _user_is_customer($user->uid) == 0 ) {
    $content .=
      '<dt><a href="' . url('reports/time_worked') . '">Time Worked Report</a></dt>' .
      '<dd>Time Worked (by job).</dd>';
  }

  $content .= '</dl>';

  return $content;
}


/*
 *	time_worked_report_form()
  *
 */

function time_worked_report_form($form, $form_state) {
  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
    return;
  }

  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.timeworked.js');

  $bAdmin = user_access('administer sabreQMS');

  $job_list = new ReportJobList;
  $user_list = array();
  $user_id = 0;

  if ( $bAdmin ) {
    // allow Admin to select from a list of employees
    /* REVISED -- users with punch_clocks may or may not be employees (could be contractors)
    $sql = "SELECT user_id, full_name FROM {qms_employees} e
            WHERE user_id IN (SELECT p.employee_user_id FROM {qms_punch_clock} p, {qms_jobs} j
                              WHERE p.job_id = j.job_id AND j.active = 1)";
     *
     */

    $sql = "SELECT DISTINCT p.employee_user_id, e.full_name, u.name
            FROM qms_punch_clock p
            LEFT JOIN qms_employees e on p.employee_user_id = e.user_id
            LEFT JOIN users u on p.employee_user_id = u.uid
            INNER JOIN qms_jobs j on p.job_id = j.job_id
            WHERE j.active = 1
            ORDER BY e.full_name, u.name";

    $result = db_query($sql);

    $user_list = array(
                    '0' => '- Select -',
                    '-1' => 'ALL',
                  );
    foreach($result as $row) {
      $user_list[$row->employee_user_id] = !empty($row->full_name) ? $row->full_name : $row->name;
    }

    $form['user'] = array(
      '#type' => 'select',
      '#title' => t('Select a User'),
      '#options' => $user_list,
      '#attributes' => array( 'id' => 'qms-user-select',
                              'class' => array('qms-select'),
                              'qms-url' => url('reports/get_jobs') ),
      '#prefix' => '<div id="qms-rpt-select-div">',
      //'#suffix' => '<div id="qms-rpt-time-worked-export"><a href="' . url('reports/timesheet/export'). '">'. t('Export Time Records for QuickBooks') . '</a></div>',
    );

  }
  else {

    global $user;

    $result = db_query("SELECT full_name FROM {qms_employees} e WHERE user_id = :uid", array(':uid' => $user->uid));
    if ( $result->rowCount() == 0 ) {
      drupal_set_message('Oops!  Something went wrong.  Unable to find current user account', 'error');
      return;
    }
    $user_name = $result->fetchField();
    $user_id = $user->uid;

    $form['user'] = array(
      '#type' => 'item',
      '#title' => t('User'),
      '#markup' => '<span id="qms-user-name">' . $user_name . '</span>',
      '#prefix' => '<div id="qms-rpt-select-div">',
    );

    $job_list->init($user->uid);

    /*
    $sql = "SELECT j.job_id, j.job_name FROM {qms_jobs} j, {qms_punch_clock} p
            WHERE j.active = 1 AND j.job_id = p.job_id AND p.employee_user_id = :uid";
    $result = db_query($sql, array(':uid' => $user->uid));

    if ( $result->rowCount() == 0 ) {
      drupal_set_message('Unable to locate active user punch clock records', 'status');
      return;
    }
    $job_list = array(0 => '- Select -');
    foreach($result as $row) {
      $job_list[$row->job_id] = $row->job_name;
    }
    */

  }

  // this could be the current user id or zero since a user has not yet been selected
  $form['user_id'] = array(
    '#markup' => '<div id="qms-user-id" class="qms-hidden-field">' . $user_id . '</div>',
  );


  $form['page_title'] = array(
    '#markup' => '<div class="qms-print-header">' .
                    '<div id="qms-page-title-base" class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />',
  );



  $form['job'] = array(
    '#type' => 'select',
    '#title' => t('Select a Job'),
    '#options' => $job_list->get(),
    '#attributes' => array( 'id' => 'qms-job-select',
                            'class' => array('qms-select'),
                            'qms-url' => url('reports/time_worked_report') ),
    //'#default_value' => $job_id,
    '#validated' => True,
    '#suffix' => '</div>',
  );

  // this could be the current user id or zero since a user has not yet been selected
  $form['report_div'] = array(
    '#markup' => '<div id="qms-report-div"></div>',
  );


  //--------------------- FORM ACTIONS (Buttons) -----------------------

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

  $form['actions']['clear'] = array(
    '#type' => 'button',
    '#value' => t('Clear'),
    '#name' => 'clear',
    '#attributes' => array('class' => array('qms-clear', 'qms-btn-extra')),
  );

  global $base_url;
  $form['actions']['print'] = array(
    '#type' => 'button',
    '#value' => t('Print'),
    '#name' => 'print',
    '#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
    '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
  );


  // storage area for dynamic dialog element
  $form['popup_dialog'] = array(
    '#markup' => '<div id="qms-message-box"></div>',
  );


  return $form;
}





function get_employee_jobs() {

  $user_id = (int)$_POST['user_id'];
  $job_list = new ReportJobList;

  if ( !$user_id ) {
    return;  // user not selected
  }

  //$job_list[0] = '- Select -';

  if ( $user_id == -1 ) {
    // GET ALL active jobs (ALL USERS)
    $job_list->init();
  }
  else {
    // Get Jobs list for the specified user
    $job_list->init($user_id);
  }

  return drupal_json_output($job_list->get());
}

/*
 *    get_time_worked_report()
 *
 */
function get_time_worked_report() {

  $user_id = (int)$_POST['user_id'];
  $job_id = (int)$_POST['job_id'];

  if ( ($user_id == 0) || ($job_id == 0) ) {
    return '<div id="qms-report-div"></div>';
  }

  $sql = "SELECT clock_in, clock_out, time_worked FROM {qms_punch_clock} p WHERE job_id = :jid ";
  $tokens[':jid'] = $job_id;

  if ( $user_id != -1 ) {
    // specific user, not ALL users
    $sql.= " AND employee_user_id = :uid ";
    $tokens[':uid'] = $user_id;

  }
  $sql.= " ORDER BY clock_in ASC";
  $results = db_query($sql, $tokens);

  $table_rows = array();
  $table_header = array(
    array( 'data' => 'Date', 'class' => 'qms-time-worked-date'),
    array( 'data' => 'Clock-In', 'class' => 'qms-time-worked-clocked'),
    array( 'data' => 'Clock-Out', 'class' => 'qms-time-worked-clocked'),
    array( 'data' => 'Time Worked (Hours)', 'class' => 'qms-time-worked-hours'),
  );


  $i = 0;
  $curr_date = '';
  $div = ' ';
  $subtotal = 0.00;
  $grand_total = 0.00;

  foreach ($results as $row) {

    // time_worked stored in seconds.  Convert to hours (2 decimal places)
    $new_hours = round(($row->time_worked / (60 * 60) ), 2);



    $new_date = _st_format_date($row->clock_in, 'custom', 'm-d-Y');
    if ( $curr_date == $new_date) {
      $new_date = '';  // don't list it in the table
    }
    else {

      $curr_date = $new_date;
      if ( $i > 0 ) { // don't do this for the first row
        // print prev date total
        $table_rows[] = array( ' ', ' ',
                          array('data' => 'Total:', 'class' => array('qms-summary-cell')),
                          array('data' => sprintf("%0.2f", $subtotal), 'class' => array('qms-summary-cell')),
                          );


        $subtotal = 0.00;
      }
      $table_rows[] = array(array('data' => $div, 'colspan' => '4', 'class' => array('qms-divrow')));
    }
    $subtotal += $new_hours;
    $grand_total += $new_hours;

    $row_data = array(
      array('data' => $new_date, 'class' => array('qms-time-worked-section')),
      _st_format_date($row->clock_in, 'short'),
      _st_format_date($row->clock_out, 'short'),
      //($row->time_worked / (60 * 60) ),
      array('data' => sprintf("%0.2f", $new_hours), 'class' => array('qms-time-worked-hours')),
    );

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

  if ( $i == 0 ) {
    $table_rows[] = array('data' => array('None', '', '', ''));
  }
  else {
    // print final subtotal and grand total
    $table_rows[] = array( ' ', ' ',
                      array('data' => 'Total:', 'class' => array('qms-summary-cell')),
                      array('data' => sprintf("%0.2f", $subtotal), 'class' => array('qms-summary-cell')),
                      );

    $table_rows[] = array(array('data' => $div, 'colspan' => '4', 'class' => array('qms-divrow')));

    $table_rows[] = array( ' ', ' ',
                      array('data' => 'Grand Total:', 'class' => array('qms-summary-cell')),
                      array('data' => sprintf("%0.2f", $grand_total), 'class' => array('qms-summary-cell')),
                      );

  }


  $content = '<div id="qms-report-div">';
  $content .= '<h3>' . _get_user_name($user_id) . '</h3>';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  $content .= '</div>';

  die($content);
}


/*
 * timesheet_export()
 *
 * exports employee timesheet data as a csv, compatible with QuickBooks
 *
 * @IN   $user_id   | may be 0 or equal to the employee user id
 * @Retn csv file for download
 */
 /*
function timesheet_export_tab($user_id = -1) {

  try {

    $col_delim = "\t";

    $sql = "SELECT p.clock_in, p.clock_out, p.time_worked,
                   u.uid, e.full_name, u.name, c.customer, j.job_name
            FROM qms_punch_clock p
            INNER JOIN qms_jobs j on p.job_id = j.job_id
            INNER JOIN qms_simulators s on j.simulator_id = s.simulator_id
            INNER JOIN users u on p.employee_user_id = u.uid
            LEFT JOIN qms_employees e on p.employee_user_id = e.user_id
            LEFT JOIN qms_customers c on s.customer_id = c.customer_id
            WHERE j.active = 1 ";

    $tokens = array();
    if ( $user_id == -1 ) {
      // all employees, broken up by employee and weeks
      $sql .= " ORDER BY e.full_name ASC, u.name ASC, p.clock_in ASC";

    } else {
      // specific user, not ALL users
      $sql.= " AND p.employee_user_id = :uid ";
      $tokens[':uid'] = $user_id;
      $sql .= " ORDER BY p.clock_in ASC";
    }
    $results = db_query($sql, $tokens);

    $punchclock_list = $results->fetchAll();

    $current_user_id = 0;
    $current_begin_range = '';

    $content = '';
    $total_columns = 12;
    $header_format = array(
      'job' => '"'. t('Customer').':'.t('Job').'"',
      'service' => '"'. t('Service').'"',
      'payroll' => '"'. t('Payroll Item'). '"',
      'notes' => '"'. t('Notes').'"',
      'date1' => '',
      'date2' => '',
      'date3' => '',
      'date4' => '',
      'date5' => '',
      'date6' => '',
      'date7' => '',
    );
    $header = array();

    if (count($punchclock_list) > 0) {

      // build CSV from records
      foreach ($punchclock_list as $pc) {

        // print the name for the next user
        if ($pc->uid != $current_user_id) {
          $name = $pc->name;

          $content .= "\n\n";
          $content .= '"'.( !empty($pc->full_name) ? $pc->full_name : $pc->name ).'"';
          $current_user_id = $pc->uid;

        }

        // get the week range for this record.
        $dt1 = new DateTime();
        $dt1->setTimestamp($pc->clock_in);


        if ($dt1->format('l') != 'Sunday') {
          $dt1->modify('last Sunday');
        }
        $begin_range = $dt1->format('M j');


        $jdt = new DateTime();
        $jdt->setTimestamp($pc->clock_in);

        $jdtf = $jdt->format('M j');


        // print the new range and time event header
        if ($begin_range != $current_begin_range) {

          $begin_range_text = $dt1->format('M d Y');

          $dt2 = new DateTime();
          $dt2->setTimestamp($pc->clock_in);
          $dt2->modify('next Saturday');
          //$end_range = $dt2->getTimestamp;
          $end_range_text = $dt2->format('M d Y');

          $content .= "\n";
          $content .= '"'. t('Week of') . ' ' .
                      $begin_range_text . ' ' . t('to') . ' ' . $end_range_text . '"' . "\n";

          $header = $header_format;

          for ($i = 1; $i <= 7; $i++) {
            $header['date'.$i] = $dt1->format('M j');
            $dt1->modify('+1 day');
          }
          $content .= implode($col_delim, $header) . "\n";
          $current_begin_range = $begin_range;
        }

        // print the punch clock data
        $content .= '"'. $pc->customer . ':' . $pc->job_name . '"' . $col_delim;
        $content .= $col_delim; // 'Database' ?
        $content .= $col_delim; // Payroll Item
        $content .= $col_delim; // Notes

        for ($i = 1; $i <= 7; $i++) {
          $job_date = $jdt->format('M j');
          if ( $header['date'.$i] == $job_date ) {
            // convert seconds to hours
            $content .= sprintf("%0.2f", ($pc->time_worked / 3600)) . $col_delim;
          } else {
            $content .= $col_delim;
          }
        }
        // convert seconds to hours
        $content .= "\n";
      }
    }

    // export to csv
    $curr_date = new DateTime();
    $file_timestamp = $curr_date->format('mdY.His');
    $export_uri = 'private://timesheets';



    if ( !file_prepare_directory($export_uri, FILE_CREATE_DIRECTORY)) {
      drupal_set_message(t('Error:  Export Directory'));
      return;
    }

    $file_basename = 'timesheet_export';
    $dir = file_stream_wrapper_get_instance_by_uri($export_uri)->realpath();

    if ($user_id == -1) {
      $name = t('all');
    }
    $filename = "$dir/$file_basename.$name.txt";

    file_put_contents($filename, $content);


    if (file_exists($filename)) {
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename='.basename($filename));
      header('Content-Transfer-Encoding: binary');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($filename));
      ob_clean();
      flush();
      readfile($filename);
      echo l('Return', '/reports/time_worked');

    }


  } catch (Exception $e) {
      watchdog('sabreQMS', 'ReportJobList::init() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }

}
*/

/*
 * timesheet_export()
 *
 * exports employee timesheet data as a csv, compatible with QuickBooks
 *
 * @IN   $user_id   | may be 0 or equal to the employee user id
 * @Retn csv file for download
 */
 /*
function timesheet_export($user_id = -1) {

  try {

    $col_delim = "\t";
    $file_ext = "iif";
    $eol = "\r\n";

    $sql = "SELECT p.clock_in, p.clock_out, p.time_worked,
                   u.uid, e.full_name, u.name, c.customer, j.job_name
            FROM qms_punch_clock p
            INNER JOIN qms_jobs j on p.job_id = j.job_id
            INNER JOIN qms_simulators s on j.simulator_id = s.simulator_id
            INNER JOIN users u on p.employee_user_id = u.uid
            LEFT JOIN qms_employees e on p.employee_user_id = e.user_id
            LEFT JOIN qms_customers c on s.customer_id = c.customer_id
            WHERE j.active = 1
            AND p.clock_in >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day))";

    $tokens = array();
    if ( $user_id == -1 ) {
      // all employees, broken up by employee and weeks
      $sql .= " ORDER BY e.full_name ASC, u.name ASC, p.clock_in ASC";

    } else {
      // specific user, not ALL users
      $sql.= " AND p.employee_user_id = :uid ";
      $tokens[':uid'] = $user_id;
      $sql .= " ORDER BY p.clock_in ASC";
    }
    $results = db_query($sql, $tokens);

    $punchclock_list = $results->fetchAll();

    $today = new DateTime();
    $name = '';

    // Quickbooks IIF format -- build the report header

    // $content = implode($col_delim, array(
    //   '!TIMERHDR',
    //   'VER',
    //   'REL',
    //   'COMPANYNAME',
    //   'IMPORTEDBEFORE',
    //   'FROMTIMER',
    //   'COMPANYCREATETIME',
    // )) . $eol;
    // $content .= implode($col_delim, array(
    //   'TIMERHDR',
    //   '16',
    //   '0',
    //   'Sabre Updates LLC',
    //   'N',
    //   'N',
    //   $today->getTimestamp(),
    // )) . $eol;

    $content .= implode($col_delim, array(
      '!HDR',
      'PROD',
      'VER',
      'REL',
      'IIFVER',
      'DATE',
      'TIME',
      'ACCNTNT',
      'ACCNTNTSPLITTIME',
    )) . $eol;
    $content .= implode($col_delim, array(
      'HDR',
      'QuickBooks Enterprise',
      '16',
      '0',
      '1',
      $today->format('m/d/Y'),
      $today->getTimestamp(),
      'N',
      '0',
    )) . $eol;
    $content .= implode($col_delim, array(
      '!TIMEACT',
      'DATE',
      'JOB',
      'EMP',
      'ITEM',
      'PITEM',
      'DURATION',
      'PROJ',
      'NOTE',
      'BILLINGSTATUS',
    )) . $eol;


    // QuickBooks -- export timesheet data in IIF format
    if (count($punchclock_list) > 0) {

      foreach ($punchclock_list as $pc) {

        if (($user_id > 0) && empty($name)) {
          $name = $pc->name;
        }

        $jdt = new DateTime();
        $jdt->setTimestamp($pc->clock_in);

        $content .= implode($col_delim, array(
          'TIMEACT',
          $jdt->format('m/d/y'),
          $pc->customer . ':' . $pc->job_name,
          ( !empty($pc->full_name) ? $pc->full_name : $pc->name ),
          'Service',
          '',
          sprintf("%0.2f", ($pc->time_worked / 3600)),
          '',
           '',
          '1', 
        )) . $eol;
      }


      // Export to QuickBooks format
      $file_timestamp = $today->format('mdY.His');
      $export_uri = 'private://timesheets';



      if ( !file_prepare_directory($export_uri, FILE_CREATE_DIRECTORY)) {
        drupal_set_message(t('Error:  Export Directory'));
        return;
      }

      $file_basename = 'timesheet_export';
      $dir = file_stream_wrapper_get_instance_by_uri($export_uri)->realpath();

      if ($user_id == -1) {
        $name = t('all');
      }
      $filename = "$dir/$file_basename.$name.$file_ext";

      file_put_contents($filename, $content);


      if (file_exists($filename)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($filename));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        ob_clean();
        flush();
        readfile($filename);
        echo l('Return', '/reports/time_worked');
      }
    } else {
      drupal_goto('reports/time_worked');
    }

  } catch (Exception $e) {
      watchdog('sabreQMS', 'ReportJobList::init() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }

}
*/


/*
 *	QMS_alerts()
 *
 *	returns:  Discrepancy Early Warning list & QTG expiring list
 *
 */

function QMS_alerts() {
//  $print_page_heading =
//									'<div class="qms-print-header">' .
//										'<div class="qms-page-title">' .
//                      drupal_get_title() .
//                    '</div>' .
//									'</div><br />';
//  $content = (!$called_by_pager) ? $print_page_heading : '<br class="clearBoth" />';
  drupal_set_title(t('Alerts'));
  $vars = array(
    'filter' => False,
    'pager' => False,
  );
  unset($_SESSION['dew_selected']);
  unset($_SESSION['qtg_selected']);
  $_SESSION['return_url'] = 'reports/alerts';

  $content = '<div class="clearBoth" /></div>';

  // save the current path and reset it after getting the form
  // due to the page sort pathing issues
  $current = $_GET['q'];

  $content .= '<h3>' . t('Discrepancy Early Warning') . '</h3>';
  $dewf = drupal_get_form('discrepancy_early_warning_form', $vars);
  $content .= drupal_render($dewf);
  $_GET['q'] = $current;

  $content .= '<br /><h3>' . t('QTG Expiring') . '</h3>';
  $qtgef = drupal_get_form('qtg_expiring_form', $vars);
  $content .= drupal_render($qtgef);

  $_GET['q'] = $current;

  $af = drupal_get_form('report_form', 'ALERTS');
  $content .= render($af);

  return $content;
}



/*
 *	discrepancy_early_warning_report()
 *
 *	returns:  Tabled list of DRs in need of being closed
 *  wrapper function
 *
 */

function discrepancy_early_warning_report($vars = array()) {

  $page_title = drupal_get_title();
  $report_code = 'DEW';

  // this is needed to override a specific case when report filtering
  // is triggered, but the $_GET['q'] is set to the pager path

  if ( isset($vars['filter']) && $vars['filter']) {
    $report_code = 'DEWf';
    $page_title .= ' [' . t('Filtered') . ']';
    drupal_set_title($page_title);
  }

  if (!isset($vars['pager']) || !$vars['pager']) {
    if ( !isset($_SESSION['return_url'])) {
      $_SESSION['return_url'] = 'reports';
    }
  }


  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      $page_title .
                    '</div>' .
                  '</div><div class="clearBoth">&nbsp;</div>';
  $content = '';

  if ( !isset($vars['pager']) || !$vars['pager']) {
    $content = $print_page_heading;
  }

  // save the current path and reset it after getting the form
  // due to the page sort pathing issues
  $current = $_GET['q'];

  $form_elems = drupal_get_form('discrepancy_early_warning_form', $vars);
  $content .= render($form_elems);
  $_GET['q'] = $current;


  if ( !isset($vars['pager']) || !$vars['pager'] ) {
    $form_elems = drupal_get_form('report_form',
                                       $report_code,
                                       'reports');
    $content .= render($form_elems);
    return $content;
  }
  die($content);
}

/*
 *	qtg_expiring_report()
 *
 *	returns:  Tabled list of QTG tests within 15 days of expiring
 *            (15 days before next Test Event for this Testing Plan)
 *
 */

function qtg_expiring_report($vars = array()) {

  $page_title = drupal_get_title();

  // this is needed to override a specific case when report filtering
  // is triggered, but the $_GET['q'] is set to the pager path
  if ( isset($vars['filter']) && $vars['filter']) {
    $page_title .= ' [' . t('Filtered') . ']';
    drupal_set_title($page_title);
  }

  if (!isset($vars['pager']) || !$vars['pager']) {
    if ( !isset($_SESSION['return_url'])) {
      $_SESSION['return_url'] = 'reports';
    }
  }

  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><div class="clearBoth">&nbsp;</div>';
  $content = '';
  if ( !isset($vars['pager']) || !$vars['pager']) {
    $content = $print_page_heading;
  }

  // save the current path and reset it after getting the form
  // due to the page sort pathing issues
  $current = $_GET['q'];
  $form_elems = drupal_get_form('qtg_expiring_form', $vars);
  $content .= render($form_elems);
  $_GET['q'] = $current;

  if ( !isset($vars['pager']) || !$vars['pager'] ) {
    $form_elems = drupal_get_form('report_form',
                                       'QTG',
                                       'reports');
    $content .= render($form_elems);
    return $content;
  }
  die($content);

}

/*
 *	discrepancies_report()
 *
 *	returns:  Tabled list of DRs based on the requirements of the specified report
 */
function discrepancies_report($report_code, $simulator_id = 0) {

  //if ( !$callback ) {
    // this builds a selection form form and also calls
    // _get_discrepancy_activity_list() to initially populate the page IF a simulator_id
    // is passed in on the initial call to discrepancies_report()
    //return render(drupal_get_form('discrepancies_report_form', $report_code, $simulator_id));

  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $form_elems = drupal_get_form('discrepancies_report_form', $report_code, $simulator_id);
  $content .= render($form_elems);
  return $content;

  /*
  }
  else {
    return _get_discrepancy_activity_list($report_code, $simulator_id, $callback);
  }
  */
}

/*
 *	discrepancies_selected_report()
 *
 *	returns:  Tabled list of DRs based on those selected from the search list
 */
function discrepancies_selected_report() {

  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $content.= _get_discrepancy_activity_list(QMS_RPT_DR_SELECTED);
  $df = drupal_get_form('discrepancies_report_form', QMS_RPT_DR_SELECTED);
  $content.= render($df);
  return $content;
}

/*
 *	discrepancies_report_form()
 *
 *	returns:  Displays select list of simulators for which to generate reports
 */

function discrepancies_report_form($form, $form_state, $report_code, $simulator_id = 0) {

  $hours = 0;
  $goto_report_url = '';
  $return_url = '';
  $page_title = '';

  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.report.js');

  switch ($report_code) {
    case QMS_RPT_72HR_ACTIVITY:
    case QMS_RPT_24HR_ACTIVITY:
      $hours = $report_code;
      $goto_report_url = url('reports/activity' . $hours);
      $page_title = $hours . ' Hour Activity Report';
      break;
    case QMS_RPT_OPEN_DISCREPANCY:
      $goto_report_url = url('reports/open_discrepancies');
      $page_title = 'Open Discrepancies Report';
      break;
    case QMS_RPT_OPEN_MMI:
      $goto_report_url = url('reports/open_mmi');
      $page_title = 'Open MMI Discrepancies Report';
      break;
  }

  switch ($report_code) {
    case QMS_RPT_72HR_ACTIVITY:
    case QMS_RPT_24HR_ACTIVITY:
    case QMS_RPT_OPEN_DISCREPANCY:
    case QMS_RPT_OPEN_MMI:

      $return_url = 'reports';

      // Get list of simulators to display -- active + inactive
      global $simulator_list;


      $form['simulator_id'] = array(
        '#type' => 'select',
        '#title' => t('Select a Simulator') . ' <span>(* = ' . t('inactive') . ')</span>',
        '#options' => $simulator_list->get(),
        '#prefix' => '<div id="qms-rpt-simulator-div">',
        '#suffix' => '</div>',
        '#attributes' => array( 'id' => 'qms-simulator-list',
                                'class' => array('qms-select'),
                                'qms-url' => $goto_report_url),
        '#default_value' => $simulator_id,
      );

      $form['page_title'] = array(
        '#markup' => '<div id="qms-page-title-base" class="qms-hidden-field">' . $page_title . '</div>',
      );

      if ( $simulator_id ) {
        global $simulator_list;

        $div_content = _get_discrepancy_activity_list($report_code, $simulator_id);

        // simulator selected, populate the div with table data
        $form['reports_div'] = array(
          '#markup' => $div_content,
        );
      }
      else {
        // this will get populated with report data after a simulator is selected
        $form['reports_div'] = array(
          '#markup' => '<div id="qms-report-div"></div>',
        );
      }

      break;
    case QMS_RPT_DR_SELECTED:
      $return_url = 'search/discrepancy';
      break;
  }

  $form['return_url'] = array(
    '#type' => 'textfield',
    '#default_value' => $return_url,
    '#attributes' => array('class' => array('qms-hidden')),
  );


  //-------------------- FORM ACTIONS (Buttons) ----------------------

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

  $form['actions']['clear'] = array(
    '#type' => 'button',
    '#value' => t('Clear'),
    '#name' => 'clear',
    '#attributes' => array('class' => array('qms-clear', 'qms-btn-extra')),
  );

  global $base_url;
  $form['actions']['print'] = array(
    '#type' => 'button',
    '#value' => t('Print'),
    '#name' => 'print',
    '#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
    '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
  );


  // storage area for dynamic dialog element
  $form['popup_dialog'] = array(
    '#markup' => '<div id="qms-message-box"></div>',
  );



  return $form;

}

/*
 * _get_discrepancy_activity_list()
 */

function _get_discrepancy_activity_list($report_code, $simulator_id = 0) {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }

  global $user;
  $user_is_customer_id = _user_is_customer($user->uid);
  $return_url = '';

  $table_header = array();

  // set table header
  switch ($report_code) {
    case QMS_RPT_72HR_ACTIVITY:
    case QMS_RPT_24HR_ACTIVITY:
      if ( $simulator_id == 0 ) {
        return;
      }
    case QMS_RPT_DR_SELECTED:
      // simulator selection id is expected to be zero for this report

      $table_header = array(
        array( 'data' => 'Closed', 'class' => 'qms-rpt-activity-closed'),
        array( 'data' => 'DR No.', 'class' => 'qms-rpt-activity-drno'),
        array( 'data' => 'Opened', 'class' => 'qms-rpt-activity-opened'),
        array( 'data' => 'Discrepancy', 'class' => 'qms-rpt-activity-discrepancy'),
        array( 'data' => 'Comments'),
      );
      break;
    case QMS_RPT_OPEN_DISCREPANCY:
      if ( $simulator_id == 0 ) { return; }

      $table_header = array(
        array( 'data' => 'DR No.', 'class' => 'qms-rpt-activity-drno'),
        array( 'data' => 'Opened', 'class' => 'qms-rpt-activity-opened'),
        array( 'data' => 'Discrepancy', 'class' => 'qms-rpt-activity-discrepancy'),
        array( 'data' => 'Comments'),
        array( 'data' => 'Days Open', 'class' => 'qms-rpt-activity-daysopen'),
      );
      break;
    case QMS_RPT_OPEN_MMI:
      if ( $simulator_id == 0 )  { return; }

      $table_header = array(
        array( 'data' => 'DR No.', 'class' => 'qms-rpt-activity-drno'),
        array( 'data' => 'Opened', 'class' => 'qms-rpt-activity-opened'),
        array( 'data' => 'Days to Clear', 'class' => 'qms-rpt-activity-daystoclear'),
        array( 'data' => 'Discrepancy', 'class' => 'qms-rpt-activity-discrepancy'),
        array( 'data' => 'Comments'),
      );
      break;
  }

  $query = db_select('qms_discrepancy_log', 'd');

  if ( $user_is_customer_id ) {
    $query->innerJoin('qms_simulators', 's',
                      'd.simulator_id = s.simulator_id AND s.customer_id = :cid',
                      array(':cid' => $user_is_customer_id));
  }


  $order_field = 'date_opened';
  $sort_order = 'DESC';
  switch ($report_code) {
    case QMS_RPT_72HR_ACTIVITY:
    case QMS_RPT_24HR_ACTIVITY:
      $query->condition('d.simulator_id', $simulator_id);

      // a quicky way to set the hours as its the same as the report code
      $query->where('d.updated_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL :hrs HOUR))', array(':hrs' => $report_code));
      $order_field = 'updated_date';
      break;
    case QMS_RPT_DR_SELECTED:
      // get the selected dr cache, if anything has been stored
      //global $user; -- defined at top
      $saved_selected_text = '';
      $selected_dr_cache_name = _get_qms_cache_name(QMS_DISCREPANCY_SELECTED);

      $selected_dr_cache = cache_get($selected_dr_cache_name);
      if ( isset($selected_dr_cache->data) && ($selected_dr_cache->data <> '') ) {
        $saved_selected_text = $selected_dr_cache->data;
      }

      $dr_list = array();
      if ( strlen($saved_selected_text) ) {
        $dr_list = explode(",", $saved_selected_text);
        $query->where('d.discrepancy_id IN (:sel_list)', array(':sel_list' => $dr_list));
      }
      else {
        drupal_set_message(t('No selections made.  Please select discrepancies to create report.'));
        $content = '<div id="qms-report-div">';

        $content .= theme( 'table', array(
          'header' => $table_header,
          'rows' => array(),
          'empty' => t('None Selected'),
        ));

        $content .= '</div>';
        return $content;
      }
      // use the default order 'date_opened DESC'
      break;
    case QMS_RPT_OPEN_DISCREPANCY:
      $query->condition('d.simulator_id', $simulator_id)
            ->condition('date_closed', 0);
      $q3 = $query->addExpression('DATEDIFF(NOW(), FROM_UNIXTIME(date_opened))', 'days_open');
      $sort_order = 'ASC';
      break;
    case QMS_RPT_OPEN_MMI:
      $query->condition('d.simulator_id', $simulator_id)
            ->condition('date_closed', 0)
            ->condition('mmi', 1);
      $q3 = $query->addExpression("DATE_ADD(FROM_UNIXTIME(d.date_opened), INTERVAL CAST((d.clear_time * 24) AS UNSIGNED) HOUR)", "clear_datetime");
      $order_field = 'clear_datetime';
      $sort_order = 'ASC';
      break;
  }
  $query->fields('d', array('discrepancy_id', 'dr_no', 'date_opened', 'date_closed', 'discrepancy', 'clear_time', 'updated_date') )
        ->orderBy($order_field, $sort_order);
  $result = $query->execute();

  $i = 0;
  $table_rows = array();
  $cmt_col = 0;

  foreach ($result as $row) {

    // determine the routing for the VIEW link so that if clicked, the user will be returned to
    // the appropriate page
    $route_to = 'discrepancy/view/' . $row->discrepancy_id;
    switch ($report_code) {
      case QMS_RPT_72HR_ACTIVITY:
        $return_url = 'reports/activity72/' . $simulator_id;
        break;
      case QMS_RPT_24HR_ACTIVITY:
        $return_url = 'reports/activity24/' . $simulator_id;
        break;
      case QMS_RPT_DR_SELECTED:
        $return_url = 'reports/discrepancies/selected';
        break;
      case QMS_RPT_OPEN_DISCREPANCY:
        $return_url = 'reports/open_discrepancies/' . $simulator_id;
        break;
      case QMS_RPT_OPEN_MMI:
        $return_url = 'reports/open_mmi/' . $simulator_id;
        break;
    }

    // determine the appropriate report results table column layout
    // also sets switch for which column contains the comments
    switch ($report_code) {
      case QMS_RPT_72HR_ACTIVITY:
      case QMS_RPT_24HR_ACTIVITY:
      case QMS_RPT_DR_SELECTED:
        $row_data = array(
          (($row->date_closed > 0) ? 'Yes' : 'No'),
          l($row->dr_no, $route_to, array('query' => array('destination' => $return_url))),
          _st_format_date($row->date_opened, 'short'),
          array('data' => $row->discrepancy, 'class' => 'qms-rpt-activity-discrepancy'),
          $row->discrepancy_id,	// placeholder with id, comments retrieved below
        );
        $cmt_col = 4; 	// index of column containing the comments
        break;
      case QMS_RPT_OPEN_DISCREPANCY:
        $row_data = array(
          l($row->dr_no, $route_to, array('query' => array('destination' => $return_url))),
          _st_format_date($row->date_opened, 'short'),
          array('data' => $row->discrepancy, 'class' => 'qms-rpt-activity-discrepancy'),
          $row->discrepancy_id,
          array('data' => $row->days_open, 'class' => 'qms-rpt-activity-daysopen'),
        );
        $cmt_col = 3;		// index of column containing the comments
        break;
      case QMS_RPT_OPEN_MMI:
        $row_data = array(
          l($row->dr_no, $route_to, array('query' => array('destination' => $return_url))),
          _st_format_date($row->date_opened, 'short'),
          array('data' => $row->clear_time, 'class' => 'qms-rpt-activity-daystoclear'),
          array('data' => $row->discrepancy, 'class' => 'qms-rpt-activity-discrepancy'),
          $row->discrepancy_id, // placeholder with id, comments retrieved below
        );
        $cmt_col = 4;		// index of column containing the comments
        break;
    }

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

  if ( $i > 0 ) {

    for($c = 0; $c < count($table_rows); $c++) {
      $discrepancy_id = $table_rows[$c]['data'][$cmt_col];  // grab the discrep id, temporarily stored here
      $table_rows[$c]['data'][$cmt_col] = array(
                      'data' => _get_formatted_discrepancy_comments($discrepancy_id),
                      'class' => 'qms-rpt-activity-comments');  // get the DR comments
    }
  }

  $content = '<div id="qms-report-div">';

  if ( $simulator_id ) {
    global $simulator_list;
    $content .= '<h3>' . $simulator_list->getName($simulator_id) . '</h3>';
  }

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';


  return $content;
}


/*
 * _get_formatted_discrepancy_comments()
*/
function _get_formatted_discrepancy_comments($discrepancy_id) {

  $content = '';

  if ( $discrepancy_id == 0 ) {
    return $content;
  }


  // get discrepancy comments
  $sql = "SELECT c.discrepancy_comment_id, u.name, c.`timestamp`, c.comment
          FROM {qms_discrepancy_comments} c, {users} u
          WHERE c.discrepancy_id = :did AND c.user_id = u.uid
          ORDER BY c.discrepancy_comment_id";
  $results = db_query($sql, array(':did' => $discrepancy_id));

  foreach ( $results as $row ) {
    $c  = '<div class="qms-comment-hdr">' . $row->name . ' - ' . _st_format_date($row->timestamp, 'short') . '</div>';
    $c .= $row->comment . '<br /><br />';
    $content .= $c;
  }
  return $content;
}

/*
 *	engineering_selected_report()
 *
 *	returns:  Tabled list of ENGs based on those selected from the search list
 */
function engineering_selected_report() {

  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $content.= _get_engineering_report_list();
  $form_elems = drupal_get_form('report_form', 'ENG');
  $content.= render($form_elems);
  return $content;
}


/*
 * _get_engineering_report_list()
 */

function _get_engineering_report_list() {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }

  global $simulator_list;
  global $user;
  $user_is_customer_id = _user_is_customer($user->uid);

  $table_header = array(
    array( 'data' => 'Tech./Instr.', 'class' => 'qms-rpt-eng-tech'),
    array( 'data' => 'Eng No.', 'class' => 'qms-rpt-eng-engno'),
    array( 'data' => 'DR No.', 'class' => 'qms-rpt-eng-drno'),
    array( 'data' => 'Simulator', 'class' => 'qms-rpt-eng-simulator'),
    array( 'data' => 'Load Updated', 'class' => 'qms-rpt-eng-loadupdated'),
    array( 'data' => 'Module', 'class' => 'qms-rpt-eng-module'),
    array( 'data' => 'Date', 'class' => 'qms-rpt-eng-datetime'),
  );


  $saved_selected_text = '';
  $selected_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SELECTED);

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;
  }

  $saved_selected_list = array();
  if ( strlen($saved_selected_text) ) {
    $saved_selected_list = explode(",", $saved_selected_text);
  }
  else {
    drupal_set_message(t('No selections made.  Please select engineering items to create report.'));
    $content = '<div id="qms-report-div">';

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => array(),
      'empty' => t('None Selected'),
    ));
    $content .= '</div>';

    return $content;
  }




  $query = db_select('qms_engineering', 'g');

  if ( count($saved_selected_list) ) {
    $query->where('g.engineering_id IN (:sel_list)', array(':sel_list' => $saved_selected_list));
  }


  $query->innerJoin('qms_discrepancy_log', 'd', 'g.discrepancy_id = d.discrepancy_id');
  $query->innerJoin('qms_eng_load_updated', 'l', 'g.load_updated_id = l.eng_load_updated_id');

  if ( $user_is_customer_id ) {
    $query->innerJoin('qms_simulators', 's', 'd.simulator_id = s.simulator_id');
    $query->condition('s.customer_id', $user_is_customer_id, '=');
  }

  $query->leftJoin('qms_employees', 'e', 'g.tech_user_id = e.user_id');
  $query->leftJoin('users', 'u', 'u.uid = g.tech_user_id');


  $query->fields('g', array('engineering_id', 'eng_no', 'discrepancy_id', 'datetime', 'module_updated') )
        ->fields('d', array('dr_no', 'simulator_id'))
        ->fields('l', array('eng_load_updated_desc'))
        //->fields('s', array('sim_name', 'active', 'device_id_internal'))
        ->fields('e', array('full_name'))
        ->fields('u', array('name'))
        ->orderBy('datetime', 'DESC');
  $result = $query->execute();

  $i = 0;
  $table_rows = array();
  $cmt_col = 0;

  foreach ($result as $row) {

    $row_data = array(
      ( (strlen($row->full_name) > 0) ? check_plain($row->full_name) : check_plain($row->name) . "*"),
      l($row->eng_no, 'engineering/view/' . $row->engineering_id,
            array('attributes' =>
                array('query' => array('destination' => 'reports/engineering/selected')))),
      l($row->dr_no, 'discrepancy/view/' . $row->discrepancy_id,
            array('attributes' =>
                array('query' => array('destination' => 'reports/engineering/selected')))),
      $simulator_list->getName($row->simulator_id),
      $row->eng_load_updated_desc,
      $row->module_updated,
      _st_format_date($row->datetime, 'short'),
    );

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

  $content = '<div id="qms-report-div">';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';

  return $content;
}

/*
 *	trouble_calls_selected_report()
 *
 *	returns:  Tabled list of TCs based on those selected from the search list
 */
function trouble_calls_selected_report() {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }
  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $content.= _get_trouble_calls_report_list();
  $form_elems = drupal_get_form('report_form', 'TC');
  $content.= render($form_elems);
  return $content;
}

/*
 * _get_trouble_call_reports_list()
 */

function _get_trouble_calls_report_list() {

  $table_header = array(
    array( 'data' => t('TC No.'), 'class' => 'qms-rpt-tc-tcno'),
    array( 'data' => t('Date Opened'), 'class' => 'qms-rpt-tc-opened'),
    array( 'data' => t('Date Closed'), 'class' => 'qms-rpt-tc-closed'),
    array( 'data' => t('Simulator'), 'class' => 'qms-rpt-tc-simulator'),
    array( 'data' => t('Cause') . '/' . t('Trouble'), 'class' => 'qms-rpt-tc-trouble'),
  );

  $saved_selected_text = '';
  $selected_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SELECTED);

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;
  }

  $saved_selected_list = array();
  if ( strlen($saved_selected_text) ) {
    $saved_selected_list = explode(",", $saved_selected_text);
  }
  else {
    drupal_set_message(t('No selections made.  Please select trouble call log items to create report.'));
    $content = '<div id="qms-report-div">';

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => array(),
      'empty' => t('None Selected'),
    ));

    $content .= '</div>';
    return $content;
  }

  global $simulator_list;




  $query = db_select('qms_trouble_call_log', 'tc');

  if ( count($saved_selected_list) ) {
    $query->where('tc.trouble_call_id IN (:sel_list)', array(':sel_list' => $saved_selected_list));
  }
  $query->innerJoin('qms_simulators', 's', 'tc.simulator_id = s.simulator_id');
  //$query->leftJoin('qms_employees', 'e', 'tc.tech_user_id = e.user_id');
  //$query->innerJoin('users', 'u', 'u.uid = tc.tech_user_id');
  $query->innerJoin('qms_trouble_causes', 'tcc', 'tc.trouble_cause_code = tcc.trouble_cause_code');


  $query->fields('tc', array('trouble_call_id', 'tc_no', 'date_opened', 'date_closed',
                             'trouble_text', 'simulator_id' ) )
        ->fields('tcc', array('trouble_cause_desc') )
        //->fields('s', array('sim_name', 'active', 'device_id_internal'))
        //->fields('e', array('full_name'))
        //->fields('u', array('name'))
        ->orderBy('date_opened', 'DESC');
  $result = $query->execute();

  $i = 0;
  $table_rows = array();
  $cmt_col = 0;

  foreach ($result as $row) {

    $row_data = array(
      l($row->tc_no, 'troublecall/view/' . $row->trouble_call_id,
        array('query' => array('destination' => 'reports/troublecalls/selected'))),
      _st_format_date($row->date_opened, 'short'),
      ($row->date_closed ? _st_format_date($row->date_closed, 'short') : ''),
      $simulator_list->getName($row->simulator_id),
      $row->trouble_cause_desc . '<div class="qms-divider"></div>' . $row->trouble_text,
      //( (strlen($row->full_name) > 0) ? $row->full_name : $row->name . "*"),
    );

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

  $content = '<div id="qms-report-div">';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';

  return $content;
}



/*
 *	shiftlog_selected_report()
 *
 *	returns:  Tabled list of SLs based on those selected from the search list
 */
function shiftlog_selected_report() {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }
  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $content .= _get_shiftlog_report_list();
  $form_elems = drupal_get_form('report_form', 'SL');
  $content.= render($form_elems);
  return $content;
}


/*
 * _get_shiftlog_report_list()
 */

function _get_shiftlog_report_list() {


  $table_header = array(
    array( 'data' => 'Date Time', 'class' => 'qms-rpt-sl-datetime'),
    array( 'data' => 'Comments', 'class' => 'qms-rpt-sl-comments'),
    array( 'data' => 'Employee', 'class' => 'qms-rpt-sl-employee'),
    array( 'data' => 'Simulator', 'class' => 'qms-rpt-sl-simulator'),
  );

  $saved_selected_text = '';
  $selected_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SELECTED);

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;
  }

  $saved_selected_list = array();
  if ( strlen($saved_selected_text) ) {
    $saved_selected_list = explode(",", $saved_selected_text);
  }
  else {
    drupal_set_message(t('No selections made.  Please select shift log items to create report.'));
    $content = '<div id="qms-report-div">';

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => array(),
      'empty' => t('None Selected'),
    ));

    $content .= '</div>';

    return $content;
  }

  global $simulator_list;




  $query = db_select('qms_shift_log', 'l');

  if ( count($saved_selected_list) ) {
    $query->where('l.shift_log_id IN (:sel_list)', array(':sel_list' => $saved_selected_list));
  }
  $query->innerJoin('qms_simulators', 's', 'l.simulator_id = s.simulator_id');
  $query->leftJoin('qms_employees', 'e', 'l.employee_user_id = e.user_id');
  $query->innerJoin('users', 'u', 'u.uid = l.employee_user_id');


  $query->fields('l', array('shift_log_id', 'datetime', 'comment', 'simulator_id') )
        //->fields('s', array('sim_name', 'active', 'device_id_internal'))
        ->fields('e', array('full_name'))
        ->fields('u', array('name'))
        ->orderBy('datetime', 'DESC');
  $result = $query->execute();

  $i = 0;
  $table_rows = array();
  $cmt_col = 0;

  foreach ($result as $row) {

    $row_data = array(
      l( _st_format_date($row->datetime, 'short'), 'shiftlog/view/' . $row->shift_log_id,
        array('query' => array('destination' => 'search/shiftlog/selected'))),
      $row->comment,
      ( (strlen($row->full_name) > 0) ? $row->full_name : $row->name . "*"),
      $simulator_list->getName($row->simulator_id),
    );

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



  $content = '<div id="qms-report-div">';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';

  return $content;
}



/*
 *	qtg_selected_report()
 *
 *	returns:  Tabled list of QTGs based on those selected from the search list
 */
function qtg_selected_report() {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }
  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $content .= _get_qtg_report_list();
  $form_elems = drupal_get_form('report_form', 'QTG');
  $content.= render($form_elems);
  return $content;
}

/*
 * _get_qtg_report_list()
 */

function _get_qtg_report_list() {

  $table_header = array(
    array( 'data' => t('QTG No.'), 'class' => 'qms-rpt-qtg-qtgno'),
    array( 'data' => t('Date Opened'), 'class' => 'qms-rpt-qtg-opened'),
    array( 'data' => t('Date Closed'), 'class' => 'qms-rpt-qtg-closed'),
    array( 'data' => t('Simulator'), 'class' => 'qms-rpt-qtg-simulator'),
    array( 'data' => t('Plan/Group') , 'class' => 'qms-rpt-qtg-plan-group'),
  );

  global $simulator_list;

  $bAllowEdit = user_access('edit qtg event');

  $saved_selected_text = '';
  $selected_cache_name = _get_qms_cache_name(QMS_QTG_SELECTED);

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;
  }

  $saved_selected_list = array();
  if ( strlen($saved_selected_text) ) {
    $saved_selected_list = explode(",", $saved_selected_text);
  }
  else {
    drupal_set_message(t('No selections made.  ' .
                         'Please select QTG event items to create report.'));
    $content = '<div id="qms-report-div">';

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => array(),
      'empty' => t('None Selected'),
    ));

    $content .= '</div>';
    return $content;
  }


  $query = db_select('qms_qtg_events', 'ev');

  if ( count($saved_selected_list) ) {
    $query->where('ev.qtg_event_id IN (:sel_list)', array(':sel_list' => $saved_selected_list));
  }
  $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->fields('ev', array('qtg_event_id', 'qtg_no',
                             'created_date', 'date_closed'))
        ->fields('p', array('qtg_test_plan_id', 'plan_name', 'simulator_id') )
        ->fields('g', array('qtg_group_id', 'group_name') )
        ->orderBy('created_date', 'DESC');
  $result = $query->execute();

  $i = 0;
  $table_rows = array();
  $cmt_col = 0;

  $qtg_url = ($bAllowEdit ? 'qtg/event/edit/' : 'qtg/event/view/');

  foreach ($result as $row) {

    $row_data = array(
      l($row->qtg_no, $qtg_url . $row->qtg_event_id,
        array('query' => array('destination' => 'reports/qtg/selected'))),
      _st_format_date($row->created_date, 'short'),
      ($row->date_closed ? _st_format_date($row->date_closed, 'short') : ''),
      $simulator_list->getName($row->simulator_id),
      $row->plan_name . ', ' . $row->group_name,
    );

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

  $content = '<div id="qms-report-div">';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';

  return $content;
}

/*
 *	vendors_selected_report()
 *
 *	returns:  Tabled list of SLs based on those selected from the search list
 */
function vendors_selected_report() {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }
  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $content .= _get_vendors_report_list();
  $form_elems = drupal_get_form('report_form', 'VE');
  $content.= render($form_elems);
  return $content;
}


/*
 * _get_vendors_report_list()
 */

function _get_vendors_report_list() {


  $table_header = array(
    array( 'data' => 'Code', 'class' => 'qms-rpt-vendor-code'),
    array( 'data' => 'Name', 'class' => 'qms-rpt-vendor-name'),
    array( 'data' => 'Website', 'class' => 'qms-rpt-vendor-website'),
    array( 'data' => 'Email', 'class' => 'qms-rpt-vendor-email'),
    array( 'data' => 'Phone', 'class' => 'qms-rpt-vendor-phone'),
  );

  $saved_selected_text = '';
  $selected_cache_name = _get_qms_cache_name(QMS_VENDOR_SELECTED);

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;
  }

  $saved_selected_list = array();
  if ( strlen($saved_selected_text) ) {
    $saved_selected_list = explode(",", $saved_selected_text);
  }
  else {
    drupal_set_message(t('No selections made.  Please select shift log items to create report.'));
    $content = '<div id="qms-report-div">';

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => array(),
      'empty' => t('None Selected'),
    ));

    $content .= '</div>';

    return $content;
  }


  $query = db_select('qms_vendors', 'v');

  if ( count($saved_selected_list) ) {
    $query->where('v.vendor_id IN (:sel_list)', array(':sel_list' => $saved_selected_list));
  }

  $query->fields('v', array('vendor_id', 'code', 'name', 'website', 'email_1', 'phone_1') )
        ->orderBy('code', 'ASC');
  $result = $query->execute();

  $i = 0;
  $table_rows = array();
  $cmt_col = 0;

  foreach ($result as $row) {

    $row_data = array(
      l( $row->code, 'vendor/view/' . $row->vendor_id,
        array('query' => array('destination' => 'search/vendors/selected'))),
      l( $row->name, 'vendor/view/' . $row->vendor_id,
        array('query' => array('destination' => 'search/vendors/selected'))),
      $row->website,
      $row->email_1,
      $row->phone_1,
    );

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



  $content = '<div id="qms-report-div">';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';

  return $content;
}






/*
 * report_form()
 * adds basic buttons to the bottom of the report
 * Done and Print
 * NOT FOR DISCREPANCIES (except DEW Report)
 */
function report_form($form, &$form_state, $mode, $dest_url = '') {


  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.report.js');

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

  if ( $mode == 'ENG') {
    if( !strlen($return_url) || ($return_url == current_path()) ) {
      $return_url = 'search/engineering';
    }
  }
  else if ( $mode == 'SL') {
    if( !strlen($return_url) || ($return_url == current_path()) ) {
      $return_url = 'search/shiftlog';
    }
  }
  else if ( $mode == 'VE') {
    if( !strlen($return_url) || ($return_url == current_path()) ) {
      $return_url = 'search/vendors';
    }
  }

  else if ( $mode == 'DEW' ) {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.dew.js');
    if( !strlen($return_url) || ($return_url == current_path()) ) {
      $return_url = 'reports';
    }
  }
  else if ( $mode == 'DEWf' ) {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.dew.js');
    $return_url = 'reports/discrepancy_early_warning';
  }
  else if ( $mode == 'TC') {
    if( !strlen($return_url) || ($return_url == current_path()) ) {
      $return_url = 'search/troublecalls';
    }
  }
  else if ( $mode == 'QTG') {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.qtgexpiring.js');
    $return_url = $dest_url;
    if( !strlen($return_url) || ($return_url == current_path()) ) {
      $return_url = 'search/qtg';
    }
  }
  else if ( $mode == 'ALERTS') {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.dew.js');
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.qtgexpiring.js');
    $return_url = 'reports/alerts';
  }


  $form['return_url'] = array(
    '#type' => 'textfield',
    '#default_value' => $return_url,
    '#attributes' => array('class' => array('qms-hidden')),
  );

  $form['report_code'] = array(
    '#type' => 'textfield',
    '#default_value' => $mode,
    '#attributes' => array('class' => array('qms-hidden')),
  );


  //----------------------- FORM ACTIONS (Buttons) --------------------

  $form['actions'] = array( '#type' => 'actions');

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

  global $base_url;
  $form['actions']['print'] = array(
    '#type' => 'button',
    '#value' => t('Print'),
    '#name' => 'print',
    '#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
    '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
  );

  // storage area for dynamic dialog element
  $form['popup_dialog'] = array(
    '#markup' => '<div id="qms-message-box"></div>',
  );


  return $form;
}


/*
 *    report_form_submit()
 */

function report_form_submit($form, $form_state) {

  $return_url = isset($form_state['values']['return_url']) ?
                  $form_state['values']['return_url'] : '';

  $report_code = isset($form_state['values']['report_code']) ?
                  $form_state['values']['report_code'] : '';

  if ( 'DEWf' == $report_code ) {
    if ( isset($_SESSION['dew_selected'])) {
      unset($_SESSION['dew_selected']);
      if ($_SESSION['return_url'] == 'reports') {
        $_SESSION['return_url'] = 'reports/discrepancy_early_warning';
      }
    }
  }
  if ( 'QTG' == $report_code ) {
    if ( isset($_SESSION['qtg_selected'])) {
      unset($_SESSION['qtg_selected']);
      if ($_SESSION['return_url'] == 'reports') {
        $_SESSION['return_url'] = 'reports/qtgexpiring';
      }
    }
  }
  if ( 'ALERTS' == $report_code ) {
    $_SESSION['return_url'] = '';
  }

  if ( isset($_SESSION['return_url']) ) {
    // need to do this as destination sometimes gets overridden
    // and form doesn't retain data over several redirects
    $return_url = $_SESSION['return_url'];
    unset($_SESSION['return_url']);
    drupal_goto($return_url);
    return;
  }


  if ( strlen($return_url) ) {
    unset($_GET['destination']);
    drupal_goto($return_url);
    return;
  }

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

  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = 'reports';
  }
  drupal_goto($goto_url);
}

/*
 *	simulator_downtime_report()
 *
 */
function simulator_downtime_report($simulator_id = 0, $date_range_text = '') {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }

  // create search object + add search fields to it
  $search = new stdClass();
  $search->simulator_id = $simulator_id;
  $search->from_date = '';
  $search->to_date = '';
  if ( strlen($date_range_text) ) {
    // split date range text field (|-delimited) into from_date and to_date
    $date_range = explode("|", $date_range_text);
    $search->from_date = isset($date_range[0]) ? $date_range[0] : '';
    $search->to_date = isset($date_range[1]) ? $date_range[1] : '';
  }

  $print_page_heading =
                  '<div class="qms-print-header">' .
                    '<div class="qms-page-title">' .
                      drupal_get_title() .
                    '</div>' .
                  '</div><br />';
  $content = $print_page_heading;
  $form_elems = drupal_get_form('simulator_downtime_report_form', $search);
  $content .= render($form_elems);
  return $content;

}

/*
 *	simulator_downtime_report()
 *
 */

function simulator_downtime_report_form($form, $form_state, $search) {

  drupal_add_library('system','ui.datepicker');
  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.reportdowntime.js');

  $goto_report_url = url('reports/simulator_downtime');
  $return_url = 'reports';
  $page_title = "Simulator Downtime/Uptime";

  // Get list of simulators to display -- active + inactive
  global $simulator_list;
  global $base_url;

  $form['sd_box'] = array(
    '#type' => 'fieldset',
    '#title' => t('Report Settings'),
    '#attributes' => array( 'id' => 'qms-sd-rpt-form-div'),
    '#collapsible' => True,
    '#collapsed' => False,
  );

  $form['sd_box']['simulator_id'] = array(
    '#type' => 'select',
    '#title' => t('Select a Simulator') . ' <span>( * = ' . t('inactive') . ')</span>',
    '#options' => $simulator_list->get(),
    '#attributes' => array( 'id' => 'qms-simulator-list',
                            'class' => array('qms-select')),
    '#default_value' => $search->simulator_id,
  );


  $form['sd_box']['from_date'] = array(
    '#type' => 'date_popup',
    '#title' => t('From'),
    '#size' => 14,
    '#date_format' => 'm-d-Y',						// displayed format
      //default value has to be in this format
    '#default_value' => ( isset($search->from_date) ? $search->from_date : date('Y-m-d')),
    '#disabled' => False,
    '#attributes' => array('class' => array('qms-date-picker'),
                           'id' => 'qms-from-date'),
    '#prefix' => '<table class="qms-plain-table"><tr><td style="width:20%; text-align:left;">',
    '#suffix' => '</td>',
  );

  $form['sd_box']['to_date'] = array(
    '#type' => 'date_popup',
    '#title' => t('To'),
    '#size' => 14,
    '#date_format' => 'm-d-Y',						// displayed format
      //default value has to be in this format
    '#default_value' => ( isset($search->to_date) ? $search->to_date : date('Y-m-d')),
    '#disabled' => False,
    '#attributes' => array('class' => array('qms-date-picker'),
                           'id' => 'qms-to-date'),
    '#prefix' => '<td style="text-align:left;">',
    '#suffix' => '</td></tr></table>',
  );

  $form['sd_box']['sd_actions'] = array('#type' => 'actions');
  $form['sd_box']['sd_actions']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Submit'),
    '#attributes' => array('class' => array('qms-btn-submit'),
                           'qms-url' => $goto_report_url ),  // ajax call to get report data
  );

  $form['sd_box']['sd_actions']['clear'] = array(
      '#type' => 'button',
      '#value' => t('Clear'),
      '#attributes' => array('class' => array('qms-clear', 'qms-btn-extra')),
      '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
   );

  // simulator selected, populate the div with table data
  $content = _get_simulator_downtime_report_list($search);

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


  if ( strlen($content) ) {
    $form['actions'] = array( '#type' => 'actions' );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Done'),
      '#name' => 'done', // not the regular submit button
      '#submit' => array('report_form_submit'),
      '#attributes' => array('class' => array('qms-btn-done')),
    );
    global $base_url;
    $form['actions']['print'] = array(
      '#type' => 'button',
      '#value' => t('Print'),
      '#name' => 'print',
      '#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
      '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                    $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
    );
  }

  $form['return_url'] = array(
    '#type' => 'textfield',
    '#default_value' => $return_url,
    '#attributes' => array('class' => array('qms-hidden')),
  );


  // storage area for dynamic dialog elements
  $form['popup_dialog'] = array(
    '#markup' => '<div id="qms-message-box"></div>',
  );


  return $form;
}

/*
 *	_get_simulator_downtime_report_list()
 *
 */

function _get_simulator_downtime_report_list($search) {


  if ( !isset($search->simulator_id) || !$search->simulator_id ) {
    return '';
  }

  global $user;
  $user_is_customer_id = _user_is_customer($user->uid);

  $table_header = array(
    array( 'data' => 'SD No.', 'class' => array('qms-sd-rpt-no')),
    array( 'data' => 'DR No.', 'class' => array('qms-sd-rpt-no')),
    array( 'data' => 'Tech./Instr.'),
    array( 'data' => 'Downtime (hours)', 'class' => array('qms-sd-rpt-downtime')),
  );

  $query = db_select('qms_simulator_downtime', 'm');

  //if ( (strlen($search->from_date) > 0) && (strlen($search->to_date) > 0)) {

  // DATE RANGE REQUIRED
  // for given date range
  // out_date falls in date range OR
  // in_date falls in date range OR
  // out_date falls in or before date_range and in_date is empty
  $from = _st_format_timestamp($search->from_date . " 00:00:00");
  $to = _st_format_timestamp($search->to_date . " 23:59:59");
 
  $and_1 = db_and()->condition('out_date', $from, '>=')->condition('out_date', $to, '<=');
  $and_2 = db_and()->condition('in_date', $from, '>=')->condition('in_date', $to, '<=')->condition('in_date', 0, '>');
  $and_3 = db_and()->condition('out_date', $to, '<=')->condition('in_date', 0, '=');
  $or = db_or()->condition($and_1)->condition($and_2)->condition($and_3);
  $query->condition($or);


  $query->innerJoin('qms_discrepancy_log', 'd', 'm.discrepancy_id = d.discrepancy_id');
  //$query->innerJoin('qms_simulators', 's', 'd.simulator_id = s.simulator_id');

  if ( $user_is_customer_id ) {
    $query->condition('s.customer_id', $user_is_customer_id);
  }

  $query->condition('d.simulator_id', $search->simulator_id, '=');
  $query->leftJoin('qms_employees', 'e', 'm.tech_user_id = e.user_id');
  $query->leftJoin('users', 'u', 'u.uid = m.tech_user_id');

  $query->fields('m', array('simulator_downtime_id', 'sd_no', 'discrepancy_id', 'out_date', 'in_date', 'downtime') )
        ->fields('d', array('dr_no', 'simulator_id'))
        //->fields('s', array('sim_name', 'device_id_internal'))
        ->fields('e', array('full_name'))
        ->fields('u', array('name'))
        ->orderBy('sd_no', 'ASC');
  $result = $query->execute()->fetchAll();

  $i = 0;
  $table_rows = array();


  $total_downtime = 0.00;

  // this is a relay parameter to pass to the view links for
  // when a user wants to return to this page
  $date_range = $search->from_date . "|" . $search->to_date;
  //$sim_name = '';
  
  
  // DEBUG
//  $dt = new DateTime("now", $tz);
//  kpr($result);
  
//  $dt->setTimestamp($from);
//  kpr("from: $from ". $dt->format('Y-m-d H:i:s'));
  
//  $dt->setTimestamp($to);
//  kpr("to:  $to ". $dt->format('Y-m-d H:i:s'));
  

  foreach ($result as $row) {
    $downtime_seconds = 0;
    $downtime = 0.00;
    //if ( !strlen($sim_name) ) { $sim_name = $row->sim_name; }

    // determine how much downtime is in the date_range
    // time calc'd is in seconds

    if ( ($from < $row->out_date) && ($row->in_date < $to) ) {
      // the downtime falls completely within the report date_range
      if ( $row->in_date == 0 ) {
        // because the simulator is still out of service, calculate downtime from
        // out_date to end of date_range ($to)
        $downtime_seconds = $to - $row->out_date;
      }
      else {
        // simulator downtime falls completely within report date_range
        // and is back in service (in_date > 0)
        // use the downtime field stored with the record
        $downtime_seconds = $row->downtime;
      }
    }
    else if ( ( $from < $row->out_date ) && ( $to < $row->in_date ) ) {
      // only the out_date falls within the report date_range
      // calc from the out_date to the end of range date
      $downtime_seconds = $to - $row->out_date;
    }
    else if ( ( $row->out_date < $from ) && ( $row->in_date < $to ) ) {
      // only the in_date falls within the report date_range
      // calculate from the starting date range to the in_date
      $downtime_seconds = $row->in_date - $from;
    }
    
    $downtime = round( ($downtime_seconds / (60 * 60)), 2);
    $total_downtime += $downtime;

//    kpr($downtime_seconds);
//    kpr($downtime);
//    kpr($total_downtime);

    $row_data = array(
      l($row->sd_no, 'simulator_downtime/view/' . $row->simulator_downtime_id, array('query' =>
          array('destination' =>
            'reports/simulator_downtime/' . $search->simulator_id . '/' . $date_range)
          )),
      l($row->dr_no, 'discrepancy/view/' . $row->discrepancy_id, array('query' =>
        array('destination' =>
          'reports/simulator_downtime/' . $search->simulator_id . '/' . $date_range)
        )),
      ( (strlen($row->full_name) > 0) ? $row->full_name : $row->name . "*"),
      array('data' => sprintf("%0.2f", $downtime ), 'class' => 'qms-sd-rpt-downtime'),
          // stored in seconds, convert to hours, format for 2 decimal places
     );

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


  $total_range_hours = round( (($to - $from) / (60 * 60)), 2);
  $total_uptime = $total_range_hours - $total_downtime;

  $chart = array(
    '#chart_id' => 'simulator_downtime_chart',
    '#title' => t(' '),
    '#type' => CHART_TYPE_PIE_3D,
    '#size' => chart_size(350,200),
    '#data' => array(
      'downtime' => (int) $total_downtime/$total_range_hours * 100,
      'uptime' => (int) $total_uptime/$total_range_hours * 100,
    ),
    '#labels' => array(
      'downtime' => t('Down'),
      'uptime' => t('Up'),
    ),
  );

  global $simulator_list;

  $has_content = True;
  $content = '<div id="qms-report-div">';
  $content .= '<h3>' . $simulator_list->getName($search->simulator_id) . '</h3>';

  // This is the report pie chart
  //$content .= theme_chart(array('chart' => $chart));
  $content .= theme('chart', array('chart' => $chart));


  // This is the summary table
  $summary_header = array(
    array( 'data' => 'Summary'),
    array( 'data' => 'Values', 'class' => array('qms-sd-summary-value')),
  );

  $summary_rows = array(
    array(
      'data' => array(
        array('data' => 'Total Downtime (hours)', 'class' => array('qms-sd-summary-name')),
        array('data' => sprintf("%0.2f", $total_downtime ), 'class' => array('qms-sd-summary-value')),
      ),
    ),
    array(
      'data' => array(
        array('data' => 'Total Uptime (hours)', 'class' => array('qms-sd-summary-name')),
        array('data' => sprintf("%0.2f", $total_uptime ), 'class' => array('qms-sd-summary-value')),
      ),
    ),
    array(
      'data' => array(
        array('data' => 'TOTAL (hours)', 'class' => array('qms-sd-summary-name')),
        array('data' => sprintf("%0.2f", $total_range_hours ), 'class' => array('qms-sd-summary-value')),
      ),
    ),
    array( 'data' => array('', 'attributes' => array('colspan' => '2')), 'class' => array('qms-divrow') ),
    array(
      'data' => array(
        array('data' => 'From Date', 'class' => array('qms-sd-summary-name')),
        array('data' => $search->from_date . " 00:00:00", 'class' => array('qms-sd-summary-value')),
      ),
    ),
    array(
      'data' => array(
        array('data' => 'To Date', 'class' => array('qms-sd-summary-name')),
        array('data' => $search->to_date . " 23:59:59", 'class' => array('qms-sd-summary-value')),
      ),
    ),
  );

  $content .= theme( 'table', array(
    'header' => $summary_header,
    'rows' => $summary_rows,
    'empty' => t('None'),
    'attributes' => array('class' => array('qms-sd-summary-table')),
  ));

  // This is the simulator downtime report listings that make up the report
  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
    'attributes' => array('class' => array('qms-sd-report-table')),
  ));
  if ( $i > 0 ) {
    // display row count
    $content .= '<p class="qms-text">Total Rows: ' . $i . '</p>';
  }
  $content .= '</div>';

  return $content;
}


/*
 *	simulator_reliability_report()
 *
 */
function simulator_reliability_report($simulator_id = 0, $year = '', $hours = 0, $target = 0) {

  if ( user_access('search view reports') == FALSE ) {
    drupal_set_message(t('Unauthorized:  Permission is required'));
    return;
  }

  // create search object + add search fields to it
  $search = new stdClass();
  $search->simulator_id = $simulator_id;
  $search->year = $year;
  //$search->days = $days;
  $search->hours = $hours;
  $search->target = $target;

  $df = drupal_get_form('simulator_reliability_report_form', $search);
  return render($df);

}

/*
 *	simulator_reliability_report_form()
 *
 */

function simulator_reliability_report_form($form, $form_state, $search) {

  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.reportreliability.js');

  //variable_set('QMS_sim_availability_days', $search->days);
  if ( $search->hours ) { variable_set('qms_sim_availability_hours', $search->hours); }
  if ( $search->target ) { variable_set('qms_sim_reliability_target', $search->target); }



  $goto_report_url = url('reports/simulator_reliability');
  $page_title = "Simulator Reliability";

  // Get list of simulators to display -- active + inactive
  global $simulator_list;
  global $base_url;

  $form['report_form_box'] = array(
    '#type' => 'fieldset',
    '#title' => t('Report Settings'),
    '#attributes' => array( 'id' => 'qms-sd-rpt-form-div'),
    '#collapsible' => True,
    '#collapsed' => False,
  );


  $form['report_form_box']['format_table_begin'] = array(
    '#markup' => '<table class="qms-plain-table" style="width:80%;"><tr>',
  );

  $form['report_form_box']['simulator_id'] = array(
    '#type' => 'select',
    '#title' => t('Select a Simulator') . ' <span>(* = ' . t('inactive') . ')</span>',
    '#options' => $simulator_list->get(),
    '#attributes' => array( 'id' => 'qms-simulator-list',
                            'class' => array('qms-select')),
    '#default_value' => $search->simulator_id,
    '#prefix' => '<td colspan="2">',
    '#suffix' => '</td>',
  );

  $year_list = new YearList();

  $form['report_form_box']['year'] = array(
    '#type' => 'select',
    '#title' => t('Select a Year'),
    '#options' => $year_list->get(),
    '#attributes' => array( 'id' => 'qms-year-list',
                            'class' => array('qms-select')),
    '#default_value' => (int)$search->year,
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );

  $form['report_form_box']['format_table_title_row'] = array(
    '#markup' => '<tr><td colspan="2"><h4>' . t('Simulator Availability') . '</h4></td></tr><tr>',
  );
  /*
  $form['report_form_box']['available_days'] = array(
    '#type' => 'textfield',
    '#title' => t('Days Per Week'),
    '#size' => 1,
    '#maxlength' => 1,
    '#attributes' => array( 'id' => 'qms-available-days',
                            'class' => array('qms-numeric')),
    '#default_value' => variable_get('QMS_sim_availability_days', 7),
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  ); */

  $form['report_form_box']['available_hours'] = array(
    '#type' => 'textfield',
    '#title' => t('Hours Per Day'),
    '#size' => 1,
    '#maxlength' => 2,
    '#attributes' => array( 'id' => 'qms-available-hours',
                            'class' => array('qms-numeric')),
    '#default_value' => variable_get('qms_sim_availability_hours', 20),
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );

  $form['report_form_box']['target'] = array(
    '#type' => 'textfield',
    '#title' => t('Target %'),
    '#size' => 2,
    '#maxlength' => 2,
    '#attributes' => array( 'id' => 'qms-target',
                            'class' => array('qms-numeric'),
                            'style' => ('float:left;')),
    '#default_value' => variable_get('qms_sim_reliability_target', 98),
    '#prefix' => '<td><div>',
    '#suffix' => '</td>',
  );




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


  $form['report_form_box']['form_actions'] = array('#type' => 'actions');
  $form['report_form_box']['form_actions']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Submit'),
    '#attributes' => array('class' => array('qms-btn-submit'),
                           'qms-url' => $goto_report_url ),  // ajax call to get report data
  );

  $form['report_form_box']['form_actions']['clear'] = array(
      '#type' => 'button',
      '#value' => t('Clear'),
      '#attributes' => array('class' => array('qms-clear', 'qms-btn-extra')),
      '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' .
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
   );



  // simulator selected, populate the div with table data
  $content = _get_simulator_reliability_report_data($search);

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

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

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


  // storage area for dynamic dialog elements
  $form['popup_dialog'] = array(
    '#markup' => '<div id="qms-message-box"></div>',
  );


  return $form;
}



/*
 *	_get_simulator_reliability_report_data()
 *
 */

function _get_simulator_reliability_report_data($search) {

  try {
    if ( !isset($search->simulator_id) || !strlen($search->year) || !$search->hours) {
      return '';
    }


    $data = array();
    $table_header[] = array( 'data' => $search->year);
    $table_rows = array();
    $chart_data = array();
    $chart_labels = array();
    $now = time();
    
    $tz = _st_get_timezone();
    $now_dt = new DateTime("now", $tz);
    $begin_dt = new DateTime("now", $tz);
    $end_dt = new DateTime("now", $tz);

    // is QMS linked to connect to the Scheduler database ??
    $is_linked = variable_get(SCH_QMS_LINK, 0);

    for ($mon = 1; $mon <= 12; $mon++ ) {

      // for each month,
      // get earliest possible timestamp for 1st date of the month
      // get the last possible timestamp for the last day of the month
      $begin_dt->setDate($search->year, $mon, 1);
      $begin_dt->setTime(0, 0, 0);
      $MonYear = $begin_dt->format('F Y');
      $end_dt->modify("last day of $MonYear");
      $end_dt->setTime(23, 59, 59);
      
      $begin_date = $begin_dt->format('Y-m-d H:i:s');
      $end_date = $end_dt->format('Y-m-d H:i:s');
      
      //$s_begin_date = sprintf('%s-%02d-01 00:00:00', $search->year, $mon);
      //$begin_date = strtotime($s_begin_date);
      //$MonthYear = date('F Y', $begin_date);
      //$s_end_date = date('Y-m-d', strtotime('last day of ' . $MonthYear)) . ' 23:59:59';
      //$end_date = strtotime($s_end_date);

      $total_actual_downtime = 0;
      $total_prorated_downtime = 0;

      if ( $begin_dt < $now_dt ) {      // don't calculate for future months

        //--------- Get Utilization for this iteration month ---------------------------------

        // if possible, connect to Scheduler database
        if ( $is_linked ) {

          $utilization_time = _scheduler_get_simulator_utilization_time($search->simulator_id,
                                                                        $begin_date,
                                                                        $end_date);
          $data['utilization_hours'][$mon] = round( ($utilization_time / (60 * 60)), 2);
        }
        else {
          $data['utilization_hours'][$mon] = '--';
        }


        //----- Get all SD and TC (non-excluded) downtime reports for this iteration month ----

        $query_sd = db_select('qms_simulator_downtime', 'sd');
        $query_sd->innerJoin('qms_discrepancy_log', 'd', 'd.discrepancy_id = sd.discrepancy_id');
        $query_sd->condition('d.simulator_id', $search->simulator_id);

        $sd_and1 = db_and()->condition('sd.out_date', $begin_date, '<')
                          ->condition('sd.in_date', $end_date, '>');
        $sd_and2 = db_and()->condition('sd.in_date', $end_date, '<')
                          ->condition('sd.out_date', 0, '=');

        $sd_or = db_or()->condition('sd.out_date', array($begin_date-1, $end_date+1), 'BETWEEN')
                     ->condition('sd.in_date', array($begin_date-1, $end_date+1), 'BETWEEN')
                     //->condition($sd_and1)
                     ->condition($sd_and2);
        $query_sd->condition($sd_or);
        $query_sd->addField('sd', 'simulator_downtime_id', 'id');
        $query_sd->addfield('sd', 'out_date', 'date_opened');
        $query_sd->addfield('sd', 'in_date', 'date_closed');
        $query_sd->addExpression(':sd', 'report_type', array(':sd' => 'SD'));

        
        /**
         *  REMOVE trouble calls from downtime calculation
         *  uncertainty about what is considered downtime and what isnt
         * 
        $query_tc = db_select('qms_trouble_call_log', 'tc');
        $query_tc->condition('tc.simulator_id', $search->simulator_id);
        $query_tc->condition('tc.trouble_cause_code', 1);  // only count non-excluded TCs


        $tc_and1 = db_and()->condition('tc.date_opened', $begin_date, '<')
                          ->condition('tc.date_closed', $end_date, '>');
        $tc_and2 = db_and()->condition('tc.date_opened', $end_date, '<')
                          ->condition('tc.date_closed', 0, '=');
        $tc_or = db_or()->condition('tc.date_opened', array($begin_date, $end_date), 'BETWEEN')
                     ->condition('tc.date_closed', array($begin_date, $end_date), 'BETWEEN')
                     ->condition($tc_and1)
                     ->condition($tc_and2);
        $query_tc->condition($tc_or);
        $query_tc->addField('tc', 'trouble_call_id', 'id');
        $query_tc->fields('tc', array('date_opened', 'date_closed'));
        $query_tc->addExpression(':tc', 'report_type', array(':tc' => 'TC'));
        $query_tc->orderBy('date_opened', 'ASC')->orderBy('date_closed', 'ASC');

        $query_sd->union($query_tc, 'UNION ALL');
         * 
         */


        $result = $query_sd->execute();


        $i = 0;

        foreach ($result as $row) {
          $downtime = 0;

          $report_date_opened = $row->date_opened;
          $report_date_closed = $row->date_closed;

          if ( !$report_date_closed ) { $report_date_closed =  ST_UNIX_TIMESTAMP_LIMIT; }


          if ( $report_date_opened ) {
            // determine how much downtime is in the date_range
            // time calc'd is in seconds

            if ( ($begin_date <= $report_date_opened) && ($report_date_closed <= $end_date) ) {
              // the downtime falls completely within the report date_range
              $downtime = $report_date_closed - $report_date_opened;
            }
            else if ( ( $report_date_opened <= $begin_date ) && (  $end_date <= $report_date_closed ) ) {
              // report dates exceed the date range in both directions, only count the date range
              $downtime = $end_date - $begin_date;
            }
            else if ( ( $begin_date < $report_date_opened ) && ( $end_date < $report_date_opened ) ) {
              // only the report_date_open falls within the report date_range
              // calc from the report_date_open to the end of range date
              $downtime = $end_date - $report_date_opened;
            }
            else if ( ( $report_date_opened < $begin_date ) && ( $report_date_closed < $end_date ) ) {
              // only the report_date_closed falls within the report date_range
              // calculate from the starting date range to the report_date_closed
              $downtime = $report_date_closed - $begin_date;
            }

//            if ( 'TC' == $row->report_type ) {
//              // this is ALWAYS straight time against downtime since the intervals are expected to be short
//              $total_downtime += $downtime;
//            }
//            else if ( 'SD' == $row->report_type ) {
              // if we only determine availability at 20hrs a day, use that %
              //$prorated_downtme = $downtime * ($search->hours / 24);
              $total_actual_downtime += $downtime; 
              $total_prorated_downtime += $downtime * ($search->hours / 24);
//            }
          }
          $i++;
        }
      }


      $data['month'][$mon] = date('M', $end_date);
      $data['available_days'][$mon] = (int)date('j', $end_date);
      $data['available_hours'][$mon] = $data['available_days'][$mon] * $search->hours;

      if ( $begin_date < $now ) {
        $data['downtime_actual'][$mon] = round( ($total_actual_downtime / (60 * 60)), 2);
        $data['downtime_prorated'][$mon] = round( ($total_prorated_downtime / (60 * 60)), 2);
        $data['availability_percent'][$mon] =
          round((($data['available_hours'][$mon] - $data['downtime_prorated'][$mon]) /
            $data['available_hours'][$mon]) * 100, 2);
        $data['future'][$mon] = False;
      }
      else {
        $data['utilization_hours'][$mon] = 0;
        $data['downtime_actual'][$mon] = 0;
        $data['downtime_prorated'][$mon] = 0;
        $data['availability_pecent'][$mon] = 0;
        $data['future'][$mon] = True;
      }

      $chart_data[] = $data['availability_pecent'][$mon];
      $chart_labels[$data['month'][$mon]] = $data['month'][$mon];

      $table_header[] = array( 'data' => $data['month'][$mon]);
    }

    $table_header[] = array( 'data' => t('Total'));

    // include initial 0 to allow for 1st column of row descriptions
    $total_util = 0.00;
    $total_dta = 0.00;
    $total_dtp = 0.00;
    $total_avail = 0.00;

    for ($cat = 0; $cat < 5; $cat++) {

      for ($mon = 0; $mon <= 12; $mon++ ) {

        $cat_data = '';
        $cat_class = (($mon == 0) ? 'qms-reliability-category' : 'qms-reliability-value');

        if ( 0 == $cat) {
          if ( !$mon ) { // print the leading category title
            $cat_data = t('Utilization (hrs)');
          }
          else {
            $cat_data = ($data['future'][$mon]) ? '--' : sprintf("%0.1f", $data['utilization_hours'][$mon]);
            $total_util += $data['utilization_hours'][$mon];
          }
        }
        else if ( 1 == $cat) {
          if ( !$mon ) { // print the leading category title
            $cat_data = t('Downtime Actual (hrs)');
          }
          else {
            $cat_data = ($data['future'][$mon]) ? '--' : sprintf("%0.1f", $data['downtime_actual'][$mon]);
            $total_dta += $data['downtime_actual'][$mon];
          }
        }
        else if ( 2 == $cat) {
          if ( !$mon ) { // print the leading category title
            $cat_data = t('Downtime Prorated (hrs)');
          }
          else {
            $cat_data = ($data['future'][$mon]) ? '--' : sprintf("%0.1f", $data['downtime_prorated'][$mon]);
            $total_dtp += $data['downtime_prorated'][$mon];
          }
        }
        else if ( 3 == $cat) {
          if ( !$mon ) { // print the leading category title
            $cat_data = t('Availability (%)');
          }
          else {
            $cat_data = ($data['future'][$mon]) ? '--' : sprintf("%0.1f", $data['availability_percent'][$mon]);
            $total_avail += $data['available_hours'][$mon];
          }

        }
        else if ( 4 == $cat) {
          $cat_data = (( !$mon ) ? t('Target (%)') : sprintf("%02d", $search->target));
        }

        $table_rows[$cat]['data'][$mon] = array( 'data' => $cat_data, 'class' => array($cat_class));
      }
    }
    $total_avail_pct = round((($total_avail - $total_dtp) / $total_avail) * 100, 2);

    $table_rows[0]['data'][13] = array( 'data' => sprintf("%0.2f", $total_util),
                                        'class' => array('qms-reliability-value'));
    $table_rows[1]['data'][13] = array( 'data' => sprintf("%0.2f", $total_dta),
                                        'class' => array('qms-reliability-value'));
    $table_rows[2]['data'][13] = array( 'data' => sprintf("%0.2f", $total_dtp),
                                        'class' => array('qms-reliability-value'));
    $table_rows[3]['data'][13] = array( 'data' => sprintf("%0.2f", $total_avail_pct),
                                        'class' => array('qms-reliability-value'));
    $table_rows[4]['data'][13] = array( 'data' => sprintf("%02d", $search->target),
                                        'class' => array('qms-reliability-value'));


    /*
    drupal_add_js(array('sabreQMS' => array(
      'chart_data' => $chart_data,
      'chart_labels' => $chart_labels,
      'chart_title' => $sim_name . ' ' . t('Availability') . ' ' . $search->year,
    )), 'setting');
    drupal_add_js('https://www.google.com/jsapi', 'external');
    */

    /*
    $chart = array(
      '#chart_id' => 'simulator_availability',
      '#title' => $sim_name . ' ' . t('Availability') . ' ' . $search->year,
      '#type' => CHART_TYPE_BAR_V,
      //'#size' => chart_size(700,400),
      '#height' => 600,
      '#width' => 800,
      '#data' => $chart_data,
      '#labels' => $chart_labels,
    );*/

    global $simulator_list;
    $sim_name = $simulator_list->getName($search->simulator_id);

    $content = '<div id="qms-report-div">';
    $content .= '<h3>' . $sim_name . ' ' . t('Reliability Report'). '</h3>';
    $content .= '<p>' . date('F j, Y') . '</p>';

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => $table_rows,
      'empty' => t('None'),
      'attributes' => array('class' => array('qms-sd-reliability-table')),
    ));

    /*
    $chart['chart']['availability'] = array(
      'containerId' => 'qms_chart_availability',
      'type' => 'ColumnChart',
      'columns' => array('98.0', '98.5', '99.0', '99.5', '100'),
      'rows' => $chart_data,
      'labels' => $chart_labels,
      'options' => array(
        'forceIFrame' => False,
        'title' => $sim_name . ' ' . t('Availability') . ' ' . $search->year,
        'width' => 800,
        'height' =>600,
      ),
    );

    draw_chart($chart);
    */
    $content .= '<div id="qms_chart_availability"></div>';
    //$content .= '<div id="qms-chart-utilization>"></div>';

    // This is the report column chart
    //$content .= theme('chart', array('chart' => $chart));
    //draw_chart($chart);

    $content .= '</div>';

    return $content;
  }
  catch (Exception $e) {
    watchdog('sabreQMS', '_get_simulator_reliability_report_data()' . $e->getMessage(), array(), WATCHDOG_ERROR);
    _st_disconnect_database('sabreQMS');
  }
}
