<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		ENGINEERING
*/

//require_once('sabreQMS.utils.inc');
require('sabreQMS.engineeringlist.inc');

/*
 *	engineering_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays an Engineering Entry form to accept user input
 */
function engineering_form($form, $form_state, $engineering_id = 0) {
	
	$bAdmin = user_access('administer sabreQMS');
	
	if ( (user_access('create engineering log') == FALSE) && ($bAdmin == FALSE) ) {
		drupal_set_message( t('Unauthorized:  Permission required'), 'status');
		return;
  }

	// edit existing shift log entry -- admin only
	$engineering = (object) Null;
	$eng_no_base = '';
  
  $goto_url = 'search/engineering';
	
	
	// all page-specific javascript loaded in the after_build function
	$form['#after_build'][] = 'engineering_form_after_build';
	
	
	if ( $engineering_id == 0 )  {		
		// NEW ENGINEERING LOG ENTRY
		$eng_no_base = _st_generate_report_base_no('ENG');
	}
	
	else {
		// EDITING EXISTING ENGINEERING LOG ENTRY  (Admin Only!!!)
		
		if ( !$bAdmin ) {
			drupal_set_message( t('Unauthorized:  Permission required to edit an engineering log entry.'), 'status');
			drupal_goto($goto_url);
			return;
		}
		
		// get the engineering log record
		$sql = "SELECT e.engineering_id, e.eng_no, e.discrepancy_id, e.datetime, e.module_updated, 
									 e.load_updated_id, e.tech_user_id, e.updated_date, 
									 d.dr_no,  d.simulator_id 
						FROM   {qms_engineering} e, {qms_discrepancy_log} d
						WHERE  e.engineering_id = :engid
						AND		 e.discrepancy_id = d.discrepancy_id";
		$result = db_query($sql, array(':engid' => $engineering_id));
		
		if ( $result->rowCount() == 0 ) {
			drupal_set_message( t('Engineering Record Not Found!'), 'warning');
			drupal_goto('search/engineering');
			return;
		}
		$engineering = $result->fetchObject();		
	}
	// ---------------- Get the Form Selection Lists ---------------------
	global $simulator_list;
	global $tech_list;
	$load_updated_list = new LoadUpdatedList();
	
	//------------ BUILD FORM ------------------
	
	// storage field for the engineering_id (edit) -- hidden
	$form['engineering_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $engineering_id,
		'#attributes' => array('id' => 'qms-engineering-id',
													 'class' => array('qms-hidden-field')),
	);

		
	if ( $engineering_id == 0 ) { // NEW
		// ENG No.  Display it, but do not allow it to be edited
		$form['eng_no'] = array(
			'#title' => t('Engineering No.'),
			'#type' =>'textfield',
			'#disabled' => True,
			'#size' => 13,
			'#value' => $eng_no_base,
			'#suffix' => '<div class="qms-desc">Assigned when submitted.</div><hr />',
		);	
		
		// 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['eng_no_display'] = array(
			'#title' => t('Eng No.'),
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($eng_no_base) . '__</div>',
			'#suffix' => '<div class="qms-desc">Assigned when submitted.</div><hr />',
		);		

		$form['eng_no'] = array(
			'#type' =>'textfield',
			'#default_value' => t($eng_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['eng_no_display'] = array(
			//'#title' => t('Eng No.'),
			'#type' =>'item',
			'#markup' => '<div class="qms-report-no">' . t($engineering->eng_no) . '</div>',
			'#suffix' => ($engineering->updated_date) ? ('<div class="qms-desc">Last Updated:  ' . 
																	_st_format_date($engineering->updated_date, 'medium') . '</div><hr />') : '',
		);		

		$form['eng_no'] = array(
			'#type' =>'textfield',
			'#default_value' => t($engineering->eng_no),
			'#attributes' => array('class' => array('qms-hidden-field')),
		);		
				
		
		$orig_date_entered = _st_format_date($engineering->datetime, 'short');

		// storage field for the engineering datetime (edit) -- hidden
		$form['original_datetime'] = array(
			'#type' => 'textfield',
			'#default_value' => $orig_date_entered,
			'#attributes' => array('id' => 'qms-original-datetime',
														 'class' => array('qms-hidden-field')),
		);

		$orig_date_entered = substr($orig_date_entered, 0, 10); // chop off the time portion for display purposes
	}
  
  $form['eng_table_begin'] = array(
    '#markup' => '<table class="qms-plain-table" style="width:100%;"><tr style="vertical-align:middle;"><td style="width:25%;">',
  );
  
	// 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' => (($engineering_id > 0) ? $engineering->dr_no : ''), 
		'#attributes' => array('id' => 'qms-dr-no', 'qms-sim-url' => url('drno/simulator')),
		'#required' => False,
		'#autocomplete_path' => 'drno/autocomplete',
	);
	
	
	$form['datetime'] = array(
		'#type' => 'date_popup',
		'#title' => t('Entry Date'),
		'#size' => 12,
		'#date_format' => 'm-d-Y',						// displayed format
			//default value has to be in this format
		'#default_value' => (($engineering_id > 0) ? $orig_date_entered : date('Y-m-d')), 
		'#required' => True,   // if no date entered, returns NULL
		'#attributes' => array('id' => 'qms-engineering-date'),
		'#suffix' => '</td>',
	);
	
	$form['simulator'] = array(
		'#type' => 'item',
		'#title' => t('Simulator'),
		'#markup' => '<div id="qms-simulator">' . 
									( ($engineering_id > 0) ? $simulator_list->getName($engineering->simulator_id) : '&nbsp;') . 
									'</div>',
		'#prefix' => '<td>',
	);
	
	global $user;
	
	$form['tech'] = array(
		'#type' => 'item',
		'#title' => t('Technician/Instructor'),
		'#markup' => (($engineering_id > 0) ? _get_user_name($engineering->tech_user_id) : _get_user_name($user->uid)),
	);

	
	$form['load_updated'] = array(
		'#type' => 'select',
		'#title' => t('Load Updated'),
		'#options' => $load_updated_list->get(),
		'#default_value' => (($engineering_id > 0) ? $engineering->load_updated_id : 0),
		'#required' => True,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'qms-load-updated-select'),
		'#suffix' => '</td></tr></table>',
	);
  
  $form['eng_table_end'] = array(
    '#markup' => '</td></tr></table>',
  );
	
	
	//------------- ADD MODULE_UPDATED TEXTAREA  -----------	
	
	$text_settings = array(
		'name' => 'module_updated',
		'title' => t('Module Updated'),
		'text' =>	(($engineering_id > 0) ? $engineering->module_updated : ''),
		'required' => True,
		'disabled' => False,
	);
	 
	_st_add_text_editor($form, $text_settings);
	
	
	//--------------------------- 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 ( $engineering_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;'),
	);
	
	
  //--------------------------- Hidden ---------------------------
  
	// storage area for dynamic dialog element
	$form['popup_dialog'] = array(
		'#type' => 'markup',
		'#markup' => '<div id="qms-message-box"></div>',
	);
	
  /*
	if ( $engineering_id > 0 ) {	
		// storage field for the change (dirty) flag
		$form['form_dirty'] = array(
			'#type' => 'textfield',
			'#default_value' => 0,
			'#attributes' => array('id' => 'qms-engineering-changed',
															'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.
*/

