<?php
/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Trouble Call Log function handling
 *    
*/

require_once('sabreQMS.troublecalllist.inc');

/*
 *	trouble_call_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays a Discrepancy Entry form to accept user input
 */


function trouble_call_form($form, $form_state, $trouble_call_id = 0) {
	
	
	global $base_url;  
	
	$bAllowEdit = user_access('edit trouble call log');
	$bAdmin = user_access('administer sabreQMS');
  $bAllowDelete = $bAdmin;
  $bAllowAddComments = user_access('add trouble call comments');
  $bAllowEditComments = user_access('edit trouble call comments');
	
	if ( (user_access('create trouble call log') == FALSE) && ($bAllowEdit == FALSE) ) {
		drupal_set_message( t('Unauthorized:  Permission required'), 'status');
		return $form;
  }
  
  //------------------- ROUTING ---------------------------
	// determine the return routing url
  
	$destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'search/troublecalls';
	}
  
	
	// javascript loaded in the after_build function
	$form['#after_build'][] = 'trouble_call_form_after_build';	
		
	$trouble_call = (object) Null;
	$tc_no_base = '';

	// NEW TC, trouble_call_id == 0, otherwise EDIT existing
	if ( $trouble_call_id == 0 ) {
		$tc_no_base = _st_generate_report_base_no('TC');	
	}
	else {
		// prevent non-Admin from editing
		if ( !$bAllowEdit ) {
			drupal_set_message( t('Unauthorized:  Administrator permission required to edit a closed trouble call report'), 
													'status');
			drupal_goto('search/troublecalls');
			return $form;
		}
		
		// trouble_call_id > 0, get the record
		$trouble_call = _get_trouble_call($trouble_call_id);
		
		if ( $trouble_call == (object) Null ) {
			drupal_set_message( t('Trouble Call Not Found!'), 'warning');
			drupal_goto('search/troublecalls');
			return $form;
		}
		
	}
	
	
	//------------ BUILD FORM ------------------
	
	// storage field for the trouble_call_id (edit) -- hidden
	$form['trouble_call_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $trouble_call_id,   // for ADD mode, this is 0
		'#attributes' => array('id' => 'qms-trouble-call-id',
													 'class' => array('qms-hidden-field')),
	);
	
	// TC No.  Display it, but do not allow it to be edited
	
	if ( $trouble_call_id == 0 ) { // NEW
		
		// only for display purposes -- the separately defined tc_no field is where the actual number is stored/retrieved
		// drupal can't access content from an 'item' field
		$form['tc_no_display'] = array(
			'#title' => t('TC No.'),
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . $tc_no_base . '__</div>',
			'#suffix' => '<div class="qms-desc">Assigned when submitted.</div><hr />',
		);		
	} 
	else {
		// only for display purposes -- the separately defined dr_no field is where the actual number is stored/retrieved
		// drupal can't access content from an 'item' field
		$form['tc_no_display'] = array(
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . $trouble_call->tc_no . '</div>',
			'#suffix' => _st_format_record_timestamp_table($trouble_call),
		);		
	}
	
	$form['tc_no'] = array(
		'#type' =>'textfield',
		'#default_value' => ($trouble_call_id > 0 ?  $trouble_call->tc_no : t($tc_no_base) ),
		'#attributes' => array('class' => array('qms-hidden-field')),
	);		
	
	
	//-----------------------------------------
	
	global $tech_list;
	global $simulator_list;  // if user is linked to a customer, this list will only be sims for that customer
	global $user;
  global $customer_list;
	
		
	/*
	// ASSIGN TECHNICIAN??  Is this feature enabled allowing for the tech to be assigned when DR is created or afterward
	$assign_technician  = variable_get(QMS_VAR_ASSIGN_TECHNICIAN, 0);  // if not set, default to off
	*/
	
	// USER IS CUSTOMER?
	$user_is_customer_id = _user_is_customer($user->uid);
		
		
	// setup a plain table for form layout
	$form['markup_1'] = array(
		'#markup' => '<table class="qms-plain-table" style="width:100%"><tr><td style="width:40%; vertical-align:top">',
	);
	
	if ( $user_is_customer_id ) {
		// user is not allowed to (re)assign a technician, display only element
		// display the tech/user	as the currently logged in user for new DRs and the user on record for saved DRs		
		$form['tech'] = array(
			'#type' => 'item',
			'#title' => t('Technician/Instructor'),
			'#markup' => (($trouble_call_id > 0) ?  _get_user_name($trouble_call->tech_user_id) : '[unassigned]'),
		);	
	}
	else { 
		
		if ( user_access('assign technician') ) {
			// user is allowed to assign a technician -- display dropdown list of employees from employee table
			$form['tech'] = array(
				'#type' => 'select',
				'#title' => t('Technician/Instructor'),
				'#options' => $tech_list->getActive(),
				// for new discrepancies, for user with assign privs, 
				// default to the current user in the select list if user is a tech
				// otherwise, non techs will default to '- Select -' option
				'#default_value' => (($trouble_call_id > 0) ? $trouble_call->tech_user_id : 
															(strlen($tech_list->getName($user->uid)) ? $user->uid : 0) ),
				'#required' => True,
				'#disabled' =>  (($trouble_call_id > 0) ? !$bAllowEdit : False),
				'#attributes' => array('class' => array('qms-select'),
															 'id' => 'qms-tech-select'),
			);
		}
		else {
			// display the tech/user as the currently logged in user for new TCs and the user on record for saved TCs			
			$form['tech_display'] = array(
				'#type' => 'item',
				'#title' => t('Technician/Instructor'),
				'#markup' => (($trouble_call_id > 0) ? _get_user_name($trouble_call->tech_user_id) : _get_user_name($user->uid)),
			);
		}
	}
	

		
	$active_only = ( !$trouble_call_id ) ? True : False;  // if editing, get all the customers
	
	if ( $user_is_customer_id ) {	
  	// logged in user is a customer account, display the customer name
		// only simulators for this customer will appear in the selection list below
		
		$form['customer_display'] = array(
			'#type' => 'item',
			'#title' => t('Customer'),
			'#markup' => $customer_list->getName($user_is_customer_id),			
		);
	}
	
	
	$form['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Simulator'),
		'#options' => $simulator_list->get($active_only),
		'#default_value' => (($trouble_call_id > 0) ? $trouble_call->simulator_id : 
																								( $simulator_list->get_active_count() == 1 ? 
																														$simulator_list->get_first_active() : 0 )),
		'#required' => True,
		'#disabled' =>  (($trouble_call_id > 0) ? !$bAllowEdit : False),
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'qms-simulator-select'),
	);
	
	$trouble_cause_list = new TroubleCauseList();
	
	$form['trouble_cause'] = array(
		'#type' => 'select',
		'#title' => t('Cause'),
		'#options' => $trouble_cause_list->get(),
		'#default_value' => (($trouble_call_id > 0) ? $trouble_call->trouble_cause_code : 0 ),
		'#required' => True,
		'#disabled' =>  (($trouble_call_id > 0) ? !$bAllowEdit : False),
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'qms-trouble-call-select'),
		'#suffix' => '</td>',
	);
	
	
	
	
	//-----------------------------------------
	// date input doesn't display properly when disabled, switch to display_only item elements
	
	$form['date_opened'] = array(
		'#type' => 'date_popup',
		'#title' => t('Opened'),
		'#size' => 14,
		'#date_format' => 'm-d-Y H:i',						// displayed format
			//default value has to be in this format
		'#default_value' => (($trouble_call_id > 0) ? _st_format_date($trouble_call->date_opened, 'short') : date('Y-m-d H:i')), 
		'#required' => True,   // if no date entered, returns NULL
		'#attributes' => array('class' => array('qms-date-picker')),
		'#prefix' => '<td><div style="display:inline;">',
	);
	
	$tc_closed = '';
	if ( $trouble_call_id > 0 ) {
		if ( $trouble_call->date_closed > 0 ) {
			$tc_closed = _st_format_date($trouble_call->date_closed, 'short');
		}
	}
	
	$form['date_closed'] = array(
		'#type' => 'date_popup',
		'#title' => t('Closed'),
		'#size' => 14,
		'#date_format' => 'm-d-Y H:i',						// displayed format
			//default value has to be in this format
		'#default_value' => $tc_closed, 
		'#required' => False,   // if no date entered, returns NULL
		'#attributes' => array('class' => array('qms-date-picker')),
		'#suffix' => '</div>',
	);
  
  // since date closed can appear in a number of different elements, enabled and disabled
	// we need to check its value from the browser and this is the only safe way to do it.
	// no need to format it, just store the unix time stamp value
	// only need to know if date_closed_verify > 0
	$form['date_closed_verify'] = array(
		'#type' => 'textfield',
		'#default_value' => (($trouble_call_id > 0) ? $trouble_call->date_closed : 0),
		'#attributes' => array('class' => array('qms-hidden-field'),
														'id' => 'qms-date-closed-verify'),
	);
	
	global $action_list;
	
	$form['corrective_action'] = array(
		'#type' => 'select',
		'#title' => t('Corrective Action'),
		'#options' => $action_list->getList(CorrectiveActionList::TC),
		'#default_value' =>  (($trouble_call_id > 0) ? $trouble_call->corrective_action_id : 0 ),
		'#required' => False,
		'#disabled' =>  (($trouble_call_id > 0) ? !$bAllowEdit : False),
		'#attributes' => array('id' => 'qms-corrective-actions-select',
													 'class' => array('qms-corrective-actions-select')),
	);
	
	$discrepancy_id = 0;
	$dr_link = _get_trouble_call_linked_discrepancy($trouble_call_id, 
																									'troublecall/edit/' . $trouble_call_id,
																									$discrepancy_id);
	
	if ( $discrepancy_id ) {
		$form['discrepancy_link'] = array(
			'#markup' => $dr_link,
		);
		
		// storage field for the discrepancy_id -- hidden
		$form['discrepancy_id'] = array(
			'#type' => 'textfield',
			'#default_value' => $discrepancy_id,   
			'#attributes' => array('id' => 'qms-discrepancy-id',
														 'class' => array('qms-hidden-field')),
		);
	}
	else {
		$form['discrepancy_link'] = array(
			'#type' => 'checkbox', 
			'#title' => t('Create a Discrepancy Report from this Trouble Call'),
			'#default_value' => 0,
			'#disabled' => !user_access('create discrepancy'), // disable if unable to create DR
			'#attributes' => array('id' => 'qms-create-discrepancy'),
		);
	}
  
