<?php
/*
===================================================================================================
WARNING! DO NOT EDIT THIS FILE OR ANY TEMPLATE FILES IN THIS THEME!

To make it easy to update your theme, you should not edit this file. Instead, you should create a
Child Theme first. This will ensure your template changes are not lost when updating the theme.

You can learn more about creating Child Themes here: http://codex.wordpress.org/Child_Themes

You have been warned! :)
===================================================================================================
*/

// Define theme location for bundled plugins
if( !defined('WP_THEME_URL') ) {
	define( 'WP_THEME_URL', get_template_directory_uri() );
}
if( !defined('WP_THEME_DIR') ) {
	define( 'WP_THEME_DIR', get_template_directory_uri() );
}


// Attempt to handle larger media uploads
@ini_set( 'upload_max_size' , '64M' );
@ini_set( 'post_max_size', '64M' );
@ini_set( 'max_execution_time', '300' );


// Attempt to prevent PHP 5.4 from erroring on entry-views.php line 61
@ini_set( 'display_errors', 'Off' );


// Add support for various awesome things
if(function_exists('add_theme_support')){
	add_theme_support('menus');
	add_theme_support('automatic-feed-links');
	add_theme_support('post-thumbnails');
}

if(function_exists('add_image_size')){
	add_image_size('slide', 924, 345, true);
	add_image_size('single', 608, 9999, false);
	add_image_size('archive', 250, 9999, false);
	add_image_size('admin', 120, 9999, false);
	add_image_size('thumb', 75, 75, true);
}


// Set content width
if ( !isset( $content_width ) ) {
	$content_width = 940;
}


// Register the scripts
function churchthemes_register() {
	wp_register_style( 'churchthemes-main', get_stylesheet_uri(), array(), CHURCHTHEMES_CURRENT_VERSION );
	wp_register_style( 'churchthemes-960', WP_THEME_DIR . '/lib/css/960.css', array( 'churchthemes-main' ), CHURCHTHEMES_CURRENT_VERSION );
	wp_register_style( 'churchthemes-responsive-ltr', WP_THEME_DIR . '/lib/css/responsive-ltr.css', array( 'churchthemes-main' ), CHURCHTHEMES_CURRENT_VERSION );
	wp_register_style( 'churchthemes-scheme', home_url() . '/?ct_scheme_css=true', array( 'churchthemes-main' ), false );
	wp_register_style( 'churchthemes-admin', WP_THEME_DIR . '/lib/admin/css/admin.css', array(), false );
	wp_register_script( 'churchthemes-slider', WP_THEME_DIR . '/lib/scripts/jquery.flexslider.min.js', array( 'jquery' ), '2.1', true );
	wp_register_script( 'churchthemes-selectbox', WP_THEME_DIR . '/lib/scripts/jquery.selectbox.min.js', array( 'jquery' ), '0.5', true );
	wp_register_script( 'churchthemes-placeholder', WP_THEME_DIR . '/lib/scripts/jquery.placeholder.min.js', array( 'jquery' ), false, true );
	wp_register_script( 'churchthemes-twitter', WP_THEME_DIR . '/lib/scripts/twitter.min.js', array(), false, false );
	wp_register_script( 'churchthemes-main', WP_THEME_DIR . '/lib/scripts/main.js', array( 'jquery' ), CHURCHTHEMES_CURRENT_VERSION, true );
}
add_action( 'init', 'churchthemes_register' );


// Load the scripts
function churchthemes_enqueue_scripts() {
	global $is_ie;

	$theme_options = get_option( 'ct_theme_options' );
	$external_target = isset( $theme_options['external_target'] ) ? $theme_options['external_target'] : '_blank';
	$responsive_css = ( isset( $theme_options['responsive_css'] ) && $theme_options['responsive_css'] === 'on' ) ? true : false;

	$slide_settings = get_option( 'ct_slide_settings' );
	$visibility = isset( $slide_settings['visibility'] ) ? $slide_settings['visibility'] : null;
	$animation = isset( $slide_settings['animation'] ) ? $slide_settings['animation'] : 'slide';
	$direction = isset( $slide_settings['direction'] ) ? $slide_settings['direction'] : 'horizontal';
	$speed = ( isset( $slide_settings['speed'] ) && is_numeric( $slide_settings['speed'] ) ) ? $slide_settings['speed'] : 5;

	if ( is_singular() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}

	if ( is_post_type_archive( 'ct_sermon' ) || is_archive( 'ct_sermon' ) ) {
		wp_enqueue_script( 'churchthemes-selectbox' );
	}

	if ( is_front_page() && $visibility !== 'off' ) {
		wp_enqueue_script( 'churchthemes-slider' );
		wp_localize_script( 'churchthemes-main', 'churchthemes_slide_vars', array(
			'animation' => esc_attr( $animation ),
			'direction' => esc_attr( $direction ),
			'speed' => intval( $speed ) . '000',
		));
	}

	if ( !is_admin() && is_active_widget( false, false, 'twitter-feed', true ) ) {
		wp_enqueue_script( 'churchthemes-twitter' );
	}

	if ( !is_admin() && $is_ie ) {
		wp_enqueue_script( 'churchthemes-placeholder' );
	}

	if ( !is_admin() ) {
		wp_enqueue_style( 'churchthemes-main' );
		if ( $responsive_css == 'on' ) {
			wp_enqueue_style( 'churchthemes-responsive-ltr' );
		}
		else {
			wp_enqueue_style( 'churchthemes-960' );
		}
		wp_enqueue_style( 'churchthemes-scheme' );
		wp_localize_script( 'churchthemes-main', 'churchthemes_global_vars', array(
			'external_target' => esc_attr( $external_target ),
		));
		wp_enqueue_script( 'churchthemes-main' );
	}
}
add_action( 'wp_enqueue_scripts', 'churchthemes_enqueue_scripts' );


