<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Engineering Log search function handling
 *    
*/

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

/*
 *	search_engineering_logs()
 *
 */

function search_engineering_logs() {
	
	drupal_add_library('system','ui.dialog');
	drupal_add_library('system','ui.datepicker');
	//drupal_add_library('system', 'tableselect');
	drupal_add_js('misc/tableselect.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', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.searchengineering.js');

	if ( user_access('search view reports') == False ) {
		drupal_set_message(t('Unauthorized:  Permission is required'));
    return;
  }

	$engineering_search_form = '';
	$engineering_search_results = '';
	$eng_search_results = new SearchResultsTable('ENG');
	$form_cache_name = QMS_ENGINEERING_SEARCH_FORM;
	
	global $user;
	$user_is_customer_id = _user_is_customer($user->uid);

	if( $user_is_customer_id ) {
    $form_elems = drupal_get_form('engineering_search_form');
		$engineering_search_form = render($form_elems);
	}
	else {
	
		$form_cache = cache_get($form_cache_name);
		if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
			$engineering_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('engineering_search_form');
			$engineering_search_form = render($form_elems);
		
			// maintains cache entry for the form for 20 min before refresh (time in seconds)
			// not tied to any one user, can be shared in the database by multiple users
			cache_set($form_cache_name, $engineering_search_form, 'cache', time() + QMS_CACHE_TIMEOUT);			
		}
	}
	
	// determine cache name
	$results_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SEARCH_RESULTS);
	$selected_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SELECTED);
	
	$results_cache = cache_get($results_cache_name);
	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$eng_search_results = $results_cache->data;
		_check_if_selected($selected_cache_name, $eng_search_results);
		
		// need to force this or pager/sort picks up the wrong path
		$_GET['q'] = 'search/engineering/pager';
		
    $form_elems = drupal_get_form('results_list_form', $eng_search_results);
		$engineering_search_results = render($form_elems);
;
	}
	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
		$engineering_search_results = '<form id="results-list-form"></form>';
		
		// don't cache the empty div
		//cache_set($results_cache_name, $engineering_search_results, 'cache', time() + QMS_CACHE_TIMEOUT;			
	}
	
	$content = $engineering_search_form . $engineering_search_results;
	
	return $content;
}

/*
 *	engineering_search_form()
 *
 *  overloads:  hook_form()
 *  search form for engineering logs
 */
function engineering_search_form($form, $form_state) {
	
	// ---------------- Get the Form Selection Lists ---------------------
	// get the load updated list
  /*
	$load_updated_list = array();
	$sql = "SELECT eng_load_updated_id, eng_load_updated_desc 
					FROM {qms_eng_load_updated} ORDER BY eng_load_updated_desc";	
	$results = db_query($sql);

	$load_updated_list[0] = '- Select -';  // add default option

	foreach($results as $row) {
		$load_updated_list[$row->eng_load_updated_id] = $row->eng_load_updated_desc;
	}
   * 
   */

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

	//------------ BUILD SEARCH FORM ------------------
	
	$form['search'] = array(
		'#type' => 'fieldset',
		'#title' => t('Search'),
		'#collapsible' => True,
		'#collapsed' => False,
		'#attributes' => array('id' => array('qms-search-div')),
	);
	
	$form['search']['eng_no'] = array(
		'#type' => 'textfield',
		'#title' => t('Eng No.'),
		'#default_value' => 'ENG',
		'#size' => 15,
		'#attributes' => array('id' => 'qms-search-eng-no'),
		'#prefix' => '<table class="qms-plain-table" style="width:100%"><tr><td class="qms-search-eng-col1">',
	);
	
	$form['search']['dr_no'] = array(
		'#type' => 'textfield',
		'#title' => t('DR No.'),
		'#default_value' => 'DR',
		'#size' => 15,
		'#attributes' => array('id' => 'qms-search-dr-no'),
		'#suffix' => '</td>',
	);
	 
	$form['search']['tech'] = array(
		'#type' => 'select',
		'#title' => t('Technician/Instructor'),
		'#options' => $tech_list->getAll(TechnicianList::INCL_ALL),
		'#default_value' => 0,
		'#attributes' => array('class' => array('qms-select'),
													'id' => 'qms-search-tech'),
		'#prefix' => '<td class="qms-search-eng-col2">',
	);
	
	$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'),
	);
	
	$form['search']['load_updated'] = array(
		'#type' => 'select',
		'#title' => t('Load Updated'),
		'#options' => $load_updated_list->get(LoadUpdatedList::INCL_ALL),
		'#default_value' => 0,
		'#attributes' => array('class' => array('qms-select'),
														'id' => 'qms-search-load-updated'),
		'#suffix' => '</td>',
	);
	
	
	$form['search']['from_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('From Date'),
		'#size' => 10,
		'#date_format' => 'm-d-Y',					
		'#default_value' => '',   	
		'#date_year_range' => '-5:+0',
		'#attributes' => array('style' => array('float:left', 'width:50px'),
														'id' => 'qms-search-from-date',
														'class' => array('qms-date-picker')),
		'#prefix' => '<td class="qms-search-eng-col3"><br />',
		'#suffix' => '</td>',
	);
	
	$form['search']['to_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('To Date'),
		'#size' => 10,
		'#default_value' => '',
		'#date_format' => 'm-d-Y',
		'#attributes' => array('style' => array('float:left', 'clear:right', 'width:50px'),
														'id' => 'qms-search-to-date',
														'class' => array('qms-date-picker')),
		'#prefix' => '<td class="qms-search-eng-col4"><br />',
		'#suffix' => '</td></tr>',
	);
	
	// Module Updated Text
	$form['search']['module_text'] = array(
		'#type' => 'textfield',
		'#title' => t('Search Text'),
		'#size' => 82,
		'#default_value' => '',
		'#attributes' => array('id' => 'qms-search-module-text'),
		'#prefix' => '<tr><td colspan="4">',
		'#suffix' => '</td></tr></table>',
	);
	
	
	
	//--------------------------------------------
	// Adds a simple submit button that refreshes the form and clears its contents 
	// -- this is the default behavior for forms.
	$form['search']['actions'] = array('#type' => 'actions');
	$form['search']['actions']['submit'] = array(
		'#type' => 'button',
		'#value' => 'Search',
		'#attributes' => array('id' => 'qms-search-btn-submit',
                            'style' => 'font-weight:bolder;',
														'qms-url' => url('search/engineering/search') ),
/*	
		// NOT using Drupal AJAX on the submit button.  
		// Need to allow jQuery .live("click") for this button as the form gets cached for performance
		
			'#ajax' => array(
			'callback' => 'engineering_search_form_callback',
			'wrapper' => 'qms-search-results-div',
			'method' => 'replace',
			'prevent' => 'click',
			'keypress' => TRUE,
		),
*/
	);
  
  global $base_url;
  $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('search/engineering/clear') ),
    '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' . 
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
	);
	
	// storage area for dynamic dialog element
	$form['popup_dialog'] = array(
		'#markup' => '<div id="qms-message-box"></div>',
	);
	

	return $form;
}


