<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *	 	General File handling utility functions to server Discrepancies and Shiftlogs
 *		Processing specific to DRs or SLs files is still handled by their respective scripts
 *
*/

require_once('sabreQMS.discrepancy.inc');
require_once('sabreQMS.shiftlog.inc');
require_once('sabreQMS.simulators.inc');

/**** NOTE ****
 Any changes made to add extensions needs to be reflected in _add_http_content_type()
 ***************/

define('QMS_VALID_FILE_UPLOAD_EXTENSIONS', 'avi csv doc docm docx eml flv gif jpg jpeg mov msg mp4 mpg odp ods odt pcap pdf png ppt ppam pps ppsm ppsx pptm pptx psd rar txt wav wmv xls xlsm xlsx zip');

define('QMS_PLUPLOAD_FILE_EXTENSIONS', 'avi,csv,doc,docm,docx,eml,flv,gif,jpg,jpeg,mov,msg,mp4,mpg,odp,ods,odt,pcap,pdf,png,ppt,ppam,pps,ppsm,ppsx,pptm,pptx,psd,rar,txt,wav,wmv,xls,xlsm,xlsx,zip');


define('QMS_PLUPLOAD_RUNTIMES', 'html5,silverlight,flash,browserplus,gears');
//define('QMS_PLUPLOAD_RUNTIMES', 'gears');  // Gears has no longer supported by Google

define('QMS_PLUPLOAD_UPLOADER', 'uploader');
//define('QMS_PLUPLOAD_UPLOADER', 'plupload_files');




// ------------------------- FILE UPLOADS INTERFACES ---------------------------------

/*
 *		file_upload_orig_form()
 *
 *		Upload files using the original individual files inputs (up to 5)
 *	  for Discrepancy and Shift Log Reports
 */

function file_upload_orig_form($form, $form_state, $report_type, $report_id) {


  if ( ('DR' != $report_type) && ('SL' != $report_type) && ('SI' != $report_type) ) {
    return $form;  // fail
  }

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


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

	$files_table = '';
	$switch_url = '';
	$goto_url = '';

	if ( 'DR' == $report_type ) {
		// get the dr_no
		$sql = "SELECT dr_no FROM {qms_discrepancy_log} d WHERE discrepancy_id = :did";
		$result = db_query($sql, array(':did' => $report_id));
		$dr_no = $result->fetchField();

		$form['dr_no_display'] = array(
			'#markup' => '<div>' . $dr_no . '</div><hr />',
		);

		// storage field for the discrepancy_id  -- hidden
		$form['discrepancy_id'] = array(
			'#type' => 'textfield',
			'#default_value' => $report_id,
			'#attributes' => array('style' => array('display:none')),
		);

		// storage field for the dr_no  -- hidden
		$form['dr_no'] = array(
			'#type' => 'textfield',
			'#default_value' => $dr_no,
			'#attributes' => array('style' => array('display:none')),
		);

		$files_table = _get_discrepancy_files_table($report_id);

		$switch_url = 'discrepancy/file/add/' . $report_id;
		$goto_url = 'discrepancy/edit/' . $report_id;
	}
	else if ( 'SL' == $report_type ) {
		// get the shift log info
		$sql = "SELECT datetime, employee_user_id FROM {qms_shift_log} s WHERE shift_log_id = :sid";
		$result = db_query($sql, array(':sid' => $report_id));
		$shift_log = $result->fetchObject();

		$sl_title = _st_format_date($shift_log->datetime, 'short') . ' shift log entry by ' .
								_get_user_name($shift_log->employee_user_id);

		$form['sl_display'] = array(
			'#markup' => '<div>' . $sl_title . '</div><hr />',
		);

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

		// storage field for the shift log display  -- hidden
		$form['shift_log_title'] = array(
			'#type' => 'textfield',
			'#default_value' => $sl_title,
			'#attributes' => array('class' => array('qms-hidden-field')),
		);

		$files_table = _get_shift_log_files_table($report_id);

		$switch_url = 'shiftlog/file/add/' . $report_id;
		$goto_url = 'shiftlog/edit/' . $report_id;
	}
  else if ( 'SI' == $report_type) {
    // get the simulator info

    global $simulator_list;
    $sim_name = $simulator_list->getName($report_id);


    $form['sim_name_display'] = array(
      '#markup' => '<div>' . $sim_name . '</div><hr />',
    );

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

    // storage field for the shift log display  -- hidden
    $form['sim_name'] = array(
      '#type' => 'textfield',
      '#default_value' => $sim_name,
      '#attributes' => array('class' => array('qms-hidden-field')),
    );

    $files_table = _get_simulator_files_table($report_id);

		$switch_url = 'simulator/file/add/' . $report_id;
		$goto_url = 'simulator/edit/' . $report_id;
  }



	$form['fs_files'] = array(
		'#type' => 'fieldset',
		'#title' => t('File Attachments'),
		'#collapsible' => False,
	);

	$form['fs_files']['files_begin_div'] = array(
		'#markup' => '<div id="qms-files-div">',
	);


	// Get a table of existing uploaded files for this DR
	if ($report_id > 0) {
		$form['fs_files']['files'] = array(
			'#markup' => $files_table,
		);
	}


	$form['fs_files']['file_input_markup1'] = array(
		'#markup' =>'<table class="qms-file-input-table" style="width:95%"><tr><td class="qms-file-input-col1">',
	);

	$form['fs_files']['file_upload1'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
    '#upload_validators' => array('file_validate_extensions' => array()),
		//'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #1'),
	);

	$form['fs_files']['clear_link1'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file1',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',
	);


	$form['fs_files']['file_upload2'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
    '#upload_validators' => array('file_validate_extensions' => array()),
		//'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #2'),
	);

	$form['fs_files']['clear_link2'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file2',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',
	);


	$form['fs_files']['file_upload3'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
    '#upload_validators' => array('file_validate_extensions' => array()),
		//'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #3'),
	);

	$form['fs_files']['clear_link3'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file3',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',
	);


	$form['fs_files']['file_upload4'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
    '#upload_validators' => array('file_validate_extensions' => array()),
		//'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #4'),
	);

	$form['fs_files']['clear_link4'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file4',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',
	);

	$form['fs_files']['file_upload5'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
    '#upload_validators' => array('file_validate_extensions' => array()),
		//'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #5'),
	);

	$form['fs_files']['clear_link5'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file5',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr></table>',
	);

	$form['fs_files']['switch_forms'] = array(
		'#markup' => '<br />' . l(t('Switch to Batch File Upload Form'), $switch_url,
																				array('attributes' => array('id' => 'qms-btn-switch',
																																		'style' => 'float:right;' ))),
		);

	$form['fs_files']['files_end_div'] = array(
		'#markup' => '</div>',
	);



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

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

  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                                url($goto_url) . '"; return false;'),
	);


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