// default to sending email notices, this can be turned off at the time
$form['notify'] = array(
    '#type' => 'checkbox', 
    '#title' => t('Send Notification Emails For This Report'),
    '#default_value' => 1,
    '#attributes' => array('id' => 'qms-notify'),
  );
	
	
	
	$form['markup_6'] = array(
		'#markup' => '</td></tr></table>',
	);
	
		
	//--------------- TROUBLE CALL TEXT EDITOR --------------	
	
	$text_settings = array(
		'name' => 'trouble_text',
		'title' => t('Trouble Call'),
		'text' =>	(($trouble_call_id > 0) ? $trouble_call->trouble_text : ''),
		'required' => True,
		'disabled' => (($trouble_call_id > 0) ? !$bAllowEdit : False),
	);
	 
	_st_add_text_editor($form, $text_settings);
  
  
  //---------------- COMMENTS -------------------------
	
	$form['fs_comments'] = array(
		'#type' => 'fieldset',
		'#title' => t('Comments'),
		'#collapsible' => True,
		'#collapsed' => ( (($trouble_call_id > 0) && ($trouble_call->has_comments)) ? False : True),
	);
	
		
	$comment_table = _get_comments_table('TC', $trouble_call_id);
	
	$form['fs_comments']['comments'] = array(
		'#markup' => '<div id="qms-comments-div">' . $comment_table,
	);
	
	//------------- ADD COMMENT TEXTAREA  -----------	
	
	// !!!! CASE SPECIFIC !!!! When a comment is entered but not added using the 'Add' comment button
	// !!!! comment will be stored and saved when the form is submitted
	
	unset($text_settings);  // clear previous values
	
	$text_settings = array(
		'name' => 'comment_text',
		'title' => t('Add Comment'),
		'text' =>	'',
		'required' => True,
		'disabled' => (($trouble_call_id > 0) ? !$bAllowAddComments : False),
		'omit_length' => True,
		'fieldset' => 'fs_comments',
		'prefix' => '<table class="qms-plain-table" style="width:100%"><tr><td>',
		'suffix' => '</td></tr></table>',
	);
	 
	_st_add_text_editor($form, $text_settings);
	
	//  -----------------------------------------	
			
	// can this user add new comments to a DR during an edit?
	// if user has create DR permission, then this should always be allowed
	// add and edit shares the same button need to enable if either perm is allowed, but if you can edit, you should be able to add
	// if you can't edit, then you won't see the "edit" link from the admin column
	$bEditComments = ($bAllowAddComments || $bAllowEditComments || $bAdmin);
	
	$form['fs_comments']['add_comment'] = array(
		'#type' => 'button',
		'#value' => t('Add'),
		'#attributes' => array('id' => 'qms-btn-add-comment',
                           'class' => array('qms-btn-reports'),
													 'qms-url' => (( $trouble_call_id > 0 ) ? 
																url('troublecall/comment/update') : 
																url('theme_comments_table'))),
		'#disabled' => ( ($trouble_call_id > 0) ? !$bEditComments : False),
		'#prefix' => '<div class="qms-actions">',
	);
  $form['fs_comments']['clear_comment'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
		'#attributes' => array('id' => 'qms-btn-clear-comment',
                           'class' => array('qms-btn-extra', 'qms-btn-reports')),
		'#disabled' => ( ($trouble_call_id > 0) ? !$bEditComments : False),
		'#suffix' => '<span id="qms-waiting-comments" class="qms-waiting"><img class="qms-waiting-img" src="' . $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span></div>', 

	);
	
	if ( $trouble_call_id == 0 ) {  // storage field for new Trouble Call, adding comments
		// need to wrap this in a hidden div since the textarea seems to want to display the grabber bar
		$form['fs_comments']['comments_to_add'] = array(
			'#type' => 'textarea',
			'#default_value' => '',
			'#prefix' => '<div id="qms-comments-hidden" class="qms-hidden-field">',
			'#attributes' => array('id' => 'qms-comments-to-add'),
			'#suffix' => '</div>',
		);
	}
	else {
		// during edits, stores the comment id in a hidden value
		$form['fs_comments']['comment_id'] = array(
			'#type' => 'textfield',
			'#default_value' => '',
			'#attributes' => array('id' => 'qms-comment-id',
															'class' => array('qms-hidden-field')),
		);		
	}
		
	$form['fs_comments']['comments_end_div'] = array(
		'#markup' => '</div>',
	);


	
	//----------------- FORM ACTIONS  ----------	
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#name' => 'submit',
		'#attributes' => array('class' => array('qms-btn-submit'),
                           'id' => 'qms-btn-submit'),
	);
	
	
	if ( $trouble_call_id && $bAllowDelete ) {
    
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#name' => 'delete',
      '#attributes' => array('class' => array('qms-btn-delete', 'qms-btn-extra')),
                             
      //'#validate' => array(),
      //'#limit_validation_errors' => array(),
      //'#submit' => array('trouble_call_form_button_delete'),
    );
	}
  
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
    '#name' => 'done',
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . url($goto_url) . 
                                        '"; return false;'),
	);
	
	
  
  //------------------------ Hidden Fields ----------------------
	// storage area for dynamic dialog elements
	$form['popup_dialog'] = array(
		'#type' => 'markup',
		'#markup' => '<div id="qms-message-box"></div>',
	);
	
	
	$form['report_changed'] = array(
		'#type' => 'textfield',
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-report-changed',
														'class' => array('qms-hidden-field')),
	);
  $form['form_validated'] = array(
		'#type' => 'textfield',
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-form-validated',
														'class' => array('qms-hidden-field')),
	);
	
	
		
	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.