// Load up styles in WP Admin area
function churchthemes_admin_enqueue_scripts() {
	if ( is_admin() ) {
		wp_enqueue_style( 'churchthemes-admin' );
	}
}
add_action( 'admin_enqueue_scripts', 'churchthemes_admin_enqueue_scripts' );


/**
 * Print meta and icons in the head.
 *
 * @action wp_head
 */
function churchthemes_head() {

	$theme_options  = get_option('ct_theme_options');
	$responsive_css = isset( $theme_options['responsive_css'] ) ? $theme_options['responsive_css'] : null;
	$favicon        = isset( $theme_options['favicon'] )        ? $theme_options['favicon']        : null;
	$ios_icon       = isset( $theme_options['ios_icon'] )       ? $theme_options['ios_icon']       : null;

	if ( $responsive_css == 'on' ) {
		printf( '<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />%s', "\n" );
	}

	if ( $favicon ) {
		printf( '<link rel="icon" type="image/png" href="%s" />%s', esc_url( $favicon ), "\n" );
	}

	if ( $ios_icon ) {
		printf( '<link rel="apple-touch-icon" href="%s" />%s', esc_url( $ios_icon ), "\n" );
	}

}
add_action( 'wp_head', 'churchthemes_head' );


/**
 * Print custom CSS in the head.
 *
 * @action wp_head
 */
function churchthemes_custom_css() {

	$theme_options  = get_option('ct_theme_options');
	$custom_css = isset( $theme_options['custom_css'] ) ? $theme_options['custom_css'] : null;

	if ( $custom_css ) {
		printf( '<style type="text/css">%2$s%1$s%2$s</style>%2$s', esc_html( $custom_css ), "\n" );
	}

}
add_action( 'wp_head', 'churchthemes_custom_css', 999 );


/* Hide WP version meta tag from header and generator tag from feeds
 * @return null
 * @filter the_generator
 */
function churchthemes_remove_wp_version_tag() {
	return null;
}
add_filter( 'the_generator', 'churchthemes_remove_wp_version_tag' );


/* Hide WP version strings from scripts and styles
 * @return {string} $src
 * @filter script_loader_src
 * @filter style_loader_src
 */
function churchthemes_remove_wp_version_strings( $src ) {
	global $wp_version;
	parse_str( parse_url( $src, PHP_URL_QUERY ), $query );
	if ( !empty( $query['ver'] ) && $query['ver'] === $wp_version ) {
		$src = remove_query_arg( 'ver', $src );
	}
	return $src;
}
add_filter( 'script_loader_src', 'churchthemes_remove_wp_version_strings' );
add_filter( 'style_loader_src', 'churchthemes_remove_wp_version_strings' );



function churchthemes_add_body_classes( $classes ) {

	$theme_options  = get_option('ct_theme_options');
	$responsive_css = isset( $theme_options['responsive_css'] ) ? $theme_options['responsive_css'] : null;

	if ( $responsive_css == 'on' ) {
		$classes[] = 'responsive-css';
	}

	return $classes;
}
add_filter( 'body_class', 'churchthemes_add_body_classes' );


// Only allow Reorder functionality on specific post types
function churchthemes_exclude_from_reorder() {
	$post_types = get_post_types();
	$allowed = array( 'post', 'page', 'ct_slide', 'ct_sermon', 'ct_location', 'ct_person' );
	$excluded = array_diff( $post_types, $allowed );
	return $excluded;
}
add_filter( 'reorder_exclude', 'churchthemes_exclude_from_reorder' );


