function eventorganiser_events_where($where, $query)
{
    global $wpdb;
    //Only alter event queries
    if (isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'event') {
        //Ensure all date queries are yyyy-mm-dd format. Process relative strings ('today','tomorrow','+1 week')
        $dates = array('ondate', 'event_start_after', 'event_start_before', 'event_end_after', 'event_end_before');
        foreach ($dates as $prop) {
            if (!empty($query->query_vars[$prop])) {
                $date = $query->query_vars[$prop];
                $dateString = eo_format_date($date, 'Y-m-d');
                $query->set($prop, $dateString);
            }
        }
        //If we only want events (or occurrences of events) that belong to a particular 'event'
        if (isset($query->query_vars['event_series'])) {
            $series_id = $query->query_vars['event_series'];
            $where .= $wpdb->prepare(" AND {$wpdb->eo_events}.post_id =%d ", $series_id);
        }
        if (isset($query->query_vars['event_occurrence_id'])) {
            $occurrence_id = $query->query_vars['event_occurrence_id'];
            $where .= $wpdb->prepare(" AND {$wpdb->eo_events}.event_id=%d ", $occurrence_id);
        }
        //Retrieve blog's time and date
        $blog_now = new DateTIme(null, eo_get_blog_timezone());
        $now_date = $blog_now->format('Y-m-d');
        $now_time = $blog_now->format('H:i:s');
        $eo_settings_array = get_option('eventorganiser_options');
        $running_event_is_past = empty($eo_settings_array['runningisnotpast']) ? true : false;
        //Query by interval
        if (isset($query->query_vars['eo_interval'])) {
            switch ($query->query_vars['eo_interval']) {
                case 'future':
                    $query->set('showpastevents', 0);
                    $running_event_is_past = true;
                    break;
                case 'expired':
                    $now_date = $blog_now->format('Y-m-d');
                    $now_time = $blog_now->format('H:i:s');
                    $where .= $wpdb->prepare(" \n\t\t\t\t\t\tAND {$wpdb->eo_events}.post_id NOT IN (\n\t\t\t\t\t\t\tSELECT post_id FROM {$wpdb->eo_events} \n\t\t\t\t\t\t\tWHERE ({$wpdb->eo_events}.EndDate > %s)\n\t\t\t\t\t\t\tOR ({$wpdb->eo_events}.EndDate=%s AND {$wpdb->eo_events}.FinishTime >= %s)\n\t\t\t\t\t\t)", $now_date, $now_date, $now_time);
                    break;
                case 'P1D':
                case 'P1W':
                case 'P1M':
                case 'P6M':
                case 'P1Y':
                    if (!isset($cutoff)) {
                        $interval = new DateInterval($query->query_vars['eo_interval']);
                        $cutoff = clone $blog_now;
                        $cutoff->add($interval);
                    }
                    if (empty($query->query_vars['showrepeats'])) {
                        $where .= $wpdb->prepare(" \n\t\t\t\t\t\t\tAND {$wpdb->eo_events}.post_id IN (\n\t\t\t\t\t\t\t\tSELECT post_id FROM {$wpdb->eo_events} \n\t\t\t\t\t\t\t\tWHERE {$wpdb->eo_events}.StartDate <= %s\n\t\t\t\t\t\t\t\tAND {$wpdb->eo_events}.EndDate >= %s)", $cutoff->format('Y-m-d'), $blog_now->format('Y-m-d'));
                    } else {
                        $where .= $wpdb->prepare(" \n\t\t\t\t\t\t\tAND {$wpdb->eo_events}.StartDate <=%s'\n\t\t\t\t\t\t\tAND {$wpdb->eo_events}.EndDate >= %s", $cutoff->format('Y-m-d'), $blog_now->format('Y-m-d'));
                    }
                    break;
            }
        }
        /*
         * If requested, retrieve only future events. 
         * Single pages behave differently - WordPress sees them as displaying the first event
         * There could be options in the future to change this behaviour.
         * Currently we show single pages, even if they don't appear in archive listings.
         * There could be options in the future to change this behaviour too.
         *
         * 'Future events' only works if we are showing all reoccurrences, and not wanting just the first occurrence of an event.
         */
        if (isset($query->query_vars['showpastevents']) && !$query->query_vars['showpastevents']) {
            //If quering for all occurrences, look at start/end date
            if (!$query->get('group_events_by') || $query->get('group_events_by') == 'occurrence') {
                $query_date = $wpdb->eo_events . '.' . ($running_event_is_past ? 'StartDate' : 'EndDate');
                $query_time = $wpdb->eo_events . '.' . ($running_event_is_past ? 'StartTime' : 'FinishTime');
                $where .= $wpdb->prepare(" AND ( \n\t\t\t\t\t({$query_date} > %s) OR\n\t\t\t\t\t({$query_date} = %s AND {$query_time}>= %s))", $now_date, $now_date, $now_time);
                //If querying for an 'event schedule': event is past if it all of its occurrences are 'past'.
            } else {
                if ($running_event_is_past) {
                    //Check if each occurrence has started, i.e. just check reoccurrence_end
                    $query_date = $wpdb->eo_events . '.reoccurrence_end';
                    $query_time = $wpdb->eo_events . '.StartTime';
                    $where .= $wpdb->prepare(" AND ( \n\t\t\t\t\t\t({$query_date} > %s) OR\n\t\t\t\t\t\t({$query_date} = %s AND {$query_time}>= %s))", $now_date, $now_date, $now_time);
                } else {
                    //Check each occurrence has finished, need to do a sub-query.
                    $where .= $wpdb->prepare(" \n\t\t\t\t\t\tAND {$wpdb->eo_events}.post_id IN (\n\t\t\t\t\t\t\tSELECT post_id FROM {$wpdb->eo_events} \n\t\t\t\t\t\t\tWHERE ({$wpdb->eo_events}.EndDate > %s)\n\t\t\t\t\t\t\tOR ({$wpdb->eo_events}.EndDate=%s AND {$wpdb->eo_events}.FinishTime >= %s)\n\t\t\t\t\t\t\t)", $now_date, $now_date, $now_time);
                }
            }
        }
        //Check date ranges were are interested in
        if (isset($query->query_vars['event_start_before']) && $query->query_vars['event_start_before'] != '') {
            $s_before = $query->query_vars['event_start_before'];
            $where .= $wpdb->prepare(" AND {$wpdb->eo_events}.StartDate <= %s ", $s_before);
        }
        if (isset($query->query_vars['event_start_after']) && $query->query_vars['event_start_after'] != '') {
            $s_after = $query->query_vars['event_start_after'];
            $where .= $wpdb->prepare(" AND {$wpdb->eo_events}.StartDate >= %s ", $s_after);
        }
        if (isset($query->query_vars['event_end_before']) && $query->query_vars['event_end_before'] != '') {
            $e_before = $query->query_vars['event_end_before'];
            $where .= $wpdb->prepare(" AND {$wpdb->eo_events}.EndDate <= %s ", $e_before);
        }
        if (isset($query->query_vars['event_end_after']) && $query->query_vars['event_end_after'] != '') {
            $e_after = $query->query_vars['event_end_after'];
            $where .= $wpdb->prepare(" AND {$wpdb->eo_events}.EndDate >= %s ", $e_after);
        }
    }
    return $where;
}
    function display()
    {
        //Get the time 'now' according to blog's timezone
        $now = new DateTIme(null, EO_Event::get_timezone());
        $venues = get_terms('event-venue', array('hide_empty' => false));
        ?>

	<div class="wrap">  
		<div id='icon-edit' class='icon32'><br/>
		</div>
		<h2><?php 
        _e('Events Calendar', 'eventorganiser');
        ?>
</h2>

		<div id="calendar-view">
			<span id='loading' style='display:none'><?php 
        _e('Loading&#8230;');
        ?>
</span>
			<a href="" class="view-button" id="agendaDay"><?php 
        _e('Day', 'eventorganiser');
        ?>
 </a>
			<a href="" class="view-button" id="agendaWeek"><?php 
        _e('Week', 'eventorganiser');
        ?>
</a>
			<a href="" class="view-button active" id="month"><?php 
        _e('Month', 'eventorganiser');
        ?>
 </a>
		</div>
		<div id='eo_admin_calendar'></div>
		<span><?php 
        _e('Current date/time', 'eventorganiser');
        ?>
: <?php 
        echo $now->format('Y-m-d G:i:s \\G\\M\\TP');
        ?>
</span>
		<div id='events-meta' class="thickbox"></div>

		<?php 
        if (current_user_can('publish_events') || current_user_can('edit_events')) {
            ?>
			<div id='eo_event_create_cal' style="display:none;" class="thickbox">
			<form name="eventorganiser_calendar" method="post" class="eo_cal">
				<table>
				<tr>
					<th><?php 
            _e('When', 'eventorganiser');
            ?>
: </th>
					<td id="date"></td>
				</tr>
				<tr>
					<th><?php 
            _e('Event Title', 'eventorganiser');
            ?>
: </th>
					<td><input name="eo_event[event_title]" class="eo-event-title ui-autocomplete-input ui-widget-content ui-corner-all" ></td>
				</tr>
				<tr>
					<th><?php 
            _e('Where', 'eventorganiser');
            ?>
: </th>
					<td><!-- If javascript is disabed, a simple drop down menu box is displayed to choose venue.
				Otherwise, the user is able to search the venues by typing in the input box.-->		
					<select size="30" id="venue_select" name="eo_event[venue_id]">
					<option>Select a venue </option>
					<?php 
            foreach ($venues as $venue) {
                ?>
						<option value="<?php 
                echo intval($venue->term_id);
                ?>
"><?php 
                echo esc_html($venue->name);
                ?>
</option>
					<?php 
            }
            ?>
					</select>
					</td>
				</tr>
				<tr>
					<th></th>
					<td><textarea rows="4" name="eo_event[event_content]"></textarea></td>
				</tr>
				</table>
				<input type="hidden" name="eo_event[StartDate]">
				<input type="hidden" name="eo_event[EndDate]">
				<input type="hidden" name="eo_event[StartTime]">
				<input type="hidden" name="eo_event[FinishTime]">
				<input type="hidden" name="eo_event[allday]">
		  		<?php 
            wp_nonce_field('eventorganiser_calendar_save');
            ?>
			<?php 
            if (current_user_can('publish_events')) {
                ?>
					<p class="submit">	
						<input type="reset" class="button" id="reset" value="Cancel">
						<input type="submit" class="button button-highlighted" tabindex="4" value="<?php 
                _e('Save Draft', 'eventorganiser');
                ?>
"" id="event-draft" name="save">
					<span class="eo_alignright">
						<input type="submit" accesskey="p" tabindex="5" value="<?php 
                _e('Publish Event', 'eventorganiser');
                ?>
" class="button-primary" id="publish" name="publish">
					</span>
					<br class="clear">
					</p>
			<?php 
            } elseif (current_user_can('edit_events')) {
                ?>
				<p class="submit">	
					<input type="reset" class="button" id="reset" value="<?php 
                _e('Cancel', 'eventorganiser');
                ?>
">
					<input type="submit" accesskey="p" tabindex="5" value="<?php 
                _e('Submit for Review', 'eventorganiser');
                ?>
" class="eo_alignright button-primary" id="submit-for-review" name="publish">
				<br class="clear">
				</p>
			<?php 
            }
            ?>
			</form>
		</div>
		<?php 
        }
        ?>
	</div><!-- .wrap -->
<?php 
    }
