<?php

function theguard_set_ajax_connector($hook) {
    wp_localize_script('jquery', 'localajax', 
	    array(
	        'url' => admin_url('admin-ajax.php')
    	)
	);	
}

add_action('admin_enqueue_scripts', 'theguard_set_ajax_connector');
add_action('wp_enqueue_scripts', 'theguard_set_ajax_connector');

add_action( 'wp_ajax_handle_post_layout', 'theguard_handle_post_layout' );
add_action( 'wp_ajax_nopriv_handle_post_layout', 'theguard_handle_post_layout' );

function theguard_handle_post_layout () {
    if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
        if (delete_post_meta($_POST['post_id'], 'layout_settings')) echo "data removed for id=".$_POST['post_id']; else echo "data not removed for id=".$_POST['post_id'];
	}
}



/* 
    theguard_get_customized_slider() returns aliases of availeble sliders, dependinding
	of $theguard_page_type which can indicate WooComerce page (forms 'shop' prefix, 
	                                 Blog page (forms 'blog' prefix),
									 and regular page (forms '' prefix)
*/

function theguard_get_customized_slider() {
	
    global $secretlab, $theguard_layout;
	if ($secretlab['theguard_page_type'] == 'blog') {
	    $secretlab['theguard_pagetype_prefix'] = 'blog-';
	}
	else if ($secretlab['theguard_page_type'] == 'shop') {
	    $secretlab['theguard_pagetype_prefix'] = 'shop-';
	}
	else {
	    $secretlab['theguard_pagetype_prefix'] = '';
	}
	$param_name = $secretlab['theguard_pagetype_prefix'].'header14_slider';
	if (count($theguard_layout) == 0 || $theguard_layout[$param_name] == 'default') {
	    $params = $secretlab; 
	}
	else {
	    $params = $theguard_layout;
	}
    
	if (!empty($params[$param_name]) && preg_match('/(rev_|lay_)(.+)/', $params[$param_name], $slider)) {
		$type = $slider[1];
		$slider = $slider[2];
		if ($type == 'lay_') echo do_shortcode('[layerslider id="'.$slider.'"]');
		if ($type == 'rev_') echo do_shortcode('[rev_slider alias="'.$slider.'"]');
	}
	else return;
}

add_action('get_header_scripts', 'theguard_get_header_scripts');

function theguard_array_insert($array, $var, $position) {
    $before = array_slice($array, 0, $position);
    $after = array_slice($array, $position);

    $return = array_merge($before, (array) $var);
    return array_merge($return, $after);
}

function theguard_get_header_scripts() {

    global $secretlab;

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

	wp_register_script('modernizr', esc_url(get_template_directory_uri()) . '/js/modernizr.custom.57510.js', array(), false, false);
	wp_enqueue_script('modernizr');
	wp_register_script('jsbootstrap', esc_url(get_template_directory_uri()) . '/js/bootstrap.min.js', array('jquery'), false, true);
	wp_enqueue_script('jsbootstrap');
	wp_register_script('theguard_mainjs', esc_url(get_template_directory_uri()) . '/js/main.js', array('jquery'), false, true);
	wp_enqueue_script('theguard_mainjs');
	wp_register_script('theguard_category_block_js', esc_url(get_template_directory_uri()) . '/js/cat_shortcode.js', array('jquery'), false, true);
	wp_enqueue_script('theguard_category_block_js');
if (isset ($secretlab['style_type'])) {
	if ($secretlab['style_type'] != 0) {
		wp_register_script('theguard_viewportchecker', esc_url(get_template_directory_uri()) . '/js/jquery.viewportchecker.min.js', array('jquery'), false, true);
		wp_enqueue_script('theguard_viewportchecker');
	}
}
	wp_register_style('theguard_alicobold', esc_url(get_template_directory_uri()) . '/css/alicoBold.css', array(), false, 'all');
	wp_enqueue_style('theguard_alicobold');
	wp_register_style('theguard_sicon', esc_url(get_template_directory_uri()) . '/css/security.css', array(), false, 'all');
	wp_enqueue_style('theguard_sicon');
	wp_register_style('theguard_fontawesome', esc_url(get_template_directory_uri()) . '/css/font-awesome.min.css', array(), false, 'all');
	wp_enqueue_style('theguard_fontawesome');
	wp_register_style('theguard_ownstyles', esc_url(get_template_directory_uri()) . '/style.css', array('theguard_css'), false, 'all');
	wp_enqueue_style('theguard_ownstyles');
}