function churchthemes_nav_menu_select( $location ) {

	if ( $locations = get_nav_menu_locations() ) {

		$menu = wp_get_nav_menu_object( $locations[ $location ] );

		$menu_items = wp_get_nav_menu_items( $menu->term_id );

		$menu_list = sprintf( '<select id="menu-%s" onchange="if (this.value) window.location.href = this.value;"><option>%s</<option>', esc_attr( $menu_name ), esc_html__( '- Main Menu -' ) );

		$parents = array_unique( array_filter( wp_list_pluck( $menu_items, 'menu_item_parent' ) ) );

		$level_1 = array();
		$level_2 = array();
		$level_3 = array();

		foreach ( (array) $menu_items as $key => $menu_item ) {
			if ( empty( $menu_item->menu_item_parent ) ) {
				$level_1[] = $menu_item->ID;
			}
			if ( ! empty( $menu_item->menu_item_parent ) ) {
				$level_2[] = $menu_item->ID;
			}
			if ( in_array( $menu_item->ID, $parents ) && ! empty( $menu_item->menu_item_parent ) ) {
				$level_3[] = $menu_item->ID;
			}
		}

		foreach ( (array) $menu_items as $key => $menu_item ) {

			$id     = ! empty( $menu_item->ID ) ? $menu_item->ID : null;
			$title  = ! empty( $menu_item->title ) ? $menu_item->title : null;
			$url    = ! empty( $menu_item->url ) ? $menu_item->url : null;
			$parent = ! empty( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : null;

			if ( in_array( $parent, $level_3 ) ) {
				$depth = '&mdash;&mdash;&nbsp;';
			} elseif ( in_array( $id, $level_2 ) ) {
				$depth = '&mdash;&nbsp;';
			} else {
				$depth = '';
			}

			$menu_list .= sprintf( '<option value="%1$s" class="%2$s"><a href="%1$s">%3$s%4$s</a></option>', esc_url( $url ), absint( $id ), $depth, esc_html( $title ) );

		}

		$menu_list .= '</select>';

	}

	echo $menu_list;
}


// Register theme menus
if(!function_exists('ct_register_menus')) {
	function ct_register_menus() {
		register_nav_menus(
			array(
				'primary' => __('Primary Nav Menu'),
				'footer' => __('Footer Nav Menu')
			)
		);
	}
	add_action( 'init', 'ct_register_menus' );
}


// Primary nav menu with fallback
if(!function_exists('ct_primary_nav_menu')) {
	function ct_primary_nav_menu() {
    	wp_nav_menu( array(
			'theme_location'  => 'primary',
			'container'       => 'div',
			'container_class' => 'navbar',
			'menu_class'      => '',
			'menu_id'         => false,
			'depth'           => 3,
			'fallback_cb'     => 'ct_primary_nav_fallback'
		));

		$theme_options  = get_option('ct_theme_options');
		$responsive_css = isset( $theme_options['responsive_css'] ) ? $theme_options['responsive_css'] : null;

		if ( $responsive_css == 'on' ) {
			?>
			<div class="navbar-select mobile-grid-100">
				<?php churchthemes_nav_menu_select( 'primary' ) ?>
			</div>
			<?php
		}

	}
	function ct_primary_nav_fallback() {
	    wp_page_menu('menu_class=navbar');
	}
}


// Footer nav menu
if(!function_exists('ct_footer_nav_menu')) {
	function ct_footer_nav_menu() {
    	wp_nav_menu( array(
			'theme_location' => 'footer',
			'container'      => false,
			'menu_class'     => 'footer_nav grid_7 grid-60 omega',
			'menu_id'        => false,
			'depth'          => 1,
		));
	}
}


/**
 * Get the attachment ID from an attachment URL.
 * @return $id
 */
function ct_get_attachment_id_from_src( $src ) {
	global $wpdb;

	$query = "SELECT ID FROM $wpdb->posts WHERE guid='$src'";
	$id = $wpdb->get_var( $query );

	return $id;
}


/**
 * Get the filesize of a remote file, used for the MP3 audio in the podcast feed.
 */
if(!function_exists('ct_get_filesize')) {
	function ct_get_filesize( $url, $timeout = 5 ) {

		// If the file is from the media library, get the filesize using the file path
		if ( $audio_file_id = ct_get_attachment_id_from_src( esc_url_raw( $url ) ) ) {
			return filesize( get_attached_file( $audio_file_id ) );
		}

		// Create a curl connection
		$getsize = curl_init();

		// Set the url we're requesting
		curl_setopt( $getsize, CURLOPT_URL, esc_url_raw( $url ) );

		// Set a valid user agent
		curl_setopt( $getsize, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11" );

		// Don't output any response directly to the browser
		curl_setopt( $getsize, CURLOPT_RETURNTRANSFER, true );

		// Don't return the header (we'll use curl_getinfo();
		curl_setopt( $getsize, CURLOPT_HEADER, false );

		// Don't download the body content
		curl_setopt( $getsize, CURLOPT_NOBODY, true );

		// Follow location headers
		curl_setopt( $getsize, CURLOPT_FOLLOWLOCATION, true );

		// Set the timeout (in seconds)
		curl_setopt( $getsize, CURLOPT_TIMEOUT, $timeout );

		// Run the curl functions to process the request
		$getsize_store = curl_exec( $getsize );
		$getsize_error = curl_error( $getsize );
		$getsize_info = curl_getinfo( $getsize );

		// Close the connection
		curl_close( $getsize );

		// Return the filesize in bytes
		return $getsize_info['download_content_length'];
	}
}


/**
 * Action for when the podcast feed is updated.
 *
 * See usage in: lib/admin/podcast-settings.php
 */
function ct_save_podcast_settings() {
	do_action( 'ct_save_podcast_settings' );
}


/**
 * Delete podcast cache when a sermon post is published, updated or deleted.
 *
 * @action save_post
 * @action delete_post
 * @action ct_save_podcast_settings
 */
function ct_delete_podcast_feed_cache( $post_id ) {

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	if ( !empty( $post_id ) && get_post_type( $post_id ) !== 'ct_sermon' ) {
		return;
	}

	delete_transient( 'churchthemes_podcast_feed_cache' );
}
add_action( 'save_post', 'ct_delete_podcast_feed_cache' );
add_action( 'delete_post', 'ct_delete_podcast_feed_cache' );
add_action( 'ct_save_podcast_settings', 'ct_delete_podcast_feed_cache' );


/**
 * Display a the excerpt with unique length and more text at each instance.
 * Choose whether or not length refers to word count or character count, for
 * more fine-grained control over the size of the rendered excerpt.
 * @param {mixed} $args A WordPress-style query string or array consisting of 'length' (integer), 'more' (str), and 'unit' ('word' || 'char')
 * @return {string} The excerpt
 */
function churchthemes_get_the_excerpt( $args ){
	static $cache = array(); // function cache to improve create_function eval performance
	$all_units = array('word', 'char',);
	$defaults = array(
		'unit' => 'word',
		'wpautop' => true,
	);
	extract(wp_parse_args($args, $defaults), EXTR_SKIP); // => $length, $more, $unit

	// Filter the excerpt length, either in terms of word count or char count
	if( isset($length) ){
		assert( is_numeric($length) );
		assert( in_array( $unit, $all_units ) );
		if( $unit === 'word' ){
			$func = sprintf('return %d;', var_export($length, true));
			if( isset($cache[$func]) ){
				$length_filter = $cache[$func];
			}
			else {
				$cache[$func] = $length_filter = create_function('', $func);
			}
			add_filter( 'excerpt_length', $length_filter );
		}
		else if( $unit === 'char' ) {
			$params = '$text, $num_words, $more, $original_text';
			$func = sprintf('return substr(wp_strip_all_tags($original_text), 0, %d) . $more;', $length);
			if( isset($cache[$func]) ){
				$wp_trim_words_filter = $cache[$func];
			}
			else {
				$cache[$func] = $wp_trim_words_filter = create_function($params, $func);
			}
			add_filter( 'wp_trim_words', $wp_trim_words_filter, 10, 4 ); // @todo This does wpautop??? Thus requiring force_balance_tags
		}
	}

	// Customize the excerpt_more if specified
	if( isset($more) ){
		$func = sprintf('return %s;', var_export($more, true));
		if( isset($cache[$func]) ){
			$more_filter = $cache[$func];
		}
		else {
			$cache[$func] = $more_filter = create_function('', $func);
		}
		add_filter('excerpt_more', $more_filter);
	}

	$excerpt = get_the_excerpt();

	// Remove filters that were added
	if( isset($length_filter) ){
		remove_filter( 'excerpt_length', $length_filter );
	}
	if( isset($more_filter) ){
		remove_filter( 'excerpt_more', $more_filter );
	}
	if( isset($wp_trim_words_filter) ){
		remove_filter( 'wp_trim_words', $wp_trim_words_filter );
	}

	if( $wpautop ){ // @todo Should this apply the_content filters? Should it even wpautop by default?
		$excerpt = wpautop($excerpt);
	}
	return $excerpt;
}


/**
 * Shortcut for: echo churchthemes_get_the_excerpt($args)
 * @see churchthemes_get_the_excerpt()
 */
function churchthemes_the_excerpt( $args ){
	echo churchthemes_get_the_excerpt( $args );
}


if(!function_exists('ct_person_social')) {
	function ct_person_social() {

		global $post;

		$delicious = get_post_meta($post->ID, '_ct_ppl_delicious', true);
		$facebook = get_post_meta($post->ID, '_ct_ppl_facebook', true);
		$flickr = get_post_meta($post->ID, '_ct_ppl_flickr', true);
		$lastfm = get_post_meta($post->ID, '_ct_ppl_lastfm', true);
		$linkedin = get_post_meta($post->ID, '_ct_ppl_linkedin', true);
		$myspace = get_post_meta($post->ID, '_ct_ppl_myspace', true);
		$picasa = get_post_meta($post->ID, '_ct_ppl_picasa', true);
		$ping = get_post_meta($post->ID, '_ct_ppl_ping', true);
		$posterous = get_post_meta($post->ID, '_ct_ppl_posterous', true);
		$tumblr = get_post_meta($post->ID, '_ct_ppl_tumblr', true);
		$twitter = get_post_meta($post->ID, '_ct_ppl_twitter', true);
		$vimeo = get_post_meta($post->ID, '_ct_ppl_vimeo', true);
		$wordpress = get_post_meta($post->ID, '_ct_ppl_wordpress', true);
		$youtube = get_post_meta($post->ID, '_ct_ppl_youtube', true);

		if($delicious || $facebook || $flickr || $lastfm || $linkedin || $myspace || $picasa || $ping || $posterous || $tumblr || $twitter || $vimeo || $wordpress || $youtube):

		printf('<div class="ct_person_social">');
			printf('<ul>');
				if($delicious):
					printf(__('<li><a href="'.$delicious.'" class="delicious" title="Delicious"></a></li>', 'churchthemes'));
				endif;
				if($facebook):
					printf(__('<li><a href="'.$facebook.'" class="facebook" title="Facebook"></a></li>', 'churchthemes'));
				endif;
				if($flickr):
					printf(__('<li><a href="'.$flickr.'" class="flickr" title="Flickr"></a></li>', 'churchthemes'));
				endif;
				if($lastfm):
					printf(__('<li><a href="'.$lastfm.'" class="lastfm" title="Last.fm"></a></li>', 'churchthemes'));
				endif;
				if($linkedin):
					printf(__('<li><a href="'.$linkedin.'" class="linkedin" title="LinkedIn"></a></li>', 'churchthemes'));
				endif;
				if($myspace):
					printf(__('<li><a href="'.$myspace.'" class="myspace" title="MySpace"></a></li>', 'churchthemes'));
				endif;
				if($picasa):
					printf(__('<li><a href="'.$picasa.'" class="picasa" title="Picasa"></a></li>', 'churchthemes'));
				endif;
				if($ping):
					printf(__('<li><a href="'.$ping.'" class="ping" title="Ping"></a></li>', 'churchthemes'));
				endif;
				if($posterous):
					printf(__('<li><a href="'.$posterous.'" class="posterous" title="Posterous"></a></li>', 'churchthemes'));
				endif;
				if($tumblr):
					printf(__('<li><a href="'.$tumblr.'" class="tumblr" title="Tumblr"></a></li>', 'churchthemes'));
				endif;
				if($twitter):
					printf(__('<li><a href="'.$twitter.'" class="twitter" title="Twitter"></a></li>', 'churchthemes'));
				endif;
				if($vimeo):
					printf(__('<li><a href="'.$vimeo.'" class="vimeo" title="Vimeo"></a></li>', 'churchthemes'));
				endif;
				if($wordpress):
					printf(__('<li><a href="'.$wordpress.'" class="wordpress" title="WordPress"></a></li>', 'churchthemes'));
				endif;
				if($youtube):
					printf(__('<li><a href="'.$youtube.'" class="youtube" title="YouTube"></a></li>', 'churchthemes'));
				endif;
			printf('</ul>');
		printf('</div>');

		endif;
	}
}


if(!function_exists('ct_person_contact')) {
	function ct_person_contact() {

		global $post;

		$person_email_label = get_post_meta($post->ID, '_ct_ppl_emaillabel', true);
		$person_email_address = get_post_meta($post->ID, '_ct_ppl_emailaddress', true);
		$person_phone_label_1 = get_post_meta($post->ID, '_ct_ppl_phonelabel1', true);
		$person_phone_num_1 = get_post_meta($post->ID, '_ct_ppl_phonenum1', true);
		$person_phone_label_2 = get_post_meta($post->ID, '_ct_ppl_phonelabel2', true);
		$person_phone_num_2 = get_post_meta($post->ID, '_ct_ppl_phonenum2', true);
		$person_phone_label_3 = get_post_meta($post->ID, '_ct_ppl_phonelabel3', true);
		$person_phone_num_3 = get_post_meta($post->ID, '_ct_ppl_phonenum3', true);


		if($person_email_address || $person_phone_num_1 || $person_phone_num_2 || $person_phone_num_3):

		printf('<div class="ct_person_contact">');
			printf('<ul>');
				if($person_email_label && $person_email_address):
					printf(__('<li><span>'.$person_email_label.'</span><a href="mailto:'.$person_email_address.'">'.$person_email_address.'</a></li>', 'churchthemes'));
				endif;
				if($person_phone_label_1 && $person_phone_num_1):
					printf(__('<li><span>'.$person_phone_label_1.'</span>'.$person_phone_num_1.'</li>', 'churchthemes'));
				endif;
				if($person_phone_label_2 && $person_phone_num_2):
					printf(__('<li><span>'.$person_phone_label_2.'</span>'.$person_phone_num_2.'</li>', 'churchthemes'));
				endif;
				if($person_phone_label_3 && $person_phone_num_3):
					printf(__('<li><span>'.$person_phone_label_3.'</span>'.$person_phone_num_3.'</li>', 'churchthemes'));
				endif;
			printf('</ul>');
		printf('</div>');

		endif;
	}
}


if(!function_exists('ct_location_address')) {
	function ct_location_address() {

		global $post;

		$location_address_1 = get_post_meta($post->ID, '_ct_loc_address1', true);
		$location_address_2 = get_post_meta($post->ID, '_ct_loc_address2', true);
		$location_address_3 = get_post_meta($post->ID, '_ct_loc_address3', true);

		if($location_address_1 || $location_address_2 || $location_address_3):

		printf('<div class="ct_location_address">');
			printf('<p>');
				if($location_address_1):
					printf(__($location_address_1, 'churchthemes'));
				endif;
				if($location_address_2):
					printf(__('<br />'.$location_address_2, 'churchthemes'));
				endif;
				if($location_address_3):
					printf(__('<br />'.$location_address_3, 'churchthemes'));
				endif;
			printf('</p>');
		printf('</div>');

		endif;
	}
}


if(!function_exists('ct_location_tagline')) {
	function ct_location_tagline() {

		global $post;

		$location_address_1 = get_post_meta($post->ID, '_ct_loc_address1', true);
		$location_address_2 = get_post_meta($post->ID, '_ct_loc_address2', true);
		$location_address_3 = get_post_meta($post->ID, '_ct_loc_address3', true);

		if($location_address_1 || $location_address_2 || $location_address_3):
			if($location_address_1):
				printf(__($location_address_1, 'churchthemes'));
			endif;
			if($location_address_2):
				printf(__(', '.$location_address_2, 'churchthemes'));
			endif;
			if($location_address_3):
				printf(__(', '.$location_address_3, 'churchthemes'));
			endif;
		endif;
	}
}


if(!function_exists('ct_location_services')) {
	function ct_location_services() {

		global $post;

		$location_service_1 = get_post_meta($post->ID, '_ct_loc_service1', true);
		$location_service_2 = get_post_meta($post->ID, '_ct_loc_service2', true);
		$location_service_3 = get_post_meta($post->ID, '_ct_loc_service3', true);
		$location_service_4 = get_post_meta($post->ID, '_ct_loc_service4', true);
		$location_service_5 = get_post_meta($post->ID, '_ct_loc_service5', true);

		if($location_service_1 || $location_service_2 || $location_service_3 || $location_service_4 || $location_service_5):

		printf('<div class="ct_location_services">');
		if($location_service_1 && ($location_service_2 || $location_service_3 || $location_service_4 || $location_service_5)):
			printf(__('<h4>Service Times</h4>', 'churchthemes'));
		else:
			printf(__('<h4>Service Time</h4>', 'churchthemes'));
		endif;
			printf('<ul>');
				if($location_service_1):
					printf(__('<li>'.$location_service_1.'</li>', 'churchthemes'));
				endif;
				if($location_service_2):
					printf(__('<li>'.$location_service_2.'</li>', 'churchthemes'));
				endif;
				if($location_service_3):
					printf(__('<li>'.$location_service_3.'</li>', 'churchthemes'));
				endif;
				if($location_service_4):
					printf(__('<li>'.$location_service_4.'</li>', 'churchthemes'));
				endif;
				if($location_service_5):
					printf(__('<li>'.$location_service_5.'</li>', 'churchthemes'));
				endif;
			printf('</ul>');
		printf('</div>');

		endif;
	}
}


if(!function_exists('churchthemes_comment')) {
	/**
	 * Template for comments and pingbacks.
	 */
	function churchthemes_comment( $comment, $args, $depth ) {
		$GLOBALS['comment'] = $comment;
		switch ( $comment->comment_type ) :
			case '' :
		?>
		<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
			<div id="comment-<?php comment_ID(); ?>" class="single-comment">
			<div class="comment-author vcard">
				<?php echo get_avatar( $comment, 40 ); ?>
				<?php printf( __( '%s <span class="says">says:</span>', 'churchthemes' ), sprintf( '<cite class="fn">%s</cite>', get_comment_author_link() ) ); ?>
			</div><!-- .comment-author .vcard -->
			<?php if ( $comment->comment_approved == '0' ) : ?>
				<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'churchthemes' ); ?></em>
				<br />
			<?php endif; ?>

			<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
				<?php
					/* translators: 1: date, 2: time */
					printf( __( '%1$s at %2$s', 'churchthemes' ), get_comment_date(),  get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)', 'churchthemes' ), ' ' );
				?>
			</div><!-- .comment-meta .commentmetadata -->

			<div class="comment-body"><?php comment_text(); ?></div>

			<div class="reply">
				<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
			</div><!-- .reply -->
		</div><!-- #comment-##  -->

		<?php
				break;
			case 'pingback'  :
			case 'trackback' :
		?>
		<li class="post pingback">
			<p><?php _e( 'Pingback:', 'churchthemes' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( '(Edit)', 'churchthemes' ), ' ' ); ?></p>
		<?php
				break;
		endswitch;
	}
}


if(!function_exists('ct_posted_by')) {
	/**
	 * Prints HTML with meta information for the current post date/time and author.
	 */
	function ct_posted_by() {
		printf( __( '<span class="%1$s">Posted by %2$s</span><br /><br />', 'churchthemes' ),
			'meta-prep-author',
			sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s">%3$s</a></span>',
				get_author_posts_url( get_the_author_meta( 'ID' ) ),
				sprintf( esc_attr__( 'View all posts by %s', 'churchthemes' ), get_the_author() ),
				get_the_author()
			)
		);
	}
}


