<?php
/**
 *		
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Schedule function handling
 *    
*/

require_once('sabreScheduler.simulators.inc');
require_once('sabreScheduler.patterns.inc');

/*
 *	schedules_display()
 *
 */

function schedules_display($called_by_pager = False) {
  
  try {

    if ( user_access('view manage menu') == False ) {
      drupal_set_message( t('Unauthorized Access.  Permission is required.'));
      drupal_goto('');
      return;	
    }		
    
    $bEdit = user_access('edit settings');

    if ( ! $called_by_pager ) {
      drupal_add_library('system','ui.dialog');
    }

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

    $page = 0;
    if ( isset($_GET['page']) ) {
      $page = (int)$_GET['page'];
    }


    $table_header = array( 
      array( 'data' => t('Schedule'), 
             'field' => 'schedule_name', 
             'sort' => 'asc' ),
      array( 'data' => t('Simulator'), 
             'field' => 'sim_name', 'sort' => 'asc', 
             'class' => array('sch-schedule-tbl-simulator')),      
    );
    if ( $bEdit ) {
      $table_header[] = array( 'data' => t('Admin'), 'class' => array('sch-schedules-tbl-admin') );
    }


    // Need to use the DB abstration layer here for the paging features
    $query = db_select('sch_schedules', 'sch');

    $query->innerJoin('sch_simulators', 'sim', 'sim.simulator_id = sch.simulator_id');

    $query->extend('PagerDefault')
          ->limit(QMS_RECORDS_PER_PAGE)
          ->extend('TableSort')
          ->orderByHeader($table_header);	

    $q2 = $query->fields('sch', array( 'schedule_id', 'simulator_id', 'schedule_name') )
                ->fields('sim', array( 'sim_name', 'device_id_internal') );

    $max_count = $q2->countQuery()->execute()->fetchField();

    pager_default_initialize($max_count, QMS_RECORDS_PER_PAGE);
    $offset = QMS_RECORDS_PER_PAGE * $page;
    $result = $query->range($offset, QMS_RECORDS_PER_PAGE)->execute();

    $i = 0;
    $table_rows = array();

    foreach ($result as $row) {

      $id = $row->schedule_id;
      $sim_id = $row->simulator_id;
      $sch_id = $row->schedule_id;
      $sim_name = _st_format_sim_name($row->sim_name, $row->device_id_internal);

      $row_data = array(
        l($row->schedule_name, "schedule/grid/$sim_id/$sch_id/0", 
          array('attributes' => array('class' => array('sch-link-assign')),
                'query' => array('destination' => 'schedules'),
        )),
        l($sim_name, 'simulator/view/' . $sim_id, 
          array('query' => array('destination' => 'schedules'))), 
        
      );
      if ( $bEdit ) {
        $row_data[] = 
          array('data' => 
              //l( t('Grid'), "schedule/grid/" . $sim_id, 
              //array('attributes' => array('class' => array('sch-link-grid')) )) . 
              l( t('Edit'), "schedule/edit/" . $id, 
                 array('attributes' => array('class' => array('sch-link-edit')) )) . 
              l( t('Delete'), "schedule/delete/" . $id, 
                 array('attributes' => array('class' => array('sch-link-delete')) )) 
              );
      }

      $table_rows[] = array('data' => $row_data);
      $i++;
    }

    $content = '';
    
    if ( $bEdit ) {
      $content .=  l( t('Add Schedule'), 'schedule/add', array('class' => array('qms-schedule-add')) ) . 
              '<div id="qms-schedules-div">';
    }

    $content .= theme( 'table', array(
      'header' => $table_header,
      'rows' => $table_rows,
      'empty' => t('None'),
    ));

    $content .= _st_add_theme_pager();
    $content .= '</div>';

    if ( $called_by_pager ) {
      die($content);
    }
    $content .= '<div id="qms-message-box" class="qms-hidden"></div>';  // storage area for dynamic dialog element
    return $content;
  }
  catch(Exception $e) {
    watchdog(SCH_SCHEDULER, 'schedules_display() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}

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

function schedule_form($form, $form_state, $schedule_id = 0) {

	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Permission is required.'));
		drupal_goto('schedules');
		return;
  }

	drupal_add_js('(function($) {
										Drupal.behaviors.schScheduleForm = {
											attach: function(context, settings) {
												$("#sch-schedule_name", context).focus(); 
												$("#sch-pattern-opt tr td:first-child", context).addClass("sch-pattern-select");
											}
										}
									}(jQuery));', 'inline');
	

	$schedule = (object) Null;

	if ( $schedule_id ) {   // Get the existing record
		
		$schedule = _get_schedule($schedule_id);
		if ( $schedule == (object) Null ) {
			drupal_set_message( t('Oops!  Something seems to have gone wrong.  Schedule not found.'));
			drupal_goto('schedules');
			return;
		}
		
		$form['timestamp'] = array(
			'#markup' => _st_format_record_timestamp_table($schedule),
		);
	}
	
	// add any required javascript or css files
	//$form['#after_build'][] = 'schedule_form_after_build';
  	
	$form['schedule_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Schedule Name'),
		'#maxlength' => 100,
		'#default_value' => ($schedule_id ? $schedule->schedule_name : ''),
		'#required' => True,
		'#attributes' => array('id' => 'sch-schedule_name'),
	);	
	
	$simulator_list = new SimulatorList();
	
	$form['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Simulator'),
		'#options' => $simulator_list->getActive(),  // active only
		'#default_value' => (($schedule_id > 0) ? $schedule->simulator_id : 0) ,
		'#required' => True,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'sch-simulator-select'),
	);
	
	/*
	$form['begin_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('Begin Date'),
		'#size' => 11,
		'#date_format' => 'm-d-Y',						// displayed format
			//default value has to be in this format
		'#default_value' => (($schedule_id > 0) ? _st_format_system_date($schedule->begin_date, 'custom', 'Y-m-d') : _st_format_system_date(_st_format_system_timestamp('now'), 'custom', 'Y-m-d')), 
		'#required' => True,   // if no date entered, returns NULL
		'#attributes' => array('class' => array('qms-date-picker')),
	);
	
	$form['end_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('End Date'),
		'#size' => 11,
		'#date_format' => 'm-d-Y',						// displayed format
			//default value has to be in this format
		'#default_value' => (($schedule_id && $schedule->end_date) ? _st_format_system_date($schedule->end_date, 'custom', 'Y-m-d') : ''), 
		'#required' => False,   // if no date entered, returns NULL
		'#attributes' => array('class' => array('qms-date-picker')),
	);
   * 
   */

  $month_list = new MonthList();
  $year_list = new YearList();
  
  $dt = new DateTime();
  $tz = (!empty($schedule->schedule_id) ? $schedule->timezone : _st_get_timezone(False));
  $dt->setTimezone(new DateTimeZone($tz));
  if (!empty($schedule->begin_date)) {
    $dt->setTimestamp($schedule->begin_date);
  }
  
  $form['date_range']['form_table_begin'] = array(
		'#markup' => '<div id="sch-schedules-date-range" style="border:1px solid #CCCCCC; padding: 0 18px;">' .
								 '<table class="qms-plain-table" style="vertical-align:bottom;width:95%;height:5em;"><tr>',
	);

  $form['date_range']['begin_month'] = array(
		'#type' => 'select',
		'#title' => t('Schedule Begins').'<br>'.t('Month'),
		'#options' => $month_list->get(),
		'#default_value' => $dt->format('F'),
		'#required' => True,
		'#attributes' => array('id' => 'sch-begin-month-select'),
		'#prefix' => '<td style="vertical-align:bottom;width:10em;">',
		'#suffix' => '</td>',
	);
	$form['date_range']['begin_year'] = array(
		'#type' => 'select',
		'#title' => t('Year'),
		'#options' => $year_list->get(),
		'#default_value' => (int)$dt->format('Y'),
		'#required' => True,
		'#attributes' => array('id' => 'sch-begin-year-select'),
		'#prefix' => '<td style="vertical-align:bottom;width:10em;">',
		'#suffix' => '</td>',
	);
  
