<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *    vendor handling
 */
require_once('sabreQMS.vendorlist.inc');

 /*
  *	vendor_form()
  *
  *  overloads:  hook_form()
  *
  *	Displays a vendor form to accept user input
  */
function vendor_form($form, $form_state, $vendor_id = 0) {

  $bAdmin = user_access('administer sabreQMS');

  $access_level = 'create vendor';
  if ($vendor_id > 0) { $access_level = 'edit vendor'; }

  if ( (user_access($access_level) == FALSE) && ($bAdmin == FALSE) ) {
   drupal_set_message( t('Unauthorized:  Permission required'), 'status');
   return;
  }

  global $user;
  $user_is_customer_id = _user_is_customer($user->uid);
  if ($user_is_customer_id) {
    if ( !$vendor_id && ! _vendor_customer_access($user_is_customer_id, $vendor_id)) {
      drupal_set_message( t('Unauthorized:  Permission required'), 'status');
      return;
    }
  }

  // javascript loaded in the after_build function
  $form['#after_build'][] = 'vendor_form_after_build';

  $vendor = (object) Null;
  global $base_url;

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

  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = 'search/vendors';
  }

  if ( $vendor_id > 0 ) { // EDITING

    if ( !$bAdmin ) {
      drupal_set_message( t('Unauthorized:  Permission required to edit vendor.'), 'status');
      drupal_goto($goto_url);
      return;
    }

    // get the vendor
    $vendor = _get_vendor($vendor_id);

    if ( $vendor == (object) Null ) {
      drupal_set_message( t('Vendor Not Found!'), 'warning');
      drupal_goto($goto_url);
      return;
    }

    $form['vendor_display'] = array(
      //'#title' => t('DR No.'),
      '#type' =>'item',
      '#markup' => _st_format_record_timestamp_table($vendor),
    );
  }


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

  $form['vendor']['code'] = array(
    '#type' => 'textfield',
    '#title' => t('Code'),
    '#default_value' => (isset($vendor->code) ? $vendor->code : ''),
    '#maxlength' => 20,
    '#size' => 12,
    '#required' => True,
    '#attributes' => array('id' => 'qms-vendor-code'),
  );

  // storage field for the vendor_id (edit) -- hidden
  $form['vendor']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => (isset($vendor->name) ? $vendor->name : ''),
    '#maxlength' => 255,
    '#size' => 60,
    '#required' => True,
    '#attributes' => array('id' => 'qms-vendor-name'),
  );

  $form['address'] = array(
    '#type' => 'fieldset',
    '#title' => t('Address'),
    //'#attributes' => array('id' => 'qms-vendor-address'),
  );

  $form['address']['address_line_1'] = array(
    '#type' => 'textfield',
    //'#title' => t('Line 1'),
    '#default_value' => (isset($vendor->address_line_1) ? $vendor->address_line_1 : ''),
    '#maxlength' => 100,
    '#size' => 78,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-line1'),
  );
  $form['address']['address_line_2'] = array(
    '#type' => 'textfield',
    //'#title' => t('Line 2'),
    '#default_value' => (isset($vendor->address_line_2) ? $vendor->address_line_2 : ''),
    '#maxlength' => 100,
    '#size' => 78,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-line2'),
  );
  $form['address']['address_line_3'] = array(
    '#type' => 'textfield',
    //'#title' => t('Line 3'),
    '#default_value' => (isset($vendor->address_line_3) ? $vendor->address_line_3 : ''),
    '#maxlength' => 100,
    '#size' => 78,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-line3'),
  );

  $form['address']['csz_box'] = array(
    '#type' => 'container',
    '#attributes' => array('id' => 'qms-vendor-csz-box'),
    '#suffix' => '<br class="clearBoth" />',
  );

  $form['address']['csz_box']['city'] = array(
    '#type' => 'textfield',
    '#title' => t('City'),
    '#default_value' => (isset($vendor->city) ? $vendor->city : ''),
    '#maxlength' => 50,
    '#size' => 30,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-city'),
  );

  $form['address']['csz_box']['state_province'] = array(
    '#type' => 'textfield',
    '#title' => t('State/Province'),
    '#default_value' => (isset($vendor->state_province) ? $vendor->state_province : ''),
    '#maxlength' => 2,
    '#size' => 3,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-state-province'),
  );
  $form['address']['csz_box']['zip_postal'] = array(
    '#type' => 'textfield',
    '#title' => t('Zip/Postal Code'),
    '#default_value' => (isset($vendor->zip_postal) ? $vendor->zip_postal : ''),
    '#maxlength' => 20,
    '#size' => 12,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-zip-postal'),
  );
  $form['address']['country'] = array(
    '#type' => 'textfield',
    '#title' => t('Country'),
    '#default_value' => (isset($vendor->country) ? $vendor->country : ''),
    '#maxlength' => 100,
    '#size' => 30,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-address-country'),
  );

  $form['phone'] = array(
    '#type' => 'fieldset',
    '#title' => t('Phone'),
    '#attributes' => array('id' => 'qms-vendor-phone'),
  );

  $form['phone']['phone_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone #1'),
    '#default_value' => (isset($vendor->phone_1) ? $vendor->phone_1 : ''),
    '#maxlength' => 25,
    '#size' => 20,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-phone-1'),
  );
  $form['phone']['phone_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone #2'),
    '#default_value' => (isset($vendor->phone_2) ? $vendor->phone_2 : ''),
    '#maxlength' => 25,
    '#size' => 20,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-phone-2'),
  );
  $form['phone']['phone_3'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone #3'),
    '#default_value' => (isset($vendor->phone_3) ? $vendor->phone_3 : ''),
    '#maxlength' => 25,
    '#size' => 20,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-phone-3'),
  );

  $form['web'] = array(
    '#type' => 'fieldset',
    '#title' => t('Web'),
    '#attributes' => array('id' => 'qms-vendor-web'),
  );
  $form['web']['email_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Email #1'),
    '#default_value' => (isset($vendor->email_1) ? $vendor->email_1 : ''),
    '#maxlength' => 255,
    '#size' => 78,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-email-1'),
  );
  $form['web']['email_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Email #2'),
    '#default_value' => (isset($vendor->email_2) ? $vendor->email_2 : ''),
    '#maxlength' => 255,
    '#size' => 78,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-email-2'),
  );
  $form['web']['website'] = array(
    '#type' => 'textfield',
    '#title' => t('Website'),
    '#default_value' => (isset($vendor->website) ? $vendor->website : ''),
    '#maxlength' => 255,
    '#size' => 78,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-website'),
  );
  $form['reference_ids'] = array(
    '#type' => 'fieldset',
    '#title' => t('Reference IDs'),
    '#attributes' => array('id' => 'qms-vendor-reference-ids'),
  );
  $form['reference_ids']['tax_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Tax Id'),
    '#default_value' => (isset($vendor->tax_id) ? $vendor->tax_id : ''),
    '#maxlength' => 20,
    '#size' => 10,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-tax-id'),
  );
  $form['reference_ids']['duns_id'] = array(
    '#type' => 'textfield',
    '#title' => t('D&B DUNS Id'),
    '#default_value' => (isset($vendor->duns_id) ? $vendor->duns_id : ''),
    '#maxlength' => 20,
    '#size' => 10,
    '#required' => False,
    '#attributes' => array('id' => 'qms-vendor-duns-id'),
  );
  
  
  $text_settings = array(
    'name' => 'vendor_note_text',
    'title' => t('Note'),
    'text' =>	(($vendor_id > 0) ? $vendor->note : ''),
    'required' => False,
    'disabled' => False,
  );

  _st_add_text_editor($form, $text_settings);


  // associated customers -- admin only
  //----------- build the user list table for this user group -----------------

  if ($bAdmin) {
    global $customer_list;

    $vendor_customer_list = _get_vendor_customers($vendor_id);
    $vendor_customer_table = _format_vendor_customers_table($vendor_customer_list, (($vendor_id > 0) ? 'EDIT':'ADD'));

    // turn database results array into an assoc array by user_id
    // needs to be in the same format as the UserList
    $assigned_customer_list = array();
    foreach($vendor_customer_list as $c) {
        $assigned_customer_list[$c->customer_id] = $c->customer;
    }

    $form['fs_customers'] = array(
      '#type' => 'fieldset',
      '#title' => 'Customers linked to this vendor',
    );

    $form['fs_customers']['customers'] = array(
      '#markup' => $vendor_customer_table,
    );

    $form['fs_customers']['customer_select'] = array(
      '#type' => 'select',
      '#title' => t('Add Customer'),
      '#options' => $customer_list->get_unassigned($assigned_customer_list),
      '#default_value' => 0,
      '#attributes' => array('id' => 'qms-customer-select',
                             'class' => array('qms-select')),  // this is necessary for CKEditor functions
      // putting this in a 1x1 table for consistency
      '#prefix' => '<table class="qms-plain-table"><tr style="vertical-align:bottom;"><td style="width:35%">',
      '#suffix' => '</td>',
    );

    $form['fs_customers']['add_customer'] = array(
      '#type' => 'button',
      '#value' => t('Add'),
      '#attributes' => array('id' => 'qms-btn-add-customer',
                             'qms-url' => (( $vendor_id > 0 ) ?
                                  url('vendor/customer/add') :
                                  url('vendor/customer/refresh')) ),
      '#prefix' => '<td><div class="qms-actions">',
      '#suffix' => '&nbsp;&nbsp;<a id="qms-btn-clear-selection" href="">Clear</a></div></td></tr></table>',
    );

    if ( $vendor_id == 0 ) {  // storage field for new vendor, adding customers
      // need to wrap this in a hidden div since the textarea seems to want to display the grabber bar
      $form['fs_customers']['customers_to_add'] = array(
        '#type' => 'textarea',
        '#default_value' => '',
        '#prefix' => '<div id="qms-customers-hidden" class="qms-hidden-field">',
        '#attributes' => array('id' => 'qms-customers-to-add'),
      );
    }
  }


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

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
  );


  if ( $vendor_id > 0 ) {
    $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;'),
  );

    /*
  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $goto_url,
                  array('attributes' => array('id' => 'qms-btn-cancel'))),
  );*/


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

  $form['report_changed'] = array(
    '#type' => 'textfield',
    '#default_value' => 0,
    '#attributes' => array('id' => 'qms-report-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.
*/

/*
* vendor_form_after_build()
*
*/
function vendor_form_after_build($form, &$form_state) {
  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');
  
  // 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));
  }

  if ( (int)$form['vendor_id']['#default_value'] == 0) {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.vendoradd.js');
  } else {
    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.vendoredit.js');
  }
  
  return $form;
}


/*
 *	vendor_form_validate()
 *
 *  overloads:  hook_form_validate()
 *
 */


function vendor_form_validate($form, $form_state) {


  $button_clicked = $form_state['triggering_element']['#name'];

  if ( $form['actions']['submit']['#name'] != $button_clicked ){
    return $form;
  }

  // validate vendor code
  $code = $form_state['values']['code'];
  $name = $form_state['values']['name'];
  $vendor_id = $form_state['values']['vendor_id'];


  // code should be unique
  if (False == _vendor_input_valid('code', $code, $vendor_id)) {
    form_set_error('code', t('Vendor code already exists, must be unique.'));
  }

  // code should be unique
  if (False == _vendor_input_valid('name', $name,  $vendor_id)) {
    form_set_error('name', t('Vendor name already exists, must be unique.'));
  }

  return $form;
}



/*
 *	vendor_form_submit()
 *
 *  overloads:  hook_form_submit()
 *
 *	Handles the Vendor form submitted data, stores to db
 */
function vendor_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) ){

    $vendor_id = isset($form_state['values']['vendor_id']) ?
                        (int) $form_state['values']['vendor_id'] : 0;

    if ( !$vendor_id && isset($form['vendor_id']['#default_value'])) {
      $vendor_id = $form['vendor_id']['#default_value'];
    }
    if ( $vendor_id ) {
      $_GET['destination'] = 'vendor/delete/' . $vendor_id .
                            '?destination=vendor/edit/' . $vendor_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/vendors';
    }

    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 --------------------

  $vendor = new stdClass();
  global $user;
  $bUpdate = False;
  $msg = '';
  $currtimestamp = REQUEST_TIME;

  $vendor_id = (int) $form_state['values']['vendor_id'];
  $vendor->vendor_id = $vendor_id;  // we need to save this separately

  if ( (int)$form_state['values']['report_changed'] == 0 ) {
    if ( user_access('administer sabreQMS') == True ) {
      drupal_goto('vendor/edit/' . $vendor->vendor_id);
    }
    else if ( user_access('search view logs') == True ) {
      drupal_goto('vendor/view/' . $vendor->vendor_id);
    }
    else {
      drupal_goto(''); // go to home page if permissions don't allow a search
    }
    return;
  }

  $vendor->name = $form_state['values']['name'];
  $vendor->code = $form_state['values']['code'];
  $vendor->address_line_1 = $form_state['values']['address_line_1'];
  $vendor->address_line_2 = $form_state['values']['address_line_2'];
  $vendor->address_line_3 = $form_state['values']['address_line_3'];
  $vendor->city = $form_state['values']['city'];
  $vendor->state_province = $form_state['values']['state_province'];
  $vendor->zip_postal = $form_state['values']['zip_postal'];
  $vendor->country = $form_state['values']['country'];
  $vendor->phone_1 = $form_state['values']['phone_1'];
  $vendor->phone_2 = $form_state['values']['phone_2'];
  $vendor->phone_3 = $form_state['values']['phone_3'];
  $vendor->email_1 = $form_state['values']['email_1'];
  $vendor->email_2 = $form_state['values']['email_2'];
  $vendor->website = $form_state['values']['website'];
  $vendor->tax_id = $form_state['values']['tax_id'];
  $vendor->duns_id = $form_state['values']['duns_id'];
  $vendor->note = _st_clean_ckeditor_text($form_state['values']['vendor_note_text_editor_value'],
                                                      QMS_TEXTAREA_MAX);


  if ( ! $vendor->vendor_id ) {  // new vendor
    $vendor->created_date = $currtimestamp;
    $vendor->created_by_user = $user->uid;
  }

  $vendor->updated_date = $currtimestamp;		// always update this, even at create time
  $vendor->updated_by_user = $user->uid;


  // save record
  // Table:  {qms_vendors}
  if ( $vendor->vendor_id > 0 ) {
    if ( False == drupal_write_record('qms_vendors', $vendor, 'vendor_id')) {
         // update
        $msg = 'Oops!  Something went wrong, updates to Vendor were not saved.';
        drupal_set_message(t($msg));
        drupal_goto('vendor/edit/' . $vendor->vendor_id );
        return;
    }

    // Reload the cache
    // determine cache name
    $search = (object) Null;
    $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;
      _get_vendor_search_list($search);
    }

    // EDIT -- assigned customers have already been saved interactively
  }
  else {

    // Save the NEW vendor record
    if ( False == drupal_write_record('qms_vendors', $vendor)) {
      $msg = 'Oops!  Something went wrong, Vendor entry was not saved.';
      drupal_set_message($msg);
      drupal_goto('vendors');
      return;
    }


    // vendor customers
    $customers_to_add = ( !empty($form_state['values']['customers_to_add']) ? 
                          trim($form_state['values']['customers_to_add']) : '' );
    $customer_list = explode('|', $customers_to_add);


    // add the vendor's customers
    $vendor_customer = new stdClass();
    $vendor_customer->vendor_id = $vendor->vendor_id;
    $vendor_customer->created_date = $currtimestamp;
    $vendor_customer->created_by_user = $user->uid;


    foreach( $customer_list as $c ) {
      $cust_rec = explode('=', $c);
      if (isset($cust_rec[1])) {
        $vendor_customer->customer_id = $cust_rec[1];


        // Table:  {qms_vendors_customers}
        if ( False == drupal_write_record('qms_vendors_customers', $vendor_customer)) {
          $msg = "Oops!  Something went wrong saving the vendor customers to the database.";
          drupal_set_message(t($msg));
        }

        $vendor_customer->vendor_customer_id = 0;
      }
    }

  }


  $msg = "Vendor was successfully saved.";
  drupal_set_message(t($msg));


  // WHERE ARE WE GOING NEXT???
  if ( user_access('administer sabreQMS') == True ) {
    drupal_goto('vendor/edit/' . $vendor->vendor_id);
  }
  else if ( user_access('search view reports') == True ) {
    drupal_goto('vendor/view/' . $vendor->vendor_id);
  }
  else {
    drupal_goto(''); // go to home page if permissions don't allow anything else
  }
}

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

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

