<?php

/*
 *	Job record functions for sabreQMS module
 */


/*
 *	search_jobs() 
 *
 */

function search_jobs() {
	
	
	if ( user_access('administer sabreQMS') == False ) {
		drupal_set_message(t('Unauthorized:  Permission is required'));
    return;
  }
  // this doesn't seem to load consistently unless specified here
  drupal_add_js('misc/tableheader.js');  

	//drupal_add_library('system','ui.dialog');
	//drupal_add_library('system','ui.datepicker');
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.jobs.js');
  
	//$form_cache_name = QMS_JOB_SEARCH_FORM;

	$search_form = '';
	$search_results = '';
  
  $form_cache_name = QMS_JOB_SEARCH_FORM;
  
  $form_cache = cache_get($form_cache_name);
	if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
		$search_form = $form_cache->data;
	}
	else {
	
		// search results not in cache, create empty div for ajax to populate after search
		// search results will get populated to cache after ajax call
    $form_elems = drupal_get_form('jobs_search_form');
		$search_form = render($form_elems);

		//maintains cache entry for the form for 20 min before refresh (time in seconds)
		cache_set($form_cache_name, $search_form, 'cache', time() + QMS_CACHE_TIMEOUT);			
	}	

	// determine cache name
	$results_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_RESULTS);	

	$results_cache = cache_get($results_cache_name);
	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$search_results = $results_cache->data;
	}
	else {
		// search results not in cache, create empty div for ajax to populate after search
		// search results will get populated to cache after ajax call
		$search_results = '<div id="qms-search-results-div"></div>';
		
		cache_set($results_cache_name, $search_results, 'cache', time() + QMS_CACHE_TIMEOUT);			
	}
	
	$content = $search_form . $search_results;
	
	return $content;
}

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

function jobs_search_form($form, $form_state) {
	
		//------------ BUILD SEARCH FORM ------------------
		global $base_url;
		global $simulator_list;
		$job_list = new JobList;
		

		$form['search'] = array(
			'#type' => 'fieldset',
			'#title' => t('Search'),
			'#collapsible' => True,
			'#collapsed' => False,
			'#attributes' => array('id' => array('qms-search-div')),
		);
    
    $form['search']['job_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Job Name'),
      '#default_value' => '',
      '#attributes' => array('id' => 'qms-search-job-name'),
      '#suffix' => '</td>',
    );
    
    $form['search']['simulator'] = array(
      '#type' => 'select',
      '#title' => t('Simulator'),
      '#options' => $simulator_list->getAll(SimulatorList::INCL_ALL),
      '#default_value' => 0,
      '#attributes' => array('class' => array('qms-select'),
                              'id' => 'qms-search-simulator'),
      '#suffix' => '</td>',
    );

    $form['search']['show_closed'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show Closed Jobs'),
      '#default_value' => 0,
      '#attributes' => array('id' => 'qms-show-closed-chk'),
    );

		


		//--------------------------------------------
		// Adds a simple submit button that refreshes the form and clears its contents 
		// -- this is the default behavior for forms.
		$form['search']['actions'] = array('#type' => 'actions');
		$form['search']['actions']['submit'] = array(
			'#type' => 'button',
			'#value' => 'Search',
			'#attributes' => array('id' => 'qms-search-btn-submit',
                             'style' => 'font-weight:bolder;',
															'qms-url' => url('qmssettings/jobs/search') ),
	/*	DO NOT do Drupal AJAX here, being done through JQuery by the javascript file
	**	as we need the .live("click") function due to form caching, which won't work here with Drupal
	*/
		);
		
    $form['search']['actions']['clear'] = array(
      '#type' => 'button',
      '#value' => t('Clear'),
      '#attributes' => array('id' => 'qms-search-btn-clear',
                             'class' => array('qms-btn-extra'),
                             'qms-url' => url('qmssettings/jobs/clear') ),
      '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' . 
                    $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
    );
    
    // Place Add Link above the jobs table
    $form['add_job'] = array(
			'#markup' => l( t('Add Job'), 'job/add', array('class' => array('qms-btn-add'))),
		);
		
		// storage area for dynamic dialog element
		$form['popup_dialog'] = array(
			'#markup' => '<div id="qms-message-box"></div>',
		);
    
		return $form;
}


