/**
 * For this to work you need to add the following to the custom field exceptions on the ThreeWP settings page:
 *
 * _eventorganiser_event_schedule
 * _eventorganiser_schedule_start_start
 * _eventorganiser_schedule_start_finish
 *_eventorganiser_schedule_last_start
 *_eventorganiser_schedule_last_finish
 *
 * @access private
 * @ignore
 *
*/
function eventorganiser_threeWP($activity)
{
    if (isset($activity['activity_id']) && $activity['activity_id'] == '3broadcast_broadcasted' && 'event' == get_post_type(get_the_ID())) {
        $details = $activity['activity_details'];
        $current_blog_id = get_current_blog_id();
        $original_id = get_the_ID();
        $original_cats = get_the_terms($original_id, 'event-category');
        $original_venue_id = eo_get_venue($original_id);
        //Venue Meta &Thumbnail
        $venue_meta = eo_get_venue_meta($original_venue_id, '', false);
        if ($original_venue_id && ($venue_thumbnail_id = eo_get_venue_meta($original_venue_id, '_eventorganiser_thumbnail_id', true))) {
            $original_upload_dir = wp_upload_dir();
            $metadata = wp_get_attachment_metadata($venue_thumbnail_id);
            $data = get_post($venue_thumbnail_id);
            $file = $metadata['file'];
            $guid = $data->guid;
            $post_title = $data->post_title;
            $menu_order = $data->menu_order;
            $post_excerpt = $data->post_excerpt;
            $filename_base = basename($metadata['file']);
            $filename_path = $original_upload_dir['basedir'] . '/' . $metadata['file'];
            $venue_thumbnail = compact('filename_path', 'file', 'filename_base', 'post_title', 'guid', 'menu_order', 'post_excerpt');
            unset($venue_meta['_eventorganiser_thumbnail_id']);
        }
        foreach ($details as $broadcast) {
            $blog_id = $broadcast['blog_id'];
            $post_id = $broadcast['post_id'];
            switch_to_blog($blog_id);
            $event_data = array('force_regenerate_dates' => true);
            eo_update_event($post_id, $event_data);
            $venue_id = eo_get_venue($post_id);
            //Delete old venue meta
            if ($old_meta = eo_get_venue_meta($venue_id, '', false)) {
                $old_meta_keys = array_keys($old_meta);
                foreach ($old_meta_keys as $key) {
                    eo_delete_venue_meta($venue_id, $key);
                }
            }
            //Add new venue  meta
            foreach ($venue_meta as $key => $values) {
                foreach ($values as $value) {
                    eo_add_venue_meta($venue_id, $key, $value);
                }
            }
            //Sync cat colours
            $cats = get_the_terms($post_id, 'event-category');
            foreach ($cats as $cat) {
                //Find original cat
                foreach ($original_cats as $original_cat) {
                    if ($original_cat->slug == $cat->slug) {
                        $re = update_option("eo-event-category_{$cat->term_id}", array('colour' => $original_cat->color));
                        break;
                    }
                }
            }
            //Sync venue thumbnails
            $upload_dir = wp_upload_dir();
            if (file_exists($venue_thumbnail['filename_path'])) {
                $file_path = $upload_dir['path'] . '/' . $venue_thumbnail['filename_base'];
                // Copy the file to the blog's upload directory
                copy($venue_thumbnail['filename_path'], $file_path);
                if (false == ($attachment_id = eventorganiser_file_to_attachment($venue_thumbnail['file']))) {
                    // And now create the attachment stuff.
                    // This is taken almost directly from http://codex.wordpress.org/Function_Reference/wp_insert_attachment
                    $wp_filetype = wp_check_filetype($venue_thumbnail['filename_base'], null);
                    $attachment = array('guid' => $upload_dir['url'] . '/' . $venue_thumbnail['filename_base'], 'menu_order' => $venue_thumbnail['menu_order'], 'post_excerpt' => $venue_thumbnail['post_excerpt'], 'post_mime_type' => $wp_filetype['type'], 'post_title' => $venue_thumbnail['post_title'], 'post_status' => 'inherit');
                    $attachment_id = wp_insert_attachment($attachment, $file_path, 0);
                    // Now to handle the metadata.
                    require_once ABSPATH . "wp-admin" . '/includes/image.php';
                    $attach_data = wp_generate_attachment_metadata($attachment_id, $file_path);
                    wp_update_attachment_metadata($attachment_id, $attach_data);
                }
                //If attachment post doesn't exist
                eo_update_venue_meta($venue_id, '_eventorganiser_thumbnail_id', $attachment_id);
            }
            //If original file exists
        }
        //Foreach blog
        switch_to_blog($current_blog_id);
    }
    //If broadcasting
}
    /**
     * Display form for creating / editing venues
     *
     * @since 1.0.0
     */
    function edit_form($venue = false)
    {
        $tax = get_taxonomy('event-venue');
        $venue = get_term_by('slug', $venue, 'event-venue');
        $term_id = isset($venue->term_id) ? (int) $venue->term_id : 0;
        $do = $this->current_action() == 'edit' ? 'update' : 'add';
        $nonce = $do == 'update' ? 'eventorganiser_update_venue_' . $venue->slug : 'eventorganiser_add_venue';
        if ('edit' == $this->current_action()) {
            ?>
			<h2>
				<?php 
            echo esc_html($tax->labels->edit_item);
            ?>
				<a href="edit.php?post_type=event&page=venues&action=create" class="add-new-h2"><?php 
            echo esc_html($tax->labels->add_new_item);
            ?>
</a>
			</h2>
		<?php 
        } else {
            ?>
			<h2>
				<?php 
            echo esc_html($tax->labels->add_new_item);
            ?>
 
			</h2>
		<?php 
        }
        ?>

		<form name="venuedetails" id="eo_venue_form" method="post" action="<?php 
        echo admin_url('edit.php?post_type=event&page=venues');
        ?>
" <?php 
        do_action('eventorganiser_venue_edit_form_tag', $venue);
        ?>
 >
			<input type="hidden" name="action" value="<?php 
        echo $do;
        ?>
"> 
			<input type="hidden" id="eo_venue_id" name="eo_venue[venue_id]" value="<?php 
        echo $term_id;
        ?>
">  
			<input type="hidden" name="event-venue" value="<?php 
        echo isset($venue->slug) ? $venue->slug : '';
        ?>
">  

			<?php 
        wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
        ?>
			<?php 
        wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
        ?>
			<?php 
        wp_nonce_field($nonce);
        ?>

			<?php 
        //WP3.3-3.3.1 backwards compabt
        if (version_compare(get_bloginfo('version'), 3.4) < 0) {
            $columns = '1';
        } else {
            $columns = 1 == get_current_screen()->get_columns() ? '1' : '2';
        }
        ?>
			<div id="poststuff">

				<div id="post-body" class="metabox-holder columns-<?php 
        echo $columns;
        ?>
">

					<div id="post-body-content">
						<div id="titlediv"><?php 
        eventorganiser_venue_title($venue);
        ?>
</div>
						<div class="postbox " id="venue_address">
							<div class="handlediv" title="Click to toggle"><br></div>
							<h3 class="hndle"><span><?php 
        echo esc_html($tax->labels->venue_location);
        ?>
</span></h3>
							<div class="inside"><?php 
        eventorganiser_venue_location($venue);
        ?>
</div>
						</div><!-- .postbox -->
						<div id="<?php 
        echo user_can_richedit() ? 'postdivrich' : 'postdiv';
        ?>
" class="venue_description postarea">
							<?php 
        wp_editor(eo_get_venue_meta($term_id, '_description'), 'content', array('textarea_name' => 'eo_venue[description]', 'dfw' => false));
        ?>
						</div>
		 			</div><!-- #post-body-content -->

					<div id="postbox-container-1" class="postbox-container">
						<?php 
        do_meta_boxes('', 'side', $venue);
        ?>
					</div>	

					<div id="postbox-container-2" class="postbox-container">
						<?php 
        do_meta_boxes('', 'normal', $venue);
        ?>
						<?php 
        do_meta_boxes('', 'advanced', $venue);
        ?>
		 			</div>

		 		</div><!-- #post-body -->
				<br class="clear"> 

			</div><!-- #poststuff -->
		</form> 	
	<?php 
    }