/**
 * engineering_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 engineering_search_form_callback() {
	
	$search = (object) NULL;
	
	$search->eng_no = trim($_POST['eng_no']);
	$search->dr_no = trim($_POST['dr_no']);
	$search->tech_id = (int)$_POST['tech'];
	$search->simulator_id = (int)$_POST['simulator'];
	$search->load_updated_id = (int)$_POST['load_updated'];
	$search->from_date = trim($_POST['from_date']);
	$search->to_date = trim($_POST['to_date']);
	$search->module_text = trim($_POST['module_text']);
	
	
	// 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_ENGINEERING_SEARCH_KEY);
	$selected_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SELECTED);
	
	// cache the search parameters
	cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
	
	// this is a new search, clear the old search results list selections
	cache_clear_all($selected_cache_name, 'cache', TRUE); 
	
	$eng_search_results = new SearchResultsTable('ENG');

	_get_engineering_search_list($search, $eng_search_results);
  $form_elems = drupal_get_form('results_list_form', $eng_search_results);
	$content = render($form_elems);
	die($content);   // always die as this is an ajax callback (we only want a partial page render)
}

/**
 * engineering_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 engineering_pager_callback() {
	
	$search = (object) NULL;
	
	// determine the key cache
	$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;
	}
	else {
		// search key not in cache, get it from POST
		// though, this should never happen... should always be in cache
		$search->eng_no = trim($_POST['eng_no']);
		$search->dr_no = trim($_POST['dr_no']);
		$search->tech_id = (int)$_POST['tech'];
		$search->simulator_id = (int)$_POST['simulator'];
		$search->load_updated_id = (int)$_POST['load_updated'];
		$search->from_date = trim($_POST['from_date']);
		$search->to_date = trim($_POST['to_date']);
		$search->module_text = trim($_POST['module_text']);
		
		// cache the latest search key
		cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
	}
	
	// get the previous SearchResultsTable object
	$eng_search_results = new SearchResultsTable('ENG');
	
	_get_engineering_search_list($search, $eng_search_results);
  
  $form_elems = drupal_get_form('results_list_form', $eng_search_results);
	$content = render($form_elems);
	die($content);  // always die as this is an ajax callback (we only want a partial page render)
}

/*
 * engineering_results_callback()
 * 
 * Clears the search results cache
 *
 */
function engineering_clear_results_callback() {
		
	// determine cache name
	global $user;
	$results_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SEARCH_RESULTS);
	$key_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SEARCH_KEY);
	$selected_cache_name = _get_qms_cache_name(QMS_ENGINEERING_SELECTED);
	
	cache_clear_all($results_cache_name, 'cache', TRUE); 
	cache_clear_all($key_cache_name, 'cache', TRUE); 
	cache_clear_all($selected_cache_name, 'cache', TRUE); 
	
	//just return an empty form container
	$content = '<form id="results-list-form"></form>';
	
	// this is an ajax callback.  Need to return + die or it renders a full page
	// we only want a piece of a page
	
	die($content);  
}




