<?php
/**
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Scheduler Home Page handlers
*/



require_once(drupal_get_path('module', 'sabreTools') . '/sabreTools.lib.inc');
require_once('sabreScheduler.classes.inc');
require_once('sabreScheduler.assignments.inc');
require_once('sabreScheduler.validator.inc');
require_once('sabreScheduler.QMS.tasks.inc');
/*
 * manager_home_page()
 *
 */
function manager_home_page() {
	
	try{
		
		   
    // is QMS linked to connect to the Scheduler database ??
		$is_linked = variable_get('sch_qms_link', 0);
	
		//------ Scheduler Grid Access ---------

		$content = '';
		
		$sl = new SimulatorList();
		$sim_list = $sl->getScheduledSimList();
		
		$sim_count = count($sim_list);
		if ( !$sim_count ) {
			drupal_set_message( t('Error: Simulators not found'), 'error');
			//drupal_goto('manage');
			$msg = "Simulator schedules have not yet been configured.  <br />" . 
              "Please visit the Manage->Simulators and Manage->Schedules pages.";
			return $msg;
		}
		
		
		//---------- create list of simulator links for easy access -----------------
		$content .= _create_simulator_grid_links($sl);
		
		$itoday = _st_format_timestamp('now');
    $begin_date_ts = _format_timestamp($itoday, '00:00:00');
    $end_date_ts = _format_timestamp($itoday, '23:59:59', '', '+1 day');
    
    
		$table_header = array( 
			array( 'data' => t('Session'), 'class' => array('sch-tbl-assignment-session') ),
      array( 'data' => t('Time'), 'class' => array('sch-tbl-assignment-time') ),
			array( 'data' => t('Customer'), 'class' => array('sch-tbl-assignment-customer') ),
			array( 'data' => t('Type'), 'class' => array('sch-tbl-assignment-type') ),
      array( 'data' => t('Options'), 'class' => array('sch-tbl-assignment-options') ),
		);
		
		
    //----------------- LOOP - all simulators -----------------
		for ( $s = 0; $s < $sim_count; $s++ ) {
      
      $schedule = _get_schedule($sim_list[$s]->schedule_id);
      # Skip schedules that aren't in effect (expired or future)
      if (!empty($schedule) && 
            (($itoday < $schedule->begin_date) || 
             (($schedule->end_date > 0) && ($schedule->end_date < $itoday))) ) {   
        continue;
      }
      
			// get the schedule_sessions for this simulator schedule
			$sessions = _get_sessions($sim_list[$s]->schedule_id);
			
			// get assignments
			$assignments = _get_assignments($begin_date_ts, $end_date_ts, $sim_list[$s]->schedule_id);
      
			$i = 0;
			$table_rows = array();
			$sessValidator = new SessionValidator();
      $timezone = $schedule->timezone;
			
      
      //----------------- LOOP - all sessions -----------------
      
			foreach($sessions as $sess) {
        
				$class = 'sch-normal';
				$blocked = False;

				$day = _st_format_schedule_date($itoday, 'j', $timezone);
        
        $sess_begin_ts = _format_timestamp($itoday, $sess->begin_time, $timezone);
        $sess_end_ts = _format_timestamp($itoday, $sess->end_time, $timezone);
        if ( (int)$sess->begin_time > (int)$sess->end_time) {
          $sess_end_ts = _st_modify_system_timestamp($sess_end_ts, '+1 day', $timezone);
        }

        $sessValidator->clear();
				$sessValidator->init(0, 0, $sess->schedule_id, $sess->schedule_session_id, 
                                  $itoday, $sim_list[$s]->simulator_id, $timezone);
				$sessValidator->setSession($sess);
				//$sessValidator->setExceptions($exceptions);
				$row_data = array();
				
				$blocked = (SessionValidator::SV_BLOCKED == $sessValidator->checkForConflictWithException());
				
        if ( $blocked ) {  
          $class = 'sch-blocked';  
        }
        else {
          $now = REQUEST_TIME;
          if ( ($sess_begin_ts <= $now) && 
               ($now < $sess_end_ts)) {
            $class = 'sch-session-now';
          }
        }
        
				if ( !empty($assignments[$sess->schedule_session_id][$day]) ) {
          
          $n = 0;
          foreach($assignments[$sess->schedule_session_id][$day] as $assign) {
					
            $row_data = array(  
              // only list once per all assigns for session
              ((!$n) ? $assign->session_name : ''), 
              '[ ' . $assign->begin_time_actual . 
                  ' - ' .  $assign->end_time_actual . ' ]',
              ($blocked ? t('BLOCKED') . ":  " :  '') . $assign->customer . 
                ($assign->group_id  ?  ': ' . $assign->group_name : ''),
              $assign->session_type_desc,
              l(t('E-Log'), 'elog/assign/' . $assign->assignment_id, 
                        array('attributes' => array('class' => array('sch-elog-link')),
                              'query' => array('destination' => 'manager/home')) ),
            );
            $table_rows[] = array('data' => $row_data, 'class' => array($class));
            $n++;
          }
				}
				else {
					$reasons = $sessValidator->getExceptionReasons();
					$row_data = array(
						$sess->session_name, 
            '[ ' . $sess->begin_time . ' - ' . $sess->end_time . ' ]',
						( $blocked ? t('BLOCKED') . ': ' . $reasons : t('Open') ) ,
						'',
            '',
					);
          $table_rows[] = array('data' => $row_data, 'class' => array($class));
				}
				
				
				$i++;
			}  // end loop Sessions
      
      
      $content .= '<div class="sch-todays-sessions-div">';
			
      // get the Simulator Operational Status from QMS
      
      if ( $is_linked ) {
        $sim_id = $sim_list[$s]->simulator_id;
        $sim_status = _qms_simulator_get_status($sim_id);
        $sim_name = $sl->getName($sim_id); // getName returns the formatted sim name

        $content .= 
           '<h3>' . l($sim_name . " : " . $sim_list[$s]->schedule_name, 
                      'schedule/grid/' . $sim_list[$s]->simulator_id . '/' . $sim_list[$s]->schedule_id,
                       array('query' => array('destination' => 'manager/home'))) . 
           '</h3>';

        $content .= _format_simulator_status_block($sim_list[$s]->simulator_id, $sim_status);
      }
			
      
				
			$content .= theme( 'table', array(
				'header' => $table_header,
				'rows' => $table_rows,
				'empty' => t('None'),
			));
			$content .= '<br /></div>';
		
		} // end loop Simulators
	
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, 'manager_home_page() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}

}



/*
 * 	current_schedule()
 *
 *	Displays a basic home page of ALL sim schedules for the day
 *  if user is linked to a simulator, only displays schedule for that sim
 *
 */

function current_schedule() {
	
	try{
    
    drupal_add_js(drupal_get_path('module', 'sabreScheduler') . '/js/sabreScheduler.refresh.js');

		
    $user_simulator_id =  _get_user_simulator_id();
    
		
        // is QMS linked to connect to the Scheduler database ??
		$is_linked = variable_get('sch_qms_link', 0);
	
		//------ Are there simulators configured? ---------

		$content = '';
		
		$sl = new SimulatorList();
		$sim_list = $sl->getScheduledSimList();
		
		$sim_count = count($sim_list);
		if ( !$sim_count ) {
			drupal_set_message( t('Error: Simulators not found'), 'error');
			//drupal_goto('manage');
			$msg = "Simulator schedules have not yet been configured.  <br />" . 
              "Please visit the Manage->Simulators and Manage->Schedules pages.";
			return $msg;
		}
		
		$itoday = _st_format_system_timestamp('now');
		$today = _st_format_system_date($itoday, 'Y-m-d');
    
    $begin_date_ts = _format_timestamp($itoday, '00:00:00', '', '-6 hours');
		$end_date_ts = _format_timestamp($itoday, '23:59:59', '','+6 hours');
    
    
//    echo "today: $today\n";
//    echo "begin_date_ts: $begin_date_ts\n";
//    echo "end_date_ts: $end_date_ts\n";

	
		$table_header = array( 
			array( 'data' => t('Session'), 'class' => array('sch-tbl-assignment-date') ),
      array( 'data' => t('Time'), 'class' => array('sch-tbl-assignment-time') ),
			array( 'data' => t('Customer'), 'class' => array('sch-tbl-assignment-customer') ),
			array( 'data' => t('Type'), 'class' => array('sch-tbl-assignment-type') ),
      array( 'data' => t('Options'), 'class' => array('sch-tbl-assignment-options') ),
		);
		
		
		//$content .= '<div id="sch-todays-sessions-div">';
		
		
    //----------------- LOOP - all simulators -----------------
    //  If user is linked to a simulator, only show that sim's schedule
    
    
    
		foreach($sim_list as $sim) {
      
      if ( ($user_simulator_id > 0) && 
           ($user_simulator_id != $sim->simulator_id) ) {
        continue;
      }
      
      
			// get the schedule_sessions for this simulator schedule
			$sessions = _get_sessions($sim->schedule_id);
			
			// get assignments
			$assignments = _get_assignments($begin_date_ts, $end_date_ts, $sim->schedule_id);
//      echo "assignments:  ".count($assignments)."<br>\n";
//      echo "begin_date_ts:  $begin_date_ts<br>\n";
//      echo "end_date_ts:  $end_date_ts<br>\n";
			
			$i = 0;
      $d = 0;
			$table_rows = array();
			$sessValidator = new SessionValidator();
			
      
      //----------------- LOOP - all sessions -----------------
      $idaystart = ($itoday-SCH_ONE_TS_DAY);
      $dt = new DateTime();
      $dt->setTimezone(new DateTimeZone($sim->timezone));
      
      
      for($iday=($itoday-SCH_ONE_TS_DAY); $iday <= $itoday; $iday+=SCH_ONE_TS_DAY) {
        $d = 0;
      
        foreach($sessions as $sess) {

          
          $class = 'sch-normal';
          $blocked = False;

          $day = _st_format_schedule_date($iday, 'j', $sim->timezone);
          
          //echo "current_schedule()";
          
          $sess_begin_ts = _format_timestamp($iday, $sess->begin_time, $sess->timezone);
          $sess_end_ts = _format_timestamp($iday, $sess->end_time, $sess->timezone);
          if ( (int)$sess->begin_time > (int)$sess->end_time) {
            //echo "sess_end_ts: $sess_end_ts<br>\n";
            //echo "timezone: ".$sess->timezone."<br>\n";
            //echo "+1 day<br>\n";
            //$sess_end_ts = _st_format_schedule_timestamp($sess_end_ts, $sess->timezone, '+1 day');
            $sess_end_ts = _st_modify_system_timestamp($sess_end_ts, '+1 day', $sess->timezone);
          }
          
          // only display sessions within the current date range
          if ( $begin_date_ts <= $sess_begin_ts ) {
            
            if ( !$d ) {
              // display this session, add a date label
              $row_data = array(
                '<b>' . _st_format_schedule_date($iday, 'm/d/Y', $sim->timezone) . '</b>',
                '&nbsp;',
                '&nbsp;',
                '&nbsp;',
                '&nbsp;',
              );
              $table_rows[] = array('data' => $row_data, 
                                  'class' => array('sch-normal'));
              $d++;
            }

            $sessValidator->clear();
            $sessValidator->init(0, 0, $sess->schedule_id, 
                                       $sess->schedule_session_id, 
                                      $iday, $sim->simulator_id);
            $sessValidator->setSession($sess);
            //$sessValidator->setExceptions($exceptions);
            

            $blocked = (SessionValidator::SV_BLOCKED == 
                              $sessValidator->checkForConflictWithException());

            if ( $blocked ) {  
              $class = 'sch-blocked';  
            }
            else {
              $now = REQUEST_TIME;
              if ( ($sess_begin_ts <= $now) && 
                   ($now < $sess_end_ts)) {
                $class = 'sch-session-now';
              }
            }

            if ( !empty($assignments[$sess->schedule_session_id][$day]) ) {

              $n = 0;
              foreach($assignments[$sess->schedule_session_id][$day] as $assign) {
              //$assign = $assignments[$sess->schedule_session_id][$day];
                
                
                $sess_name = ((!$n) ? $assign->session_name : '');
                
                //print_r($assign);
                
                $row_data = array(  
                  // only list once per all assigns for session
                  '<span class="sch-indent">' . $sess_name . '</span>',
                  '[ ' . $assign->begin_time_actual . 
                      ' - ' .  $assign->end_time_actual . ' ]',
                  ($blocked ? t('BLOCKED') . ":  " :  '') . $assign->customer . 
                    ($assign->group_id  ?  ': ' . $assign->group_name : ''),
                  $assign->session_type_desc,
                  l(t('E-Log'), 'elog/assign/' . $assign->assignment_id, 
                     array('attributes' => 
                                   array('class' => array('sch-elog-link')),
                        'query' => array('destination' => 'user/home')) ),
                );
                $table_rows[] = array('data' => $row_data, 
                                      'class' => array($class));
                $n++;
              }
            }
            else {
              $reasons = $sessValidator->getExceptionReasons();
              $row_data = array(
                '<span class="sch-indent">' . 
                    $sess->session_name . '</span>', 
                '[ ' . $sess->begin_time . ' - ' . $sess->end_time . ' ]',
                ( $blocked ? t('BLOCKED') . ': ' . $reasons : t('Open') ) ,
                '',
                '',
              );
              $table_rows[] = array('data' => $row_data, 'class' => array($class));
            }
          }


          $i++;
        }  // end loop Sessions
      }
      
      
      $content .= '<div class="sch-todays-sessions-div">';
			
      // get the Simulator Operational Status from QMS
      if ( $is_linked ) {
        $sim_id = $sim->simulator_id;
        $sim_status = _qms_simulator_get_status($sim_id);
        $sim_name = $sl->getName($sim_id); // getName returns the formatted sim name

        $content .= 
           '<h3>' . l($sim_name . " : " . $sim->schedule_name, 
                      'schedule/grid/' . $sim->simulator_id . '/' . $sess->schedule_id,
                       array('query' => array('destination' => 'user/home'))) . 
           '</h3>';

        $content .= _format_simulator_status_block($sim->simulator_id, 
                                                   $sim_status, 
                                                   'user/home');
      }
			
				
			$content .= theme( 'table', array(
				'header' => $table_header,
				'rows' => $table_rows,
				'empty' => t('None'),
			));
			$content .= '<br /></div>';
		
		} // end loop Simulators
	
		return $content;
    
	}
	catch(Exception $e) {
    echo "Exception";
    var_dump($e->getTraceAsString());
		watchdog(SCH_SCHEDULER, 'current_schedule() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}







/*
 * 	kiosk_home_page()
 *
 *	Displays a Welcome and a list of buttons for users to 
 *  select from for their company affiliation
 *
 */
/*
function kiosk_home_form($form, $form_state) {
	
  if ( user_access('access sabreScheduler') == FALSE ) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
    return;
  }

  $content = '';
  $customer_list = _get_customer_select_list();

  if ( !count($customer_list) ) {
    $form['message'] = array(
      '#markup' => '<h1>' . t('Customer accounts have not been configured.') . '</h1>',
    );
  }
  else {
    $form['message'] = array(
      '#markup' => '<h1>' . t('Please select your company') . '</h1>',
    );
    $i = 0;
    $form['actions'] = array('#type' => 'actions');
    foreach($customer_list as $id => $c) {
      if ( $id > 1) {
        // do not include host company or ' Select -' option
        $form['actions']['button_' . $id] = array(
          '#type' => 'submit',
          '#value' => $c,
          '#name' => $id,
          '#attributes' => array('class' => array('sch-btn-kiosk')),
        );
      }
    }
  }

  return $form;

}

function kiosk_home_form_submit($form, $form_state) {
  
  $customer_id = (int)$form_state['triggering_element']['#name'];
  
  drupal_goto('user/home/' . $customer_id);
}
*/


/*
 * 	user_home_page()
 *
 *	Displays a customer's schedule for today only
 *
 */
/*
function user_home_page($customer_id = 0, $called_by_pager = False) {
	
	try{

		if ( user_access('access sabreScheduler') == FALSE ) {
	    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
			return;
	  }
    
    $user_customer_id =  _get_user_customer_id();
    $bKioskMode = (( $user_customer_id == 1 ) && user_access('kiosk mode'));

		$begin_date_range = strtotime('- 24 hours', REQUEST_TIME);
		$end_date_range = strtotime('+ 2 hours', REQUEST_TIME);
		$title = 'Current Sessions';
    $pager_url = 'user/home/pager';
		
		// Turns on access to E-Logs & changes sorting
		$current_sessions = True;

		$content = '<h3>' . t($title) . '&nbsp;&nbsp;&bull;&nbsp;&nbsp' . 
                     l(t('90-Day Schedule'), 'user/view90days/' . $customer_id, 
                        array('class' => array('sch-view90days'))) . 
                     ( $bKioskMode ?  '&nbsp;&nbsp;&bull;&nbsp;&nbsp' . 
                     l(t('Done'), 'kiosk', 
                        array('class' => array('sch-kiosk'))) : '') . 
                '</h3><hr />';
    
    
    if ( $bKioskMode ) {
      drupal_add_js(drupal_get_path('module', 'sabreScheduler') . 
                        '/js/sabreScheduler.kioskreset.js');
      $content .= '<div id="qms-kiosk-url" class="qms-hidden">' . url('kiosk') . '</div>';
    }
		
		$content .= _get_user_schedule($customer_id, $begin_date_range, $end_date_range, 
                                    $title, $current_sessions, $called_by_pager, $pager_url);
		
		return $content;

	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, 'user_home_page() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}
 * */
 



/*
 * user_upcoming_schedule_display()
 *
 *	Displays a customer's schedule for tomorrow through 90 days
 */
/*
function user_upcoming_schedule_display($customer_id = 0, $called_by_pager = False) {
	
	try{
		
		if ( user_access('access sabreScheduler') == FALSE ) {
	    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
			return;
	  }
    // host customer is always 1
    $user_customer_id = _get_user_customer_id();
    //$bKioskMode = (( $user_customer_id == 1 ) && user_access('kiosk mode'));
	
		$begin_date_range = REQUEST_TIME;
		$end_date_range = strtotime('+ 90 days', REQUEST_TIME);
		$title = t('90-Day Schedule');
		$current_sessions = False;
    $pager_url = 'user/view90days/pager';
    
    $content = '<h3>' . l(t('Current Sessions'), 'user/home/' . $customer_id, 
                            array('class' => array('sch-user-home'))) . 
                    '&nbsp;&nbsp;&bull;&nbsp;&nbsp' .  $title . 
                    ( $bKioskMode ? '&nbsp;&nbsp;&bull;&nbsp;&nbsp' .  
                        l(t('Done'), 'kiosk', 
                            array('class' => array('sch-kiosk'))) : '') . 
                '</h3><hr />';
    
//    if ( $bKioskMode ) {
//      drupal_add_js(drupal_get_path('module', 'sabreScheduler') . 
//                        '/js/sabreScheduler.kioskreset.js');
//      $content .= '<div id="qms-kiosk-url" class="qms-hidden">' . url('kiosk') . '</div>';
//    }
		
		$content .= _get_user_schedule($customer_id, $begin_date_range, $end_date_range, 
                                  $title, $current_sessions, $called_by_pager,
                                  $pager_url);
		
		return $content;
		
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, 'user_upcoming_schedule_display() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}
 * */
 


/*
 * user_upcoming_schedule_display()
 *
 *	Displays a customer's schedule for a supplied unixtime date range
 */
function _get_user_schedule($customer_id = 0, $begin_date_range = 0, $end_date_range = 0, 
														$sched_title = '', $current_sessions = False, 
                            $called_by_pager = False, $pager_url = 'user/home/pager') {
	
	try{
		
		if ( !$begin_date_range || !$end_date_range ) {
			drupal_set_message( t('Invalid date range'), 'error');
			return "";
		}
		if ( !strlen($sched_title) ) {
			drupal_set_message( t('Invalid Schedule Title'), 'error');
			return "";
		}
    
    // is QMS linked to connect to the Scheduler database ??
		$is_linked = variable_get('sch_qms_link', 0);
		
	
		global $user;
			
		$table_header = array( 
			array( 'data' => t('Session'), 
             'field' => 'begin_timestamp', 
             'sort' => 'desc', 
             'class' => array('sch-tbl-assignment-date') 
          ),
			array( 'data' => t('Group'), 
             'field' => 'group_name', 
             'sort' => 'asc', 
             'class' => array('sch-tbl-assignment-group') 
          ),
			array( 'data' => t('Type'), 
             'field' => 'session_type_desc', 
             'sort' => 'asc', 
             'class' => array('sch-tbl-assignment-type') 
          ),
		);
		
		if ( $current_sessions ) {
			$table_header[] = array( 'data' => t('Options'), 
                               'class' => array('sch-tbl-assignment-options') );
		}
    else {
      $table_header[] = array( 'data' => t('Simulator'), 
                              'field' => 'sim_name', 
                              'sort' => 'asc', 
                              'class' => array('sch-tbl-assignment-simulator'), 
                           );
    }
		
		
		$num_per_page = 100;
		
		$search_init = array(
			'table_name' => 'sch_assignments',
			'table_alias' => 'a',
			'table_header' => $table_header,
			'pager_path' => $pager_url . ($customer_id ? '/' . $customer_id : ''),
			'order' => 'begin_timestamp',
			'sort' => 'asc',
			'variable' => False,
			'num_records' => $num_per_page, // just for this request
		);

		$query = _st_setup_paged_search($search_init);
	
	
		//--------- Add Conditions ---------------
		$query->innerJoin('sch_schedules', 'sch', 'a.schedule_id = sch.schedule_id');
		$query->innerJoin('sch_simulators', 'si', 'sc.simulator_id = si.simulator_id');
		$query->innerJoin('sch_session_types', 't', 'a.session_type = t.session_type');
		$query->innerJoin('sch_customers', 'c', 'a.customer_id = c.customer_id');
		$query->leftJoin('sch_groups', 'g', 'a.group_id = g.group_id');
    
    if ( $customer_id ) {
      $query->condition('c.customer_id', $customer_id);
    }
    else {
      // use the logged-in user/customer_id
      $query->innerJoin('sch_users', 'u', 'c.customer_id = u.customer_id');
      $query->condition('u.user_id', $user->uid);
    }
		
		$query->condition('a.cut_bill', 0); // do not include cut_bill'ed assignments
		$query->condition('a.begin_timestamp', $begin_date_range, '>=');
		$query->condition('a.begin_timestamp', $end_date_range, '<=');
    
		$query->fields('a', array('assignment_id', 'begin_time_actual', 'end_time_actual', 
                              'customer_id', 'group_id', 'session_type'))
            ->fields('si', array('simulator_id', 'sim_name', 'device_id_internal'))
						->fields('t', array('session_type_desc'))
						->fields('c', array('customer'))
						->fields('g', array('group_name'));
    
    if ( $current_sessions ) {
      // this is for the current sessions display
      // we need to sort this by simulator
      $query->orderBy('sim_name')->orderBy('begin_time_actual', 'ASC');
    }
    else {
      // this is for the 90-day display
      // we will sort this by assignment date
      $query->orderBy('begin_time_actual', 'ASC');
    }
		
	
		$max_count = 0;
		$results = _st_execute_paged_search($query, $max_count, $num_per_page);						
												
									
		$i = 0;
    $sim_list = array();
		$table_rows[] = array();
		//$customer_id = 0;
		$customer_name = '';
		$user_group_name = '';
    
	
		foreach ($results as $row) {
      
			if ( !$customer_id ) { 
				$customer_id = $row->customer_id; 
				$customer_name = $row->customer;
			}
		
      if ( $current_sessions ) {
        $row_data = array(
          _st_format_system_date($row->begin_timestamp, 'm/d/Y') . 
              ' &nbsp; [ ' . $row->begin_time_actual . ' - ' . 
                              $row->end_time_actual . ' ]',
          $row->group_name,
          $row->session_type_desc,
          l(t('E-Log'), 'elog/assign/' . $row->assignment_id, 
											array('attributes' => array('class' => array('sch-elog-link')),
                            'query' => array('destination' => 'user/home/' . 
                                                              $customer_id)) 
          ),
        );
        // these get split up and displayed in separate tables by sim
        $sim_list[$row->simulator_id] = _st_format_sim_name($row->sim_name, $row->device_id_internal);
        $table_rows[$row->simulator_id][] = array('data' => $row_data);
      }
      else {
        
        // 90 day report - sorted by date
        $row_data = array(
          _st_format_system_date($row->begin_timestamp, 'dateonly') . 
              ' &nbsp; [ ' . $row->begin_time_actual . ' - ' . $row->end_time_actual . ' ]',
          $row->group_name,
          $row->session_type_desc,
          _st_format_sim_name($row->sim_name, $row->device_id_internal),
        );
        // these get displayed in a single table
        $table_rows[0][] = array('data' => $row_data);
      }
			
			
			$i++;
		}
	
		/*
		if ($i) {
			$user_group_name = _get_customer_user_group_name($customer_id, $user->uid); 
			if (strlen($user_group_name)) { $user_group_name = t('Group:  ') . $user_group_name;  }
		}*/
		//$user_name = _get_sch_user_name($user->uid);
		//$content .= $user_name . '<br />' . $user_group_name;
	
		//$content = '<div id="sch-search-results-div">';
    $content = '';
    
    if ( $current_sessions ) {
      foreach($sim_list as $sim_id => $sim_name) {

        $content .= '<h3>' . $sim_name . '</h3>';

        if ( $is_linked ) {
          // get the current sim status from QMS, if the apps are linked
          $sim_status = _qms_simulator_get_status($sim_id);
          $content .= _format_simulator_status_block($sim_id, $sim_status, 
                                                      $customer_id);
        }
        
        $content .= theme( 'table', array(
          'header' => $table_header,
          'rows' => $table_rows[$sim_id],
          'empty' => t('None'),
        ));

      }
      
      if (!count($sim_list)) {
        // no sims to display listings for, just display an empty table
        $content .= theme( 'table', array(
          'header' => $table_header,
          'rows' => array(),
          'empty' => t('None'),
        ));
      }
    }
    else {
      
      $content .= '<h3>' . t('All Simulators - Next 90 Days') . '</h3>';
      
      $content .= theme( 'table', array(
        'header' => $table_header,
        'rows' => $table_rows[0],
        'empty' => t('None'),
      ));

      //Append pager:  http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager
      $content .= theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
    }
    
		//$content .= '</div>';
		
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_user_schedule() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}




/*
 *		_create_simulator_grid_links()
 *		IN:  SimulatorList object (optional), if not passed in, will be retrieved in function
 *		OUT:  formatted text markup
 */
function _create_simulator_grid_links($sl = Null) {
	if ( !isset($sl) ) {
		$sl = new SimulatorList();
	}
	
	
	//---------- create list of simulator links for easy access -----------------
	$link_list = array();
  
  try {
    
    $scheduled_simulators = $sl->getScheduledSimList();
  
    foreach($scheduled_simulators as $s) {
      $key = $s->simulator_id . '|' . $s->schedule_id;
      $value = $s->sim_name . '[' . $s->schedule_name . ']';
      $select_opts[$key] = $value;
    }
  
    foreach($scheduled_simulators as $s) {
      $name = $s->sim_name.' : '.$s->schedule_name;
      $link_list[] = l($name, 'schedule/grid/' . $s->simulator_id . '/' . $s->schedule_id, 
                      array('query' => array('destination' => 'manage'))) . '</span>';
    }
    return '<div class="sch-sim-links"><span class="sch-prefix-text">' . t('View Grid') . ':</span>' . 
                      implode('<span class="sch-bull-sep">&bull;</span>', $link_list) . '</div><hr />';
  }
  catch(Exception $ex) {
    
  }
  
	
}



