<?php
add_action('after_setup_theme', 'uncode_language_setup');
function uncode_language_setup()
{
	load_child_theme_textdomain('uncode', get_stylesheet_directory() . '/languages');
}

function theme_enqueue_styles()
{
	$production_mode = ot_get_option('_uncode_production');
	$resources_version = ($production_mode === 'on') ? null : rand();
	if ( function_exists('get_rocket_option') && ( get_rocket_option( 'remove_query_strings' ) || get_rocket_option( 'minify_css' ) || get_rocket_option( 'minify_js' ) ) ) {
		$resources_version = null;
	}
	$parent_style = 'uncode-style';
	$child_style = array('uncode-style');
	wp_enqueue_style($parent_style, get_template_directory_uri() . '/library/css/style.css', array(), $resources_version);
	wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', $child_style, $resources_version);
	
	if ( is_category( 'results' ) ) {
		wp_enqueue_script('jquery-ui-datepicker');
		wp_enqueue_style('jquery-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css');
	}
	
}
add_action('wp_enqueue_scripts', 'theme_enqueue_styles', 100);



if ( function_exists( 'vc_disable_frontend' ) ) {
	vc_disable_frontend();
}

function custom_post_type() {
	
// Tournaments custom post type
	$labels = array(
		'name'                => _x( 'Tournaments', 'Post Type General Name', 'twentythirteen' ),
		'singular_name'       => _x( 'Tournaments', 'Post Type Singular Name', 'twentythirteen' ),
		'menu_name'           => __( 'Tournaments', 'twentythirteen' ),
		'parent_item_colon'   => __( 'Parent Tournaments', 'twentythirteen' ),
		'all_items'           => __( 'All Tournaments', 'twentythirteen' ),
		'view_item'           => __( 'View Tournament', 'twentythirteen' ),
		'add_new_item'        => __( 'Add New Tournament', 'twentythirteen' ),
		'add_new'             => __( 'Add New', 'twentythirteen' ),
		'edit_item'           => __( 'Edit Tournament', 'twentythirteen' ),
		'update_item'         => __( 'Update Tournament', 'twentythirteen' ),
		'search_items'        => __( 'Search Tournament', 'twentythirteen' ),
		'not_found'           => __( 'Not Found', 'twentythirteen' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),

	);
	
	$args = array(
		'label'               => __( 'tournaments', 'twentythirteen' ),
		'description'         => __( 'Tournaments', 'twentythirteen' ),
		'labels'              => $labels,
		'supports'            => array( 'title', 'thumbnail', ),
		'hierarchical'        => false,
		'menu_icon'           => 'dashicons-star-filled',
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
	);
	
	register_post_type( 'tournaments', $args );
}

// Lakes custom post type
	$labels = array(
		'name'                => _x( 'Lakes', 'Post Type General Name', 'twentythirteen' ),
		'singular_name'       => _x( 'Lake', 'Post Type Singular Name', 'twentythirteen' ),
		'menu_name'           => __( 'Lakes', 'twentythirteen' ),
		'parent_item_colon'   => __( 'Parent Lake', 'twentythirteen' ),
		'all_items'           => __( 'All Lakes', 'twentythirteen' ),
		'view_item'           => __( 'View Lake', 'twentythirteen' ),
		'add_new_item'        => __( 'Add New Lake', 'twentythirteen' ),
		'add_new'             => __( 'Add New', 'twentythirteen' ),
		'edit_item'           => __( 'Edit Lake', 'twentythirteen' ),
		'update_item'         => __( 'Update Lake', 'twentythirteen' ),
		'search_items'        => __( 'Search Lake', 'twentythirteen' ),
		'not_found'           => __( 'Not Found', 'twentythirteen' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),

	);
	
	$args = array(
		'label'               => __( 'lake', 'twentythirteen' ),
		'description'         => __( 'Lake news and details', 'twentythirteen' ),
		'labels'              => $labels,
		'supports'            => array( 'title', 'thumbnail', ),
		'hierarchical'        => false,
		'menu_icon'           => 'dashicons-location-alt',
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
	);
	
	register_post_type( 'lakes', $args );


// Lake Listings custom post type
	$labels = array(
		'name'                => _x( 'Lake Listings', 'Post Type General Name', 'twentythirteen' ),
		'singular_name'       => _x( 'Listing', 'Post Type Singular Name', 'twentythirteen' ),
		'menu_name'           => __( 'Lake Guide', 'twentythirteen' ),
		'parent_item_colon'   => __( 'Parent Listings', 'twentythirteen' ),
		'all_items'           => __( 'All Listings', 'twentythirteen' ),
		'view_item'           => __( 'View Listing', 'twentythirteen' ),
		'add_new_item'        => __( 'Add New Listings', 'twentythirteen' ),
		'add_new'             => __( 'Add New', 'twentythirteen' ),
		'edit_item'           => __( 'Edit Listings', 'twentythirteen' ),
		'update_item'         => __( 'Update Listings', 'twentythirteen' ),
		'search_items'        => __( 'Search Lake Listings', 'twentythirteen' ),
		'not_found'           => __( 'Not Found', 'twentythirteen' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),

	);
	
	$args = array(
		'label'               => __( 'listing', 'twentythirteen' ),
		'description'         => __( 'Lake Guide Listings', 'twentythirteen' ),
		'labels'              => $labels,
		'supports'            => array( 'title', 'thumbnail', ),
		'hierarchical'        => false,
		'menu_icon'           => 'dashicons-book-alt',
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
	);
	
	register_post_type( 'listings', $args );


// Lake Landings custom post type
	$labels = array(
		'name'                => _x( 'Landings', 'Post Type General Name', 'twentythirteen' ),
		'singular_name'       => _x( 'Landing', 'Post Type Singular Name', 'twentythirteen' ),
		'menu_name'           => __( 'Landings', 'twentythirteen' ),
		'parent_item_colon'   => __( 'Parent Landings', 'twentythirteen' ),
		'all_items'           => __( 'All Landings', 'twentythirteen' ),
		'view_item'           => __( 'View Landing', 'twentythirteen' ),
		'add_new_item'        => __( 'Add New Landing', 'twentythirteen' ),
		'add_new'             => __( 'Add New', 'twentythirteen' ),
		'edit_item'           => __( 'Edit Landing', 'twentythirteen' ),
		'update_item'         => __( 'Update Landing', 'twentythirteen' ),
		'search_items'        => __( 'Search Landing', 'twentythirteen' ),
		'not_found'           => __( 'Not Found', 'twentythirteen' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),

	);
	
	$args = array(
		'label'               => __( 'landing', 'twentythirteen' ),
		'description'         => __( 'Lake Landings news and details', 'twentythirteen' ),
		'labels'              => $labels,
		'supports'            => array( 'title', 'thumbnail', ),
		'hierarchical'        => false,
		'menu_icon'           => 'dashicons-flag',
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
	);
	
	register_post_type( 'landings', $args );

// Trails custom post type
	$labels = array(
		'name'                => _x( 'Trails', 'Post Type General Name', 'twentythirteen' ),
		'singular_name'       => _x( 'Trails', 'Post Type Singular Name', 'twentythirteen' ),
		'menu_name'           => __( 'Trails', 'twentythirteen' ),
		'parent_item_colon'   => __( 'Parent Trails', 'twentythirteen' ),
		'all_items'           => __( 'All Trails', 'twentythirteen' ),
		'view_item'           => __( 'View Trail', 'twentythirteen' ),
		'add_new_item'        => __( 'Add New Trail', 'twentythirteen' ),
		'add_new'             => __( 'Add New', 'twentythirteen' ),
		'edit_item'           => __( 'Edit Trail', 'twentythirteen' ),
		'update_item'         => __( 'Update Trail', 'twentythirteen' ),
		'search_items'        => __( 'Search Trail', 'twentythirteen' ),
		'not_found'           => __( 'Not Found', 'twentythirteen' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),

	);
	
	$args = array(
		'label'               => __( 'trails', 'twentythirteen' ),
		'description'         => __( 'Trails details', 'twentythirteen' ),
		'labels'              => $labels,
		'supports'            => array( 'title', 'thumbnail', ),
		'hierarchical'        => false,
		'menu_icon'           => 'dashicons-palmtree',
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
	);
	
	register_post_type( 'trails', $args );



/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/

add_action( 'init', 'custom_post_type', 0 );


// Google Maps API Key
function my_acf_google_map_api( $api ){
	
	$api['key'] = ot_get_option('_uncode_gmaps_api');
	
	return $api;
	
}

