<?php
/**
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Scheduler E-Log handlers
*/


require_once('sabreScheduler.classes.inc');
require_once(drupal_get_path('module', 'sabreTools') . '/sabreTools.lib.inc');


define('SCH_MAX_CREW_COUNT', 7);
define('SCH_CREW_PILOT', 1);
define('SCH_CREW_PILOT_2ND', 2);
define('SCH_CREW_INSTRUCTOR', 3);
// remaining flight roles don't affect functioning, stored as selected


function elogs_search() {
	
	if ( user_access('view manage menu') == FALSE ) {
		drupal_set_message( t('Unauthorized.  Permission is required.'), 'status');
		drupal_goto('');
		return '';
  }
	
	drupal_add_library('system','ui.dialog');
	drupal_add_library('system','ui.datepicker');
  
  // see http://digitalbush.com/projects/masked-input-plugin/
	drupal_add_js(drupal_get_path('module', 'sabreScheduler') . '/js/vendor/jquery.maskedinput-1.3.1.min.js');
  
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreScheduler') . '/js/sabreScheduler.elogs.search.js');


	$form_cache_name = SCH_ELOGS_SEARCH_FORM;

	$search_form = '';
	$search_results = '';
	
	
	$form_cache = cache_get($form_cache_name);
	if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
		$search_form = $form_cache->data;
	}
	else {
	
		// search results not in cache, create empty div for ajax to populate after search
		// search results will get populated to cache after ajax call
    $df = drupal_get_form('elogs_search_form');
		$search_form = render($df);
	
		//maintains cache entry for the form for 20 min before refresh (time in seconds)
		cache_set($form_cache_name, $search_form, 'cache', REQUEST_TIME + QMS_CACHE_TIMEOUT);			
	}	
	

	// determine cache name
	$results_cache_name = _get_scheduler_cache_name(SCH_ELOGS_SEARCH_RESULTS);	

	$results_cache = cache_get($results_cache_name);
	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$search_results = $results_cache->data;
	}
	else {
		// search results not in cache, create empty div for ajax to populate after search
		// search results will get populated to cache after ajax call
		$search_results = '<div id="sch-search-results-div"></div>';
		
		cache_set($results_cache_name, $search_results, 'cache', REQUEST_TIME + QMS_CACHE_TIMEOUT);			
	}
	
	$content = $search_form . $search_results;
	
	// text strings for multilang handling, positional, pipe-delim
	$content .= '<div id="sch-strings" class="qms-hidden">' . 
									t('OK') . '|' . 
									t("Server Request Error") . '|' . 
									t('The server has experienced an error.  Please refresh the page and try again.') . '|' . 
									t('The server has experienced an error.  Please refresh the page and try again.') . '|' . 
									t("The server request has timed out.  Please refresh the page and try again.") . 
							'</div>';
	
	
	return $content;
}

/*
 * 	elogs_search_form()
 * 	display form to get user input of search parameters
 *
 */

function elogs_search_form($form, $form_state) {
	
		//------------ BUILD SEARCH FORM ------------------
		global $base_url;

		$simulator_list = new SimulatorList();
    $customer_list = new CustomerList();
    $session_list = new SessionNameList();
		

		$form['search'] = array(
			'#type' => 'fieldset',
			'#title' => t('Search'),
			'#collapsible' => True,
			'#collapsed' => False,
			'#attributes' => array('id' => array('sch-search-div')),
		);
		
		$form['search']['search_table_begin'] = array(
			'#markup' => '<table class="qms-plain-table"><tr><td rowspan="3" style="width:40%;">'
		);
    
    $form['search']['el_no'] = array(
      '#type' => 'textfield',
      '#title' => t('EL No.'),
      '#default_value' => 'EL',
      '#size' => 15,
      '#attributes' => array('id' => 'sch-el-no'),
    );
		

		$form['search']['simulator'] = array(
			'#type' => 'select',
			'#title' => t('Simulator'),
			'#options' => $simulator_list->getAll(),
			'#default_value' => 0,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-simulator-list'),
		);

		$form['search']['customer'] = array(
			'#type' => 'select',
			'#title' => t('Customer'),
			'#options' => $customer_list->getAll(),
			'#default_value' => 0,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-customer-list'),
		);
    
    $form['search']['sim_quality'] = array(
			'#type' => 'select',
			'#title' => t('Simulator Quality'),
			'#options' => array(
                      0 => '- ' . t('Select') . ' -',
                      1 => t('Deficient'),
                      2 => t('Unsatisfactory'),
                      3 => t('Satisfactory'),
                      4 => t('Good'),
                      5 => t('Excellent'),
                    ),
			'#default_value' => 0,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-sim-quality-list'),
		);
		
		
		$form['search']['table_markup1'] = array(
			'#markup' => '</td><td style="vertical-align:top">',
		);
		
		
		$form['search']['search_date_label'] = array(
			'#markup' => '<label style="padding-bottom:8px">' . 
                    t('Search E-Logs by Date Range') . '</label></td></tr>',
		);
		


		$form['search']['from_date'] = array(
			'#type' => 'date_popup',
			'#title' => t('From Date'),
			'#size' => 10,
			'#date_format' => 'm-d-Y',					 	
			'#attributes' => array('style' => array('float:left', 'width:50px'),
															'id' => 'sch-from-date',
															'class' => array('qms-date-picker')),
			'#prefix' => '<tr><td style="display:inline-block;text-align:left;">',
			//'#suffix' => '</td>',
		);

		$form['search']['to_date'] = array(
			'#type' => 'date_popup',
			'#title' => t('To Date'),
			'#size' => 10,
			'#date_format' => 'm-d-Y',
			'#attributes' => array('style' => array('float:left', 'clear:right', 'width:50px'),
															'id' => 'sch-to-date',
																'class' => array('qms-date-picker')),
			//'#prefix' => '<td>',
			'#suffix' => '</td></tr>',
		);
    
    $form['search']['sessions'] = array(
			'#type' => 'select',
			'#title' => t('Session'),
			'#options' => $session_list->get(),
			'#default_value' => 0,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-session-list'),
      '#prefix' => '<tr><td>',
			'#suffix' => '</td></tr>',
		);

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


		//--------------------------------------------
		// Adds a simple submit button that refreshes the form and clears its contents 
		// -- this is the default behavior for forms.
		$form['search']['actions'] = array('#type' => 'actions');
		$form['search']['actions']['submit'] = array(
			'#type' => 'button',
			'#value' => 'Search',
			'#attributes' => array('id' => 'sch-btn-search',
															'sch-url' => url('elogs/search') ),
	/*	DO NOT do Drupal AJAX here, being done through JQuery by the javascript file
	**	as we need the .live("click") function due to form caching, which won't work here with Drupal
	*/
		);
    $form['search']['actions']['clear'] = array(
      '#type' => 'button',
      '#value' => t('Clear'),
      '#attributes' => array('class' => array('sch-clear', 'qms-btn-extra'),
                             'id' => 'sch-btn-clear',
                             'sch-url' => url('elogs/clear') ),
      '#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="sch-popup-dialog"></div>',
		);
		
		

		return $form;
}

/**
 * elogs_search_callback()
 * displays the search results, first page only
 * Has to be a separate handler from pager & sort link callback
 * This is the callback that gets called when the Search button is clicked
 *
 */
function elogs_search_callback() {
	
	$search = new stdClass();
  
	$search->el_no = trim($_POST['el_no']);
	$search->simulator_id = (int)$_POST['simulator'];
  $search->customer_id = (int)$_POST['customer'];
	$search->from_date = trim($_POST['from_date']);
	$search->to_date = trim($_POST['to_date']);
	$search->sim_quality = (int)$_POST['sim_quality'];
	$search->session_name_id = (int)$_POST['session'];
	
	// cache the latest search key
	// determine cache name, always use it specific to this user + session
	// set key cache to expire in 30 minutes
	$key_cache_name = _get_scheduler_cache_name(SCH_ELOGS_SEARCH_KEY);
	
	cache_set($key_cache_name, $search, 'cache', REQUEST_TIME + QMS_CACHE_TIMEOUT);		

	die(_get_elogs_search_list($search));
}


/**
 * elogs_pager_callback()
 * displays the search results, for subsequent page results
 * Has to be a separate handler from pager & sort link callback
 * This is the callback that gets called when the page number links are clicked
 *
 */