function theguard_post_is_in_descendant_category( $cats, $_post = null )
{
    foreach ( (array) $cats as $cat ) {
        // get_term_children() accepts integer ID only
        $descendants = get_term_children( (int) $cat, 'category');
        if ( $descendants && in_category( $descendants, $_post ) )
            return true;
    }
    return false;
}


/* 
  Function passing params to Slick Carousel JS script
*/

function theguard_add_slick_carousel() {

    global $secretlab;
	
    foreach ($secretlab['slick'] as $params) {
	
	if (!isset($params["961"])) {
	    $params['961'] = array( 'sp_row' => $params['sp_row'],
		                        'sp_scroll' => $params['sp_scroll'],
								'sp_show' => $params['sp_show'] );
	}
	
	if (!isset($params["768"])) {
	    $params['768'] = array( 'sp_row' => $params['sp_row'],
		                        'sp_scroll' => $params['sp_scroll'],
								'sp_show' => $params['sp_show'] );
	}	
	
	echo '<script type="text/javascript">jQuery(document).ready(function() { jQuery(".'.$params['class'].'").slick({
		  autoplay      : '.$params['autoplay'].
		 ',arrows        : '.$params['enable_nav'].
		 ',autoplaySpeed : '.$params['speed'].
		 ',dots : '.$params['dots'].
		 ',arrows : '.$params['arrows'].
		 ',slidesPerRow : '.$params['sp_row'].
		 ',slidesToScroll : '.$params['sp_scroll'].
		 ',slidesToShow : '.$params['sp_show'].
		  			 
		 ',responsive : [
          {
		      breakpoint : 961,
			  settings : {
			      slidesPerRow : '.$params["961"]["sp_row"].',
				  slidesToScroll : '.$params["961"]["sp_scroll"].', 
				  slidesToShow : '.$params["961"]["sp_show"].'
			  }
		  },		 
          {
		      breakpoint : 768,
			  settings : {
			      slidesPerRow : ' . $params["768"]["sp_row"].',
				  slidesToScroll : ' . $params["768"]["sp_scroll"].',
				  slidesToShow : ' . $params["768"]["sp_show"] . '				  
			  }
		  }		  
		  ]
		 }); });</script>';
		 
	}
			
    }

/**
 * Print HTML with meta information for current post in SecretLab Shortcodes Plugin: author, categories, date and comment counter.
 */
if ( ! function_exists( 'theguard_get_entry_meta' ) ) :

	function theguard_get_entry_meta($meta_set = true, $item = null)
	{
		global $secretlab, $post;
		
		if (!$meta_set) { 
		    $settings = $secretlab;
		}
		else {
		    $settings = array ( 'show_post_date' => true,
                                'show_post_category' => true,
								'show_post_author' => true,
								'show_comments_count' => true );
		}
		
		if (!$item) {
		    $p = $post;
		}
		else {
		    $p = $item;
		}
		
		$out = '';
		
		if (is_sticky($p->ID))
			$out .= '';


		/* Post data */
		$sl_show_post_date = isset($settings['show_post_date']) ? $settings['show_post_date'] : 1;
		if ($sl_show_post_date == 1) {
			if (!has_post_format('link') && 'post' == get_post_type($p)) {
				$out .= '<span class="post_date date updated"><i class="fa fa-calendar"></i> <a href="'.get_permalink($p->ID).'">'.get_the_date('F j, Y', $p).'</a></span>';
			}
		}

		// Post author
		if (isset($secretlab['show_post_author'])) {
			if ($secretlab['show_post_author'] == 1) {
				$out .= '<span class="vcard author author_name"><i class="fa fa-user"></i> <a class="url fn n" href="'.esc_url(get_author_posts_url(get_the_author_meta('ID'))).'" title="'.esc_html__('View all posts by %s', 'the-guard') . get_the_author().'" rel="author">'.get_the_author().'</a></span>';
			}
		}

		// Comments counter
		$sl_show_comments_count = isset($settings['show_comments_count']) ? $settings['show_comments_count'] : 1;
		if ($sl_show_comments_count == 1) {
			if (comments_open($p->ID)) {
			    $comments = wp_count_comments( $p->ID );
				if ($comments->approved > 0) {
				    $out .= '<span class="comments-link"> ';
				    $out .= '<a href="'.get_permalink($p->ID).'#comments'.'"><i class="fa fa-comments"></i> '.$comments->approved.' '.esc_html__('comments', 'the-guard').'</a>';
					$out .= '</span>';
				}
		        else {
		            $out .= '<span class="comments-link">
		                    <i class="fa fa-comments"></i> <a href="'.get_permalink($p->ID).'#respond"> 0</a>
				        </span>';
				}
			
            }			
		}
		
			
		return $out;
	}
