<?php
/**
 * Main theme functions.
 *
 * @package Sunset
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! function_exists( 'sunset_setup' ) ) {
	add_action( 'after_setup_theme', 'sunset_setup' );
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 */
	function sunset_setup() {
		$header_type = sunset_get_option( 'sunset_header_type' );
		$is_disable_block_widgets = sunset_get_option( 'sunset_disable_block_widgets' );

		// Make theme available for translation.
		load_theme_textdomain( 'my-sunset' );

		// Add theme support for various features.
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'post-thumbnails' );
		add_theme_support( 'woocommerce' );
		add_theme_support( 'title-tag' );
		add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'script', 'style' ) );
		add_theme_support( 'customize-selective-refresh-widgets' );
		add_theme_support( 'align-wide' );
		add_theme_support( 'responsive-embeds' );
		add_theme_support( 'custom-spacing' );
		add_theme_support( 'editor-styles' );

		add_theme_support(
			'custom-logo',
			array(
				'height' => 60,
				'width' => 200,
				'flex-height' => true,
				'flex-width' => true,
				'header-text'          => array( 'site-title', 'site-description' ),
				'unlink-homepage-logo' => true,
			)
		);

		// Register primary menus
		if ($header_type === 'header_2') { // for centered menu
			register_nav_menus(
				array(
					'primary' => __( 'Primary Left Menu', 'my-sunset' ),
					'primary-right' => __( 'Primary Right Menu', 'my-sunset' ),
				)
			);
		} else {
			register_nav_menus(
				array(
					'primary' => __( 'Primary Menu', 'my-sunset' ),
				)
			);
		}
		
		// This theme styles the visual editor to resemble the theme style.
		add_editor_style( 'assets/css/fa/all.css' );
		add_editor_style( 'assets/css/editor-style.css' );
		add_editor_style( 'assets/css/styles.css' );

		// Trick editor into loading inline styles. See sunset_pre_http_request_block_editor_customizer_styles()
		add_editor_style( get_template_directory_uri().'/assets/css/admin-inline.css' );

		// restore default WordPress widgets intead of block-editor widgets
		if ($is_disable_block_widgets) {
			add_filter('use_widgets_block_editor', '__return_false');
		}
	}
}

if ( ! function_exists( 'sunset_add_custom_color_palette' ) ) {	
	add_action('after_setup_theme', 'sunset_add_custom_color_palette', 20);
	/**
	 * Add custom colors from Customizer options
	 */
	function sunset_add_custom_color_palette()	{

		/**
		 * Get default core color palette from wp-includes/theme.json
		 * @see https://www.wpdiaries.com/gutenberg-color-palette/
		 */
		$existing_palette = [];
		if (class_exists('WP_Theme_JSON_Resolver')) {
			$settings = WP_Theme_JSON_Resolver::get_core_data()->get_settings();
			if (isset($settings['color']['palette']['default'])) {
				$existing_palette = $settings['color']['palette']['default'];
			}
		}

		$primary_color = sunset_get_option( 'sunset_content_primary_color', sunset_get_color_defaults() );
		$content_bg_color = sunset_get_option( 'sunset_content_bg_color', sunset_get_color_defaults() );
		$link_color = sunset_get_option( 'sunset_content_link_color', sunset_get_color_defaults() );
		$link_hover_color = sunset_get_option( 'sunset_content_link_hover_color', sunset_get_color_defaults() );

		$theme_colors = array(
			array(
				'name'  => __( 'Primary', 'my-sunset' ),
				'slug'  => 'primary',
				'color'	=> $primary_color,
			),
			array(
				'name'  => __( 'Background', 'my-sunset' ),
				'slug'  => 'bg',
				'color'	=> $content_bg_color,
			),
			array(
				'name'  => __( 'Link', 'my-sunset' ),
				'slug'  => 'link',
				'color'	=> $link_color,
			),
			array(
				'name'  => __( 'Link Hover', 'my-sunset' ),
				'slug'  => 'link-hover',
				'color'	=> $link_hover_color,
			),
			array(
				'name'  => __( 'Transparent', 'my-sunset' ),
				'slug'  => 'transparent',
				'color'	=> 'transparent',
			),
		);

		/*if (is_array($existing_palette)) {
			$new_palette = array_merge($existing_palette, $theme_colors);

			// @see https://stackoverflow.com/a/42578062/2573521
			$new_palette = array_reverse(array_values(array_column(
				array_reverse($new_palette),
				null,
				'color'
			)));
		} else {*/
			$new_palette = $theme_colors;
		//}

		add_theme_support('editor-color-palette',  $new_palette);
		
		add_theme_support( 'editor-gradient-presets', array(
			array(
				'name'     => esc_attr__( 'Vivid cyan blue to vivid purple', 'my-sunset' ),
				'gradient' => 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%)',
				'slug'     => 'vivid-cyan-blue-to-vivid-purple'
			),
			array(
				'name'     => esc_attr__( 'Vivid green cyan to vivid cyan blue', 'my-sunset' ),
				'gradient' => 'linear-gradient(135deg,rgba(0,208,132,1) 0%,rgba(6,147,227,1) 100%)',
				'slug'     =>  'vivid-green-cyan-to-vivid-cyan-blue',
			),
			array(
				'name'     => esc_attr__( 'Light green cyan to vivid green cyan', 'my-sunset' ),
				'gradient' => 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)',
				'slug'     => 'light-green-cyan-to-vivid-green-cyan',
			),
			array(
				'name'     => esc_attr__( 'Luminous vivid amber to luminous vivid orange', 'my-sunset' ),
				'gradient' => 'linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%)',
				'slug'     => 'luminous-vivid-amber-to-luminous-vivid-orange',
			),
			array(
				'name'     => esc_attr__( 'Luminous vivid orange to vivid red', 'my-sunset' ),
				'gradient' => 'linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%)',
				'slug'     => 'luminous-vivid-orange-to-vivid-red',
			),
		) );
	}
}


if ( ! function_exists( 'sunset_excerpt_length' ) ) {
	add_filter( 'excerpt_length', 'sunset_excerpt_length', 99 );
	/**
	 * Limit the excerpt length
	 *
	 * @param array $length The existing excerpt length.
	 * @return integer Excerpt length.
	 */
	function sunset_excerpt_length( $length ) {
		if ( is_admin() ) return $length;
		return 30;
	}	
}


if ( ! function_exists( 'sunset_excerpt_more' ) ) {
	add_filter( 'excerpt_more', 'sunset_excerpt_more', 99 );
	/**
	 * Modify excerpt's more tag
	 *
	 * @return string Excerpt's more tag
	 */
	function sunset_excerpt_more($more) {
		global $post;
		if ( is_admin() ) return $more;
		return '...';
	}	
}


if ( ! function_exists( 'sunset_excerpt' ) ) {	
	add_filter( 'the_excerpt', 'sunset_excerpt', 99 );
	/**
	 * Modify excerpt
	 *
	 * @return string Excerpt
	 */
	function sunset_excerpt($excerpt) {
		global $post;
		return '<p>'.$excerpt.'</p><p class="readmore-block"><a class="readmore-link" href="'.esc_url(get_permalink($post->ID)).'" title="'.esc_attr(get_the_title($post->ID)).'">'.__( 'Read more', 'my-sunset' ).'</a></p>';
	}
}


if ( ! function_exists( 'sunset_menu_not_found' ) ) {
	/**
	 * Fallback if menu was not found
	 *
	 * @param array $args Menu's args
	 * @return string Message if menu wasn't found
	 */
	function sunset_menu_not_found( $args ) {
		if ( current_user_can( 'administrator' ) && is_customize_preview() ) {
			echo '<em>'.__( 'Go to Menus section to set up menu.', 'my-sunset' ).'</em>';
		} else {
			echo '
			<ul id="menu-menu-1" class="main-nav-menu main-nav-menu--regular main-nav-menu--stroked">
				<li id="menu-item-119" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-12 current_page_item menu-item-119">
					<a href="'.esc_url(home_url('/')).'" aria-current="page" data-content="Home"><span>Home</span></a>
				</li>
				<li id="menu-item-121" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-121">
					<a href="#" data-content="Demos"><span>Demos</span></a><button class="menu-item-arrow"></button>
					<ul class="sub-menu">
						<li id="menu-item-122" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-122"><a href="https://sunset.bogdan.kyiv.ua/minimal" data-content="Minimal"><span>Minimal</span></a></li>
						<li id="menu-item-123" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-123"><a href="https://sunset.bogdan.kyiv.ua/bold" data-content="Bold"><span>Bold</span></a></li>
					</ul>
				</li>
			</ul>
			<div id="fullscreen-menu-block" class="fullscreen-menu-block fullscreen-menu-block--align-x-left fullscreen-menu-block--underlined ">

				<button class="fullscreen-menu__back-button hidden">
					<i class="fas fa-arrow-left"></i>
				</button>

				<button class="burger" tabindex="-1">
					<svg xmlns="http://www.w3.org/2000/svg" width="56" height="55" viewBox="0 0 56 55" fill="none" class="burger-close">
						<line x1="3.76777" y1="2.23223" x2="53.2652" y2="51.7297" stroke="white" stroke-width="3"></line>
						<line x1="1.98223" y1="52.4784" x2="51.4797" y2="2.98098" stroke="white" stroke-width="3"></line>
					</svg>
				</button>

				<div class="fullscreen-menu-block__cover">
					<div class="fullscreen-menu-block__inner">
						<nav class="main-nav main-nav--fullscreen" id="primary-menu--fullscreen">
							<ul id="menu-menu-2" class="main-nav-menu opened main-nav-menu--mobile main-nav-menu--underlined">
								<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-12 current_page_item menu-item-119">
									<a href="'.esc_url(home_url('/')).'" aria-current="page" data-content="Home" tabindex="-1"><span>Home</span></a><button class="menu-item-arrow fas fa-arrow-right"></button>
								</li>
								<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-121">
									<a href="#" data-content="Demos" tabindex="-1"><span>Demos</span></a><button class="menu-item-arrow fas fa-arrow-right"></button>
									<ul class="sub-menu parent-menu-item-121 main-nav-menu">
										<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-122"><a href="https://sunset.bogdan.kyiv.ua/minimal" data-content="Minimal" tabindex="-1"><span>Minimal</span></a><button class="menu-item-arrow fas fa-arrow-right"></button></li>
										<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-123"><a href="https://sunset.bogdan.kyiv.ua/bold" data-content="Bold" tabindex="-1"><span>Bold</span></a><button class="menu-item-arrow fas fa-arrow-right"></button></li>
									</ul>
								</li>
							</ul>						
						</nav>
					</div>
				</div>
			</div>
			';
		}
		return '';
	}
}


if ( ! function_exists( 'sunset_get_social_links' ) ) {
	/**
	 * Get array of social links
	 * 
	 * @return array Array of social networks and their urls
	 */
	function sunset_get_social_links() {
		$values = html_entity_decode(stripslashes(sunset_get_option('sunset_social_links')));
		$json = json_decode( $values );

		if ( ! is_array( $json ) ) {
			$json = array( $values );
		}
		return apply_filters( 'sunset_get_social_links', $json);
	}
}


if ( ! function_exists( 'sunset_get_social_icons_names' ) ) {
	/**
	 * Get array of social networks icons names (from FontAwesome 5)
	 * 
	 * @return array Array of social networks icons names
	 */
	function sunset_get_social_icons_names() {
		return apply_filters( 'sunset_get_social_icons_names', 
			array(
				'facebook',
				'facebook-f',
				'facebook-messenger',
				'facebook-square',
				'twitter',
				'twitter-square',
				'instagram',
				'youtube',
				'youtube-square',
				'vimeo',
				'vimeo-square',
				'vimeo-v',
				'behance',
				'behance-square',
				'linkedin',
				'linkedin-in',
				'pinterest',
				'pinterest-square',
				'pinterest-p',
				'reddit',
				'reddit-alien',
				'reddit-square',
				'skype',
				'slack',
				'whatsapp',
				'whatsapp-square',
				'telegram',
				'telegram-plane',
				'twitch',
				'viber',
				'soundcloud',
				'spotify',
				'squarespace',
				'yahoo',
				'stack-overflow',
				'steam',
				'steam-square',
				'steam-symbol',
				'tumblr',
				'tumblr-square',
				'google-plus',
				'google-plus-g',
				'500px',
				'blogger',
				'blogger-b',
				'atlassian',
				'bitbucket',
				'codepen',
				'discord',
				'dribbble',
				'dribbble-square',
				'figma',
				'git',
				'git-square',
				'github',
				'github-alt',
				'github-square',
				'lastfm',
				'medium',
				'medium-m',
				'patreon',
				'zhihu',
			)
		);
	}
}