/*
 * file_upload_orig_form_after_build()
 *
 */
function file_upload_orig_form_after_build($form, &$form_state)
{
	drupal_add_js( drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.files.js');

	return $form;
}


/*
 *	file_upload_orig_form_submit()
 *
 *  implements hook_form_submit()
 */
function file_upload_orig_form_submit($form, $form_state) {

	/*
	 * private file directory handling by....http://www.beacon9.ca/labs/drupal-7-private-files-module
	 * create subdirectory in private file area specific to this discrepancy
	 * all files for this discrepancy will be physically stored in that directory with links
	 * entered in the database
	 */

	$report_type = $form_state['values']['report_type'];
	$cancel = (int)$form_state['values']['cancel_action'];

	$dest_dir = '';
	$report_files_table_name = '';
	$report_id_field_name = '';
	$report_id = '';
	$goto_url = '';

	$error_files = array();
	$added = 0;
	$msg = '';


	if ( 'DR' == $report_type ) {
		$report_id = (int) $form_state['values']['discrepancy_id'];
		$report_files_table_name = 'qms_discrepancy_files';
		$report_id_field_name = 'discrepancy_id';
		$goto_url = 'discrepancy/edit/' . $report_id;

		// the directory name for each set of DR files is the DR No
		$dr_no = $form_state['values']['dr_no'];
		$dest_dir = _get_discrepancy_file_upload_directory($dr_no);

	}
	else if ( 'SL' == $report_type ) {
		$report_id = (int) $form_state['values']['shift_log_id'];
		$report_files_table_name = 'qms_shift_log_files';
		$report_id_field_name = 'shift_log_id';
		if ( user_access('administer sabreQMS') ) {
			$goto_url = 'shiftlog/edit/' . $report_id;
		}
		else {
			$goto_url = 'shiftlog/view/' . $report_id;
		}

		// shift logs do not have unique display report numbers so we key by the table id
		$sl_title = $form_state['values']['shift_log_title'];
		$dest_dir = _get_shift_log_file_upload_directory($report_id);

	}
  else if ( 'SI' == $report_type ) {
    $report_id = (int) $form_state['values']['simulator_id'];
    //$sim_name = $form_state['values']['sim_name'];
		$report_files_table_name = 'qms_simulator_files';
		$report_id_field_name = 'simulator_id';
    $goto_url = 'simulator/edit/' . $report_id;


		// shift logs do not have unique display report numbers so we key by the table id
		$sim_name = $form_state['values']['sim_name'];
		$dest_dir = _get_simulator_file_upload_directory($report_id);
  }

	if ( !$cancel ) {
		// store files here
		$file_id_list = array(
				isset($form_state['values']['file_upload1']) ? $form_state['values']['file_upload1'] : 0,
				isset($form_state['values']['file_upload2']) ? $form_state['values']['file_upload2'] : 0,
				isset($form_state['values']['file_upload3']) ? $form_state['values']['file_upload3'] : 0,
				isset($form_state['values']['file_upload4']) ? $form_state['values']['file_upload4'] : 0,
				isset($form_state['values']['file_upload5']) ? $form_state['values']['file_upload5'] : 0,
		);


		if ( _attach_files_ajax($file_id_list, $dest_dir, $report_files_table_name, $report_id_field_name,
												$report_id, $error_files, $added ) ) {

			if ( $added ) {
				if ( 'DR' == $report_type )		 {
					$num_rows = db_update('qms_discrepancy_log')
								->fields(array('files_attached' => 1))
								->condition('discrepancy_id', $report_id)
								->execute();
					$msg = 'Files for ' . $dr_no . ' have been successfully uploaded.';
				}
				else if ( 'SL' == $report_type ) {
					$num_rows = db_update('qms_shift_log')
								->fields(array('files_attached' => 1))
								->condition('shift_log_id', $report_id)
								->execute();
					$msg = 'Files for the shift log entry have been successfully uploaded.';
				}
        else if ( 'SI' == $report_type ) {
          $num_rows = db_update('qms_simulators')
								->fields(array('files_attached' => 1))
								->condition('simulator_id', $report_id)
								->execute();
					$msg = 'Files for the simulator have been successfully uploaded.';
        }
			}
		}
		else {
			$msg = 'Oops!  An error occurred while attempting to add files.  ';
			$msg .= _list_files('Unable to attach: ', $error_files);
		}
	}


	// SEND EMAIL NOTIFICATIONS
	// Allows latest file attachments to be included in notifications

	if ( 'DR' == $report_type ) {
		_discrepancy_add_update_post_processing($report_id, $added);
	}
	else if ( 'SL' == $report_type ) {  // $report_type == SL
		_send_shift_log_email_notifications($report_id, $added);
	}
  // no notifications for 'SI' == $record_type

	drupal_set_message(t($msg));
	drupal_goto($goto_url);
}


/*
 *		file_upload_plupload_form()
 *
 *		Upload files using the plupload widget
 *	  for Discrepancy and Shift Log Reports
 */

function file_upload_plupload_form($form, $form_state, $report_type, $report_id) {

  if ( ('DR' != $report_type) && ('SL' != $report_type) && ('SI' != $report_type) ) {
    return $form;  // fail
  }

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


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

	$files_table = '';
	$switch_url = '';
	$goto_url = '';

	if ( 'DR' == $report_type ) {
		// get the dr_no
		$sql = "SELECT dr_no FROM {qms_discrepancy_log} d WHERE discrepancy_id = :did";
		$result = db_query($sql, array(':did' => $report_id));
		$dr_no = $result->fetchField();

		$form['dr_no_display'] = array(
			'#markup' => '<div>' . $dr_no . '</div><hr />',
		);

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

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

		$files_table = _get_discrepancy_files_table($report_id);

		$switch_url = 'discrepancy/file/orig/add/' . $report_id;
		$goto_url = 'discrepancy/edit/' . $report_id;

	}
	else if ( 'SL' == $report_type ) {
		// get the shift log info
		$sql = "SELECT datetime, employee_user_id FROM {qms_shift_log} s WHERE shift_log_id = :sid";
		$result = db_query($sql, array(':sid' => $report_id));
		$shift_log = $result->fetchObject();

		$sl_title = _st_format_date($shift_log->datetime, 'short') . ' shift log entry by ' .
								_get_user_name($shift_log->employee_user_id);

		$form['sl_display'] = array(
			'#markup' => '<div>' . $sl_title . '</div><hr />',
		);

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

		// storage field for the shift log display  -- hidden
		$form['shift_log_title'] = array(
			'#type' => 'textfield',
			'#default_value' => $sl_title,
			'#attributes' => array('class' => array('qms-hidden-field')),
		);

		$files_table = _get_shift_log_files_table($report_id);

		$switch_url = 'shiftlog/file/orig/add/' . $report_id;
		$goto_url = 'shiftlog/edit/' . $report_id;
	}
  else if ( 'SI' == $report_type ) {
    // get the simulator info
    global $simulator_list;
    $sim_name = $simulator_list->getName($report_id);


    $form['sim_name_display'] = array(
      '#markup' => '<div>' . $sim_name . '</div><hr />',
    );

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

    // storage field for the shift log display  -- hidden
    $form['sim_name'] = array(
      '#type' => 'textfield',
      '#default_value' => $sim_name,
      '#attributes' => array('class' => array('qms-hidden-field')),
    );

    $files_table = _get_simulator_files_table($report_id);

		$switch_url = 'simulator/file/orig/add/' . $report_id;
		$goto_url = 'simulator/edit/' . $report_id;
  }



	$form['fs_files'] = array(
		'#type' => 'fieldset',
		'#title' => t('File Attachments'),
		'#collapsible' => False,
	);

	$form['fs_files']['files_begin_div'] = array(
		'#markup' => '<div id="qms-files-div">',
	);


	// Get a table of existing uploaded files for this DR
	if ($report_id > 0) {
		$form['fs_files']['files'] = array(
			'#markup' => $files_table,
		);
	}



	// --------------------------- PLUPLOAD ------------------------------

	global $base_url;

	$get_silverlight_url = 'https://www.microsoft.com/getsilverlight';
	$get_flash_url = 'https://get.adobe.com/flashplayer/';
	$get_browserplus_url = 'https://browserplus.yahoo.com/install/';

	// this is the div element that gets converted to the plupload widget in the browser
	$form['fs_files']['plupload_files'] = array(
		'#markup' => '<div id="' . QMS_PLUPLOAD_UPLOADER . '">' .
		'<p>Batch file upload requires that your browser have HTML5, ' .
		l('Silverlight', $get_silverlight_url) . ', ' .
		l('Flash', $get_flash_url) . ' or ' .
		l('BrowserPlus', $get_browserplus_url) . '.<br />' .
		'You may also switch to the ' .
		l('Alternate File Upload Form', $switch_url) . ', which works with any browser.</p>' .
		'</div>',
	);


	$form['fs_files']['switch_forms'] = array(
		'#markup' => '<br />' . l(t('Switch to Alternate File Upload Form'), $switch_url, array('attributes' => array('id' => 'qms-btn-switch', 'style' => 'float:right;' ))),
	);


	//------- PLUPLOAD settings that get pushed to the browser for config purposes -------
	$form['fs_files']['plupload_config'] = array(
		'#type' => 'textarea',
		'#default_value' => QMS_PLUPLOAD_RUNTIMES . '|' .									//runtimes
							file_upload_max_size() . 'b' . '|' .					//filesize
							url('plupload-handle-uploads', ['query' => ['plupload_token' => drupal_get_token('plupload-handle-uploads')],]) . '|' . // upload url - plupload module handler
							$base_url . '/sites/all/libraries/plupload/js/plupload.flash.swf' . '|' .		//flash url
							$base_url . '/sites/all/libraries/plupload/js/plupload.silverlight.xap' . '|' .
							QMS_PLUPLOAD_FILE_EXTENSIONS,
		'#attributes' => ['id' => 'qms-plupload-config',
						  'class' => array('qms-hidden-field'),
						 ],
		'#prefix' => '<div id="qms-plupload-config-div" class="qms-hidden-field">',
		'#suffix' => '</div>',
	);



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

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

  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                                url($goto_url) . '"; return false;'),
	);


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

