<?php
/**
 * TopPic theme functions and definitions
 *
 * When using a child theme you can override certain functions (those wrapped
 * in a function_exists() call) by defining them first in your child theme's
 * functions.php file. The child theme's functions.php file is included before
 * the parent theme's file, so the child theme functions would be used.
 *
 * @link https://codex.wordpress.org/Theme_Development
 * @link https://codex.wordpress.org/Child_Themes
 *
 * Functions that are not pluggable (not wrapped in function_exists()) are
 * instead attached to a filter or action hook.
 *
 * For more information on hooks, actions, and filters,
 * {@link https://codex.wordpress.org/Plugin_API}
 *
 */
 
/*-----------------------------------------------------------------------------------*/
/* INCLUDE NEEDED FILES
/*-----------------------------------------------------------------------------------*/
 
require_once get_theme_file_path( '/admin/main.php' );
require_once get_theme_file_path( '/includes/img-filters.php' );
require_once get_theme_file_path( '/includes/class-tgm-plugin-activation.php' );
require_once get_theme_file_path( '/includes/class-kk-get-options.php' );
require_once get_theme_file_path( '/extends/widget-flickr.php' );
require_once get_theme_file_path( '/extends/theme-meta-boxes.php' );
require_once get_theme_file_path( '/extends/widget-portfolio.php' );
require_once get_theme_file_path( '/admin/class_check_ver.php' );


/*-----------------------------------------------------------------------------------*/
/* SETS UP THEME DEFAULTS AND REGISTERS SUPPORT FOR VARIOUS WORDPRESS FEATURES
/*-----------------------------------------------------------------------------------*/

function toppic_setup() {

	/* MAKE THEME AVAILABLE FOR TRANSLATION */
	
	load_theme_textdomain('toppic', get_template_directory() . '/languages');

	/* ENABLE SUPPORT FOR POST THUMBNAILS ON POSTS AND PAGES */
	
	add_theme_support( 'post-thumbnails' );		

	add_image_size( 'kktfwp-xs', 500, false );
	add_image_size( 'kktfwp-s', 690, false );
	add_image_size( 'kktfwp-l', 1300, false );
	add_image_size( 'kktfwp-m', 1660, false );
	add_image_size( 'kktfwp-xl', 1920, false );
	add_image_size( 'kktfwp-xxl', 2560, false );
	
	/* Really huge image size for 5k HiDPI monitors support (will be used in the srcset attribute only) */
	add_image_size( 'kktfwp-xxxl', 5120, false );
	
	/* WOOCOMMERCE SUPPORT */
	
	add_theme_support( 'woocommerce' );	

	add_theme_support( 'wc-product-gallery-lightbox' );
	add_theme_support( 'wc-product-gallery-slider' );
	
	/* LET WORDPRESS MANAGE THE DOCUMENT TITLE */
	
	add_theme_support( 'title-tag' );
	
	
	/* POST FORMATS */	

	$format_types =	array(
						'gallery',
						'link',
						'image',
						'quote',
						'video');

	add_theme_support('post-formats', $format_types);

	/* REGISTER MENU */	
	
	add_theme_support( 'nav-menus' );

	register_nav_menus( array(
		'main-menu' 	=> esc_html__( 'Main Navigation', 'toppic' ), // MAIN MENU
		'footer-menu' 	=> esc_html__( 'Footer Navigation', 'toppic' ), // FOOTER MENU
	) );
	
	/* ADD DEFAULT POSTS AND COMMENTS RSS FEED LINKS TO HEAD */
	
	add_theme_support('automatic-feed-links' );		

}

add_action('after_setup_theme', 'toppic_setup');


/*-----------------------------------------------------------------------------------*/
/* CURRENT THEME VERSION
/*-----------------------------------------------------------------------------------*/

if ( ! defined( 'KKFW_VERSION' ) ) {

	define( 'KKFW_VERSION', '2.7' );	
}


/*-----------------------------------------------------------------------------------*/
/* CHECK IF META PLUGIN INSTALLED
/*-----------------------------------------------------------------------------------*/

if ( !function_exists('rwmb_meta') ) {
	function rwmb_meta() {
		return false;
	}
} else {
	function kktfwp_meta_style() {
		wp_enqueue_style( 'kktfwp-meta-style', get_theme_file_uri( '/css/meta-style.css' ), '', KKFW_VERSION );
	}	
	add_action('admin_enqueue_scripts', 'kktfwp_meta_style');
}


/*-----------------------------------------------------------------------------------*/
/* REQUIRED PLUGINS
/*-----------------------------------------------------------------------------------*/

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

		/**
		 * Array of plugin arrays. Required keys are name and slug.
		 * If the source is NOT from the .org repo, then source is also required.
		 */
		$plugins = array(

			array(
				'name'                     => esc_html__( 'Like This', 'toppic' ), // The plugin name
				'slug'                     => 'roses-like-this', // The plugin slug (typically the folder name)
				'source'                   => get_template_directory() . '/includes/plugins/roses-like-this.zip', 
				'required'                 => false, // The plugin source
				'version'                  => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
				'force_activation'         => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
				'force_deactivation'       => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
				'external_url'             => '' // If set, overrides default API URL and points to an external URL
			),
			array(
				'name'                     => esc_html__( 'Gallery Meta Boxes', 'toppic' ), // The plugin name
				'slug'                     => 'meta-box', // The plugin slug (typically the folder name)
				'source'                   => get_template_directory() . '/includes/plugins/meta-box.zip', 
				'required'                 => true, // The plugin source
				'version'                  => '16.0', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
				'force_activation'         => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
				'force_deactivation'       => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
				'external_url'             => '' // If set, overrides default API URL and points to an external URL
			),
			array(
				'name'          		=> esc_html__( 'Visual Composer', 'toppic' ), // The plugin name
				'slug'          		=> 'js_composer', // The plugin slug (typically the folder name)
				'source'           		=> get_template_directory() . '/includes/plugins/js_composer.zip', // The plugin source
				'required'         		=> false, // If false, the plugin is only 'recommended' instead of required
				'version'               => '5.6', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
				'force_activation'      => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
				'force_deactivation'    => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
				'external_url'          => '' // If set, overrides default API URL and points to an external URL
			),
			array(
				'name'          		=> esc_html__( 'Kotofey Custom Post Types', 'toppic' ), // The plugin name
				'slug'          		=> 'kk-cpt', // The plugin slug (typically the folder name)
				'source'           		=> get_template_directory() . '/includes/plugins/kk-cpt.zip', // The plugin source
				'required'         		=> true, // If false, the plugin is only 'recommended' instead of required
				'version'               => '1.2', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
				'force_activation'      => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
				'force_deactivation'    => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
				'external_url'          => '' // If set, overrides default API URL and points to an external URL
			),
			array(
				'name'          		=> esc_html__( 'Contact From 7', 'toppic' ), // The plugin name
				'slug'          		=> 'contact-form-7', // The plugin slug (typically the folder name)
				'required'         		=> false, // If false, the plugin is only 'recommended' instead of required
				'version'               => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
			),
			array(
				'name'          		=> esc_html__( 'One Click Demo Import', 'toppic' ), // The plugin name
				'slug'          		=> 'one-click-demo-import', // The plugin slug (typically the folder name)
				'required'         		=> false, // If false, the plugin is only 'recommended' instead of required
				'version'               => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
			)

		);

		/**
		 * Array of configuration settings. Amend each line as needed.
		 * If you want the default strings to be available under your own theme domain,
		 * leave the strings uncommented.
		 * Some of the strings are added into a sprintf, so see the comments at the
		 * end of each line for what each argument will be.
		 */
		$config = array(
			'id'           => 'tgmpa',                 // Unique ID for hashing notices for multiple instances of TGMPA.
			'domain'    => 'KK_TF',
			'default_path' => '',                      // Default absolute path to pre-packaged plugins.
			'menu'         => 'tgmpa-install-plugins', // Menu slug.
			'has_notices'  => true,                    // Show admin notices or not.
			'dismissable'  => false,                    // If false, a user cannot dismiss the nag message.
			'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
			'is_automatic' => true,                   // Automatically activate plugins after installation or not.
			'message'      => '',                      // Message to output right before the plugins table.
			'strings'      => array(
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ), // %s = plugin name.
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
				'notice_can_install_required'     => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_can_install_recommended'  => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_cannot_install'           => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_can_activate_required'    => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_cannot_activate'          => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_ask_to_update'            => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'tgmpa' ), // %1$s = plugin name(s).
				'notice_cannot_update'            => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.', 'tgmpa' ), // %1$s = plugin name(s).
				'install_link'                    => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'tgmpa' ),
				'activate_link'                   => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'tgmpa' ),
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
				'complete'                        => __( 'All plugins installed and activated successfully. %s', 'tgmpa' ), // %s = dashboard link.
				'nag_type'                        => 'updated' // Determines admin notice type - can only be 'updated', 'update-nag' or 'error'.
			)
		);

		tgmpa( $plugins, $config );

	}
}