*/

/* 
 * trouble_call_form_after_build()
 *
 */
function trouble_call_form_after_build($form, &$form_state)
{
	drupal_add_library('system','ui.datepicker');
	drupal_add_library('system','ui.dialog');
  
  _st_add_js_timezone();
  $sabreTools = drupal_get_path('module', 'sabreTools');
	drupal_add_js($sabreTools . '/js/sabreTools.lib.js');
	drupal_add_js($sabreTools . '/js/sabreTools.ckeditor.js');
	
	if ( (int)$form['trouble_call_id']['#default_value'] == 0) {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.troublecall.add.js');
  }
  else {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.troublecall.edit.js');
  }
	
	// WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
	if ( isset( $form['ckeditor_module_path'])  ) {		
		global $base_url;
		drupal_add_js( $base_url . QMS_CKEDITOR_PATH_CONFIG);
		// need to specify preprocess == false otherwise 'Aggregate Javascript' setting in drupal 
		// causes ckeditor not to load properly
		// adding scope to footer speeds up the page load
		drupal_add_js( $base_url . QMS_CKEDITOR_LIB, array('type' => 'file', 'scope' => 'footer', 'preprocess' => FALSE));
	}
		
	return $form;
}


/*
 *	trouble_call_form_validate()
 *
 *  Overloads hook_form_validate()
 *  Validation for the discrepancy_form
 */

function trouble_call_form_validate($form, &$form_state) {
  
  $button_clicked = $form_state['triggering_element']['#name'];
  
  if($form['actions']['submit']['#name'] != $button_clicked){
    
    return;
  }
	
	$err_msg = 'Required fields missing.  ';
	
	if ( 0 == (int) $form_state['values']['simulator'] ) {
		form_set_error('simulator', t($err_msg . 'Simulator is a required field'));
	}
	if ( 0 == (int) $form_state['values']['trouble_cause'] ) {
		form_set_error('trouble_cause', t($err_msg . 'Cause is a required field'));
	}
		
	$dr_text = trim($form_state['values']['trouble_text_editor_value']);
	if ( $dr_text == '' ) {
		form_set_error('qms_trouble_text', t($err_msg . 'Description is a required field'));
	}
	
	
	//----------------- date checking ---------------------
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	// date_opened may not always be present if the element is display only due to permission restrictions
  /*
	if ( isset($form_state['values']['date_opened']) ) {
		$date_opened = $form_state['values']['date_opened'];
		$idate_opened = _st_format_timestamp($date_opened);  
		if ( $idate_opened == 0 ) {
			form_set_error('date_opened', t($err_msg . 'Date Reported is a required field'));
		}
	}*/
	
	
	
	//----------------- date checking ---------------------
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	// date_opened may not always be present if the element is display only due to permission restrictions
	$date_opened = '';
	$idate_opened = 0;
	if ( isset($form_state['values']['date_opened']) ) {
		$date_opened = $form_state['values']['date_opened'];
		$idate_opened = _st_format_timestamp($date_opened . ':00');  
		if ( $idate_opened == 0 ) {
			form_set_error('date_opened', t($err_msg . 'Date Opened is a required field'));
		}
	}
	

	$date_closed = ( isset($form_state['values']['date_closed']) ? $form_state['values']['date_closed'] : '' );
	$idate_closed = _st_format_timestamp($date_closed);  
	
	if ( $idate_closed > 0 )  {
		if ( 0 == (int)$form_state['values']['corrective_action'] ) {
			form_set_error('corrective_action', t($err_msg . 'Corrective Action is required when closing a Trouble Call.'));
		}
		
		// this is ok since you have to have edit permissions in order to be able to close a TC
		if ( ($idate_opened > 0) && ($idate_closed > 0) && ($idate_closed < $idate_opened)) {
			form_set_error('date_closed', t('Date Closed cannot be set to a date earlier than the Date Opened.'));
		}
	}	
	
	if ( (isset($form_state['values']['discrepancy_link'])) &&
			 (1 == (int) $form_state['values']['discrepancy_link']) &&
	 	   (0 == (int) $form_state['values']['corrective_action']) ) {
		form_set_error('corrective_action', 
			t($err_msg . 'Corrective Action is required if creating a Discrepancy record from this Trouble Call'));
 }
	
//    if ( isset($form_state['values']['trouble_call_id']) && 
//        ((int)$form_state['values']['trouble_call_id'] > 0) &&
//        (0 == (int) $form_state['values']['corrective_action'])) {
//      form_set_error('corrective_action', 
//        t($err_msg . 'Corrective Action is required to be set for a Trouble Call report with a linked Discrepancy report'));
//    }
  
	
	
}

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