add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');

// Enqueue google-maps.js
add_action( 'wp_enqueue_scripts', 'my_theme_add_scripts' );
function my_theme_add_scripts() {
	
	if ( is_post_type_archive( 'lakes' ) ) {
		wp_enqueue_script( 'google-map-cluster', get_stylesheet_directory_uri() . '/js/markerclustererplus.min.js', array('jquery'), null, true );
	}
	wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key='. ot_get_option('_uncode_gmaps_api'), array( 'jquery' ), 3, true );
	wp_enqueue_script( 'google-map-init', get_stylesheet_directory_uri() . '/google-maps.js', array('google-map', 'jquery'), 'v0.1.1', true );


	if ( is_singular( 'tournaments' ) ) {
		wp_enqueue_script( 'ical_dep_js', get_stylesheet_directory_uri() . '/js/ics.deps.min.js', array( 'jquery' ), null, true );
		wp_enqueue_script( 'ical_js', get_stylesheet_directory_uri() . '/js/ics.min.js', array( 'ical_dep_js', 'jquery' ), null, true );
	}

	// Only enqueue the navionics API if we're on the lakes page
	// if ( is_singular( 'lakes' ) || is_singular( 'tournaments' ) ) {
		wp_enqueue_script( 'navionics-web-api', '//webapiv2.navionics.com/dist/webapi/webapi.min.no-dep.js', array( 'google-map' ), null, true );

		// Store the API key in a global variable that we can access in google-maps.js
		wp_localize_script( 'navionics-web-api', 'acnl_maps', array(
			'navionics' => get_option( 'acnl_navionics_api_key' ),
		) );

		wp_enqueue_style( 'navionics-web-api', '//webapiv2.navionics.com/dist/webapi/webapi.min.css', array() );
	// }
}

add_filter('script_loader_tag', 'anglers_add_async_defer_attribute', 10, 2);
function anglers_add_async_defer_attribute($tag, $handle) {
	if ( 'google-map' !== $handle ) {
		return $tag;
	}
	return str_replace( ' src', ' async defer src', $tag );
}
 


// State Select field for Advanced Custom Fields
function acnl_populate_state_select( $field ) {
    // reset choices
    $field['choices'] = array(
	    'AL'=>"AL",  
		'AK'=>"AK",  
		'AZ'=>"AZ",  
		'AR'=>"AR",  
		'CA'=>"CA",  
		'CO'=>"CO",  
		'CT'=>"CT",  
		'DE'=>"DE",  
		'DC'=>"DC",  
		'FL'=>"FL",  
		'GA'=>"GA",  
		'HI'=>"HI",  
		'ID'=>"ID",  
		'IL'=>"IL",  
		'IN'=>"IN",  
		'IA'=>"IA",  
		'KS'=>"KS",  
		'KY'=>"KY",  
		'LA'=>"LA",  
		'ME'=>"ME",  
		'MD'=>"MD",  
		'MA'=>"MA",  
		'MI'=>"MI",  
		'MN'=>"MN",  
		'MS'=>"MS",  
		'MO'=>"MO",  
		'MT'=>"MT",
		'NE'=>"NE",
		'NV'=>"NV",
		'NH'=>"NH",
		'NJ'=>"NJ",
		'NM'=>"NM",
		'NY'=>"NY",
		'NC'=>"NC",
		'ND'=>"ND",
		'OH'=>"OH",  
		'OK'=>"OK",  
		'OR'=>"OR",  
		'PA'=>"PA",  
		'RI'=>"RI",  
		'SC'=>"SC",  
		'SD'=>"SD",
		'TN'=>"TN",  
		'TX'=>"TX",  
		'UT'=>"UT",  
		'VT'=>"VT",  
		'VA'=>"VA",  
		'WA'=>"WA",  
		'WV'=>"WV",  
		'WI'=>"WI",  
		'WY'=>"WY"
	);

    // return the field
    return $field;
}

add_filter('acf/load_field/name=state', 'acnl_populate_state_select');

// Initialize a setting for storing the Navionics API key
function acnl_initialize_customizer_settings( $wp_customize ) {
	$wp_customize->add_setting( 'acnl_navionics_api_key', array(
		'default'   => '',
		'type'      => 'option',
	) );

	$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'acnl_navionics_api_key_control', array(
		'label'      => 'Navionics API Key',
		'priority'   => 100,
		'section'    => 'title_tagline',
		'settings'   => 'acnl_navionics_api_key',
	) ) );
}
add_action( 'customize_register', 'acnl_initialize_customizer_settings', 12 );




function titlechange($thetitle){
	$return=str_replace(array('Flw','Bfl', 'Abt', 'flw', 'b.a.s.s'),array('FLW','BFL', 'ABT', 'FLW', 'B.A.S.S'),$thetitle);
	return $return;
}

function well_delete_post_type(){
    unregister_post_type( 'portfolio' );
    unregister_post_type( 'uncode_gallery' );    
    
}
add_action('init','well_delete_post_type');

add_filter( 'gform_submit_button', 'form_submit_button', 10, 2 );
function form_submit_button($button, $form) {
    return '<input type="submit" class="custom-link btn border-width-0 btn-color-136494 btn-icon-left" id="gform_submit_button_' . $form['id'] . '" value="' . $form['button']['text'] . '">';
}