/* 
 * engineering_form_after_build()
 *
 */
function engineering_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');
	
	
	// 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');
	
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.engineering.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;
}



/*
 *	engineering_form_validate()
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates the engineering entry form
 */

function engineering_form_validate(&$form, &$form_state) {
  
  $button_clicked = $form_state['triggering_element']['#name'];
  
  if ( $form['actions']['submit']['#name'] != $button_clicked ){
    return $form;
  }
	
	// WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
	$ckeditor_activated  = isset($form['ckeditor_module_path']);
	
	$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 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 Engineering Log entry.  The DR Number ' . $dr_no . ' was not found.'));
	}
	if ( $result->rowCount() > 1 ) {
		return form_set_error('dr_no', t('Unable to add Engineering Log entry.  ' . $dr_no . ' matched multiple reports.'));
	}
		
	
	$eng_datetime = trim($form_state['values']['datetime']);
	if ( !isset($eng_datetime) || ($eng_datetime == '') ) {
		form_set_error('datetime', t('Unable to add Engineering Log entry.  Date is a required field'));
	}
	if ( (int) $form_state['values']['load_updated'] == 0 ) {
		form_set_error('load_updated', t('Unable to add Engineering Log entry.  Load Updated selection is a required field'));
	}
	
	// module_updated_editor_value is ALWAYS the field that the comment text field gets pushed to on submit
	// this is a kluge to deal with a CKEditor bug
	if ( trim($form_state['values']['module_updated_editor_value']) == '' ) {
		form_set_error('module_updated', t('Unable to add Engineering Log entry.  Module Updated is a required field'));
	}	
	
}