//  $form['date_range']['table_row'] = array(
//		'#markup' => '</tr><tr>',
//	);
  
  $end_month = 0;
  $end_year = 0;
  if (!empty($schedule->end_date)) {
    $dt->setTimestamp($schedule->end_date);
    $end_month = $dt->format('F');
    $end_year = $dt->format('Y');
  }
  
  
  $form['date_range']['end_month'] = array(
		'#type' => 'select',
		'#title' => t('Schedule Ends').'<br>'.t('Month'),
		'#options' => $month_list->get(),
		'#default_value' => $end_month,
		'#required' => False,
		'#attributes' => array('id' => 'sch-end-month-select'),
		'#prefix' => '<td style="vertical-align:bottom;width:10em;">',
		'#suffix' => '</td>',
	);
	$form['date_range']['end_year'] = array(
		'#type' => 'select',
		'#title' => t('Year'),
		'#options' => $year_list->get(),
		'#default_value' => (int)$end_year,
		'#required' => False,
		'#attributes' => array('id' => 'sch-end-year-select'),
		'#prefix' => '<td style="vertical-align:bottom;width:10em;">',
		'#suffix' => '</td>',
	);
  
  $form['date_range']['form_table_end'] = array(
		'#markup' => '</tr></table></div>',
	);
  
  // Date settings:
  if (empty($schedule->schedule_id)) {
    $zones = system_time_zones();
    $form['timezone'] = array(
      '#type' => 'select',
      '#title' => t('Schedule Time Zone'),
      //'#default_value' => variable_get('date_default_timezone', date_default_timezone_get()),
      '#default_value' => (!empty($schedule->schedule_id) ? $schedule->timezone : _st_get_timezone(False)),
      '#options' => $zones,
      '#required' => False,
    );
  } else {
    $form['timezone'] = array(
      '#type' => 'textfield',
      '#title' => t('Schedule Time Zone'),
      //'#default_value' => variable_get('date_default_timezone', date_default_timezone_get()),
      '#default_value' => $schedule->timezone,
      '#attributes' => array('readonly' => 'readonly'),
    );
  }
	
	
	$form['schedule_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $schedule_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	
	
			
	if ( $schedule_id ) {   // Edit existing record
		
		// ------------------- GET SESSIONS ---------------------
		
		$form['sessions_section'] = array(
			'#markup' => '<hr /><h3>' . t('Schedule Sessions') . '</h3>',
		);
		
		$sessions = _get_sessions($schedule_id);
		
		// there are users linked... add them to a table
		$table_header = array(
			array('data' => t('Session Name')),
			array('data' => t('Begin Time')),
			array('data' => t('End Time')),
		);
		$table_rows = array();
		$sess_table = '';
		
		foreach( $sessions as $row) {
			$row_data = array(
				$row->session_name,
				$row->begin_time,
				$row->end_time,
			);
			
			$table_rows[] = array( 'data' => $row_data );		
		}
		
		$sess_table = '<div id="sch-sessions-div">';
		$sess_table .= theme( 'table', array(
			'header' => $table_header,
			'rows' => $table_rows,
			'empty' => t('None'),
		));
				
		$sess_table .= '</div>';
		
		$form['sessions'] = array(
			'#markup' => $sess_table,
		);
	}
	else {
		$form['sessions_section'] = array(
			'#markup' => '<hr /><h3>' . t('Schedule Sessions') . '</h3><p>' . t('Select the session pattern to use with this schedule.') . '</p>',
		);
		
		// new schedule, get the list of available patterns to display as options
		$content = _get_session_patterns_table('tableselect');
		
		$values = element_children($content['#options']);
		
		$form['pattern_opt'] = array(
			'#type' => 'tableselect',
			'#header' => $content['#header'],
			'#options' =>  $content['#options'],
			'#multiple' => False,
			'#empty' => t('None'),
			'#sticky' => False,
			'#js_select' => False,
			'#default_value' => $values[0],  //default to the first option so that something is selected
			'#attributes' => array('id' => 'sch-pattern-opt'),
		);
	}
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url('schedules') . '"; return false;'),
	);
	

	return $form;
}