add_action( 'tgmpa_register', 'kk_register_required_plugins' );


/*-----------------------------------------------------------------------------------*/
/* VC SETUP
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'kk_vcSetAsTheme' ) ) {
	function kk_vcSetAsTheme() {
		vc_set_as_theme( $disable_updater = true );
		require_once get_theme_file_path( '/includes/vc-func.php' );
	}
}

add_action( 'vc_before_init', 'kk_vcSetAsTheme' );

add_action('admin_init', function()
{
    if(is_admin()) {
        setcookie('vchideactivationmsg', '1', strtotime('+3 years'), '/');
        setcookie('vchideactivationmsg_vc11', (defined('WPB_VC_VERSION') ? WPB_VC_VERSION : '1'), strtotime('+3 years'), '/');
    }
});


/*-----------------------------------------------------------------------------------*/
/* POSTS ID HELPER
/*-----------------------------------------------------------------------------------*/

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

	if (is_home() || is_search() || is_category() || is_tag() || is_date() || is_author() || is_404()) {
			$postid = get_option( 'page_for_posts' );
		} else if ( is_tax( 'portfolio-type' )) {
			$postid = portfolioID();
		} else if ( is_tax( 'gallery-type' )) {
			$postid = galleryID();
		}  else if ( function_exists('is_shop') && is_shop() ) {
			$postid = get_option( 'woocommerce_shop_page_id' );
		}  else {
			$postid = get_the_ID();
		}
		
		return $postid;
	}
}


/*-----------------------------------------------------------------------------------*/
/* REGISTERING SIDEBARS
/*-----------------------------------------------------------------------------------*/

function toppic_widgets_init() {

	$sbopts=array(
		'before_widget'=>'<div class="widget %2$s" id="%1$s">',
		'after_widget'=>'</div>',
		'before_title'=>'<h5 class="widget-title">',
		'after_title'=>'</h5>'
	);
	
	// BLOG SIDEBAR
	
	register_sidebar(
		array_merge($sbopts,
			array(
				'name'=>'Blog Sidebar',
				'id'=>'kk-blog-sidebar',
				'description'=>__( 'Add widgets here to appear in your blog sidebar.', 'toppic' ),
			)
		)
	);
		
	// PAGE SIDEBAR
	
	register_sidebar(
		array_merge($sbopts,
			array(
				'name'=>'Page Sidebar',
				'id'=>'kk-page-sidebar',
				'description'=>__( 'Add widgets here to appear in your page sidebar.', 'toppic' ),
			)
		)
	);
	
	// PORTFOLIO SIDEBAR
	
	register_sidebar(
		array_merge($sbopts,
			array(
				'name'=>'Portfolio Sidebar',
				'id'=>'kk-portfolio-sidebar',
				'description'=>__( 'Add widgets here to appear in your portfolio sidebar.', 'toppic' ),
			)
		)
	);

}

add_action('widgets_init', 'toppic_widgets_init');


/*-----------------------------------------------------------------------------------*/
/* ENQUEUE SCRIPTS AND STYLES
/*-----------------------------------------------------------------------------------*/

