<?php

/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		SIMULATOR DOWNtime functions
*/

require_once('sabreQMS.troublecall.inc');
require_once('sabreQMS.simulatordownlist.inc');

/*
 *	simulator_downtime_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays a Simulator Downtime form to accept user input
 */
function simulator_downtime_form($form, $form_state, $simulator_downtime_id = 0) {
	$bAdmin = user_access('administer sabreQMS');
	
	if ( (user_access('create simulator downtime') == FALSE) && ($bAdmin == FALSE) ) {
		drupal_set_message( t('Unauthorized:  Permission required'), 'status');
		return;
  }

	// edit existing shift log entry -- admin only
	$simulator_downtime = (object) Null;
  
  $goto_url = 'search/simulator_downtime';
	
	
	// all page-specific javascript loaded in the after_build function
	$form['#after_build'][] = 'simulator_downtime_form_after_build';
	$sd_no_base = '';
	
	
	if ( $simulator_downtime_id == 0 )  {		
		// NEW SIMULATOR DOWNTIME ENTRY
		$sd_no_base = _st_generate_report_base_no('SD');
	}
	else {
		// EDITING EXISTING SIMULATOR DOWNTIME ENTRY  (Admin Only!!!)
		
		if ( !$bAdmin ) {
			drupal_set_message( t('Unauthorized:  Permission required to edit a simulator downtime entry.'), 'status');
			drupal_goto($goto_url);
			return;
		}
		
		// get the simulator downtime record
		$sql = "SELECT s.simulator_downtime_id, s.sd_no, s.discrepancy_id, s.out_date, s.in_date, s.downtime, 
									 s.tech_user_id, s.updated_date, 
									 d.dr_no, d.simulator_id 
						FROM   {qms_simulator_downtime} s, {qms_discrepancy_log} d
						WHERE  s.simulator_downtime_id = :sdid 
						AND		 s.discrepancy_id = d.discrepancy_id";
		$result = db_query($sql, array(':sdid' => $simulator_downtime_id));
		
		if ( $result->rowCount() == 0 ) {
			drupal_set_message( t('Simulator Downtime Record Not Found!'), 'warning');
			drupal_goto('search/simulator_downtime');
			return;
		}
		$simulator_downtime = $result->fetchObject();		
	}
	// ---------------- Get the Form Selection Lists ---------------------
	global $simulator_list;
	//global $tech_list;
	
	
	//------------ BUILD FORM ------------------
	
	// storage field for the simulator_downtime_id (edit) -- hidden
	$form['simulator_downtime_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_downtime_id,
		'#attributes' => array('id' => 'qms-simulator-downtime-id',
													 'class' => array('qms-hidden-field')),
	);
	
	if ( $simulator_downtime_id == 0 ) { // NEW
		
		// only for display purposes -- the separately defined eng_no field is where the actual number is stored/retrieved
		// drupal can't access content from an 'item' field
		$form['sd_no_display'] = array(
			'#title' => t('SD No.'),
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($sd_no_base) . '__</div>',
			'#suffix' => '<div class="qms-desc">Assigned when submitted.</div><hr />',
		);		

		$form['sd_no'] = array(
			'#type' =>'textfield',
			'#default_value' => $sd_no_base,
			'#attributes' => array('class' => array('qms-hidden-field')),
		);		
		
	} 
	else {
		// only for display purposes -- the separately defined eng_no field is where the actual number is stored/retrieved
		// drupal can't access content from an 'item' field
		$form['sd_no_display'] = array(
			//'#title' => t('SD No.'),
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($simulator_downtime->sd_no) . '</div>',
			'#suffix' => ($simulator_downtime->updated_date) ? ('<div class="qms-desc">Last Updated:  ' . 
																	_st_format_date($simulator_downtime->updated_date, 'medium') . '</div><hr />') : '',
		);		

		$form['sd_no'] = array(
			'#type' =>'textfield',
			'#default_value' => t($simulator_downtime->sd_no),
			'#attributes' => array('class' => array('qms-hidden-field')),
		);		
		
	}
	
  // Field masking/autocomplete force validation even when we don't want it
  // turn required off
	$form['dr_no'] = array(
		'#title' => t('DR No.') . 
                '<span class="form-required" title="' . 
                  t('This field is required.') . '"> *</span>',
		'#type' =>'textfield',
		'#size' => 15,
		'#default_value' => (($simulator_downtime_id > 0) ? $simulator_downtime->dr_no : ''), 
		'#attributes' => array('id' => 'qms-dr-no', 'qms-sim-url' => url('drno/simulator')),
		'#required' => False,
		'#autocomplete_path' => 'drno/autocomplete',
		'#prefix' => '<table class="qms-plain-table" style="width:100%;"><tr style="vertical-align:middle;"><td width="25%">',
	);
	
	
	$form['simulator'] = array(
		'#type' => 'item',
		'#title' => t('Simulator'),
		'#markup' => '<div id="qms-simulator">' . 
									( ($simulator_downtime_id > 0) ? $simulator_list->getName($simulator_downtime->simulator_id) : '&nbsp;') . 
									'</div>',
		
	);
	
	global $user;
	$form['tech'] = array(
		'#type' => 'item',
		'#title' => t('Technician/Instructor'),
		'#markup' => (($simulator_downtime_id > 0) ? _get_user_name($simulator_downtime->tech_user_id) : _get_user_name($user->uid)),
		'#suffix' => '</td>',
	);
	
	/*
	$form['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Simulator'),
		'#options' => $simulator_list->get_active(),
		'#default_value' => (($simulator_downtime_id > 0) ? $simulator_downtime->simulator_id : 0),
		'#required' => True,
		'#attributes' => array('class' => array('qms-select'), 
													 'id' => 'qms-simulator-select'),
		'#suffix' => '</td>',
	);
	*/
	
	$form['out_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('Out of Service'),
		'#size' => 14,
		'#date_format' => 'm-d-Y H:i',						// displayed format
			//default value has to be in this format
		'#default_value' => (($simulator_downtime_id > 0) ? _st_format_date($simulator_downtime->out_date, 'short') : _st_format_date(0, 'custom', 'Y-m-d H:i')), 
		'#required' => False,   // if no date entered, returns NULL
		// don't set an id when there is a time involved (datepicker bug)
		// sets its own element id
		'#attributes' => array('class' => array('qms-date-picker')), 
		'#prefix' => '<td style="width:30%; text-align:left;">',
		'#suffix' => '</td>',
	);
	
	$in_date = '';
	if ( $simulator_downtime_id > 0 ) {
		if ( $simulator_downtime->in_date > 0 ) {
			$in_date = _st_format_date($simulator_downtime->in_date, 'short');
		}
	}
	
	
	$form['in_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('In Service'),
		'#size' => 14,
		'#date_format' => 'm-d-Y H:i',						// displayed format
			//default value has to be in this format
		'#default_value' => $in_date, 
		'#required' => False,   // if no date entered, returns NULL
		// don't set an id when there is a time involved (datepicker bug)
		// sets its own element id
		'#attributes' => array('class' => array('qms-date-picker')),
		'#prefix' => '<td style="text-align:left;">',
		'#suffix' => '</td></tr></table>',
	);
	
	// storage field for the downtime interval (edit) -- hidden
	// diff between in_date - out_date
	$form['downtime'] = array(
		'#type' => 'textfield',
		'#default_value' => (($simulator_downtime_id > 0) ? $simulator_downtime->downtime : 0), 
		'#attributes' => array('id' => 'qms-simulator-downtime-id',
													 'class' => array('qms-hidden-field')),
	);
	
	//--------------------- FORM ACTIONS (Buttons) -----------------------
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#name' => 'submit',
		'#attributes' => array('class' => array('qms-btn-submit')),
	);
	
	
	if ( $simulator_downtime_id ) {
		// if the user is an Admin, they are allowed to edit and to delete
		$form['actions']['delete'] = array(
			'#type' => 'submit',
      '#value' => t('Delete'),
      '#name' => 'delete',
      '#attributes' => array('class' => array('qms-btn-delete', 'qms-btn-extra')),
    );
		
	}

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

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