if ( ! function_exists( 'sunset_social_links' ) ) {
	$sunset_header_type = sunset_get_option( 'sunset_header_type' ) ;
	if ( $sunset_header_type !== 'header_4' ) { // hook social links if not burger menu header type selected
		add_action('sunset_header_inner', 'sunset_social_links', 70, 1);
	}
	add_action('sunset_after_mobile_menu', 'sunset_social_links', 10, 1);
	/**
	 * Output social links
	 * 
	 * @param string $is_mobile_social_links true, if function used for mobile menu
	 * @param string $is_shortcode true, if function used as shortcode
	 */
	function sunset_social_links( $is_mobile_social_links = false, $is_shortcode = false ) {
		$social_links = sunset_get_social_links();
		$is_header_add_social = sunset_get_option( 'sunset_header_add_social' );
		$has_values = false;
		$first_item = false;
		$header_menu_hover_type = sunset_get_option( 'sunset_header_menu_hover_type' );
		$header_menu_mobile_hover_type = sunset_get_option( 'sunset_header_menu_mobile_hover_type' );
		if (count($social_links) > 0 && $is_header_add_social) {
			foreach ($social_links as $key => $network) {
				if ($network->link !== '' ) {
					$has_values = true;

					if ($has_values && !$first_item) {
						if ($is_shortcode) {
							echo '<ul class="main-nav-menu main-nav-menu--social social-menu-shortcode">';
						} else {
							echo '<ul class="main-nav-menu main-nav-menu--social social-menu main-nav-menu--'.($is_mobile_social_links ? $header_menu_mobile_hover_type : $header_menu_hover_type).'">';
						}
						$first_item = true;
					}
					
					$link_text = '<i class="fab fa-'.$network->icon_type.'"></i>';
					
					$link_inline_style = '<style>
						#social-menu__item--'.sanitize_title($network->text).'-'.$key.' a {
							color: '.$network->icon_color.';
						}
						.main-nav-menu.main-nav-menu--stroked #social-menu__item--'.sanitize_title($network->text).'-'.$key.' a {
							-webkit-text-stroke-color: '.$network->icon_color.' !important;
						}
						#social-menu__item--'.sanitize_title($network->text).'-'.$key.' a:hover {
							color: '.$network->icon_hover_color.';
						}
						.main-nav-menu.main-nav-menu--stroked #social-menu__item--'.sanitize_title($network->text).'-'.$key.' a:hover {
							color: '.$network->icon_hover_color.' !important;
							-webkit-text-stroke-color: transparent !important;
						}
					</style>';
					echo '<li id="social-menu__item--'.sanitize_title($network->text).'-'.$key.'" class="social-menu__item social-menu__item--'.sanitize_title($network->text).'">
					'.$link_inline_style.'
					<a href="'.$network->link.'" target="_blank"><span>'.$link_text.'</span></a>
					</li>';
				}
			}
			if ($has_values) echo '</ul>';
		}
	}
}


if ( ! function_exists( 'sunset_header_search' ) ) {	
	add_action('sunset_header_inner', 'sunset_header_search', 80);
	/**
	 * Output search icon and form in the header
	 * 
	 *  @param bool $is_rtl If search should appear from the left if true
	 * 
	 */
	function sunset_header_search() {
		$search_active = sunset_get_option( 'sunset_header_add_search' );

		if (!$search_active) 
			return true;

		$is_rtl = is_rtl();
		$header_type = sunset_get_option( 'sunset_header_type' );
		$header_menu_hover_type = sunset_get_option( 'sunset_header_menu_hover_type' );
		$form_args = array(
			'echo' => true,
			'aria_label' => 'header-search',
		);
		$search_form_container_class = 'header-search-form header-search-form--inline';
		$search_item_class = 'header-search-item ';
		if ($is_rtl) {
			$search_item_class .= ' header-search-item--rtl';
		}
		?>

		<ul class="main-nav-menu main-nav-menu--<?php echo esc_attr($header_menu_hover_type); ?> main-nav-menu--search">
			<li class="<?php echo esc_attr($search_item_class); ?>">
				<a class="header-search-button" type="button" role="button" href="#">
					<?php echo sunset_get_svg_icon('search'); ?>
					<?php echo sunset_get_svg_icon('close'); ?>
				</a>				
			</li>
		</ul>
		<div class="<?php echo esc_attr($search_form_container_class); ?>">
			<?php get_search_form( $form_args ); ?>
		</div>

		<?php
	}
}


if ( ! function_exists( 'sunset_header_logo' ) ) {
	/**
	 * Output header logo
	 */
	function sunset_header_logo() {
		if ( function_exists( 'the_custom_logo' ) ) {
			if ( has_custom_logo() ) {
				the_custom_logo();
			} else {
				if (!is_front_page()) {
					echo '<a href="'.esc_html(home_url()).'" class="logo">';
				} else {
					echo '<div class="logo">';
				}
				echo '<span class="logo__title">'. get_bloginfo( 'name' ) .'</span><span class="logo__desc">'. get_bloginfo( 'description' ) .'</span>';
				if (!is_front_page()) {
					echo '</a> ';
				} else {
					echo '</div>';
				}
			}
		}
	}
}

if ( ! function_exists( 'sunset_header_burger' ) ) {	
	add_action('sunset_header_inner', 'sunset_header_burger', 90);
	/**
	 * Output header's burger menu icon
	 */
	function sunset_header_burger() {
		$burger_icon_type = sunset_get_option('sunset_header_burger_icon_type');
		$burger_html = '';

		if ($burger_icon_type === 'burger') {
			$burger_html = '
			<button class="burger">
				<svg width="38" height="38" viewBox="0 0 38 38" fill="none" xmlns="http://www.w3.org/2000/svg" class="lined">
					<rect x="8" y="30" width="30" height="2" fill="black"/>
					<rect y="18" width="37.8161" height="2" fill="black"/>
					<rect x="8" y="6" width="30" height="2" fill="black"/>
				</svg>
			</button>
			';
		}
		if ($burger_icon_type === 'kebab') {
			$burger_html = '
			<button class="burger">
				<svg width="12" height="52" viewBox="0 0 12 52" fill="none" xmlns="http://www.w3.org/2000/svg" class="kebab">
					<circle cx="6" cy="6" r="6" fill="black"/>
					<circle cx="6" cy="26" r="6" fill="black"/>
					<circle cx="6" cy="46" r="6" fill="black"/>
				</svg>
			</button>
			';
		}
		if ($burger_icon_type === 'kebab_2') {
			$burger_html = '
			<button class="burger">
				<svg width="52" height="12" viewBox="0 0 52 12" fill="none" xmlns="http://www.w3.org/2000/svg" class="kebab kebab--horizontal">
					<circle cx="46" cy="6" r="6" fill="black"/>
					<circle cx="26" cy="6" r="6" fill="black"/>
					<circle cx="6" cy="6" r="6" fill="black"/>
				</svg>
			</button>
			';
		}
		if ($burger_icon_type === 'text') {
			$burger_icon_text = sunset_get_option('sunset_header_burger_icon_text');
			$burger_html = '
			<button class="burger">
				<span class="texted">'. $burger_icon_text .'</span>
			</button>
			';
		}
		echo apply_filters('sunset_burger_html', $burger_html);
	}
}

if ( ! function_exists( 'sunset_header_burger_close' ) ) {
	/**
	 * Output header's burger close menu icon
	 */
	function sunset_header_burger_close() {
		$burger_html = '
			<button class="burger" tabindex="-1">
				<svg xmlns="http://www.w3.org/2000/svg" width="56" height="55" viewBox="0 0 56 55" fill="none" class="burger-close">
					<line x1="3.76777" y1="2.23223" x2="53.2652" y2="51.7297" stroke="white" stroke-width="3"/>
					<line x1="1.98223" y1="52.4784" x2="51.4797" y2="2.98098" stroke="white" stroke-width="3"/>
				</svg>
			</button>
		';

		echo apply_filters('sunset_burger_close_html', $burger_html);
	}
}


if ( ! function_exists( 'sunset_fullscreen_menu' ) ) {
	add_action('sunset_header_inner', 'sunset_fullscreen_menu', 95);
	/**
	 * Output fullscreen/mobile menu
	 */
	function sunset_fullscreen_menu() {
		if (!has_nav_menu('primary') && !has_nav_menu('primary-right')) return true;
		
		$header_type = sunset_get_option( 'sunset_header_type' ) ;
		$header_menu_mobile_hover_type = sunset_get_option( 'sunset_header_menu_mobile_hover_type' ) ;
		$header_add_social = sunset_get_option( 'sunset_header_add_social' );
		$header_add_search = sunset_get_option( 'sunset_header_add_search' );
		?>
		<div id="fullscreen-menu-block" class="<?php echo sunset_get_classes('mobile_menu'); ?>" role="dialog">

			<button class="fullscreen-menu__back-button hidden">
				<i class="fas fa-arrow-left"></i>
			</button>

			<?php sunset_header_burger_close(); ?>

			<div class="fullscreen-menu-block__cover">
				<div class="fullscreen-menu-block__inner">

					
					<nav class="main-nav main-nav--fullscreen" id="primary-menu--fullscreen">
						<?php 
						wp_nav_menu(
							array(
								'theme_location' => 'primary',
								'container' => false,
								'menu_class' => 'main-nav-menu opened main-nav-menu--mobile main-nav-menu--'.$header_menu_mobile_hover_type,
								'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
								'link_before' => '<span>',
								'link_after' => '</span>',
								'after' => '<button class="menu-item-arrow fas fa-arrow-right"></button>',
								'fallback_cb' => 'sunset_menu_not_found'
							)
						);
						if ($header_type === 'header_2' ) {
							wp_nav_menu(
								array(
									'theme_location' => 'primary-right',
									'container' => false,
									'menu_class' => 'main-nav-menu opened main-nav-menu--mobile main-nav-menu--'.$header_menu_mobile_hover_type,
									'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
									'link_before' => '<span>',
									'link_after' => '</span>',
									'after' => '<button class="menu-item-arrow fas fa-arrow-right"></button>',
									'fallback_cb' => '__return_empty_string'
								)
							);
						}
						?>
						
					</nav>
				</div>
			</div>

			<?php
			/**
			 * sunset_after_mobile_menu hook.
			 * 
			 * @hooked sunset_social_links - 10
			 */
			$is_mobile_social_links = true;
			do_action( 'sunset_after_mobile_menu', $is_mobile_social_links );
			?>

		</div>
		<?php
	}
}


if ( ! function_exists( 'sunset_change_logo_class' ) ) {	
	add_filter( 'get_custom_logo', 'sunset_change_logo_class' );
	/**
	 * Replace custom logo's class
	 * 
	 * @param string $html Current logo's html
	 * @return string New logo's html
	 */
	function sunset_change_logo_class( $html ) {
		
		$html = str_replace( 'custom-logo-link', 'logo', $html );
		$html = str_replace( 'custom-logo', 'logo-img', $html );

		return $html;
	}
}