add_action( 'wp_ajax_be_ajax_load_more', 'be_ajax_load_more' );
add_action( 'wp_ajax_nopriv_be_ajax_load_more', 'be_ajax_load_more' );
function be_ajax_load_more() {
	check_ajax_referer( 'be-load-more-nonce', 'nonce' );
	if(isset($_POST['gparma']) && !empty($_POST['gparma'])) {
		$arrGet = json_decode(stripslashes($_POST['gparma']),true);
		foreach( $arrGet as $index => $get_value ) {
			$_GET[$index] = $get_value;
		}
	}

/****** TRAILS CUSTOM PAGE ************/

if ( isset( $_POST[ 'query' ][ 'pagename' ] ) && $_POST[ 'query' ][ 'pagename' ] == 'trails-list' ) {
	
	$args = array(
		'numberposts'		=> -1,
		'post_type'			=> 'trails',
		'paged' 			=> $_POST[ 'page' ],
		'posts_per_page'	=> 35,
		'orderby'    		=> 'post_title',
		'order' 			=> 'ASC'
	);
	if ( isset( $_GET[ 'search_trail' ] )  && $_GET[ 'search_trail' ]!="" ) {
		
		$args['s']	= esc_sql( $_GET[ 'search_trail' ] );
	}
	
	if( isset( $_GET[ 'bystate' ] ) && $_GET[ 'bystate' ]!="" ) {
		$args['meta_query'][] = array(
			'key'		=> 'state',
			'value'   => esc_sql( $_GET[ 'bystate' ] ),
			'compare' => '=',
		);
	}
	
	
	if( isset( $_GET[ 'starts_with' ] ) && $_GET[ 'starts_with' ]!="" ) {
		$args['starts_with'] = esc_sql( $_GET[ 'starts_with' ] );
	}
	
	$trails = new WP_Query( $args );
	if ($trails->have_posts()) { 
		while ($trails->have_posts()) { 
			$trails->the_post();
			$alternate_names= get_post_meta( get_the_ID(),'alternate_names');
			$state= strtoupper( get_field('state') );
		
	?>

    <div class="drow">
        <div class="dcell">
            <a href="<?php the_permalink();?>"><?php echo titlechange(get_the_title());?></a>
            <br /><span class="post_info_date"><?php echo $alternate_names[0]; ?> </span>
        </div>
        <div class="dcell">
            <span class="post_info_date"><?php echo ( !empty( $state )  && $state != 'NULL' ? $state : '' ); ?> </span>
        </div>
    </div>
    <?php 
		}
	}	
	
	wp_die();
	
}



/************* ************/
	
if($_POST['query']['post_type'] == 'tournaments'){

	$args = array(
		'numberposts'	=> -1,
		'post_type'		=> 'tournaments',
		'paged' => $_POST['page'],
		'posts_per_page'=>35
	);
	$datesort =  "";
	$trail = "";
	$state = "";
	$lake="";
	if(isset($_GET['bytrails']) && $_GET['bytrails']!=""){
	$trail = $_GET['bytrails'];
	}
	if(isset($_GET['bystate']) && $_GET['bystate']!=""){
	$state = $_GET['bystate'];
	}
	if(isset($_GET['bylake']) && $_GET['bylake']!=""){
	$lake = $_GET['bylake'];
	}
/*
	if(isset($_GET['datesort']) && $_GET['datesort']!=""){
		$datesort = $_GET['datesort'];
		$year_month = explode('-',$_GET['datesort']);
		$args['date_query'] = array(
			array(
				'year'  => $year_month[0],
				'month' => $year_month[1],
			)
		);

	}*/

	$args['meta_query']	= array(
			'relation'		=> 'and',
			array(
				'key'		=> 'trail',
				'value'		=> $trail,
				'compare'	=> 'LIKE'
			),
			array(
				'key'		=> 'state',
				'value'		=> $state,
				'compare'	=> 'LIKE'
			),
			array(
				'key'		=> 'lake',
				'value'		=> $lake,
				'compare'	=> 'LIKE'
			)
		);
		$args['meta_key'] = 'from_date';
		$args['orderby'] =  'meta_value+0';
		$args['order'] = 'ASC';
		
		/*************** If view Range Set *******************/
		if(isset($_GET['datesort']) && !empty($_GET['datesort']) && strtolower($_GET['datesort']) != 'date'){
			$datesort = $_GET['datesort'];
			$year_month = explode('-',$_GET['datesort']);
			
			/*
			$args['date_query'] = array(
				array(
					'year'  => $year_month[0],
					'month' => $year_month[1],
				)
			);
			*/
			$Current_date = date($year_month[0]."-".$year_month[1]."-01");	//Current date...
			$date = strtotime($Current_date);
			$next_month_date = date($year_month[0].'-'.$year_month[1].'-'.date('t',$date));
			
			$start_date = $Current_date;	//Current Month Date...
			$end_date = $next_month_date;	// Next Month
			
			$args['meta_query'][]= array(
					'key'		=> 'from_date',
					'value'		=> array($start_date, $end_date),
					'compare'	=> 'BETWEEN',
					'type' => 'DATE' 
				);

		} else if(isset($_GET['view']) && $_GET['view'] =="weekly") {
			
			$Current_date = date("Y-m-d");	//Current date...
			$week_number = get_week_number($Current_date);	//Get week number from the date...
			$year = date("Y",strtotime($Current_date));	// date year...
			$start_date_end_date = getStartAndEndDate($week_number,$year);
			
			
			$start_date = date("Y-m-d",strtotime($start_date_end_date[0]));	//Week Start Date...
			$end_date = date("Y-m-d",strtotime($start_date_end_date[1]));	//Week end date....
			
			$args['meta_query'][]= array(
					'key'		=> 'from_date',
					'value'		=> array($start_date, $end_date),
					'compare'	=> 'BETWEEN',
					'type' => 'DATE' 
				);
				$args['order'] = 'ASC';
		} else if(isset($_GET['view']) && $_GET['view'] =="monthly") {
			$Current_date = date("Y-m-d");	//Current date...
			$date = strtotime($Current_date);
			$next_month_date = date('Y-m-d', strtotime('+1 months'));
			
			$start_date = $Current_date;	//Current Month Date...
			$end_date = $next_month_date;	// Next Month
			
			$args['meta_query'][]= array(
					'key'		=> 'from_date',
					'value'		=> array($start_date, $end_date),
					'compare'	=> 'BETWEEN',
					'type' => 'DATE' 
				);
				$args['order'] = 'ASC';
		} else if( (isset($_GET['view']) && $_GET['view'] =="upcoming") || !isset($_GET['view']) ) {
			$Current_date = date("Y-m-d");	//Current date...
			$args['meta_query'][]= array(
					'key'		=> 'from_date',
					'value'		=> $Current_date,
					'compare'	=> '>=',
					'type' => 'DATE' 
				);
				$args['order'] = 'ASC';
		}
		
		// make sure that the date is set
		$args['meta_query'][]= array(
			'key'		=> 'from_date',
			'compare'	=> 'EXISTS',
		);
	$args['meta_query'][]= array(
			'key'		=> 'from_date',
			'value'		=> '',
			'compare'	=> '!=',
		);
		
		/****************************************/
		
		
		// query
		$tournaments = new WP_Query( $args );
		
		$layouts = array( 'upcoming', 'monthly', 'day' );
		$layout = 'upcoming';
		if ( isset( $_GET['layout'] ) && in_array( esc_attr( $_GET['layout'] ), $layouts ) ) {
			$layout = esc_attr( $_GET['layout'] );
		}
		
		if ($tournaments->have_posts()) {
		
			$checkmonth = $_POST['lastmonth'];
		
			while ($tournaments->have_posts()) {
				$tournaments->the_post();
				$from_date= get_post_meta(get_the_ID(),'from_date',true);
				$to_date= get_post_meta(get_the_ID(),'to_date',true);
				$tournamentsID = get_the_ID();
				
				
				include( locate_template( 'templates/tournaments-'. $layout .'.php' ) );

		
			}
		}
	
	}elseif($_POST['query']['post_type'] == 'trails'){
		
        $args = array(
		'numberposts'	=> -1,
		'post_type'		=> 'trails',
		'paged' => $_POST['page'],
		'posts_per_page'=>35,
		'orderby'    => 'post_title',
		'order' => 'asc'
	);
	$lakes = new WP_Query( $args );
	//if (have_posts()) : while (have_posts()) : the_post();
	if ($lakes->have_posts()) : while ($lakes->have_posts()) : $lakes->the_post();
	$TheID = get_the_ID();
	$state= get_post_meta( get_the_ID(),'state');
	
	//print_r($alternate_names);
	  //$state = get_field('state');
//print_r($state.get_field('state'));
	?>

    <div class="drow">
        <div class="dcell">
            <p><a href="<?php the_permalink();?>"><?php the_title();?></a></p>
        </div>
       <div class="dcell">
            <p class="txt"><?php  
			echo ( !empty( $state[0] && $state[0] != 'null' ) ? $state[0] : '' );
			?></p>
        </div>
        
    </div>
    <?php endwhile; endif; ?>
        
  <?php 		
	}elseif($_POST['query']['post_type'] == 'lakes') {
			
		$search_filter = false;
		$state = "";
		$filter_lake_name = "";
		$filter_lake_type = "";
		if(isset($_GET['bystate']) && $_GET['bystate']!=""){
			$state = $_GET['bystate'];
			$search_filter = true;
		}
		if(isset($_GET['filter_lake_name']) && $_GET['filter_lake_name']!=""){
			$filter_lake_name = $_GET['filter_lake_name'];
			//$search_filter = true;
		}
		if(isset($_GET['filter_lake_type']) && $_GET['filter_lake_type']!=""){
			$filter_lake_type = $_GET['filter_lake_type'];
			$search_filter = true;
		}
		 $args = array(
			'numberposts'		=> -1,
			'post_type'			=> 'lakes',
			'paged' 			=> $_POST['page'],
			'posts_per_page'	=> 35,
			'orderby'    		=> 'post_title',
			'order' 			=> 'asc'
		);
		
		if($search_filter == true) {
			$args['meta_query']	= array(
				'relation'		=> 'and',
			);
			if(!empty($state)) {
				$args['tax_query'][] = array(
					'taxonomy'	=> 'state',
					'terms'		=> $state,
					'field'		=> 'slug'
				);
			}
			if(!empty($filter_lake_type)) {
				$args['meta_query'][] = array(
					'key'		=> 'lake_type',
					'value'		=> $filter_lake_type,
					'compare'	=> 'LIKE'
				);
			}
		}
		if(!empty($filter_lake_name)) {
			return '';
			$args['page_id'] = $filter_lake_name;
		}		
		
		$lakes = new WP_Query( $args );
		//if (have_posts()) : while (have_posts()) : the_post();
		if ($lakes->have_posts()) : while ($lakes->have_posts()) : $lakes->the_post();
		$alternate_names= get_post_meta( get_the_ID(),'alternate_names');
		$lake_type= get_post_meta( get_the_ID(),'lake_type');
		$lake_type= get_post_meta( get_the_ID(),'lake_type');
		$full_pool= get_post_meta( get_the_ID(),'full_pool');
		$size= get_post_meta( get_the_ID(),'size');
		// $state= get_post_meta( get_the_ID(),'state');
		$state= strtoupper( get_term( get_field('state') )->slug );
		
		
		//print_r($alternate_names);
		  //$state = get_field('state');
	//print_r($state.get_field('state'));
		?>

		<div class="drow">
			<div class="dcell">
				<a href="<?php the_permalink();?>"><?php the_title();?></a>
				<br /><span class="post_info_date"><?php echo $alternate_names[0]; ?> </span>
			</div>
			<div class="dcell">
				<?php  echo $lake_type[0];?><br /><span class="post_info_date"><?php echo $state; ?> </span>
			</div>
			<div class="dcell">
				<?php  echo $size[0];?><br /><span class="post_info_date"><?php echo $full_pool[0]; ?> </span>
			</div>
			
		</div>
		<?php endwhile; endif; ?>
			
	  <?php 		
	}
	wp_die();
}