function trouble_call_form_submit($form, $form_state) {
  
  //---------------- Button Handlers --------------------
  
  $button_clicked = $form_state['triggering_element']['#name'];
  
  if ( isset($form['actions']['delete']['#name']) && 
       ($form['actions']['delete']['#name'] == $button_clicked) ){
    
    $trouble_call_id = isset($form_state['values']['trouble_call_id']) ? 
                        (int) $form_state['values']['trouble_call_id'] : 0;
  
    if ( !$trouble_call_id && isset($form['trouble_call_id']['#default_value'])) {
      $trouble_call_id = $form['trouble_call_id']['#default_value'];
    }
    if ( $trouble_call_id ) {
      $_GET['destination'] = 'troublecall/delete/' . $trouble_call_id . 
                            '?destination=troublecall/edit/' . $trouble_call_id;
    }
  }
  else if ( isset($form['actions']['done']['#name']) && 
            ($form['actions']['done']['#name'] == $button_clicked) ){
    
    $destination = drupal_get_destination();
    $goto_url = $destination['destination'];

    if( !strlen($goto_url) || ($goto_url == current_path()) ) {
      $goto_url = 'search/troublecalls';
    }	
    drupal_goto($goto_url);
    
  }
  else if ( $form['actions']['submit']['#name'] != $button_clicked ) {
    // if not delete & not done, then make sure its a submit click, otherwise, return
    return;
  }
  
  //---------------- SUBMIT:  Process Form --------------------
	
	$trouble_call = new stdClass();
	global $user;
	$currtime = REQUEST_TIME;
  $comment = new stdClass();
  $comment_list = array();
 
	
	$trouble_call_id = (int)$form_state['values']['trouble_call_id'];
	$trouble_call->simulator_id = (int)$form_state['values']['simulator'];
	$trouble_call->trouble_cause_code = (int)$form_state['values']['trouble_cause'];
	$trouble_call->corrective_action_id = (int)$form_state['values']['corrective_action'];
	
	// add seconds to make the timestamp iso standard
	$date_opened = $form_state['values']['date_opened']; 
	$trouble_call->date_opened = _st_format_timestamp($date_opened);
	$date_closed = ( isset($form_state['values']['date_closed']) ? 
											trim($form_state['values']['date_closed']) : '' );
	$trouble_call->date_closed = 0;
	if ( strlen($date_closed) ) {
		$trouble_call->date_closed = _st_format_timestamp($date_closed);  
	}
	
	$trouble_call->trouble_text = _st_clean_ckeditor_text($form_state['values']['trouble_text_editor_value'], 
																											QMS_TEXTAREA_MAX);
  
  $bNotify = (int)$form_state['values']['notify'];
  $bReportChanged = false;
	
  
  //-------------- NEW TROUBLE CALL ---------------------
	if ( $trouble_call_id == 0 )  {
    
		$tc_base_no = $form_state['values']['tc_no'];
		$trouble_call->tc_no = _st_generate_report_no('TC', $tc_base_no);
		$trouble_call->tech_user_id = $user->uid;
		$trouble_call->created_date = $currtime;
		$trouble_call->created_by_user = $user->uid;
    $trouble_call->updated_date = $currtime;
		$trouble_call->updated_by_user = $user->uid;
    
    $bReportChanged = True;
    
    if ( !$bNotify ) {
      // new TC but not sending out the 'New Trouble Call Report' email
      // update the updated_date by +1 so as not to trigger 
      // a "NEW report" email on an updated
      $trouble_call->updated_date++;
    }
    
    
    $cl = isset($_POST['comments_to_add']) ? $_POST['comments_to_add'] : '';
	
    // parse the grouped fields (|-delimited) into individual records
    if ( strlen($cl) > 0 ) {
      $comment_list = explode('|', $cl);
      $trouble_call->has_comments = 1;
    }
		
		// Save NEW trouble call
		if ( False == drupal_write_record('qms_trouble_call_log', $trouble_call)) {
			$msg = 'Oops!  Something went wrong, Trouble Call Log entry was not saved.';
			drupal_set_message($msg);
			drupal_goto('troublecall/add');
			return;
		}
		else {
			$msg = "Trouble Call Log entry was successfully saved.";
			drupal_set_message(t($msg));
		}
    
    if ( count($comment_list) ) {
      // store comments
      $comment->trouble_call_id = $trouble_call->trouble_call_id;
      $comment->user_id = $user->uid;  // currently logged in user
      $comment->name = $user->name;
      $comment->timestamp = $currtime;
      $msg = '';
      foreach ($comment_list as $cmt) {
        // comment length is controlled from the browser, 
        // but if that fails for some reason, trim it here
        $comment->comment =  _st_clean_ckeditor_text($cmt, QMS_TEXTAREA_MAX);

        if ( False == drupal_write_record('qms_trouble_call_comments', $comment)) {
          $msg = 'Oops!  Something went wrong saving the Trouble Call comment record to the database.';
          $bError = True;
        }

        // record stored, clear unique fields in prep for next comment record to save
        unset($comment->trouble_call_comment_id);
        unset($comment->comment);
      }
      if ( $msg <> '' ) {
        drupal_set_message(t($msg));	
      }
    }

	}
	else {
    
    //-------------- UPDATE TROUBLE CALL ---------------------
    $trouble_call->trouble_call_id = $trouble_call_id;
    $trouble_call->updated_date = $currtime;
		$trouble_call->updated_by_user = $user->uid;
    

    $bReportChanged = (int)$form_state['values']['report_changed'];


    // check if comments input, but not specifically added... if so, add them now  (only one of each)
    $comment = (object) Null;
    $comment->comment = _st_clean_ckeditor_text(
            $form_state['values']['comment_text_editor_value'], 
            QMS_TEXTAREA_MAX
          );

    if ( strlen($comment->comment) ) {

      $comment->trouble_call_comment_id = (int) $form_state['values']['comment_id'];
      $comment->trouble_call_id = $trouble_call->trouble_call_id;
      $comment->user_id = $user->uid;  // currently logged in user
      $comment->timestamp = $currtime;


      if ( $comment->trouble_call_comment_id == 0 ) {
        unset( $comment->trouble_call_comment_id );

        if ( False == drupal_write_record('qms_trouble_call_comments', $comment) ) {
          drupal_set_message(t('Oops!  Something went wrong saving the Trouble Call comment to the database.'));	
        }
        else { $bCommentAdded = True; }
      }
      else {
        unset($comment->user_id);
        if ( False == drupal_write_record('qms_trouble_call_comments', $comment, 'discrepancy_comment_id') ) {
          drupal_set_message(t('Oops!  Something went wrong saving the Trouble Call comment to the database.'));	
        }
        else { $bCommentAdded = True; }
      }

      $bReportChanged = True;
      $trouble_call->has_comments = 1;
    }

		
		
		if ( False == drupal_write_record('qms_trouble_call_log', $trouble_call, 'trouble_call_id')) {
			 	// update
				$msg = 'Oops!  Something went wrong, updates to Trouble Call Log were not saved.';
				drupal_set_message(t($msg));	
				drupal_goto('troublecall/edit/' . $trouble_call->trouble_call_id );
				return;
		}
		else {
			$msg = "Trouble Call Log entry was successfully saved.";
			drupal_set_message(t($msg));
			
		}
		
		
		// Reload the cache 
		// determine cache name
		$search = (object) Null;
		$key_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_KEY); 

		$key_cache = cache_get($key_cache_name);
		if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
			$search = $key_cache->data;
			_get_trouble_call_search_results($search, 0, True);
		}
	}
  
  if ( $bReportChanged && $bNotify ) {
    // SEND EMAIL NOTIFICATIONS
    _trouble_call_add_update_post_processing($trouble_call->trouble_call_id);
  }
	
	
	// determine routing
	
	if (isset($form_state['values']['discrepancy_link']) && 
			(1 == (int) $form_state['values']['discrepancy_link'])) {
		
		$options = array();
		/*
		if ( True == user_access('edit trouble call log') ) {
			$options = array('query' => array('destination' => 'troublecall/edit/' . $trouble_call->trouble_call_id));
		}*/
		drupal_goto('troublecall/discrepancy/add/' . $trouble_call->trouble_call_id, $options);
	}
	else if ( True == user_access('edit trouble call log') ) {	
		drupal_goto('troublecall/edit/' . $trouble_call->trouble_call_id );
	}
	else if ( True == user_access('search view logs') ) {
		drupal_goto('troublecall/view/' . $trouble_call->trouble_call_id );
	}
	else {
		drupal_goto(''); // go to home page if permissions don't allow anything else  
	}
	
}