function elogs_pager_callback() {
	
	$search = new stdClass();
	
	// determine the key cache
	$key_cache_name = _get_scheduler_cache_name(SCH_ELOGS_SEARCH_KEY);
	
	$key_cache = cache_get($key_cache_name);
	if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
		$search = $key_cache->data;
	}
	else {
		// search key not in cache, get it from POST
		// though, this should never happen... should always be in cache
    $search->el_no = trim($_POST['el_no']);
    $search->simulator_id = (int)$_POST['simulator'];
    $search->customer_id = (int)$_POST['customer'];
    $search->from_date = trim($_POST['from_date']);
    $search->to_date = trim($_POST['to_date']);
    $search->sim_quality = (int)$_POST['sim_quality'];
    $search->session_name_id = (int)$_POST['session'];

		
		// cache the latest search key
		cache_set($key_cache_name, $search, 'cache', REQUEST_TIME + QMS_CACHE_TIMEOUT);		
	}
	
	die(_get_elogs_search_list($search));
}


/*
 * elogs_clear_callback()
 * 
 * Clears the search results cache
 *
 */

function elogs_clear_callback() {
	
	// Clear the cache 
	$search_results = '<div id="sch-search-results-div"></div>';
	
	// determine cache name
	$results_cache_name = _get_scheduler_cache_name(SCH_ELOGS_SEARCH_RESULTS);
	$key_cache_name = _get_scheduler_cache_name(SCH_ELOGS_SEARCH_KEY);
	
	cache_set($results_cache_name, $search_results, 'cache', REQUEST_TIME + QMS_CACHE_TIMEOUT);
	cache_clear_all($key_cache_name, 'cache', TRUE); 
	// this is an ajax callback.  Need to return + die or it renders a full page
	// we only want a piece of a page
	
	die($search_results);  
}


/*
 * _get_elogs_search_list()
 * display the search results
 * This function gets called by elogs_search_callback() and elogs_pager_callback()
  *
 */

function _get_elogs_search_list($search) {
	
	if ( user_access('view manage menu') == FALSE ) {
		drupal_set_message( t('Unauthorized.  Permission is required.'), 'status');
		drupal_goto(''); // go to main page -- not authorized for any other page
		return '';
  }
  
	
	$table_header = array( 
		array( 'data' => t('EL No.'), 
           'field' => 'el_no', 
           'sort' => 'asc', 
           'class' => array('sch-tbl-elog-elno') 
         ),
		array( 'data' => t('Date'), 
           'field' => 'created_date', 
           'sort' => 'desc', 
           'class' => array('sch-tbl-elog-date') 
         ),
    array( 'data' => t('Simulator'), 
           'field' => 'sim_name', 
           'sort' => 'asc', 
           'class' => array('sch-tbl-elog-sim') 
         ),
    array( 'data' => t('Customer'), 
           'field' => 'customer', 
           'sort' => 'asc', 
           'class' => array('sch-tbl-elog-customer') 
         ),
    array( 'data' => t('Quality'), 
           'field' => 'sim_quality_rating', 
           'sort' => 'asc', 
           'class' => array('sch-tbl-elog-quality') 
         ),
		array( 'data' => t('Admin'), 'class' => array('qms-results-admin') ),
	);
  
  $search_init = array(
		'table_name' => 'sch_elogs',
		'table_alias' => 'e',
		'table_header' => $table_header,
		'pager_path' => 'elogs/pager',
		'order' => 'created_date',
		'sort' => 'desc',
	);
	
	$query = _st_setup_paged_search($search_init);
	
	// Need to use the DB abstration layer here for the paging features
	//$query = db_select('sch_elogs', 'e');
	
  //--------- Link to Assignments ---------
  
  $query->innerJoin('sch_assignments', 'a', 'a.assignment_id = e.assignment_id');
  $query->leftJoin('sch_schedules', 'sch', 'sch.schedule_id = a.schedule_id');
	$query->leftJoin('sch_simulators', 'sim', 'sim.simulator_id = sch.simulator_id');
  $query->leftJoin('sch_customers', 'c', 'c.customer_id = a.customer_id');
  $query->leftJoin('sch_schedule_sessions', 'ss', 
                          'ss.schedule_session_id = a.schedule_session_id');
  $query->leftJoin('sch_session_names', 'sn', 
                          'ss.session_name_id = sn.session_name_id');
	
	//--------- Date filtering -----------
	
	if ( isset($search->from_date) || isset($search->to_date) ) {
		if ( (strlen($search->from_date) > 0) && (strlen($search->to_date) > 0)) {
			$query->condition('e.created_date', _st_format_system_timestamp($search->from_date . " 00:00:00"), '>=');
			$query->condition('e.created_date', _st_format_system_timestamp($search->to_date . " 23:59:59"), '<=');
		}
		else if (strlen($search->from_date) > 0) {
			$query->condition('e.created_date', _st_format_system_timestamp($search->from_date . " 00:00:00"), '>=');
		}
		else if (strlen($search->to_date) > 0) {
			$query->condition('e.created_date', _st_format_system_timestamp($search->to_date . " 23:59:59"), '<=');
		}
	}
  
  
  //---------- EL No -----------------
  
	if ( strlen($search->el_no) && ( $search->el_no <> 'EL') ) {  // if only EL prefix, don't bother
		$query->condition('e.el_no', $search->el_no . '%', 'LIKE');  // append wildcard for fuzzy match
	}
	
	//---------- Simulator ----------------
  
	if ( isset($search->simulator_id) && $search->simulator_id ) {
		$query->condition('sch.simulator_id', $search->simulator_id);
	}
	
	//---------- Customer -----------------
  
	if ( isset($search->customer_id) && $search->customer_id ) {
		$query->condition('a.customer_id', $search->customer_id);
	}
  
  //---------- Sim Quality Rating -----------------
  
	if ( isset($search->sim_quality) && $search->sim_quality ) {  
		$query->condition('e.sim_quality_rating', $search->sim_quality);  
	}
  
  //---------- Session -----------------
  
	if ( isset($search->session_name_id) && $search->session_name_id ) {  
		$query->condition('ss.session_name_id', $search->session_name_id);  
	}
  
	
	$query->fields('e', array('elog_id', 'el_no', 'sim_quality_rating', 'created_date') )
				->fields('sim', array('simulator_id', 'sim_name', 'active', 
                              'faa_id', 'device_id_internal'))
        ->fields('sch', array('schedule_id', 'timezone'))
        ->fields('sn', array('session_name'))
        ->fields('c', array('customer'));
							
  
  $max_count = 0;
	$result = _st_execute_paged_search($query, $max_count);
	
	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
    
    $quality = '';
    switch ($row->sim_quality_rating) {  
      case 1: $quality = t('Deficient'); break;
      case 2: $quality = t('Unsatisfactory'); break;
      case 3: $quality = t('Satisfactory'); break;
      case 4: $quality = t('Good'); break;
      case 5: $quality = t('Excellent'); break;
      default: 
        break;
    }
    
    $sim_name = '';
    if ( $row->simulator_id ) {
      $sim_name = _st_format_sim_name($row->sim_name, $row->device_id_internal, $row->active);
    }
                      
              
		$row_data = array(
      l($row->el_no, 'elog/view/' . $row->elog_id,
              array('query' => array('destination' => 'reports/search/elogs'))),
			_st_format_schedule_date($row->created_date, 'short', $row->timezone) . '<br />' . $row->session_name,
      
      $sim_name,
      $row->customer,
      $quality,
      array('data' => l( t('Edit'), "elog/edit/" . $row->elog_id, 
              array('attributes' => array('class' => array('sch-elog-edit')),
                    'query' => array('destination' => 'reports/search/elogs')) ),
             'class' => array('qms-results-admin')),
		);
				
		$table_rows[] = array('data' => $row_data);
		$i++;
	}
	
	$content = '<div id="sch-search-results-div">';
	
	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
	));
	
	//Append pager:  http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager
	$content .= theme('pager', array('tags' => array(), 'quantity' => QMS_RECORDS_PER_PAGE));
	$content .= '</div>';
	
	// Save to cache
	$results_cache_name = _get_scheduler_cache_name(SCH_ELOGS_SEARCH_RESULTS);
	
	$search_results = $content;
	cache_set($results_cache_name, $search_results, 'cache', REQUEST_TIME + (30*60));
	
	return $content;
}




/*
 *	elog_form()
 *
 *  overloads:  hook_form()
 *	Displays the elog form for instructors to login for a session
 */