/**
* Gets the formated date of next occurrence of an event
*
* @param string - the format to use, using PHP Date format
* @param id - Optional, the event (post) ID, 
* @return string the formatted date or FALSE if no date exists
*
* @since 1.0.0
*/
function eo_get_next_occurrence($format = 'd-m-Y', $id = '')
{
    global $post, $wpdb;
    if (!isset($id) || $id == '') {
        $id = $post->ID;
    }
    //Retrieve the blog's local time and create the date part
    $blog_now = new DateTIme(null, eo_get_blog_timezone());
    $now_date = $blog_now->format('Y-m-d');
    $now_time = $blog_now->format('H:i:s');
    $querystr = $wpdb->prepare("\n\t\tSELECT StartDate, StartTime\n\t\tFROM  {$wpdb->eo_events}\n\t\tWHERE {$wpdb->eo_events}.post_id=%d\n\t\tAND ( \n\t\t\t({$wpdb->eo_events}.StartDate > %s) OR\n\t\t\t({$wpdb->eo_events}.StartDate = %s AND {$wpdb->eo_events}.StartTime >= %s))\n\t\tORDER BY {$wpdb->eo_events}.StartDate ASC\n\t\tLIMIT 1", $id, $now_date, $now_date, $now_time);
    $nextoccurrence = $wpdb->get_row($querystr);
    if ($nextoccurrence !== null) {
        $date = esc_html($nextoccurrence->StartDate) . ' ' . esc_html($nextoccurrence->StartTime);
        if (empty($date) || $date == " ") {
            return false;
        }
        return eo_format_date($date, $format);
    }
}
function eventorganiser_widget_agenda()
{
    global $wpdb, $wp_locale;
    $meridiem = $wp_locale->meridiem;
    $direction = intval($_GET['direction']);
    $today = new DateTIme('now', eo_get_blog_timezone());
    $before_or_after = $direction < 1 ? 'before' : 'after';
    $date = $direction < 1 ? $_GET['start'] : $_GET['end'];
    $order = $direction < 1 ? 'DESC' : 'ASC';
    $selectDates = "SELECT DISTINCT StartDate FROM {$wpdb->eo_events}";
    if ($order == 'ASC') {
        $whereDates = " WHERE {$wpdb->eo_events}.StartDate >= %s ";
    } else {
        $whereDates = " WHERE {$wpdb->eo_events}.StartDate <= %s ";
    }
    $whereDates .= " AND {$wpdb->eo_events}.StartDate >= %s ";
    $orderlimit = "ORDER BY  {$wpdb->eo_events}.StartDate {$order} LIMIT 4";
    $dates = $wpdb->get_col($wpdb->prepare($selectDates . $whereDates . $orderlimit, $date, $today->format('Y-m-d')));
    if (!$dates) {
        return false;
    }
    $date1 = min($dates[0], $dates[count($dates) - 1]);
    $date2 = max($dates[0], $dates[count($dates) - 1]);
    $events = eo_get_events(array('event_start_after' => $date1, 'event_start_before' => $date2));
    $return_array = array();
    global $post;
    foreach ($events as $post) {
        $startDT = new DateTime($post->StartDate . ' ' . $post->StartTime);
        if (!eo_is_all_day()) {
            $ampm = trim($meridiem[$startDT->format('a')]);
            $ampm = empty($ampm) ? $startDT->format('a') : $ampm;
            //Tranlsate am/pm
            $time = $startDT->format('g:i') . $ampm;
        } else {
            $time = __('All Day', 'eventorganiser');
        }
        $color = '';
        $terms = get_the_terms($post->ID, 'event-category');
        if ($terms) {
            $term = array_shift(array_values($terms));
            $color = isset($term->color) ? $term->color : '';
        }
        //'StartDate'=>eo_format_date($post->StartDate,'l jS F'),
        $return_array[] = array('StartDate' => $post->StartDate, 'time' => $time, 'post_title' => substr($post->post_title, 0, 25), 'event_allday' => $post->event_allday, 'color' => $color, 'link' => get_permalink(), 'Glink' => eo_get_the_GoogleLink());
    }
    echo json_encode($return_array);
    exit;
}