/*------ VIEW --------*/

/*
 *	view_trouble_call_form()
 *
 *  Overloads hook_form()
 *  Trouble Call VIEW ONLY form
 */

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

	if ( $trouble_call_id == 0 ) {
		drupal_set_message( t('Invalid.  trouble_call_id == 0'), 'status');
		return $form;
	}
	
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.view.js');

	$trouble_call = _get_trouble_call($trouble_call_id);

	if ( $trouble_call == (object) Null ) {
		drupal_set_message( t('Trouble Call Not Found!'), 'warning');
		drupal_goto('search/troublecalls');
		return $form;
	}
			
		
	//------------ BUILD VIEW-ONLY FORM ------------------
	
	$form['tc_no'] = array(
		'#type' =>'item',
		'#markup' => '<div class="qms-report-no">' . t($trouble_call->tc_no) . '</div>',
		'#suffix' => _st_format_record_timestamp_table($trouble_call),
	);	
  
  $form['trouble_call_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $trouble_call_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	
	
	//-----------------------------------------
	
	//global $tech_list;
	global $simulator_list;
	
	$form['tech'] = array(
		'#type' => 'item',
		'#title' => t('Technician/Instructor'),
		'#markup' => (($trouble_call->tech_user_id) ? _get_user_name($trouble_call->tech_user_id) : '[unassigned]'),
		'#prefix' => '<table class="qms-plain-table" style="width:100%"><tr><td style="width:40%">',
	);

	$form['customer'] = array(
		'#type' => 'item',
		'#title' => t('Customer'),
		'#markup' => _get_simulator_customer_name($trouble_call->simulator_id),
		
	);
	
	$form['simulator'] = array(
		'#type' => 'item',
		'#title' => t('Simulator'),
		'#markup' => $simulator_list->getName($trouble_call->simulator_id),
		
	);	
	
	//-----------------------------------------
	$form['date_opened'] = array(
		'#type' => 'item',
		'#title' => t('Date Opened'),
		'#markup' => _st_format_date($trouble_call->date_opened, 'short'),
		'#size' => 14,
		'#prefix' => '<td style="width:33%"><div style="display:inline">',
	);
	
	$form['date_closed'] = array(
		'#type' => 'item',
		'#title' => t('Date Closed'),
		'#markup' => ((isset($trouble_call->date_closed) && ($trouble_call->date_closed)) ? 
											_st_format_date($trouble_call->date_closed, 'short') : ''),
		'#size' => 14,
		'#suffix' => '</div></td>',
	);
	
	$form['markup3'] = array(
		'#markup' => '</tr><tr>',
	);
	
	$trouble_cause_list = new TroubleCauseList();
	
	$form['trouble_cause'] = array(
		'#type' => 'item',
		'#title' => t('Cause'),
		'#markup' => ($trouble_call->trouble_cause_code ? 
											$trouble_cause_list->getName($trouble_call->trouble_cause_code) : '[' . t('None') . ']'),
		'#prefix' => '<td>',
		'#suffix' => '</td>',
	);
	
	
	global $action_list;
	
	$form['corrective_action'] = array(
		'#type' => 'item',
		'#title' => t('Corrective Action'),
		'#markup' => ( $trouble_call->corrective_action_id ? 
				$action_list->getName(CorrectiveActionList::TC, $trouble_call->corrective_action_id) : 
				'[' . t('None') . ']'),
		'#prefix' => '<td>',
	);
	
	$discrepancy_id = 0;
	$dr_link = _get_trouble_call_linked_discrepancy($trouble_call_id, 
																									'troublecall/view/' . $trouble_call_id, 
																									$discrepancy_id);
	
	if ( $trouble_call_id ) {
		$form['discrepancy_link'] = array(
			'#markup' => $dr_link,
		);
	}
	
	
				
	$form['markup4'] = array(
		'#markup' => '</td></tr></table>',
	);
	
	
	
	//-----------------------------------------
	
	// these items placed in a table for style consistency with the rest of the elements
	
	// WYSIWYG EDITOR??  If enabled, we format differently for textareas than for the editor
	$ckeditor_activated = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON
	
	
	$form['trouble_text'] = array(
		'#type' => 'item',
		'#title' => t('Description'),
		'#prefix' => '<table class="qms-plain-table" style="width:100%"><tr><td>',
		'#markup' =>  ($ckeditor_activated ? 
										_st_convert_symbols($trouble_call->trouble_text) : 	
									 	nl2br(_st_convert_symbols($trouble_call->trouble_text))),
		'#suffix' => '</td></tr></table>',
	);
  
  
  //---------------- COMMENTS -------------------------
	
	
	if ( $trouble_call->has_comments ) {
		$comment_table = _get_comments_table('TC', $trouble_call_id, True);  //view_only=true
		
		$form['comments'] = array(
			'#markup' => $comment_table,
		);
		
	}
  
  
  //--------------------- Links & Buttons -------------------------------
	
	
	$next_report_link = '';
	$prev_report_link = '';

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

	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$search_results = $results_cache->data;
		$results_table_rows = $search_results->getResults();
		$prev_id = _st_array_key_relative($results_table_rows, $trouble_call_id, -1);
		if ( $prev_id !== False ) {
			//$prev_report_link = l(t('View Previous'), 'troublecall/view/' . $prev_id );
      $form['view_previous_link'] = array(
        '#type' => 'textfield',
        '#default_value' => 'troublecall/view/' . $prev_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
		}
		$next_id = _st_array_key_relative($results_table_rows, $trouble_call_id, 1);
		if ( $next_id !== False ) {
			//$next_report_link = l(t('View Next'), 'troublecall/view/' . $next_id );
      $form['view_next_link'] = array(
        '#type' => 'textfield',
        '#default_value' => 'troublecall/view/' . $next_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
		}
	}
	
	$destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'search/troublecalls';
	}
	
	
	$form['actions'] = array( '#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Done'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
	);
  
  $form['actions']['print'] = array(
		'#type' => 'button',
		'#value' => t('Print'),
    '#name' => 'print',
		'#attributes' => array('class' => array('qms-print', 'qms-btn-extra')),
	);
	
	
	if ( (!$trouble_call->date_closed)  || ( user_access('administer sabreQMS') == True ) ) {
//		$form['actions']['edit'] = array(
//			'#markup' => l(t('Edit'), 'troublecall/edit/' . $trouble_call_id,
//											array('query' => array('destination' => 'troublecall/view/' . $trouble_call_id))),
//		);
    
    $form['actions']['edit'] = array(
      '#type' => 'submit',
      '#value' => t('Edit'),
      '#name' => 'edit',
      '#attributes' => array('class' => array('qms-btn-edit', 'qms-btn-extra'),
                              'query' => array('destination' => 
                                              'troublecall/view/' . $trouble_call_id)),
    );
	}
	
  if ( isset($form['view_previous_link']) ) {
		$form['actions']['view_previous'] = array(
			'#type' => 'submit',
      '#value' => t('View Previous'),
      '#name' => 'view_previous',
      '#attributes' => array('class' => array('qms-btn-previous', 'qms-btn-extra'),
                              'query' => array('destination' => 
                                                'troublecall/view/' . $trouble_call_id)),
		);
	}
	
	if ( isset($form['view_next_link']) ) {
		$form['actions']['view_next'] = array(
			'#type' => 'submit',
      '#value' => t('View Next'),
      '#name' => 'view_next',
      '#attributes' => array('class' => array('qms-btn-next', 'qms-btn-extra'),
                              'query' => array('destination' => 
                                                'troublecall/view/' . $trouble_call_id)),
      
		);
	}

	
	return $form;
}