function kk_get_jquery() {
	$postid = kk_postid();
	
	$bg_post_meta = get_post_meta($postid, '_custom_bg_type_value', true);
			
	if( empty( $bg_post_meta ) ) {
		$bg_post_meta = 'Default';
	}

	/* Stylesheets */
	
	wp_enqueue_style( 'kk-icons', get_theme_file_uri( '/css/fontello.css' ), '', KKFW_VERSION );
	wp_enqueue_style( 'kk-reset', get_theme_file_uri( '/css/reset.css' ), '', KKFW_VERSION );
	wp_enqueue_style( 'kk-default', get_theme_file_uri( '/css/default.css' ), '', KKFW_VERSION );
	wp_enqueue_style( 'style', get_stylesheet_uri(), array(), KKFW_VERSION );
	wp_enqueue_style( 'kk-royalslider', get_theme_file_uri(  '/css/royalslider.css' ), '', KKFW_VERSION );
	wp_enqueue_style( 'kk-royalslider-skin',  get_theme_file_uri( '/css/rs-default.css' ), '', KKFW_VERSION );
	wp_enqueue_style( 'kk-lightbox',  get_theme_file_uri( '/css/lightbox.css' ), '', KKFW_VERSION );
	wp_enqueue_style( 'kk-woocommerce',  get_theme_file_uri( '/css/woocommerce.css' ), '', KKFW_VERSION );
	
	/**
	* Enqueue Google Fonts.
	*/
	wp_enqueue_style( 'kk-gfonts', '//fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans:300,400,600&subset=latin,latin-ext', '', KKFW_VERSION);
	
	if (get_option('toppic_theme_con_res') == 'true') {
		wp_enqueue_style( 'kk-responsive', get_theme_file_uri( '/css/responsive.css' ), '', KKFW_VERSION);
	}
	
	
	/* Scripts */
	wp_enqueue_script( 'kk-plugins', get_theme_file_uri( '/js/jquery.plugins.js' ), array( 'jquery' ), KKFW_VERSION, true );					
	wp_enqueue_script( 'kk-custom', get_theme_file_uri( '/js/jquery.custom.js' ), array( 'jquery' ), '1.8', true );	
	wp_enqueue_script( 'kk-modernizr', get_theme_file_uri( '/js/jquery.modernizr.custom.js' ), array( 'jquery' ), KKFW_VERSION, true );	
	
	if ( in_array( get_option( 'toppic_theme_menu_style' ), array( 'kk-menu-slide-right', 'kk-menu-fullscreen' ) ) ) {
		wp_enqueue_script( 'kk-bg-check', get_theme_file_uri( '/js/jquery.background-check.min.js' ), array( 'jquery' ), KKFW_VERSION, true );
		wp_enqueue_script( 'kk-classie', get_theme_file_uri( '/js/jquery.classie.js' ), array( 'jquery' ), KKFW_VERSION, true );
		wp_enqueue_script( 'kk-menu', get_theme_file_uri( '/js/jquery.dlmenu.js' ), array( 'jquery' ), KKFW_VERSION, true );
	}	
	
	/* Remove Visual Composer prettyPhoto lightbox */
	
	wp_deregister_script( 'prettyphoto' );	
	
	
	/* Move an array to jQuery */
	
	KkGetOptions::init();
	$kk_data = KkGetOptions::TplConditions();
	wp_localize_script( 'kk-custom', 'kk_js_data', $kk_data );
	
	if ( rwmb_meta( 'kk_slider_auto' ) ) {
		
		$postSliderData = array();
		$postSliderData['state'] = rwmb_meta( 'kk_slider_auto' );
		$postSliderData['delay'] = rwmb_meta( 'kk_sliderDelay' );
		
		wp_localize_script( 'kk-custom', 'kk_postSlider', $postSliderData );
	}
	
				
	if ( post_password_required() && has_post_thumbnail() ) {
		$passImg = wp_get_attachment_image_src(get_post_thumbnail_id(kk_postid()), 'featured-image-thumb');
		wp_localize_script( 'kk-custom', 'kk_js_passImg', esc_url( $passImg[0] ) );
	}
	
	
	if (!is_admin()){
		if ( is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
			wp_enqueue_script( 'comment-reply' );
	}		
	
	if ( ( $bg_post_meta == 'Video' ) && ( get_post_meta( $postid, '_gallery_layout_value', true ) != 'Fullscreen') && ( get_post_meta( $postid, '_gallery_layout_value', true) != 'Fullscreen-Grid' ) ) {
	
		if ( (get_option('toppic_theme_content_style') === 'kk-boxed' ) || (is_page_template('template-homepage-slider.php'))) {	
			$kkCheckBg = esc_url( get_post_meta($postid, '_bg_video_value', true) );
		
			if (strpos($kkCheckBg, 'youtube') > 0) {
				wp_enqueue_script('kk-bgvideo', get_theme_file_uri( '/js/jquery.bgVideo.js' ), array( 'jquery' ), KKFW_VERSION, true);
			}
		}
	}
	
	if ((( $bg_post_meta === 'Default' ) || ( $bg_post_meta === 'Custom Slideshow')) && ( get_post_meta($postid, '_gallery_layout_value', true) !== 'Fullscreen' ) && (get_post_meta($postid, '_gallery_layout_value', true ) !== 'Fullscreen-Grid' )) {
	
		if ( get_option('toppic_theme_fullscreen_stream') === 'kk_royal' ) {
			wp_enqueue_script('kk-royalslider', get_theme_file_uri( '/js/jquery.royalslider.min.js' ), array( 'jquery' ), KKFW_VERSION, true);
		} else {		
			wp_enqueue_script('kk-kenb', get_theme_file_uri( '/js/jquery.kenb.js' ), array( 'jquery' ), KKFW_VERSION, true);	
		}
	
	} else if ( get_post_meta($postid, '_gallery_layout_value', true) == 'Fullscreen' ) {	
		wp_enqueue_script('kk-royalslider', get_theme_file_uri( '/js/jquery.royalslider.min.js' ), array( 'jquery' ), KKFW_VERSION, true);
	}
	
	if( is_home() || is_front_page() || is_archive() || is_search() || has_post_format('gallery') || is_singular('portfolio') || is_page_template('template-home-demo.php') || is_page_template('template-home-demo-2.php') ) {	
		if(!is_page_template('template-homepage-slider.php')) {		
			wp_enqueue_script('kk-royalslider', get_theme_file_uri( '/js/jquery.royalslider.min.js' ), array( 'jquery' ), KKFW_VERSION, true);
		}			
	}
	
	if ( is_page_template('template-portfolio.php') || is_page_template('template-gallery.php') || is_tax( 'portfolio-type' ) || is_tax( 'gallery-type' ) ) {
			wp_enqueue_script('kk-mixitup', get_theme_file_uri( '/js/jquery.mixitup.min.js' ), array( 'jquery' ), KKFW_VERSION, true);
	}
	
	if ( is_page_template('template-homepage-grid.php') || in_array( get_post_meta($postid, '_gallery_layout_value', true), array( '2-column', '3-column', '4-column', 'Thumbnails' ) ) && get_post_meta($postid, '_is_masonry_value', true) === 'Yes' || get_post_meta($postid, '_gallery_layout_value', true) == 'Mosaic' || get_post_meta($postid, '_gallery_layout_value', true) == 'Fullscreen-Grid' && get_post_meta($postid, '_grid_type_value', true) == 'Random' ) {
		wp_enqueue_script('masonry');
	}
	
	
	if(get_post_meta($postid, '_gallery_layout_value', true) !== 'Fullscreen' && !is_page_template('template-homepage.php')) {
		wp_enqueue_script('kk-lightbox', get_theme_file_uri( '/js/jquery.lightbox.js' ), array( 'jquery' ), KKFW_VERSION, true);	
	}


}

add_action('wp_enqueue_scripts', 'kk_get_jquery');


/*-----------------------------------------------------------------------------------*/
/* HELLO MESSAGE
/*-----------------------------------------------------------------------------------*/

if( ! function_exists( 'siteoptions_admin_head' ) ) {
function siteoptions_admin_head() { ?>

	<script type="text/javascript">
	
		jQuery(function () {
			var message = '<p><strong>toppic is now activated.</strong> The custom options panel is located under <a href="<?php echo admin_url('themes.php?page=toppic_theme'); ?>">Dashboard > Appearance > Theme Options</a>.</p>';
			jQuery('.themes-php #message2').html(message);	
		});

	</script>
<?php }
}

add_action('admin_head', 'siteoptions_admin_head');


/*-----------------------------------------------------------------------------------*/	
/* MAX CONTENT WIDTH
/*-----------------------------------------------------------------------------------*/	

if ( ! function_exists( 'kktfwp_content_width' ) ) {
	function kktfwp_content_width() {
		$GLOBALS['content_width'] = apply_filters( 'kktfwp_content_width', 2560 );
	}
}

add_action( 'after_setup_theme', 'kktfwp_content_width', 0 );

if ( ! function_exists( 'kktfwp_max_srcset_image_width' ) ) {
	function kktfwp_max_srcset_image_width( $w, $sizes = array() ) {
		return 5120;
	}
}
add_filter( 'max_srcset_image_width', 'kktfwp_max_srcset_image_width', 10, 2 );


/*-----------------------------------------------------------------------------------*/
/* BACKGROUND VIDEO
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'bgVideo' ) ) {
	function bgVideo($postid) {
	
		if ( (get_option('toppic_theme_content_style') === 'kk-boxed' ) || (is_page_template('template-homepage-slider.php'))) {
			$bgUrl = trim(get_post_meta($postid, '_bg_video_value', true));
			$fallbackImg = get_post_meta($postid, '_bg_image_fallback_value', true);
			
			$kk_data = array();
			
			if (strpos($bgUrl, 'youtube') > 0) {

			parse_str( parse_url( esc_url( $bgUrl ), PHP_URL_QUERY ), $array );
	  
				$kk_data['video_source'] = $array['v'];
				$kk_data['helper'] = true;
				
			} else {
			
				$kk_data['video_source'] = esc_url( $bgUrl );
				
			}

			$kk_data['fallback_img'] = esc_url( $fallbackImg );
			
			wp_localize_script( 'kk-custom', 'kk_js_video', $kk_data );
		}
	}
}


/*-----------------------------------------------------------------------------------*/
/* PHOTO PROOFING AJAX HANDLER
/*-----------------------------------------------------------------------------------*/

add_action( 'wp_ajax_nopriv_kk_proofing', 'kk_proofing' );
add_action( 'wp_ajax_kk_proofing', 'kk_proofing' );

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

		check_ajax_referer( 'proof-nonce', '_wpnonce' );
							
		$data = wp_get_attachment_metadata( $_POST['image_id'] );
		
		if ( isset($data['image_meta']['proof_status'] ) && $data['image_meta']['proof_status'] === 'checked' ) {
			$data['image_meta']['proof_status'] = 'unchecked';
		} else {
			$data['image_meta']['proof_status'] = 'checked';
		}	
				
		wp_update_attachment_metadata( $_POST['image_id'], $data );
		
		$new_status = wp_get_attachment_metadata( $_POST['image_id'] );			
		wp_send_json_success( $new_status['image_meta']['proof_status'] );
	}
}