add_action( 'wp_enqueue_scripts', 'be_load_more_js' );
function be_load_more_js() {
	
	if ( !( is_post_type_archive( 'tournaments' ) || is_post_type_archive( 'lakes' ) || is_post_type_archive( 'trails' ) || is_page( 'trails-list' ) ) ) {
		return;
	}
	
	global $wp_query;
	$args = array(
		'nonce' => wp_create_nonce( 'be-load-more-nonce' ),
		'url'   => admin_url( 'admin-ajax.php' ),
		'loader' => '<div class="dynamic_loader load-more"><img style="left:0px; right:0px; margin:10px auto; position:absolute;" class="load-more-iamges" src="'. get_stylesheet_directory_uri().'/img/ajax-loader.gif' .'"></div>',
		'query' => $wp_query->query,
		'gparma' => COUNT($_GET) ? json_encode($_GET) : ''
	);
			
	wp_enqueue_script( 'be-load-more', get_stylesheet_directory_uri() . '/js/load-more.js', array( 'jquery' ), '1.0.1', true );
	wp_localize_script( 'be-load-more', 'beloadmore', $args );
	
}


// disable social links on the right of the primary menu
add_filter( 'uncode_socials_active', '__return_false' );

add_filter( 'option_uncode', 'anglers_option_uncode' );
function anglers_option_uncode( $option ) {

	
	$socials = $option['_uncode_social_list'];
	$social_html_inner = '';
	
	if (!empty($socials)) {
		foreach ($socials as $social) {
			if (isset($social['_uncode_menu_hidden']) && $social['_uncode_menu_hidden'] === 'on' || $social['_uncode_social'] === '') {
				continue;
			}
			$social_html_inner .= '<li class="menu-item-link social-icon tablet-hidden mobile-hidden '.$social['_uncode_social_unique_id'].'"><a href="'.$social['_uncode_link'].'" class="social-menu-link" target="_blank"><i class="'.$social['_uncode_social'].'"></i></a></li>';
		}
	}
	
	$social_out = '<ul class="anglers_social menu-smart'.(is_rtl() ? ' sm-rtl' : '').' sm menu-icons menu-smart-social">';
	$social_out .= $social_html_inner;
	$social_out .= '</ul>';
	
	$option['_uncode_menu_bloginfo'] =  $social_out;
	
	return $option;
}

add_shortcode( 'lakemap', 'lakemap_func' );
function lakemap_func( $atts ) {
	$a = shortcode_atts( array(
		'slug' => '',
		'id' => 0,
	), $atts );
	
	
	if ( intval( $a['id'] ) == 0 && isset( $a['slug'] ) && $a['slug'] != '' ) {
	
		if ( $lake_post = get_page_by_path( $a['slug'], OBJECT, 'lakes' ) ) {
			
			$a['id'] = $lake_post->ID;
			
		}
		
	}
	
	if ( intval( $a['id'] ) == 0 ) {
		return;
	}
	
	$post_id = $a['id'];
	
	
	ob_start();
	?>
	<div class="custom_fields clear clearfix">				
	<?php 
		$location = get_field('google_map', $post_id );
		
		if( !empty($location) ) {
		?>
	<div class="acf-map acf-map-navionics" data-lat="<?php  echo $location['lat']; ?>" data-lng="<?php  echo $location['lng']; ?>">
	</div>
	<?php  
		} 
		
		$alternate_name = get_field('alternate_names', $post_id);
		$full_pool = get_field('full_pool', $post_id);
		$lake_type = get_field('lake_type', $post_id);
		$size = get_field('size', $post_id);
		$state = get_field('state', $post_id);
		$description = get_field('description', $post_id);
		$lake_logo = get_field('lake_logo', $post_id);
		$lakeName  = get_the_title( $post_id );
		?> 
	 <div class="extra_fields">
		 <h1><?php  echo $lakeName; ?></h1>
		 <div class="main_extra_wrap <?php echo ( !empty($lake_logo) ? 'has_logo' : ''); ?>">
	<?php  if(!empty($alternate_name)){ ?>
			<div class="extra_field"><strong>Alternate Name:&nbsp;</strong> <?php  echo $alternate_name; ?> </div>
	<?php  } ?>
	<?php  if(!empty($full_pool)){ ?>
			<div class="extra_field"><strong>Full Pool:&nbsp;</strong> <?php  echo $full_pool ; ?></div>
	<?php  } ?>  
	<?php  if(!empty($state)){ ?>
			<div class="extra_field"><strong>State:&nbsp;</strong> <?php  echo $state ; ?></div> 
	<?php }
		
		if(!empty($lake_type)){
			?><div class="extra_field"><strong>Full Type:&nbsp;</strong> <?php  echo $lake_type ; ?></div><?php 
		}

		
		if(!empty($size)){
			?> <div class="extra_field"><strong>Size: &nbsp;</strong><?php  echo $size ; ?></div><?php  } ?>
			<?php  if(!empty($description)){ ?>
				<div class="description_txt">
				<?php  echo  $description; ?>
				</div>
				<?php  } ?>
		</div>
		<?php  if(!empty($lake_logo)){ ?>
			<div class="extra_field lake_logo"><img src="<?php  echo $lake_logo['sizes']['medium']; ?>" width="<?php  echo $lake_logo['sizes']['medium-width']; ?>" height="<?php  echo $lake_logo['sizes']['medium-height']; ?>" /></div>
		<?php } ?>
		</div>
	 </div>
	
	
	<?php
	$out = ob_get_clean();
	
	return $out;
}



// Register Custom Taxonomy
add_action( 'init', 'states_taxonomy', 0 );
function states_taxonomy() {

	$labels = array(
		'name'                       => _x( 'US States', 'Taxonomy General Name', 'text_domain' ),
		'singular_name'              => _x( 'US State', 'Taxonomy Singular Name', 'text_domain' ),
		'menu_name'                  => __( 'US States', 'text_domain' ),
		'all_items'                  => __( 'All Items', 'text_domain' ),
		'parent_item'                => __( 'Parent Item', 'text_domain' ),
		'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
		'new_item_name'              => __( 'New Item Name', 'text_domain' ),
		'add_new_item'               => __( 'Add New Item', 'text_domain' ),
		'edit_item'                  => __( 'Edit Item', 'text_domain' ),
		'update_item'                => __( 'Update Item', 'text_domain' ),
		'view_item'                  => __( 'View Item', 'text_domain' ),
		'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
		'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
		'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
		'popular_items'              => __( 'Popular Items', 'text_domain' ),
		'search_items'               => __( 'Search Items', 'text_domain' ),
		'not_found'                  => __( 'Not Found', 'text_domain' ),
		'no_terms'                   => __( 'No items', 'text_domain' ),
		'items_list'                 => __( 'Items list', 'text_domain' ),
		'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
	);
	$args = array(
		'labels'                     => $labels,
		'hierarchical'               => true,
		'public'                     => true,
		'show_ui'                    => true,
		'show_admin_column'          => true,
		'show_in_nav_menus'          => false,
		'show_tagcloud'              => false,
		'show_in_quick_edit'         => false,
		'meta_box_cb'                => false,
	);
	register_taxonomy( 'state', array( 'lakes' ), $args );

}

add_filter( 'the_content', 'anglers_insert_post_ads' );
function anglers_insert_post_ads( $content ) {
	global $post;
	
	if ( !is_single() || is_admin() || get_post_type( $post ) != 'post' ) {
		return $content;
	}
  
	$ad_code = '<div class="anglers_post_ad">'. adrotate_group(3) .'</div>';

	$my_content = explode('</p>', $content);
	if ( isset( $my_content[2] ) ) {
		$my_content[2] .= $ad_code;
		return implode('</p>', $my_content);
	} else {
		return $content.$ad_code;
	}
	
	return $content;

}