/*
 *	view_trouble_call_form_submit()
 *
 *  Overloads hook_form_submit()
 *  trouble call VIEW ONLY submit handler, just routes
 */


function view_trouble_call_form_submit($form, $form_state) {
  
  $button_clicked = $form_state['triggering_element']['#name'];
  
  if ( $form['actions']['submit']['#name'] == $button_clicked ){
    drupal_goto('search/troublecalls');
  }
	else if ( isset($form['actions']['edit']['#name']) &&
            ($form['actions']['edit']['#name'] == $button_clicked)) {
      
    $trouble_call_id = isset($form_state['values']['trouble_call_id']) ? 
                        (int) $form_state['values']['trouble_call_id'] : 0;
    if ( !$trouble_call_id && isset($form['trouble_call_id']['#default_value'])) {
      $trouble_call_id = $form['trouble_call_id']['#default_value'];
    }

    if ( $trouble_call_id ) {

      // we have to force $_GET['destination'] otherwise drupal_goto
      // ignores the supplied path and reverts to the destination setting
      $_GET['destination'] = 'troublecall/edit/' . $trouble_call_id . 
                '?destination=troublecall/view/' . $trouble_call_id;
    }
  }
  else if ( isset($form['actions']['view_previous']['#name']) &&
            ($form['actions']['view_previous']['#name'] == $button_clicked)) {
    
    $prev_link = isset($form_state['values']['view_previous_link']) ? 
                  $form_state['values']['view_previous_link'] : '';
    if ( !strlen($prev_link) ) {
      $prev_link = isset($form['view_previous_link']) ? 
                    $form['view_previous_link']['#default_value'] : '';
    }

    if ( strlen($prev_link) ) {
      $_GET['destination'] = $prev_link . '?destination=search/troublecalls';
    }
  }
  else if ( isset($form['actions']['view_next']['#name']) &&
            ($form['actions']['view_next']['#name'] == $button_clicked)) {
    
    $next_link = isset($form_state['values']['view_next_link']) ? 
                  $form_state['values']['view_next_link'] : '';
    if ( !strlen($next_link) ) {
      $next_link = isset($form['view_next_link']) ? 
                    $form['view_next_link']['#default_value'] : '';
    }
    if ( strlen($next_link) ) {
      $_GET['destination'] = $next_link . '?destination=search/troublecalls';
    }
  }
}