/*-----------------------------------------------------------------------------------*/
/* FULLSCREEN GALLERY
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'galleryFS' ) ) {
	function galleryFS() {
		$postid = get_the_ID();
		$attachments = rwmb_meta( 'kk_imgadv', 'type=image_advanced', $post_id = $postid );	
	
		echo '<div class="royalSlider_fullscreen type-fullscreen-gallery rsKK"></div>';
		
		if (get_post_meta($postid, '_full_style_value', true) == 'Fade') {
			$kk_galleryFS = 'fade';
		} else if (get_post_meta($postid, '_full_style_value', true) == 'Move') {
			$kk_galleryFS = 'move';
		} else {
			$kk_galleryFS = get_option("toppic_theme_gallery_fullscreen_effect");
		}
		
		if (get_post_meta($postid, '_scale_mode_value', true) === 'Fill') {
			$kk_galleryScale = 'fill';
		} else if (get_post_meta($postid, '_scale_mode_value', true) === 'Fit') {
			$kk_galleryScale = 'fit';
		}
		
		if (get_post_meta($postid, '_near_by_value', true) === 'Yes') {
			$kk_near_by = 1;
		} else {
			$kk_near_by = 0;
		}
		
		if (get_option("toppic_theme_gallery_fullscreen_loop") === 'true') {
			$kk_loop = 1;
		} else {
			$kk_loop = 0;
		}
		
		if (get_option("toppic_theme_gallery_fullscreen_autoplay") === 'true') {
			$kk_autoplay = 1;
		} else {
			$kk_autoplay = 0;
		}
		
		// Built an array for slider
		
		$kk_data = array();
		$kk_data['menuStyle'] = get_option('toppic_theme_menu_style');
		$kk_data['transitionType'] = $kk_galleryFS;
		$kk_data['galleryScale'] = $kk_galleryScale;
		$kk_data['visibleNearBy'] = $kk_near_by;
		$kk_data['galleryLoop'] = $kk_loop;
		$kk_data['transitionSpeed'] = get_option("toppic_theme_gallery_fullscreen_transition");
		$kk_data['autoplay'] = array(
			'enabled' => $kk_autoplay,
			'delay' => get_option("toppic_theme_gallery_fullscreen_delay"),
		);
		$kk_data['slides'] = array_merge($attachments);		
		
		// Move an array to jQuery
		
		if (!empty($attachments)) {
			wp_localize_script( 'kk-custom', 'kk_js_gallery', $kk_data );
		}
	}
}


/*-----------------------------------------------------------------------------------*/
/* BACKGROUND SLIDESHOW
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'bgSlideshow' ) ) { 
	function bgSlideshow() {  
		// Check layout style. Enable slideshow if style 'Boxed' or it's a frontpage
		if ( (get_option('toppic_theme_content_style') === 'kk-boxed' ) || (is_page_template('template-homepage-slider.php'))) {	
			if ( get_option('toppic_theme_fullscreen_stream') === 'kk_royal' ) {
				slideshowType_1();
			} elseif( get_option('toppic_theme_fullscreen_stream') === 'ken_b') {
				slideshowType_2();
			}
		}  
	}
}
 
if ( ! function_exists( 'slideshowType_1' ) ) { 
	function slideshowType_1() {

		$postid = kk_postid();

			$kk_data = array();

			$bg_post_meta = get_post_meta($postid, '_custom_bg_type_value', true);
			
			if( empty( $bg_post_meta ) ) {
				$bg_post_meta = 'Default';
			}
			
			query_posts(array('post_type' => 'slider', 'posts_per_page' => -1));
			if( have_posts() && $bg_post_meta == 'Default' ) {
			echo '<div class="royalSlider_fullscreen"></div>';
			} elseif( rwmb_meta( 'kk_homegrid', 'type=image_advanced', $post_id = $postid ) && $bg_post_meta == 'Custom Slideshow' ) {
			echo '<div class="royalSlider_fullscreen"></div>';
			}
			
			if ( $bg_post_meta == 'Custom Slideshow' ) {
											
				$attachments = rwmb_meta( 'kk_homegrid', 'type=image_advanced', $post_id = $postid );	
				//print_r($attachments);
				
			} elseif ( $bg_post_meta == 'Default' ) {					
				
				$kk_data['ifDefault'] = '1';
				$attachments = array();
				
				while (have_posts()): the_post();
				
				$full = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
				
				$attachments[get_post_thumbnail_id()] = array( 
															'image' => $full[0],
															'title' => get_post_meta(get_the_ID(), '_slide_title_value', true)
														);						
				endwhile;
				wp_reset_query();
			} 
			
			if (!empty($attachments)) {			
				// Built an array for slider
				$kk_data['menuStyle'] = get_option('toppic_theme_menu_style');
				$kk_data['randomizeSlides'] = get_option("toppic_theme_fullscreen_start_slide");
				$kk_data['transitionType'] = get_option("toppic_theme_fullscreen_effect");
				$kk_data['transitionSpeed'] = get_option("toppic_theme_fullscreen_transition");
				$kk_data['autoplay'] = array(
					'delay' => get_option("toppic_theme_fullscreen_delay"),
				);
				$kk_data['slides'] = array_merge($attachments);		
				
				// Move an array to jQuery		
				wp_localize_script( 'kk-custom', 'kk_js_fs_slideshow', $kk_data );
			}
	}
}
	
	
if ( ! function_exists( 'slideshowType_2' ) ) { 	
	function slideshowType_2() {

		$postid = kk_postid();
		
		// Built an array for slider		
		$kk_data = array();
		
		$bg_post_meta = get_post_meta($postid, '_custom_bg_type_value', true);
			
		if( empty( $bg_post_meta ) ) {
			$bg_post_meta = 'Default';
		}
			
		query_posts(array('post_type' => 'slider', 'posts_per_page' => -1)); 
	
			if( have_posts() && $bg_post_meta == 'Default' ) {
				
				$kk_data['ifDefault'] = '1';
				
				while (have_posts()): the_post();									
				$full = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');						
				$attachments[get_post_thumbnail_id()] = array( 
												'image' => $full[0],
												'title' => get_post_meta(get_the_ID(), '_slide_title_value', true)
											);									
				endwhile;
				wp_reset_query(); 
				
			} elseif ( $bg_post_meta == 'Custom Slideshow' ) {
			
				$attachments = rwmb_meta( 'kk_homegrid', 'type=image_advanced', $post_id = $postid );
				
			}  		
		
		if (!empty($attachments)) {
			// Built an array for slider		
			$kk_data['fps'] = get_option("toppic_theme_ken_b_frames");
			$kk_data['delay'] = get_option("toppic_theme_ken_b_delay");
			$kk_data['transitionSpeed'] = get_option("toppic_theme_ken_b_transition");
			$kk_data['zoom'] = get_option("toppic_theme_ken_b_zoom");
			$kk_data['slides'] = array_merge($attachments);
			
			// Move an array to jQuery		
			wp_localize_script( 'kk-custom', 'kk_js_fsk_slideshow', $kk_data );
		}
	}
}


/*-----------------------------------------------------------------------------------*/
/* CUSTOM LOGIN SCREEN
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'my_custom_login_logo' ) ) { 
	function my_custom_login_logo() {
		$logo = get_option('toppic_theme_logo_admin');
		if(empty($logo)) $logo=get_admin_url()."images/wordpress-logo.png";
		
		echo '<style type="text/css">
			.login h1 a { background-image:url('.$logo.') !important; background-size: auto!important; width: auto; }
		</style>';
	}
}

add_action('login_head', 'my_custom_login_logo');



/*-----------------------------------------------------------------------------------*/
/* ADD EXTRA CLASSES TO THE BODY CLASS 
/*-----------------------------------------------------------------------------------*/

