<?php
// $Id$

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

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

/*
 *	search_vendors()
 *
 */

function search_vendors() {

  drupal_add_library('system','ui.dialog');
  //drupal_add_library('system','ui.datepicker');
  drupal_add_js('misc/tableselect.js');	// this doesn't seem to load consistently unless specified here
  drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.searchvendors.js');

  $vendor_search_form = '';
  $vendor_search_results = '';
  $form_cache_name = QMS_VENDOR_SEARCH_FORM;
  $vendor_search_results = new SearchResultsTable('VE');

  // this is required for forms that have customer-specific informtion
  // such as simulators
  // not necessary for the vendors form... so far
  // global $user;
  // $user_is_customer_id = _user_is_customer($user->uid);

//  if( $user_is_customer_id ) {
//    $form_elems = drupal_get_form('vendor_search_form');
//    $vendor_search_form = render($form_elems);
//  }
//  else {
    $form_cache = cache_get($form_cache_name);
    if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
      $vendor_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('vendor_search_form');
      $vendor_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, $vendor_search_form, 'cache', time() + QMS_CACHE_TIMEOUT);
    }
//  }

  // determine cache name
  $results_cache_name = _get_qms_cache_name(QMS_VENDOR_SEARCH_RESULTS);
  $selected_cache_name = _get_qms_cache_name(QMS_VENDOR_SELECTED);

  $results_cache = cache_get($results_cache_name);
  if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
    $vendor_search_results = $results_cache->data;
    _check_if_selected($selected_cache_name, $vendor_search_results);

    // need to force this or pager/sort picks up the wrong path
    $_GET['q'] = 'search/vendors/pager';

    $form_elems = drupal_get_form('results_list_form', $vendor_search_results);
    $vendor_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
    $vendor_search_results = '<form id="results-list-form"></form>';

    // don't cache the empty form object
    //cache_set($results_cache_name, $vendor_search_results, 'cache', time() + QMS_CACHE_TIMEOUT);
  }

  $content = $vendor_search_form . $vendor_search_results;

  return $content;
}

/*
 *	vendor_search_form()
 *
 *  overloads:  hook_form()
 *  search form for vendors
 */
function vendor_search_form($form, $form_state) {


  //------------ BUILD SEARCH FORM ------------------

  $form['search'] = array(
    '#type' => 'fieldset',
    '#title' => t('Search'),
    '#collapsible' => True,
    '#collapsed' => False,
    '#attributes' => array('id' => 'qms-search-div'),
  );


  $form['search']['vendor'] = array(
    '#type' => 'container',
    '#attributes' => array('id' => 'qms-search-vendor'),
  );

  // vendor code
  $form['search']['vendor']['code'] = array(
    '#type' => 'textfield',
    '#title' => t('Vendor Code'),
    '#maxlength' => 10,
    '#size' => 10,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-vendor-code'),
  );

  // vendor name
  $form['search']['vendor']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Vendor Name'),
    '#maxlength' => 70,
    '#size' => 56,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-vendor-name'),
  );
  

  $form['search']['vendor_location'] = array(
    '#type' => 'container',
    '#attributes' => array('id' => 'qms-search-vendor-location'),
    '#suffix' => '<br class="clearBoth" />',
  );

  // address
  $form['search']['vendor_location']['city'] = array(
    '#type' => 'textfield',
    '#title' => t('City'),
    '#maxlength' => 60,
    '#size' => 40,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-vendor-city'),
  );
  // address
  $form['search']['vendor_location']['state'] = array(
    '#type' => 'textfield',
    '#title' => t('State/Province'),
    '#maxlength' => 10,
    '#size' => 10,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-vendor-state'),
  );

  // address
  $form['search']['vendor_location']['zip'] = array(
    '#type' => 'textfield',
    '#title' => t('Zip/Postal'),
    '#maxlength' => 10,
    '#size' => 10,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-vendor-zip'),
  );
  
  // vendor name
  $form['search']['note'] = array(
    '#type' => 'textfield',
    '#title' => t('Vendor Note'),
    '#maxlength' => 70,
    '#size' => 72,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-vendor-note'),
  );


  //--------------------------------------------
  // 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/vendors/search') ),
  );

  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/vendors/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;
}


/**
 * vendor_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 vendor_search_form_callback() {

  $search = (object) NULL;

  if (!empty($_POST['code'])) {
    $search->code = trim($_POST['code']);
  }
  if (!empty($_POST['name'])) {
    $search->name = trim($_POST['name']);
  }
  if (!empty($_POST['note'])) {
    $search->note = trim($_POST['note']);
  }
  if (!empty($_POST['city'])) {
    $search->city = trim($_POST['city']);
  }
  if (!empty($_POST['state'])) {
    $search->state = trim($_POST['state']);
  }
  if (!empty($_POST['zip'])) {
    $search->zip = trim($_POST['zip']);
  }


  // 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_VENDOR_SEARCH_KEY);
  $selected_cache_name =  _get_qms_cache_name(QMS_VENDOR_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);

  $vendor_search_results = new SearchResultsTable('VE');

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

/**
 * vendor_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 vendor_pager_callback() {

  $search = (object) NULL;

  // determine the key cache
  $key_cache_name =  _get_qms_cache_name(QMS_VENDOR_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
    if (!empty($_POST['code'])) {
      $search->code = trim($_POST['code']);
    }
    if (!empty($_POST['name'])) {
      $search->name = trim($_POST['name']);
    }
    if (!empty($_POST['note'])) {
      $search->note = trim($_POST['note']);
    }
    if (!empty($_POST['city'])) {
      $search->city = trim($_POST['city']);
    }
    if (!empty($_POST['state'])) {
      $search->state = trim($_POST['state']);
    }
    if (!empty($_POST['zip'])) {
      $search->zip = trim($_POST['zip']);
    }

    // cache the latest search key, expire it in 30min
    cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);

  }

  // get the previous SearchResultsTable object
  $vendor_search_results = new SearchResultsTable('SL');

  _get_vendor_search_list($search, $vendor_search_results);
  $form_elems = drupal_get_form('results_list_form', $vendor_search_results);
  $content = render($form_elems);
  die($content);
}

/*
 * vendor_results_callback()
 *
 * Clears the search results cache
 *
 */
function vendor_clear_results_callback() {

  // Clear the cache

  // determine cache name
  $results_cache_name = _get_qms_cache_name(QMS_VENDOR_SEARCH_RESULTS);
  $key_cache_name =  _get_qms_cache_name(QMS_VENDOR_SEARCH_KEY);
  $selected_cache_name =  _get_qms_cache_name(QMS_VENDOR_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);

  $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);
}
