<?php
/**
 * Krown Wordpress Theme functions and definitions
 *
 * @package Krown
 * @subpackage Krown
 * @since Krown 1.0
 */

//=====================================
// TMG Plugin Hook
//=====================================
if (!function_exists('krwn_plugin_load')) {

    function krwn_plugin_load() {
        // Load TGM plugin activation
        load_template(get_template_directory() . '/includes/admin/Plugin/class-tgm-plugin-activation.php');
    }

}
add_action('after_setup_theme', 'krwn_plugin_load');

//=====================================
// TGM plugin activation
//=====================================
if (!function_exists('krwn_theme_plugins')) {

    function krwn_theme_plugins() {
        // Add the following plugins
        $plugins = array(
			// Redux Framework
            array(
                'name' => 'Redux Framework',
                'slug' => 'redux-framework',
                'source' => get_template_directory() . '/includes/admin/Plugin/plugins/redux-framework.zip',
                'required' => true,
            ),
			// Contact Form 7
			array(
				'name' 				=> 'Contact Form 7',
				'slug' 				=> 'contact-form-7',
				'required'			=> true,
				'force_activation' 	=> false,
				'force_deactivation'=> false,
			),
			// RMS Custom Post Type
            array(
                'name' => 'Rmsit Custom Post',
                'slug' => 'Rmsit-Custom-Post',
                'source' => get_template_directory() . '/includes/admin/Plugin/plugins/Rmsit-Custom-Post.zip',
                'required' => true,
            ),
			// RMS Custom Post Type
            array(
                'name' => 'attachments',
                'slug' => 'attachments',
				'required'			=> true,
				'force_activation' 	=> false,
				'force_deactivation'=> false,
            ),
			// RMS Custom Post Type
            array(
                'name' => 'widget-importer-exporter',
                'slug' => 'widget-importer-exporter',
				'required'			=> true,
				'force_activation' 	=> false,
				'force_deactivation'=> false,
            )
        );
        tgmpa($plugins);
    }

}
add_action('tgmpa_register', 'krwn_theme_plugins');
//=====================================
// Redux Fremawork Hook
//=====================================
if (!class_exists('theme-option') && file_exists(dirname(__FILE__) . '/theme-option/ReduxCore/framework.php')) {
    require_once( dirname(__FILE__) . '/theme-option/ReduxCore/framework.php' );
}
if (!isset($redux_demo) && file_exists(dirname(__FILE__) . '/theme-option/sample/sample-config.php')) {
    require_once( dirname(__FILE__) . '/theme-option/sample/sample-config.php' );
}
if (!function_exists('redux_disable_dev_mode_plugin')) {

    function redux_disable_dev_mode_plugin($redux) {
        if ($redux->args['opt_name'] != 'redux_demo') {
            $redux->args['dev_mode'] = false;
        }
    }

    add_action('redux/construct', 'redux_disable_dev_mode_plugin');
}
//=====================================
// After Theme Setup Function
//=====================================
if (!function_exists('krwn_theme_setup')) :
    /**
     * Evential Theme setup.
     *
     * Set up theme defaults and registers support for various WordPress features.
     *
     * Note that this function is hooked into the after_setup_theme hook, which
     * runs before the init hook. The init hook is too late for some features, such
     * as indicating support post thumbnails.
     *
     * @since Evential 1.0
     */
    function krwn_theme_setup() {
		global $content_width;
		// Set Content Width
		if (!isset($content_width))
			$content_width = 900;
			
		// Title Tag
		add_theme_support( 'title-tag' );
		
		// Add theme support for automatic feed links.
		add_theme_support('automatic-feed-links');
		
		// Set Post Thumbnail
        // add_theme_support('post-thumbnails');
		// add_theme_support( 'post-formats', array('image', 'video', 'gallery', 'aside', 'status'));
		// add_post_type_support( 'portfolio', 'post-formats' );
		
		// Add your nav menus function to the 'init' action hook.
		add_action( 'init', 'krwn_register_menus' );
		
		// Add your sidebars function to the 'widgets_init' action hook.
		add_action( 'widgets_init', 'krwn_register_sidebars' );
		
		// Load JavaScript files on the 'wp_enqueue_scripts' action hook.
		add_action( 'wp_enqueue_scripts', 'krwn_all_default_script' );
		
		// Load Stylesheet files on the 'wp_enqueue_scripts' action hook.
		add_action( 'wp_enqueue_scripts', 'krwn_all_default_style' );
		
		// Load Google Font on the 'wp_enqueue_scripts' action hook.
		add_action( 'wp_enqueue_scripts', 'krwn_google_fonts' );
		
		// Load Editor Style on the 'wp_enqueue_scripts' action hook.
		add_action( 'wp_enqueue_scripts', 'krwn_add_editor_styles' );
		
		// Custom Header and Background
		add_theme_support('custom-header', array(
			// Header image default
			'default-image' => ''
		));
		add_theme_support('custom-background', array(
			// Background color default
			'default-color' => '000',
			// Background image default
			'default-image' => ''
		));
        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support('html5', array(
            'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
        ));

        /*
         * Enable support for Post Formats.
         * See http://codex.wordpress.org/Post_Formats
         */
        add_theme_support('post-formats', array(
            'image', 'video', 'audio',
        ));

        // Add support for featured content.
        add_theme_support('featured-content', array(
            'featured_content_filter' => 'evential_get_featured_posts',
            'max_posts' => 6,
        ));

        // This theme uses its own gallery styles.
        add_filter('use_default_gallery_style', '__return_false');
    }