function elog_form($form, $form_state, $elog_id = 0, $assignment_id = 0) {

	if ( user_access('access sabreScheduler') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Permission is required.'));
		drupal_goto('');
		return;
  }

	if ( !$elog_id && !$assignment_id ) {
    // we need at least one of these
		drupal_set_message( 
      t('Oops!  Something seems to have gone wrong.  Session Assignment not found. Id=0'));
		drupal_goto('');
		return;
    
	}

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

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = '';
	}
	
	$assignment = (object) Null;
	$elog = (object) Null;
	$elog_crew = array();
  $preflight_warning = '';
  $preflight_alert = 0;
  //$sch_user = (object) Null;
  global $user;
  

  if ( $assignment_id ) {
    $assignment = _get_assignment($assignment_id);

    if ( $assignment == (object) Null ) {
      drupal_set_message( 
        t('Oops!  Something seems to have gone wrong.  Session Assignment not found.'));
      drupal_goto($goto_url);
      return $form;
    }
    
    $elog = _get_elog(0, $assignment_id);
    
    // $elog may come back null since E-Log may not exist yet
  }
  else if ( $elog_id ) {
    $elog = _get_elog($elog_id);
    
    if ( $elog == (object) Null ) {
      drupal_set_message( 
        t('Oops!  Something seems to have gone wrong.  E-Log not found.'));
      drupal_goto($goto_url);
      return $form;
    }
    
    $assignment = _get_assignment($elog->assignment_id);

    if ( $assignment == (object) Null ) {
      drupal_set_message( 
        t('Oops!  Something seems to have gone wrong.  Session Assignment not found.'));
      drupal_goto($goto_url);
      return $form;
    }
  }
  
  if (empty($assignment_id) and !empty($elog->assignment_id)) { $assignment_id = $elog->assignment_id; }
  if (empty($elog_id) && !empty($elog->elog_id)) { $elog_id = $elog->elog_id; }
  
  /*
  if ( !$elog_id && (False == user_access('manage menu')) ) {
    // first time form is being set up, pre-populate instructor
    $sch_user = _get_scheduler_user($user->uid);
   
  }*/
	
	// e-log may or may not exist yet.
	// if there is an elog, it will be updated, if not, we will create a new one
	
	$form['#after_build'][] = 'elog_form_after_build';
	
	// is QMS linked to connect to the Scheduler database ??
  $is_linked = variable_get('sch_qms_link', 0);
  if ( $is_linked ) {
    $preflight_alert = 
         _qms_simulator_get_preflight_status($assignment->simulator_id);
    $preflight_warning = 
         ($preflight_alert ? '<br />' . _show_preflight_warning() : '' );
  }
	
	if ( isset($elog->elog_id) && $elog->elog_id ) {
		$elog_crew = _get_elog_crew_info($elog->elog_id);
		
		// only for display purposes -- the separately defined field is where the actual number 
		// is stored/retrieved
		$form['el_no_display'] = array(
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($elog->el_no) . '</div>',
			'#suffix' => _st_format_record_timestamp_table($elog) . $preflight_warning,
		);		
	}
	else {
		//  Determine the new EL No when submitted
		$el_no_base = _st_generate_report_base_no('EL', $assignment->device_id_internal);
		
		// only for display purposes -- the separately defined  
		// field is where the actual number is stored/retrieved
		// drupal can't access content from an 'item' field
		$form['el_no_display'] = array(
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($el_no_base) . '____</div>',
			'#suffix' => '<div class="qms-desc">' . t('Assigned when submitted') . '</div>' . 
                    $preflight_warning . '<hr />',            
		);		
		
	}
	
	$form['el_no'] = array(
		'#type' =>'textfield',
		'#default_value' => (isset($elog->el_no) ?  $elog->el_no : $el_no_base ),
		'#attributes' => array('class' => array('qms-hidden')),
	);		
	
	
	
	$form['customer'] = array(
		'#type' => 'item',
		'#markup' => '<h2>' . $assignment->customer . 
									(strlen($assignment->group_name) ? ', ' . $assignment->group_name : '') . '</h2>',
	);	
  
  
  //-------------------- E-LOG HEADING ------------------------
  
  $sim_name = _st_format_sim_name($assignment->sim_name, $assignment->device_id_internal);
  
  
  $form['elog_heading_table_begin'] = array(
    '#markup' => 
        '<table class="qms-plain-table">' . 
        '<tr style="vertical-align:bottom;">',
  );
	
	$form['simulator'] = array(
		'#markup' =>  '<td style="width:25%"><h2>' . $sim_name . '</h2></td>' . 
                  '<td style="width:38%"><h2>' . 
                      t('FAA') . ' #' . $assignment->faa_id . '</h2></td>' . 
                  '<td style="width:30%"><h2>' . $assignment->session_type_desc . 
                      '</h2></td>',
	);	
  
  if ( $is_linked ) {
    $create_dr_url = 'discrepancy/' . $assignment_id . '/' . $elog_id;

    $form['submit_with_dr1'] = array(
      '#type' => 'submit',
      '#value' => t('E-DR'),
      '#name' => 'submit_with_dr1',
      '#attributes' => array('class' => array('qms-btn-create-dr'),
                             'id' => 'sch-btn-create-dr1'),
                             //'onclick' => 'window.location="' . 
                             //     url($submit_with_dr1_url) . '?destination=' . 
                              //    current_path() . '"; return false;'),
      '#prefix' =>  '<td><div id="sch-create-dr1-div">',
      '#suffix' => '<h4 id="sch-create-dr1-text">' . t('E-Discrepancy') . '</h4></div></td>',
    );	
  }
  else {
    // no QMS-scheduler link, do not show this button
    $form['submit_with_dr1'] = array(
      '#markup' => '<td>&nbsp;</td>',
    );
  }
  
  
  $form['elog_heading_table_row'] = array(
    '#markup' => 
        '<td>&nbsp;</td></tr>' . 
        '<tr style="vertical-align:bottom;">',
  );
  
  $f_assign_hours = (float)$assignment->total_time / (60 * 60);
  
  $dt = new DateTime();
  $tz = _get_schedule_timezone($assignment->schedule_id);
  $dt->setTimezone(new DateTimeZone($tz));
  $dt->setTimestamp($assignment->begin_timestamp);
  $adt = $dt->format('m/d/Y');
  
  $form['session'] = array(
		'#markup' => '<td ><h2>' . $adt . '</h2></td>' . 
                  '<td><h2>' . $assignment->session_name . ': ' . 
                      $assignment->begin_time_actual . ' - ' . $assignment->end_time_actual . 
                  '</h2></td>' . 
                  '<td><h2>' . 
                      sprintf('%0.1f', $f_assign_hours) . ' ' . t('hours') . 
                  '</h2></td>' . 
                  // this is a place holder cell for the DR button above
                  '<td>&nbsp;</td>',
	);	
	
  
  $form['elog_heading_table_end'] = array(
    '#markup' => '<tr></table>',
  );
  
  
	
	// ------------ Flight Crew Info ----------------
	
	$flight_roles = new FlightRolesList();
	
	$form['crew_table_begins'] = array(
		'#markup' => '<hr /><h3>' . t('Flight Crew') . '</h3>' . 
								 '<table class="sch-elog-crew qms-plain-table" style="100%">',
	);
	
	for($i=0; $i<SCH_MAX_CREW_COUNT; $i++) {
    
    $fname_default = '';
    $lname_default = '';
    $flight_role_default = 0;
    $flight_role_1_hours_default = '';
    $flight_role_2_hours_default = '';
    
    /*
    if ( isset($sch_user->last_name) && (0 == $i) ) {
      $fname_default = $sch_user->first_name;
      $lname_default = $sch_user->last_name;
      $flight_role_default = SCH_CREW_INSTRUCTOR;
    }*/
		
		$form['first_name_' . $i] = array(
			'#type' => 'textfield',
			'#title' => t('First Name'),
			'#maxlength' => 50,
			'#size' => 13,
			'#default_value' => (isset($elog_crew[$i]->fname) ? 
                          $elog_crew[$i]->fname : $fname_default),
			'#attributes' => array('class' => array(
                                          'sch-crew-input',
                                          'sch-crew-fname',
                                          'sch-crew-fname-' . $i)
                                        ),
			'#prefix' => '<tr class="sch-elog-crew-member"><td style="width:19%">',
			'#suffix' => '</td>',
		);
		
		$form['last_name_' . $i] = array(
			'#type' => 'textfield',
			'#title' => t('Last Name'),
			'#maxlength' => 50,
			'#size' => 18,
			'#default_value' => (isset($elog_crew[$i]->lname) ? 
                           $elog_crew[$i]->lname : $lname_default),
			'#attributes' => array('class' => array(
                                          'sch-crew-input',
                                          'sch-crew-lname',
                                          'sch-crew-lname-' . $i)
                                        ),
			'#prefix' => '<td>',
			'#suffix' => '</td>',
		);
		
    /* ---May add this back in later as an option---
		$form['employee_num_' . $i] = array(
			'#type' => 'textfield',
			'#title' => t('Employee Number'),
			'#maxlength' => 50,
			'#size' => 20,
			'#default_value' => isset($elog_crew[$i]->employee_num) ? $elog_crew[$i]->employee_num : '',
			'#attributes' => array('class' => array('sch-crew-employee-num-' . $i)),
			'#prefix' => '<td>',
			'#suffix' => '</td>',
		);*/
    
    
    $is_visible = 'hidden';
    $bPilots = False;
    
    if ( isset($elog_crew[$i]->flight_role_1_id) && 
         ( (SCH_CREW_PILOT == $elog_crew[$i]->flight_role_1_id) || 
           (SCH_CREW_PILOT_2ND == $elog_crew[$i]->flight_role_1_id) ) ) {
      $is_visible = 'visible';
      $bPilots = True;
    }
    
    //$hours_opts = _get_flight_role_time_opts($f_assign_hours);
    //reset($hours_opts);
    
    
    $flight_role_1_hours = 2.0;
            //current($hours_opts); // get the first entry 'ALL'
    $flight_role_2_hours = '0';
   
    if (isset($elog_crew[$i]->flight_role_1_time) &&  
            ($elog_crew[$i]->flight_role_1_time )) {
      $flight_role_1_hours = 
           sprintf('%0.2f', $elog_crew[$i]->flight_role_1_time / (60 * 60));
      
    }
//    if (isset($elog_crew[$i]->flight_role_2_time) &&
//        ($elog_crew[$i]->flight_role_2_time )) {
//      $flight_role_2_hours = 
//           sprintf('%0.2f', $elog_crew[$i]->flight_role_2_time / (60 * 60));
//    }
    
    $form['flight_role_first_' . $i] = array(
			'#type' => 'select',
			'#title' => t('Flight Role') . ($bPilots ? ' - ' . t('First') : ''),
			'#options' => $flight_roles->get(),
			'#default_value' => (isset($elog_crew[$i]->flight_role_1_id) ? 
                            $elog_crew[$i]->flight_role_1_id : $flight_role_default),
			'#attributes' => array('class' => array(
                                              'sch-crew-input',
                                              'sch-flight-role-select', 
																							'sch-crew-flight-role',
																							'sch-crew-flight-role-first-' . $i),
                             'qms-index' => $i),
			'#prefix' => '<td style="width:22%">',
      '#suffix' => '</td>',
		);
   
    
    $form['flight_role_hours_first_' . $i] = array(
			'#type' => 'textfield',
			'#title' => t('Hours'),
      '#maxlength' => 4,
      '#size' => 4,
			//'#options' => $hours_opts,
			'#default_value' => isset($elog_crew[$i]->flight_role_1_time) ? 
                          $flight_role_1_hours : $flight_role_1_hours_default,
			'#attributes' => array('class' =>  array(
                              'qms-numeric',
                             'sch-crew-flight-role-hours-first',
                             'sch-crew-flight-role-hours-first-' . $i),
                             'qms-index' => $i),
			'#prefix' => '<td  style="width:10%">' . 
                    '<div class="sch-crew-flight-role-hours-div-' . $i . 
                   ' style="visibility:' . $is_visible . '">',
      '#suffix' => '</div></td>',
		);
    
    $form['flight_role_second_' . $i] = array(
			'#type' => 'item',
      '#title' => t('Flight Role') . ' - ' . t('Second'),
			'#markup' => '<span class="sch-crew-flight-role-second ' . 
                    'sch-crew-flight-role-second-' . $i . '">' . 
                    ( (isset($elog_crew[$i]->flight_role_2_id) &&
                      $elog_crew[$i]->flight_role_2_id) ?
                      $flight_roles->getName($elog_crew[$i]->flight_role_2_id) : '---') . 
//                      '<br />' . $flight_role_2_hours . ' ' . t('Hours') : 
//                      '---') . 
                    '</span>',
      '#prefix' => '<td style="width:25%">' . 
                    '<div class="sch-crew-flight-role-second-div' . 
                    ' sch-crew-flight-role-second-div-' . $i . 
                   ' style="visibility:' . $is_visible . ';margin-left:8px;">',
      '#suffix' => '</div>',
		);
		
		$form['elog_crew_id_' . $i] = array(
			'#type' => 'textfield',
			'#default_value' => isset($elog_crew[$i]->elog_crew_id) ? $elog_crew[$i]->elog_crew_id : 0,
			'#attributes' => array('class' => array('qms-hidden')),
			'#suffix' => '</td></tr>',
		);
	}
	
	$form['crew_table_ends'] = array(
		'#markup' => '</tr></table><hr />',
	);
		
	
	
	//------------- Simulator Quality Rating --------
	$quality_opts = array(
		1 => t('Deficient'),
		2 => t('Unsatisfactory'),
		3 => t('Satisfactory'),
		4 => t('Good'),
		5 => t('Excellent'),
	);
  
	
	$form['rating'] = array(
		'#type' => 'fieldset',
		'#title' => t('Rate Simulator Quality'),
		'#attributes' => array('id' => 'sch-sim-quality-rating',
														/* 'class' => array('container-inline') */ ),		
    '#prefix' => '<div class="sch-quality-rating-options">',
    '#suffix' => '</div>',
	);
	
	$form['rating']['sim_quality_rating'] = array(
		'#type' => 'radios',
		'#options' => $quality_opts,
		'#default_value' => (isset($elog->sim_quality_rating) ? 
                         $elog->sim_quality_rating : 5),
		'#attributes' => array('class' => array('sch-sim-rating'),
													 /*'style' => 'display:inline-block;'*/),
    '#suffix' => '<br class="clearBoth">',
	);
  
  //------------- Log Text Editor -----------------
	$text_settings = array(
		'name' => 'log_text',
		'title' => t('Comments'),
		'text' =>	(isset($elog->log_text) ? $elog->log_text : ''),
    'fieldset' => 'rating',
		'required' => False,
    'prefix' => '<div class="sch-log-text-div">',
		'suffix' => '</div>',
	);
	 
	_st_add_text_editor($form, $text_settings);
	
	
  
  //------------- Report a Discrepancy --------
 
  // is QMS linked to connect to the Scheduler database ??
  /*
  if ( $is_linked ) {
    $dr_opts = array(
      0 => t('No'),
      1 => t('Yes'),
    );

    $form['discrepancy'] = array(
      '#type' => 'fieldset',
      '#title' => t('Report a Discrepancy'),
      '#attributes' => array('id' => 'sch-discrepancy-fieldset',
                              'class' => array('container-inline')),		
    );

    $form['discrepancy']['report_discrepancy'] = array(
      '#type' => 'radios',
      '#title' => t('Do you want to report a discrepancy for this simulator?'),
      '#options' => $dr_opts,
      '#default_value' => 0,
      '#attributes' => array('class' => array('sch-report-discrepancy'),
                             'style' => 'display:inline-block;'),
    );
  }*/

	
	//--------------- Hidden -------------------------
	$form['assignment_id'] = array(
		'#type' => 'textfield',
		'#default_value' => isset($elog->assignment_id) ? $elog->assignment_id : $assignment_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	

	$form['elog_id'] = array(
		'#type' => 'textfield',
		'#default_value' => (isset($elog->elog_id) ? $elog->elog_id : 0),
		'#attributes' => array('class' => array('qms-hidden')),
	);	
  
  $ah = round($f_assign_hours, 1, PHP_ROUND_HALF_UP);
  $form['assignment_hours'] = array(
		'#type' => 'textfield',
		'#default_value' => sprintf('%0.2f', $ah),
		'#attributes' => array('class' => array('qms-hidden'),
                           'id' => 'sch-assignment-hours'),
	);	
  
  $form['kiosk_mode'] = array(
    '#markup' => '<div id="qms-kiosk-url" class="qms-hidden">' . 
                  url('kiosk') . '</div>',
  );
  
  $form['strings'] = array(
    '#markup' => '<div id="sch-strings" class="qms-hidden">' .
                    $flight_roles->getName(SCH_CREW_PILOT) . '|' .
                    $flight_roles->getName(SCH_CREW_PILOT_2ND) . '|' .
                    t('Flight Role') . '|' . 
                    t('First') . '|' . 
                    t('Second') . '|' . 
                    t('Hours') . 
                 '</div>',
  );



	//--------------- Buttons -------------------------		
	$form['actions'] = array('#type' => 'actions');
	
  
  if ( $is_linked ) {
    
    $form['actions']['submit_with_dr2'] = array(
      '#type' => 'submit',
      '#name' => 'submit_with_dr2',
      '#value' => t('E-Discrepancy'),
      '#attributes' => array('class' => array('qms-btn-create-dr', 'qms-btn-extra-leading'),
                               'id' => 'sch-btn-create-dr2'),
    );
  }
  else {
    // no QMS-scheduler link, do not show this button
    $form['submit_with_dr2'] = array(
      '#markup' => '&nbsp;',
    );
  }
  
  if (!empty($elog_id)) {
    $view_url = '/elog/view/' . $elog_id . '/' . $assignment_id;
    $form['actions']['view_print'] = array(
      '#type' => 'button',
      '#name' => 'view_print',
      '#value' => t('View/Print'),
      '#attributes' => array('class' => array('qms-btn-view-print', 
                                              'qms-btn-extra-leading'),
                             'onclick' => 'window.location="' . 
                                           url($view_url) . '?destination=' . 
                                           current_path() . '"; return false;'),
	);
  }
   
  $form['actions']['submit'] = array(
		'#type' => 'submit',
    '#name' => 'submit',
		'#value' => t('Save/Print'),
	);
  
  $form['actions']['done'] = array(
		'#type' => 'submit',
		'#value' => t('Cancel'),
    '#name' => 'done',
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra')),
	);
	
	return $form;
}


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