if ( ! function_exists( 'sunset_change_logo_for_dark_mode' ) ) {	
	add_filter( 'get_custom_logo', 'sunset_change_logo_for_dark_mode' );
	/**
	 * Add dark-mode logo
	 * 
	 * @param string $html Current logo's html
	 * @return string New logo's html
	 */
	function sunset_change_logo_for_dark_mode( $html ) {
		
		if ( is_page() || is_singular('post') ) {
			$page_header_type = sunset_get_option('sunset_page_header_type');
			$post_header_type = sunset_get_option('sunset_post_header_type');
			$dark_mode_logo_image_id = sunset_get_option('sunset_logo_dark_mode');

			if ( $dark_mode_logo_image_id && (is_page() && $page_header_type === 'cover') || (is_singular('post') && $post_header_type === 'cover') ) {
				preg_match('/(<)([img])(\w+)([^>]*>)/', $html, $origin_img);				
				$html = preg_replace('(src="(.*?)")', "src='" . wp_get_attachment_image_url($dark_mode_logo_image_id, 'full') . "'", $html);
				$html = preg_replace('(srcset="(.*?)")', "srcset='" . wp_get_attachment_image_srcset($dark_mode_logo_image_id, 'full') . "'", $html);
				$html = preg_replace('/class=\"logo-img\"/', "class='logo-img logo-img--dark-mode'", $html);
				$html = preg_replace('/\<img/', $origin_img[0]."<img", $html);
			}
		}

		return $html;
	}
}

if ( ! function_exists( 'sunset_skip_to_content_link' ) ) {	
	add_action( 'sunset_before_header', 'sunset_skip_to_content_link', 3 );
	/**
	 * Add skip to content link before the header.
	 */
	function sunset_skip_to_content_link() {
		printf(
			'<a class="screen-reader-text skip-link" href="#content" title="%1$s">%2$s</a>',
			esc_attr__( 'Skip to content', 'my-sunset' ),
			esc_html__( 'Skip to content', 'my-sunset' )
		);
	}
}


if ( ! function_exists( 'sunset_construct_top_bar' ) ) {	
	add_action( 'sunset_header', 'sunset_construct_top_bar', 5 );
	/**
	 * Output the top bar
	 */
	function sunset_construct_top_bar() {
		$is_topbar_enable = sunset_get_option( 'sunset_topbar_enable' );
		$topbar_container_class = sunset_get_option( 'sunset_topbar_full_width' ) ? 'container-fluid' : 'container';
		$is_topbar_runline_enable = sunset_get_option( 'sunset_topbar_runline' );
		$topbar_runline_duration = sunset_get_option( 'sunset_topbar_runline_duration' );
		$topbar_content = sunset_get_option( 'sunset_topbar_content' );

		if ( $is_topbar_enable ) {
		?>
			<section class="<?php echo sunset_get_classes('topbar'); ?>" data-speed="<?php echo esc_attr( $is_topbar_runline_enable ? $topbar_runline_duration : ''); ?>">
				<div class="<?php echo esc_attr($topbar_container_class); ?>">
					<div class="topbar__inner <?php echo !$is_topbar_runline_enable ? 'dragscroll' : ''; ?>">
						<div class="topbar__inner__content">
							<?php if ( !empty($topbar_content) ) : ?>
								<?php echo wp_kses($topbar_content, 'post'); ?>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</section>
		<?php
		}
	}
}


if ( ! function_exists( 'sunset_toc' ) ) {
	add_action( 'sunset_before_main_content', 'sunset_toc', 10 );
	/**
	 * Output TOC (table of contents) for single posts
	 */
	function sunset_toc() {
		if (is_singular('post')) {
			$is_post_toc_enable = sunset_get_option('sunset_post_toc_enable');

			if (!$is_post_toc_enable) return true;

			$toc_tags = sunset_get_option('sunset_post_toc_tags');
			$toc_headlines = sunset_get_headlines(get_the_content());
			echo sunset_get_toc($toc_headlines, get_the_permalink(), $toc_tags);
		}
	}	
}


if ( ! function_exists( 'sunset_before_content_tags' ) ) {	
	add_action( 'sunset_before_main_content', 'sunset_before_content_tags', 10 );
	/**
	 * Output opening tags before main content
	 */
	function sunset_before_content_tags() {
		$layout_type = sunset_get_layout_type();

		$body_container_class = $layout_type === 'full' ? 'container-fluid' : 'container';
		$body_container_class .= is_singular('post') ? ' container--post' : '';
		?>
			<section class="content" id="content">
				<div class="<?php echo esc_attr($body_container_class); ?>">
					<?php 
					/**
					 * sunset_before_site_content hook.
					 */
					do_action( 'sunset_before_site_content');
					?>
					<div class="site-content">
		<?php
	}
}


if ( ! function_exists( 'sunset_after_content_tags' ) ) {	
	add_action( 'sunset_after_main_content', 'sunset_after_content_tags', 20 );
	/**
	 * Output closing tags after main content
	 */
	function sunset_after_content_tags() {
		?>
					</div> <!-- .site-content -->
					<?php 
					/**
					 * sunset_after_site_content hook.
					 * 
					 * @hooked sunset_do_comments_template - 5 (only for single posts)
					 * @hooked sunset_related_posts - 10 (only for single posts)
					 */
					do_action( 'sunset_after_site_content');
					?>
				</div> <!-- .container -->
			</section> <!-- .content -->
		<?php
	}
}


if ( ! function_exists( 'sunset_get_layout_type' ) ) {
	/**
	 * Get layout type for the current page
	 * 
	 * @return string 
	 */
	function sunset_get_layout_type() {
		$layout_type = sunset_get_option( 'sunset_layout_type' );

		if (is_home() || is_archive() || is_search()) {
			$layout_type = sunset_get_option( 'sunset_blog_layout_type' );
		}

		if (is_single()) {
			$layout_type = sunset_get_option( 'sunset_post_layout_type' );
		}

		return $layout_type;
	}	
}


if ( ! function_exists( 'sunset_header_left_open_tags' ) ) {	
	add_action( 'sunset_header_inner', 'sunset_header_left_open_tags', 1 );
	/**
	 * Output opening tags for the left side of the header
	 */
	function sunset_header_left_open_tags() {
		$header_type = sunset_get_option( 'sunset_header_type' );
		$tag = $header_type === 'header_2' ? 'nav' : 'div';
		?>
		<<?php echo esc_attr($tag); ?> class="main-nav main-nav--left">
		<?php
	}
}

if ( ! function_exists( 'sunset_header_left_close_tags' ) ) {	
	add_action( 'sunset_header_inner', 'sunset_header_left_close_tags', 20 );
	/**
	 * Output closing tags for the left side of the header
	 */
	function sunset_header_left_close_tags() {
		$header_type = sunset_get_option( 'sunset_header_type' );
		$tag = $header_type === 'header_2' ? 'nav' : 'div';
		?>
		</<?php echo esc_attr($tag); ?>>
		<?php
		if ( $header_type === 'header_2' ) {
			sunset_header_logo();
		}
	}
}


if ( ! function_exists( 'sunset_header_right_open_tags' ) ) {	
	add_action( 'sunset_header_inner', 'sunset_header_right_open_tags', 50 );
	/**
	 * Output opening tags for the right side of the header
	 */
	function sunset_header_right_open_tags() {
		?>
		<nav class="main-nav main-nav--right">
		<?php
	}
}


if ( ! function_exists( 'sunset_header_right_close_tags' ) ) {	
	add_action( 'sunset_header_inner', 'sunset_header_right_close_tags', 99 );
	/**
	 * Output closing tags for the right side of the header
	 */
	function sunset_header_right_close_tags() {
		?>
		</nav>
		<?php
	}
}


if ( ! function_exists( 'sunset_header_primary_menu' ) ) {
	/**
	 * Output primary menu of the header
	 * 
	 * @param string $theme_location - location of the menu
	 */
	function sunset_header_primary_menu( $theme_location ) {
		$header_menu_hover_type = sunset_get_option( 'sunset_header_menu_hover_type' );
		$is_header_burger_always = sunset_get_option( 'sunset_header_burger_always' );	
		$header_type = sunset_get_option( 'sunset_header_type' ) ;
		if ($is_header_burger_always) return true;
		wp_nav_menu(
			array(
				'theme_location' => $theme_location,
				'container' => false,
				'menu_class' => 'main-nav-menu main-nav-menu--regular main-nav-menu--'.$header_menu_hover_type,
				'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
				'link_before' => '<span>',
				'link_after' => '</span>',
				'fallback_cb' => $header_type === 'header_2' ? '__return_empty_string' : 'sunset_menu_not_found'
			)
		);
	}
}


if ( ! function_exists( 'sunset_header_left' ) ) {
	add_action( 'sunset_header_inner', 'sunset_header_left', 10 );
	/**
	 * Output header's left inner part
	 */
	function sunset_header_left() {
		$header_type = sunset_get_option( 'sunset_header_type' );
		switch ($header_type) :

			case 'header_1' : // logo on left - menu on right
				
				sunset_header_logo(); 

			break;
				
			case 'header_2' : // logo on center - menu on sides

				sunset_header_primary_menu('primary');				
	
			break;
	
			case 'header_3' : // logo and menu on left - socials and search on right
	
				sunset_header_logo();
	
				sunset_header_primary_menu('primary');
	
			break;

			case 'header_4' : // logo on left - burger menu on right
				
				sunset_header_logo(); 

			break;
	
		endswitch;
	}
}

if ( ! function_exists( 'sunset_header_right' ) ) {
	add_action( 'sunset_header_inner', 'sunset_header_right', 60 );
	/**
	 * Output header's right inner part
	 */
	function sunset_header_right() {
		$header_type = sunset_get_option( 'sunset_header_type' );
		switch ($header_type) :

			case 'header_1' : // logo on left - menu on right
				
				sunset_header_primary_menu('primary'); 

			break;
				
			case 'header_2' : // logo on center - menu on sides

				sunset_header_primary_menu('primary-right');
	
			break;
	
			case 'header_3' : // logo and menu on left - socials and search on right
	
			break;
	
		endswitch;
	}
}


if ( ! function_exists( 'sunset_construct_header' ) ) {
	add_action( 'sunset_header', 'sunset_construct_header', 10 );
	/**
	 * Output the header
	 */
	function sunset_construct_header() {
		$header_container_class = sunset_get_option( 'sunset_header_full_width' ) ? 'container-fluid' : 'container';
		$header_type = sunset_get_option( 'sunset_header_type' ) ;
		$is_mobile_social_links = false;
		?>

		<section class="header">
			<div class="<?php echo esc_attr($header_container_class); ?>">
				<div class="header__inner">

				<?php
				/**
				 * sunset_header_inner hook
				 * 
				 * @hooked sunset_header_left_open_tags - 1
				 * @hooked sunset_header_left - 10
				 * @hooked sunset_header_left_close_tags - 20
				 * @hooked sunset_header_right_open_tags - 50
				 * @hooked sunset_header_right - 60
				 * @hooked sunset_social_links - 70
				 * @hooked sunset_header_search - 80
				 * @hooked sunset_header_burger - 90
				 * @hooked sunset_fullscreen_menu - 95
				 * @hooked sunset_header_right_close_tags - 99
				 */
				do_action( 'sunset_header_inner', $is_mobile_social_links );
				?>

				</div>
			</div>
		</section>

		<?php
	}
}


if ( ! function_exists( 'sunset_preloader' ) ) {
	add_action( 'sunset_before_header', 'sunset_preloader', 1 );
	/**
	 * Output the preloader
	 */
	function sunset_preloader() {
		$is_preloader_enable = sunset_get_option('sunset_preloader_enable');

		if (!$is_preloader_enable)
			return true;
		?>
		<div id="sunset-preloader">
			<?php
			if ( has_custom_logo() ) {
				$custom_logo_id = get_theme_mod( 'custom_logo' );
    			$image = wp_get_attachment_image_src( $custom_logo_id , 'medium' );
				echo '<img src="'.$image[0].'" alt="'.get_bloginfo( 'name' ).'" />';
			} else {
				echo get_bloginfo( 'name' );
			}
			$loading_text = 'Loading';
			?>
			<div><span><?php echo apply_filters('sunset_preloader_loading_text', $loading_text); ?></span></div>
		</div>
		<?php
		
	}
}