/* 
 * simulator_downtime_form_after_build()
 *
 */
function simulator_downtime_form_after_build($form, &$form_state)
{
	drupal_add_library('system','ui.datepicker');
	drupal_add_library('system','ui.dialog');
	
	// see http://digitalbush.com/projects/masked-input-plugin/
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/vendor/jquery.maskedinput-1.3.1.min.js');
  
  _st_add_js_timezone();
  
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	//drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.ckeditor.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.simulatordown.js');
	
	return $form;
}





/*
 *	simulator_downtime_form_validate()
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates the simulator_downtime entry form
 */

function simulator_downtime_form_validate($form, &$form_state) {
  
  $button_clicked = $form_state['triggering_element']['#name'];
  
  if ( $form['actions']['submit']['#name'] != $button_clicked ){
    return $form;
  }
	
	$dr_no = trim($form_state['values']['dr_no']);
	
	if ( $dr_no == '' ) {
		form_set_error('dr_no', t('DR No. is a required field'));
	}
	
	// search for $dr_no
	$sql = "SELECT discrepancy_id, date_closed FROM {qms_discrepancy_log} WHERE dr_no = :drno";
	$result = db_query($sql, array(':drno' => $dr_no));
	
	if ( $result->rowCount() == 0 ) {
		return form_set_error('dr_no', t('Unable to add Simulator Downtime entry.  ' . $dr_no . ' was not found.'));
	}
	if ( $result->rowCount() > 1 ) {
		return form_set_error('dr_no', t('Unable to add Simulator Downtime entry.  ' . $dr_no . ' matched multiple reports.'));
	}
	$discrepancy = (object) Null;
	$discrepancy = $result->fetchObject();
	if ( $discrepancy->date_closed > 0 ) {
		return form_set_error('dr_no', t('Unable to add Simulator Downtime entry.  ' . $dr_no . ' is already closed.'));
	}
	
	// do not allow multiple open SD reports per discrepancy.  Only one allowed
	$sql = "SELECT sd_no FROM {qms_simulator_downtime} WHERE in_date = 0 AND discrepancy_id = :did";
	$result = db_query($sql, array(':did' => $discrepancy->discrepancy_id));
	if ( $result->rowCount() > 1 ) {
		$sd_no = $result->fetchField();
		return form_set_error('dr_no', t('Unable to add Simulator Downtime entry for ' . $dr_no . '.<br />' . $sd_no . ' already exists and remains active.'));
	}
	
	
	//----------------- date checking ---------------------
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	// out_date will always be set, just needs to be valid
	$sd_out_date = trim($form_state['values']['out_date']);
	$isd_out_date = _st_format_timestamp($sd_out_date);  
		
	$sd_in_date = '';
	$isd_in_date = 0;
	if ( isset($form_state['values']['in_date'])) {
		$sd_in_date = trim($form_state['values']['in_date']);
		$isd_in_date = _st_format_timestamp($sd_in_date);  
	}
	
	if ( !isset($sd_out_date) || ($isd_out_date == 0) ) {
		form_set_error('out_date', t('Unable to add Simulator Downtime entry.  Out Date is a required field'));
	}
	
	if ( ( $isd_in_date > 0 ) && ($isd_in_date < $isd_out_date) ) {
		form_set_error('in_date', t('In Date cannot be set to a date earlier than the simulator Out Date.'));
	}
	
}