if(!function_exists('ct_sermon_meta')) {
	/**
	 * Prints HTML with meta information for the current sermon (speaker, series, service and topics).
	 */
	function ct_sermon_meta() {
		global $post;
		// Retrieves tag list of current post, separated by commas.
		$tag_list = get_the_tag_list( '', ', ' );
		$sermon_speaker = get_the_term_list($post->ID, 'sermon_speaker');
		$sermon_series = get_the_term_list($post->ID, 'sermon_series');
		$sermon_service = get_the_term_list($post->ID, 'sermon_service');
		if ( $sermon_speaker ) {
			printf( '<p><span>%s</span><br />%s</p>', __( 'Speaker', 'churchthemes' ), $sermon_speaker );
		}
		if ( $sermon_series ) {
			printf( '<p><span>%s</span><br />%s</p>', __( 'Series', 'churchthemes' ), $sermon_series );
		}
		if ( $sermon_service ) {
			printf( '<p><span>%s</span><br />%s</p>', __( 'Service', 'churchthemes' ), $sermon_service );
		}
	}
}


// Assign unique classes to first and last menu items
if(!function_exists('ct_first_last_class')) {
	function ct_first_last_class($output) {
		$output = preg_replace('/class="menu-item/', 'class="first menu-item', $output, 1);
		$output = substr_replace($output, 'class="last menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
		return $output;
	}
	add_filter( 'wp_nav_menu', 'ct_first_last_class' );
}


// Create custom feed for sermon podcast
function ct_add_podcast_feed(){
	add_feed( 'podcast', 'ct_podcast_feed_template' );
}
add_action( 'init', 'ct_add_podcast_feed' );


// Load up the sermon podcast feed template
function ct_podcast_feed_template() {
	load_template( locate_template( '/lib/scripts/podcast-feed.php' ) );
}


// Query for the sermon podcast feed
if(!function_exists('ct_podcast_feed_pre')) {
	function ct_podcast_feed_pre( $query ) {
		if ( !$query->is_feed( 'podcast' ) ) {
			return;
		}
		$query->set( 'posts_per_page', -1 );
		$query->set( 'post_type', 'ct_sermon' );
		$query->set( 'post_status', 'publish' );
		$query->set( 'orderby', 'date' );
		$query->set( 'order', 'DESC' );
	}
	add_action( 'pre_get_posts', 'ct_podcast_feed_pre' );
}


// Returns the URL of the current page
if(!function_exists('ct_get_current_url')) {
	function ct_get_current_url() {
		$url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
		$url .= ( $_SERVER["SERVER_PORT"] !== '80' ) ? ":".$_SERVER["SERVER_PORT"] : null;
		$url .= $_SERVER["REQUEST_URI"];
		return esc_url_raw( $url );
	}
}


// Flush rewrite rules
if(!function_exists('ct_flush_rules')) {
	function ct_flush_rules() {
		global $wp_rewrite;
		$wp_rewrite->flush_rules();
	}
	add_filter('register_activation_hook', 'ct_flush_rules');
}


// Awesome Pagination
if(!function_exists('pagination')) {
	function pagination($pages = '', $range = 3) {
		$showitems = ($range * 2)+1;

		global $paged;
		if(empty($paged)) $paged = 1;

		if($pages == '') {
			global $wp_query;
			$pages = $wp_query->max_num_pages;
			if(!$pages) {
				$pages = 1;
			}
		}

		if(1 != $pages) {
			echo "<ul class=\"pagination\">";
			if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<li><a href=\"".get_pagenum_link(1)."\">&lt;&lt; First</a></li>";
			if($paged > 1 && $showitems < $pages) echo "<li class=\"previous\"><a href=\"".get_pagenum_link($paged - 1)."\">&lt; Prev</a></li>";

			for ($i=1; $i <= $pages; $i++) {
				if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) {
					echo ($paged == $i)? "<li class=\"active\"><a href=\"javascript:void(0)\">".$i."</a></li>":"<li><a href=\"".get_pagenum_link($i)."\">".$i."</a></li>";
				}
			}

			if ($paged < $pages && $showitems < $pages) echo "<li class=\"next\"><a href=\"".get_pagenum_link($paged + 1)."\">Next &gt;</a></li>";
			if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<li><a href=\"".get_pagenum_link($pages)."\">Last &gt;&gt;</a></li>";
			echo "</ul>\n";
			echo "<p class=\"pagecount\">Page ".$paged." of ".$pages."</p>\n";
		}
	}
}