endif; // evential_setup
add_action('after_setup_theme', 'krwn_theme_setup');
//==============================================================================================
// Load Enqueue JS, CSS and Nav Walker
//==============================================================================================
require dirname(__FILE__) . '/includes/admin/enqueue.php';
require dirname(__FILE__) . '/includes/admin/meta-box.php';
require dirname(__FILE__) . '/includes/widget.php';

//=================================================
// Add Menu
//=================================================
function krwn_register_menus() {
	register_nav_menus(array(
		'primary' => __('Top primary menu', 'Evential'),
	));
}
//=================================================
// Add Image Size
//=================================================
add_action( 'after_setup_theme', 'setup' );
function setup() {
    add_theme_support( 'post-thumbnails' ); // This feature enables post-thumbnail support for a theme
	add_theme_support( 'post-formats', array('image', 'video', 'gallery'));
    add_post_type_support( 'portfolio', 'post-formats' );
	// Team image Resize
    add_image_size( 'team_thumb', 263, 340, true ); 
    add_image_size( 'port_thumb', 315, 315, true );
    add_image_size( 'port_large', 750, 750, true );
    add_image_size( 'client_thumb', 190, 122, true ); 
    add_image_size( 'blog_thumb', 360, 252, true ); 
    add_image_size( 'fullpage_thumb', 1140, 400, true ); 
    add_image_size( 'blog_single', 850, 590, true ); 
}
//=================================================
// Add Sidebar Support
//=================================================
function krwn_register_sidebars() {
    if (function_exists('register_sidebar')) {

        register_sidebar(
                array(
                    'name' => __('Main Sidebar', 'evential'),
                    'id' => 'main-sidebar',
                    'description' => __('Appears on posts and pages, which has its own widgets', 'evential'),
                    'before_widget' => '<div id="%1$s" class="widget %2$s">',
                    'after_widget' => '</div>',
                    'before_title' => '<h3>',
                    'after_title' => '</h3>'
                )
        );
    }
}

//=================================================
// Enable Page excerpt
//=================================================
function enable_page_excerpt() {
    add_post_type_support('page', 'excerpt');
}
add_action('init', 'enable_page_excerpt');