/*
 *	engineering_form_submit()
 *
 *  overloads:  hook_form_submit()
 *
 *	Handles the Engineering form submitted data, stores to db
 */
function engineering_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) ){
    
    $engineering_id = isset($form_state['values']['engineering_id']) ? 
                        (int) $form_state['values']['engineering_id'] : 0;
    if ( !$engineering_id && isset($form['engineering_id']['#default_value'])) {
      $engineering_id = $form['engineering_id']['#default_value'];
    }
    if ( $engineering_id ) {
      $_GET['destination'] = 'engineering/delete/' . $engineering_id . 
                            '?destination=engineering/edit/' . $engineering_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/engineering';
    }	
    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 --------------------
	
	$engineering = (object) NULL;
	
	// WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
	$ckeditor_activated  = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON
	
	$engineering->engineering_id = (int) $form_state['values']['engineering_id'];
	
	$eng_datetime = substr($form_state['values']['datetime'], 0, 10);
	
	if ( $engineering->engineering_id > 0 ) {  // editing engineering report
		// compare only the date portion of the datetime field to see if it changed
		$orig_date = $form_state['values']['original_datetime'];
		
		if ( $eng_datetime <> substr($orig_date, 0, 10) )  {
			// date changed from original, add a new time portion and 
			// include it in the $engineering record to save
			// add time to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
			$eng_datetime .= ' ' . date('H:i:s');
		}	
		else {
			$eng_datetime = substr($orig_date, 0, 10) . ' ' . date('H:i:s');
		}	
		
		// for editing a report, do not set the tech_user_id as it is not allowed to be edited
	}
	else {  // new shift log

		$eng_base_no = $form_state['values']['eng_no'];
		$engineering->eng_no = _st_generate_report_no('ENG', $eng_base_no);
		
		
		// add time to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
		$eng_datetime .= ' ' . date('H:i:s');
		
		// set the tech user id to the currently logged in user
		global $user;
		$engineering->tech_user_id = $user->uid;
	}
	
	
	$engineering->datetime = _st_format_timestamp($eng_datetime);   // convert to unix time
	$engineering->load_updated_id = (int) $form_state['values']['load_updated'];
	
	// because of a CKEditor bug and the possibility that the editor may or may not be enabled,
	// the value of the module updated editor field is ALWAYS pushed to this field value:
	// $form['module_updated_editor_value']
	$engineering->module_updated = _st_clean_ckeditor_text($form_state['values']['module_updated_editor_value'], 
																											QMS_TEXTAREA_MAX);
	
	
	$currtimestamp = REQUEST_TIME;
	$engineering->updated_date = $currtimestamp;
	
	
	//----------------- search for $dr_no -----------------------

	
	$dr_no = trim($form_state['values']['dr_no']);
	
	$sql = "SELECT discrepancy_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 Engineering Log entry.  Invalid DR No. ' . $dr_no . '.'), 'Error');
		return;
	}
	$engineering->discrepancy_id = $result->fetchField();
	
	// save record
	// Table:  {qms_engineering}
	if ( $engineering->engineering_id > 0 ) {
		if ( drupal_write_record('qms_engineering', $engineering, 'engineering_id')) {
			 	// update
			$msg = 'Engineering Log 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_ENGINEERING_SEARCH_KEY); 

			$key_cache = cache_get($key_cache_name);
			if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
				$search = $key_cache->data;
				_get_engineering_search_list($search, 0, 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_engineering', $engineering)) {
			// new record
			// new id was assigned -- saved successfully
			$msg = 'Engineering Log entry has been successfully added.';
		}
		else {
			$msg = 'Oops!  Something went wrong, Engineering Log entry was not saved.';
		}
		drupal_set_message(t($msg));	
	}
	
	$num_rows = db_update('qms_discrepancy_log')
				->fields(array(
									'engineering' => 1,
									'updated_date' => $currtimestamp,
								))
				->condition('discrepancy_id',  $engineering->discrepancy_id, '=')
				->condition('engineering', 0, '=')
				->execute();
	
	
	//drupal_goto('engineering/edit/' . $engineering->engineering_id);  
	drupal_goto('search/engineering');  
}




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