/*
 * file_upload_plupload_form_after_build()
 *
 */
function file_upload_plupload_form_after_build($form, &$form_state)
{
	drupal_add_js( drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.files.js');

	// --------------------------- PLUPLOAD ------------------------------
	global $base_url;
	//plupload  - file uploads
	drupal_add_css(drupal_get_path('module', 'plupload') . '/plupload.css');
	//drupal_add_js(drupal_get_path('module', 'plupload') . '/plupload.js');
	drupal_add_css( $base_url . '/sites/all/libraries/plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css');
	//drupal_add_js( 'https://bp.yahooapis.com/2.4.21/browserplus-min.js');
	drupal_add_js( $base_url . '/sites/all/libraries/browserplus-2.4.21.min.js');
	//drupal_add_js( 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js');
	drupal_add_js( $base_url . '/sites/all/libraries/plupload/js/plupload.full.js');
	drupal_add_js( $base_url . '/sites/all/libraries/plupload/js/jquery.plupload.queue/jquery.plupload.queue.js');

	return $form;
}


/*
 *	file_upload_plupload_form_submit()
 *
 *  implements hook_form_submit()
 */
function file_upload_plupload_form_submit($form, $form_state) {

	/*
	 * private file directory handling by....//www.beacon9.ca/labs/drupal-7-private-files-module
	 * create subdirectory in private file area specific to this discrepancy
	 * all files for this discrepancy will be physically stored in that directory with links
	 * entered in the database
	 */

	$report_type = $form_state['values']['report_type'];
	$cancel = (int)$form_state['values']['cancel_action'];
	$dest_dir = '';
	$report_files_table_name = '';
	$report_id_field_name = '';
	$report_id = '';
	$goto_url = '';

	$added = 0;
	$msg = '';


	if ( 'DR' == $report_type ) {
		$report_id = (int) $form_state['values']['discrepancy_id'];
		$report_files_table_name = 'qms_discrepancy_files';
		$report_id_field_name = 'discrepancy_id';
		$goto_url = 'discrepancy/edit/' . $report_id;

		// the directory name for each set of DR files is the DR No
		$dr_no = $form_state['values']['dr_no'];
		$dest_dir = _get_discrepancy_file_upload_directory($dr_no);

	}
	else if ( 'SL' == $report_type ) {
		$report_id = (int) $form_state['values']['shift_log_id'];
		$report_files_table_name = 'qms_shift_log_files';
		$report_id_field_name = 'shift_log_id';
		if ( user_access('administer sabreQMS') ) {
			$goto_url = 'shiftlog/edit/' . $report_id;
		}
		else {
			$goto_url = 'shiftlog/view/' . $report_id;
		}


		// shift logs do not have unique display report numbers so we key by the table id
		$sl_title = $form_state['values']['shift_log_title'];
		$dest_dir = _get_shift_log_file_upload_directory($report_id);
	}
  else if ( 'SI' == $report_type ) {
    $report_id = (int) $form_state['values']['simulator_id'];
    //$sim_name = $form_state['values']['sim_name'];
		$report_files_table_name = 'qms_simulator_files';
		$report_id_field_name = 'simulator_id';
    $goto_url = 'simulator/edit/' . $report_id;


		// shift logs do not have unique display report numbers so we key by the table id
		$sim_name = $form_state['values']['sim_name'];
		$dest_dir = _get_simulator_file_upload_directory($report_id);
  }


	if ( !$cancel ) {

		//----------------- Save to DB ------------------------
		$error_files = array();

		if ( isset($_POST[QMS_PLUPLOAD_UPLOADER .'_count']) ) {
			$file_list = array();
			$num_files = (int)$_POST[QMS_PLUPLOAD_UPLOADER . '_count'];

			for ( $i=0; $i<$num_files; $i++) {
				if ( strtoupper($_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_status']) == 'DONE') {
          $file_list[$i] = new stdClass();
					$file_list[$i]->tmpname = $_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_tmpname'];
					$file_list[$i]->name = $_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_name'];
				}
			}

			if ( _attach_files_plupload($file_list, $dest_dir, $report_files_table_name, $report_id_field_name,
													$report_id, $error_files, $added) ) {

				if ( $added ) {
          if ( 'DR' == $report_type )		 {
            $num_rows = db_update('qms_discrepancy_log')
                  ->fields(array('files_attached' => 1))
                  ->condition('discrepancy_id', $report_id)
                  ->execute();
            $msg = 'Files for ' . $dr_no . ' have been successfully uploaded.';
          }
          else if ( 'SL' == $report_type ) {
            $num_rows = db_update('qms_shift_log')
                  ->fields(array('files_attached' => 1))
                  ->condition('shift_log_id', $report_id)
                  ->execute();
            $msg = 'Files for the shift log entry have been successfully uploaded.';
          }
          else if ( 'SI' == $report_type ) {
            $num_rows = db_update('qms_simulators')
                  ->fields(array('files_attached' => 1))
                  ->condition('simulator_id', $report_id)
                  ->execute();
            $msg = 'Files for the simulator have been successfully uploaded.';
          }
        }
			}
			else {
				$msg = 'Oops!  An error occurred while attempting to add files.  ';
				$msg .= _list_files('Unable to attach: ', $error_files);
			}
		}
	}

	// SEND EMAIL NOTIFICATIONS
	// Allows latest file attachments to be included in notifications

	if ( 'DR' == $report_type ) {
		_discrepancy_add_update_post_processing($report_id, $added);
	}
	else if ( 'SL' == $report_type ) {  // $report_type == SL
		_send_shift_log_email_notifications($report_id, $added);
	}
  // no email notifications for simulators

	drupal_set_message(t($msg));
	drupal_goto($goto_url);
}




//-------------------------------------- Storage of Files After Upload -----------------------------------

/**
 *	_attach_files()
 *
 */

function _attach_files($file_list, $upload_dir, $table_name, $table_id, $report_id, &$error_files, &$added) {

	/*
	 * private file directory handling by....http://www.beacon9.ca/labs/drupal-7-private-files-module
	 * create subdirectory in private file area specific to this shift log
	 * all files for this shift log will be physically stored in that directory with links
	 * entered in the database
	 */

	// process the $file_list
	$added = 0;  // initialize files added counter
	$uploaded_files = array();
	$validators = array(
    'file_validate_extensions' => array(),
		//'file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS),
	);

	file_prepare_directory($upload_dir, FILE_CREATE_DIRECTORY);

	foreach ( $file_list as $fl ) {
		$save_result = file_save_upload($fl, $validators, $upload_dir);
		if ( $save_result ) {
			$uploaded_files[] = $save_result;
		}
	}

	// files weren't uploaded, check if anything is in the directory.  If not, delete it
	if ( !count($uploaded_files) ) {
		$scanned_directory = array_diff(scandir($upload_dir), array('..', '.'));

		if ( !count($scanned_directory) ) {
			// nothing left in attached files directory, delete it
			rmdir($upload_dir);
		}
		return True;
	}


	$file_rec = (object) Null;
	$error_files = array(); // clear the list of error files

	$file_rec->$table_id = $report_id;

	global $user;
	$file_rec->user_id = $user->uid;  // currently logged in user
	$file_rec->uploaded_timestamp = time();

	$msg = '';
	foreach( $uploaded_files as $f ) {
		if ( $f ) {
			// if file_name has spaces in it, replace with underscores as unix doesn't like spaces
			// if the newly named URI is a duplicate of an existing URI file name,
			// file_managed_move will rename by adding an incemented suffix to the name until it
			// can save the file as unique, then returns the corrected URI name to $dest_uri
			$num_spaces = 0;
			$dest_uri = '';
			$new_uri = str_replace(' ', '_', $f->uri, $num_spaces);
			if ( $num_spaces ) { // only do a move if spaces found and file name corrected
				$dest_uri = file_unmanaged_move($f->uri, $new_uri);
			}

			if ( $dest_uri ) {
				$new_uri = $dest_uri;
			}
			$file_rec->file_uri = $new_uri;
			$file_rec->file_name = basename($new_uri);

			if ( False == drupal_write_record($table_name, $file_rec)) {
				$error_files[] = $file_rec->file_name;
			}
			else {
				if  ( $file_rec->file_id > 0 ) {
					$added++;
				}
			}

			unset($file_rec->file_uri);
			unset($file_rec->file_name);
			unset($file_rec->file_id);
		}
	}

	// remove any entries in the file_managed table... unnecessary Drupal interference
	//$num_rows = db_delete('file_managed')->execute();

	return (count($error_files) == 0);
}


/**
 *	_delete_all_attached_files($file_uri)
 *
 *	Accepts the $file_uri, deletes all files, then deletes the subdirectory
 */

function _delete_all_attached_files($file_uri) {

	if ( trim($file_uri) == '' )  return;

	// get the parent directory of this file
	$file_path = '';

	$wrapper = file_stream_wrapper_get_instance_by_uri($file_uri);
	if ( !$wrapper ) return;  // error condition

  $file_path = $wrapper->realpath();
	$file_dir = dirname($file_path);

	// delete the directory and everything in it
	return file_unmanaged_delete_recursive($file_dir);
}

/**
 *	_delete_attached_file()
 *
 *	Accepts the file_uri, deletes the file, then deletes the subdirectory if it's empty
 */

function _delete_attached_file($file_uri) {

	if ( trim($file_uri) == '' ) return;

	// the get the file_uri's actual path + delete
	$file_path = '';

	$wrapper = file_stream_wrapper_get_instance_by_uri($file_uri);
	if ( !$wrapper ) return;  // error condition

	$file_path = $wrapper->realpath();
	file_unmanaged_delete($file_path);

	// get the deleted file's directory
	$file_dir = dirname($file_path);
	$scanned_directory = array_diff(scandir($file_dir), array('..', '.'));

	if ( !count($scanned_directory) ) {
		// nothing left in attached files directory, delete it
		rmdir($file_dir);
	}
}

/**
 *	_delete_attached_file()
 *
 *	Accepts the file_uri, deletes the file, then deletes the subdirectory if it's empty
 */

function _cleanup_old_upload_files() {

	try {
		//global $base_path;
		$upload_file_path = variable_get('file_temporary_path', 'sites/default/files/upload' );
		$path = $upload_file_path;

		// remove files that are older than 48hours
		$interval = 60 * 60 + 24 * 2;

		$objects = scandir($path);
		foreach( $objects as $obj ) {

			if ( ($obj != ".") && ($obj != "..") && ($obj != ".htaccess")  &&
           ( is_file($path . "/" . $obj) )) {
				$ftime = filemtime($path . "/" . $obj);
				if( (int)$ftime < (time() - $interval) ) {
					file_unmanaged_delete($path . "/" . $obj);
				}
			}
		}
	}
	catch (Exception $e) {
		//echo 'Exception caught: ' . $e->getMessage() . "\n";
	}
}





/*
 *		_list_files()
 *		Lists a formatted list of filenames with a prefix message
 *	  Useful for error messages after processing a group of files.
 */
function _list_files($prefix_msg, $file_list) {
	$msg = '';
	if ( count($file_list) ) {
		$msg .= $prefix_msg . '<br>';
		foreach($file_list as $filename) {
			$msg .=  $filename . '<br />';
		}
	}
	return $msg;
}


/*
 *	_attach_files_ajax()
 *
 *	Alternative function to _attach_files()
 *	Called when files are uploaded via ajax xhr rather than through drupal and post data on submit
 *  files currently reside in public://uploads directory and need to be moved into the report-related dirs
 */
function _attach_files_ajax($file_id_list, $dest_dir, $table_name, $table_id, $report_id, &$error_files, &$added) {

	// process the $file_list

	$added = 0;  // initialize files added counter
	$error_files = array(); // clear the list of error files

	if ( !file_prepare_directory($dest_dir, FILE_CREATE_DIRECTORY)) {
		return false;
	}

	global $user;
	$file_rec = (object)Null;
	$file_rec->$table_id = $report_id;
	$file_rec->user_id = $user->uid;  // currently logged in user



	$msg = '';
	foreach( $file_id_list as $fid ) {

		if ( $fid > 0 ) {
			// load the file info from the temporary directory
			$temp_file = file_load($fid);

			// if file_name has spaces in it, replace with underscores as unix doesn't like spaces
			// if the newly named URI is a duplicate of an existing URI file name,
			// file_managed_move will rename by adding an incemented suffix to the name until it
			// can save the file as unique, then returns the corrected URI name to $dest_uri
			$num_spaces = 0;
			$new_filename = str_replace(' ', '_', $temp_file->filename, $num_spaces);
			$new_uri = $dest_dir . '/' . $new_filename;

			$dest_uri = file_unmanaged_move($temp_file->uri, $new_uri);

			// if uri is altered due to conflicting filenames, the renamed file uri will be ret'd in $dest_uri
			if ( $dest_uri ) {
				$new_uri = $dest_uri;
			}

			$file_rec->file_uri = $new_uri;
			$file_rec->file_name = basename($new_uri);
			$file_rec->uploaded_timestamp = $temp_file->timestamp;

			if ( False == drupal_write_record($table_name, $file_rec)) {
				$error_files[] = $file_rec->file_name;
			}
			else {
				if  ( $file_rec->file_id > 0 ) {
					$added++;
				}
			}

			unset($file_rec->file_uri);
			unset($file_rec->file_name);
			unset($file_rec->file_id);

			// remove the corresponding file from the file_managed table after its been logged to the files tbl
			// for each report
			$num_rows = db_delete('file_managed')
									->condition('fid', $fid)
									->execute();
		}
	}

	// files weren't uploaded, check if anything is in the directory.  If not, delete it
	if ( !$added ) {
		$scanned_directory = array_diff(scandir($dest_dir), array('..', '.'));

		if ( !count($scanned_directory) ) {
			// nothing left in attached files directory, delete it
			rmdir($dest_dir);
		}
		return True;
	}


	return (count($error_files) == 0);
}


/*
 *	_attach_files_plupload()
 *
 *	Alternative function to _attach_files()
 *	Called when files are uploaded via plupload module rather than through drupal and post data on submit
 *  files currently reside in public://uploads directory and need to be moved into the report-related dirs
 */
function _attach_files_plupload($file_list, $dest_dir, $table_name, $table_id, $report_id, &$error_files, &$added) {

	// process the $file_list
	if ( !count($file_list) ) {
		// no files to attach and thats... OK
		return True;
	}

	$added = 0;  // initialize files added counter
	$error_files = array(); // clear the list of error files

	if ( !file_prepare_directory($dest_dir, FILE_CREATE_DIRECTORY)) {
		return false;
	}

	global $user;
	$file_rec = (object)Null;
	$file_rec->$table_id = $report_id;
	$file_rec->user_id = $user->uid;  // currently logged in user

	$temp_dir = 'temporary://';
	$timestamp = time();


	$msg = '';
	foreach( $file_list as $temp_file ) {

		// if file_name has spaces in it, replace with underscores as unix doesn't like spaces
		// if the newly named URI is a duplicate of an existing URI file name,
		// file_managed_move will rename by adding an incemented suffix to the name until it
		// can save the file as unique, then returns the corrected URI name to $dest_uri
		$num_spaces = 0;
		$new_filename = str_replace(' ', '_', $temp_file->name, $num_spaces);
		$new_uri = $dest_dir . '/' . $new_filename;

		//tmpname has the file's original extension, but saves the file with .tmp
		// if we don't change it here, the file will not be found
		$temp_file_name = $temp_dir . preg_replace("/\\.[^.\\s]{3,4}$/", "", $temp_file->tmpname) . '.tmp';

		//$temp_file_name = $temp_dir . $temp_file->tmpname;

		$dest_uri = file_unmanaged_move($temp_file_name, $new_uri);

		// if uri is altered due to conflicting filenames, the renamed file uri will be ret'd in $dest_uri
		if ( $dest_uri ) {
			$new_uri = $dest_uri;
		}

		$file_rec->file_uri = $new_uri;
		$file_rec->file_name = basename($new_uri);
		$file_rec->uploaded_timestamp = $timestamp;

		if ( False == drupal_write_record($table_name, $file_rec)) {
			$error_files[] = $file_rec->file_name;
		}
		else {
			if  ( $file_rec->file_id > 0 ) {
				$added++;
			}
		}

		unset($file_rec->file_uri);
		unset($file_rec->file_name);
		unset($file_rec->file_id);

	}


	// files weren't uploaded, check if anything is in the directory.  If not, delete it
	if ( !$added ) {
		$scanned_directory = array_diff(scandir($dest_dir), array('..', '.'));

		if ( !count($scanned_directory) ) {
			// nothing left in attached files directory, delete it
			rmdir($dest_dir);
		}
		return True;
	}

	// run a quick check of the upload directory and remove any orphaned files after 48 hrs
	// files that were successfully uploaded are moved to their correct destination directories so
	// there is no permanent storage in the uploads dir
	_cleanup_old_upload_files();

	return (count($error_files) == 0);
}


/*  XXXXXXXXXX   THIS IS NOT BEING USED XXXXXXXXXXXXX
 *  Problem with reloading file list queue, doesn't work with PLUPLOAD
 *  We now handle file uploads after the report has been submitted and validated
 *
 *	_get_uploaded_file_references()
 *
 *	Retrieves the list of files uploaded and reloads it into the plupload file queue
 *  in the event validation fails
 *  Used by Discrepancies and Shift Logs
 */

function _get_uploaded_file_references(&$form, &$form_state) {

	$num_files = (isset($_POST[ QMS_PLUPLOAD_UPLOADER . '_count'])) ? (int)$_POST[QMS_PLUPLOAD_UPLOADER . '_count'] : 0;
	$base_file_path = variable_get('file_temporary_path', 'sites/default/files/upload' ) . '/';

	$files = array();

	// get the file reference values from post
	if ( $num_files ) {


		for ( $i=0; $i<$num_files; $i++) {
			// only save references to files that have been uploaded successfully ('done')
			if ( strtoupper($_POST[ QMS_PLUPLOAD_UPLOADER .'_' . $i . '_status']) == 'DONE') {

				//tmpname has the file's original extension, but saves the file with .tmp
				// if we don't change it here, the file will not be found
				$orig_file_name = $_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_tmpname'];
				$temp_file_name = preg_replace("/\\.[^.\\s]{3,4}$/", "", $orig_file_name)	 . '.tmp';

				$file_path = $base_file_path . $temp_file_name;
				$size = filesize($file_path);

				$files[$i]= $orig_file_name . ',' .
										$_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_name'] . ',' .
										$size;

				/*
				$files[$i]->id = $_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_tmpname'];
				$files[$i]->loaded = 100;
				$files[$i]->name = $_POST[QMS_PLUPLOAD_UPLOADER .'_' . $i . '_name'];
				$files[$i]->percent = 100;
				$files[$i]->size = $size;
				$files[$i]->status = "DONE";
				*/
			}
		}

		$file_references = implode("|", $files);

		//$form['files_uploaded']['#parents'] = array('files_uploaded');
		//form_set_value($form['files_uploaded'], array(LANGUAGE_NONE => array(0 =>
										//array('value' => $file_references))), $form_state);
		//form_set_value($form['files_uploaded'], $file_references, $form_state);

		$form['files_uploaded']['#value'] = $file_references;
		$form_state['values']['files_uploaded'] = $file_references;

	}
	/*
	else {
		// test data
		$files[0]->id = 'p17743gpaernqf7q1a5nju2lo41.tmp';
		$files[0]->loaded = 100;
		$files[0]->name = 'myfile.pdf';
		$files[0]->percent = 100;
		$files[0]->size = 156651;
		$files[0]->status = "DONE";
	}
	*/
	return $files;

}