/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it. 
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/* 
 * schedule_form_after_build()
 *
 */
function schedule_form_after_build($form, &$form_state)
{
	//drupal_add_library('system','ui.datepicker');
	//drupal_add_library('system','ui.dialog');
	
	/*
	if ( (int)$form['discrepancy_id']['#default_value'] == 0) {
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.discrepancyadd.js');
	}
	else {
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.discrepancyedit.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));
	}
	*/
		
	return $form;
}


/*
 *	schedule_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates schedule_form after it is submitted
 */

function schedule_form_validate($form, $form_state) {
	
	if ( trim($form_state['values']['schedule_name']) == '' ) {
		form_set_error('schedule_name', t('Schedule Name is a required field'));
	}
	
	$simulator_id = (int)$form_state['values']['simulator'];
	if ( !$simulator_id ) {
		form_set_error('simulator', t('Simulator is a required field'));
	}
	$schedule_id = (int)$form_state['values']['schedule_id'];
	$pattern_id = (isset($form_state['values']['pattern_opt']) ? (int)$form_state['values']['pattern_opt'] : 0);
	
	//form_set_error('schedule_name', t('Code Break'));
	
	
	//----------------- date checking ---------------------
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	$begin_date = '';
	$ibegin_date = 0;
  $end_date = '';
  $iend_date = 0;
  $tz = _st_get_timezone(False);
  

  $begin_date =  date_parse($form_state['values']['begin_month'] . ' 01, ' . $form_state['values']['begin_year']);

  $dt = new DateTime();
  $dt->setTimezone(new DateTimeZone($tz));
  $dt->setDate($begin_date['year'], $begin_date['month'], $begin_date['day']);
  $dt->setTime(0, 0, 0);
  $ibegin_date = $dt->getTimestamp();
  
  
  if ((empty($form_state['values']['end_month']) && !empty($form_state['values']['end_year'])) ||
      (!empty($form_state['values']['end_month']) && empty($form_state['values']['end_year'])) ) {
    if ( empty($form_state['values']['end_month'])) {
      form_set_error('end_month', t('When setting schedule expiration, Schedule Ends-Month is a required field'));
    } 
    if (empty($form_state['values']['end_year'])) {
      form_set_error('end_year', t('When setting schedule expiration, Schedule Ends-Year is a required field'));
    } 
      
  } else if ( !empty($form_state['values']['end_month']) && !empty($form_state['values']['end_year'])) {
    
    $end_date =  date_parse($form_state['values']['end_month'] . ' 01, ' . $form_state['values']['end_year']);
    
    $dt = new DateTime();
    $dt->setTimezone(new DateTimeZone($tz));
    $dt->setDate($end_date['year'], $end_date['month'], $end_date['day']);
    $dt->modify('last day of this month');
    $dt->setTime(23, 59, 59);
    $iend_date = $dt->getTimestamp();
  }
  
	
	if ( $iend_date > 0 )  {
		if ( $ibegin_date && $iend_date && ($iend_date < $ibegin_date)) {
			form_set_error('end_month', t('End of Schedule cannot be set to a date earlier than beginning of schedule.'));
		}
	}	
	
	// overlap with another schedule for this simulator
  if ( _schedule_overlaps($schedule_id, $simulator_id, $ibegin_date, $iend_date)) {
    form_set_error('begin_month', t('Schedule settings conflict with another schedule for this simulator.  You must set an end date for the conflicting schedule and start the new schedule after that date.'));
  }
  
	// check if assignments are scheduled after end date
  $last_assignment_end_date = 0;
  if ( _schedule_assignments_after_end_date($schedule_id, $iend_date, $last_assignment_end_date)) {
    $end_of_month = _st_format_schedule_date($last_assignment_end_date, 'Y-m-d', $tz, 'last day of this month');
    
    form_set_error('end_date', t('Schedule has assignments/bookings after the end_date.  Unable to end this schedule until ') . $end_of_month);
  }
  
	// only allow schedules to end at the end of the month
  
  
}