/* 
 * schedule_form_after_build()
 *
 */
function elog_form_after_build($form, &$form_state)
{
	//drupal_add_library('system','ui.datepicker');
	//drupal_add_library('system','ui.dialog');
	$sabreTools = drupal_get_path('module', 'sabreTools');
	drupal_add_js($sabreTools . '/js/sabreTools.lib.js');
	drupal_add_js($sabreTools . '/js/sabreTools.ckeditor.js');
  
  $sabreScheduler = drupal_get_path('module', 'sabreScheduler');
  drupal_add_css($sabreScheduler . '/css/sch-elog.css');
  
  // see http://digitalbush.com/projects/masked-input-plugin/
	drupal_add_js($sabreScheduler . '/js/vendor/jquery.maskedinput-1.3.1.min.js');
	drupal_add_js($sabreScheduler . '/js/sabreScheduler.elog.addedit.js');

	global $base_url;
	drupal_add_js( $base_url . QMS_CKEDITOR_PATH_CONFIG);
	// need to specify preprocess == false otherwise 'Aggregate Javascript' setting in drupal 
	// causes ckeditor not to load properly
	// adding scope to footer speeds up the page load
	drupal_add_js( $base_url . QMS_CKEDITOR_LIB, array('type' => 'file', 'scope' => 'footer', 'preprocess' => FALSE));
  
  
//  KIOSK revised -- do not do this here
//  also, timeout reset does not work correctly with CKEditor
//  global $user;
//  
//  $user_customer_id =  _get_user_customer_id();
//  $bKioskMode = (( $user_customer_id == 1 ) && 
//                    user_access('kiosk mode') &&
//                    ($user->uid != 1) );
//  if ( $bKioskMode ) {
//    drupal_add_js(drupal_get_path('module', 'sabreScheduler') . 
//                        '/sabreScheduler.kioskreset.js');
//  }

		
	return $form;
}