function view_vendor_form($form, $form_state, $vendor_id) {

  if ( $vendor_id == 0 ) {
    return;
  }

  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.view.js');

  $bAdmin = user_access('administer sabreQMS');

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


  // get the Vendor record
  $vendor = _get_vendor($vendor_id);

  if ( $vendor == (object) Null ) {
    drupal_set_message( t('Vendor Not Found!'), 'warning');
    drupal_goto('search/vendors');
    return;
  }

  $form['vendor_timestamps'] = array(
    '#markup' => _st_format_record_timestamp_table($vendor),
  );

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

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

  $form['code'] = array(
    '#type' => 'item',
    '#title' => t('Code'),
    '#markup' => $vendor->code,
  );

  $form['name'] = array(
    '#type' => 'item',
    '#title' => t('Name'),
    '#markup' => $vendor->name,
  );

  $form['address'] = array(
    '#type' => 'fieldset',
    '#title' => t('Address'),
  );

  $form['address']['address_line_1'] = array(
    '#type' => 'item',
    '#markup' => $vendor->address_line_1,
  );
  $form['address']['address_line_2'] = array(
    '#type' => 'item',
    '#markup' => $vendor->address_line_2,
  );
  $form['address']['address_line_3'] = array(
    '#type' => 'item',
    '#markup' => $vendor->address_line_3,
  );

  $form['address']['city'] = array(
    '#type' => 'item',
    '#title' => t('City'),
    '#markup' => $vendor->city,
  );
  $form['address']['state'] = array(
    '#type' => 'item',
    '#title' => t('State/Province'),
    '#markup' => $vendor->state_province,
  );
  $form['address']['zip_postal'] = array(
    '#type' => 'item',
    '#title' => t('Zip/Postal Code'),
    '#markup' => $vendor->zip_postal,
  );
  $form['address']['country'] = array(
    '#type' => 'item',
    '#title' => t('Country'),
    '#markup' => $vendor->country,
  );

  $form['phone'] = array(
    '#type' => 'fieldset',
    '#title' => t('Phone'),
  );
  $form['phone']['phone_1'] = array(
    '#type' => 'item',
    '#title' => t('Phone #1'),
    '#markup' => $vendor->phone_1,
  );
  $form['phone']['phone_2'] = array(
    '#type' => 'item',
    '#title' => t('Phone #2'),
    '#markup' => $vendor->phone_2,
  );
  $form['phone']['phone_3'] = array(
    '#type' => 'item',
    '#title' => t('Phone #3'),
    '#markup' => $vendor->phone_3,
  );

  $form['web'] = array(
    '#type' => 'fieldset',
    '#title' => t('Web'),
  );
  $form['web']['email_1'] = array(
    '#type' => 'item',
    '#title' => t('Email #1'),
    '#markup' => $vendor->phone_1,
  );
  $form['web']['email_2'] = array(
    '#type' => 'item',
    '#title' => t('Email #2'),
    '#markup' => $vendor->phone_2,
  );
  $form['web']['website'] = array(
    '#type' => 'item',
    '#title' => t('Website'),
    '#markup' => $vendor->website,
  );

  $form['reference_ids'] = array(
    '#type' => 'fieldset',
    '#title' => t('Reference IDs'),
  );
  $form['reference_ids']['tax_id'] = array(
    '#type' => 'item',
    '#title' => t('Tax Id'),
    '#markup' => $vendor->tax_id,
  );
  $form['reference_ids']['duns_id'] = array(
    '#type' => 'item',
    '#title' => t('D&B DUNS Id'),
    '#markup' => $vendor->duns_id,
  );
  
  $form['note'] = array(
    '#type' => 'fieldset',
    '#title' => t('Note'),
  );
  
  $form['note']['note'] = array(
    '#type' => 'item',
    //'#title' => t('Note'),
    '#markup' => ($ckeditor_activated ? _st_convert_symbols($vendor->note) : nl2br(_st_convert_symbols($vendor->note))),
  );

  if ($bAdmin) {
    $vendor_customer_list = _get_vendor_customers($vendor_id);
    $vendor_customer_table = _format_vendor_customers_table($vendor_customer_list, 'VIEW');

    $form['fs_customers'] = array(
      '#type' => 'fieldset',
      '#title' => 'Customers linked to this vendor',
    );

    $form['fs_customers']['customers'] = array(
      '#markup' => $vendor_customer_table,
    );
  }


  $prev_report_link = '';
  $next_report_link = '';

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

  if( !strlen($goto_url) || ($goto_url == current_path()) ) {
    $goto_url = 'search/vendors';
  }


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

  if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
    $sl_search_results = $results_cache->data;
    $sl_results_table_rows = $sl_search_results->getResults();

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


  $form['actions'] = array( '#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Done'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
                            //'qms-url' => $goto_url),
  );
  $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' =>
                                                'vendor/view/' . $vendor_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' =>
                                                'vendor/view/' . $vendor_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' =>
                                                'vendor/view/' . $vendor_id)),
    );
  }


  return $form;
}