/*
 *	schedule_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves schedule_form data upon successful submit
 */

function schedule_form_submit($form, $form_state) {
	
	$schedule = new stdClass();
	global $user;
  
  $ibegin_date = 0;
  $iend_date = 0;
	
	$schedule_id = (int)$form_state['values']['schedule_id'];
	$schedule->schedule_name = $form_state['values']['schedule_name'];
	$schedule->simulator_id = (int)$form_state['values']['simulator'];
  $schedule->timezone = $form_state['values']['timezone'];
	
	$pattern_id = (isset($form_state['values']['pattern_opt']) ? (int)$form_state['values']['pattern_opt'] : 0);
	
  $dt = new DateTime();
  $dt->setTimezone(new DateTimeZone($schedule->timezone));
  $date =  date_parse($form_state['values']['begin_month'] . ' 01, ' . $form_state['values']['begin_year']);
  $dt->setDate($date['year'], $date['month'], $date['day']);
  $dt->setTime(0, 0, 0);
  $ibegin_date = $dt->getTimestamp();
  
  if ( !empty($form_state['values']['end_month']) && !empty($form_state['values']['end_year'])) {
    
    $date =  date_parse($form_state['values']['end_month'] . ' 01, ' . $form_state['values']['end_year']);
  
    $dt->setDate($date['year'], $date['month'], $date['day']);
    $dt->modify('last day of this month');
    $dt->setTime(23, 59, 59);
    $iend_date = $dt->getTimestamp();
  }
  
  $schedule->begin_date = $ibegin_date;
	$schedule->end_date = $iend_date;
	
	
	if ( !$schedule_id ) {
		$schedule->created_date = REQUEST_TIME;
		$schedule->created_by_user = $user->uid;
		
		// new record
		if ( False == drupal_write_record('sch_schedules', $schedule)) {
			$msg = "Oops!  Something went wrong saving the schedule.";
			drupal_set_message(t($msg));
			drupal_goto('schedules');
			return False;
		}
		
		// copy the pattern session settings to create the new schedule
		if ( $pattern_id ) {
			// new schedule, copy the selected pattern's sessions
			if ( False == _copy_pattern_sessions($schedule->schedule_id, $pattern_id)) {
				$msg = "Oops!  Something went wrong saving the schedule sessions.";
				drupal_set_message(t($msg));
				drupal_goto('schedules');
				return False;				
			}
		}
	}
	else {
		$schedule->schedule_id = $schedule_id;
		$schedule->updated_date = REQUEST_TIME;
		$schedule->updated_by_user = $user->uid;
		
		// update existing
		if ( False == drupal_write_record('sch_schedules', $schedule, 'schedule_id')) {
			$msg = "Oops!  Something went wrong updating the schedule.";
			drupal_set_message(t($msg));
			drupal_goto('schedules');
			return False;
		}
	}
	

	drupal_set_message('"' . $schedule->schedule_name . '" ' . t('successfully saved.'));
	drupal_goto('schedules');
	return True;
}

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