/**
* Returns an array with address details of the event's venue.
* The keys consist of
*
* * 'address'
* * 'city'
* * 'state' - the state/province/county of the venue
* * 'postcode'
* * 'country'
*
* If used without any arguments uses the venue of the current event.
* 
* ### Examples
* Return the details of venue 16. **(Please note when using the ID it must be an integer - that is 16 not '16').**
* <code>
*     $address_details = eo_get_venue_address(16); 
*     //$address_details = eo_get_venue_address('16'); This method is incorrect.
* </code>   
* Print the post-code of venue 'my-venue-slug'
* <code>
*     $address_details = eo_get_venue_address('my-venue-slug'); 
*     echo "The post code of 'my-venue-slug' is: ".$address_details['postcode']; 
* </code>   
* Return the details of the venue of event 23 we can use `{@see eo_get_venue()}` to obtain the venue ID.
* <code>
*   $venue_id = eo_get_venue(23); 
*    $address_details = eo_get_venue_address($venue_id); 
* </code>   
* 
* @since 1.0.0
* @param int|string $venue_slug_or_id The venue ID (as an integer) or slug (as a string). Uses venue of current event if empty.
* @return array Array of venue address details
*/
function eo_get_venue_address($venue_slug_or_id = '')
{
    $address = array();
    $venue_id = eo_get_venue_id_by_slugorid($venue_slug_or_id);
    $address_keys = array_keys(_eventorganiser_get_venue_address_fields());
    foreach ($address_keys as $meta_key) {
        $key = trim($meta_key, '_');
        $address[$key] = eo_get_venue_meta($venue_id, $meta_key);
    }
    return $address;
}
/**
 * Handles city auto-fill request.
 *
 * Hooked onto admin_post_eo-autofillcity. Triggered when user clicks 'autofill' link.
 * This routine goes through all the venues, reverse geocodes to find their city and 
 * autofills the city field (added in 1.7).
 *
 *@ignore
 *@access private
 *@link https://github.com/stephenh1988/Event-Organiser/issues/18
 *@link http://open.mapquestapi.com/nominatim/ Nominatim Search Service
 */