/*
 *	view_engineering_form()
 *
 *  Overloads hook_form()
 *  Engineering VIEW ONLY form
 */

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

	// WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
	$ckeditor_activated  = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON



	// get the engineering log record
	$sql = "SELECT e.engineering_id, e.eng_no, e.discrepancy_id, e.datetime, e.module_updated, 
								 e.load_updated_id, e.tech_user_id, e.updated_date, 
								 d.dr_no, d.simulator_id 
					FROM   {qms_engineering} e, {qms_discrepancy_log} d
					WHERE  e.engineering_id = :engid
					AND		 e.discrepancy_id = d.discrepancy_id";
	$result = db_query($sql, array(':engid' => $engineering_id));
	
	if ( $result->rowCount() == 0 ) {
		drupal_set_message( t('Engineering Record Not Found!'), 'warning');
		drupal_goto('search/engineering');
		return;
	}
	$engineering = $result->fetchObject();		
	

	global $simulator_list;
	global $tech_list;
	$load_updated_list = new LoadUpdatedList();

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

	$form['datetime'] = array(
		'#type' => 'item',
		'#title' => t('Date'),
		'#markup' => _st_format_date($engineering->datetime, 'short'),
		'#suffix' => '</td>',
	);
	
	$form['simulator'] = array(
		'#type' => 'item',
		'#title' => t('Simulator'),
		'#markup' => $simulator_list->getName($engineering->simulator_id),
		
		'#prefix' => '<td style="width:33%">',
	);
	
	
	global $user;
	// we don't need to save the tech user id on the form
	// new shift log, store the current user_id (logged-in)
	// editing shift log, user cannot be changed
	$form['tech_name'] = array(
		'#type' => 'item',
		'#title' => t('Technician/Instructor'),
		'#markup' => (($engineering_id > 0) ? _get_user_name($engineering->tech_user_id) : _get_user_name($user->uid)),
		'#suffix' => '</td>',
	);
	
	
	$form['load_updated'] = array(
		'#type' => 'item',
		'#title' => t('Load Updated'),
		'#prefix' => '<td>',
		'#markup' => $load_updated_list->getName($engineering->load_updated_id),
		'#suffix' => '</td></tr>',
	);
	

	$form['module_updated'] = array(
		'#type' => 'item',
		'#title' => t('Module Updated'),
		'#prefix' => '<tr><td colspan="3">',
		
		'#markup' => ($ckeditor_activated ? _st_convert_symbols($engineering->module_updated) : nl2br(_st_convert_symbols($engineering->module_updated))),
		'#suffix' => '</td></tr></table>',
	);
	

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

	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$eng_search_results = $results_cache->data;
		$eng_results_table_rows = $eng_search_results->getResults();
		
		// get key of previous item in currently loaded page of engineering search results
		$prev_id = _st_array_key_relative($eng_results_table_rows, $engineering_id, -1);
		if ( $prev_id !== False ) {
//			$prev_report_link = l(t('View Previous'), 'engineering/view/' . $prev_id,
//			 											array('query' => array('destination' => 'search/engineering')));
      $form['view_previous_link'] = array(
        '#type' => 'textfield',
        '#default_value' => 'engineering/view/' . $prev_id,
        '#attributes' => array('class' => array('qms-hidden') ),
      );
		}
		// get key of next item in currently loaded page of engineering search results
		$next_id = _st_array_key_relative($eng_results_table_rows, $engineering_id, 1);
		if ( $next_id !== False ) {
//			$next_report_link = l(t('View Next'), 'engineering/view/' . $next_id,
//														array('query' => array('destination' => 'search/engineering')));
      $form['view_next_link'] = array(
        '#type' => 'textfield',
        '#default_value' => 'engineering/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/engineering';
	}


	$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 ( user_access('administer sabreQMS') == True ) {
		
    $form['actions']['edit'] = array(
      '#type' => 'submit',
      '#value' => t('Edit'),
      '#name' => 'edit',
      '#attributes' => array('class' => array('qms-btn-edit', 'qms-btn-extra'),
                              'query' => array('destination' => 
                                                'engineering/view/' . $engineering_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' => 
                                                'engineering/view/' . $engineering_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' => 
                                                'engineering/view/' . $engineering_id)),
		);
	}
	
	return $form;
}

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


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

      // we have to force $_GET['destination'] otherwise drupal_goto
      // ignores the supplied path and reverts to the destination setting
      $_GET['destination'] = 'engineering/edit/' . $engineering_id . 
                '?destination=engineering/view/' . $engineering_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/engineering';
    }
  }
  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/engineering';
    }  
  }
}