/*
 *	elog_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates form after it is submitted
 */
function elog_form_validate($form, $form_state) {
  
  $button_clicked = $form_state['triggering_element']['#name'];
  $bSubmit = False;
  
  if ( ($form['actions']['submit']['#name'] == $button_clicked) ) {
    $bSubmit = True;
  }
  else if ( isset($form['actions']['submit_with_dr1']['#name']) && 
            ($form['actions']['submit_with_dr1']['#name'] == 
                $button_clicked) ) {
    $bSubmit = True;
  }
  else if ( isset($form['actions']['submit_with_dr2']['#name']) && 
            ($form['actions']['submit_with_dr2']['#name'] == 
                $button_clicked) ) {
    $bSubmit = True;
  }
  
  if ( !$bSubmit ){
    return $form;
  }
	
	$pilot = False;
	$instructor = False;
  
  $err_msg = t('Missing required fields.');
  
  $input_hours = 0.0;
	
	for ($i=0; $i<SCH_MAX_CREW_COUNT; $i++) {
		$fname = trim($form_state['values']['first_name_' . $i]);
		$lname = trim($form_state['values']['last_name_' . $i]);
		//$emp_num = trim($form_state['values']['employee_num_' . $i]);
		$hours = $form_state['values']['flight_role_hours_first_' . $i];
    $flight_role = (int)$form_state['values']['flight_role_first_' . $i];
		
		// if any of these are set, they should all be set... validate
		if ( strlen($fname) || strlen($lname) || $flight_role ) {
			if ( !strlen($fname) ) {
				form_set_error('first_name_' . $i, t('First Name is a required field.'));
			}
			if ( !strlen($lname) ) {
				form_set_error('last_name_' . $i, t('Last Name is a required field.'));
			}
			if ( !$flight_role ) {
				form_set_error('flight_role_first_' . $i, 
                t('Flight Role is a required field.'));
			}
      
		}
		if ( SCH_CREW_PILOT == $flight_role) { 
      $pilot = True; 
      if ( (float)$hours == 0) {
        form_set_error('flight_role_hours_first_' . $i, 
                t('Please enter a flight time for the Pilot.'));
      }
    }
		if ( SCH_CREW_INSTRUCTOR == $flight_role) { $instructor = True;}
    if ( $i <= 1) {
      // only count hours for the first 2 crew members
      $input_hours += (float)$hours;
    }
	}
	
	if ( !$pilot ) {
		form_set_error('flight_role_1_1', t('"PF: Pilot" flight role must be assigned'));
	}
	if ( !$instructor ) {
		form_set_error('flight_role_1_0', t('"INS: Instructor" flight role must be assigned'));
	}
  
  $assignment_hours = (float)$form_state['values']['assignment_hours'];
  $f_input_hours = round($input_hours, 1, PHP_ROUND_HALF_UP);
  if (($f_input_hours <= $assignment_hours - 0.25)||($f_input_hours > $assignment_hours)) {
    form_set_error('flight_role_hours_first_0', t('Time must total ') . sprintf('%0.2f', $assignment_hours));
  }
	
	/* // E-Log Log Text not required -------
	$log_text = trim($form_state['values']['log_text_editor_value']);
	if ( $log_text == '' ) {
		form_set_error('qms_log_text', t($err_msg . 'Comments is a required field'));
	} */	
}

/*
 *	elog_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Submits form for final save
 */