if ( ! function_exists( 'sunset_custom_cursor' ) ) {	
	add_action( 'sunset_after_footer', 'sunset_custom_cursor', 99 );
	/**
	 * Output the custom cursor
	 */
	function sunset_custom_cursor() {
		$is_custom_cursor_enabled = sunset_get_option('sunset_style_custom_cursor_enable');
		$cursor_style = sunset_get_option('sunset_style_custom_cursor_style');
		if (!$is_custom_cursor_enabled) return true;
		
		echo apply_filters('sunset_custom_cursor', '
		<svg class="cursor cursor--'.$cursor_style.'" id="sunset-custom-cursor" width="25" height="25" viewBox="0 0 25 25">
			<circle class="cursor__inner" cx="12.5" cy="12.5" r="6.25"/>
		</svg>
		', $cursor_style);
	}
}


if ( ! function_exists( 'sunset_loop_post' ) ) {
	/**
	 * Output loop through posts
	 */
	function sunset_loop_post() {

		/**
		 * sunset_loop_post hook
		 * 
		 * @hooked sunset_loop_post_open_tags - 1
		 * @hooked sunset_loop_post_thumbnail - 5
		 * @hooked sunset_loop_post_content_open_tags - 10
		 * @hooked sunset_loop_post_categories - 15
		 * @hooked sunset_loop_post_title - 20
		 * @hooked sunset_loop_post_meta - 25
		 * @hooked sunset_loop_post_excerpt - 30
		 * @hooked sunset_loop_post_content_close_tags - 35
		 * @hooked sunset_loop_post_tags - 40
		 * @hooked sunset_loop_post_close_tags - 50
		 */
		do_action('sunset_loop_post');

	}
}


if ( ! function_exists( 'sunset_loop_opening_tags' ) ) {
	add_action( 'sunset_before_loop', 'sunset_loop_opening_tags', 10 );
	/**
	 * Before loop tags
	 * 
	 * @param string $section - name of a section (blog, post)
	 */
	function sunset_loop_opening_tags($section) {
		$blog_grid_type = sunset_get_option( 'sunset_blog_grid_type' );
		?>
		<section class="<?php echo sunset_get_classes($section); ?>">
			<div class="content-section__inner">
		<?php
	}
}


if ( ! function_exists( 'sunset_after_loop_extra_tags' ) ) {
	add_action( 'sunset_after_loop', 'sunset_after_loop_extra_tags', 10 );
	/**
	 * After loop helping html
	 */
	function sunset_after_loop_extra_tags() {
		if (!is_archive() && !is_home() && !is_search()) return true;
		
		$blog_grid_type = sunset_get_option( 'sunset_blog_grid_type' );
		if ($blog_grid_type === 'sticky') {
			echo '</div>'; // closing .aside-posts tag
		}
		if ($blog_grid_type === 'grid' || $blog_grid_type === 'grid-fluid') { // add (blog_grid_columns - 1) divs to fill the last row
			$blog_grid_columns = sunset_get_option( 'sunset_blog_grid_columns' );
			for ($i = 0; $i < ($blog_grid_columns - 1); $i += 1) {
				echo '<div class="loop-grid-empty-block"></div>';
			}
		}
	?>
		</div> <!-- .content-section__inner -->
	<?php
	}
}


if ( ! function_exists( 'sunset_content_closing_tags' ) ) {
	add_action( 'sunset_after_loop', 'sunset_content_closing_tags', 50 );
	/**
	 * Closing loop tags
	 */
	function sunset_content_closing_tags() {
	?>
		</section> <!-- .content-section -->
	<?php
	}
}


if ( ! function_exists( 'sunset_pagination' ) ) {
	add_action( 'sunset_after_loop', 'sunset_pagination', 20 );
	/**
	 * Pagination for archives
	 */
	function sunset_pagination() {
		if (!is_archive() && !is_home() && !is_search()) return true;

		$pagination_type = sunset_get_option( 'sunset_blog_pagination' );
		
		global $wp_query;

		if (  $wp_query->max_num_pages > 1 ) {

			if ($pagination_type === 'loadmore') {

				echo '<div class="pagination"><button data-loading-text="'.__('Loading...', 'my-sunset').'" data-more-text="'.__('Load more', 'my-sunset').'" class="pagination-loadmore">'.__('Load more', 'my-sunset').'</button></div>';
			
			} elseif( $pagination_type === 'infinite' ) {

				echo '<div class="pagination"><span class="pagination-spinner"></span></div>';

			} else {

				$big = 999999999;
				$args = [
					'base'         => str_replace($big,'%#%',esc_url(get_pagenum_link($big))),
					'format'       => '?page=%#%',
					'total'        => $wp_query->max_num_pages,
					'current'      => max(1, get_query_var('paged')),
					'show_all'     => false,
					'end_size'     => 1,
					'mid_size'     => 2,
					'prev_next'    => true,
					'prev_text'    => apply_filters('sunset_pagination_prev_text', '<svg width="30" height="34" viewBox="0 0 30 34" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.1721 8.73343L9.6456 9.20293C9.9594 9.51411 9.9594 10.0187 9.6456 10.3299L4.02542 15.8711H29.1964C29.6402 15.8711 30 16.2279 30 16.668V17.332C30 17.7721 29.6402 18.1289 29.1964 18.1289H4.02542L9.6456 23.6701C9.9594 23.9813 9.9594 24.4859 9.6456 24.7971L9.1721 25.2666C8.8583 25.5778 8.34951 25.5778 8.03572 25.2666L0.235382 17.5635C-0.078413 17.2523 -0.078413 16.7477 0.235382 16.4365L8.03572 8.73343C8.34951 8.42219 8.8583 8.42219 9.1721 8.73343Z" fill="black"/></svg>'),
					'next_text'    => apply_filters('sunset_pagination_next_text', '<svg width="30" height="34" viewBox="0 0 30 34" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20.8279 8.73343L20.3544 9.20293C20.0406 9.51411 20.0406 10.0187 20.3544 10.3299L25.9746 15.8711H0.803571C0.359799 15.8711 0 16.2279 0 16.668V17.332C0 17.7721 0.359799 18.1289 0.803571 18.1289H25.9746L20.3544 23.6701C20.0406 23.9813 20.0406 24.4859 20.3544 24.7971L20.8279 25.2666C21.1417 25.5778 21.6505 25.5778 21.9643 25.2666L29.7646 17.5635C30.0784 17.2523 30.0784 16.7477 29.7646 16.4365L21.9643 8.73343C21.6505 8.42219 21.1417 8.42219 20.8279 8.73343Z" fill="black"/></svg>'),
					'type'         => 'plain',
					'add_args'     => false,
					'add_fragment' => '',
					'before_page_number' => '',
					'after_page_number'  => ''
				];
				
				echo '<div class="pagination">'.paginate_links( $args ).'</div>';

			}

		}

	}
}


if ( ! function_exists( 'sunset_get_headlines' ) ) {
	/**
	 * Get all H1-6 headings in post (for the TOC)
	 * @see https://stackoverflow.com/questions/15628305/creating-a-table-of-contents-in-php
	 *
	 * @param string $html Posts contents
	 * @return array Array of headings
	 */
	function sunset_get_headlines($html){

		$has_headlines = preg_match_all('/<\s*h[1-6][^>]*>(.*?)<\s*\/\s*h[1-6]>/i', $html, $headlines);
		
		unset($headlines[1]);

		if (empty($headlines[0])) {
			return [];
		}

		$toc = [];

		foreach ($headlines[0] as $headline) {
			$tag = $text = $id = '';

			$is_tag = preg_match('/<\s*h[1-6]/i', $headline, $tags);
			if ($is_tag) {
				$tag = substr(trim($tags[0]), 1);
			}

			$text = strip_tags($headline);

			$is_id = preg_match('/id=(\"|\')(.*?)(\"|\')/i', $headline, $ids);

			if ($is_id) {
				$id = substr($ids[0], stripos($ids[0], 'id=') + 4);
				$id = str_replace( '"', "", $id);
				$id = str_replace( '\'', "", $id);
			}

			$toc[] = array(
				'id' => $id,
				'text' => $text,
				'tag' => $tag
			);
		}

		return $toc;
	}
}


if ( ! function_exists( 'sunset_get_toc' ) ) {
	/**
	 * Get table of contents
	 *
	 * @param array $toc Array of post's Headings
	 * @param string $link_to_htmlpage URL of the post
	 * @param array $tags Tags used for the TOC
	 * 
	 * @return string Table of contents
	 */
	function sunset_get_toc($toc, $link_to_htmlpage = '', $tags = array('h2', 'h3')) {
		if(empty($toc))
			return '';

		$toc_str = '';

		$toc_str = '<aside class="post__contents" id="post__contents"><div data-simplebar class="post__contents__holder"><ul class="post__contents__inner">';

		foreach($toc as $headline) {
			if ( in_array($headline['tag'], $tags) ) {
				$toc_str .= '<li class="post__contents__headline ' . ($headline['id'] === '' ? ' post__contents__headline--no-anchor' : '') . '">';

				if($headline['id'] !== '' ) {
					$toc_str .= '<a href="' . $link_to_htmlpage . '#' . $headline['id'] . '">';
				} else {
					$toc_str .= '<a href="#">';
				}

				$toc_str .= $headline['text'];
				$toc_str .= '</a>';
				$toc_str .= '</li>';
			}
		}

		$toc_str .= '</div></ul></aside>';

		return $toc_str;
	}
}


if ( ! function_exists( 'sunset_construct_footer' ) ) {
	add_action( 'sunset_footer', 'sunset_construct_footer', 10 );
	/**
	 * Output the footer
	 */
	function sunset_construct_footer() {
		$footer_type = sunset_get_option( 'sunset_footer_type' );
		$footer_container_class = sunset_get_option( 'sunset_footer_full_width' ) ? 'container-fluid' : 'container';
		if ($footer_type  === 'footer_1') { // columns
			$footer_columns = sunset_get_option( 'sunset_footer_columns' );
		}
		if ($footer_type  === 'footer_2') { // cross
			$footer_columns = 4;
		}
		?>
		
		<div class="<?php echo esc_attr($footer_container_class); ?>">
			<div class="site-footer__inner">
				<?php for ($i = 1; $i <= $footer_columns; $i += 1) : ?>
					<?php if ( $footer_type  === 'footer_2' || ($footer_type  === 'footer_1' && is_active_sidebar( 'footer-'.$i )) ) : ?>
						<div class="footer-column footer-column-<?php echo esc_attr($i); ?>">
							<?php dynamic_sidebar( 'footer-'.$i ); ?>
						</div>
					<?php endif; ?>
				<?php endfor; ?>
			</div>
		</div>
		
		<?php
	}
}


if ( ! function_exists( 'sunset_construct_copyright' ) ) {
	add_action( 'sunset_after_footer', 'sunset_construct_copyright', 10 );
	/**
	 * Output the copyright
	 */
	function sunset_construct_copyright() {
		$is_copyright_enabled = sunset_get_option( 'sunset_copyright_enable' );
		$copyright_container_class = sunset_get_option( 'sunset_copyright_full_width' ) ? 'container-fluid' : 'container';
		$is_copyright_runline_enable = sunset_get_option( 'sunset_copyright_runline' );
		$copyright_runline_duration = sunset_get_option( 'sunset_copyright_runline_duration' );	

		if ( $is_copyright_enabled ) {
		?>
		<section class="<?php echo sunset_get_classes('copyright'); ?>" data-speed="<?php echo esc_attr ($is_copyright_runline_enable ? $copyright_runline_duration : ''); ?>">
				<div class="<?php echo esc_attr($copyright_container_class); ?>">
					<div class="site-copyright__inner">
						<div class="site-copyright__inner__content">
							<?php if ( is_active_sidebar( 'copyright' ) ) : ?>
								<?php dynamic_sidebar( 'copyright' ); ?>
							<?php else: ?>
								<?php echo "<p>".__("Copyright © 2022 My Sunset by Bogdan Bendziukov.", 'my-sunset')."</p>"; ?>
							<?php endif; ?>
						</div>
					</div>
				</div>
		</section>
		<?php
		}
	}
}


if ( ! function_exists( 'sunset_get_h1_h6_tags' ) ) {
	/**
	 * Get H1-H6 tags
	 * 
	 * @return array List of H1-H6 tags
	 */
	function sunset_get_h1_h6_tags () {
		return apply_filters(
			'sunset_h1_h6_tags',
			array (
				'h1' => 'H1',
				'h2' => 'H2',
				'h3' => 'H3',
				'h4' => 'H4',
				'h5' => 'H5',
				'h6' => 'H6',
			)
		);
	}
}


if ( ! function_exists( 'sunset_get_text_animations' ) ) {
	/**
	 * Get list of animations for texts
	 * 
	 * @return array List of animations
	 */
	function sunset_get_text_animations () {
		return apply_filters(
			'sunset_text_animations',
			array (
				'slide_up'   => 'Slide up',
				'slide_down'   => 'Slide down',
				'slide_right'   => 'Slide right',
				'slide_left'   => 'Slide left',
				'typing'   => 'Typing text',
				'fade_in'   => 'Fade In',
				'morph'   => 'Morphing',
			)
		);
	}
}


if ( ! function_exists( 'sunset_get_image_animations' ) ) {
	/**
	 * Get list of animations for images
	 * 
	 * @return array List of image animations
	 */
	function sunset_get_image_animations () {
		return apply_filters(
			'sunset_image_animations',
			array (
				'slide_up'   => 'Slide up',
				'slide_down'   => 'Slide down',
				'slide_right'   => 'Slide right',
				'slide_left'   => 'Slide left',
				'fade_in'   => 'Fade In',
				'morph'   => 'Morphing',
			)
		);
	}
}


if ( ! function_exists( 'sunset_get_sidebar' ) ) {
	add_action('sunset_before_main_content', 'sunset_get_sidebar', 10, 1);
	/**
	 * Output sidebar
	 * 
	 * @param string $sidebar - name of a sidebar (blog, post)
	 */
	function sunset_get_sidebar($sidebar) {
		if (is_page()) return true;

		$sidebar_position = sunset_get_option('sunset_'.$sidebar.'_sidebar_position');		
		if ($sidebar_position !== 'none') {
		?>
		<aside class="<?php echo sunset_get_classes('sidebar_'.$sidebar.'_'.$sidebar_position); ?>">
			<div class="sidebar__inner__placeholder"></div>
			<div class="sidebar__inner">
				<?php dynamic_sidebar('sidebar-'.$sidebar); ?>
			</div>
		</aside>
		<?php
		}
	}
}


if ( ! function_exists( 'sunset_heading_title' ) ) {
	add_action( 'sunset_before_main_content', 'sunset_heading_title', 5 );
	/**
	 * Output the title for the archive, post, page
	 */
	function sunset_heading_title() {
		if ( is_front_page() ) return true;

		if (is_singular('post')) {
			$post_header_type = sunset_get_option('sunset_post_header_type');
			$post_meta_position = sunset_get_option('sunset_post_meta_position');

			if ($post_header_type === 'split') {
				add_action( 'sunset_content_header', 'sunset_content_heading_split_open_tags', 15 );
				add_action( 'sunset_content_header', 'sunset_content_heading_split_close_tags', 60 );
			} 
			if ($post_meta_position === 'top') {
				remove_action( 'sunset_after_loop', 'sunset_single_meta', 15 );
				add_action( 'sunset_content_header', 'sunset_single_meta', 50 );
			}
		}

		if (is_page()) {
			$page_header_type = sunset_get_option('sunset_page_header_type');
			$is_page_hide_title = sunset_get_option('sunset_page_hide_title');
			$is_show_page_breadcrumbs = sunset_get_option('sunset_page_show_breadcrumbs');
			$is_hide_title = ($page_header_type === 'default' && $is_page_hide_title) ? true : false;

			if (!$is_show_page_breadcrumbs && $is_hide_title) return true; // dont show the heading section if nothing to show :)

			if ($page_header_type === 'split') {
				add_action( 'sunset_content_header', 'sunset_content_heading_split_open_tags', 15 );
				add_action( 'sunset_content_header', 'sunset_content_heading_split_close_tags', 60 );
			}
		}
		
		/**
		 * sunset_content_header hook.
		 *
		 * @hooked sunset_open_content_heading_tags - 5
		 * @hooked sunset_thumbnail - 10
		 * @hooked sunset_breadcrumbs - 20
		 * @hooked sunset_title - 30
		 * @hooked sunset_category_description - 32
		 * @hooked sunset_post_subtitle - 32
		 * @hooked sunset_posts_found - 35
		 * @hooked sunset_single_date - 40
		 * @hooked sunset_single_meta - 50
		 * @hooked sunset_close_content_heading_tags - 70
		 */
		do_action( 'sunset_content_header' );
		
	}
}


if ( ! function_exists( 'sunset_content_heading_split_open_tags' ) ) {
	/**
	 * Open tags for the header with 'split' style 
	 */
	function sunset_content_heading_split_open_tags() {
		$is_show_post_meta = sunset_get_option('sunset_post_meta_show') && is_single();
		$has_meta_class =  $is_show_post_meta ? 'with-meta' : '';
		?>
			<div class="heading-section--split__content <?php echo esc_attr($has_meta_class); ?>">
		<?php
	}
}


if ( ! function_exists( 'sunset_content_heading_split_close_tags' ) ) {
	/**
	 * Close tags for the header with 'split' style 
	 */
	function sunset_content_heading_split_close_tags() {    
		?>
			</div>
		<?php
	}
}


if ( ! function_exists( 'sunset_open_content_heading_tags' ) ) {
	add_action( 'sunset_content_header', 'sunset_open_content_heading_tags', 5 );
	/**
	 * Open tags for the post/page header
	 */
	function sunset_open_content_heading_tags() {
		$layout_type = sunset_get_layout_type();
		$body_container_class =  'container-fluid';       
		?>
		<header class="<?php echo sunset_get_classes('heading_section'); ?>">
			<div class="<?php echo esc_attr($body_container_class); ?>">
		<?php
	}
}


if ( ! function_exists( 'sunset_thumbnail' ) ) {
	add_action( 'sunset_content_header', 'sunset_thumbnail', 10 );
	/**
	 * Output thumbnail for the single post/page
	 */
	function sunset_thumbnail() {
		$page_header_type = sunset_get_option('sunset_page_header_type');
		$post_header_type = sunset_get_option('sunset_post_header_type');
		if ( ( is_singular('post') && $post_header_type !== 'default' ) || ( is_page() && $page_header_type !== 'default' ) ) {
			if (has_post_thumbnail()) {
				if ( (is_page() && $page_header_type === 'big-text') || (is_singular('post') && $post_header_type === 'big-text') ) {
					the_post_thumbnail('', array('class' => 'add-magnetic'));
				} else {
					the_post_thumbnail();
				}
				
			} elseif( ( is_page() && $page_header_type === 'split' ) || ( is_singular('post') && $post_header_type === 'split' ) ) {
				// for single posts/pages print random svg thumbnail
				$rand_number = rand(1,6);
				$url = get_template_directory_uri().'/assets/images/no-image-single-'.$rand_number.'.svg';
				echo '<img src="'.apply_filters('sunset_default_page_thumbnail_url', $url).'" alt="" class="wp-post-image no-image" />';
			}
		}
	}
}


if ( ! function_exists( 'sunset_title' ) ) {
	add_action( 'sunset_content_header', 'sunset_title', 30 );
	/**
	 * Output title for the single post/page, archive
	 */
	function sunset_title() {     
		if (is_single() || is_page()) {
			$page_header_type = sunset_get_option('sunset_page_header_type');
			$is_page_hide_title = sunset_get_option('sunset_page_hide_title');
			$is_hide_title = is_page() && $page_header_type === 'default' && $is_page_hide_title ? true : false;
			$post_title = get_the_title();

			if ($is_hide_title) return true;
			?>

			<h1 class="<?php echo sunset_get_classes('post_title'); ?>"><?php echo esc_html($post_title); ?></h1>

			<?php
		}
		if (is_archive() || is_home()) {
			$archive_title = is_home() ? get_the_title(get_option('page_for_posts')) : get_the_archive_title();
			$blog_title_type = sunset_get_option( 'sunset_blog_title_type' );

			if ($blog_title_type === 'siblings') {

				if (is_home()) {
					$taxonomy = 'category';
					$current_term_id = get_queried_object_id();
				} elseif (is_date()) {
					$type = '';
					$current_term_id = $archive_title;

					if (is_year()) $type = 'yearly';
					if (is_month()) $type = 'monthly'; 
					if (is_day()) $type = 'daily';

					$sibling_terms = wp_get_archives(array(
						'type' => $type,
						'format' => 'custom',
						'echo' => false,
					));

					$sibling_terms = explode("</a>", $sibling_terms);
					$sibling_terms = array_map(function($el){
						return $el."</a>";
					}, $sibling_terms);

				} elseif (is_author()) {
					$current_term_id = $archive_title;

					$sibling_terms = wp_list_authors(array(
						'style' => 'none',
						'echo' => false,
					));

					$sibling_terms = explode(",", $sibling_terms);

				} else {
					$current_term = get_queried_object();
					$taxonomy = $current_term->taxonomy;
					$current_term_id = $current_term->term_id;
				}

				if (!is_date() && !is_author()) {
					$sibling_terms = get_terms( array(
						'taxonomy' => $taxonomy,
						'orderby'       => 'title',
						'order'         => 'ASC',
						'hide_empty' => true,
						'number' => is_home() ? 6 : 0,
					) );
				}

				if ($sibling_terms) :
					$was_current = false;
					$siblings_arr = [];
					?>
					<div class="heading-section__titles">
					<?php
					foreach( $sibling_terms as $key => $sibling ) :

						if ( is_home() ) :
							$sibling_terms = array_values($sibling_terms);
							$siblings_arr[] = isset($sibling_terms[0]) ? $sibling_terms[0] : null;
							$siblings_arr[] = isset($sibling_terms[1]) ? $sibling_terms[1] : null;
							$siblings_arr[] = isset($sibling_terms[2]) ? $sibling_terms[2] : null;
							$siblings_arr[] = isset($sibling_terms[3]) ? $sibling_terms[3] : null;
							$siblings_arr[] = isset($sibling_terms[4]) ? $sibling_terms[4] : null;
							$siblings_arr[] = isset($sibling_terms[5]) ? $sibling_terms[5] : null;

							foreach( $siblings_arr as $key2 => $sibling_term ) :
								if (!$sibling_term) continue;
								?>
								<?php if ($key2 < 3) : ?>
									<a class="<?php echo sunset_get_classes('blog_title'); ?> title--sibling" href="<?php echo get_term_link($sibling_term->term_id); ?>"><?php echo esc_html($sibling_term->name); ?></a>
								<?php endif; ?>	
								<?php if ($key2 === 2) : ?>
									<h1 class="<?php echo sunset_get_classes('blog_title'); ?> title--current"><?php echo esc_html($archive_title); ?></h1>
								<?php endif; ?>
								<?php if ($key2 > 2) : ?>
									<a class="<?php echo sunset_get_classes('blog_title'); ?> title--sibling" href="<?php echo get_term_link($sibling_term->term_id); ?>"><?php echo esc_html($sibling_term->name); ?></a>
								<?php endif; ?>
							<?php endforeach;
							
							break;
						elseif ( is_date() || is_author() ) :
							$sibling = trim(strip_tags($sibling));

							if ($current_term_id == $sibling) :
								$siblings_arr[] = isset($sibling_terms[$key + 3]) ? $sibling_terms[$key + 3] : null;
								$siblings_arr[] = isset($sibling_terms[$key + 2]) ? $sibling_terms[$key + 2] : null;
								$siblings_arr[] = isset($sibling_terms[$key + 1]) ? $sibling_terms[$key + 1] : null;
								$siblings_arr[] = $sibling_terms[$key];
								$siblings_arr[] = isset($sibling_terms[$key - 1]) ? $sibling_terms[$key - 1] : null;
								$siblings_arr[] = isset($sibling_terms[$key - 2]) ? $sibling_terms[$key - 2] : null;
								$siblings_arr[] = isset($sibling_terms[$key - 3]) ? $sibling_terms[$key - 3] : null;

								foreach( $siblings_arr as $sibling_link ) :
									if (!$sibling_link) continue;
									?>
									<?php if (!$was_current && trim(strip_tags($sibling_link)) != $current_term_id) : ?>
										<?php echo str_replace("<a", '<a class="'.sunset_get_classes('blog_title').' title--sibling"', $sibling_link); ?>
									<?php endif; ?>	
									<?php if (trim(strip_tags($sibling_link)) == $current_term_id) : ?>
										<h1 class="<?php echo sunset_get_classes('blog_title'); ?> title--current"><?php echo esc_html($archive_title); ?></h1>
									<?php $was_current = true; continue; endif; ?>
									<?php if ($was_current) : ?>
										<?php echo str_replace("<a", '<a class="'.sunset_get_classes('blog_title').' title--sibling"', $sibling_link); ?>
									<?php endif; ?>
								<?php endforeach;
								break;
							endif;

						elseif ( !is_home() && !is_date() && $current_term_id === $sibling->term_id ) :
							$siblings_arr[] = isset($sibling_terms[$key - 3]) ? $sibling_terms[$key - 3] : null;
							$siblings_arr[] = isset($sibling_terms[$key - 2]) ? $sibling_terms[$key - 2] : null;
							$siblings_arr[] = isset($sibling_terms[$key - 1]) ? $sibling_terms[$key - 1] : null;
							$siblings_arr[] = $sibling_terms[$key];
							$siblings_arr[] = isset($sibling_terms[$key + 1]) ? $sibling_terms[$key + 1] : null;
							$siblings_arr[] = isset($sibling_terms[$key + 2]) ? $sibling_terms[$key + 2] : null;
							$siblings_arr[] = isset($sibling_terms[$key + 3]) ? $sibling_terms[$key + 3] : null;
							
							foreach( $siblings_arr as $sibling_term ) :
								if (!$sibling_term) continue;
								?>
								<?php if (!$was_current && $sibling_term->term_id !== $current_term_id) : ?>
									<a class="<?php echo sunset_get_classes('blog_title'); ?> title--sibling" href="<?php echo get_term_link($sibling_term->term_id); ?>"><?php echo esc_html($sibling_term->name); ?></a>
								<?php endif; ?>	
								<?php if ($sibling_term->term_id === $current_term_id) : ?>
									<h1 class="<?php echo sunset_get_classes('blog_title'); ?> title--current"><?php echo esc_html($archive_title); ?></h1>
								<?php $was_current = true; continue; endif; ?>
								<?php if ($was_current) : ?>
									<a class="<?php echo sunset_get_classes('blog_title'); ?> title--sibling" href="<?php echo get_term_link($sibling_term->term_id); ?>"><?php echo esc_html($sibling_term->name); ?></a>
								<?php endif; ?>
							<?php endforeach; ?>
							<?php 
							break;
						endif;
					endforeach;
					?>
					</div>
					<?php
				else : 
				?>
					<h1 class="<?php echo sunset_get_classes('blog_title'); ?>"><?php echo esc_html($archive_title); ?></h1>
				<?php
				endif;
			} else {
			?>			
				<h1 class="<?php echo sunset_get_classes('blog_title'); ?>"><?php echo esc_html($archive_title); ?></h1>			
			<?php 
			}
		}
		if (is_search()) {
			$archive_title = _x( 'Search for:', 'label', 'my-sunset' ).' '.get_search_query();
			?>
				<h1 class="<?php echo sunset_get_classes('blog_title'); ?>"><?php echo esc_html($archive_title); ?></h1>
			<?php
		}
	}
}


if ( ! function_exists( 'sunset_posts_found' ) ) {
	add_action( 'sunset_content_header', 'sunset_posts_found', 35 );
	/**
	 * Output posts count for the archive
	 */
	function sunset_posts_found() {     
		if (is_archive() || is_home() || is_search()) {
			$is_show_posts_count = sunset_get_option('sunset_blog_title_show_posts_count');

			if ($is_show_posts_count) { 
				global $wp_query;
				?>
					<div class="posts-found"><?php echo sprintf( _n( '%s post found', '%s posts found', $wp_query->found_posts, 'my-sunset'), $wp_query->found_posts ); ?></div>
				<?php 
			}
		}
	}
}

if ( ! function_exists( 'sunset_category_description' ) ) {
	add_action( 'sunset_content_header', 'sunset_category_description', 32 );
	/**
	 * Output category's description
	 */
	function sunset_category_description() {     
		if (is_category()) {
			$description = category_description();

			if ($description) {
				?>
				<div class="category-description"><?php echo $description; ?></div>
				<?php 
			}
		}
	}
}

if ( ! function_exists( 'sunset_post_subtitle' ) ) {
	add_action( 'sunset_content_header', 'sunset_post_subtitle', 32 );
	/**
	 * Output post's/page's subtitle
	 */
	function sunset_post_subtitle() {
		global $post;

		if (is_singular('post') || is_page()) {
			$subtitle = get_post_meta( $post->ID, '_sunset_post_subtitle', true );

			if ($subtitle) {
				?>
				<h2 class="post-subtitle"><?php echo $subtitle; ?></h2>
				<?php 
			}
		}
	}
}

if ( ! function_exists( 'sunset_close_content_heading_tags' ) ) {
	add_action( 'sunset_content_header', 'sunset_close_content_heading_tags', 70 );
	/**
	 * Close tags for the post/page header
	 */
	function sunset_close_content_heading_tags() {     
		?>
			</div>
		</header>
		<?php
	}
}

if ( ! function_exists( 'sunset_get_post_read_time' ) ) {
	/**
	 * Get post reading time
	 * @see https://gist.github.com/mynameispj/3170442 
	 * 
	 * @param integer $post_id - ID of the post
	 * @param integer $words_per_minute - average reading speed is between 230-280 words per minute
	 * 
	 * @return integer
	 */
	function sunset_get_post_read_time($post_id, $words_per_minute = 200) {
		$mypost = get_post($post_id);

		if (is_null($mypost))
			return null;

		$post_content = $mypost->post_content; // WordPress users only
		$word = str_word_count(strip_tags($post_content));
		$m = floor($word / $words_per_minute);
		$s = floor($word % $words_per_minute / ($words_per_minute / 60));
		$est = sprintf( ($m < 1 ? __("%d sec. read", 'my-sunset') : __("%d min. read", 'my-sunset') ), ($m < 1 ? $s : $m)  );

		return $est;
	}
}

if ( ! function_exists( 'sunset_get_text_separator' ) ) {
	/**
	 * Get separator for the text
	 * 
	 * @return string
	 */
	function sunset_get_text_separator() {
		return apply_filters('sunset_text_separator', '<span class="text-separator">/</span>');
	}
}

/*
 * Shows custom breadcrumbs
*/
if ( ! function_exists( 'sunset_custom_breadcrumbs' ) ) {
	function sunset_custom_breadcrumbs() {

		$text['home']     = __('Home', 'my-sunset'); 
		$text['category'] = '%s'; 
		$text['search']   = __('Search for:', 'my-sunset')."%s";
		$text['tag']      = '%s'; 
		$text['author']   = '%s';
		$text['404']      = __('404 not found', 'my-sunset');
		$text['page']     = '%s'; 
		$text['cpage']    = '%s';

		$wrap_before    = '<div class="breadcrumbs" itemscope itemtype="http://schema.org/BreadcrumbList"><ul>';
		$wrap_after     = '</ul></div><!-- .breadcrumbs -->';
		$sep            = '';
		$before         = '<span class="breadcrumbs__current">';
		$after          = '</span>';

		$show_on_home   = 0; 
		$show_home_link = 1;
		$show_current   = 1;
		$show_last_sep  = 1; 

		global $post;
		$home_url       = home_url('/');
		$link           = '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">';
		$link          .= '<a class="breadcrumbs__link" href="%1$s" itemprop="item"><span itemprop="name">%2$s</span></a>';
		$link          .= '<meta itemprop="position" content="%3$s" />';
		$link          .= '</li>';
		$parent_id      = ( $post ) ? $post->post_parent : '';
		$home_link      = sprintf( $link, $home_url, $text['home'], 1 );

		if ( is_home() || is_front_page() ) {

			if ( $show_on_home ) echo $wrap_before . $home_link . $wrap_after;

		} else {

			$position = 0;

			echo $wrap_before;

			if ( $show_home_link ) {
				$position += 1;
				echo $home_link;
			}

			if ( is_category() ) {
				$parents = get_ancestors( get_query_var('cat'), 'category' );
				foreach ( array_reverse( $parents ) as $cat ) {
					$position += 1;
					if ( $position > 1 ) echo $sep;
					echo sprintf( $link, get_category_link( $cat ), get_cat_name( $cat ), $position );
				}
				if ( get_query_var( 'paged' ) ) {
					$position += 1;
					$cat = get_query_var('cat');
					echo $sep . sprintf( $link, get_category_link( $cat ), get_cat_name( $cat ), $position );
					echo $sep . $before . sprintf( $text['page'], get_query_var( 'paged' ) ) . $after;
				} else {
					if ( $show_current ) {
						if ( $position >= 1 ) echo $sep;
						echo $before . sprintf( $text['category'], single_cat_title( '', false ) ) . $after;
					} elseif ( $show_last_sep ) echo $sep;
				}

			} elseif ( is_search() ) {
				if ( get_query_var( 'paged' ) ) {
					$position += 1;
					if ( $show_home_link ) echo $sep;
					echo sprintf( $link, $home_url . '?s=' . get_search_query(), sprintf( $text['search'], get_search_query() ), $position );
					echo $sep . $before . sprintf( $text['page'], get_query_var( 'paged' ) ) . $after;
				} else {
					if ( $show_current ) {
						if ( $position >= 1 ) echo $sep;
						echo $before . sprintf( $text['search'], get_search_query() ) . $after;
					} elseif ( $show_last_sep ) echo $sep;
				}

			} elseif ( is_year() ) {
				if ( $show_home_link && $show_current ) echo $sep;
				if ( $show_current ) echo $before . get_the_time('Y') . $after;
				elseif ( $show_home_link && $show_last_sep ) echo $sep;

			} elseif ( is_month() ) {
				if ( $show_home_link ) echo $sep;
				$position += 1;
				echo sprintf( $link, get_year_link( get_the_time('Y') ), get_the_time('Y'), $position );
				if ( $show_current ) echo $sep . $before . get_the_time('F') . $after;
				elseif ( $show_last_sep ) echo $sep;

			} elseif ( is_day() ) {
				if ( $show_home_link ) echo $sep;
				$position += 1;
				echo sprintf( $link, get_year_link( get_the_time('Y') ), get_the_time('Y'), $position ) . $sep;
				$position += 1;
				echo sprintf( $link, get_month_link( get_the_time('Y'), get_the_time('m') ), get_the_time('F'), $position );
				if ( $show_current ) echo $sep . $before . get_the_time('d') . $after;
				elseif ( $show_last_sep ) echo $sep;

			} elseif ( is_single() && ! is_attachment() ) {
				if ( get_post_type() != 'post' ) {
					$position += 1;
					$post_type = get_post_type_object( get_post_type() );
					if ( $position > 1 ) echo $sep;
					echo sprintf( $link, get_post_type_archive_link( $post_type->name ), $post_type->labels->name, $position );
					if ( $show_current ) echo $sep . $before . get_the_title() . $after;
					elseif ( $show_last_sep ) echo $sep;
				} else {
					$cat = get_the_category(); $catID = $cat[0]->cat_ID;
					$parents = get_ancestors( $catID, 'category' );
					$parents = array_reverse( $parents );
					$parents[] = $catID;
					foreach ( $parents as $cat ) {
						$position += 1;
						if ( $position > 1 ) echo $sep;
						echo sprintf( $link, get_category_link( $cat ), get_cat_name( $cat ), $position );
					}
					if ( get_query_var( 'cpage' ) ) {
						$position += 1;
						echo $sep . sprintf( $link, get_permalink(), get_the_title(), $position );
						echo $sep . $before . sprintf( $text['cpage'], get_query_var( 'cpage' ) ) . $after;
					} else {
						if ( $show_current ) echo $sep . $before . get_the_title() . $after;
						elseif ( $show_last_sep ) echo $sep;
					}
				}

			} elseif ( is_post_type_archive() ) {
				$post_type = get_post_type_object( get_post_type() );
				if ( get_query_var( 'paged' ) ) {
					$position += 1;
					if ( $position > 1 ) echo $sep;
					echo sprintf( $link, get_post_type_archive_link( $post_type->name ), $post_type->label, $position );
					echo $sep . $before . sprintf( $text['page'], get_query_var( 'paged' ) ) . $after;
				} else {
					if ( $show_home_link && $show_current ) echo $sep;
					if ( $show_current ) echo $before . $post_type->label . $after;
					elseif ( $show_home_link && $show_last_sep ) echo $sep;
				}

			} elseif ( is_attachment() ) {
				$parent = get_post( $parent_id );
				$cat = get_the_category( $parent->ID ); $catID = $cat[0]->cat_ID;
				$parents = get_ancestors( $catID, 'category' );
				$parents = array_reverse( $parents );
				$parents[] = $catID;
				foreach ( $parents as $cat ) {
					$position += 1;
					if ( $position > 1 ) echo $sep;
					echo sprintf( $link, get_category_link( $cat ), get_cat_name( $cat ), $position );
				}
				$position += 1;
				echo $sep . sprintf( $link, get_permalink( $parent ), $parent->post_title, $position );
				if ( $show_current ) echo $sep . $before . get_the_title() . $after;
				elseif ( $show_last_sep ) echo $sep;

			} elseif ( is_page() && ! $parent_id ) {
				if ( $show_home_link && $show_current ) echo $sep;
				if ( $show_current ) echo $before . get_the_title() . $after;
				elseif ( $show_home_link && $show_last_sep ) echo $sep;

			} elseif ( is_page() && $parent_id ) {
				$parents = get_post_ancestors( get_the_ID() );
				foreach ( array_reverse( $parents ) as $pageID ) {
					$position += 1;
					if ( $position > 1 ) echo $sep;
					echo sprintf( $link, get_page_link( $pageID ), get_the_title( $pageID ), $position );
				}
				if ( $show_current ) echo $sep . $before . get_the_title() . $after;
				elseif ( $show_last_sep ) echo $sep;

			} elseif ( is_tag() ) {
				if ( get_query_var( 'paged' ) ) {
					$position += 1;
					$tagID = get_query_var( 'tag_id' );
					echo $sep . sprintf( $link, get_tag_link( $tagID ), single_tag_title( '', false ), $position );
					echo $sep . $before . sprintf( $text['page'], get_query_var( 'paged' ) ) . $after;
				} else {
					if ( $show_home_link && $show_current ) echo $sep;
					if ( $show_current ) echo $before . sprintf( $text['tag'], single_tag_title( '', false ) ) . $after;
					elseif ( $show_home_link && $show_last_sep ) echo $sep;
				}

			} elseif ( is_author() ) {
				$author = get_userdata( get_query_var( 'author' ) );
				if ( get_query_var( 'paged' ) ) {
					$position += 1;
					echo $sep . sprintf( $link, get_author_posts_url( $author->ID ), sprintf( $text['author'], $author->display_name ), $position );
					echo $sep . $before . sprintf( $text['page'], get_query_var( 'paged' ) ) . $after;
				} else {
					if ( $show_home_link && $show_current ) echo $sep;
					if ( $show_current ) echo $before . sprintf( $text['author'], $author->display_name ) . $after;
					elseif ( $show_home_link && $show_last_sep ) echo $sep;
				}

			} elseif ( is_404() ) {
				if ( $show_home_link && $show_current ) echo $sep;
				if ( $show_current ) echo $before . $text['404'] . $after;
				elseif ( $show_last_sep ) echo $sep;

			} elseif ( has_post_format() && ! is_singular() ) {
				if ( $show_home_link && $show_current ) echo $sep;
				echo get_post_format_string( get_post_format() );
			}

			echo $wrap_after;

		}
	}
}

if ( ! function_exists( 'sunset_breadcrumbs' ) ) {
	add_action( 'sunset_content_header', 'sunset_breadcrumbs', 20 );
	/**
	 * Output breadcrumbs
	 */
	function sunset_breadcrumbs() {
		$is_show_post_breadcrumbs = sunset_get_option('sunset_post_show_breadcrumbs');
		$is_show_page_breadcrumbs = sunset_get_option('sunset_page_show_breadcrumbs');
		$is_show_blog_breadcrumbs = sunset_get_option('sunset_blog_title_show_breadcrumbs');

		if ( (is_single() && $is_show_post_breadcrumbs) || (is_page() && $is_show_page_breadcrumbs) ||
			( (is_archive() || is_home() || is_search()) && $is_show_blog_breadcrumbs) ) {
			if ( function_exists('yoast_breadcrumb') ) {
				yoast_breadcrumb( '<div class="breadcrumbs">','</div>' );
			} else {
				sunset_custom_breadcrumbs();
			}
		}
	}
}


if ( ! function_exists( 'sunset_single_meta' ) ) {
	add_action( 'sunset_after_loop', 'sunset_single_meta', 15 );
	/**
	 * Show meta data for a single post/page
	 */
	function sunset_single_meta() {
		global $post;
		$is_show_post_meta = sunset_get_option('sunset_post_meta_show');

		if (is_singular('post') && $is_show_post_meta) {
			$post_categories = get_the_category($post->ID);
			$post_tags = get_the_tags($post->ID);
			$is_post_show_default_category = sunset_get_option('sunset_post_show_default_category');
			$default_category_id = get_option('default_category');
			?>
			<div class="post-meta">
				<?php if ( ($is_post_show_default_category && $post_categories) ||
					(!$is_post_show_default_category && count($post_categories) > 1) ) : ?>
					<dl>
						<dt><i class="fas fa-folder"></i></dt>
						<dd>
							<ul class="post-meta__categories">
								<?php foreach ($post_categories as $category) : ?>
									<?php if (!$is_post_show_default_category && $category->term_id == $default_category_id) continue; ?>
									<li><a href="<?php echo get_term_link($category->term_id); ?>"><?php echo esc_html($category->name); ?></a></li>
								<?php endforeach; ?>
							</ul>
						</dd>
					</dl>
				<?php endif; ?>

				<?php if ($post_tags) : ?>
					<dl>
						<dt><i class="fas fa-tag"></i></dt>
						<dd>
							<ul class="post-meta__tags">
								<?php foreach ($post_tags as $tag) : ?>
									<li><a href="<?php echo get_term_link($tag->term_id); ?>"><?php echo esc_html($tag->name); ?></a></li>
								<?php endforeach; ?>
							</ul>
						</dd>
					</dl>
				<?php endif; ?>
				
			</div>
			<?php 
		}
	}
}


if ( ! function_exists( 'sunset_single_date' ) ) {
	add_action( 'sunset_content_header', 'sunset_single_date', 40 );
	/**
	 * Show date and/or read time for a single post
	 */
	function sunset_single_date() {
		if (!is_singular('post')) return false;

		global $post;
		$is_post_show_date = sunset_get_option( 'sunset_post_show_date' );
		$is_post_show_read_time = sunset_get_option( 'sunset_post_show_read_time' );

		if ( $is_post_show_date || $is_post_show_read_time ) : ?>
			<div class="post-date">
				<?php if ( $is_post_show_date ) : ?>
					<span class="post-date__date">
						<?php echo get_the_date('', $post->ID); ?>
					</span>
				<?php endif; ?>
				<?php if ( $is_post_show_date && $is_post_show_read_time ) : ?>
					<?php echo sunset_get_text_separator(); ?>
				<?php endif; ?>
				<?php if ( $is_post_show_read_time ) : ?>
					<span class="post-date__read-time">
						<?php echo sunset_get_post_read_time($post->ID); ?>
					</span>
				<?php endif; ?>
			</div>
		<?php endif; 
	}
}


if ( ! function_exists( 'sunset_related_posts' ) ) {
	add_action( 'sunset_after_site_content', 'sunset_related_posts', 10 );
	/**
	 * Output related posts
	 */
	function sunset_related_posts() {
		$is_related_posts_enabled = sunset_get_option('sunset_post_related_show');

		if (!is_single() || !$is_related_posts_enabled) return;

		global $post;
		
		$number_of_related_posts = sunset_get_option('sunset_post_related_number');
		$related_posts_type = sunset_get_option( 'sunset_post_related_type' );
		$is_related_posts_title_show = sunset_get_option( 'sunset_post_related_title_show' );

		$args = array(
			'category__in' => wp_get_post_categories( $post->ID ), 
			'tax_query' => array(
				'relation' => 'OR',
				array(
					'taxonomy' => 'category',
					'field'    => 'id',
					'terms'    => wp_get_post_categories( $post->ID ), 
				),
				array(
					'taxonomy' => 'post_tag',
					'field'    => 'id',
					'terms'    => wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) ), 
				),
			),
			'posts_per_page'  => $number_of_related_posts, 
			'post__not_in' => array( $post->ID )
		);

		$query = new WP_Query( $args );

		if ( $query->have_posts() ) {
			?>
			<section class="<?php echo sunset_get_classes("related_posts"); ?>">			
				<?php
				if ($is_related_posts_title_show) {
					$related_posts_title_text = apply_filters("sunset_post_related_title_text", sunset_get_option( 'sunset_post_related_title_text' ));
					echo "<h3 class='related-posts__title'>".$related_posts_title_text."</h3>";
				}
				?>

				<div class="related-posts__inner">

					<?php
					while ( $query->have_posts() ) {
						$query->the_post();		
						sunset_related_post();
					}
					
					if ($related_posts_type === 'grid') { // add (related_posts_columns - 1) divs to fill the last row
						$related_posts_columns = sunset_get_option( 'sunset_post_related_columns' );
						for ($i = 0; $i < ($related_posts_columns - 1); $i += 1) {
							echo '<div class="loop-grid-empty-block"></div>';
						}
					}
					?>
					
				</div>
			</section>
			<?php
		}
		
		wp_reset_postdata();
	}
}