/*
 *	trouble_call_delete_confirm()
 *
 *  Delete the trouble_call report -- ADMIN ONLY
 */

function trouble_call_delete_confirm($form, $form_state, $trouble_call_id) {
		
	$bAdmin = user_access('administer sabreQMS');
	
	if ( $bAdmin == False ) {
		drupal_set_message(t('Administrator permissions required to delete a trouble call report.'));
		drupal_goto('troublecall/edit/' . $trouble_call_id);
		return $form;
	}
	
	// get the tc_no
	$trouble_call = array();
	$result = db_query("SELECT tc_no FROM {qms_trouble_call_log} WHERE trouble_call_id = :tcid", 
										array(':tcid' => $trouble_call_id));
	$trouble_call = $result->fetchObject();
	
	// store the trouble_call_id and dr_no in hidden fields for the next step
	// storage field for the trouble_call_id (edit) -- hidden
	$form['trouble_call_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $trouble_call_id,
		'#attributes' => array('id' => 'qms-trouble-call-id',
														'class' => array('qms-hidden-field')),
	);
	// storage field for the trouble_call_id (edit) -- hidden
	$form['tc_no'] = array(
		'#type' => 'textfield',
		'#default_value' => $trouble_call->tc_no,
		'#attributes' => array('id' => 'qms-tc-no',
														'class' => array('qms-hidden-field')),
	);
  
  $title = t('Delete Trouble Call') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $trouble_call->tc_no . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'troublecall/edit/' . $trouble_call_id;
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  // force this here to avoid a problem with routing if cancelled
  $_GET['destination'] = 'search/troublecalls';
  
  return confirm_form($form, $title,	$goto_if_canceled, $question, 
                      $yes_btn, $no_btn);
	
}

/*
 *	trouble_call_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the trouble_call -- ADMIN ONLY
 */