function elog_form_submit($form, $form_state) {
  
  //---------------- Button Handlers --------------------
  
  $button_clicked = $form_state['triggering_element']['#name'];
  $bSubmit = False;
  $bCreateDR = False;
  $bView = False;
  
  if ( ($form['actions']['submit']['#name'] == $button_clicked) ) {
    $bSubmit = True;
    $bView = True;
  } else if ( isset($form['submit_with_dr1']['#name']) && 
            ($form['submit_with_dr1']['#name'] ==  $button_clicked) ) {
    // submit_with_dr1 is not contained within $form['actions']
    // this may not always appear (if scheduler is not linked to QMS
    $bSubmit = True;
    $bCreateDR = True;
  } else if ( isset($form['actions']['submit_with_dr2']['#name']) && 
            ($form['actions']['submit_with_dr2']['#name'] == $button_clicked) ) {
    // submit_with_dr2 IS contained within $form['actions']
    // this may not always appear (if scheduler is not linked to QMS
    $bSubmit = True;
    $bCreateDR = True;
  }
  
  
  $destination = drupal_get_destination();
  $goto_url = $destination['destination'];

  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = '';
  }	
  
  
  if ( isset($form['actions']['done']['#name']) && 
            ($form['actions']['done']['#name'] == $button_clicked) ){
    
    
    drupal_goto($goto_url);
    
  }
  else if ( !$bSubmit ) {
    return;
  }
  
  //---------------- SUBMIT:  Process Form --------------------

	$elog = new stdClass();
	$elog_crew = new stdClass();
	global $user;
	$bError = False;
  
	
	$elog_id = (int)$form_state['values']['elog_id'];
	$elog->assignment_id = (int)$form_state['values']['assignment_id'];
	$elog->log_text = _st_clean_ckeditor_text($form_state['values']['log_text_editor_value']);
	$elog->sim_quality_rating = (int)$form_state['values']['sim_quality_rating'];
  
	
	
	if ( !$elog_id ) {  
		// create
		$el_base_no = $form_state['values']['el_no'];
		$elog->el_no = _st_generate_report_no('EL', $el_base_no);
		$elog->created_date = REQUEST_TIME;
		$elog->created_by_user = $user->uid;
		
		if ( False == drupal_write_record('sch_elogs', $elog)) {
			$msg = "Oops!  Something went wrong saving the E-Log record.";
			drupal_set_message(t($msg));
			$bError = True;
		}
    $elog_id = $elog->elog_id;
	}
	else {
		// update
		$elog->elog_id = $elog_id;
		$elog->updated_date = REQUEST_TIME;
		$elog->updated_by_user = $user->uid;
		
		if ( False == drupal_write_record('sch_elogs', $elog, 'elog_id')) {
			$msg = "Oops!  Something went wrong saving the E-Log record.";
			drupal_set_message(t($msg));
			$bError = True;
		}
	}
  
	
  $total_time_hours = (float)$form_state['values']['assignment_hours'];
  $total_time_secs = (int)$total_time_hours * (60 * 60);
  
	for ($i=0; $i<SCH_MAX_CREW_COUNT; $i++) {
        
		$elog_crew_id = (int)$form_state['values']['elog_crew_id_' . $i];
		$elog_crew->elog_id = $elog->elog_id;
		$elog_crew->fname = $form_state['values']['first_name_' . $i];
		$elog_crew->lname = $form_state['values']['last_name_' . $i];
		$elog_crew->employee_num = ''; // not used yet, removed for AFG
		$elog_crew->flight_role_1_id = 
            (int)$form_state['values']['flight_role_first_' . $i];
    
    $flight_role_1_hours = 
            (float)$form_state['values']['flight_role_hours_first_' . $i];
    $flight_role_1_secs = (int)($flight_role_1_hours * (60*60));
    //$flight_role_2_hours = (float)$total_time_hours - $flight_role_1_hours;
    //$flight_role_2_secs = (int)($flight_role_2_hours * (60 * 60));
    
    
    
    
    if ( SCH_CREW_PILOT == $elog_crew->flight_role_1_id ) {
      if ( $total_time_secs == $flight_role_1_secs) {
        $elog_crew->flight_role_2_id = 0;
      }
      else {
        $elog_crew->flight_role_2_id = SCH_CREW_PILOT_2ND;
      }
      $elog_crew->flight_role_1_time = $flight_role_1_secs;
      //$elog_crew->flight_role_2_time = $flight_role_2_secs;
    }
    else if ( SCH_CREW_PILOT_2ND == $elog_crew->flight_role_1_id ) {
      if ( $total_time_secs == $flight_role_1_secs) {
        $elog_crew->flight_role_2_id = 0;
      }
      else {
        $elog_crew->flight_role_2_id = SCH_CREW_PILOT;
      }
      $elog_crew->flight_role_1_time = $flight_role_1_secs;
      //$elog_crew->flight_role_2_time = $flight_role_2_secs;
    }
    else {
      $elog_crew->flight_role_1_time = $total_time_secs;
      $elog_crew->flight_role_2_id = 0;
      //$elog_crew->flight_role_2_time = 0;
    }
   
    
    if ( $elog_crew->flight_role_1_id ||
         $elog_crew->fname || 
         $elog_crew->lname ) {
      unset($elog_crew->elog_crew_id);

      if ( !$elog_crew_id ) {
        $elog_crew->created_date = REQUEST_TIME;
        $elog_crew->created_by_user = $user->uid;	
        unset($elog_crew->elog_crew_id);

        if ( False == drupal_write_record('sch_elog_crew', $elog_crew)) {
          $msg = "Oops!  Something went wrong saving the E-Log crew records.";
          drupal_set_message(t($msg));
          $bError = True;
        }
      }
      else {

        // only include it into the record if value > 0
        $elog_crew->elog_crew_id = $elog_crew_id;
        $elog_crew->updated_date = REQUEST_TIME;
        $elog_crew->updated_by_user = $user->uid;

        if ( False == drupal_write_record('sch_elog_crew', $elog_crew, 'elog_crew_id')) {
          $msg = "Oops!  Something went wrong saving the E-Log crew records.";
          drupal_set_message(t($msg));
          $bError = True;
        }
      }
    }
    
	}
	
	if ( !$bError ) {
		drupal_set_message(t('E-Log saved successfully.'));
    
    // send email notification
    _send_elog_email_notifications($elog_id);
    
    if ( $bCreateDR ) {
      // user wants to create a discrepancy, route to the DR page
      // but reroute back to the elog/view page for this log
      //$dest_url = 'elog/assign/' . $elog->assignment_id;
      unset($_GET['destination']);
      drupal_goto('discrepancy/' . $elog->assignment_id . '/' . $elog->elog_id, 
                  array('query' => array('destination' => $goto_url)) );
    } else if ($bView) {
      unset($_GET['destination']);
      $view_url = '/elog/view/' . $elog->elog_id . '/' . $elog->assignment_id;
      drupal_goto($view_url, array('query' => array('destination' => $goto_url)));
    } else {
      // display a printable copy of the elog
      drupal_goto('');
    }
	}
	else {
    if ($bView) {
      $goto_url = '/elog/view/' . $elog->elog_id . '/' . $elog->assignment_id;
    }
		//drupal_goto('elog/assign/' . $elog->assignment_id);
    drupal_goto($goto_url);
	}
}


/*
 * _send_elog_email_notifications()
 */
function _send_elog_email_notifications($elog_id) {
  $email_title = 'E-Log Filed';
  
  // pull the full elog record since an add or update only contains parts
  $elog = _get_elog($elog_id);  
  
  $assignment = _get_assignment($elog->assignment_id);
    
  $emails = _st_get_simulator_notification_email_list(SCHEDULER_APP, 
                                                      $assignment->simulator_id, 
                                                      QMS_NOTIFY_ELOG);
  
  if (strlen($emails)) {
    // there are people to notify, build the email and send it
    
    $subject = 'SCHEDULER NOTICE -- ' . $email_title . ' for ' . 
               $assignment->sim_name;
    $body = _notify_elog_body($assignment, $elog);

    _st_send_drupal_email($elog->elog_id, $subject, $body, $emails);  
    
    watchdog(SCH_SCHEDULER, "E-Log Alert Emails Sent: ". var_export($emails, True), array(), WATCHDOG_NOTICE);
  }
}

/*
 *  _notify_elog_body()
 */
function _notify_elog_body($assignment, $elog) {
  
  ///////////////////////////////////////////////
	// format the contents of the E-Log for email  //
	///////////////////////////////////////////////
  //watchdog(SCH_SCHEDULER, var_export($elog, True), array(), WATCHDOG_DEBUG);
  //watchdog(SCH_SCHEDULER, var_export($elog_crew_list, True), array(), WATCHDOG_DEBUG);
  
  $elog_crew_list = _get_elog_crew_info($elog->elog_id);
  
  $created_email = _st_get_user_email($elog->created_by_user);  // this may return '' if updated_by_user==0
	$created_user_link = ( strlen($created_email) ? l(_get_user_name($elog->created_by_user), 'mailto:' . $created_email) : _get_user_name($elog->created_by_user) );
  
  
  $updated_email = _st_get_user_email($elog->updated_by_user);  // this may return '' if updated_by_user==0
	$updated_user_link = ( strlen($updated_email) ? l(_get_user_name($elog->updated_by_user), 'mailto:' . $updated_email) : _get_user_name($elog->updated_by_user) );
  
  $customer_info = $assignment->customer . (strlen($assignment->group_name) ? ', ' . $assignment->group_name : ''); 
  $simulator_info = _st_format_sim_name($assignment->sim_name, $assignment->device_id_internal) . ' ';
  if (!empty($assignment->faa_id)) {
    $simulator_info .= ' '.t('FAA'). ' #'.$assignment->faa_id;
  }
  
  $session_info =  $assignment->session_name . ': ' . 
                      $assignment->begin_time_actual . ' - ' . $assignment->end_time_actual. ', '.
                      sprintf('%0.1f', $assignment->total_time/(60*60)) . ' ' . t('hours');
  
	$quality_rating = _get_sim_quality_desc($elog->sim_quality_rating);
	
  $body = 
		'<h2><strong>'.t('E-Log Submitted').'</strong></h2>' .
		'<hr />' .
		'<p>'. 
    '<strong>'.t('Created'). ':  </strong>' .
		( $elog->created_by_user ? $created_user_link . ', ' : '' ) . 
		( $elog->created_date ? _st_format_date($elog->created_date, 'medium') : '');
  
  if (!empty($elog->updated_by_user)) {
    $body .=
      '<br />' .
      '<strong>'.t('Updated').':  </strong>' .
      ( $elog->updated_by_user ? $updated_user_link . ', ' : '' ) . 
      ( $elog->updated_date ? _st_format_date($elog->updated_date, 'medium') : '');
  }
  $body .= '</p>';
  
	$body .= 
		'<table style="width: 100%;">' .
		'<tr><td colspan="2"><h2><strong>'. $elog->el_no . '</strong></h2></td></tr>' . 
		'<tr><td style="width: 40%;"><strong>'.t('Customer').'</strong></td>' .
        '<td style="width: 60%;">' . $customer_info . '</td></tr>' .
    '<tr><td style="width: 40%;"><strong>'.t('Simulator').'</strong></td>' . 
         '<td style="width: 60%;">' . $simulator_info . '</td></tr>' . 
		'<tr><td style="width: 40%;"><strong>'.t('Date Submitted').'</strong></td>' . 
         '<td style="width: 60%;">' . _st_format_date($elog->created_date, 'short') . '</td></tr>' . 
		'<tr><td style="width: 40%;"><strong>'.t('Session').'</strong></td>' . 
         '<td style="width: 60%;">' . $session_info . '</td></tr>';
    '<tr><td style="width: 40%;"><strong>'.t('Session Type').'</strong></td>' . 
         '<td style="width: 60%;">' . $assignment->session_type_desc . '</td></tr>';
    
  $body .= '<tr><td colspan="2">&nbsp;<hr />&nbsp;</td></tr>';
    
  // Flight Crew
  $flight_roles = new FlightRolesList();
  
  $body .= '<tr><td colspan="2"><strong>'.t('Flight Crew').'</strong></td></tr>';
  foreach ($elog_crew_list as $crew) {
    
    $body .= '<tr><td colspan="2">' . sprintf("%s %s, %s", 
                          $crew->fname, 
                          $crew->lname,
                          $flight_roles->getName($crew->flight_role_1_id) ).
             '</td></tr>';
  }
  $body .= '<tr><td colspan="2">&nbsp;<hr />&nbsp;</td></tr>';
  
  $body .= 
       '<tr><td style="width: 40%;"><strong>'.t('Quality Rating').'</strong></td>' . 
       '<td style="width: 60%;">' . $quality_rating . '</td></tr>';
  
  $body .= '<tr><td colspan="2">&nbsp;</td></tr>';

  $body .= '<tr><td colspan="2"><strong>'.t('Comments').'</strong></td></tr>'.
           '<tr><td colspan="2">'.nl2br(_st_convert_symbols($elog->log_text)).'</td></tr>';
    
  $body .= '</table>';
  
  return $body;
}