add_filter( 'body_class' , 'kk_body_class' );

if ( ! function_exists( 'kk_body_class' ) ) { 
	function kk_body_class( $classes ) {

		$postid = kk_postid();
		
		$classes[] = 'kk_vc';
		
		$content_style = get_option( 'toppic_theme_content_style' );
		
		switch ( $content_style ) {
			case 'kk-boxed':
				$classes[] = 'kk-content-boxed';
				break;
			case 'kk-full':
				$classes[] = 'kk-content-fullwidth';
				if ( ( rwmb_meta( 'kk_title_type', 'type=select', $postid ) === 'parallax' ) && ( get_post_meta( $postid, '_gallery_layout_value', true ) !== 'Fullscreen' ) ) {

					$classes[] = 'kk-parallax-title';
					wp_localize_script( 'kk-custom', 'kk_title_parallax', 'active' );
					
					if ( rwmb_meta( 'kk_title_size', 'type=select', $postid ) === 'full' ) {
						$classes[] = 'kk-parallax-title-fullheight';
						wp_localize_script( 'kk-custom', 'kk_title_height', 'active' );
					}
				}
				break;	
		}
		
		$menu_style = get_option( 'toppic_theme_menu_style' );
		
		switch ( $menu_style ) {
			case 'kk-menu-default':
				$classes[] = 'kk_menu_default';
				break;
			case 'kk-menu-classic':
				$classes[] = 'kk_menu_classic';
				break;
			case 'kk-menu-default-hidden':
				$classes[] = 'kk_menu_default_hidden';
				break;
			case 'kk-menu-slide-right':
				$classes[] = 'kk_menu_slide_right';
				break;
			case 'kk-menu-left-boxed':
				$classes[] = 'kk_menu_left_boxed';
				break;
			case 'kk-menu-fullscreen':
				$classes[] = 'kk_menu_fullscreen';
				break;
		}	
		
		if ( rwmb_meta( 'kk_proof' ) === 'proofing' ) {
			$classes[] = 'kk-photo-proofing';		
		}
		
		if ( ( get_option( 'toppic_theme_is_border' ) == 'true' ) && ( get_option( 'toppic_theme_menu_style' ) == 'kk-menu-slide-right' ) )  {
			$classes[] = 'kk-is-borders';
		}
		
		if ( in_array( get_post_meta($postid, '_gallery_layout_value', true), array( '2-column', '3-column', '4-column', 'Thumbnails' ) ) && get_post_meta($postid, '_is_masonry_value', true) == 'Yes' || get_post_meta($postid, '_gallery_layout_value', true) == 'Mosaic' ) {
			$classes[] = 'kk-masonry';
		}
		
		if ( post_password_required($postid) && !is_front_page() && !is_archive() ) {
			$classes[] = 'password-protected';
		}
		
		if ( get_option( 'toppic_theme_skin_color' ) == 'dark' ) {
			$classes[] = 'dark-skin';
		}
		
		// return the $classes array
		return $classes;	
	}
}