/**
 * job_search_form_callback()
 * displays the search results, first page only
 * Has to be a separate handler from pager & sort link callback
 * This is the callback that gets called when the Search button is clicked
 *
 */
function jobs_search_form_callback() {
	
	$search = new stdClass();
	
	$search->show_closed = (int)$_POST['show_closed'];
  $search->job_name = trim($_POST['job_name']);
  $search->simulator_id = (int)$_POST['simulator_id'];
	
	// cache the latest search key
	// determine cache name, always use it specific to this user + session
	// set key cache to expire in 30 minutes
	$key_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_KEY);
	
	cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		

	die(_job_search_list($search));
}

/**
 * job_pager_callback()
 * displays the search results, first page only
 * Has to be a separate handler from pager & sort link callback
 * This is the callback that gets called when the Search button is clicked
 *
 */
function jobs_pager_callback() {
	
	$search = new stdClass();
	
	// determine the key cache
	$key_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_KEY);
	
	$key_cache = cache_get($key_cache_name);
	if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
		$search = $key_cache->data;
	}
	else {
		// search key not in cache, get it from POST
		// though, this should never happen... should always be in cache
		$search->show_closed = (int)$_POST['show_closed'];
    $search->job_name = trim($_POST['job_name']);
    $search->simulator_id = (int)$_POST['simulator_id'];
		
		// cache the latest search key
		cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
	}
	
	die(_job_search_list($search));
}


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

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



/*
 *	job_display()
 *
 *	returns:  Displays table list of jobs
 *
 */

function _job_search_list($search, $called_by_pager = True) {
	
	if (user_access('view admin lists') == False) {
		return '';
	}
	
	
	// Check permissions -- only allow editing capabilities if 'administer officers' enabled
	$bAdmin = user_access('administer sabreQMS');
	
	
	$table_header = array( 
		array( 'data' => 'Job', 'field' => 'job_name', 'sort' => 'asc', 'class' => array('qms-job-tbl-jobname')  ),
		array( 'data' => 'Simulator', 'field' => 'sim_name', 'sort' => 'asc', 'class' => array('qms-job-tbl-simulator') ),
		array( 'data' => 'Opened', 'field' => 'date_opened', 'sort' => 'desc', 'class' => array('qms-job-tbl-opened')  ),
		array( 'data' => 'Closed', 'field' => 'date_closed', 'sort' => 'desc', 'class' => array('qms-job-tbl-closed') ),
		array( 'data' => 'Clocked-In?', 'field' => 'date_opened', 'sort' => 'asc', 'class' => array('qms-job-tbl-clockedin') ),
	);
	
	if ( $bAdmin == True ) {
		$table_header[] = array( 'data' => 'Admin', 'class' => array('qms-results-admin') );
	}
	
	
	$search_init = array(
		'table_name' => 'qms_jobs',
		'table_alias' => 'j',
		'table_header' => $table_header,
		'pager_path' => 'qmssettings/jobs/pager',
		'order' => 'Job',
		'sort' => 'asc',
		'variable' => False,
	);
	
	$query = _st_setup_paged_search($search_init);	
	
	
	// Get List of Jobs
	$query->leftJoin('qms_simulators', 's', 's.simulator_id = j.simulator_id');
	$query->addExpression("IF( j.job_id IN (SELECT job_id FROM qms_punch_clock WHERE clock_out = 0), 1, 0 )", 
													"clocked_in" );	
	$query->fields('j', array('job_id', 'job_name', 'date_opened', 'date_closed') )
				->fields('s', array('sim_name', 'device_id_internal'));
  
  if (empty($search->show_closed)) {
    $query->condition('date_closed', 0);
  } 
  
  if (!empty($search->simulator_id)) {
    $query->condition('j.simulator_id', $search->simulator_id);
  }
  
  if (!empty($search->job_name)) {
    _st_add_keyword_search_condition($query, 'j.job_name', $search->job_name);
  }
				
	$max_count = 0;
	$result = _st_execute_paged_search($query, $max_count);
	
	
	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
		
		$row_data = array(
			$row->job_name,
			_st_format_sim_name($row->sim_name, $row->device_id_internal),
			_st_format_date($row->date_opened, 'custom', 'Y-m-d'),
			_st_format_date($row->date_closed, 'custom', array('custom_format' => 'Y-m-d',
                                                         'fail_empty' => True)),
			($row->clocked_in ? 'x' : ''),
			//($row->active ? 'x' : ''),
		);
		
		if ( $bAdmin == True ) {
			$row_data[] = _st_generate_options('job', $row->job_id);
		}
		
		$table_rows[] = array( 'data' => $row_data	);
		$i++;
	}
	
	$content = '';