/*
 *	view_elog_form()
 *
 *  overloads:  hook_form()
 *	Displays the submitted elog form
 */

function view_elog_form($form, $form_state, $elog_id = 0, $assignment_id = 0) {

	if ( user_access('access sabreScheduler') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Permission is required.'));
		drupal_goto('');
		return;
  }

	if ( !(int)$elog_id ) {
		drupal_set_message( 
        t('Oops!  Something seems to have gone wrong.  E-Log not found. Id=0'));
		drupal_goto('');
		return;
    
	}
  
  drupal_add_js('(function($) {
										Drupal.behaviors.schViewPrint = {
											attach: function(context, settings) {
												$(".qms-print", context).click(function() {
                          window.print();
                          return false;
                        });
											}
										}
									}(jQuery));', 'inline');

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

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = '';
	}
	
	$assignment = Null;
	$elog = Null;
	$elog_crew = array();
  
  $elog = _get_elog($elog_id, $assignment_id);
  
  if ( $elog == Null ) {
		drupal_set_message( t('Oops!  Something seems to have gone wrong.  E-Log not found.'));
		drupal_goto($goto_url);
		return;
	}

  if ( isset($elog->assignment_id) ) {
    $assignment = _get_assignment($elog->assignment_id);

    if ( $assignment == (object) Null ) {
      drupal_set_message( 
         t('Oops!  Something seems to have gone wrong.  Session Assignment not found.'));
      drupal_goto($goto_url);
      return;
    }
  }
	
	
	if ( isset($elog->elog_id) ) {
		$elog_crew = _get_elog_crew_info($elog->elog_id);
	
		$form['el_no_display'] = array(
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($elog->el_no) . '</div>',
			'#suffix' => _st_format_record_timestamp_table($elog),
		);	
	}
	else {
    // failsafe, something not quite right
		$form['timestamp'] = array(
			'#markup' => '&nbsp;<hr />',
		);
  }
	
	
	$form['customer'] = array(
		'#type' => 'item',
		'#markup' => '<h2>' . $assignment->customer . 
									(strlen($assignment->group_name) ? ', ' . $assignment->group_name : '') . 
                  '</h2>',
	);	
  
  $sim_name = _st_format_sim_name($assignment->sim_name, $assignment->device_id_internal);
	
	$form['simulator'] = array(
		'#type' => 'item',
		//'#title' => t('Simulator'),
		'#markup' => 
                 '<table class="qms-plain-table"><tr>' . 
                  '<td style="width:25%"><h2>' . $sim_name . '</h2></td>' . 
                  '<td style="width:42%"><h2>' . 
                      t('FAA') . ' #' . $assignment->faa_id . '</h2></td>' . 
                  '<td style="width:33%"><h2>' . $assignment->session_type_desc . '</h2></td>' . 
                 '</tr></table>',
	);		
  
  $dt = new DateTime();
  $tz = _get_schedule_timezone($assignment->schedule_id);
  $dt->setTimezone(new DateTimeZone($tz));
  $dt->setTimestamp($assignment->begin_timestamp);
  $adt = $dt->format('m/d/Y');
	
	$form['session'] = array(
		'#type' => 'item',
		//'#title' => t('Session'),
		'#markup' => '<table class="qms-plain-table"><tr>' . 
                  '<td style="width:25%"><h2>' . $adt . '</h2></td>' . 
                  '<td style="width:42%"><h2>' . $assignment->session_name . ': ' . 
                      $assignment->begin_time_actual . ' - ' . $assignment->end_time_actual . 
                  '</h2></td>' . 
                  '<td style="width:33%"><h2>' . 
                      sprintf('%0.1f', $assignment->total_time / (60 * 60)) . ' ' . t('hours') . 
                  '</h2></td>' . 
                 '</tr></table>',
			
	);	
	
		
	
	// ------------ Flight Crew Info ----------------
	
	$flight_roles = new FlightRolesList();
	
  /*
	$form['crew_table_begins'] = array(
		'#markup' => '<hr /><h3>' . t('Flight Crew') . '</h3>' . 
								 '<table class="qms-plain-table"><thead>' .
                 '<tr><th>' . t('First Name') . '</th>' . 
                 '<th>' . t('Last Name') . '</th>' . 
                 '<th>' . t('Employee Number') . '</th>' . 
                 '<th>' . t('Flight Role') . '</th></tr></thead>' . 
                 '<tbody>',
	);
   * */
   
  
  $table_header = array( 
		array( 'data' => t('First Name'), 
           'class' => array('sch-crew-tbl-fname') 
         ),
		array( 'data' => t('Last Name'), 
           'class' => array('sch-crew-tbl-lname') 
         ),
		/*array( 'data' => t('Employee Number'), 
           'class' => array('sch-crew-employee-num') 
         ),*/
		array( 'data' => t('Flight Role First'), 
           'class' => array('sch-crew-tbl-flight-role') 
         ),
    array( 'data' => t('Flight Role Second'), 
           'class' => array('sch-crew-tbl-flight-role') 
         ),
	);
  $table_rows = array();
  
	
	for($i=0; $i<count($elog_crew); $i++) {
    $row_data = array();
    
  
    if ( isset($elog_crew[$i]->flight_role_1_id) && ($elog_crew[$i]->flight_role_1_id) ) {
      $bPilot = ((SCH_CREW_PILOT == $elog_crew[$i]->flight_role_1_id) || 
                (SCH_CREW_PILOT_2ND == $elog_crew[$i]->flight_role_1_id));
      $fr1_hours = 
         sprintf('%0.2f', (((float)$elog_crew[$i]->flight_role_1_time) / (60*60)));
      $fr1 = $flight_roles->getName($elog_crew[$i]->flight_role_1_id);
      
      if ( $bPilot ) {
        $fr1 .= '<br>' . $fr1_hours . ' ' . t('Hrs');
      }
              
      
      $fr2 = '';
      if ( $elog_crew[$i]->flight_role_2_id ) {
//        $fr2_hours = 
//         sprintf('%0.2f', (((float)$elog_crew[$i]->flight_role_2_time) / (60*60)));
         $fr2 = $flight_roles->getName($elog_crew[$i]->flight_role_2_id); // . '<br>' . 
                //$fr2_hours . ' ' . t('Hrs');
      }
      
      $row_data = array(
          $elog_crew[$i]->fname,
          $elog_crew[$i]->lname,
          //$elog_crew[$i]->employee_num,
          $fr1,
          $fr2,
      );
      
    }
    $table_rows[] = array('data' => $row_data);
	}
  
  $crew_table = '<hr /><h3>' . t('Flight Crew') . '</h3>';
  $crew_table .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
	));
	
	$form['crew_table'] = array(
		'#markup' => $crew_table . '<br />',
	);
	
	
	
	//------------- Log Text -----------------
	
	$form['log_text'] = array(
		'#type' => 'item',
		'#title' => t('Comments'),
		'#markup' => nl2br(_st_convert_symbols($elog->log_text)),
	);
	
	
	//------------- Simulator Quality Rating --------
  $rating = _get_sim_quality_desc($elog->sim_quality_rating);

  
  $form['quality_rating'] = array(
		'#type' => 'item',
		'#title' => t('Simulator Quality Rating'),
		'#markup' => $rating,
    '#prefix' => '<br />',
    '#suffix' => '<br />',
	);
  
  // Was a DR filed resulting from this training session?
  if ( isset($elog->discrepancy_reported) && $elog->discrepancy_reported ) {
    $form['discrepancy'] = array(
      '#type' => 'item',
      //'#title' => t(''),
      '#markup' => 
        '<b>' . 
           t('A Discrepancy Report has been filed.') .
        '</b>',
    );
  }
	
		
	//--------------- Hidden -------------------------
	$form['assignment_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $elog->assignment_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	

	$form['elog_id'] = array(
		'#type' => 'textfield',
		'#default_value' => (isset($elog->elog_id) ? $elog->elog_id : 0),
		'#attributes' => array('class' => array('qms-hidden')),
	);	


	//--------------- Buttons -------------------------		
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
    '#name' => 'submit',
		'#value' => t('Done'),
	);
  $form['actions']['print'] = array(
		'#type' => 'button',
		'#value' => t('Print'),
    '#name' => 'print',
		'#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
	);
  $form['actions']['edit'] = array(
		'#type' => 'submit',
		'#value' => t('Edit'),
    '#name' => 'edit',
		'#attributes' => array('class' => array('qms-btn-edit', 'qms-btn-extra')),
	);
	 

	return $form;
}