function schedule_delete_confirm($form, $form_state, $schedule_id = 0) {
	
	try {
		
		if ( user_access('view manage menu') == FALSE ) {
	    drupal_set_message( t('Unauthorized Access.  Permission is required.'));
			drupal_goto('');
			return $form;	
	  }

		$schedule_name = _get_schedule_name($schedule_id);
		if ( $schedule_name == '' ) {
			drupal_set_message( t('Oops!  Something seems to have gone wrong.  Schedule not found.'));
			drupal_goto('schedules');
			return $form;	
		}
		
		// is this record eligible for deletion?
		
		$sql = "SELECT assignment_id 
						FROM {sch_assignments} a, {sch_schedule_sessions} sp 
						WHERE a.schedule_session_id = sp.schedule_session_id 
						AND   sp.schedule_id = :sid 
						LIMIT 1";
		$result = db_query($sql, array(':sid' => $schedule_id));
		if ( $result->rowCount() ) {
			// cannot delete, customer linked to user account records
			$msg = "Unable to delete " . $schedule_name .  ".  Schedule has assignments.  ";
			drupal_set_message(t($msg));	
			drupal_goto('schedules');
			return $form;	
		}
		
	
		$form['schedule_id'] = array(
			'#type' => 'value',
			'#value' => $schedule_id,
		);
	
		$form['schedule_name'] = array(
			'#type' => 'value',
			'#value' => $schedule_name,
		);
    
    $title = t('Delete Schedule') . '?';
    $question = t('Are you sure you want to delete?') . 
                '<h2>' . $schedule_name . '</h2><br />' . 
                t('This action cannot be undone.');
    $goto_if_canceled = 'schedules';
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);	
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'schedule_delete_confirm() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

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

function schedule_delete_confirm_submit($form, $form_state) {
	
	try {
		if ( $form_state['values']['confirm']) {
			$schedule_id = $form_state['values']['schedule_id'];
			$schedule_name = $form_state['values']['schedule_name'];
      
      // delete from database
			$num_rows = db_delete('sch_schedule_sessions')
									->condition('schedule_id', $schedule_id, '=')
									->execute();

			// delete from database
			$num_rows = db_delete('sch_schedules')
									->condition('schedule_id', $schedule_id, '=')
									->execute();

			$msg = '';					
			if ( $num_rows == 1 ) {
				// success
				$msg = 'Schedule ' . $schedule_name . ' has been deleted.';
			}
			else {
				$msg = 'Oops!  Unable to delete schedule' . $schedule_name . '.';
			}
			drupal_set_message(t($msg));	
		}

		drupal_goto('schedules');
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'schedule_delete_confirm_submit() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_get_schedules($schedule_id)  
 *
 *	get the schedule record by id
 */
function _get_schedules() 
{
	try {
		
		$schedules = array();

		$sql = "SELECT sch.schedule_id, sch.schedule_name, sch.simulator_id, 
            s.sim_name, s.device_id_internal 
						FROM {sch_schedules} sch, {sch_simulators} s 
						WHERE sch.simulator_id = s.simulator_id 
						ORDER BY sch.schedule_name";
		$results = db_query($sql);

		if ( $results->rowCount() ) {
		  $schedules = $results->fetchAll();
		}
		
		return $schedules;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_schedule() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}



/*
 *	_get_schedule($schedule_id)  
 *
 *	get the schedule record by id
 */
function _get_schedule($schedule_id = 0, $simulator_id = 0) 
{
	try {
		
		$schedule = (object) Null;
    
    
		if ( $schedule_id || $simulator_id ) {
      
      
      $query = db_select('sch_schedules', 's');
      
      if ( $schedule_id ) { 
        $query->condition('schedule_id', $schedule_id, '=');
      }
      if ( $simulator_id ) { 
        $query->condition('simulator_id', $simulator_id, '=');
      }
      $query->fields('s', array('schedule_id', 'schedule_name', 'simulator_id', 
                                'begin_date', 'end_date', 'timezone',
                                'created_date', 'created_by_user', 
                                'updated_date', 'updated_by_user' ));
          
			$results = $query->execute();

			if ( $results->rowCount() ) {
			  $schedule = $results->fetchObject();
        _set_schedule_timezone($schedule->timezone);
			}
		}
		return $schedule;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_schedule() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

/*
 *	_get_schedule_name($schedule_id)  
 *
 *	get the schedule name by schedule_id
 */
function _get_schedule_name($schedule_id) 
{
	try {
		
		$schedule_name = '';
		
		if ( $schedule_id > 0 ) {
			$sql = "SELECT schedule_name FROM {sch_schedules} s WHERE schedule_id = :id";
			$schedule_name = db_query($sql, array(':id' => $schedule_id))->fetchField();
		}
		return $schedule_name;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_schedule_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

/*
 *	_schedule_overlaps()  
 *
 *	returns True:  found an overlapping schedule
 *  returns False:  No overlaps found
 */

function _schedule_overlaps($schedule_id, $simulator_id, $ibegin_date, $iend_date) {
	
	try {
		$query = db_select('sch_schedules', 'sch');
    
    $query->where("(begin_date <= :bd AND :bd <= end_date) OR 
                   (:bd <= begin_date AND begin_date <= :ed) OR 
                   (begin_date <= :ed AND end_date = 0)", 
                  array(':bd' => $ibegin_date, ':ed' => $iend_date));
    
		/*
		$and_1 = db_and()->condition('begin_date', $ibegin_date, '>=')->condition('begin_date', $iend_date, '<=');
		$and_2 = db_and()->condition('end_date', $ibegin_date, '>=')->condition('end_date', $iend_date, '<=')->condition('end_date', 0, '>');
		$and_3 = db_and()->condition('begin_date', $iend_date, '<=')->condition('end_date', 0, '=');
		$and_4 = db_and()->condition('begin_date', $ibegin_date, '<=')->condition('end_date', 0, '=');
		$and_5 = db_and()->condition('end_date', 0, '=')->condition($iend_date, 0, '=');
		$or = db_or()->condition($and_1)->condition($and_2)->condition($and_3)->condition($and_4)->condition($and_5
     * );
     */
		//$query->condition($or);
		$query->condition('simulator_id', $simulator_id, '=')
					->condition('schedule_id', $schedule_id, '<>');
		$query->fields('sch', array('schedule_id'))
					->range(0, 1);
		$results = $query->execute();
		
		if ( $results->rowCount() ) {
			return True;
		}
		return False;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_schedule_overlaps() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}

/*
 * 
 */
function _schedule_assignments_after_end_date($schedule_id, $iend_date, &$last_assignment_end_date) {
	
	try {
		$query = db_select('sch_assignments', 'a');
    $query->condition('a.begin_timestamp', $iend_date, '>');
		$query->condition('a.schedule_id', $schedule_id, '=');
		$query->fields('a', array('end_timestamp'));
    $query->orderBy('a.end_timestamp', 'DESC');
		$query->range(0, 1);
		$results = $query->execute();
		
		if ( $results->rowCount() ) {
      $last_assignment_end_date = $results->fetchField();
			return True;
		}
		return False;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_schedule_assignments_after_end_date() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}




/*
 *	_copy_pattern_sessions()
 *
 *	copy the pattern sessions for the new schedule
 */
function _copy_pattern_sessions($schedule_id, $pattern_id) {
	try {
		if ( $schedule_id && $pattern_id) {
			// get the schedule_sessions for this simulator schedule
			
			$sessions = array();
			
			// omit copying sessions from the begin_time and end-time are '0000'
			
			$query = db_select('sch_pattern_sessions', 'ps')
							 ->condition('schedule_pattern_id', $pattern_id)
							 ->condition('begin_time', '0000', '<>')
							 ->condition('end_time', '0000', '<>');
			$query->fields('ps', array('session_name_id', 'begin_time', 'end_time'));
			$query->orderBy('begin_time', 'ASC');
			
			$results = $query->execute();
			if ( $results->rowCount() ) {
				$sessions = $results->fetchAll();
			}
						
			$iquery = db_insert('sch_schedule_sessions')
						->fields(array('schedule_id', 'session_name_id', 'begin_time', 'end_time'));
			foreach ($sessions as $s) {
				$record = array();
				// if begin_time == end_time, ignore it
				if ($s->begin_time <> $s->end_time)  {
					$record = array(
						'schedule_id' => $schedule_id,
						'session_name_id' => $s->session_name_id,
						'begin_time' => $s->begin_time,
						'end_time' => $s->end_time,
					);
					$iquery->values($record);
				}
			}
			$iquery->execute();
			
			return True;
		}
		else {
			return False;
		}
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_copy_pattern_sessions() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 

}