//	if ( False == $called_by_pager ) {
//		// Place Add Link above the jobs table
//		$content .= ( ($bAdmin) ? l( t('Add Job'), 'job/add', array('class' => array('qms-btn-add'))) : '' );
//	}
	
	$content .= '<div id="qms-search-results-div">';
  $content .= theme('pager', array('tags' => array(), 'quantity' => QMS_RECORDS_PER_PAGE));
	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
	));
	
	//Append pager:  http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager
	$content .= theme('pager', array('tags' => array(), 'quantity' => QMS_RECORDS_PER_PAGE));
	$content .= '</div>';
	
	if ( True == $called_by_pager ) {
		die($content);
	}
	global $base_url;
	$content .= '<div id="qms-waiting" class="qms-waiting""><img class="qms-waiting-img" src="' . 
							$base_url . QMS_IMAGES_DIR . 'waiting.gif" /></div>';  // popup "waiting" anim. gif displayed during ajax requests
	$content .= '<div id="qms-message-box" class="qms-hidden"></div>';// storage area for dynamic dialog element
	
	return $content;
}

/*
 *	job_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays the job form for adding/updating
 */

function job_form($form, $form_state, $job_id=0) {

	if ( user_access('administer sabreQMS') == FALSE ) {
		drupal_set_message( t('Unauthorized.  Administrator access required'));
		drupal_goto('qmssettings/jobs');
    return;
  }

	// all page-specific javascript loaded in the after_build function
	$form['#after_build'][] = 'job_form_after_build';


	$form['job_box'] = array(
		'#type' => 'container',
	);
  
	$form['job_box']['job_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Job Name'),
		'#maxlength' => 100,
		'#default_value' => '',
	);		
	
	global $simulator_list;
	
	$form['job_box']['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Simulator'),
		'#options' => $simulator_list->get_active(),
		'#default_value' => 0,
		'#required' => False,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'qms-simulator-select'),
	);
		
	$form['job_box']['date_opened'] = array(
		'#type' => 'date_popup',
		'#title' => t('Date Opened'),
		'#size' => 14,
		'#date_format' => 'm-d-Y',						// displayed format
		'#default_value' => date('Y-m-d'), // default has to be in this format
		'#required' => True,   // if no date entered, returns NULL
		'#attributes' => array('class' => array('qms-date-picker'),
													 'id'		=> 'qms-date-opened'),
		'#prefix' => '<table class="qms-plain-table"><tr><td style="width:22%;text-align:left;">',
		'#suffix' => '</td>',
	);
	
	$form['job_box']['date_closed'] = array(
		'#type' => 'date_popup',
		'#title' => t('Date Closed'),
		'#size' => 14,
		'#date_format' => 'm-d-Y',
		'#default_value' => '',
		'#required' => False,   // if no date entered, returns NULL
		'#attributes' => array('class' => array('qms-date-picker'), 
													 'id'	=> 'qms-date-closed'),
		'#prefix' => '<td style="text-align:left;">',
		'#suffix' => '</td></tr></table>',
	);			
	
	$form['job_id'] = array(
		'#type' => 'value',
		'#value' => 'NEW',
	);				
	
	
	if ( $job_id > 0 ) {   // Edit existing record
		
		$job = new stdClass();
		
		// get the record
		$sql = "SELECT job_name, simulator_id, date_opened, date_closed, active,  
										IF( job_id IN (SELECT job_id FROM qms_punch_clock WHERE clock_out = 0), 1, 0 ) AS `clocked_in` 
						FROM {qms_jobs}  WHERE job_id = :jid";
		$result = db_query($sql, array(':jid' => $job_id));

		if ( !$result->rowCount() ) {
			drupal_set_message( t('Job Not Found!'), 'warning');
			drupal_goto('qmssettings/jobs');
			return;
		}
		
		$job = $result->fetchObject();
		
		$orig_date_opened = _st_format_date($job->date_opened, 'short');
    $orig_date_closed = _st_format_date($job->date_closed, 'short', array('fail_empty' => True));

		// storage field for the original date opened (edit) -- hidden
		$form['original_date_opened'] = array(
			'#type' => 'textfield',
			'#default_value' => $orig_date_opened,
			'#attributes' => array('id' => 'qms-original-date-opened',
														 'class' => array('qms-hidden-field')),
		);
		// storage field for the original date opened (edit) -- hidden
		$form['original_date_closed'] = array(
			'#type' => 'textfield',
			'#default_value' => $orig_date_closed,
			'#attributes' => array('id' => 'qms-original-date-closed',
														 'class' => array('qms-hidden-field')),
		);
		
		$orig_date_opened = substr($orig_date_opened, 0, 10); // chop off the time portion for display purposes
		$orig_date_closed = substr($orig_date_closed, 0, 10); // chop off the time portion for display purposes
		
		if ( $job->date_closed == 0 ) {
			$form['job_box']['clocked_in'] = array(
				'#type' => 'item',
				'#title' => t('Clocked-In'),
			);
			
			$form['job_box']['clocked_in']['#markup'] = ( $job->clocked_in ? 'Yes' : 'No');
		}
		
		// set existing job values into form
		$form['job_id']['#value'] = $job_id;		
		$form['job_box']['job_name']['#default_value'] = $job->job_name;
		$form['job_box']['simulator']['#default_value'] = $job->simulator_id;
		$form['job_box']['date_opened']['#default_value'] = $orig_date_opened;
		$form['job_box']['date_closed']['#default_value'] = ($job->date_closed ? $orig_date_closed : '');
	}
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#attributes' => array('class' => array('qms-btn-submit')),
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                            url('qmssettings/jobs') . 
                                         '"; return false;'),
	);
	

	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.