add_action('admin_footer', 'anglers_admin_inline_js', PHP_INT_MAX);
function anglers_admin_inline_js() {
	if ( isset( $_GET[ 'page' ] ) && 'anglers-bulk-tournaments' == esc_attr( $_GET[ 'page' ] ) ) {
    ?>
    <script>
		jQuery( document ).ready( function( $ ) {
			$( document ).on( 'change', 'td[data-name="from_date"] input.hasDatepicker', function () {
				
				var $row = $( this ).closest( '.acf-row' );
				var $to_date_val = $row.find( 'td[data-name="to_date"] input.hasDatepicker' ).val();
				if ( $to_date_val == '' ) {
					
					$row.find( 'td[data-name="to_date"] input.hasDatepicker' ).val( $row.find( 'td[data-name="from_date"] input.hasDatepicker' ).val() );
					$row.find( 'td[data-name="to_date"] input[type="hidden"]' ).val( $row.find( 'td[data-name="from_date"] input[type="hidden"]' ).val() );
					$row.find( 'td[data-name="to_date"] input[type="hidden"]' ).attr( 'value', $row.find( 'td[data-name="from_date"] input[type="hidden"]' ).val() );
				}
				
			});
			$( document ).on( 'change', 'td[data-name="to_date"] input.hasDatepicker', function () {
				
				var $row = $( this ).closest( '.acf-row' );
				var $from_date_val = $row.find( 'td[data-name="from_date"] input.hasDatepicker' ).val();
				if ( $from_date_val == '' ) {
					
					$row.find( 'td[data-name="from_date"] input.hasDatepicker' ).val( $row.find( 'td[data-name="to_date"] input.hasDatepicker' ).val() );
					$row.find( 'td[data-name="from_date"] input[type="hidden"]' ).val( $row.find( 'td[data-name="to_date"] input[type="hidden"]' ).val() );
					$row.find( 'td[data-name="from_date"] input[type="hidden"]' ).attr( 'value', $row.find( 'td[data-name="to_date"] input[type="hidden"]' ).val() );
				}
				
			});
		});
	</script>
    <?php
	}
}

add_action( 'wp_footer', 'ads_tweaks', 10000 );
function ads_tweaks() {
	?>
	<div class="headerads">
		<?php echo adrotate_group(1); ?>
	</div>
	<script>
	jQuery( document ).ready( function( $ ) {
		$( '#logo-container-mobile' ).after( $( '.headerads' ) );
	});
	</script>
	<?php
}

add_action( 'wp_footer', 'lakes_archive_inline_js', 10000 );
function lakes_archive_inline_js() {
	
	if ( is_singular( 'tournaments' ) || !is_post_type_archive( 'tournaments' ) ) {
		?>
		<script>
		jQuery( document ).ready( function( $ ) {
			$( '.add_to_call' ).on( 'click', function( e ) {
				e.preventDefault();
				var cal = ics();
				cal.addEvent( $(this).data( 'subject' ), $(this).data( 'description' ), $(this).data( 'location' ), $(this).data( 'begin' ), $(this).data( 'end' ) );
				cal.download( $(this).data( 'subject' ) );
			});
		});
		</script>
		<?php
	}
	
	if ( !( is_post_type_archive( 'lakes' ) || is_page( 'lake-hotels' ) ) ) {
		return;
	}
	
	$search_filter = false;
	$state = "";
	$filter_lake_name = "";
	$filter_lake_type = "";
	if(isset($_GET['bystate']) && $_GET['bystate']!=""){
		$state = $_GET['bystate'];
		$search_filter = true;
	}
	if(isset($_GET['filter_lake_name']) && $_GET['filter_lake_name']!=""){
		$filter_lake_name = $_GET['filter_lake_name'];
		//$search_filter = true;
	}
	if(isset($_GET['filter_lake_type']) && $_GET['filter_lake_type']!=""){
		$filter_lake_type = $_GET['filter_lake_type'];
		$search_filter = true;
	}
	
	$paged = ( get_query_var( 'paged') ) ? absint( get_query_var( 'paged' ) ) : 1; 
	$args = array(
		'numberposts'	=> -1,
		'post_type'		=> 'lakes',
		'paged' => $paged,
		'posts_per_page'=>35,
		'orderby'    => 'post_title',
		'order' => 'asc'
	);
	if($search_filter == true) {
		$args['meta_query']	= array(
			'relation'		=> 'and',
		);
		if(!empty($state)) {
			$args['tax_query'][] = array(
				'taxonomy'	=> 'state',
				'terms'		=> $state,
				'field'		=> 'slug'
			);
		}
		if(!empty($filter_lake_type)) {
			$args['meta_query'][] = array(
				'key'		=> 'lake_type',
				'value'		=> $filter_lake_type,
				'compare'	=> 'LIKE'
			);
		}
	}
	if(!empty($filter_lake_name)) {
		$args['page_id'] = $filter_lake_name;
	}
	
	if ( is_page( 'lake-hotels' ) ) {
		$args['meta_query'][] = array(
			'key'		=> 'hotel_logo',
			'compare'	=> 'EXISTS'
		);
		$args['meta_query'][] = array(
			'key'		=> 'hotel_logo',
			'value'   => array(''),
			'compare' => 'NOT IN',
		);
		$args['meta_query'][] = array(
			'key'		=> 'hotel_booking_link',
			'compare'	=> 'EXISTS',
		);
		$args['meta_query'][] = array(
			'key'		=> 'hotel_booking_link',
			'value'   => array(''),
			'compare' => 'NOT IN',
		);
	}
	
	
	?>
<script>
	
	function initMap() {
	
		var locations = [
			<?php
				$mapargs = $args;
				$mapargs['posts_per_page'] = 99999999999;
				$maplakes = new WP_Query( $mapargs );
			
				if ( !empty( $maplakes->posts ) ) {
					foreach( $maplakes->posts as $lake ) {
						$location = get_field('google_map', $lake->ID );
						$alternate_name = esc_attr( get_post_meta( $lake->ID,'alternate_names', true ) );
						$lake_type= esc_attr( get_post_meta( $lake->ID,'lake_type', true ) );
						$full_pool= esc_attr( get_post_meta( $lake->ID,'full_pool' , true) );
						$size= esc_attr( get_post_meta( $lake->ID,'size', true) );
						$state= strtoupper( get_term( get_field('state', $lake->ID) )->slug );
						
						if ( !empty( $full_pool ) ) {
							$full_pool = '('. $full_pool .')';
						}
						if ( !empty( $size ) ) {
							$size = 'Size: '. $size .' '. $full_pool .'<br />';
						}
						
						if ( !empty( $lake_type ) ) {
							$lake_type = 'Type: '. $lake_type .'<br />';
						}
						
						$infow = 'Name: <a href=\''. get_permalink( $lake->ID ) .'\' >'. esc_attr( $lake->post_title ) .'</a> '. ( !empty( $alternate_name ) ? '('.$alternate_name.')' : '' ) .'<br />State: '. $state .'<br />'. $lake_type . $size;
						
						echo '["'. $infow .'", '. $location['lat'] .', '. $location['lng'] .', 2299],'."\n";
					}
				}
			?>
		];
	  var map;
	  var bounds = new google.maps.LatLngBounds();
	  var mapOptions = {
		center: new google.maps.LatLng(0, 0),
		zoom: 5,
		minZoom: 3,
		maxZoom: 15,
		mapTypeId: 'roadmap',
		mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, JNC.Views.gNavionicsOverlay.CHARTS.SONAR, google.maps.MapTypeId.TERRAIN, google.maps.MapTypeId.HYBRID],
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
            }
	  };

	  // Display a map on the page
	  map = new google.maps.Map(document.getElementById("lakesmap"), mapOptions);
	  map.setTilt(45);

	  // Info Window Content
	  var infoWindowContent = locations;  // suitable dummy value

	  // Display multiple markers on a map
	  var infoWindow = new google.maps.InfoWindow(), marker, i, position;

	  // Loop through our array of markers & place each one on the map 
	  var markers = [];
	  var image = "<?php echo get_stylesheet_directory_uri().'/img/marker.png'; ?>";
	  for (i = 0; i < locations.length; i++) {
		position = new google.maps.LatLng(locations[i][1], locations[i][2]);
		marker = new google.maps.Marker({
		  position: position,
		  map: map,
		  icon: image,
		  title: locations[i][0]
		});
		bounds.extend(position);

		// Allow each marker to have an info window    
		google.maps.event.addListener(marker, 'click', (function(marker, i) {
		  return function() {
			infoWindow.setContent(infoWindowContent[i][0]);
			infoWindow.open(map, marker);
		  }
		})(marker, i));
		
		markers.push(marker);
	  }

	  // Automatically center the map fitting all markers on the screen
	  map.fitBounds(bounds);
	  
		var navionicsSonarChartOverlay = new JNC.Views.gNavionicsOverlay({
			navKey: acnl_maps.navionics,
			chartType: JNC.Views.gNavionicsOverlay.CHARTS.SONAR,
			isTransparent: false
		});
		map.mapTypes.set(JNC.Views.gNavionicsOverlay.CHARTS.SONAR, navionicsSonarChartOverlay);
		// map.setMapTypeId(JNC.Views.gNavionicsOverlay.CHARTS.SONAR);
	  
		// Add a marker clusterer to manage the markers.
		var markerCluster = new MarkerClusterer(map, markers,
			{imagePath: '<?php echo get_stylesheet_directory_uri(); ?>/img/m/m'});
	}
	jQuery( document ).ready( function( $ ) {
		$(window).on('load', function() {
			initMap();
		});
	});