//=================================================
// Pagination
//=================================================
function pagination($pages = '', $range = 1) {
    $rms_showitems = ($range * 2) + 1;

    global $paged;
    if (empty($paged))
        $paged = 1;

    if ($pages == '') {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if (!$pages) {
            $pages = 1;
        }
    }

    if (1 != $pages) {
        echo "<ul class=\"pagination blog2\">";
        if ($paged > 2 && $paged > $range + 1 && $rms_showitems < $pages)
            echo "<a href='" . get_pagenum_link(1) . "'><img style='margin-right: 15px;' src='" . get_template_directory_uri() . "/images/arrow.png' alt='left-arrow'/></a>";
        if ($paged > 1 && $rms_showitems < $pages)
            echo "<a href='" . get_pagenum_link($paged - 1) . "' style='float: left;margin-right: 20px;line-height: 35px;'> <i class='fa fa-angle-double-left'></i></a>";

        for ($i = 1; $i <= $pages; $i++) {
            if (1 != $pages && (!($i >= $paged + $range + 1 || $i <= $paged - $range - 1) || $pages <= $rms_showitems )) {
                echo ($paged == $i) ? "<li><a class=\"cur-page\" style='border-radius: 0;color: rgb(112, 112, 112)'>" . $i . "</a></li>" : "<li><a href='" . get_pagenum_link($i) . "' class=\"inactive\" style=' border-radius: 0;color:#ae9364'>" . $i . "</a></li>";
            }
        }

        if ($paged < $pages && $rms_showitems < $pages)
            echo "</li><a href=\"" . get_pagenum_link($paged + 1) . "\" style='float: left;line-height: 35px;margin-left: 20px;'>
		 <i class='fa fa-angle-double-right'></i></a></li>";
        echo "</ul>\n";
    }
}


//======================================
// Activate Shortcode
//======================================
$ThemePageShortcode = array('section','rtweet', 'features', 'row', 'counter' ,'heading', 'columns', 'textblock', 'team', 'fun','fun2', 'googlemap', 'testimonial', 'portfolio', 'pricing', 'faq', 'client', 'services', 'imageblock', 'spacers', 'blogpost', 'skill','process','callaction');

//==============================================================================================
// Load Krwn options
//==============================================================================================
require dirname(__FILE__) . '/includes/krwn-bootstrap.php';
//====================================
// Multi Images Uploader
//====================================
function my_attachments( $attachments )
{
  $fields         = array(
  );

  $args = array(

    // title of the meta box (string)
    'label'         => 'My Attachments',

    // all post types to utilize (string|array)
    'post_type'     => array( 'portfolio','post' ),

    // meta box position (string) (normal, side or advanced)
    'position'      => 'normal',

    // meta box priority (string) (high, default, low, core)
    'priority'      => 'high',

    // allowed file type(s) (array) (image|video|text|audio|application)
    'filetype'      => null,  // no filetype limit

    // include a note within the meta box (string)
    'note'          => 'Attach Images Here!',

    // by default new Attachments will be appended to the list
    // but you can have then prepend if you set this to false
    'append'        => true,

    // text for 'Attach' button in meta box (string)
    'button_text'   => __( 'Attach Files', 'attachments' ),

    // text for modal 'Attach' button (string)
    'modal_text'    => __( 'Attach', 'attachments' ),

    // which tab should be the default in the modal (string) (browse|upload)
    'router'        => 'browse',

    // whether Attachments should set 'Uploaded to' (if not already set)
	'post_parent'   => false,

    // fields array
    'fields'        => $fields,

  );

  $attachments->register( 'my_attachments', $args ); // unique instance name
}