function trouble_call_delete_confirm_submit($form, $form_state) {
	
	try {
		if ($form_state['values']['confirm']) {
			$trouble_call_id = $form_state['values'] ['trouble_call_id'];
			$tc_no = $form_state['values']['tc_no'];
				
			$num_rows = db_delete('qms_trouble_call_log')
						->condition('trouble_call_id', $trouble_call_id, '=')
						->execute();
					
			$msg = ( ($num_rows == 1) ? $tc_no . ' has been deleted.' : 'Error occurred deleting' . $tc_no . '.');
			drupal_set_message($msg, 'status');
		
			// remove the troublecall search results, but leave the search key so that the list gets refreshed
			// leave the search key cache intact
		
			// Reload the cache 

			// determine cache name
			$search = (object) Null;
			$key_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_KEY); 
		
			$key_cache = cache_get($key_cache_name);
			if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
				$search = $key_cache->data;
			
				// refresh the cached search results to reflect any changes
				_get_trouble_call_search_results($search);
			}
		
		}
		drupal_goto('search/troublecalls');	
	}
	catch(Exception $e) {
		watchdog('sabreQMS', 'trouble_call_delete_confirm_submit()' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}

/*
 * _get_trouble_call($trouble_call_id)
 * Returns a trouble_call object
 */

function _get_trouble_call($trouble_call_id) {
	try{
	
		$trouble_call = (object) Null;
	
		if ( !$trouble_call_id ) { return $trouble_call; }
	
		$sql = "SELECT trouble_call_id, tc_no, tech_user_id, simulator_id, 
		 							 trouble_text, date_opened, date_closed, trouble_cause_code, 
									 corrective_action_id, has_comments, 
									 created_date, updated_date, updated_by_user, created_by_user 
						FROM {qms_trouble_call_log} 
						WHERE trouble_call_id = :tcid";					
		$result = db_query($sql, array(':tcid' => $trouble_call_id));
	
		if ( $result->rowCount() ) {
			$trouble_call = $result->fetchObject();
		}
		return $trouble_call;
	}
	catch(Exception $e) {
		watchdog('sabreQMS', '_get_trouble_call()' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}

/*
 * _get_trouble_call_linked_discrepancy($trouble_call_id)
 * Returns link text to the DR if the TC has one
 */

function _get_trouble_call_linked_discrepancy($trouble_call_id, $route_url = '', &$discrepancy_id = 0) {
	
	try {
		//$links = array();
		$link = '';
	
		// get associated DR
		if ( isset($trouble_call_id) && $trouble_call_id ) {
		
			// include the associated TC (only one possible), if there is one included in the DR itself
			// we have a linked TC report which initiated this DR
		
			$sql = "SELECT discrepancy_id, dr_no FROM {qms_discrepancy_log} WHERE from_trouble_call_id = :tcid";				
			$result = db_query($sql, array(':tcid' => $trouble_call_id));
		
			if ( $result->rowCount() ) {
				$discrepancy = $result->fetchObject();
				$discrepancy_id = $discrepancy->discrepancy_id;
				$link = l( $discrepancy->dr_no, 'discrepancy/view/' . $discrepancy->discrepancy_id,
											array('query' => array('destination' => $route_url))
				 						);
			}
		}
	
		return $link;
	
	}
	catch (Exception $e) {
		watchdog('sabreQMS', '_get_trouble_call_linked_discrepancy()' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}

/*
 * 	_close_trouble_call()
 * 	IN:  $trouble_call_id
 *  IN:	 $date_closed
 *
 *	return True (success) | False (Fail)
 */


function _close_trouble_call($trouble_call_id, $date_closed) {
	try {
		if ( $trouble_call_id ) {

			// Close the linked TC report (if there is one) and it isn't already closed
			// TC report's corrective action has to already be set before it gets converted to a DR
			$tc_rows = db_update('qms_trouble_call_log')
						->fields(array(
								'date_closed' => $date_closed
						))
						->condition('trouble_call_id', $trouble_call_id)
						->condition('date_closed', 0, '=')
						->execute();
			return True;
		}
		return False;
	}
	catch (Exception $e) {
		watchdog('sabreQMS', '_close_trouble_call()' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}


/*
 *  _trouble_call_add_update_post_processing($trouble_call->trouble_call_id);
 * 
 * 
 */
function _trouble_call_add_update_post_processing($trouble_call_id) {
  
  if ( !$trouble_call_id ) { return; }
  
  $trouble_call = _get_trouble_call($trouble_call_id);
  if ( Null == $trouble_call ) { return; }
  
  $tc_comments = _get_trouble_call_comments($trouble_call_id);
  global $user;
  $updated_date = 0;
  $bNew = false;
  
  
  $notify_type = QMS_NOTIFY_TROUBLE_CALL;
  $emails = _st_get_simulator_notification_email_list(QMS_APP, 
                                                      $trouble_call->simulator_id, 
                                                      $notify_type);
  
  // This TC was just created
	if ( $trouble_call->created_date == $trouble_call->updated_date ) {
		// Notifications for New TC
		
		// Determine the timestamp
    // we will bump the updated_date timestamp by 1 second so that it will no longer exactly 
    // match the created date and will no longer trigger a "New Trouble Call" Notice
    // but isn't significant to anything else
		$updated_date = $trouble_call->updated_date + 1;
    $email_title = t('New Trouble Call Report');
    $bNew = True;
  }
  else {
    $email_title = t('Updated Trouble Call Report');
    $bNew = False;
  }

    

  // there are users to be notified about this new TC, 
  // send out the notification emails
  if ( strlen($emails) ) 
  {		
    // format an email message to send out
    global $simulator_list;

    $subject = t('QMS NOTICE') . ' -- ' . $email_title . ' ' . t('for') . ' ' . 
                $simulator_list->getName($trouble_call->simulator_id);
    $body = _notify_trouble_call_email($email_title, $trouble_call, $tc_comments, $bNew);

    _st_send_drupal_email($trouble_call->trouble_call_id, $subject, $body, $emails);   

  }
  
  if ( $updated_date > 0) {
    // UPDATE the TC Timestamps, 
    $num_rows = db_update('qms_trouble_call_log')
                  ->fields(array(
                            'updated_date' => $updated_date,
                            'updated_by_user' => $user->uid,
                            ))
                  ->condition('trouble_call_id', $trouble_call_id)
                  ->execute();
  }
}


/*
 *   
 *
 *	_notify_trouble_call_email()
 *
 */

function _notify_trouble_call_email($title, $trouble_call, $tc_comments, $bNew = false) {
	
	
	$body = 
		'<h2><strong>' . $title . '</strong></h2>' .
		'<hr />';
  
  if ( $bNew ) {
    // this may return '' if created_by_user==0
    $email = _st_get_user_email($trouble_call->created_by_user);  
    $user_link = ( strlen($email) ? 
                 l(_get_user_name($trouble_call->created_by_user), 'mailto:' . $email) : 
                 _get_user_name($trouble_call->created_by_user) );
	
    $body .=
      '<p>' . t('This report was created') . ':  <br />' .
      ( $trouble_call->created_by_user ? $user_link . ', ' : '' ) . 
      ( $trouble_call->created_date ? _st_format_date($trouble_call->created_date, 'medium') : '') . '</p>';
  }
  else {
    $email = _st_get_user_email($trouble_call->updated_by_user);  
    $user_link = ( strlen($email) ? 
                 l(_get_user_name($trouble_call->updated_by_user), 'mailto:' . $email) : 
                 _get_user_name($trouble_call->updated_by_user) );
    
    $body .=
      '<p>' . t('This report was updated') . ':  <br />' .
      ( $trouble_call->updated_by_user ? $user_link . ', ' : '' ) . 
      ( $trouble_call->updated_date ? _st_format_date($trouble_call->updated_date, 'medium') : '') . '</p>';
  }
  
  $body .= '<hr />';
		
	$body .= _format_trouble_call_for_email($trouble_call, $tc_comments);
	
	return $body;
}



/*
 *   Format the trouble call report information for email
 *
 *	_format_trouble_call_for_email()
 *
 */

function _format_trouble_call_for_email($trouble_call, $tc_comments) {

		
	///////////////////////////////////////////////
	// format the contents of the TC for email  //
	///////////////////////////////////////////////
	global $simulator_list;	
	
	
	// Header Information
	$body =
		'<table>' .
		'<tr><td colspan="2"><h2><strong>' . $trouble_call->tc_no . '</strong></h2></td></tr>' . 
		'<tr><td><strong>' . t('Technician/Instructor') . '</strong></td><td>' . 
         _get_user_name($trouble_call->tech_user_id) . '</td></tr>' . 
		'<tr><td><strong>' . t('Simulator') . '</strong></td><td>' . 
         $simulator_list->getName($trouble_call->simulator_id) . '</td></tr>' . 
		'<tr><td><strong>' . t('Date Opened') . '</strong></td><td>' . 
         _st_format_date($trouble_call->date_opened, 'short') . '</td></tr>';
	
	// TC Text
	$body .= 
		'<tr><td colspan="2">&nbsp;</td></tr>' . 
		'<tr><td colspan="2"><h3><strong>' . t('Trouble Call') . '</strong></h3></td></tr>' . 
		'<tr><td colspan="2">' . $trouble_call->trouble_text . '</td></tr>' .
		'<tr><td colspan="2">&nbsp;</td></tr>';
		
	// TC Comments
	if ( count($tc_comments) ) {
		$body .= 
			'<tr><td colspan="2">&nbsp;</td></tr>' . 
			'<tr><td colspan="2"><h3><strong>' . t('Comments') . '</strong></h3></td></tr>';
		
		foreach ( $tc_comments as $cmt ) {
			$body .= '<tr><td colspan="2">' . $cmt->name . ' - ' . _st_format_date($cmt->timestamp, 'short') . '<hr />' . 
										$cmt->comment . '</td></tr>' . 
							 '<tr><td colspan="2">&nbsp;</td></tr>';
		}
	}	
	
		
	// End of TC
	$body .= '</table>';

	return $body;
}

