<?php 
/**
 * @package WordPress
 * @subpackage:
 *	Name: 	Kingdom Amazon Affiliate Theme
 *	Alias: 	kingdom
 *	Author: AA-Team
 *	Name: 	http://themeforest.net/user/AA-Team/portfolio
 *	
**/
! defined( 'ABSPATH' ) and exit;


/**
 * ===============================================
 * Table of Contents
 * ===============================================
 *
 * 1. The class constructor
 * 2. Register Google Fonts
 * 3. Load the css files for the theme
 * 4. Load the javascript files for the theme
 * 5. Extra head html content
 * 
 */
 
if(class_exists('kingdomCoreFunctions') != true) {
	class kingdomCoreFunctions extends kingdom 
	{
		private $debug = false;
		public $the_theme = null;
		public $data = array();
		public $settings = array();
		public $colors = array();
		
		// shortcuts 
		public $template_directory = '';
		public $locName = '';
		
		public $need_refresh_css = false;

		public $main_style_css_name = 'main-style.css';
		
		public $defaults_theme = array();
		
		/* 1. The class constructor
		=========================== */
		public function __construct( $the_theme=array() ) 
		{
			$this->the_theme = $the_theme;
			$this->template_directory = $this->the_theme->cfg['paths']['theme_dir_url'];
			$this->template_directory_path = $this->the_theme->cfg['paths']['theme_dir_path'];
			
			$this->cfg['css_cache_time'] = 86400; // seconds  (86400 seconds = 24 hours) 
			
			if( defined('WP_KINGDOM_STYLE_CACHE') === true ){
				$this->cfg['css_cache_time'] = 1; // seconds  (86400 seconds = 24 hours) 
			}
			
			$css_cache_option = get_theme_mod('css_cache');
			
			if( $css_cache_option == 'NO' ) {
				$this->cfg['css_cache_time'] = 1; // seconds  (86400 seconds = 24 hours) 
			}
 			
			add_action('wp_ajax_kingdom_frontend_style', array( $this, 'frontend_style') );
			add_action('wp_ajax_nopriv_kingdom_frontend_style', array( $this, 'frontend_style') );

			$this->main_style_css_name = md5( home_url() ) . '.css';
				
			// load only for frontend
			if ( !is_admin() ) {
				add_action( 'wp_head', array( $this, 'html_head' ));
				
				add_action( 'wp_enqueue_scripts', array( $this, 'add_styles' ), 10);
				add_action( 'wp_enqueue_scripts', array( $this, 'add_scripts' ));
				
				add_action('wp', array( $this, 'update_page_data' ), 10);
				add_action('wp', array( $this, 'update_settings' ), 10);
				
				// set size for blog featured image
				add_image_size( 'kingdom_blog-featured-image', 700, 272, true );
				
				// Set the content width based on the theme's design and stylesheet.
				if(!isset($content_width)) $content_width = 960;
				
				// Add default posts and comments RSS feed links to <head>.
				add_theme_support( 'automatic-feed-links' );
				
				// Background customizer
				add_theme_support('custom-background');
				
				// This theme styles the visual editor with editor-style.css to match the theme style.
				add_editor_style(); 
				add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
				
				// Custom sale flash
				add_filter( 'woocommerce_sale_flash', array( $this, 'filter_woocommerce_sale_flash' ), 10, 3 ); 
			}

			add_action('after_setup_theme', array( $this, 'kingdom_setup_theme' ));
			add_filter( 'wp_page_menu_args', array( $this, 'page_menu_args' ) );
			
			//add_filter('the_content', array( $this, 'remove_empty_p' ), 20, 1);
			
			// Declare WooCommerce support
			add_theme_support( 'woocommerce' );
			
			remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
			remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 20, 0);
			
			add_filter( 'woocommerce_get_price_html', array($this, 'superscript_price_html'), 100, 2 );
			
			// Display x products per page.
			add_filter( 'loop_shop_per_page', array( $this, 'woocommerce_products_per_page' ) );
			//add_filter( 'pre_get_posts', array( $this, 'woocommerce_pre_get_posts' ), 1, 50 );
			
			// ajax star rating for amazon products
			add_action('wp_ajax_kingdom_save_stars', array( $this, 'save_stars') );
			add_action('wp_ajax_nopriv_kingdom_save_stars', array( $this, 'save_stars') );
			
			// show Amazon rating if is setup
			add_action('wp_ajax_kingdom_show_amazon_rating', array( $this, 'get_product_ratings') );
			add_action('wp_ajax_nopriv_kingdom_show_amazon_rating', array( $this, 'get_product_ratings') );
			
			if( $this->the_theme->is_woocommerce ) {
				add_filter( 'the_content', array($this, 'remove_gallery'), 6);
			}
			
			add_action('init', array( $this,'register_sidebars'), 10);
			
			$this->data['slideshow_buttons'] = array(
				esc_html__('Buy NOW!', 'kingdom'),
				esc_html__('Get IT!', 'kingdom'),
				esc_html__('View Details', 'kingdom'),
				esc_html__('Read more', 'kingdom'),
				esc_html__('More', 'kingdom'),
			);
			
			// Include the TGM_Plugin_Activation class
			load_template( $this->the_theme->cfg['paths']['freamwork_dir_path'] . 'class-tgm-plugin-activation.php', true );
			add_action( 'tgmpa_register', array( $this, 'register_required_plugins') );
			
			// load Customizer
			require_once( $this->the_theme->cfg['paths']['theme_dir_path'] . '/customizer/customize.class.php' );
			new kingdom_Customize( $this );
			
			$this->add_theme_colors();

			$this->cfg['fonts'] = array(
				'font_main' => 'Rajdhani:300,400,500,600,700',
				'font_secondary' => 'Abril Fatface:300,400,500,600,700',
				'font_headings' => 'Abril Fatface:300,400,500,600,700'
			);
			
			//add_filter('loop_shop_columns', 'loop_columns');
			
			//add_action( 'init', array($this, 'remove_my_shortcodes'), 20 );
			add_filter( 'woocommerce_checkout_fields', array( $this, 'custom_edit_checkout_fields' ) );
			
			add_filter( 'woocommerce_output_related_products_args', array( $this, 'related_products_args' ) );
			
			$this->set_default_theme_mods();
	    }
		
		public function set_default_theme_mods()
		{
			$this->defaults_theme["enable_display"] = "YES";
			$this->defaults_theme["head_cart"] = "YES";
			$this->defaults_theme["head_search"] = "YES";
			$this->defaults_theme["head_search_in"] = "PRODUCTS";
			$this->defaults_theme["head_facebook_url_on"] = "YES";
			$this->defaults_theme["head_facebook_url"] = "#";
			$this->defaults_theme["head_twitter_url_on"] = "YES";
			$this->defaults_theme["head_twitter_url"] = "#";
			$this->defaults_theme["head_instagram_url_on"] = "YES";
			$this->defaults_theme["head_instagram_url"] = "#";
			$this->defaults_theme["head_gplus_url_on"] = "YES";
			$this->defaults_theme["head_gplus_url"] = "#";
			$this->defaults_theme["head_youtube_url_on"] = "YES";
			$this->defaults_theme["head_youtube_url"] = "#";
			$this->defaults_theme["head_pinterest_url_on"] = "YES";
			$this->defaults_theme["head_pinterest_url"] = "#";
			$this->defaults_theme["enable_top_bar"] = "YES";
			$this->defaults_theme["font_main"] = "Rajdhani";
			$this->defaults_theme["font_secondary"] = "Abril Fatface";
			$this->defaults_theme["font_headings"] = "Rajdhani";
			$this->defaults_theme["primary"] = "#dd3333";
			$this->defaults_theme["main_menu_font"] = "Rajdhani";
			$this->defaults_theme["menu_background"] = "#81d742";
			$this->defaults_theme["menu_normal_state"] = "#ffffff";
			$this->defaults_theme["menu_hover_state"] = "#ffffff";
			$this->defaults_theme["secondary"] = "#3843b7";
			$this->defaults_theme["main_menu_submenu_top_margin"] = "81px";
			$this->defaults_theme["products_per_page"] = "12";
			$this->defaults_theme["main_menu_font_size"] = "18px";
			$this->defaults_theme["main_menu_submenu_font_size"] = "18px";
			$this->defaults_theme["shop_template"] = "regular";
			$this->defaults_theme["show_related_products"] = "YES";
			$this->defaults_theme["enable_product_tags"] = "YES";
			$this->defaults_theme["facebook_share_on"] = "YES";
			$this->defaults_theme["twitter_share_on"] = "YES";
			$this->defaults_theme["gplus_share_on"] = "YES";
			$this->defaults_theme["pinterest_share_on"] = "YES";
			$this->defaults_theme["footer_copyright_text"] = 'Copyright &copy; 2018 <span>Kingdom</span>. Created by <a href="http://aa-team.com">AA-Team</a>. Powered by WooCommerce.';
			$this->defaults_theme["show_footer_partners"] = "YES";
			$this->defaults_theme["footer_amazon_url"] = "http://www.google.ro";
			$this->defaults_theme["footer_sidebar_on"] = "YES";
			$this->defaults_theme["phone_support_text"] = "24/5 Phone support: 0800 556-880";
			$this->defaults_theme["main_menu_vertical_spacing"] = "21px";
			$this->defaults_theme["main_menu_horizontal_spacing"] = "20px";
			$this->defaults_theme["h3_font_size"] = "20px";
			$this->defaults_theme["phone_no"] = "24/7 Phone support: 0800 556-880";
			$this->defaults_theme["email"] = '';
			$this->defaults_theme["logo"] = ($this->template_directory) . '/images/kd_logo.png';
			$this->defaults_theme["logo_width"] = "264px";
			$this->defaults_theme["logo_height"] = "100%";
			$this->defaults_theme["h1_font_size"] = "32px";
			$this->defaults_theme["h1_font_weight"] = "700";
			$this->defaults_theme["h3_font_weight"] = "700";
			$this->defaults_theme["show_star_rating"] = "YES";
			$this->defaults_theme["footer_discover_url"] = "http://www.google.ro";
			$this->defaults_theme["footer_money_url"] = "http://www.google.ro";
			$this->defaults_theme["footer_visa_url"] = "http://www.google.ro";
			$this->defaults_theme["footer_paypal_url"] = "http://www.google.ro";
			$this->defaults_theme["footer_mastercard_url"] = "http://www.google.ro";
			$this->defaults_theme["main_menu_font_weight"] = "700";
			$this->defaults_theme["main_menu_subment_font_weight"] = "700";
			$this->defaults_theme["enable_product_general_description"] = "YES";
			$this->defaults_theme["enable_product_description_tab"] = "YES";
			$this->defaults_theme["google_api_key"] = "";
			$this->defaults_theme["carousel_nav_icon_picker"] = "icon-arrow-right8";
			$this->defaults_theme["carousel_nav_icon_size"] = "27";
			$this->defaults_theme["enable_discount_percent"] = "YES";
			$this->defaults_theme["show_post_date_meta"] = "YES";
			$this->defaults_theme["show_post_category_meta"] = "YES";
			$this->defaults_theme["show_post_comments_meta"] = "YES";
			$this->defaults_theme["enable_color_insteadofdropdown"] = "NO";
			$this->defaults_theme["rating_type"] = "own";
			$this->defaults_theme["product_general_description_type"] = "first_paragraph";
			$this->defaults_theme["enable_product_in_category"] = "YES";
			$this->defaults_theme["enable_top_filters_sidebar"] = "YES";
			$this->defaults_theme["enable_bottom_filters_sidebar"] = "YES";
		}

		public function page_menu_args($args)
		{
			$args['show_home'] = true;
			return $args;
		}

		public function related_products_args()
		{
			$args['posts_per_page'] = 10; // 4 related products
			return $args;
		}

		public function filter_woocommerce_sale_flash( $html, $post, $product )
		{
			$html = '';
			$enable_discount_percent = get_theme_mod('enable_discount_percent', $this->defaults_theme['enable_discount_percent']);
			if( $enable_discount_percent == 'YES' ) {
				$only_above = get_theme_mod('only_discount_percent_above');
				  
				if ($product->is_on_sale() && $product->get_type() == 'variable') {
 
					$available_variations = $product->get_available_variations();								
					$maximumper = 0;
					
					for ($i = 0; $i < count($available_variations); ++$i) {
						
						$variation_id = $available_variations[$i]['variation_id'];
						$variable_product1 = new WC_Product_Variation( $variation_id );
						
						if( $variable_product1->is_on_sale() ) {
							$regular_price = $variable_product1->get_regular_price();
							$sales_price = $variable_product1->get_sale_price();
							$percentage = round((( ( $regular_price - $sales_price ) / $regular_price ) * 100)) ;
							
							if ($percentage > $maximumper) {
								$maximumper = $percentage;
							}
						}
					}
					
					if( ((!isset($only_above) || $only_above == '') && $maximumper > 0) || ( $maximumper > 0 && isset($only_above) && $only_above != '' && $maximumper >= $only_above) ) {
						$html = '<span class="kd_salelabel">' . sprintf( __('%s', 'kingdom' ), $maximumper . '%' ) . '</span>';
					}
			            
				} else if ($product->is_on_sale() && $product->get_type() == 'simple') {
					$percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );
					
					if( $percentage > 0 && ( $percentage > 0 && isset($only_above) && $only_above != '' && $percentage >= $only_above) ) {
						$html = '<span class="kd_salelabel">' . sprintf( __('%s', 'kingdom' ), $percentage . '%' ) . '</span>';
					}
				} else if ($product->is_on_sale() && $product->get_type() == 'external') {
					$percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );
					
					if( $percentage > 0 && ( $percentage > 0 && isset($only_above) && $only_above != '' && $percentage >= $only_above) ) {
						$html = '<span class="kd_salelabel">' . sprintf( __('%s', 'kingdom' ), $percentage . '%' ) . '</span>';
					}
				}

			}else{
				
				$html = '<span class="kd_salelabel">' . __('Sale', 'kingdom') . '</span>';
				
			}
			
			return $html;
		}
	    
	    private function check_valid_colorhex($colorCode) {
		    // If user accidentally passed along the # sign, strip it off
		    $colorCode = ltrim($colorCode, '#');
		
		    if (
		          ctype_xdigit($colorCode) &&
		          (strlen($colorCode) == 6 || strlen($colorCode) == 3))
		               return true;
		
		    else return false;
		}

		public function frontend_style() 
		{
			$this->the_theme->coreFunctions->update_settings();
			
			$cssFiles = array( $this->the_theme->cfg['paths']['theme_dir_path'] . 'style.css' );
			if( file_exists( get_template_directory() . '-child/style.css' ) ) {
				$cssFiles[] = get_template_directory() . '-child/style.css';
			}
			
			$buffer = "";
			foreach ($cssFiles as $cssFile) {
				$buffer .= $this->the_theme->wp_filesystem->get_contents($cssFile);
			}
			
			$primary = get_theme_mod( 'primary', $this->defaults_theme['primary'] );
			
			if( $primary != '#C73030' ){
				$buffer = str_ireplace( "#C73030", $primary, $buffer);
				$buffer = str_ireplace( "#A21312", kingdom()->coreFunctions->adjustBrightness( $primary, -30 ), $buffer);
			}
			
			$secondary = get_theme_mod( 'secondary', $this->defaults_theme['secondary'] );
			if( $secondary != strtolower('#781B80') ){
				$buffer = str_ireplace( "#781B80" , $secondary, $buffer);
				$buffer = str_ireplace( "#196EA6", kingdom()->coreFunctions->adjustBrightness( $secondary, -30 ), $buffer);
			}
			
			$menu_normal_state = get_theme_mod( 'menu_normal_state', $this->defaults_theme['menu_normal_state'] );
			
			if( $menu_normal_state ){

				$buffer .= 'body .wpb_wrapper h3 { color: '.$secondary.';}';
				$buffer .= 'body .kd_alternate_menu .kd_alternate_menu-submenu a { color: '.$primary.';}';
				$buffer .= 'body .kd_alternate_menu .kd_alternate_menu-submenu-items a:hover { color: '.$secondary.';}';
				$buffer .= '.kd_product_offer_wrapper .kd_deal_price { color: '.$primary.';}';
				$buffer .= 'body .navigationbar .kd_main_menu li a { color: '.$menu_normal_state.';}';
				$buffer .= 'body .navigationbar .kd_main_menu .sub-menu { box-shadow: 0 3px 0 0 '.$menu_normal_state.' inset; }';
			}
			
			$menu_hover_state = get_theme_mod( 'menu_hover_state', $this->defaults_theme['menu_hover_state'] );
			if( $menu_hover_state ){
				$buffer .= 'body .navigationbar .kd_main_menu li a:hover, body .navigationbar .kd_main_menu > li.current-menu-item > a { color: '.$menu_hover_state.';}';
			}
			
			
			$menu_background = get_theme_mod( 'menu_background', $this->defaults_theme['menu_background'] );
			if( $menu_background ){
				$buffer .= '.kd_product_offer_wrapper .kd_prod_img a span { background-color: '.$primary.';}';
				$buffer .= '.kd_product_offer_wrapper .kd_deal_of_the_day { background-color: '.$primary.';}';	
				$buffer .= '.kd_product_offer_wrapper .kd_deal_of_the_day:after { border-bottom: 27px solid'.$primary.';}';	
				$buffer .= '.kd_product_offer_wrapper .kd_prod_img a span:hover { background-color: '.$secondary.';}';
				$buffer .= '.kd_alternate_menu li:hover { background-color: '.$menu_background.';}';
				$buffer .= 'body .navigationbar { background-color: '.$menu_background.';}';
				$buffer .= '.navigationbar .kd_main_menu .sub-menu { background-color: '.$menu_background.';}';
	
				$buffer .= 'body .mean-container .mean-bar { background-color: '.$menu_background.';}';
				$buffer .= '.mean-container .mean-bar { background-color: '.$menu_background.';}';
			
				$buffer .= 'body .mean-container .mean-nav { background-color: '.$menu_background.';}';
				$buffer .= '.mean-container .mean-nav { background-color: '.$menu_background.';}';
			}
			
			// custom fonts
			$font_main = get_theme_mod( 'font_main', $this->defaults_theme['font_main'] );
			$font_main_size = get_theme_mod( 'font_main_size', $this->defaults_theme['font_main_size'] );
			$font_headings = get_theme_mod( 'font_headings', $this->defaults_theme['font_headings'] );
			$main_menu_font = get_theme_mod( 'main_menu_font', $this->defaults_theme['main_menu_font'] );
			$main_menu_font_size = get_theme_mod( 'main_menu_font_size', $this->defaults_theme['main_menu_font_size'] );
			$main_menu_font_weight = get_theme_mod( 'main_menu_font_weight', $this->defaults_theme['main_menu_font_weight'] );
			$main_menu_submenu_font_size = get_theme_mod( 'main_menu_submenu_font_size', $this->defaults_theme['main_menu_submenu_font_size'] );
			$main_menu_submenu_font_weight = get_theme_mod( 'main_menu_submenu_font_weight', $this->defaults_theme['main_menu_submenu_font_weight'] );
			$main_menu_vertical_spacing = get_theme_mod( 'main_menu_vertical_spacing', $this->defaults_theme['main_menu_vertical_spacing'] );
			$main_menu_horizontal_spacing = get_theme_mod( 'main_menu_horizontal_spacing', $this->defaults_theme['main_menu_horizontal_spacing'] );
			$main_menu_submenu_top_margin = get_theme_mod( 'main_menu_submenu_top_margin', $this->defaults_theme['main_menu_submenu_top_margin'] );
			$main_content_font_size = get_theme_mod( 'main_content_font_size', $this->defaults_theme['main_content_font_size']  );
			$main_content_font_weight= get_theme_mod( 'main_content_font_weight', $this->defaults_theme['main_content_font_weight'] );
			$h1_font_size = get_theme_mod( 'h1_font_size', $this->defaults_theme['h1_font_size'] );
			$h1_font_weight = get_theme_mod( 'h1_font_weight', $this->defaults_theme['h1_font_weight'] );
			$h2_font_size = get_theme_mod( 'h2_font_size', $this->defaults_theme['h2_font_size'] );
			$h2_font_weight = get_theme_mod( 'h2_font_weight', $this->defaults_theme['h2_font_weight'] );
			$h3_font_size = get_theme_mod( 'h3_font_size', $this->defaults_theme['h3_font_size'] );
			$h3_font_weight = get_theme_mod( 'h3_font_weight', $this->defaults_theme['h3_font_weight'] );
			$h4_font_size = get_theme_mod( 'h4_font_size', $this->defaults_theme['h4_font_size'] );
			$h4_font_weight = get_theme_mod( 'h4_font_weight', $this->defaults_theme['h4_font_weight'] );
			$h5_font_size = get_theme_mod( 'h5_font_size', $this->defaults_theme['h5_font_size'] );
			$h5_font_weight = get_theme_mod( 'h5_font_weight', $this->defaults_theme['h5_font_weight'] );
			$h6_font_size = get_theme_mod( 'h6_font_size', $this->defaults_theme['h6_font_size'] );
			$h6_font_weight = get_theme_mod( 'h6_font_weight', $this->defaults_theme['h6_font_weight'] );
			$show_star_rating = get_theme_mod( 'show_star_rating', $this->defaults_theme['show_star_rating'] );
			$show_footer_partners = get_theme_mod( 'show_footer_partners', $this->defaults_theme['show_footer_partners'] );
			$enable_product_general_description = get_theme_mod( 'enable_product_general_description', $this->defaults_theme['enable_product_general_description'] );
			$carousel_nav_icon_size = get_theme_mod( 'carousel_nav_icon_size', $this->defaults_theme['carousel_nav_icon_size'] );
			
			if( $font_main ){
				$buffer = str_replace( "Open Sans", $font_main, $buffer );
			}

			if( $font_main_size ){
				$buffer .= 'body { font-size: '.$font_main_size.' !important;}';
			}
			
			if( $font_headings ){
				$buffer .= 'body .row h1, body .row h2, body .row h3, body .row h4, body .row h5, body .row h6 { font-family: '.$font_headings.' !important;}';
			}
			
			if( $main_menu_font ){
				$buffer .= 'body .navigationbar .kd_main_menu li a { font-family: '.$main_menu_font.' !important;}';
			}
			
			if( $main_menu_font_size ){
				$buffer .= 'body .navigationbar .kd_main_menu li a { font-size: '.$main_menu_font_size.' !important;}';
			}
		
			if( $main_menu_font_weight ){
				$buffer .= 'body .navigationbar .kd_main_menu li a { font-wieght: '.$main_menu_font_weight.' !important;}';
			}
			
			if( $main_menu_submenu_font_size ){
				$buffer .= 'body .navigationbar .kd_main_menu li ul li a { font-size: '.$main_menu_submenu_font_size.' !important;}';
			}
			
			if( $main_menu_submenu_font_weight ){
				$buffer .= 'body .navigationbar .kd_main_menu li ul li a { font-weight: '.$main_menu_submenu_font_weight.' !important;}';
			}
			
			if( $main_menu_vertical_spacing ){
				$buffer .= 'body .navigationbar .kd_main_menu > li a { padding-bottom: '.$main_menu_vertical_spacing.'; padding-top: '.$main_menu_vertical_spacing.';}';
			}
			
			if( $main_menu_horizontal_spacing ){
				$buffer .= 'body .navigationbar .kd_main_menu > li a { padding-left: '.$main_menu_horizontal_spacing.'; padding-right: '.$main_menu_horizontal_spacing.';}';
			}
			
			if( $main_menu_submenu_top_margin ){
				$buffer .= 'body .navigationbar .kd_main_menu .sub-menu { top: '.$main_menu_submenu_top_margin.';}';
			}
			
			if( $main_content_font_size ){
				$buffer .= 'body .row p { font-size: '.$main_content_font_size.' !important;}';
			}
			
			if( $main_content_font_weight ){
				$buffer .= 'body .row p { font-weight: '.$main_content_font_weight.' !important;}';
			}
			
			if( $h1_font_size ){
				$buffer .= 'body .row h1 { font-size: '.$h1_font_size.' !important;}';
			}
			
			if( $h1_font_weight ){
				$buffer .= 'body .row h1 { font-weight: '.$h1_font_weight.' !important;}';
			}
			
			if( $h2_font_size ){
				$buffer .= 'body .row h2 { font-size: '.$h2_font_size.' !important;}';
			}
			
			if( $h2_font_weight ){
				$buffer .= 'body .row h2 { font-weight: '.$h2_font_weight.' !important;}';
			}
			
			if( $h3_font_size ){
				$buffer .= 'body .row h3 { font-size: '.$h3_font_size.' !important;}';
			}
			
			if( $h3_font_weight ){
				$buffer .= 'body .row h3 { font-weight: '.$h3_font_weight.' !important;}';
			}
			
			if( $h4_font_size ){
				$buffer .= 'body .row h4 { font-size: '.$h4_font_size.' !important;}';
			}
		
			if( $h4_font_weight ){
				$buffer .= 'body .row h4 { font-weight: '.$h4_font_weight.' !important;}';
			}
			
			if( $h5_font_size ){
				$buffer .= 'body .row h5 { font-size: '.$h5_font_size.' !important;}';
			}
			
			if( $h5_font_weight ){
				$buffer .= 'body .row h5 { font-weight: '.$h5_font_weight.' !important;}';
			}
			
			if( $h6_font_size ){
				$buffer .= 'body .row h6 { font-size: '.$h6_font_size.' !important;}';
			}
			
			if( $h6_font_weight ){
				$buffer .= 'body .row h6 { font-weight: '.$h6_font_weight.' !important;}';
			}
			
			if( $show_star_rating && $show_star_rating == 'NO' ){
				$buffer .= 'body .rating-input { display: none !important;}';
			}
			
			if( $show_footer_partners && $show_footer_partners == 'NO' ){
				$buffer .= 'body #kd_footer_partners { display: none !important;}';
			}
		
			if( $enable_product_general_description && $enable_product_general_description == 'NO' ){
				$buffer .= 'body #kd_general_description { display: none !important;}';
			}
			
			if( $carousel_nav_icon_size && $carousel_nav_icon_size != '' ) {
				$buffer .= '.woocommerce.owl-carousel .owl-buttons .owl-prev, .woocommerce.owl-carousel .owl-buttons .owl-next, .owl-set .woocommerce .owl-buttons .owl-prev, .owl-set .woocommerce .owl-buttons .owl-next, #kd_related_products .owl-buttons .owl-prev, #kd_related_products .owl-buttons .owl-next { font-size: '.$carousel_nav_icon_size.'px !important; }';
			}
			
			// fix the images paths
			$buffer = str_replace( "images/", get_template_directory_uri() . "/images/", $buffer ); 
			
			// end
			
			
			//:: HOVER FIX
			$buffer = $this->fix_buffer_hover( $buffer );			
			
			// Remove comments
			$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
			 
			// Remove space after colons
			$buffer = str_replace(': ', ':', $buffer);
			 
			// Remove whitespace
			$buffer = str_replace(array("\r\n", "\r", "\n", "\t", '    ', '    '), '', $buffer);
			 
			// Enable GZip encoding.
			if ( ! ini_get('zlib.output_compression') || 'ob_gzhandler' != ini_get('output_handler') ) ob_start();
			else ob_start("ob_gzhandler");
			
			if( $this->need_refresh_css != true ){
				// Enable caching
				header('Cache-Control: public');
				 
				// Expire in one day
				header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
				 
				// Set the correct MIME type, because Apache won't set it for us
				header("Content-type: text/css");
			}
			 
			// Write everything out
			echo $buffer;  
			
			// try to write the buffer as .css
			//if( !is_file( get_template_directory() . '/load-style.css' ) ){
				$this->the_theme->wp_filesystem->put_contents( get_template_directory() . '/' . $this->main_style_css_name, $buffer );
			//}
			
			if( $this->need_refresh_css != true ){
				die;
			}
		}

		public function fix_buffer_hover( $buffer='' ) {
			//var_dump('<pre>', $buffer, '</pre>'); echo __FILE__ . ":" . __LINE__;die . PHP_EOL;

			$found = substr_count( $buffer, ':hover' );

			/*			
			$found = preg_match_all('/(?:^|[^\}\/\s]).+(?:\:hover)(?:[^\,\{]*|$)/imu', $buffer, $m);
			if ( ! $found || ! isset($m[0]) ) {
				return $buffer;
			}
			//var_dump('<pre>', $found, $m, '</pre>'); echo __FILE__ . ":" . __LINE__;die . PHP_EOL;
			$m = $m[0];
			
			foreach ($m as $key =>$val) {
				if ( strstr( $val, '{' ) ) {
					$val2 = $this->_fix_buffer_hover_acolade($val);
					$buffer = str_replace($val, $val2, $buffer);
				}
				else {
					$val2 = str_replace(':hover', '.is_hover', $val);
					$val2 = $val . ', ' . $val2 . PHP_EOL;
					$buffer = str_replace($val, $val2, $buffer);
				}
			}
			*/
			///*
			$buffer = $this->_fix_buffer_hover_acolade($buffer);
			//*/ 			

			//var_dump('<pre>', $buffer, '</pre>'); echo __FILE__ . ":" . __LINE__;die . PHP_EOL;

			$found2 = substr_count( $buffer, 'is_hover' );
			//var_dump('<pre>', $found, $found2, '</pre>'); echo __FILE__ . ":" . __LINE__;die . PHP_EOL;    
			
			return $buffer;
		}
		public function _fix_buffer_hover_acolade( $val='' ) {
			if ( ! strstr( $val, '{' ) ) {
				return $val;
			}

			$_ = explode('{', $val);
			foreach ($_ as $kk => $vv) { // foreach 1
				$_2 = explode('}', $vv);
				foreach ($_2 as $kk2 => $vv2) { // foreach 2
					$_3 = explode(',', $vv2);
					foreach ($_3 as $kk3 => $vv3) { // foreach 3
						$vv3a = str_replace(':hover', '.is_hover', $vv3);
						if ( $vv3 != $vv3a ) {
							$vv3a = $vv3 . ', ' . $vv3a;
						}
						$_3["$kk3"] = $vv3a;
					} // end foreach 3
					$_2["$kk2"] = implode(',', $_3);
				} // end foreach 2
				$_["$kk"] = implode('}', $_2);
			} // end foreach 1

			$val = implode('{', $_);
			return $val;
		}
		
		public function woocommerce_products_per_page(){
			global $woocommerce;
			$cols = get_theme_mod('products_per_page', $this->defaults_theme['products_per_page']);
			return $cols;
		}
		
		public function woocommerce_pre_get_posts( $q ) {   
			if ( function_exists( 'woocommerce_products_will_display' ) && @woocommerce_products_will_display() && $q->is_main_query() && ! is_admin() ) {
				$q->set( 'posts_per_page', $this->woocommerce_products_per_page() );
			}
	
			return $q;
	
		}
		
		public function sanitize_hex_color( $color )
		{
			if ( '' === $color )
				return '';

			// 3 or 6 hex digits, or the empty string.
			if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) )
				return $color;

			return null;
		}

		public function add_theme_colors()
		{
			$this->colors['primary'] = array(
				'color' => '#C73030',
				'name'	=> 'Primary Color'
			);

			$this->colors['secondary'] = array(
				'color' => '#781B80',
				'name'	=> 'Secondary Color'
			);
			
			$this->colors['menu_normal_state'] = array(
				'color' => '#ffffff',
				'name'	=> 'Menu Normal State Color'
			);
			
			$this->colors['menu_hover_state'] = array(
				'color' => '#ffffff',
				'name'	=> 'Menu Hover State Color'
			);
			
			$this->colors['menu_background'] = array(
				'color' => '#cb4040',
				'name'	=> 'Menu Background Color'
			);
			 
			
		}

	    public function kingdom_setup_theme()
	    {
			load_theme_textdomain('kingdom', get_template_directory() . '/languages');
			add_theme_support( "title-tag" );
			add_theme_support( "post-thumbnails" );
			
			// navigation menu	
			register_nav_menus(array(
		    	'top_nav' =>'Top Navigation',
		    	'main_nav' => 'Main Navigation',
		    	'alternate_nav' => 'Alternate Navigation', 
			));
	    }
		
		public function update_settings()
		{
			$this->settings['layout'] = maybe_unserialize( get_option( $this->the_theme->alias . '_config', true ) ); 
		}
		
		public function data_debug()
		{ 
			if( $this->debug == true ){
			?> 
				<script>console.log( '<?php echo json_encode($this->data);?>' )</script>
			<?php
			}	
		}
		
		public function update_page_data()
		{   
			$page_object = get_queried_object();
			$page_id     = get_queried_object_id();
			  
			if( $this->the_theme->is_woocommerce ){
				if( is_shop() ) {
					$page_id = wc_get_page_id('shop');
				}	
			}

			if( (int) $page_id > 0 ){
				// get the sidebar position and id
				$this->data['sidebar'] = array(
					'position' => get_post_meta( $page_id, '_page_sidebar_position', true ),
					'sidebars' => get_post_meta( $page_id, '_page_sidebar_ids', true ),
				);
			}
			
			$this->data['layout'] = get_post_meta( $page_id, '_layout', true );
			
			// get all sidebars
			$sidebars_list = get_option( 'kingdom_dynamic_sidebars', true ); 
			if( $sidebars_list && count($sidebars_list) > 0 && $sidebars_list !== true ){
				foreach ($sidebars_list as $sidebar ) {
					$this->data['sidebar'][sanitize_title($sidebar['title'])] = get_option( 'kingdom_ds_' . md5(sanitize_title($sidebar['title'])), true );
				}
			}
		}
		
		public function printSidebar( $pos='none' )
		{ 
			if( isset($this->data['page_sidebars']) && count($this->data['page_sidebars']) > 0 ){
				foreach ($this->data['page_sidebars'] as $sidebar_key => $sidebar_value) {
					if( 
						$sidebar_value['settings']['position'] == $pos 
						//&& (isset($this->data['sidebar']['printed']) && $this->data['sidebar']['printed'] != true) 
					){
						//$this->data['sidebar']['printed'] = true;
						if( in_array($pos, array('top', 'bottom')) ) {
							$col_class = 'col-lg-12 col-md-12 col-sm-12 col-xs-12';
						}else{
							$col_class = 'col-lg-3 col-md-4 col-sm-4 col-xs-12';
						}
		?>
						<div class="<?php echo $col_class; ?>">
							<div class="kd_shop_sidebar">
								<?php
									dynamic_sidebar( $sidebar_key );
								?>
							</div>
						</div>
		<?php
					}
				}
			}
		}
		
		public function has_side_bar()
		{
			$is_side_bar = false;
			
			foreach( $this->data['page_sidebars'] as $sidebar ) {
				if( in_array( $sidebar['settings']['position'], array('left', 'right') ) ) {
					$is_side_bar = true;
				}
			}
			
			return $is_side_bar;
		}

		public function content_class()
		{
			$shop_template = get_theme_mod('shop_template', $this->defaults_theme['shop_template']);
			
			$class = 'col-lg-12 col-md-12 col-sm-12 col-xs-12';
			if( isset($this->data['page_sidebars']) && count($this->data['page_sidebars']) > 0 && !is_search() && $this->has_side_bar() ){
					
				if ( $shop_template == 'regular' ) {
					$class = 'col-lg-9 col-md-8 col-sm-8 col-xs-12 kd_shop';
				}
				elseif( (is_product_category() || is_search() || is_shop() || is_product_taxonomy()) && !is_product() ) {
					$class = 'col-lg-9 col-md-8 col-sm-8 col-xs-12 kd_shop kd_shop_alternate kd_shop_has_sidebar';
				}
				else {
					$class = 'col-lg-9 col-md-8 col-sm-8 col-xs-12 kd_shop';
				}
				
			} else {
				
				if ( $shop_template == 'regular' ) {
					$class = 'col-lg-12 col-md-12 col-sm-12 col-xs-12 kd_shop kd_shop_no_sidebar';
				}
				else {
					$class = 'col-lg-12 col-md-12 col-sm-12 col-xs-12 kd_shop kd_shop_alternate kd_shop_no_sidebar';
				}
				
			}
			
			return $class;
		}


		public function register_sidebars()
		{
			if ( function_exists('register_sidebar') ) {
				// default sidebar
				
				register_sidebar(array(
					'name' => esc_html__('Shop - Top Filters', 'kingdom'),
					'id' => 'shop-top-filters',
					'description'   => '',
				    'class'         => '',
					'before_widget' => '<div class="kingdom-widget %2$s col-lg-3 col-md-6 col-sm-6 col-xs-12">',
					'after_widget'  => '</div>',
					'before_title'  => '<h3>',
					'after_title'   => '</h3>'
				));
				
				register_sidebar(array(
					'name' => esc_html__('Shop - Footer Filters', 'kingdom'),
					'id' => 'shop-footer-filters',
					'description'   => '',
				    'class'         => '',
					'before_widget' => '<div class="kingdom-widget col-lg-3 col-md-6 col-sm-6 col-xs-12">',
					'after_widget'  => '</div>',
					'before_title'  => '<h3>',
					'after_title'   => '</h3>'
				));
				
				register_sidebar(array(
					'name' => 'Footer Content',
					'id' => 'footercontent',
					'description'   => '',
				    'class'         => '',
					'before_widget' => '<div class="kingdom-widget col-lg-3 col-md-6 col-sm-6 col-xs-12"><div class="kd_footer_column">',
					'after_widget'  => '</div></div>',
					'before_title'  => '<h3>',
					'after_title'   => '</h3>'
				));
				
				// custom sidebars (base on admin.php?page=kingdom#!/sidebars)
				$sidebars_meta =  get_option( 'kingdom_dynamic_sidebars' );
				if(  $sidebars_meta !== false && count($sidebars_meta) > 0 && isset($sidebars_meta) && $sidebars_meta != '' ){
					$sidebars_meta = $sidebars_meta; 

					foreach ($sidebars_meta as $key => $value) {
						register_sidebar(array(
							'name' => $value['title'],
							'id' => sanitize_title($value['title']),
							'before_widget' => '<div id="%1$s" class="kingdom-widget %2$s sidebar-position-'. ( sanitize_title($value['title']) ) .'">',
							'after_widget' => '</div>',
							'before_title' => '<h3>',
							'after_title' => '</h3>'
						));  
					}
				}
			}
		}

		public function limit_posts_per_archive_page() {
			if ( is_search() )
				set_query_var('posts_per_archive_page', 100); // or use variable key: posts_per_page
		}

		/* 2. Register Google Fonts
		====================================== */
		public function kingdom_fonts_url() {
		    $font_url = '';
		    
		    /*
		    Translators: If there are characters in your language that are not supported
		    by chosen font(s), translate this to 'off'. Do not translate into your own language.
		     */
		    if ( 'off' !== _x( 'on', 'Google font: on or off', 'kingdom' ) ) {
		    	$fonts_arr = array();
				// main menu font
				$main_menu_font = get_theme_mod( 'main_menu_font', $this->defaults_theme['main_menu_font']);
				$font_main = get_theme_mod( 'font_main', $this->defaults_theme['font_main']);
				$font_headings = get_theme_mod( 'font_headings', $this->defaults_theme['font_headings']);
				if( $main_menu_font && $main_menu_font != $font_main ) {
					$fonts_arr[] = '|'. $main_menu_font;
				}
				
				// headings font
				if( $font_headings && $font_headings != $font_main ) {
					$fonts_arr[] = '|'. $font_headings;
				}
				$fonts_arr = implode('', $fonts_arr);
		        $font_url = add_query_arg( 'family', urlencode( ( $font_main ? $font_main : 'Open+Sans:400,300,600') . $fonts_arr ), "//fonts.googleapis.com/css" );
		    }
			
			//var_dump('<pre>',$font_url,'</pre>'); die;  
		    return $font_url;
		}

		/* 3. Load the css files for the theme
		====================================== */
		public function add_styles()
		{
			$protocol = is_ssl() ? 'https' : 'http';

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

			wp_enqueue_style( 'fonts', 'https://fonts.googleapis.com/css?family=Abril+Fatface|Rajdhani:500,700', array(), '1.0' );
			wp_enqueue_style( 'icomoon', $this->template_directory . 'css/icomoon.css', array(), '1.0' );
			wp_enqueue_style( 'bootstrap-css', $this->template_directory . 'css/bootstrap.css', array(), '3.1.0' );
			wp_enqueue_style( 'bootstrap-theme', $this->template_directory . 'css/bootstrap-theme.css', array(), '1.0' );	
			
			wp_enqueue_style( 'meanmenu-css', $this->template_directory . 'css/meanmenu.css', array(), '1.0' );
			
			wp_enqueue_style( 'kingdom-fonts', $this->kingdom_fonts_url(), array(), '1.0.0' );
			
			$main_style = admin_url('admin-ajax.php?action=kingdom_frontend_style');
			$main_style_cached = get_stylesheet_directory() . '/' . $this->main_style_css_name;
			
			if( isset($_REQUEST['wp_customize']) && $_REQUEST['wp_customize'] == 'on' ){
				$this->need_refresh_css = true;
			}
			
			if( $this->need_refresh_css ){
				$main_style = $main_style . "&" . time();
				
				/*foreach( $this->colors as $key => $color ){
					$main_style .= ("&" . $key . "=" . urlencode(get_theme_mod( $key )));
				}*/
				
			}
			else{
				if( is_file( $main_style_cached ) ) {
					if( (filemtime($main_style_cached) + $this->cfg['css_cache_time']) > time() ) {  
						$main_style = get_stylesheet_directory_uri() . '/' . $this->main_style_css_name;
					}
				}
			}
			
			//var_dump( $main_style );
			wp_enqueue_style( $this->the_theme->alias . '-main-style',	$main_style, array( 'bootstrap-css' ) );
			//wp_enqueue_style( $this->the_theme->alias . '-additional-style', $this->template_directory . 'css/additional.css', array( $this->the_theme->alias . '-main-style' ) );
			
			wp_enqueue_style( 'owl-carousel', $this->template_directory . 'owl-carousel/owl.carousel.css', array(), '1.2' );
			wp_enqueue_style( 'owl-carousel-theme', $this->template_directory . 'owl-carousel/owl.theme.css', array(), '1.2' );
			
			wp_enqueue_style( 'prettyphoto', $this->template_directory . 'addons/prettyphoto/prettyPhoto.css', array(), '1.0' );

			wp_enqueue_style( $this->the_theme->alias . '-font-awesome', $this->template_directory . 'css/font-awesome.css' );
		}
		
		/* 4. Load the javascript files for the theme
		============================================= */
		public function add_scripts()
		{
			$google_api_key = get_theme_mod('google_api_key', $this->defaults_theme['google_api_key']);
			if( isset( $google_api_key ) && $google_api_key != '' ) {
				wp_enqueue_script( $this->the_theme->alias . '-google-maps', '//maps.google.com/maps/api/js?key=' . $google_api_key, array('jquery'), '2.0', true);
			}
			wp_enqueue_script( 'bootstrapjs', $this->template_directory . 'js/bootstrap.js', array('jquery'), '3.0.0', true);
			wp_enqueue_script( 'owl-carousel', $this->template_directory . 'owl-carousel/owl.carousel.js', array('jquery'), '1.2', true);
			//wp_enqueue_script( 'bootstrap-rating', $this->template_directory . 'js/bootstrap-rating-input.min.js', array('jquery'), '1.0', true);
			wp_enqueue_script( 'ddaccordion', $this->template_directory . 'js/ddaccordion.js', array('jquery'), '1.0', true);
			wp_enqueue_script( $this->the_theme->alias . '-meanmenu', $this->template_directory . 'js/jquery.meanmenu.js', array('jquery'), '1.0', true);
			wp_enqueue_script( 'jquery-gmap', $this->template_directory . 'js/jquery.gmap.min.js', array('jquery', $this->the_theme->alias . '-google-maps'), '1.0', true);
			wp_enqueue_script( $this->the_theme->alias . '-main', $this->template_directory . 'js/main.js', array('jquery', 'jquery-ui-core', 'jquery-ui-slider'), '1.0', true);
			wp_enqueue_script( 'prettyPhoto', $this->template_directory . 'addons/prettyphoto/jquery.prettyPhoto.js', array('jquery', $this->the_theme->alias . '-main'), '3.1.6', true);
			
			// localize script
			$owl_nav_arrows = get_theme_mod('carousel_nav_icon_picker', $this->defaults_theme['carousel_nav_icon_picker']);
			$main_js_params = array(
				'text_show_more' => esc_html__('show more...', 'kingdom'),
				'text_show_less' => esc_html__('show less...', 'kingdom'),
				'owl_nav_arrow'	=> isset($owl_nav_arrows) && $owl_nav_arrows != '' ? $owl_nav_arrows : '',
				'shop_url' => get_permalink( $this->the_theme->is_woocommerce ? wc_get_page_id ( 'shop' ) : 0 ),
			);
			wp_localize_script( $this->the_theme->alias . '-main', 'kingdom_params', $main_js_params);
		}
		
		/* 5. Extra head html content
		============================= */
		public function html_head()
		{
			if (!empty( $this->data['facebook']['opengraph'] ) ) {
				?>
					<meta property="og:title" content=""/>
					<meta property="og:type" content=""/>
					<meta property="og:url" content="<?php echo esc_url( "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );?>"/>
					<meta property="og:site_name" content="<?php esc_attr( bloginfo( 'name') ); ?>"/>
					<meta property="fb:app_id" content="<?php echo esc_attr( $this->data['facebook']['opengraph'] );?>"/>
					<meta property="og:description" content=" <?php esc_attr( bloginfo( 'description') ); ?>"/>
				<?php
			}
			?>
			
			<script type="text/javascript">
			var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
			</script>
			
			<!--[if lt IE 9]>
				<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
			<![endif]-->
			<?php
			if( $this->need_refresh_css == true ){
			?>
			<style type="text/css" id="kd-customizer">
				<?php $this->frontend_style();?>
			</style>
			<?php	
			}
		}
		
		public function display_breadcrumbs()
	    {
	        $text['home']     = esc_html__('Home', 'kingdom'); // text for the 'Home' link
			$text['category'] = esc_html__('Archive by Category "%s"', 'kingdom'); // text for a category page
			$text['tax'] 	  = esc_html__('Archive for "%s"', 'kingdom'); // text for a taxonomy page
			$text['search']   = esc_html__('Search Results for "%s" Query', 'kingdom'); // text for a search results page
			$text['tag']      = esc_html__('Posts Tagged "%s"', 'kingdom'); // text for a tag page
			$text['author']   = esc_html__('Articles Posted by %s', 'kingdom'); // text for an author page
			$text['404']      = esc_html__('Error 404', 'kingdom'); // text for the 404 page
		
			$showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
			//$delimiter   = '<li class="arrow-breadcrumbs"></li>'; // delimiter between crumbs
			$delimiter = '';
			$before      = '<li class="current">'; // tag before the current crumb
			$after       = '</li>'; // tag after the current crumb
			/* === END OF OPTIONS === */
		
			global $post;
			$homeLink = esc_url( home_url('/') );
			$linkBefore = '<li typeof="v:Breadcrumb">';
			$linkAfter = '</li>';
			$linkAttr = ' rel="v:url" property="v:title"';
			$link = $linkBefore . '<a' . $linkAttr . ' href="%1$s">%2$s</a>' . $linkAfter;
		
			echo '<ol id="crumbs" class="breadcrumb" xmlns:v="http://rdf.data-vocabulary.org/#">' . sprintf($link, $homeLink, $text['home']) . $delimiter;
			
			if ( is_category() ) {
				$thisCat = get_category(get_query_var('cat'), false);
				if ($thisCat->parent != 0) {
					$cats = get_category_parents($thisCat->parent, TRUE, $delimiter);
					$cats = str_replace('<a', $linkBefore . '<a' . $linkAttr, $cats);
					$cats = str_replace('</a>', '</a>' . $linkAfter, $cats);
					echo $cats;
				}
				echo $before . sprintf($text['category'], single_cat_title('', false)) . $after;
	
			} elseif ( $this->the_theme->is_woocommerce && is_product() ) { 
				$terms = get_the_terms( $post->ID, 'product_cat' );
				$cats = '';
				if( $terms != '' && count( $terms ) > 0 ) {
					foreach ($terms as $term) {
					    $product_cat_id = $term->term_id;
						$product_cat_slug = $term->slug;
						$product_cat_name = $term->name;
						
						$cats .= '<li><a href="'. esc_url( get_term_link($term) ) .'">'.$product_cat_name.'</a></li>';	
						$cats .= '<li><a href="'. esc_url( get_permalink() ).'">'.$post->post_title.'</a></li>';			
						echo $cats;
						break; 
					}
				}
			} elseif ( $this->the_theme->is_woocommerce && is_tax() ) {

				$taxonomy = get_query_var('taxonomy');  
				$parent = get_term_by( 'slug', get_query_var($taxonomy), $taxonomy );
				
				if( isset($parent) && $parent !== false )  {
				
					$parentsHtml = "";
				
					while ($parent->parent != '0'){
						$term_id = $parent->parent; 
						$parent  = get_term_by( 'id', $term_id, $taxonomy);
						$parentsHtml = '<li><a href="' . ( esc_url( get_term_link($parent) ) ) . '">' . $parent->name . '</a></li>' . $parentsHtml;
					}
				
					echo $parentsHtml;
				
				}
				
				echo $before . sprintf($text['tax'], single_cat_title('', false)) . $after;
			
			} elseif( is_tax() ){    
				$thisCat = get_category(get_query_var('cat'), false);
				if ($thisCat->parent != 0) {
					$cats = get_category_parents($thisCat->parent, TRUE, $delimiter);
					$cats = str_replace('<a', $linkBefore . '<a' . $linkAttr, $cats);
					$cats = str_replace('</a>', '</a>' . $linkAfter, $cats);
					echo $cats;
				}
				echo $before . sprintf($text['tax'], single_cat_title('', false)) . $after;
			
			}elseif ( is_search() ) {
				echo $before . sprintf($text['search'], get_search_query()) . $after;
	
			} elseif ( is_day() ) {
				echo sprintf($link, get_year_link(get_the_time('Y')), get_the_time('Y')) . $delimiter;
				echo sprintf($link, get_month_link(get_the_time('Y'),get_the_time('m')), get_the_time('F')) . $delimiter;
				echo $before . get_the_time('d') . $after;
	
			} elseif ( is_month() ) {
				echo sprintf($link, get_year_link(get_the_time('Y')), get_the_time('Y')) . $delimiter;
				echo $before . get_the_time('F') . $after;
	
			} elseif ( is_year() ) {
				echo $before . get_the_time('Y') . $after;
	
			} elseif ( is_single() && !is_attachment() ) {
				if ( get_post_type() != 'post' ) {
					$post_type = get_post_type_object(get_post_type());
					$slug = $post_type->rewrite;
					printf($link, $homeLink . '/' . $slug['slug'] . '/', $post_type->labels->singular_name);
					if ($showCurrent == 1) echo $delimiter . $before . get_the_title() . $after;
				} else {
					$cat = get_the_category(); $cat = $cat[0];
					$cats = get_category_parents($cat, TRUE, $delimiter);
					if ($showCurrent == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats);
					$cats = str_replace('<a', $linkBefore . '<a' . $linkAttr, $cats);
					$cats = str_replace('</a>', '</a>' . $linkAfter, $cats);
					echo $cats;
					if ($showCurrent == 1) echo $before . get_the_title() . $after;
				}
	
			} elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
				$post_type = get_post_type_object(get_post_type());
				echo $before . $post_type->labels->singular_name . $after;
	
			} elseif ( is_page() && !$post->post_parent ) {
				if ($showCurrent == 1) echo $before . get_the_title() . $after;
	
			} elseif ( is_page() && $post->post_parent ) {
				$parent_id  = $post->post_parent;
				$breadcrumbs = array();
				while ($parent_id) {
					$page = get_page($parent_id);
					$breadcrumbs[] = sprintf($link, get_permalink($page->ID), get_the_title($page->ID));
					$parent_id  = $page->post_parent;
				}
				$breadcrumbs = array_reverse($breadcrumbs);
				for ($i = 0; $i < count($breadcrumbs); $i++) {
					echo $breadcrumbs[$i];
					if ($i != count($breadcrumbs)-1) echo $delimiter;
				}
				if ($showCurrent == 1) echo $delimiter . $before . get_the_title() . $after;
	
			} elseif ( is_tag() ) {
				echo $before . sprintf($text['tag'], single_tag_title('', false)) . $after;
	
			} elseif ( is_author() ) {
		 		global $author;
				$userdata = get_userdata($author);
				echo $before . sprintf($text['author'], $userdata->display_name) . $after;
	
			} elseif ( is_404() ) {
				echo $before . $text['404'] . $after;
			}
	
			echo '</ol>';
	    }
		
		public function get_product_more_images($offset = 0, $size, $class = '',$num ='-1')
		{
			global $post;

			$args = array(
				'order'          	=> 'ASC',
				'orderby'        	=> 'menu_order',
				'post_type'      	=> 'attachment',
				'post_parent'   	 => $post->ID,
				'post_mime_type' 	=> 'image',
				'post_status'    	=> null,
				'numberposts'     	=> $num,
				//'exclude'    	=> get_post_thumbnail_id(),
			);
			
			$attachments = get_posts( $args, ARRAY_A );
 
			$images = array();
		  	if ($attachments) {
				foreach ($attachments as $attachment) {
					$full_img = wp_get_attachment_image_src( $attachment->ID, 'full' );
					$images[] = array(
						'thumb' => wp_get_attachment_image( $attachment->ID, $size, false, array('class' => $class) ),
						'full_img' => $full_img[0]
					);
				}
			}
			return $images;
		}

		/**
		* Get first paragraph from a WordPress post. Use inside the Loop.
		*
		* @return string
		*/
		function get_first_paragraph()
		{
			global $post;
			$str = wpautop( get_the_content() );
			$str = substr( $str, 0, strpos( $str, '</p>' ) + 4 );
			$str = strip_tags($str);
			 
			return '<p>' . implode(' ', array_slice(explode(' ', $str), 0, 30)) . '</p>';
		}

		public function remove_gallery($content)
		{
			if( is_product() ){	
		    	return str_replace('[gallery]', '', $content);
			}
			return $content;
		}
		
		public function save_stars()
		{
			$_product_rating = (float)get_post_meta( (int)$_REQUEST['productid'], '_product_rating', true );
			$_product_votes = (int)get_post_meta( (int)$_REQUEST['productid'], '_product_votes', true );
			
			update_post_meta( (int)$_REQUEST['productid'], '_product_rating', $_product_rating + (float)$_REQUEST['value'] );
			update_post_meta( (int)$_REQUEST['productid'], '_product_votes', $_product_votes + 1 );
			die(json_encode(array(
				'status' => 'valid'
			)));
		}
		
		public function superscript_price_html( $price, $product )
		{
			$prod_id  = 0;
			if ( method_exists( $product, 'get_id' ) ) {
				$prod_id = (int) $product->get_id();
			} else if ( isset($product->id) && (int) $product->id > 0 ) {
				$prod_id = (int) $product->id;
			}
			$post_id = $prod_id;
			if ( $post_id <=0 ) return $price;
			
			return preg_replace('/\.([0-9]*)/', '<sup>.$1</sup>', $price);
		}
		
		public function print_slideshow_button( $key=0 )
		{
			return isset($this->data['slideshow_buttons'][$key]) ? $this->data['slideshow_buttons'][$key] : ''; 
		}

		public function remove_empty_p($content)
		{
		    $content = force_balance_tags($content);
		    return preg_replace('#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $content);
		}
		
		public function comment_template()
		{
			global $kingdom_comment;
			$GLOBALS['kingdom_comment'] = $kingdom_comment;   
		?>
			<div class="kd_comments">
				<div class="kd_comment_author">
					<div class="kd_comment_image">
						<?php echo get_avatar( $kingdom_comment, 58 );?>
					</div>
				</div>				
				<div class="kd_comment_container">
					<div class="kd_comment_name">
						<h3><?php comment_author();?></h3>
						<p><span><?php comment_date();?></span></p>
					</div>		
					<?php comment_text(); ?>
					<div class="kd_comment_reply"> <a href="#"><?php esc_html_e('Reply', 'kingdom'); ?></a></div>
				</div>
			</div>
		<?php
		}
		
		public function print_share_buttons( $post_id, $post_title='' )
		{
			$post_url = get_permalink( $post_id ); 
			$image_url = wp_get_attachment_url( get_post_thumbnail_id( $post_id ) );
			
			$twitter_share_on = get_theme_mod('twitter_share_on', $this->defaults_theme['twitter_share_on']);
			$facebook_share_on = get_theme_mod('facebook_share_on', $this->defaults_theme['facebook_share_on']);
			$gplus_share_on = get_theme_mod('gplus_share_on', $this->defaults_theme['gplus_share_on']);
			$pinterest_share_on = get_theme_mod('pinterest_share_on', $this->defaults_theme['pinterest_share_on']);
		?>
			<?php if( $twitter_share_on == 'YES' ) { ?>
			<a href="https://twitter.com/share?url=<?php echo esc_url($post_url);?>&text=<?php echo esc_attr($post_title);?>"><i class="fa fa-twitter" aria-hidden="true"></i></a>
			<?php } ?>
			<?php if( $facebook_share_on == 'YES' ) { ?>
			<a href="http://www.facebook.com/sharer.php?u=<?php echo esc_url($post_url);?>"><i class="fa fa-facebook" aria-hidden="true"></i></a>
			<?php } ?>
			<?php if( $gplus_share_on == 'YES' ) { ?>
			<a href="https://plus.google.com/share?url=<?php echo esc_url($post_url);?>"><i class="fa fa-google-plus" aria-hidden="true"></i></a>
			<?php } ?>
			<?php if( $pinterest_share_on == 'YES' ) { ?>
			<a href="https://pinterest.com/pin/create/link/?url=<?php echo esc_url($post_url);?>&amp;description=<?php echo esc_attr($post_title);?>"><i class="fa fa-pinterest" aria-hidden="true"></i></a>
			<?php } ?>
		<?php
		}
		
		public function shorten_string($str, $limit=100, $strip = false)
		{
		    $str = ($strip == true)?strip_tags($str):$str;
		    if (strlen ($str) > $limit) {
		        $str = substr ($str, 0, $limit - 3);
		        return (substr ($str, 0, strrpos ($str, ' ')).'...');
		    }
		    return trim($str);
		}
		
		public function 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'     				=> 'Kingdom - Core Functionality plugin',
					'slug'     				=> 'kingdom-core',
					'source'   				=> get_stylesheet_directory() . '/plugins/kingdom-core.zip',
					'required' 				=> false,
					'version' 				=> '1.0', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '', 
				),
				
				array(
					'name'     				=> 'Customizer Site Beautify',
					'slug'     				=> 'customizer-site-beautify',
					'source'   				=> get_stylesheet_directory() . '/plugins/customizer-site-beautify.zip',
					'required' 				=> false,
					'version' 				=> '0.1', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '', 
				),

				array(
					'name'     				=> 'ConvertPlus',
					'slug'     				=> 'convertplus',
					'source'   				=> get_stylesheet_directory() . '/plugins/convertplug.zip',
					'required' 				=> false,
					'version' 				=> '3.0.0', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '', 
				),

				array(
					'name'     				=> 'Premium Seo Pack',
					'slug'     				=> 'premium-seo-pack',
					'source'   				=> get_stylesheet_directory() . '/plugins/premium-seo-pack.zip',
					'required' 				=> false,
					'version' 				=> '2.2 Lite', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '', 
				),
				
				array(
					'name'     				=> 'Revolution Slider',
					'slug'     				=> 'revslider',
					'source'   				=> get_stylesheet_directory() . '/plugins/revslider.zip',
					'required' 				=> false,
					'version' 				=> '5.4.6.3.1', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '', 
				),
				
				array(
					'name'     				=> 'AA Backup Manager', 
					'slug'     				=> 'aa-backup-manager',
					'source'   				=> get_stylesheet_directory() . '/plugins/aa-backup-manager.zip',
					'required' 				=> false,
					'version' 				=> '1.0', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '',
				),

				array(
					'name'     				=> 'Kingdom Visual Composer Shortcodes', 
					'slug'     				=> 'js-composer-extend-kingdom',
					'source'   				=> get_stylesheet_directory() . '/plugins/js-composer-extend-kingdom.zip',
					'required' 				=> false,
					'version' 				=> '1.0', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '',
				),
				array(
					'name'     				=> 'Visual Composer', 
					'slug'     				=> 'js-composer',
					'source'   				=> get_stylesheet_directory() . '/plugins/js_composer.zip',
					'required' 				=> false,
					'version' 				=> '5.4.4', 
					'force_activation' 		=> false,
					'force_deactivation' 	=> false,
					'external_url' 			=> '',
				),

				
				
		        array(
		            'name'      => 'Woocommerce',
		            'slug'      => 'woocommerce',
		            'required'  => false,
		        ),
		        
				array(
		            'name'      => 'Contact Form 7',
		            'slug'      => 'contact-form-7',
		            'required'  => false,
		        ),
		        
				array(
		            'name'      => 'Recent Posts Widget Extended',
		            'slug'      => 'recent-posts-widget-extended',
		            'required'  => false,
		        ),
		        
			
				
			);
		
			// Change this to your theme text domain, used for internationalising strings
			$theme_text_domain = 'kingdom';
		
			/**
			 * 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(
				'domain'       		=> $theme_text_domain,         	// Text domain - likely want to be the same as your theme.
				'default_path' 		=> '',                         	// Default absolute path to pre-packaged plugins
				'menu'         		=> 'install-required-plugins', 	// Menu slug
				'has_notices'      	=> true,                       	// Show admin notices or not
				'is_automatic'    	=> false,					   	// Automatically activate plugins after installation or not
				'message' 			=> ''							// Message to output right before the plugins table
			);
		
			tgmpa( $plugins, $config );
		}

		public function adjustBrightness($hex, $steps) 
		{
		    // Steps should be between -255 and 255. Negative = darker, positive = lighter
		    $steps = max(-255, min(255, $steps));
		
		    // Format the hex color string
		    $hex = str_replace('#', '', $hex);
		    if (strlen($hex) == 3) {
		        $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
		    }
		
		    // Get decimal values
		    $r = hexdec(substr($hex,0,2));
		    $g = hexdec(substr($hex,2,2));
		    $b = hexdec(substr($hex,4,2));
		
		    // Adjust number of steps and keep it inside 0 to 255
		    $r = max(0,min(255,$r + $steps));
		    $g = max(0,min(255,$g + $steps));  
		    $b = max(0,min(255,$b + $steps));
		
		    $r_hex = str_pad(dechex($r), 2, '0', STR_PAD_LEFT);
		    $g_hex = str_pad(dechex($g), 2, '0', STR_PAD_LEFT);
		    $b_hex = str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
		
		    return '#'.$r_hex.$g_hex.$b_hex;
		}
		
		public function getAllGfonts( $what='all' ) { 
			$fonts = json_decode(  
				$this->the_theme->wp_filesystem->get_contents( $this->the_theme->cfg['paths']['theme_dir_path'] . '/fonts/google-webfonts.json' ) 
			, true);
			
			$ret_fonts = array();
			if(count($fonts['items']) > 0 ){ 
				foreach ( $fonts['items'] as $font ) {
					$ret_fonts[$font['family']] = $font['family'];
				}
			}
			
			if( $what == 'all' ){
				return $ret_fonts;
			}
			
		}
		
		public function print_WooZone_country_box()
		{
			global $WooZone;
			if( is_object($WooZone)) {
				$is_country_check = ( ! isset($WooZone->amz_settings['product_countries']) || 'yes' == $WooZone->amz_settings['product_countries'] ? true : false );
				if ( $is_country_check ) {
					$WooZone->frontend->woocommerce_single_product_summary();
				}
			}
		}
		
		public function get_product_ratings() 
		{
			$productid = isset($_REQUEST['productid']) && (int)$_REQUEST['productid'] > 0 ? (int)$_REQUEST['productid'] : 0;
			
			if( $productid == 0 ) {
				die(json_encode(array(
					'status' => 'invalid',
					'msg' => 'NO valid product ID'
				)));
			}
			
			// get the product country
			$country = get_post_meta( $productid, '_amzaff_country', true );
			if( $country == false || empty($country) || trim($country) == "" ){
				$country = 'com';
			}
			
			// get the product ASIN
			$asin = get_post_meta( $productid, '_amzASIN', true );
			if( $asin == false || empty($asin) || trim($asin) == "" ){
				$asin = 'invalid';
			}
			
			// get cached rating 
			$cached_rating = get_post_meta( $productid, '_kd_amz_rating', true );
			$cached_rating_when = get_post_meta( $productid, '_kd_amz_rating_when', true );
			if( $cached_rating != false && $cached_rating_when != false && isset($cached_rating) && isset($cached_rating_when) ){
 
				if( time() - 172800 /* 48 hours */ < $cached_rating_when){
				//if( 0 ){
					
					die(json_encode(array(
						'status' => 'valid',
						'data' => array(
							'rating' => $cached_rating,
							'when' => '(As Of ' . ( date('F j, Y, g:i a', $cached_rating_when ) ) . ')',
							'html' => wc_get_rating_html( floatval($cached_rating) )
						)
					)));
				}
			}

			$input = 'https://www.amazon.' . ( $country ) . '/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=' . $asin . '&' . time();

			$input = wp_remote_get( $input );
			$input = wp_remote_retrieve_body( $input );
			
			$rating = $this->get_string_between( $input, '<span class="a-size-base a-color-secondary">', '</span>' );
			$rating = trim($rating);
			$rating = @explode(" ", $rating);
			$rating = isset($rating[0]) ? (float)$rating[0] : 0;
			
			if( $rating >= 0 ){
				update_post_meta( $productid, '_kd_amz_rating_when', time() );
				update_post_meta( $productid, '_kd_amz_rating', $rating );
			}
			elseif( isset($cached_rating['value']) ){
				$rating = (float)$cached_rating;
			}
			else{
				update_post_meta( $productid, '_kd_amz_rating_when', time() );
				update_post_meta( $productid, '_kd_amz_rating', $rating );
				
				die(json_encode(array(
					'status' => 'invalid',
					'msg' => 'This product has no rating yet!'
				)));
			}
			
			die(json_encode(array(
				'status' => 'valid',
				'data' => array(
					'rating' => $rating,
					'when' => '(As Of ' . ( date('F j, Y, g:i a', time() ) ) . ')',
					'html' => wc_get_rating_html( floatval($rating) )
				)
			)));
		}

		public function get_string_between($string, $start, $end) 
		{
		    $string = ' ' . $string;
		    $ini = strpos($string, $start);
		    if ($ini == 0) return '';
		    $ini += strlen($start);
		    $len = strpos($string, $end, $ini) - $ini;
		    return substr($string, $ini, $len);
		}
		
		public function custom_edit_checkout_fields( $fields ) {
			 
			foreach ( $fields['billing'] as $billing_field_name => $billing_field_value ) {
				$fields['billing'][$billing_field_name]['label'] = false; 
				$fields['billing'][$billing_field_name]['placeholder'] = $billing_field_value['label'];
			}

			foreach ( $fields['shipping'] as $shipping_field_name => $shipping_field_value ) {
				$fields['shipping'][$shipping_field_name]['label'] = false; 
				$fields['shipping'][$shipping_field_name]['placeholder'] = $shipping_field_value['label'];
			}
			
			$fields['order']['order_comments']['label'] = false;
			$fields['order']['order_comments']['placeholder'] = 'Order notes...';
		
		   return $fields;
		}

	}
}