endif;

// Excerpt function for SecretLab Shortcodes Plugin
function theguard_get_excerpt($p, $excerpt, $length = 30) {
    global $post;
    if ($excerpt) { return implode(' ', array_slice(explode(' ', $excerpt), 0 , $length)); }
	if (!$p) $p = $post;
    
    $text = strip_shortcodes( $p->post_content );
	$text = preg_replace( '~\[[^\]]+\]~', '', $text );

    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]&gt;', $text);
    $text = strip_tags($text);
    $excerpt_length = apply_filters('excerpt_length', $length);

	$more_link_text = '';
	$excerpt_more = apply_filters( 'the_content_more_link', '', $more_link_text );
    $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
    if ( count($words) > $excerpt_length || count($words) <= 5) {
            array_pop($words);
            $text = implode(' ', $words);
            $text = '<p>'.$text.'</p>';
    } else {
            $text = implode(' ', $words);
    }
	$raw_excerpt = '';

	if( !post_password_required( $p ) ){
		return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
	} else {
		return esc_html__( 'There is no excerpt because this is a protected post.', 'the-guard' );
	}

}

function theguard_get_excerpt_short($p, $excerpt, $length = 35) {

	global $post;

	if ($excerpt) return $excerpt;

	if (!$p) $p = $post;

	$text = strip_shortcodes( $p->post_content );

	$text = apply_filters('the_content', $text);
	$text = str_replace(']]>', ']]&gt;', $text);
	$text = strip_tags($text);
	$excerpt_length = apply_filters('excerpt_length', $length);
	$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
	if ( count($words) > $excerpt_length || count($words) <= 5) {
		array_pop($words);
		$text = implode(' ', array_slice( $words, 0, $length ) );
		$text = $text.'...' ;
	} else {
		$text = implode(' ', $words);
	}
	$raw_excerpt = '';

	return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}


function theguard_get_content ($p = null, $more_link_text = null, $strip_teaser = false) {
    global $post;
	if (!$p) $p = $post;

	if ( null === $more_link_text )
		$more_link_text = esc_html__( 'Continue reading', 'the-guard' ).'&hellip;';

	$output = '';
	$has_teaser = false;

	// If post password required and it doesn't match the cookie.
	if ( post_password_required( $p ) )
		return get_the_password_form( $p );

	$content = apply_filters( 'the_content', $p->post_content);
	if ( preg_match( '/<!--more(.*?)?-->/', $content, $matches ) ) {
		$content = explode( $matches[0], $content, 2 );
		if ( ! empty( $matches[1] ) && ! empty( $more_link_text ) )
			$more_link_text = strip_tags( wp_kses_no_null( trim( $matches[1] ) ) );

		$has_teaser = true;
	} else {
		$content = array( $content );
	}

	if ( false !== strpos( $p->post_content, '<!--noteaser-->' ) && ( ! $multipage ) )
		$strip_teaser = true;

	$teaser = $content[0];

	if ( $more_link_text && $strip_teaser && $has_teaser )
		$teaser = '';

	$output .= $teaser;

	if ( count( $content ) > 1 ) {
		if ( $more ) {
			$output .= '<span id="more-' . $post->ID . '"></span>' . $content[1];
		} else {
			if ( ! empty( $more_link_text ) )
                $more_link_text = preg_replace('/%s/', '', $more_link_text); // it is a hack !!
				/**
				 * Filter the Read More link text.
				 *
				 * @since 2.8.0
				 *
				 * @param string $more_link_element Read More link element.
				 * @param string $more_link_text    Read More text.
				 */
				$output .= apply_filters( 'the_content_more_link', ' <a href="' . get_permalink($p->ID) . "#more-{$p->ID}\" class=\"more-link\">$more_link_text</a>", $more_link_text );
			$output = force_balance_tags( $output );
		}
	}
	
	$preview = false;

	if ( $preview ) // Preview fix for JavaScript bug with foreign languages.
		$output =	preg_replace_callback( '/\%u([0-9A-F]{4})/', '_convert_urlencoded_to_entities', $output );

	return $output;	
}


?>