// Find the real image path for TimThumb on multisite
function get_realpath($img_src) {
    global $blog_id;
    if (isset($blog_id) && $blog_id > 0) {
        $imageParts = explode('/files/', $img_src);
        if (isset($imageParts[1])) {
            $img_src = '/blogs.dir/'.$blog_id.'/files/'.$imageParts[1];
        }
    }
    return $img_src;
}


// Add support for TimThumb
if(!function_exists('get_thumbnail')) {
	function get_thumbnail($id, $w, $h) {
		global $post;
		$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 300,300 ), false, '');
		$path = get_realpath($src[0]);
		$dir = WP_THEME_DIR;
		if(empty($w)) $w = '80';
		if(empty($h)) $h = '80';
		if(!empty($src)):
			$image = $dir.'/lib/scripts/timthumb.php?src='.$path.'&w='.$w.'&h='.$h;
			return $image;
		else:
			return null;
		endif;
	}
}


// Convert HEX colors to RGB
function churchthemes_hex_to_rgb( $color ) {
	if ( $color[0] == '#' ) {
		$color = substr( $color, 1 );
	}
	if ( strlen( $color ) == 6 ) {
		list( $r, $g, $b ) = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
	} elseif ( strlen( $color ) == 3 ) {
		list( $r, $g, $b ) = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
	} else {
		return false;
	}
	$r = hexdec( $r );
	$g = hexdec( $g );
	$b = hexdec( $b );
	return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}