if(class_exists('kingdom_themeWalkerMainNav') != true && !is_admin()) {
	class kingdom_themeWalkerMainNav extends Walker_Nav_Menu
	{   
		function start_lvl( &$output, $depth=0, $args=array() ) 
		{ 
		    // depth dependent classes
		    $indent = ( $depth > 0  ? str_repeat( "\t", $depth ) : '' ); // code indent
		    $display_depth = ( $depth + 1); // because it counts the first submenu as 0
		    $classes = array(
		        'sub-menu',
		        ( $display_depth % 2  ? 'menu-odd' : 'menu-even' ),
		        ( $display_depth >=2 ? 'sub-sub-menu' : '' ),
		        'menu-depth-' . $display_depth
		        );
		    $class_names = implode( ' ', $classes );
			
		    // build html
		    $output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n";
		}
	  
		// add main/sub classes to li's and links
	 	function start_el( &$output, $item, $depth=0, $args=array(), $id=0 ) 
	 	{
		    global $wp_query;
		    $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
		  	$icon = '';
			
		    // depth dependent classes
		    $depth_classes = array(
		        ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ),
		        ( $depth >=2 ? 'sub-sub-menu-item' : '' ),
		        ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ),
		        'menu-item-depth-' . $depth
		    );
		    $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );
		  
		    // passed classes
		    $classes = empty( $item->classes ) ? array() : (array) $item->classes;
			$menu_icon = get_post_meta( $item->ID, 'menu-item-menu-icon', true );
			$menu_image = (int)get_post_meta( $item->ID, 'menu-item-menu-image', true );
	  		if( $menu_image > 0 ){
	  			$menu_image = wp_get_attachment_image_src( $menu_image, 'full' );
				if( $menu_image == false ){
					$menu_image = '';
				}else{
					$menu_image = $menu_image[0];
				}
	  		}
	  		
			if( isset($menu_icon) && trim($menu_icon) != "" ) {
				$icon_class = "fa ". $menu_icon;
				if( strpos( $menu_icon, "kingdom") > -1 ){
					$icon_class = "micon  ". str_replace( "kingdom-", "", $menu_icon );
				} 
		   		$icon = '<i class="' . ( $icon_class ) . '"></i>';
			}
			// find if have submenu
			$submenu_class = ''; 
			$is_on = false;
			if( count($classes) > 0 ){
				foreach ($classes as $key => $value){  
					// check if have submenu  	
					if( preg_match('/menu-item-has-children/i', $value) ){
						$submenu_class = $value;
					}
					
					// check if current element
					if( in_array($value, array('current-menu-item', 'current_page_item')) ){
						$is_on = true;
					}
				}
			}
			
			// passed classes
    		$classes = empty( $item->classes ) ? array() : (array) $item->classes;
    		$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
			
		    // build html
		    $output .= $indent . '<li class="' . ( $is_on == true ? 'on' : '' ) . ' ' . $class_names .'" data-submenu="' . ( trim($submenu_class) != "" ? $submenu_class : '' ) . '">';
		    
		    // link attributes
		    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
		    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
		    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
		    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
		    
		    $attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';

		    $attributes .= trim( $menu_image ) != ""    ? ' data-bg="'   . esc_attr( $menu_image       ) .'"' : '';
		  	
		  	$icon = ( isset( $icon ) && trim( $icon ) != '' ? $icon : '' );
			
			$icon_only = false;
			
			$menu_item_classes = explode(' ', $class_names);
			
			if( in_array('icon-only', $menu_item_classes) ) {
				$icon_only = true;
			}
			
			if( $icon_only == false ) {
			
				$item_title = isset($item->title) ? $item->title : $item->post_title;
				$menu_elm_text = apply_filters( 'the_title', $item_title, $item->ID );
				
			} else {
				$menu_elm_text = '';
			}
			  
		    $item_output = sprintf( '%1$s<a%2$s>%7$s%3$s%4$s%5$s</a>%6$s',
		        isset($args->before) ? $args->before : '',
		        isset($attributes) ? $attributes : '',
		        isset($args->link_before) ? $args->link_before : '',
		        $menu_elm_text,
		        isset($args->link_after) ? $args->link_after : '',
		        isset($args->after) ? $args->after : '',
		        isset($icon) ? $icon : ''
		    );

		    // build html
		    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
		}
	}
}