</script>

	<?php
}


// custom filters on results archive query
add_action('pre_get_posts', 'anglers_pre_results_get_posts', 10000000, 1);
function anglers_pre_results_get_posts( $query ) {
	
	// bail early if is in admin
	if( is_admin() ) return;
	if( !is_category( 'results' ) ) { return; }
	
	
	// bail early if not main query
	// - allows custom code / plugins to continue working
	// if( !$query->is_main_query() ) { return; }
	
	if ( !isset( $query->query['category_name'] ) || $query->query['category_name'] != 'results' ) { return; }
	
	if ( isset( $_GET['_fkw'] ) && !empty( $_GET['_fkw'] ) ) {
		$query->set( 's', esc_sql( $_GET['_fkw'] ) );
		$query->is_search = TRUE;
		
		add_filter('template_include','anglers_custom_search_template');
	}
	
	// get meta query
	$meta_query = $query->get('meta_query');
	$update_meta = false;
	
	if ( $meta_query == '' ) {
		$meta_query = array();
	}
	
	if( isset( $_GET['bylake'] ) && !empty( $_GET['bylake'] ) ) {
		
		$bylake = esc_sql( $_GET['bylake'] );
		
		$meta_query[] = array(
			'key'		=> 'lake',
			'value'		=> $bylake,
			'compare'	=> 'LIKE'
		);
		
		$update_meta = true;
		
	}
	
	if( isset( $_GET['bytrails'] ) && !empty( $_GET['bytrails'] ) ) {
		
		$bytrails = esc_sql( $_GET['bytrails'] );
		
		$meta_query[] = array(
			'key'		=> 'trail',
			'value'		=> $bytrails,
			'compare'	=> 'LIKE'
		);
		
		$update_meta = true;
	}
	
	if ( isset( $_GET['datesort'] ) && !empty( $_GET['datesort'] ) ) {
		
		$datesort = $_GET['datesort'];
		$year_month = explode('-',$_GET['datesort']);

		$Current_date = date($year_month[0]."-".$year_month[1]."-01");	//Current date...
		$date = strtotime($Current_date);
		$next_month_date = date($year_month[0].'-'.$year_month[1].'-'.date('t',$date));
		
		$start_date = $Current_date;	//Current Month Date...
		$end_date = $next_month_date;	// Next Month

				
		$query->set( 'year', $year_month[0] );
        $query->set( 'monthnum', $year_month[1] );
		
		$update_meta = true;
	}
	
	if ( $update_meta ) {
		// update meta query
		// always set is searh to true
		$meta_query['relation'] = 'AND';
		$query->is_search = TRUE;
		$query->meta_query = $meta_query;
		$query->set('meta_query', $meta_query);
		add_filter('template_include','anglers_custom_search_template');
	}

}


function anglers_custom_search_template($template){
	
	$template = get_template_part( 'archive' );

    return $template;

}