add_action( 'attachments_register', 'my_attachments' );
//==============================================================================================
// Breadcrumbs Functions
//==============================================================================================
function my_breadcrumbs() {
 
    /* === OPTIONS === */
    $text['home']     = 'Home'; // text for the 'Home' link
    $text['category'] = 'Archive by Category "%s"'; // text for a category page
    $text['search']   = 'Search Results for "%s" Query'; // text for a search results page
    $text['tag']      = 'Posts Tagged "%s"'; // text for a tag page
    $text['author']   = 'Articles Posted by %s'; // text for an author page
    $text['404']      = 'Error 404'; // text for the 404 page
 
    $show_current   = 1; // 1 - show current post/page/category title in breadcrumbs, 0 - don't show
    $show_on_home   = 0; // 1 - show breadcrumbs on the homepage, 0 - don't show
    $show_home_link = 1; // 1 - show the 'Home' link, 0 - don't show
    $show_title     = 1; // 1 - show the title for the links, 0 - don't show
    $delimiter      = ' <span class="color">/</span> '; // delimiter between crumbs
    $before         = '<span class="current">'; // tag before the current crumb
    $after          = '</span>'; // tag after the current crumb
    /* === END OF OPTIONS === */
 
    global $post;
    $home_link    = home_url('/');
    $link_before  = '<span typeof="v:Breadcrumb">';
    $link_after   = '</span>';
    $link_attr    = ' rel="v:url" property="v:title"';
    $link         = $link_before . '%2$s' . $link_after;
    $parent_id    = $parent_id_2 = $post->post_parent;
    $frontpage_id = get_option('page_on_front');
 
    if (is_home() || is_front_page()) {
 
        if ($show_on_home == 1) echo '<h3><a href="' . $home_link . '">' . $text['home'] . '</a></h3>';
 
    } else {
 
        echo '<h2>';
        if ($show_home_link == 1) {
            echo '' . $text['home'] . '';
            if ($frontpage_id == 0 || $parent_id != $frontpage_id) echo $delimiter;
        }
 
        if ( is_category() ) {
            $this_cat = get_category(get_query_var('cat'), false);
            if ($this_cat->parent != 0) {
                $cats = get_category_parents($this_cat->parent, TRUE, $delimiter);
                if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats);
                $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats);
                $cats = str_replace('</a>', '</a>' . $link_after, $cats);
                if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats);
                echo $cats;
            }
            if ($show_current == 1) echo $before . sprintf($text['category'], 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, $home_link . '/' . $slug['slug'] . '/', $post_type->labels->singular_name);
                if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after;
            } 
			else {
                $cat = get_the_category(); $cat = $cat[0];
                $cats = get_category_parents($cat, TRUE, $delimiter);
                if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats);
                $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats);
                $cats = str_replace('</a>', '</a>' . $link_after, $cats);
                if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats);
                echo $cats;
                if ($show_current == 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_attachment() ) {
            $parent = get_post($parent_id);
            $cat = get_the_category($parent->ID); $cat = $cat[0];
            $cats = get_category_parents($cat, TRUE, $delimiter);
            $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats);
            $cats = str_replace('</a>', '</a>' . $link_after, $cats);
            if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats);
            echo $cats;
            printf($link, get_permalink($parent), $parent->post_title);
            if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after;
 
        } elseif ( is_page() && !$parent_id ) {
            if ($show_current == 1) echo $before . get_the_title() . $after;
 
        } elseif ( is_page() && $parent_id ) {
            if ($parent_id != $frontpage_id) {
                $breadcrumbs = array();
                while ($parent_id) {
                    $page = get_page($parent_id);
                    if ($parent_id != $frontpage_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 ($show_current == 1) {
                if ($show_home_link == 1 || ($parent_id_2 != 0 && $parent_id_2 != $frontpage_id)) echo $delimiter;
                echo $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;
        }
 
        if ( get_query_var('paged') ) {
            if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
            echo __('Page','krwn') . ' ' . get_query_var('paged');
            if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
        }
 
        echo '</h2><!-- .breadcrumbs -->';
 
    }
}
//==============================================================================================
// inner page script
//==============================================================================================
function krwn_inner_scripts() {
        wp_enqueue_script('custom', get_template_directory_uri().'/assets/js/custom-inner.js', array( 'easypiechart' ), '', true);
}
function krwn_front_scripts() {
        wp_enqueue_script('custom', get_template_directory_uri().'/assets/js/custom.js', array( 'easypiechart' ), '', true);
}
function script_check_loading()
{
    if( is_front_page() )
    {
        add_action( 'wp_enqueue_scripts', 'krwn_front_scripts' );
    }
	elseif ( is_home() )
    {
        add_action( 'wp_enqueue_scripts', 'krwn_inner_scripts' );
    }
    else
    {
        add_action( 'wp_enqueue_scripts', 'krwn_inner_scripts' );
    }
}
add_action( 'wp', 'script_check_loading' );