/*-----------------------------------------------------------------------------------*/
/* COMMENTS NAVIGATION
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'kk_comment_nav' ) ) {

	function kk_comment_nav() {
		// Are there comments to navigate through?
		if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) {
		?>
		<nav class="navigation comment-navigation" role="navigation">
			<div class="com-nav-links">
				<?php
					if ( $prev_link = get_previous_comments_link( __( 'Older Comments', 'toppic' ) ) ) {
						printf( '<div class="com-nav-previous">%s</div>', $prev_link );
					}

					if ( $next_link = get_next_comments_link( __( 'Newer Comments', 'toppic' ) ) ) {
						printf( '<div class="com-nav-next">%s</div>', $next_link );
					}
				?>
			</div><!-- .nav-links -->
		</nav><!-- .comment-navigation -->
		<?php
		}
	}
}

/*-----------------------------------------------------------------------------------*/
/* EXCLUDE FEATURED IMAGE FROM THE WORDPRESS GALLERY
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'exclude_thumbnail_from_gallery' ) ) {

	function exclude_thumbnail_from_gallery($null, $attr) {

		if (!$thumbnail_ID = get_post_thumbnail_id())
		return $null; // no point carrying on if no thumbnail ID

		// temporarily remove the filter, otherwise endless loop!
		remove_filter('post_gallery', 'exclude_thumbnail_from_gallery');

		// pop in our excluded thumbnail
		if (!isset($attr['exclude']) || empty($attr['exclude']))
		$attr['exclude'] = array($thumbnail_ID);
		elseif (is_array($attr['exclude']))
		$attr['exclude'][] = $thumbnail_ID;

		// now manually invoke the shortcode handler
		$gallery = gallery_shortcode($attr);

		// add the filter back
		add_filter('post_gallery', 'exclude_thumbnail_from_gallery', 10, 2);

		// return output to the calling instance of gallery_shortcode()
		return $gallery;
	}
}

add_filter('post_gallery', 'exclude_thumbnail_from_gallery', 10, 2);


/*-----------------------------------------------------------------------------------*/
/* FILTERS
/*-----------------------------------------------------------------------------------*/

add_filter('widget_text', 'do_shortcode');
add_filter('the_excerpt', 'do_shortcode');

if ( ! function_exists( 'toppic_filter_wp_page_menu_args' ) ) {
	function toppic_filter_wp_page_menu_args($args) {
		$args['show_home'] = true;
		return $args;
	}
}

add_filter('wp_page_menu_args', 'toppic_filter_wp_page_menu_args');


if ( ! function_exists( 'toppic_search_all' ) ) {
	function toppic_search_all($query){
		if($query->is_search) $query->set('post_type', array('post, page, portfolio, gallery'));
		return $query;
	}
}

//add_filter('the_search_query', 'toppic_search_all');


if ( ! function_exists( 'my_more_link' ) ) {
	function my_more_link( $more_link, $more_link_text ) {
		return '<br><a class="more-link" href="'. get_permalink() . '">'. __('Read more','toppic') .'	</a>';
	}
}

add_filter( 'the_content_more_link', 'my_more_link', 10, 2 );


/*-----------------------------------------------------------------------------------*/
/* INCLUDE STYLES
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'add_styles' ) ) {
	function add_styles() {
		get_template_part('css/main.css');
		echo stripslashes(get_option("toppic_theme_custom_footer"));
	}
}

add_action('wp_head', 'add_styles');


/*-----------------------------------------------------------------------------------*/
/* COMMENTS
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'toppic_comment' ) ) {
	function toppic_comment($comment, $args, $depth) {

		$GLOBALS['comment'] = $comment;?>

		<li id="comment-<?php comment_ID()?>" class="comment wrapper">
		
			<div class="kk-gravatar vcard">	
				<?php echo get_avatar($comment, 60)?>
			</div>
			<div class="kk-comment-wrapper">	
				<div class="comment-info">				
					<div class="response-info">
						<strong class="comment-author"><?php echo get_comment_author_link()?></strong>&nbsp;&nbsp;&mdash;&nbsp;&nbsp;<?php printf( __('%1$s at %2$s','toppic'),get_comment_date(),get_comment_time())?>
					</div>				
				</div>
				<div class="comment-text">
					<?php if($comment->comment_approved=='0') {
							_e( 'Your comment is awaiting moderation.', 'toppic' );
						} else { 
							comment_text();
							comment_reply_link(array_merge($args, array('depth'=>$depth, 'max_depth'=>$args['max_depth'], 'after' => '<i class="kk kk-icon-reply"></i>')));
					} ?>
				</div>
			</div>
			<?php if ( comments_open() ) : ?>
			<?php endif; ?>
		</li><?php
	}
}


/*-----------------------------------------------------------------------------------*/
/* TITLE TYPE
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'kk_parallax' ) ) {
	function kk_parallax() {
	
		$postid = kk_postid();
		
		$title_type = rwmb_meta( 'kk_title_type', 'type=select', $postid );

		if( empty( $title_type ) ||  get_option( 'toppic_theme_content_style' ) === 'kk-boxed' ) {
			$title_type = 'default';
		}	

		$bg_title = rwmb_meta( 'kk_title_bg', 'type=image_advanced', $postid );
		
		if( $bg_title !== false ) {
		
			$bg_title_img = array_shift($bg_title);
		
			return array( $title_type, $bg_title_img['full_url'], $bg_title_img['title'] );
		
		} else {
		
			return;
		
		}
		
	}
}


/*-----------------------------------------------------------------------------------*/
/* OPEN WORDPRESS IMAGES IN LIGHTBOX
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'add_rel_to_gallery' ) ) {
	function add_rel_to_gallery($link, $id = null) {
		$id = intval( $id );
		$_post = get_post( $id );
		$post_title = esc_attr( $_post->post_title );
		$link = str_replace("'><img", "' class=\"kk-lightbox\" data-title=\"".$post_title."\"><img", $link);
		return $link;
	}
}

add_filter('wp_get_attachment_link', 'add_rel_to_gallery', 10, 2);


/*-----------------------------------------------------------------------------------*/
/* HELPERS
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'BackLink' ) ) {
	function BackLink()
	{
			$get_posts = new WP_Query;
			$ppages = array();
			$pages = $get_posts->query('post_type=page&posts_per_page=-1');
			foreach ($pages as $page) {
				$post_custom = get_post_custom($page->ID);
				if ($post_custom['_wp_page_template'][0] == 'template-portfolio.php') {
					$ppages[] = $page->ID;
				}
			}
			if (!empty($ppages)) {
				echo '<span class="all-l" title="' . __('View all projects', 'toppic') . '"><a href="' . get_permalink($ppages[0]) . '"></a></span>';
			}
	}
}

if ( ! function_exists( 'portfolioID' ) ) {
	function portfolioID()
	{
			$ppages = array();
			
			$pages = get_pages(

				 array(
					'meta_key' => '_wp_page_template',
					'meta_value' => 'template-portfolio.php'
				)
			);
			
			foreach ($pages as $page) {			
					$ppages[] = $page->ID;
			}
			
			if (!empty($ppages)) {
				return $ppages[0];
			}
	}
}

if ( ! function_exists( 'galleryID' ) ) {
	function galleryID()
	{
			$ppages = array();
			
			$pages = get_pages(

				 array(
					'meta_key' => '_wp_page_template',
					'meta_value' => 'template-gallery.php'
				)
			);
			foreach ($pages as $page) {
					$ppages[] = $page->ID;
			}
			if (!empty($ppages)) {
				return $ppages[0];
			}
	}
}

if ( ! function_exists( 'BlogLink' ) ) {
	function BlogLink()
	{
			$posts_page_id = get_option( 'page_for_posts');
			$site_url = home_url() ;
			
			echo '<div class="all-l" title="' . __('View all posts', 'toppic') . '"><a href="'.$site_url.'/?page_id=' . $posts_page_id . '"></a></div>';

	}
}


/*-----------------------------------------------------------------------------------*/
/* PAGINATION
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'page_pagination' ) ) {
	function page_pagination($pages = '', $range = 2) {

		echo "<div class='pagination' id='kk-pagination'>"; ?>
			<div class="alignleft"><?php next_posts_link(__('&laquo; Previous Entries','toppic')) ?></div>
			<div class="alignright"><?php previous_posts_link(__('Next Entries &raquo;','toppic')) ?></div>
		 <?php echo "</div>\n";
	}
}


/*-----------------------------------------------------------------------------------*/
/* SOCIAL PROFILES
/*-----------------------------------------------------------------------------------*/

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

		$opArray = theme_options_array();
		
		$output = '';
		
		foreach( $opArray['main']['Social'] as $key ) {
			end( $key );
			$op = key($key);
			$field = get_option( 'toppic_theme_'. $op .''  );			
			$title = $key['options']['title'];
			
			if ( $field !== '' ) {
				$output .= '<li><a class="kk-icon-'. esc_attr( $op ) .'" title="'. esc_attr( $title ) .'" target="_blank" href="'. ( $title === 'Skype' ? esc_html( $field ) : esc_url( $field ) ) .'"></a></li>';
			}			
		}
		
		if ( $output !== '' ) {
			return '<ul class="social">' .$output. '</ul>';
		} else {
			return $output;
		}
		
	}
}