// Add support for entry views
if(!function_exists('ct_add_entry_views')) {
	function ct_add_entry_views() {
		add_post_type_support('post', array('entry-views'));
		add_post_type_support('page', array('entry-views'));
		add_post_type_support('ct_slide', array('entry-views'));
		add_post_type_support('ct_sermon', array('entry-views'));
		add_post_type_support('ct_location', array('entry-views'));
		add_post_type_support('ct_person', array('entry-views'));
	}
	add_action( 'init', 'ct_add_entry_views' );
}


// Register custom post column for views and allow sorting
if(!function_exists('ct_post_edit_columns')) {
	function ct_post_edit_columns( $columns ) {
		$columns['post_views'] = __( 'Views', 'churchthemes' );
		return $columns;
	}
	add_filter( 'manage_edit-post_columns', 'ct_post_edit_columns' );
}

if(!function_exists('ct_post_custom_columns')) {
	function ct_post_custom_columns( $column_name, $post_id ) {
		if ( 'post_views' != $column_name )
			return;
		$views = get_post_meta($post_id, 'Views', true);
		if ( !$views )
			$views = __( 'none', 'churchthemes' );
		echo $views;
	}
	add_action( 'manage_posts_custom_column', 'ct_post_custom_columns', 10, 2 );
}

if(!function_exists('ct_post_views_column_register_sortable')) {
	function ct_post_views_column_register_sortable($columns) {
		$columns['post_views'] = 'Views';
		return $columns;
	}
	add_filter('manage_edit-post_sortable_columns', 'ct_post_views_column_register_sortable');
}