/*
 *	simulator_downtime_form_submit()
 *
 *  overloads:  hook_form_submit()
 *
 *	Handles the Simulator Downtime form submitted data, stores to db
 */
function simulator_downtime_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) ){
    
    $simulator_downtime_id = isset($form_state['values']['simulator_downtime_id']) ? 
                          (int) $form_state['values']['simulator_downtime_id'] : 0;
    if ( !$simulator_downtime_id && 
         isset($form['simulator_downtime_id']['#default_value'])) {
      $simulator_downtime_id = $form['simulator_downtime_id']['#default_value'];
    }

    if ( $simulator_downtime_id ) {
      $_GET['destination'] = 'simulator_downtime/delete/' . $simulator_downtime_id . 
                   '?destination=simulator_downtime/edit/' . $simulator_downtime_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/simulator_downtime';
    }	
    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 --------------------
	
	$simulator_downtime = new stdClass();
	
	// Alert Flags for sending emails to customer users linked to this customer's simulator
	// if customer users are linked, we will send out email alerts 
	// that the simulator is out of service or back in service
	$bAlertOutOfService = False;
	$bAlertInService = False;
	
	
	$simulator_downtime->simulator_downtime_id = (int) $form_state['values']['simulator_downtime_id'];	
	$simulator_downtime->updated_date = $currtimestamp = REQUEST_TIME;
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	$out_date = trim($form_state['values']['out_date']);
	$simulator_downtime->out_date = _st_format_timestamp($out_date);  

	$in_date = trim($form_state['values']['in_date']);
	if ( $in_date <> '' ) {
		$simulator_downtime->in_date = _st_format_timestamp($in_date); 
		
		//---------------- calculate the downtime --------------------------
		// store interval in seconds, convert as needed elsewhere
		$simulator_downtime->downtime = ($simulator_downtime->in_date - $simulator_downtime->out_date);  
		$bAlertInService = True;
	}
	else {
		$simulator_downtime->in_date = 0;
		$simulator_downtime->downtime = 0;
		$bAlertOutOfService = True;
	}
			
	
	if ( $simulator_downtime->simulator_downtime_id == 0 ) {
		
		$sd_base_no = $form_state['values']['sd_no'];
		$simulator_downtime->sd_no = _st_generate_report_no('SD', $sd_base_no);
		
		// set the tech_user_id to the current user, can't edit this later
		global $user;
		$simulator_downtime->tech_user_id = $user->uid;
		$bAlertOutOfService = True;
	}
	
	//----------------- search for corresponding dr_no, (+simulator) -----------------------
	
	$dr_no = trim($form_state['values']['dr_no']);
	
	$sql = "SELECT discrepancy_id, simulator_id, from_trouble_call_id 
					FROM {qms_discrepancy_log} WHERE dr_no = :drno";
	$result = db_query($sql, array(':drno' => $dr_no));
	if ( $result->rowCount() <> 1 ) {
		drupal_set_message(t('Unable to add Simulator Downtime entry.  Invalid DR No. ' . $dr_no . '.'), 'Error');
		return;
	}
	
	$discrepancy = $result->fetchObject();
	
	$simulator_downtime->discrepancy_id = $discrepancy->discrepancy_id;
	
		
	
	//----------------- save record -----------------------------------
	$bSuccess = False;
	
	// Table:  {qms_simulator_downtime}
	if ( $simulator_downtime->simulator_downtime_id > 0 ) {
		if ( drupal_write_record('qms_simulator_downtime', $simulator_downtime, 'simulator_downtime_id')) {
			 	// update
			$msg = 'Simulator Downtime entry has been successfully updated.';
			drupal_set_message(t($msg));	
			
			// Reload the cache 

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

			$key_cache = cache_get($key_cache_name);
			if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
				$search = $key_cache->data;
				_get_simulator_downtime_search_list($search, True);
			}
			$bSuccess = True;
		}
		else {
			$msg = 'Oops!  Something went wrong, updates to Engineering Log were not saved.';
			drupal_set_message(t($msg));	
		}
	}
	else {
		if ( drupal_write_record('qms_simulator_downtime', $simulator_downtime)) {
			// new record
			// new id was assigned -- saved successfully
			$msg = 'Simulator Downtime entry has been successfully added.';
			$bSuccess = True;
			
			if ( $discrepancy->from_trouble_call_id ) {
				// For an existing Trouble Call, we close it, when a new SD report is open
				// we do not want downtime double-counted against Sim availability
				_close_trouble_call($discrepancy->from_trouble_call_id, $simulator_downtime->out_date);
			}
		}
		else {
			$msg = 'Oops!  Something went wrong, Simulator Downtime entry was not saved.';
		}
		drupal_set_message(t($msg));	
	}
	
	if ( $bSuccess ) {
		//$customer_emails = _get_customer_emails($simulator_downtime->discrepancy_id);
				
		$simulator_id = $discrepancy->simulator_id;
		$sd_emails = _st_get_simulator_notification_email_list(QMS_APP, 
                                                          $simulator_id, 
                                                          QMS_NOTIFY_SIMULATOR_DOWNTIME);
		
		
		if ( strlen($sd_emails) && ( $bAlertOutOfService || $bAlertInService ) ) {
			global $simulator_list;
			$sim_name = $simulator_list->getName($simulator_id);
			
			if ( $bAlertOutOfService ) {
				$subject = 'Simulator Status Change:  ' . $sim_name . ' out of service.';
				$body = "Flight simulator, " . $sim_name . ", was taken out of service on " . 
								_st_format_date($simulator_downtime->out_date, "short") .	".<br /><br />" .
								"You will be notified when " . $sim_name . " is back in service.";
				_st_send_drupal_email($simulator_downtime->simulator_downtime_id . '_out', 
                              $subject, $body, $sd_emails);
			}
			else if ( $bAlertInService ) {
				$subject = 'Simulator Status Change:  ' . $sim_name . ' is back in service.';
				$body = "Flight simulator, " . $sim_name . ", was placed back in service on " . 
								_st_format_date($simulator_downtime->in_date, "short") . ".";
				_st_send_drupal_email($simulator_downtime->simulator_downtime_id . '_in', 
                              $subject, $body, $sd_emails);
			}
		}
		
	}
	
	//drupal_goto('simulator_downtime/edit/' . $simulator_downtime->simulator_downtime_id);  
	drupal_goto('search/simulator_downtime');  
}