function _eventorganiser_autofill_city()
{
    $seen_notices = get_option('eventorganiser_admin_notices', array());
    if (in_array('autofillvenue17', $seen_notices)) {
        return;
    }
    EO_Admin_Notice_Handler::dismiss_notice('autofillvenue17');
    $cities = array();
    $venues = eo_get_venues();
    foreach ($venues as $venue) {
        $venue_id = (int) $venue->term_id;
        $latlng = extract(eo_get_venue_latlng($venue_id));
        if (eo_get_venue_meta($venue_id, '_city', true)) {
            continue;
        }
        $response = wp_remote_get("http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat={$lat}&lon={$lng}&osm_type=N&limit=1");
        $geo = json_decode(wp_remote_retrieve_body($response));
        if (isset($geo->address->city)) {
            $cities[$venue_id] = $geo->address->city;
            eo_update_venue_meta($venue_id, '_city', $geo->address->city);
        }
        if (isset($geo->address->country_code) && 'gb' == $geo->address->country_code) {
            //For the UK use county not state.
            if (isset($geo->address->county)) {
                $cities[$venue_id] = $geo->address->county;
                eo_update_venue_meta($venue_id, '_state', $geo->address->county);
            }
        } else {
            if (isset($geo->address->state)) {
                $cities[$venue_id] = $geo->address->state;
                eo_update_venue_meta($venue_id, '_state', $geo->address->state);
            }
        }
    }
    wp_safe_redirect(admin_url('edit.php?post_type=event&page=venues'));
}
 /**
  * Get a CiviEvent loc_block ID for a given EO venue ID
  *
  * @since 0.1
  *
  * @param int $venue_id The numeric ID of the venue
  * @return void
  */
 public function get_civi_location($venue_id)
 {
     // get venue meta data
     $loc_block_id = eo_get_venue_meta($venue_id, '_civi_loc_id', true);
     // --<
     return $loc_block_id;
 }
/**
* Returns an array with address details of the event's venue
* Can be used inside the loop to return an array of venue address
* of the current event.
*
* @param (int) venue id or (string) venue slug
*
* @since 1.0.0
*/
function eo_get_venue_address($venue_slug_or_id = '')
{
    $address = array();
    $venue_id = eo_get_venue_id_by_slugorid($venue_slug_or_id);
    $address['address'] = eo_get_venue_meta($venue_id, '_address');
    $address['postcode'] = eo_get_venue_meta($venue_id, '_postcode');
    $address['country'] = eo_get_venue_meta($venue_id, '_country');
    return $address;
}