if(!function_exists('ct_post_column_orderby_views')) {
	function ct_post_column_orderby_views($vars) {
		if (isset( $vars['orderby']) && 'Views' == $vars['orderby']) {
			$vars = array_merge( $vars, array(
				'meta_key' => 'Views',
				'orderby' => 'meta_value_num'
			));
		}
		return $vars;
	}
	add_filter( 'request', 'ct_post_column_orderby_views' );
}


// Custom taxonomy terms dropdown function
if(!function_exists('dropdown_taxonomy_term')) {
	function dropdown_taxonomy_term($taxonomy) {
		$terms = get_terms($taxonomy);
		foreach ($terms as $term) {
			$term_slug = $term->slug;
			$current_speaker = get_query_var('sermon_speaker');
			$current_series = get_query_var('sermon_series');
			$current_service = get_query_var('sermon_service');
			$current_topic = get_query_var('sermon_topic');
			if($term_slug == $current_speaker || $term_slug == $current_series || $term_slug == $current_service || $term_slug == $current_topic) {
				echo '<option value="'.$term->slug.'" selected>'.$term->name.'</option>';
			} else {
				echo '<option value="'.$term->slug.'">'.$term->name.'</option>';
			}
		}
	}
}


// Create custom Page Options
$page_options_meta = new WPAlchemy_MetaBox(
	array(
		'id' => '_page_options',
		'types' => array('page'),
		'autosave' => TRUE,
		'title' => 'Page Options',
		'template' => TEMPLATEPATH . '/lib/admin/page-options.php',
	)
);


// Allow shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');


// Add the shortcode handler for YouTube videos
if(!function_exists('ct_youtube_shortcode')) {
	function ct_youtube_shortcode($atts, $content = null) {

		extract( shortcode_atts(
			array(
				"id" => '',
				"width" => 608,
				"height" => 375,
				"hd" => 'false',
				"autoplay" => 'false',
				"related" => 'true',
				"showinfo" => 'true',
				"controls" => 'true',
				"https" => 'false'
			),
			$atts
		));

		$autoplay = ( $autoplay === 'true' ) ? '&autoplay=1' : null;
		$related = ( $related === 'false' ) ? '&rel=0' : null;
		$showinfo = ( $showinfo === 'false' ) ? '&showinfo=0' : null;
		$controls = ( $controls === 'false' ) ? '&controls=0' : null;
		$https = ( $https === 'true' ) ? 's' : null;

		if ( $hd === 'true' ) {
			return '<div class="video_player"><object class="ct-video-object" width="'.$width.'" height="'.$height.'"><param name="movie" value="http'.$https.'://www.youtube.com/v/'.$id.'&wmode=opaque&hd=1'.$autoplay.$related.$showinfo.$controls.'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="transparent"><embed src="http'.$https.'://www.youtube.com/v/'.$id.'&wmode=opaque&hd=1'.$autoplay.$related.$showinfo.$controls.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="'.$width.'" height="'.$height.'"></embed></object></div>';
		}
		else {
			return '<div class="video_player"><iframe width="'.$width.'" height="'.$height.'" src="http'.$https.'://www.youtube.com/embed/'.$id.'?wmode=opaque'.$autoplay.$related.$showinfo.$controls.'" frameborder="0" allowfullscreen></iframe></div>';
		}
	}
	add_shortcode('youtube', 'ct_youtube_shortcode');

	function ct_youtube_shortcode_button() {
	   // Don't bother doing this stuff if the current user lacks permissions
	   if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
	     return;

	   // Add only in Rich Editor mode
	   if ( get_user_option('rich_editing') == 'true') {
	     add_filter('mce_external_plugins', 'ct_add_youtube_tinymce_plugin');
	     add_filter('mce_buttons', 'ct_register_youtube_button');
	   }
	}

	function ct_register_youtube_button($buttons) {
	   array_push($buttons, "|", "ct_youtube_button");
	   return $buttons;
	}

	// Load the TinyMCE plugin : editor_plugin.js (wp2.5)
	function ct_add_youtube_tinymce_plugin($plugin_array) {
	   $plugin_array['ct_youtube_button'] = WP_THEME_DIR . '/lib/admin/scripts/editor_plugin.js';
	   return $plugin_array;
	}

	function ct_youtube_refresh_mce($ver) {
	  $ver += 3;
	  return $ver;
	}

	add_filter('tiny_mce_version', 'ct_youtube_refresh_mce');
	add_action('init', 'ct_youtube_shortcode_button');
}