/*
 *	view_simulator_downtime_form()
 *
 *  Overloads hook_form()
 *  Simulator Downtime VIEW ONLY form
 */

function view_simulator_downtime_form($form, $form_state, $simulator_downtime_id) {
	
	if (user_access('search view reports') == FALSE) {
		drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
		return $form;
  }
  
  if ( !$simulator_downtime_id ) { return $form; }
  
  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.view.js');

	// get the simulator downtime record
	$sql = "SELECT s.simulator_downtime_id, s.sd_no, s.discrepancy_id, s.out_date, s.in_date, s.downtime, 
								 s.tech_user_id, s.updated_date, 
								 d.dr_no, d.simulator_id 
					FROM   {qms_simulator_downtime} s, {qms_discrepancy_log} d
					WHERE  s.simulator_downtime_id = :sdid 
					AND		 s.discrepancy_id = d.discrepancy_id";
	$result = db_query($sql, array(':sdid' => $simulator_downtime_id));
	
	if ( $result->rowCount() == 0 ) {
		drupal_set_message( t('Simulator Downtime Record Not Found!'), 'warning');
		drupal_goto('search/simulator_downtime');
		return;
	}
	$simulator_downtime = $result->fetchObject();		
	
	
	global $simulator_list;
	//global $tech_list;

	
	//------------ BUILD FORM ------------------
	
	$form['sd_no'] = array(
		//'#title' => t('SD No.'),
		'#type' =>'item',
		'#markup' =>'<div class="qms-report-no">' .  t($simulator_downtime->sd_no) . '</div>',
		'#suffix' => ($simulator_downtime->updated_date) ? ('<div class="qms-desc">Last Updated:  ' . 
																_st_format_date($simulator_downtime->updated_date, 'medium') . '</div><hr />') : '',		
											
	);
	
	$form['dr_no'] = array(
		'#title' => t('Dr No.'),
		'#type' =>'item',
		'#markup' => t($simulator_downtime->dr_no),
		'#prefix' => '<table class="qms-plain-table" style="width:100%;"><tr style="vertical-align:top;"><td style="width:50%">',
	);
  
  // storage field for the simulator_downtime_id (edit) -- hidden
	$form['simulator_downtime_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_downtime_id,
		'#attributes' => array('id' => 'qms-simulator-downtime-id',
													 'class' => array('qms-hidden-field')),
	);
	

	$form['out_date'] = array(
		'#type' => 'item',
		'#title' => t('Out of Service Date'),
		'#markup' => _st_format_date($simulator_downtime->out_date, 'short'),
	);
	
	if ( $simulator_downtime->in_date ) {
		$form['in_date'] = array(
			'#type' => 'item',
			'#title' => t('In Service Date'),
			'#markup' => _st_format_date($simulator_downtime->in_date, 'short'),
		);
	}
	else {
		$form['in_date'] = array(
			'#type' => 'item',
			'#title' => t('In Service'),
			'#markup' => 'No',
		);		
	}
	
	$form['markup1'] = array(
		'#markup' =>'</td>',
	);
	
	$form['simulator'] = array(
		'#type' => 'item',
		'#title' => t('Simulator'),
		'#markup' => $simulator_list->getName($simulator_downtime->simulator_id),
		'#prefix' => '<td style="width:50%">',
	);
	
	$form['tech'] = array(
		'#type' => 'item',
		'#title' => t('Technician/Instructor'),
		'#markup' => _get_user_name($simulator_downtime->tech_user_id),
		'#suffix' => '</td></tr></table>',
	);

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

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'search/simulator_downtime';
	}
  
  
  //--------------------- FORM ACTIONS (buttons) ------------------------

	$form['actions'] = array( '#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => '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')),
	);
	
	
	return $form;
}