if ( ! function_exists( 'sunset_related_post' ) ) {
	/**
	 * Related post (loop)
	 */
	function sunset_related_post() {
		/**
		 * sunset_loop_related_post hook
		 * 
		 * @hooked sunset_loop_post_open_tags - 1
		 * @hooked sunset_loop_post_thumbnail - 5
		 * @hooked sunset_loop_post_content_open_tags - 10
		 * @hooked sunset_loop_post_categories - 15
		 * @hooked sunset_loop_post_title - 20
		 * @hooked sunset_loop_post_meta - 25
		 * @hooked sunset_loop_post_content_close_tags - 35
		 * @hooked sunset_loop_post_close_tags - 50
		 */
		do_action('sunset_loop_related_post');
	}
}

/**
 * Handle AJAX request for the load more posts action
 */
function sunset_loadmore_ajax_handler(){
 
	// prepare our arguments for the query
	$args = json_decode( stripslashes( $_POST['query'] ), true );
	$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
	$args['post_status'] = 'publish';
 
	// it is always better to use WP_Query but not here
	query_posts( $args );
 
	if( have_posts() ) :
 
		// run the loop
		while( have_posts() ): the_post();
 
			// look into your theme code how the posts are inserted, but you can use your own HTML of course
			// do you remember? - my example is adapted for Twenty Seventeen theme
			sunset_loop_post();
			// for the test purposes comment the line above and uncomment the below one
			// the_title();
 
 
		endwhile;
 
	endif;
	die; // here we exit the script and even no wp_reset_query() required!
}
add_action('wp_ajax_sunset_loadmore', 'sunset_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_sunset_loadmore', 'sunset_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}


add_filter('walker_nav_menu_start_el', 'sunset_add_image_before_menu_item', 10, 4);
/**
 * Output menu item's image for mobile menu
 */
function sunset_add_image_before_menu_item ($item_output, $item, $depth, $args) {
	if( strrpos($args->menu_class, 'main-nav-menu--mobile') === false ) {
		return $item_output;
	}
	$image_url = get_post_meta($item->ID, '_sunset_menu_image_url', true) ?: '';
	if ($image_url !== '') {
		$item_output = $item_output.'<img src="'.$image_url.'" alt="'.$item->post_title.'" class="menu-item-image menu-item-image-'.$item->ID.'" />';
	}
	
	return $item_output;
}

add_filter('walker_nav_menu_start_el', 'sunset_add_arrow_to_menu_item', 10, 4);
/**
 * Output menu item's adropdown arrow for sub-menu
 */
function sunset_add_arrow_to_menu_item ($item_output, $item, $depth, $args) {
	if( in_array('menu-item-has-children', $item->classes) && strrpos($args->menu_class, 'main-nav-menu--mobile') === false ) {
		$item_output = str_replace("</a>", "</a><button class='menu-item-arrow'></button>", $item_output);
	}
	
	return $item_output;
}


add_filter( 'get_the_archive_title_prefix', 'sunset_remove_archive_title_prefix', 10, 1 );
/**
 * Remove prefix from category and tag archive's title
 */
function sunset_remove_archive_title_prefix($prefix) {
	if (is_category() || is_tag() || is_date() || is_author()) {
		$prefix = '';
	}
	return $prefix;
}


add_filter( 'wp_lazy_loading_enabled', 'sunset_lazyload_images', 10, 3 );
/**
 * Handle loading=lazy atribute to images
 * Note! WordPress DOES NOT lazyload first media content, it handled by wp_omit_loading_attr_threshold filter, default is 1
 */
function sunset_lazyload_images($default, $tag_name, $context) {
	$is_image_lazy_loading = sunset_get_option('sunset_lazyload_images');

	if ( 'img' === $tag_name && 'the_content' === $context && !$is_image_lazy_loading ) { // disable lazyload for images in content if option disabled
        return false;
    }
    return $default;	
}


add_filter( 'wp_lazy_loading_enabled', 'sunset_lazyload_iframes', 10, 3 );
/**
 * Handle loading=lazy atribute to iframes
 */
function sunset_lazyload_iframes($default, $tag_name, $context) {
	$is_iframe_lazy_loading = sunset_get_option('sunset_lazyload_iframes');

	if ( 'iframe' === $tag_name && 'the_content' === $context && !$is_iframe_lazy_loading ) { // disable lazyload for iframes if option disabled
        return false;
    }
    return $default;	
}

add_filter( 'wp_get_attachment_image_attributes', 'sunset_remove_loading_from_images', 10, 3 );
/**
 * Remove loading=lazy attribute from images outside the_content if has class 'no-lazy' or disabled option in Customizer
 */
function sunset_remove_loading_from_images( $attr, $attachment, $size ) {
	$is_image_lazy_loading = sunset_get_option('sunset_lazyload_images');

    if ( !$is_image_lazy_loading || false !== strpos( $attr['class'], 'no-lazy' ) ) {
        unset( $attr['loading'] );
    }
    return $attr;
}

if ( ! function_exists( 'sunset_loop_post_open_tags' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_open_tags', 1);
	add_action('sunset_loop_related_post', 'sunset_loop_post_open_tags', 1);
	/**
	 * Output post's open tags in loop
	 */
	function sunset_loop_post_open_tags() {
		global $post, $wp_query;

		$blog_grid_type = sunset_get_option( 'sunset_blog_grid_type' );		

		if ( $blog_grid_type === 'sticky' && (is_archive() || is_home() || is_search()) ) {
			if ($wp_query->current_post === 0) {
				echo '<div class="primary-posts">';
			}
			if ($wp_query->current_post === 1) {
				echo '<div class="aside-posts">';
			}
		}
		?>

		<article id="post-<?php the_ID(); ?>" <?php post_class(sunset_get_classes('loop_post')); ?>>
			<div class="loop-post__inner">

		<?php
	}
}

if ( ! function_exists( 'sunset_loop_post_thumbnail' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_thumbnail', 5);
	add_action('sunset_loop_related_post', 'sunset_loop_post_thumbnail', 5);
	/**
	 * Output post's thumbnail in loop
	 */
	function sunset_loop_post_thumbnail() {
		global $post;

		$default_image_id = sunset_get_option('sunset_layout_default_image');

		if (has_post_thumbnail()) : ?>
			<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="loop-post__image">
				<?php the_post_thumbnail(); ?>
			</a>
		<?php else: ?>
			<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="loop-post__image no-image">
				<?php 
				if ($default_image_id) {
					echo wp_get_attachment_image($default_image_id, 'large');
				} else {
					echo '<img src="'.get_stylesheet_directory_uri().'/assets/images/no-image.png" alt="no-image" />';
				}
				?>
			</a>
		<?php endif;
	}
}

if ( ! function_exists( 'sunset_loop_post_content_open_tags' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_content_open_tags', 10);
	add_action('sunset_loop_related_post', 'sunset_loop_post_content_open_tags', 10);
	/**
	 * Output post's content open tags in loop
	 */
	function sunset_loop_post_content_open_tags() {
		?>

		<div class="loop-post__content">
			<div class="loop-post__aside">

		<?php
	}
}

if ( ! function_exists( 'sunset_loop_post_categories' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_categories', 15);
	add_action('sunset_loop_related_post', 'sunset_loop_post_categories', 15);
	/**
	 * Output post's categories in loop
	 */
	function sunset_loop_post_categories() {
		global $post, $wp_query;
	
		$is_blog_show_categories = sunset_get_option( 'sunset_blog_show_categories' );
		$post_categories = get_the_category($post->ID);
		$is_blog_show_default_category = sunset_get_option('sunset_blog_show_default_category');
		$default_category_id = get_option('default_category');

		if ($post_categories && $is_blog_show_categories) : ?>
			<ul class="loop-post__categories">
			<?php foreach ($post_categories as $category) : ?>
				<?php if (!$is_blog_show_default_category && $category->term_id == $default_category_id) continue; ?>
				<li><a href="<?php echo get_term_link($category->term_id); ?>"><?php echo esc_html($category->name); ?></a></li>
			<?php endforeach; ?>
			</ul>
		<?php endif;
	}
}

if ( ! function_exists( 'sunset_loop_post_title' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_title', 20);
	add_action('sunset_loop_related_post', 'sunset_loop_post_title', 20);
	/**
	 * Output post's title in loop
	 */
	function sunset_loop_post_title() {
		global $post;

		the_title( '<h3 class="title title--loop"><a href="'.get_the_permalink($post->ID).'">', '</a></h3>' );
	}
}

if ( ! function_exists( 'sunset_loop_post_meta' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_meta', 25);
	add_action('sunset_loop_related_post', 'sunset_loop_post_meta', 25);
	/**
	 * Output post's meta (date/read time) in loop
	 */
	function sunset_loop_post_meta() {
		global $post, $wp_query;
		
		$is_blog_show_date = sunset_get_option( 'sunset_blog_show_date' );
		$is_blog_show_read_time = sunset_get_option( 'sunset_blog_show_read_time' );		

		if ( $is_blog_show_date || $is_blog_show_read_time ) : ?>
			<div class="loop-post__meta">
				<?php if ( $is_blog_show_date ) : ?>
					<span class="loop-post__meta__date">
						<?php echo get_the_date('', $post->ID); ?>
					</span>
				<?php endif; ?>
				<?php if ( $is_blog_show_date && $is_blog_show_read_time ) : ?>
					<?php echo sunset_get_text_separator(); ?>
				<?php endif; ?>
				<?php if ( $is_blog_show_read_time ) : ?>
					<span class="loop-post__meta__read-time">
						<?php echo sunset_get_post_read_time($post->ID); ?>
					</span>
				<?php endif; ?>
			</div>
		<?php endif;
	}
}

if ( ! function_exists( 'sunset_loop_post_excerpt' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_excerpt', 30);
	/**
	 * Output post's excerpt in loop
	 */
	function sunset_loop_post_excerpt() {
		global $post, $wp_query;

		$blog_grid_type = sunset_get_option( 'sunset_blog_grid_type' );
		$is_blog_show_excerpt = sunset_get_option( 'sunset_blog_show_excerpt' );		

		if ( ( $blog_grid_type !== 'sticky' && $is_blog_show_excerpt ) || 
		( $blog_grid_type === 'sticky' && $wp_query->current_post === 0 && $is_blog_show_excerpt) ) : ?>
			<div class="loop-post__excerpt">
				<?php the_excerpt(); ?>
			</div>
		<?php endif;
	}
}


if ( ! function_exists( 'sunset_loop_post_content_close_tags' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_content_close_tags', 35);
	add_action('sunset_loop_related_post', 'sunset_loop_post_content_close_tags', 35);
	/**
	 * Output post's content close tags in loop
	 */
	function sunset_loop_post_content_close_tags() {
		?>
		</div> <!-- .loop-post__aside -->
		<?php
	}
}

if ( ! function_exists( 'sunset_loop_post_tags' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_tags', 40);
	/**
	 * Output post's tags in loop
	 */
	function sunset_loop_post_tags() {
		global $post, $wp_query;

		$is_blog_show_tags = sunset_get_option( 'sunset_blog_show_tags' );	
		$post_tags = get_the_tags($post->ID);
		
		if ($post_tags && $is_blog_show_tags) : ?>
			<ul class="loop-post__tags">
			<?php foreach ($post_tags as $tag) : ?>
				<li><a href="<?php echo get_term_link($tag->term_id); ?>"><?php echo esc_html($tag->name); ?></a></li>
			<?php endforeach; ?>
			</ul>
		<?php endif;
	}
}

if ( ! function_exists( 'sunset_loop_post_close_tags' ) ) {
	add_action('sunset_loop_post', 'sunset_loop_post_close_tags', 50);
	add_action('sunset_loop_related_post', 'sunset_loop_post_close_tags', 50);
	/**
	 * Output post's close tags in loop
	 */
	function sunset_loop_post_close_tags() {
		global $post, $wp_query;

		$blog_grid_type = sunset_get_option( 'sunset_blog_grid_type' );
		?>
				</div> <!-- .loop-post__content -->
			
			</div> <!-- .loop-post__inner -->
		</article>
		
		<?php
		if ( (is_archive() || is_home() || is_search()) && $wp_query->current_post === 0 && $blog_grid_type === 'sticky' ) { // add closing tag for the primary sticky post
			echo '</div>';
		}
	}
}

if ( ! function_exists( 'sunset_author_url_blank' ) ) {
	add_filter( 'get_comment_author_link', 'sunset_author_url_blank', 10, 3 );
	/**
	 * Open author's URL in a new tab
	 */
	function sunset_author_url_blank($html, $author, $comment_ID) {
		$html = str_replace( 'href', 'target="_blank" href', $html );

		return $html;
	}
}

if ( ! function_exists( 'sunset_404_content' ) ) {
	add_action( 'sunset_404_content', 'sunset_404_content', 10 );
	/**
	 * Output 404 content
	 */
	function sunset_404_content() {
	?>
	<header class="<?php echo sunset_get_classes('heading_section'); ?>">
		<div class="container">
			<h1 class="<?php echo sunset_get_classes('blog_title'); ?>"><?php _e('404 not found', 'my-sunset'); ?></h1>
			<br>
			<?php echo get_search_form(); ?>
		</div>
	</header>
	<?php
	}
}