/*
 *	engineering_delete_confirm()
 *
 *  Delete the engineering log entry -- ADMIN ONLY
 */

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

/*
 *	engineering_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the engineering entry -- ADMIN ONLY
 */


function engineering_delete_confirm_submit($form, $form_state) {
	
	if ($form_state['values']['confirm']) {
		$engineering_id = (int) $form_state['values']['engineering_id'];
		$discrepancy_id = (int) $form_state['values']['discrepancy_id'];
		$dr_no = $form_state['values']['dr_no'];
		$eng_no = $form_state['values']['eng_no'];
		
		$num_rows = db_delete('qms_engineering')
					->condition('engineering_id', $engineering_id, '=')
					->execute();
		
		if ( $num_rows <> 1 ) {
			$msg = t('Error occurred deleting engineering log entry.');
		}
		else {
			$msg = t('The engineering log entry ' . $eng_no . ' for ' . $dr_no . ' has been deleted.');
		}
		
		drupal_set_message($msg);
		
		$result = db_query("SELECT discrepancy_id FROM {qms_engineering} e WHERE discrepancy_id = :did LIMIT 1",
												array(':did' => $discrepancy_id));

		if ( $result->rowCount() == 0 ) {
			// no engineering reports remaining linked to this DR, unset the flag
			$num_rows = db_update('qms_discrepancy_log')
						->fields(array(
											'engineering' => 0,
											'updated_date' => time(),
										))
						->condition('discrepancy_id',  $discrepancy_id, '=')
						->execute();
		}
		
		// Reload the cache 
		// determine cache name
		$search = (object) Null;
		$key_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SEARCH_KEY); 
		
		$key_cache = cache_get($key_cache_name);
		if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
			$search = $key_cache->data;
			_get_engineering_search_list($search, 0, True);
		}
	}
	drupal_goto('search/engineering');
}