/*
 *	view_simulator_downtime_form_submit()
 *
 *  Overloads hook_form_submit()
 *  Simulator Downtime VIEW ONLY submit handler, just routes
 */


function view_simulator_downtime_form_submit($form, $form_state) {
	
	drupal_goto('search/simulator_downtime');
}

/*
 *	simulator_downtime_delete_confirm()
 *
 *  Delete the simulator_downtime log entry -- ADMIN ONLY
 */

function simulator_downtime_delete_confirm($form, $form_state, $simulator_downtime_id) {
		
	$bAdmin = user_access('administer sabreQMS');
	
	if ( $bAdmin == False ) {
		drupal_set_message(t('Administrator permissions required to delete a simulator downtime entry.'));
		drupal_goto('simulator_downtime/edit/' . $simulator_downtime_id);
		return;
	}
	
	// get the simulator_downtime log record
	$simulator_downtime = (object) Null;
	
	$result = db_query("SELECT s.sd_no, d.dr_no 
											FROM {qms_simulator_downtime} s, {qms_discrepancy_log} d 
											WHERE s.discrepancy_id = d.discrepancy_id
											AND   s.simulator_downtime_id = :sdid",
										array(':sdid' => $simulator_downtime_id));
	if ( $result->rowCount() == 0 ) {
		drupal_set_message(t('Unable to delete simulator downtime entry.  Record not found.'));
		drupal_goto('simulator_downtime/edit/' . $simulator_downtime_id);
		return;
	}
	$simulator_downtime = $result->fetchObject();
	
	// storage field for the discrepancy_id (edit) -- hidden
	$form['simulator_downtime_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_downtime_id,
		'#attributes' => array('id' => 'qms-simulator-downtime-id',
														'class' => array('qms-hidden-field')),
	);
	// storage field for the discrepancy_id (edit) -- hidden
	$form['sd_no'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_downtime->sd_no,
		'#attributes' => array('id' => 'qms-sd-no',
														'class' => array('qms-hidden-field')),
	);
	// storage field for the discrepancy_id (edit) -- hidden
	$form['dr_no'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_downtime->dr_no,
		'#attributes' => array('id' => 'qms-dr-no',
														'class' => array('qms-hidden-field')),
	);
	
	//global $tech_list;
	global $simulator_list;
  
  $title = t('Delete Simulator Downtime Entry') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $simulator_downtime->sd_no . ' for ' . 
                       $simulator_downtime->dr_no . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'simulator_downtime/edit/' . $simulator_downtime_id;
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  // force this here to avoid a problem with routing if cancelled
  $_GET['destination'] = 'search/simulator_downtime';
  
  return confirm_form($form, $title,	$goto_if_canceled, $question, 
                      $yes_btn, $no_btn);
	
}