/*-----------------------------------------------------------------------------------*/
/* DISABLING COMMENTS BY DEFAULT
/*-----------------------------------------------------------------------------------*/

add_filter( 'wp_insert_post_data', 'kk_default_page_comments_off' );

if ( ! function_exists( 'kk_default_page_comments_off' ) ) {
	function kk_default_page_comments_off( $data ) {
		if ( in_array( $data['post_type'], array( 'page', 'portfolio', 'gallery' ) ) && $data['post_status'] == 'auto-draft' ) {
			$data['comment_status'] = 0;
			$data['ping_status'] = 0;
		}
		return $data;
	}
  }

/*-----------------------------------------------------------------------------------*/
/* IMAGES QUALITY
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'jpeg_quality_callback' ) ) {
	function jpeg_quality_callback($arg) {
		return (int)85;
	}
}

add_filter('jpeg_quality', 'jpeg_quality_callback');


/*-----------------------------------------------------------------------------------*/
/* CONVERTS A HEX VALUE TO RGB
/*
/* @param string $color The original color, in 3- or 6-digit hexadecimal form.
/* @return array Array containing RGB (red, green, and blue) values for the given
/*               HEX code, empty array otherwise.
/*-----------------------------------------------------------------------------------*/

if ( ! function_exists( 'kk_hex2rgb' ) ) {

	function kk_hex2rgb( $color ) {
		$color = trim( $color, '#' );

		if ( strlen( $color ) === 3 ) {
			$r = hexdec( substr( $color, 0, 1 ).substr( $color, 0, 1 ) );
			$g = hexdec( substr( $color, 1, 1 ).substr( $color, 1, 1 ) );
			$b = hexdec( substr( $color, 2, 1 ).substr( $color, 2, 1 ) );
		} else if ( strlen( $color ) === 6 ) {
			$r = hexdec( substr( $color, 0, 2 ) );
			$g = hexdec( substr( $color, 2, 2 ) );
			$b = hexdec( substr( $color, 4, 2 ) );
		} else {
			return array();
		}

		return array( 'red' => $r, 'green' => $g, 'blue' => $b );
	}
}

/*-----------------------------------------------------------------------------------*/
/* MENU COLOR
/*-----------------------------------------------------------------------------------*/

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

		$color = kk_hex2rgb( get_option( 'toppic_theme_menu_color' ));
		
		if ( empty( $color ) ) {
			return;
		}
		
		if ( in_array( get_option('toppic_theme_menu_style'), array( 'kk-menu-slide-right', 'kk-menu-default', 'kk-menu-classic', 'kk-menu-default-hidden' ) ) ) {
		
			$color_rgb = vsprintf( 'rgb( %1$s, %2$s, %3$s)', $color );
			
			return $color_rgb;
		
		} else {
		
			$color[] = get_option('toppic_theme_menu_opacity');
			
			$color_rgb = vsprintf( 'rgba( %1$s, %2$s, %3$s, %4$s)', $color );
			
			return $color_rgb;
			
		}
	}
}


/*-----------------------------------------------------------------------------------*/
/* WOOCOMMERCE
/*-----------------------------------------------------------------------------------*/

// Default image sizes

if ( ! function_exists( 'kk_default_woo_image_dimensions' ) ) {
	function kk_default_woo_image_dimensions() {
	
		global $pagenow;
	 
		if ( ! isset( $_GET['activated'] ) || $pagenow != 'themes.php' ) {
			return;
		}
		
		$catalog = array(
			'width' => '800', // px
			'height'=> '1000', // px
			'crop' => 1 // true
		);

		$single = array(
			'width' => '800', // px
			'height'=> '1000', // px
			'crop' => 1 // true
		);

		$thumbnail = array(
			'width' => '300', // px
			'height'=> '300', // px
			'crop' => 1 // true
		);

		// Image sizes
		update_option( 'shop_catalog_image_size', $catalog ); // Product category thumbs
		update_option( 'shop_single_image_size', $single ); // Single product image
		update_option( 'shop_thumbnail_image_size', $thumbnail ); // Image gallery thumbs
	}
}

add_action( 'after_switch_theme', 'kk_default_woo_image_dimensions', 1 );


// Wrap shop loop