*/

/* 
 * job_form_after_build()
 *
 */
function job_form_after_build($form, &$form_state)
{
	drupal_add_library('system','ui.datepicker');
	//drupal_add_library('system','ui.dialog');	
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.jobsinput.js');
	
	return $form;
}


/*
 *	job_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates job_form after it is submitted
 */

function job_form_validate($form, $form_state) {
	if ( trim($form_state['values']['job_name']) == '' ) {
		form_set_error('job_name', t('Job Name is a required field'));
	}
	
	//----------------- date checking ---------------------
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	$date_opened = trim($form_state['values']['date_opened']);
	$idate_opened = _st_format_timestamp($date_opened);  

	$date_closed = trim($form_state['values']['date_closed']);
	$idate_closed = 0;
	if ( $date_closed <> '' ) {
		$idate_closed = _st_format_timestamp($date_closed);  
	}
	if ( $idate_opened == 0 ) {
		form_set_error('date_opened', t($err_msg . 'Date Opened is a required field'));
	}
	if ( ( $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.'));
	}
	
}

/*
 *	job_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves job_form data upon successful submit
 */

function job_form_submit($form, $form_state) {
	$job = new stdClass();
	$currtimestamp = REQUEST_TIME;
	$append_time = ' ' . date('H:i:s', REQUEST_TIME);
	
	
	$job_id = $form_state['values']['job_id'];
	if ($job_id == 'NEW') {
		$job->job_name = $form_state['values']['job_name'];
		$job->simulator_id = (int)$form_state['values']['simulator'];
		$date_opened = substr($form_state['values']['date_opened'], 0, 10);
		$date_closed = trim($form_state['values']['date_closed']);
		
		// add time to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
		$date_opened .= $append_time;
		$job->date_opened = _st_format_timestamp($date_opened);
		
		if ( strlen($date_closed) > 0 ) {
//      echo "strlen(\$date_closed) > 0<br />\n";
			$date_closed = substr($date_closed, 0, 10);
			$date_closed = $append_time;
			$job->date_closed = _st_format_timestamp($date_closed);
			if ( $job->date_closed <= time() ) {
				// job already set as closed, set to not active
				$job->active = 0;
			}
		}
	
	}
	else {
		// compare only the date portion of the datetime field to see if it changed
		$date_opened = trim($form_state['values']['date_opened']);
		$date_closed = trim($form_state['values']['date_closed']);
		$orig_date_opened = $form_state['values']['original_date_opened'];
		$orig_date_closed = $form_state['values']['original_date_closed'];
    //$date_closed .= $append_time;
		$idate_closed = _st_format_timestamp($date_closed, array('fail_empty' => True));
    
    
//    print "date_opened: $date_opened<br>\n";
//    print "date_closed: $date_closed<br>\n";
//    print "idate_closed: $idate_closed<br>\n";
//    print "orig_date_opened: $orig_date_opened<br>\n";
//    print "orig_date_closed: $orig_date_closed<br>\n";
    
		
		if ( substr($date_opened, 0, 10) <> substr($orig_date_opened, 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'
			$date_opened .=  $append_time;
			$job->date_opened = _st_format_timestamp($date_opened);
		}		

     
		if ( substr($date_closed, 0, 10) <> substr($orig_date_closed, 0, 10) )  {
//      echo "substr(\$date_closed, 0, 10) <> substr(\$orig_date_closed, 0, 10)<br />\n";
			// 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'
			if ( $idate_closed > 0 ) {
//        echo "\$idate_closed > 0<br />\n";
				$date_closed .=  $append_time;
				$job->date_closed = _st_format_timestamp($date_closed);
			}
			else {
				$job->date_closed = 0;
			}
		}	
		
		$job->job_id = (int) $form_state['values']['job_id'];
		$job->job_name = trim($form_state['values']['job_name']);
		$job->simulator_id = (int) $form_state['values']['simulator'];
		$job->active = ( ($idate_closed > 0 ) ? 0 : 1 );	
	}
  
//  echo "job_id: $job_id<br>\n";
//  var_dump($job);
//  die;
	

	if  ( $job_id == 'NEW' )  {  
		// new record
		// Table:  {qms_jobs}
		if ( False == drupal_write_record('qms_jobs', $job)) {
			$msg = "Oops!  Something went wrong storing the job record.";
			drupal_set_message(t($msg));
		}
	}
	else {
		// update existing
		// Table:  {qms_jobs}
		if ( False == drupal_write_record('qms_jobs', $job, 'job_id')) {
			$msg = "Oops!  Something went wrong updating the job record.";
			drupal_set_message(t($msg));
		}
	}
  
  // Reload the cache 

	// determine cache name
	$search = Null;
	$key_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_KEY); 
	
	$key_cache = cache_get($key_cache_name);
  
	if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
    // previous search found
		$search = $key_cache->data;
    
	} else {
    // search is empty
    $search = new stdClass();
    $search->job_name = $job->job_name;
    $search->simulator_id = $job->simulator_id;
    $search->active = 1;
	
    // cache the latest search key
    // determine cache name, always use it specific to this user + session
    // set key cache to expire in 30 minutes
    $key_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_KEY);
    cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
    
  }
  //refresh the cached search results in the event of any changes may be displayed
  $search_results = _job_search_list($search, FALSE);
  $results_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_RESULTS); 
  cache_set($results_cache_name, $search_results, 'cache', time() + QMS_CACHE_TIMEOUT);	
	
	_clear_qms_cache(QMS_PUNCHCLOCKEVENT_SEARCH_FORM); 
	//global $job_list;
	//$job_list->reload();
	
  drupal_set_message("Job {$job->job_name} has been saved.");
	drupal_goto('qmssettings/jobs');
}