/*
 *	simulator_downtime_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the simulator_downtime entry -- ADMIN ONLY
 */


function simulator_downtime_delete_confirm_submit($form, $form_state) {
	
	if ($form_state['values']['confirm']) {
		$simulator_downtime_id = (int) $form_state['values']['simulator_downtime_id'];
		$dr_no = $form_state['values']['dr_no'];
		$sd_no = $form_state['values']['sd_no'];
		
		$num_rows = db_delete('qms_simulator_downtime')
					->condition('simulator_downtime_id', $simulator_downtime_id, '=')
					->execute();
		
		if ( $num_rows <> 1 ) {
			$msg = t('Error occurred deleting simulator downtime entry.');
		}
		else {
			$msg = t('The simulator_downtime entry ' . $sd_no . ' for ' . $dr_no . ' has been deleted.');
		}
		
		drupal_set_message($msg);
		
		// Reload the cache 
		// determine cache name
		$search = (object) Null;
		$key_cache_name = _get_qms_cache_name(QMS_SIMULATORDOWNTIME_SEARCH_KEY); 
		
		$key_cache = cache_get($key_cache_name);
		if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
			$search = $key_cache->data;
			
			_get_simulator_downtime_search_list($search, True);
		}	
	}
	drupal_goto('search/simulator_downtime');
}