// Add the shortcode handler for Vimeo videos
if(!function_exists('ct_vimeo_shortcode')) {
	function ct_vimeo_shortcode($atts, $content = null) {

		$theme_options = get_option('ct_theme_options');
		$ct_main_color = $theme_options['main_color'];
		$ct_main_color = str_replace('#', '', $ct_main_color);
		if(empty($ct_main_color)): $ct_main_color = '00adef'; endif;

		extract( shortcode_atts(
			array(
				"id" => '',
				"width" => '608',
				"height" => '342',
				"title" => 'false',
				"byline" => 'false',
				"portrait" => 'false',
				"color" => $ct_main_color
			),
			$atts
		));

		$title = ( $title == 'true' ) ? 1 : 0;
		$byline = ( $byline == 'true' ) ? 1 : 0;
		$portrait = ( $portrait == 'true' ) ? 1 : 0;

		return '<div class="video_player"><iframe src="http://player.vimeo.com/video/'.esc_attr($id).'?title='.esc_attr($title).'&amp;byline='.esc_attr($byline).'&amp;portrait='.esc_attr($portrait).'&amp;color='.esc_attr($color).'" width="'.intval($width).'" height="'.intval($height).'" frameborder="0"></iframe></div>';
	}
	add_shortcode('vimeo', 'ct_vimeo_shortcode');

	function ct_add_vimeo_shortcode_button() {
		// Don't bother doing this stuff if the current user lacks permissions
		if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
			return;

		// Add only in Rich Editor mode
		if ( get_user_option('rich_editing') == 'true') {
			add_filter('mce_external_plugins', 'ct_add_vimeo_tinymce_plugin');
			add_filter('mce_buttons', 'ct_register_vimeo_button');
		}
	}

	function ct_register_vimeo_button($buttons) {
		array_push($buttons, "|", "ct_vimeo_button");
		return $buttons;
	}

	// Load the TinyMCE plugin : editor_plugin.js (wp2.5)
	function ct_add_vimeo_tinymce_plugin($plugin_array) {
		$plugin_array['ct_vimeo_button'] = WP_THEME_DIR . '/lib/admin/scripts/editor_plugin.js';
		return $plugin_array;
	}

	function ct_vimeo_refresh_mce($ver) {
		$ver += 3;
		return $ver;
	}

	// init process for button control
	add_filter('tiny_mce_version', 'ct_vimeo_refresh_mce');
	add_action('init', 'ct_add_vimeo_shortcode_button');
}


// CSS3 Button shortcode
if(!function_exists('ct_css3_button_shortcode')) {
	function ct_css3_button_shortcode($atts, $content = null) {
		extract(shortcode_atts(
			array(
				'text' => 'menu_order',
				'url' => '',
				'target' => '_self',
				'title' => '',
				'rel' => '',
			), $atts));
		return "<p><a href=\"$url\" class=\"button\" target=\"$target\">$text</a></p>";
	}
	add_shortcode('button', 'ct_css3_button_shortcode');
}


// Build an array of meta values from all posts in a specified post type
function churchthemes_get_meta_values( $key = null, $type = null, $status = null ) {
	global $wpdb;
	if ( !$key ) {
		return;
	}
	$meta_values = $wpdb->get_col( $wpdb->prepare( "
		SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
		LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
		WHERE pm.meta_key = '%s'
		AND p.post_type = '%s'
		AND p.post_status = '%s'
	", $key, $type, $status ) );
	return $meta_values;
}


// Add more Appearance options to the Admin Bar
function churchthemes_extend_admin_bar() {
	global $wp_admin_bar, $wpdb;

	if (!is_super_admin() || !is_admin_bar_showing())
		return;

	$wp_admin_bar->add_menu(
		array(
			'parent' => 'site-name',
			'title' => __('Theme Options', 'churchthemes'),
			'id' => 'theme-options',
			'href' => home_url('/wp-admin/themes.php?page=theme-options')
		)
	);
	$wp_admin_bar->add_menu(
		array(
			'parent' => 'site-name',
			'title' => __('Social Footer', 'churchthemes'),
			'id' => 'social-footer',
			'href' => home_url('/wp-admin/themes.php?page=social-footer')
		)
	);
	$wp_admin_bar->add_menu(
		array(
			'parent' => 'site-name',
			'title' => __('Sidebars', 'churchthemes'),
			'id' => 'sidebars',
			'href' => home_url('/wp-admin/themes.php?page=sidebars')
		)
	);
}
add_action('admin_bar_menu', 'churchthemes_extend_admin_bar', 1000);