/*
 *	view_vendor_form_submit()
 *
 *  Overloads hook_form_submit()
 *  Vendor VIEW ONLY submit handler, just routes
 */


function view_vendor_form_submit($form, $form_state) {

  $button_clicked = $form_state['triggering_element']['#name'];

  if ( $form['actions']['submit']['#name'] == $button_clicked ){
    drupal_goto('search/vendors');
  }
  else if ( isset($form['actions']['edit']['#name']) &&
            ($form['actions']['edit']['#name'] == $button_clicked)) {

    $vendor_id = isset($form_state['values']['vendor_id']) ?
                        (int) $form_state['values']['vendor_id'] : 0;

    if ( !$vendor_id && isset($form['vendor_id']['#default_value'])) {
      $vendor_id = $form['vendor_id']['#default_value'];
    }

    if ( $vendor_id ) {

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

}


/*
 *	vendor_delete_confirm()
 *
 *  Delete the shift log entry -- ADMIN ONLY
 */

function vendor_delete_confirm($form, $form_state, $vendor_id) {

  $bAdmin = user_access('administer sabreQMS');

  if ( $bAdmin == False ) {
    drupal_set_message(t('Administrator permissions required to delete a vendor.'));
    drupal_goto('vendor/edit/' . $vendor_id);
    return;
  }

  $vendor = _get_vendor($vendor_id);

  if ( empty($vendor) ) {
    drupal_set_message(t('Unable to delete vendor.  Record not found.'));
    drupal_goto('vendor/edit/' . $vendor_id);
    return;
  }

  // storage field for the discrepancy_id (edit) -- hidden
  $form['vendor_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $vendor_id,
    '#attributes' => array('id' => 'qms-vendor-id',
                            'class' => array('qms-hidden-field')),
  );


  $title = t('Delete Vendor') . '?';
  $question =
      t('Are you sure you want to delete?') .
      '<h2>' . $vendor->name . '</h2>' . '<br />' .
      t('This action cannot be undone.');
  $goto_if_canceled = 'vendor/edit/' . $vendor_id;
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');

  // force this here to avoid a problem with routing if cancelled
  $_GET['destination'] = 'search/vendors';

  return confirm_form($form, $title,	$goto_if_canceled, $question,
                      $yes_btn, $no_btn);


}

/*
 *	vendor_delete_confirm_submit()
 *
 *  overloads:  hook_confirm_submit()
 *  Delete the shift log entry -- ADMIN ONLY
 */


function vendor_delete_confirm_submit($form, $form_state) {

  if ($form_state['values']['confirm']) {
    $vendor_id = (int) $form_state['values'] ['vendor_id'];

    // DELETE VENDOR

    db_delete('qms_vendors_customers')
          ->condition('vendor_id', $vendor_id)
          ->execute();

    // db_delete('qms_vendors_parts')
    //       ->condition('vendor_id', $vendor_id)
    //       ->execute();

    $num_rows = db_delete('qms_vendors')
          ->condition('vendor_id', $vendor_id)
          ->execute();

    $msg = ( ($num_rows == 1) ? 'The vendor has been deleted.' : 'Error occurred deleting vendor.');
    drupal_set_message($msg);

    // Reload the cache

    // determine cache name
    $search = (object) Null;
    $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;
      _get_vendor_search_list($search, 0, True);
    }
  }
  drupal_goto('search/vendors');
}


/*
 *  vendor_customer_add_user_callback()
 *
 *	AJAX Callback Function
 *
 */
function vendor_add_customer_callback() {

  $content = "";
  $customer_list = array();
  $vendor_id = ( isset($_POST['vendor_id'])  ? (int)$_POST['vendor_id'] : 0 );
  $customer_id = ( isset($_POST['customer_id'])  ? (int)$_POST['customer_id'] : 0 );
  global $user;


  if ( ($vendor_id > 0) && ($customer_id > 0) ) {
    $query = db_insert('qms_vendors_customers')
               ->fields(array(
                        'vendor_id',
                        'customer_id',
                        'created_date',
                        'created_by_user',
                      ))
              ->values(array(
                        'vendor_id' => $vendor_id,
                        'customer_id' => $customer_id,
                        'created_date' => REQUEST_TIME,
                        'created_by_user' => $user->uid,
                      ))
              ->execute();

    $customer_list = _get_vendor_customers($vendor_id);
  }
  $content = _format_vendor_customers_table($customer_list, "EDIT");
  die($content);
}

/*
 *  vendor_customer_remove_callback()
 *
 *	AJAX Callback Function
 *
 */
function vendor_remove_customer_callback() {

  $content = "";

  $vendor_id = ( isset($_POST['vendor_id'])  ? (int)$_POST['vendor_id'] : 0 );
  $customer_id = ( isset($_POST['customer_id'])  ? (int)$_POST['customer_id'] : 0 );

  if ( $customer_id > 0 && $vendor_id > 0 ) {


    // delete customer links
    db_delete('qms_vendors_customers')
              ->condition('vendor_id', $vendor_id)
              ->condition('customer_id', $customer_id)
              ->execute();


  }
  $customer_list = _get_vendor_customers($vendor_id);
  $content = _format_vendor_customers_table($customer_list, "EDIT");

  die($content);
}


/*
 *  vendor_customer_table_refresh_callback()
 *
 *	AJAX Callback Function
 *  Reformats and redisplays customer table without links which has not been added yet
 *
 */
function vendor_customer_table_refresh_callback() {

  // break user id list into individual records
  $cl = trim($_POST['customer_list']);
  $customer_list = array();
  $customer_row_data = array();


  if ( strlen($cl) > 0 ) {
    $customer_list = explode('|', $cl);
    //asort($group_user_list);
  }
  else {  // only one in the list
    $customer_list = $cl;
  }


  $content = _format_vendor_customers_table($customer_list, 'ADD');

  die($content);
}

/*
 *  _format_vendor_customers_table()
 *
 *	accepts the vendor customer list and formats it/themes it into a table
 *
 */

function _format_vendor_customers_table($customer_list, $mode = 'EDIT') {

  $content = "";
  $user_row_data = array();
  $header = array(array('data' => 'Customer', 'class' => 'qms-vendor-customer-tbl-col1'));

  $i = 0;
  if (count($customer_list)) {
    foreach($customer_list as $c) {

      if ( $mode == 'ADD') {
        $customer_info = explode('=', $c);
        $link_options = l( t('Remove'), "",  array('attributes' => array('class' => 'qms-customer-remove', 'row' => $i) ) );
        $customer_row_data[$i] = array('data' => array( $customer_info[0], $link_options));

      } else if ( $mode == 'EDIT' ) {  // EDIT
        $row = array(
          $c->customer,
          l( t('Remove'), "vendor/customer/remove/" . $c->customer_id,
                  array('attributes' => array('class' => 'qms-customer-remove', 'row' => $i, 'customer' => $c->customer) ) ),
        );
        $customer_row_data[] = array( 'data' => $row );

      } else {
        // VIEW
        $customer_row_data[] = array( 'data' => array( $c->customer ) );
      }
      $i++;
    }
  }
  if ( $i == 0 ) {
    if ($mode == 'VIEW') {
      $customer_row_data = array('data' => array('None'));
    } else {
      $customer_row_data = array('data' => array('None', ''));
    }
  }


  // rebuild table
  $content = '<div id="qms-customers-div">';
  if (($mode == 'ADD') || ($mode == 'EDIT')) {
    $header[] = array('data' => 'Admin');
  }

  $content .= theme( 'table', array(
    'header' => $header,
    'rows' => $customer_row_data,
  ));

  $content .= '</div>';

  return $content;
}


/*
 * _get_vendor($vendor_id)
 * Returns and object pointing to the vendor record data
 */

function _get_vendor($vendor_id) {

  $vendor = (object) Null;

  // get the vendor record
  $sql = "SELECT * FROM qms_vendors
          WHERE vendor_id = :vid";
  $result = db_query($sql, array(':vid' => $vendor_id));

  if ( $result->rowCount() ) {
    $vendor = $result->fetchObject();
  }
  return $vendor;
}


/*
 *  _get_vendor_customers($vendor_id = 0)
 *
 *	Returns the Vendor Customers
 *
 */

function _get_vendor_customers($vendor_id = 0) {

  if ( $vendor_id == 0 ) return array();

  $sql = "SELECT c.customer_id, c.customer
          FROM   qms_vendors_customers vc
          LEFT JOIN qms_customers c on vc.customer_id = c.customer_id
          WHERE  vc.vendor_id = :vid
          AND    c.active = 1
          ORDER BY c.customer ASC";

  return db_query($sql, array(':vid' => $vendor_id))->fetchAll();
}


/*
 *
 */
function _vendor_customer_access($user_is_customer_id, $vendor_id) {
  if (!$user_is_customer_id || !$vendor_id) { return TRUE; }

  $sql = "SELECT qms_vendor_customer_id
          FROM   qms_vendors_customers
          WHERE  vendor_id = :vid
          AND    customer_id = :cid";
  $result = db_query($sql);
  if ($result->rowCount() > 0) {
    return True;
  }
  return False;
}

/*
 * _validate_vendor_input
 */
function _vendor_input_valid($field, $input, $vendor_id) {

  $sql = "SELECT $field FROM qms_vendors
          WHERE $field = :input
          AND   vendor_id != :vid";

  $result = db_query($sql, array(':input' => $input, ':vid' => $vendor_id));
  if ($result->rowCount()) {
    return False;
  }
  return True;
}