/*
 *	job_delete_confirm()  
 *
 *	Validate and Ask for confirmation before deleting record
 */

function job_delete_confirm($form, $form_state, $job_id) {
	
	if ( $job_id == 0 ) {
		return;
	}
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized Access.  Administrator access required.'));
		drupal_goto('qmssettings/jobs');
		return;	
  }
	
	// Get Job record by id
	$sql = "SELECT job_name FROM {qms_jobs} WHERE job_id = :jid";
	$result = db_query($sql, array(':jid' => $job_id));
	
	if ( !$result->rowCount() ) {
		drupal_set_message( t('Job Not Found!'), 'warning');
		drupal_goto('qmssettings/jobs');
		return;
	}
	
	$job_name = $result->fetchField();
	
	if ( $job_name == '' ) {
    drupal_set_message( t('Oops!  Something seems to have gone wrong.  Job not found.'));
		drupal_goto('qmssettings/jobs');
		return;
  }
	
	// check if the job is linked to a Time Clock record
	$sql = "SELECT job_id FROM {qms_punch_clock} WHERE job_id = :jid LIMIT 1";
	$result = db_query($sql, array(':jid' => $job_id));
	if ( $result->rowCount() ) {
		// cannot delete, job linked to time clock records
		$msg = "Unable to delete " . $job_name .  ".  Job is linked to time clock records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/jobs');
		return;	
	}
	
	
	$form['job_id'] = array(
		'#type' => 'value',
		'#value' => $job_id,
	);
	
	$form['job_name'] = array(
		'#type' => 'value',
		'#value' => $job_name,
	);
	
	$title = t('Delete Job') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $job_name . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'qmssettings/jobs';
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  // force this here to avoid a problem with routing if cancelled
  //$_GET['destination'] = $goto_if_canceled;
  
  return confirm_form($form, $title,	$goto_if_canceled, $question, 
                      $yes_btn, $no_btn);
}

/*
 *	job_delete_confirm_submit()  
 *
 *	Submit after confirmation, delete the specified record
 */

function job_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$job_id = $form_state['values']['job_id'];
		$job_name = $form_state['values']['job_name'];
	
		// delete from database
		$num_rows = db_delete('qms_jobs')
								->condition('job_id', $job_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			$msg = 'Job record for ' . $job_name . ' has been deleted.';
		}
		else {
			$msg = 'Oops!  Unable to delete record for ' . $job_name . '.';
		}
		drupal_set_message(t($msg));
	}
  
  // Reload the cache 

	// determine cache name
	$search = Null;
	$key_cache_name = _get_qms_cache_name(QMS_JOB_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 in the event of any changes may be displayed
    $search_results = _job_search_list($search, FALSE);
    $results_cache_name = _get_qms_cache_name(QMS_JOB_SEARCH_RESULTS); 
		cache_set($results_cache_name, $search_results, 'cache', time() + QMS_CACHE_TIMEOUT);	
	}
	
	_clear_qms_cache(QMS_PUNCHCLOCKEVENT_SEARCH_FORM); 
	
	
	drupal_goto('qmssettings/jobs');
}