/*
 *	view_elog_form_submit()
 *
 *  Overloads hook_form_submit()
 *  VIEW ONLY submit handler, just routes
 */


function view_elog_form_submit($form, $form_state) {
  
  $button_clicked = $form_state['triggering_element']['#name'];
  
  if ( $form['actions']['submit']['#name'] == $button_clicked ){
    
    $destination = drupal_get_destination();
    $goto_url = $destination['destination'];

    if( !strlen($goto_url) || ($goto_url == current_path()) ) {
      if ( user_access('manager menu')) {
        $goto_url = 'reports/search/elogs';
      }
      else {
        $goto_url = '';
      }
    }

    drupal_goto($goto_url); 
    
  }
	else if ( isset($form['actions']['edit']['#name']) &&
            ($form['actions']['edit']['#name'] == $button_clicked)) {
      
    $elog_id = isset($form_state['values']['elog_id']) ? 
                        (int) $form_state['values']['elog_id'] : 0;
  
    if ( !$elog_id && isset($form['elog_id']['#default_value'])) {
      $elog_id = $form['elog_id']['#default_value'];
    }
    if ( $elog_id ) {

      // we have to force $_GET['destination'] otherwise drupal_goto
      // ignores the supplied path and reverts to the destination setting
      $_GET['destination'] = 'elog/edit/' . $elog_id . 
                '?destination=elog/view/' . $elog_id;
    }
  }
	
  
}





/*
 *		_get_elog()
 *
 *		retrieves the e-log record by the elog_id or assignment_id
 */

function _get_elog($elog_id = 0, $assignment_id = 0) {
	try {
		
		$elog = Null;
		
		if ( $elog_id || $assignment_id ) { 
			$query = db_select('sch_elogs', 'e');
			$query->innerJoin('sch_assignments', 'a', 'e.assignment_id = a.assignment_id');
			$query->innerJoin('sch_schedule_sessions', 's', 'a.schedule_session_id = s.schedule_session_id');
			$query->innerJoin('sch_customers', 'c', 'a.customer_id = c.customer_id');
			$query->leftJoin('sch_groups', 'g', 'a.group_id = g.group_id');
			$query->innerJoin('sch_session_names', 'sn', 's.session_name_id = sn.session_name_id');
			$query->innerJoin('sch_session_types', 't', 'a.session_type = t.session_type');
      
      if ( $elog_id ) {
        $query->condition('e.elog_id', (int)$elog_id);
      }
      else if ( $assignment_id ) {
        $query->condition('e.assignment_id', (int)$assignment_id);
      }
			
			$query->fields('e', array('elog_id', 'assignment_id', 'el_no', 
                                'log_text', 'sim_quality_rating', 
                                'created_date', 'created_by_user', 
                                'updated_date', 'updated_by_user'))
					  ->fields('a', array('schedule_id', 'schedule_session_id', 
                                'begin_time_actual', 'end_time_actual',
																'customer_id', 'group_id', 
                                'session_type', 'cut_bill', 
                                'discrepancy_reported', 
																'begin_timestamp', 'end_timestamp', 'total_time', 
																/*'created_date', 'created_by_user', 
                                'updated_date', 'updated_by_user',*/
															))
						->fields('c', array('customer', 'customer_code'))
						->fields('g', array('group_name', 'group_code'))
						->fields('sn', array('session_name_id', 'session_name'))
						->fields('t', array('session_type_desc'));
			$result = $query->execute();
			
			if ( $result->rowCount() ) {
				$elog = $result->fetchObject();
			}
		}												
		return $elog;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_elog() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

/*
 *		_get_elog_crew_info()
 *
 *		retrieves the e-log crew records by the elog_id
 */

function _get_elog_crew_info($elog_id) {
	try {
		
		$elog_crew = array();
		
		if ( $elog_id ) { 
			$query = db_select('sch_elog_crew', 'cr');
      $query->innerJoin('sch_flight_roles', 'fr', 'cr.flight_role_1_id = fr.flight_role_id');
			$query->condition('elog_id', $elog_id);
			$query->fields('cr', array('elog_crew_id', 'elog_id', 'fname', 'lname', 
																'flight_role_1_id', 'flight_role_1_time', 
                                'flight_role_2_id', //'flight_role_2_time', 
																'created_date', 'created_by_user', 'updated_date', 'updated_by_user'));
      $query->fields('fr', array('flight_role_code', 'flight_role_name'));
			$result = $query->execute();
			
			if ( $result->rowCount() ) {
				$elog_crew = $result->fetchAll();
			}
		}												
		return $elog_crew;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_elog_crew_info() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}


/*
 * 
 *  _get_flight_role_time_opts()
 * 
 */
function _get_flight_role_time_opts($f_assign_hours = 0) {
  
  $all = sprintf('%0.2f', $f_assign_hours);
  
  $hours_opts = array( $all => t('FULL') );
    
  if ( $f_assign_hours > (float) 9 ) {
    $hours_opts += array(
      '10.00' => '10  ',
      '9.75' => '9.75',
      '9.50' => '9.50',
      '9.25' => '9.25',
    );
  }
  if ( $f_assign_hours > (float) 8 ) {
    $hours_opts += array(
      '9.00' => '9   ',
      '8.75' => '8.75',
      '8.50' => '8.50',
      '8.25' => '8.25',
    );
  }
  if ( $f_assign_hours > (float) 7 ) {
    $hours_opts += array(
      '8.00' => '8   ',
      '7.75' => '7.75',
      '7.50' => '7.50',
      '7.25' => '7.25',
    );
  }
  if ( $f_assign_hours > (float) 6 ) {
    $hours_opts += array(
      '7.00' => '7   ',
      '6.75' => '6.75',
      '6.50' => '6.50',
      '6.25' => '6.25',
    );
  }
  if ( $f_assign_hours > (float) 5 ) {
    $hours_opts += array(
      '6.00' => '6   ',
      '5.75' => '5.75',
      '5.50' => '5.50',
      '5.25' => '5.25',
    );
  }
  if ( $f_assign_hours > (float) 4 ) {
    $hours_opts += array(
      '5.00' => '5   ',
      '4.75' => '4.75',
      '4.50' => '4.50',
      '4.25' => '4.25',
    );
  }
  if ( $f_assign_hours > (float) 3 ) {
    $hours_opts += array(
      '4.00' => '4   ',
      '3.75' => '3.75',
      '3.50' => '3.50',
      '3.25' => '3.25',
    );
  }
  if ( $f_assign_hours > (float) 2 ) {
    $hours_opts += array(
      '3.00' => '3   ',
      '2.75' => '2.75',
      '2.50' => '2.50',
      '2.25' => '2.25',
    );
  }
  if ( $f_assign_hours > (float) 1 ) {
    $hours_opts += array(
      '2.00' => '2   ',
      '1.75' => '1.75',
      '1.50' => '1.50',
      '1.25' => '1.25',
    );
  }
  $hours_opts += array(
    '1.00' => '1   ',
    '0.75' => '0.75',
    '0.50' => '0.50',
    '0.25' => '0.25',
    '0' => '0',
  );

  return $hours_opts;
}