if ( ! function_exists( 'kk_woo_before_shop_loop' ) ) {
	function kk_woo_before_shop_loop() {
		echo '<div class="divider clear"></div><div class="kk-woo-shop-wrapper">';
	}
}

add_action('woocommerce_before_shop_loop', 'kk_woo_before_shop_loop');

if ( ! function_exists( 'kk_woo_after_shop_loop' ) ) {
	function kk_woo_after_shop_loop() {
		echo '</div>';
	}
}

add_action('woocommerce_after_shop_loop', 'kk_woo_after_shop_loop');


// Move filter

remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 );
add_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 30 );

remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30 );
add_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 20 );


// Change number or products per row

add_filter('loop_shop_columns', 'loop_columns');

if ( ! function_exists( 'loop_columns' ) ) {
	function loop_columns() {
		return 3; // 3 products per row
	}
} 


// Redefine woocommerce_output_related_products()

add_filter( 'woocommerce_output_related_products_args', 'related_products_args' );

function related_products_args( $args ) {
   $args['posts_per_page'] = 3; // 4 related products
   $args['columns'] = 3; // arranged in 4 columns
   return $args;
  }


// Move ratings

remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 );
add_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_rating', 5 );


// Move price on single product page

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 27 );


// Wrap product element

remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_result_count', 20 );
add_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 30 );

if ( ! function_exists( 'kk_woo_before_shop_loop_item_title' ) ) {
	function kk_woo_before_shop_loop_item_title() {
		echo '<div class="kk-woo-shop-item">';
	}
}

add_action('woocommerce_before_shop_loop', 'kk_woo_before_shop_loop_item_title');

if ( ! function_exists( 'kk_woo_after_shop_loop_item_title' ) ) {
	function kk_woo_after_shop_loop_item_title() {
		echo '</div>';
	}
}

add_action('woocommerce_after_shop_loop', 'kk_woo_after_shop_loop_item_title');


// Single product page

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_before_single_product', 'woocommerce_template_single_title', 1 );

if ( ! function_exists( 'kk_woo_before_single_product_1' ) ) {
	function kk_woo_before_single_product_1() {
		echo '<div class="inner-content">';
	}
}

add_action('woocommerce_before_single_product', 'kk_woo_before_single_product_1', 4);

if ( ! function_exists( 'kk_woo_after_single_product_2' ) ) {
	function kk_woo_after_single_product_2() {
		echo '</div>';
	}
}

add_action('woocommerce_after_single_product', 'kk_woo_after_single_product_2', 6);

if ( ! function_exists( 'kk_woo_before_single_product_3' ) ) {
	function kk_woo_before_single_product_3() {
		echo '<div class="divider clear"></div>';
	}
}

add_action('woocommerce_before_single_product', 'kk_woo_before_single_product_3', 2);


// Remove product description heading (in tabs)

add_filter( 'woocommerce_product_description_heading', '__return_false', 10 );


// Remove upsell block

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 );

if ( ! function_exists( 'kk_woocommerce_after_single_product_summary_1' ) ) {
	function kk_woocommerce_after_single_product_summary_1() {
		echo '<div class="kk-woo-related">';
	}
}

add_action('woocommerce_after_single_product_summary', 'kk_woocommerce_after_single_product_summary_1', 19);

if ( ! function_exists( 'kk_woocommerce_after_single_product_summary_2' ) ) {
	function kk_woocommerce_after_single_product_summary_2() {
		echo '</div>';
	}
}

add_action('woocommerce_after_single_product_summary', 'kk_woocommerce_after_single_product_summary_2', 21);

/**
 * Displays the optional custom logo.
 * Set default theme logo if the custom logo is not available. *
 * @since TopPic 1.8
 */
 
if ( ! function_exists( 'kktfwp_the_custom_logo' ) ) :

function kktfwp_the_custom_logo() {

	$logo = get_option( 'toppic_theme_logo_main' );
	$logo_light = get_option( 'toppic_theme_logo_main_light' );
	$logo_retina = get_option( 'toppic_theme_logo_main_retina' );
	$logo_retina_light = get_option( 'toppic_theme_logo_main_light_retina' );

	if ( empty( $logo ) && empty( $logo_light ) ) {
		$logo = get_theme_file_uri( '/images/logo.png' );
	} else if ( empty( $logo ) && !empty( $logo_light ) ) {
		$logo = $logo_light;
	}		
	
	if ( empty( $logo_light ) && empty( $logo ) ) {
		$logo_light = get_theme_file_uri( '/images/logo-light.png' );
	} else if ( !empty( $logo ) && empty( $logo_light ) ) {
		$logo_light = $logo;
	}
	
	if ( empty( $logo_retina ) ) {
		$logo_retina = $logo;
	}
	if ( empty( $logo_retina_light ) ) {
		$logo_retina_light = $logo_light;
	}
	
	$info = getimagesize( $logo );	
	$html = '';
	
	if ( in_array( get_option('toppic_theme_menu_style'), array( 'kk-menu-slide-right', 'kk-menu-fullscreen', 'kk-menu-default', 'kk-menu-classic', 'kk-menu-default-hidden', 'kk-menu-left-boxed' ) ) ) {
		
		$html .= '<img class="logo-light" src="'. esc_url( $logo_light ) .'" width="'. esc_attr( $info[0] ) .'" height="'. esc_attr( $info[1] ). '" alt="'. esc_attr( get_bloginfo( 'name', 'display' ) ) .'">';
	
		$html .= '<img class="logo-light2x" src="'. esc_url( $logo_retina_light ) .'" width="'. esc_attr( $info[0] ) .'" height="'. esc_attr( $info[1] ). '" alt="'. esc_attr( get_bloginfo( 'name', 'display' ) ) .'">';				
	}
	
	if ( in_array( get_option('toppic_theme_menu_style'), array( 'kk-menu-slide-right', 'kk-menu-fullscreen', 'kk-menu-classic' ) ) ) {
		
		$html .= '<img class="logo-dark" src="'. esc_url( $logo ) .'" width="'. esc_attr( $info[0] ) .'" height="'. esc_attr( $info[1] ). '" alt="'. esc_attr( get_bloginfo( 'name', 'display' ) ) .'">';
		
		$html .= '<img class="logo-dark2x" src="'. esc_url( $logo_retina ) .'" width="'. esc_attr( $info[0] ) .'" height="'. esc_attr( $info[1] ). '" alt="'. esc_attr( get_bloginfo( 'name', 'display' ) ) .'">';			
	}
	
	echo '<a href="'. esc_url( home_url( '/' ) ) .'" class="custom-logo-link" rel="home">'. $html .'</a>';
}
endif;


/**
 * One Click Import Demo Data
 */
 
require_once get_theme_file_path( '/includes/one-click-import.php' );


/**
 * RWMB Tabs
 */