add_action( 'anglers_archive_top', 'anglers_results_archive_top_filters' );
function anglers_results_archive_top_filters() {
	
	if( !is_category( 'results' ) ) { return; }
	
	$fkw = '';
	$trail = '';
	$lake = '';
	$datesort = '';
	
	if(isset($_GET['bytrails']) && $_GET['bytrails']!=""){
		$trail = $_GET['bytrails'];
	}
	if(isset($_GET['bylake']) && $_GET['bylake']!=""){
		$lake = $_GET['bylake'];
	}
	if ( isset( $_GET['_fkw'] ) && !empty( $_GET['_fkw'] ) ) {
		$fkw = $_GET['_fkw'];
	}
	if ( isset( $_GET['datesort'] ) && !empty( $_GET['datesort'] ) ) {
		$datesort = esc_sql( $_GET['datesort'] );
	}
	
	?>
	<div class="row-container">
		<div class="row row-parent style-light double-top-padding">
			<div id="search-wrapper" class="results_filter_wrapper">
				<form action="" method="get" class="tournamet_filters">
					<input type="text" value="<?php echo $datesort; ?>" class="drop" id="MyDate" name="datesort" placeholder="Select Date" autocomplete="off" />
					
					<select class="drop" id="trail" name="bytrails">
					<option value="" >Select Trail</option>
					<?php 
					$args = array( 'posts_per_page' => -1, 'post_type' => 'trails', 'orderby'    => 'post_title', 'order' => 'asc' );
					$rand_posts = get_posts( $args );
					foreach ( $rand_posts as $post ) : 
						setup_postdata( $post ); 
						
							echo "<option value='$post->ID'";
							if($post->ID==$trail){echo " selected ";}
							echo ">" .$post->post_title . '</option>';
					endforeach; 
					wp_reset_postdata(); 
					
					?>
				 </select>
					
					
					<select class="drop" id="lake" name="bylake">
					<option value="" >Select Lake</option>
					<?php
					$args = array( 'posts_per_page' => -1, 'post_type' => 'lakes', 'orderby'    => 'post_title', 'order' => 'asc' );
					$rand_posts = get_posts( $args );
					foreach ( $rand_posts as $post ) : 
						setup_postdata( $post ); 
						
							echo "<option value='$post->ID'";
							if($post->ID==$lake){echo " selected ";}
							echo ">" .$post->post_title . '</option>';
					endforeach; 
					wp_reset_postdata(); 
					
					?>
					</select>

					<input name="_fkw" type="text" value="<?php echo $fkw; ?>" class="results_search" placeholder="Search by keyword" />
					
					<input class="button-red" type="submit" value="Search" />
				</form>
			</div>
		</div>
	</div>
		

	<script type="text/javascript">
		jQuery(document).ready( function( $ ) {
			$('#MyDate').datepicker({
				dateFormat: "yy-mm",
				changeMonth: true,
				changeYear: true,
				showButtonPanel: true,
				placeholder: 'Select Date',
				onClose: function(dateText, inst) {


					function isDonePressed(){
						return (jQuery('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
					}

					if (isDonePressed()){
						var month = jQuery("#ui-datepicker-div .ui-datepicker-month :selected").val();
						var year = jQuery("#ui-datepicker-div .ui-datepicker-year :selected").val();
						jQuery(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');
						
						jQuery('.date-picker').focusout()//Added to remove focus from datepicker input box on selecting date
					}
				},
				beforeShow : function(input, inst) {

					inst.dpDiv.addClass('month_year_datepicker')

					if ((datestr = jQuery(this).val()).length > 0) {
						year = datestr.substring(datestr.length-4, datestr.length);
						month = datestr.substring(0, 2);
						jQuery(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
						jQuery(this).datepicker('setDate', new Date(year, month-1, 1));
						jQuery(".ui-datepicker-calendar").hide();
					}
				}
			});
			// $('#MyDate').prop( 'placeholder', 'Select Date');
		});
	</script>
	<?php
	
}

$Globals['count_posts'] = 0;
add_action( 'uncode_create_single_block', 'anglers_uncode_create_single_block', 10 );
function anglers_uncode_create_single_block() {
	
	if ( !( is_post_type_archive( array( 'post' ) ) || is_category() ) ) {
		return;
	}
	
	global $Globals;
	if ( $Globals['count_posts'] > 0 && ( $Globals['count_posts'] == 2 || ( ( $Globals['count_posts'] - 2 ) % 6 ) == false ) ) {
		?>
	<div class="tmb tmb-iso-w3 tmb-iso-h4 tmb-round tmb-light tmb-text-showed tmb-content-center tmb-image-anim tmb-shadowed tmb-shadowed-sm tmb-entry-title-uppercase  grid-cat-164 tmb-id-105467 tmb-img-ratio tmb-content-under tmb-media-first">
    <div class="t-inside style-color-xsdn-bg">
		<?php echo adrotate_group(2); ?>
		<a href="<?php echo get_permalink( 108959 ); ?>" title="ADVERTIZE ON THE ANGLERSCHANNEL" class="adlink">ADVERTIZE ON THE ANGLERSCHANNEL</a>
    </div>
</div>
	<?php
	}
}

add_action( 'uncode_create_single_block', 'anglers_uncode_create_single_block_counter', 11 );
function anglers_uncode_create_single_block_counter() {
	global $Globals;
	$Globals['count_posts']++;
	
}

add_action( 'wp_footer', 'anglers_reset_post_counter', 10000 );
function anglers_reset_post_counter() {
	global $Globals;
	$Globals['count_posts'] = 0;
	
}

add_action( 'do_meta_boxes', 'wpdocs_remove_plugin_metaboxes' );
 
/**
 * Remove Editorial Flow meta box for users that cannot delete pages 
 */
function wpdocs_remove_plugin_metaboxes(){
        remove_meta_box( 'formatdiv', 'post', 'side' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'uncode_gallery_div', 'lakes', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'commentsdiv', 'post', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'uncode_gallery_div', 'post', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'uncode_gallery_div', 'listings', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'uncode_gallery_div', 'landings', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'uncode_gallery_div', 'trails', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( 'uncode_gallery_div', 'tournaments', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( '_uncode_page_options', 'tournaments', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( '_uncode_page_options', 'trails', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( '_uncode_page_options', 'landings', 'normal' ); // Remove Edit Flow Editorial Metadata
        remove_meta_box( '_uncode_page_options', 'listings', 'normal' ); // Remove Edit Flow Editorial Metadata
}


add_shortcode( 'upcomingtournaments', 'upcomingtournaments_func' );
function upcomingtournaments_func( $atts ) {
	$a = shortcode_atts( array(
		'limit' => '4',
	), $atts );
	
	$Current_date = date("Y-m-d");
	
	$args = array(
		'post_type'		=> 'tournaments',
		'posts_per_page'=> $a['limit'],
		'fields' => 'ids'
	);
	
	$args['meta_query'][]= array(
		'key'		=> 'from_date',
		'value'		=> $Current_date,
		'compare'	=> '>=',
		'type' => 'DATE' 
	);
	// make sure that the date is set
	$args['meta_query'][]= array(
		'key'		=> 'from_date',
		'compare'	=> 'EXISTS',
	);
	$args['meta_query'][]= array(
		'key'		=> 'from_date',
		'value'		=> '',
		'compare'	=> '!=',
	);
	
	$args['meta_key'] = 'from_date';
	$args['orderby'] =  'meta_value';
	$args['order'] = 'ASC';
	
	$tour_ids = new WP_Query( $args );
	
	$out = '';
	
	if ( !empty( $tour_ids ) ) {
	
		ob_start();
		?>
		<div id="tournaments" class="isotope-system isotope-general-light">
			<div class="isotope-wrapper half-gutter">
				<div class="isotope-container isotope-layout style-masonry isotope-pagination" data-type="masonry" data-layout="fitRows" data-lg="480" data-md="480" data-sm="480" data-vp-height="">
		<?php foreach( $tour_ids->posts as $post_id ) { ?>
		
			<div class="tmb tmb-iso-w6 tmb-iso-h4 tmb-light tmb-overlay-text-anim tmb-content-lateral-left tmb-content-vertical-middle tmb-content-size-3 tmb-content-left tmb-entry-title-uppercase  tmb-id-111298 tmb-img-ratio tmb-only-text tmb-content-lateral tmb-no-bg tmb-iso">
				<div class="t-inside">
					<div class="t-entry-text">
						<div class="t-entry-text-tc no-block-padding">
							<div class="t-entry">
								<h5 class="t-entry-title h6"><a href="<?php echo get_the_permalink( $post_id ); ?>" title="<?php echo get_the_title( $post_id ); ?>" target="_self"><?php echo get_the_title( $post_id ); ?></a></h5></div>
						</div>
					</div>
				</div>
			</div>
		
		<?php } ?>
		
				</div>
			</div>
		</div>
		<?php
		$out = ob_get_clean();
	}
	
	wp_reset_postdata();
	
	return $out;
}


/**** BULK ADD TOURNAMENTS START ****/
add_action('acf/init', 'anglers_acf_op_init');
function anglers_acf_op_init() {
	
	if( function_exists('acf_add_options_page') ) {
		
		acf_add_options_page(array(
			'page_title' 	=> 'Add Bulk Tournaments',
			'menu_title'	=> 'Add Bulk Tournaments',
			'menu_slug' 	=> 'anglers-bulk-tournaments',
			'capability'	=> 'edit_posts',
			'parent_slug' 	=> 'edit.php?post_type=tournaments',
			'update_button' => __('Create Tournaments', 'acf'),
			'updated_message' => __("Tournaments created", 'acf'),
			'redirect'		=> false
		));
	}
}


add_action('acf/save_post', 'bulk_crate_tournament_posts', 20);
function bulk_crate_tournament_posts() {
	$screen = get_current_screen();
	if (strpos($screen->id, "anglers-bulk-tournaments") == true) {
		
		$option_fields = get_fields( 'options' );
				
		$title = $option_fields[ 'bulk_tournaments_title' ];
		$state = $option_fields[ 'bulk_tournaments_state' ][ 'state' ];
		$trail = $option_fields[ 'bulk_tournaments_trail' ][ 'trail' ]->ID;
			
		$details = $option_fields[ 'bulk_tournaments_details' ];
		
		$count = count( $details );
		$i = 0;
		if ( !empty( $details ) ) {
			foreach( $details as $detail ) {
				
				$new_post_id = false;
				
				$args = array(
					'post_author' => get_current_user_id(),
					'post_content' => '&nbsp;',
					'post_title' => $title,
					'post_status' => 'publish',
					'post_type' => 'tournaments',
				);
				
				$new_post_id = wp_insert_post( $args );
				if ( intval( $new_post_id ) > 0 ) {
					
					$i++;
					
					update_field( 'state', $state, $new_post_id );
					update_field( 'trail', $trail, $new_post_id );
					
					foreach( $detail as $field => $value ) {
						
						if ( empty( $value ) ) {
							continue;
						}
						
						$get_id = url_to_postid( $value );
						if ( $get_id > 0 ) {
							$value = $get_id;
						}
						$meta_value = false;
						if ( strpos( $field, 'date' ) !== false ) {
							$value = date( 'm/d/Y', strtotime( $value ) );
							$meta_value = date( 'Ymd', strtotime( $value ) );
						}
						
						$acf_field = update_field( $field, $value, $new_post_id );
						if ( $meta_value ) {
							update_post_meta( $new_post_id, $field, $meta_value );
						}
						
						if ( !$acf_field ) {

							echo '<pre>Bulk Tournaments Error: '.print_r( $value, true ).'</pre>';
							echo '<pre>'.print_r( $detail, true ).'</pre>';
							echo '<p>Copy this and send it to Conor :)</p>';
							return;
						}
					}
					
					do_action( 'save_post', $new_post_id, get_post( $new_post_id ), false );
					do_action( 'save_post_tournaments', $new_post_id, get_post( $new_post_id ), false );
				}
			}
			
			if ( $count == $i ) {
				
				global $wpdb;
				
				$delete_query = $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE '%options_bulk_tournaments%'" );
			}
		}
	}
}


/**** BULK ADD TOURNAMENTS END   ****/



/**** REFERRAL START  ****/


add_filter( 'gform_field_value_refer_code', 'set_refer_code', 10 );
function set_refer_code( $value ){

	$value = uniqid();
	return $value;
}
add_filter( 'gform_field_value_referred_from', 'set_referred_from_code', 10 );
function set_referred_from_code( $value ) {
	
	if ( isset( $_COOKIE[ 'referred_from' ] ) ) {
		$value = $_COOKIE[ 'referred_from' ];
	}
	return $value;
}


add_action( 'init', 'set_referred_from_cookie');
function set_referred_from_cookie() {
 
	if ( isset( $_GET[ 'rcode' ] ) ) {
		
		if( isset( $_COOKIE[ 'referred_from' ] ) ) {				
			unset(	$_COOKIE['referred_from' ] );
		}
		setcookie( 'referred_from', esc_sql( $_GET[ 'rcode' ] ), time()+2592000 ); // 30 days cookie
		
	}
}

// change the leads number
add_action( 'gform_after_submission_7', 'referred_from_pre_submission', 10, 2 );
function referred_from_pre_submission( $entry, $form ) {
	
	// count the number that referred_from has been used
	$referred_from = rgar( $entry, '9' );
	if ( empty( $referred_from ) ) {
		return;
	}
	
	$search_criteria = array(
		'field_filters' => array(
		array (
			'key'   => '9', // the field ID we want to count
			'value' => $referred_from
			)
		)
	);
	$entry_count = GFAPI::count_entries( 7, $search_criteria ); // form ID 7
	
	
	// get_user_entry
	$search_criteria = array(
		'field_filters' => array(
		array (
			'key'   => '7', // the field ID we want to count
			'value' => $referred_from
			)
		)
	);
	$get_entries = GFAPI::get_entries( 7, $search_criteria );
	
	if ( !empty( $get_entries ) && isset( $get_entries[ 0 ] ) ) {
		$from_entry_id = $get_entries[ 0 ][ 'id' ];
		GFAPI::update_entry_field( $from_entry_id, 10, ( intval( $entry_count ) + 1 ) ); // 10 is the ID of the leads
	}
	
}


// custom confirmation
add_filter( 'gform_confirmation_7', 'referal_custom_confirmation', 10, 4 );
function referal_custom_confirmation( $confirmation, $form, $entry, $is_ajax ) {
	
	
	$url = $entry->source_url;
	$name = rgar( $entry, '1' );
	$code = rgar( $entry, '7' ); 
	
	$confirmation = '
	Thank you for entering, check back the following day for winners.
	<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v12.0&appId=192001206393277&autoLogAppEvents=1" nonce="4angmiwP"></script>

';

$confirmation .= '
<script>window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));</script>
';


	$facebooktext = $name.' wants you to play AnglersChannel’s Holiday Extravaganza Giveaway Contest';
	
	$confirmation .= '
	<div class="fb-share-button contest_share" data-message="'. $facebooktext .'" data-quote="'. $facebooktext .'" data-href="'.$url.'?rcode='. $code .'" data-layout="button" data-size="large">
		<a target="_blank" onclick="window.open(this.href,\'targetWindow\',\'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=560,height=690\'); return false;" id="tbpfbshare" href="https://www.facebook.com/dialog/share?app_id=192001206393277&quote='. urlencode( $facebooktext ) .'&href='. urlencode( $url.'?rcode=' ) . $code .'&src=sdkpreparse" class="fb-xfbml-parse-ignore">
			<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-facebook" viewBox="0 0 16 16" style="transform: translateY( -1px );">
  <path d="M16 8.049c0-4.446-3.582-8.05-8-8.05C3.58 0-.002 3.603-.002 8.05c0 4.017 2.926 7.347 6.75 7.951v-5.625h-2.03V8.05H6.75V6.275c0-2.017 1.195-3.131 3.022-3.131.876 0 1.791.157 1.791.157v1.98h-1.009c-.993 0-1.303.621-1.303 1.258v1.51h2.218l-.354 2.326H9.25V16c3.824-.604 6.75-3.934 6.75-7.951z"/>
</svg> Share</a>
	</div> ';
	
	
	// twitter
	
	$twittertext = $name. ' wants you to play AnglersChannel’s Holiday Extravaganza Giveaway Contest';
	$confirmation .= '
	<div class="twitter-share-contest contest_share">
	<a class="twitter-share-button" data-size="large"
		href="https://twitter.com/intent/tweet?text='. urlencode( $twittertext ) .'&url='. urlencode( $url.'?rcode=' ) . $code .'">
		Tweet</a>
	</div>';
	
	// what's up
	
	$whatapptext = 'A friend wants you to play AnglersChannel’s Holiday Extravaganza Giveaway Contest';
	
	$confirmation .= '
	<div class="whatsapp_share contest_share">
	<a href="whatsapp://send?text='. urlencode( $whatapptext.' '. $url .'?rcode=' ) . $code .'" class="btn btn-secondary btn-what rounded" target="_blank"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-whatsapp" viewBox="0 0 16 16" style="transform: translateY(4px);">
  <path d="M13.601 2.326A7.854 7.854 0 0 0 7.994 0C3.627 0 .068 3.558.064 7.926c0 1.399.366 2.76 1.057 3.965L0 16l4.204-1.102a7.933 7.933 0 0 0 3.79.965h.004c4.368 0 7.926-3.558 7.93-7.93A7.898 7.898 0 0 0 13.6 2.326zM7.994 14.521a6.573 6.573 0 0 1-3.356-.92l-.24-.144-2.494.654.666-2.433-.156-.251a6.56 6.56 0 0 1-1.007-3.505c0-3.626 2.957-6.584 6.591-6.584a6.56 6.56 0 0 1 4.66 1.931 6.557 6.557 0 0 1 1.928 4.66c-.004 3.639-2.961 6.592-6.592 6.592zm3.615-4.934c-.197-.099-1.17-.578-1.353-.646-.182-.065-.315-.099-.445.099-.133.197-.513.646-.627.775-.114.133-.232.148-.43.05-.197-.1-.836-.308-1.592-.985-.59-.525-.985-1.175-1.103-1.372-.114-.198-.011-.304.088-.403.087-.088.197-.232.296-.346.1-.114.133-.198.198-.33.065-.134.034-.248-.015-.347-.05-.099-.445-1.076-.612-1.47-.16-.389-.323-.335-.445-.34-.114-.007-.247-.007-.38-.007a.729.729 0 0 0-.529.247c-.182.198-.691.677-.691 1.654 0 .977.71 1.916.81 2.049.098.133 1.394 2.132 3.383 2.992.47.205.84.326 1.129.418.475.152.904.129 1.246.08.38-.058 1.171-.48 1.338-.943.164-.464.164-.86.114-.943-.049-.084-.182-.133-.38-.232z"/>
</svg> Whatsapp</a></div>';

return $confirmation;
	
	
}
/**** REFERRAL END   ****/




add_filter( 'posts_where', 'nitro_posts_where_by_letter', 10, 2 );
function nitro_posts_where_by_letter( $where, $query ) {
	
    global $wpdb;

    $starts_with = esc_sql( $query->get( 'starts_with' ) );

    if ( $starts_with ) {
        $where .= " AND $wpdb->posts.post_title LIKE '$starts_with%'";
    }

    return $where;
}


// add rotate fix
remove_action('wp_enqueue_scripts', 'adrotate_scripts');
if( !is_admin() ) {
	add_action('wp_enqueue_scripts', 'anglers_adrotate_scripts', 100);
}

function anglers_adrotate_scripts() {
	global $adrotate_config;

	// $in_footer = ($adrotate_config['jsfooter'] == "Y") ? true : false;
	$in_footer = false;
	
	if($adrotate_config['jquery'] == 'Y') {
		wp_enqueue_script('jquery', false, false, null, $in_footer);
	}

	if(get_option('adrotate_dynamic_required') > 0) {
		wp_enqueue_script('adrotate-dyngroup', get_stylesheet_directory_uri().'/js/jquery.dyngroup.js', array( 'jquery' ), null, $in_footer);
	}

	if($adrotate_config['stats'] == 1) {
		wp_enqueue_script('adrotate-clicktracker', plugins_url('/adrotate-pro/library/jquery.adrotate.clicktracker.js', ''), false, null, $in_footer);
		wp_localize_script('adrotate-clicktracker', 'click_object', array('ajax_url' => admin_url('admin-ajax.php')));
		wp_localize_script('adrotate-dyngroup', 'impression_object', array('ajax_url' => admin_url( 'admin-ajax.php')));
	}

	if(!$in_footer) {
		add_action('wp_head', 'adrotate_custom_javascript');
	} else {
		add_action('wp_footer', 'adrotate_custom_javascript', 100);
	}
}

add_action('admin_head', 'admin_css');

function admin_css() {
  echo '<style>
	.sbi_notice {
	  display:none !important;
	} 
  </style>';
}

add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;
    
    if ($pagenow === 'edit-comments.php') {
        wp_redirect(admin_url());
        exit;
    }

    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});