<?php
/**
 * Main function
 *
 * @author LeapIn Corp.
 * @since 1.0.0
 */
/*********************
 * WP_HEAD GOODNESS
 * The default wordpress head is
 * a mess. Let's clean it up by
 * removing all the junk we don't
 * need.
 *********************/
function tp_head_cleanup()
{
    // category feeds
    // remove_action( 'wp_head', 'feed_links_extra', 3 );
    // post and comment feeds
    remove_action('wp_head', 'feed_links', 2);
    // EditURI link
    remove_action('wp_head', 'rsd_link');
    // windows live writer
    remove_action('wp_head', 'wlwmanifest_link');
    // previous link
    remove_action('wp_head', 'parent_post_rel_link', 10, 0);
    // start link
    remove_action('wp_head', 'start_post_rel_link', 10, 0);
    // links for adjacent posts
    remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
    // WP version
    remove_action('wp_head', 'wp_generator');
    // js and style for emoji
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');
    // remove WP version from css
    add_filter('style_loader_src', 'tp_remove_wp_ver_css_js', 9999);
    // remove Wp version from scripts
    add_filter('script_loader_src', 'tp_remove_wp_ver_css_js', 9999);

} /* end pjax blog head cleanup */


function tp_head_add_tags()
{
    $echo = '';
    if (TP_AMP_Tags::has_amp_page()):
        $echo .= sprintf('<link rel="amphtml" href="%s">', TP_AMP_Tags::get_amp_permalink());
    endif;
    echo $echo;
}

add_action('wp_head', 'tp_head_add_tags');

// A better title
// http://www.deluxeblogtips.com/2012/03/better-title-meta-tag.html
function rw_title($title)
{
    global $page, $paged;

    // Don't affect in feeds.
    if (is_feed()) return $title;
    $sep = '';
    $seplocation = '';
    // Add the blog's name
    if ('right' == $seplocation) {
        $title .= get_bloginfo('name');
    } else {
        $title = get_bloginfo('name') . $title;
    }

    // Add the blog description for the home/front page.
    $site_description = get_bloginfo('description', 'display');

    if ($site_description && (is_home() || is_front_page())) {
        $title .= " {$sep} {$site_description}";
    }

    // Add a page number if necessary:
    if ($paged >= 2 || $page >= 2) {
        $title .= " {$sep} " . sprintf(__('Page %s', 'pjax-blog'), max($paged, $page));
    }

    return $title;

} // end better title

// remove WP version from RSS
function tp_rss_version()
{
    return '';
}

// remove WP version from scripts
function tp_remove_wp_ver_css_js($src)
{
    if (strpos($src, 'ver='))
        $src = remove_query_arg('ver', $src);
    return $src;
}

// remove injected CSS for recent comments widget
function tp_remove_wp_widget_recent_comments_style()
{
    if (has_filter('wp_head', 'wp_widget_recent_comments_style')) {
        remove_filter('wp_head', 'wp_widget_recent_comments_style');
    }
}

// remove injected CSS from recent comments widget
function tp_remove_recent_comments_style()
{
    global $wp_widget_factory;
    if (isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) {
        remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
    }
}

// remove injected CSS from gallery
function tp_gallery_style($css)
{
    return preg_replace("!<style type='text/css'>(.*?)</style>!s", '', $css);
}


/*********************
 * SCRIPTS & ENQUEUEING
 *********************/

// loading modernizr and jquery, and reply script
function tp_scripts_and_styles()
{

    global $wp_styles; // call global $wp_styles variable to add conditional wrapper around ie stylesheet the WordPress way

    if (!is_admin()) {
        /**
         * enqueue js
         */
        if (WP_DEBUG) {
            // sandbox
            wp_enqueue_script('modernizr', get_js_file('libs/modernizr.custom.min.js'), array(), '2.6.2', true);
            wp_enqueue_script('shave', get_js_file('libs/jquery.shave.min.js'), array('jquery'), '2.1.3', true);
            wp_enqueue_script('barbajs', get_js_file('libs/barba.min.js'), array(), '1.0.0', false);
            wp_enqueue_script('aos', get_js_file('libs/aos.min.js'), array(), '2.2.0', true);
            wp_enqueue_script('pagetransition', get_js_file('libs/pagetransitions.js'), array('jquery'), '1.0.0', true);
//            wp_enqueue_script('tween-max', '//cdnjs.cloudflare.com/ajax/libs/gsap/1.18.1/TweenMax.min.js', array(), '1.18.1', true);
            wp_enqueue_script('swiper', '//cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.6/js/swiper.min.js', array(), '2.0.1', true);
            wp_enqueue_script('pjax-blog', get_js_file('scripts.js'), array('jquery', /*'tween-max',*/
                'shave', 'barbajs', 'pagetransition', 'aos', 'swiper'), '1.0.0', true);

        } else {
            // production
            // I wanted to concat all js files but Theme Check plugin gets error when trying to deregister core script, jquery.
//            wp_deregister_script('jquery');
            wp_enqueue_script('pjax-blog', get_js_file('bundle.js'), array('jquery'), '1.0.0', '1.0.0', true);
        }

        /**
         * enqueue styles
         */
        wp_enqueue_style('tp-stylesheet', get_css_file('style.css'), array(), '1.0.0', 'all');
        wp_enqueue_style('tp-ie-only', get_css_file('ie.css'), array(), '1.0.0');
        $wp_styles->add_data('tp-ie-only', 'conditional', 'lt IE 9'); // add conditional wrapper around ie stylesheet

        // comment reply script for threaded comments
        if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) {
            wp_enqueue_script('comment-reply');
        }
    }
}


function tp_admin_scripts_and_styles()
{
    // admin and customizer preview styles
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_style('admin_css', get_css_file('admin.css'), false, '1.0.0');

    // admin and customizer preview scripts
    wp_enqueue_script('wp-color-picker');

    // only in preview
    if (is_customize_preview()) {
        wp_enqueue_script('alpha-color-picker', get_js_file('libs/alpha-color-picker.js'), array('jquery', 'wp-color-picker'), '1.0.0', true);

        // only in wp-admin
    } else {
        wp_enqueue_script('tp-admin-script', get_js_file('admin.js'), array('wp-color-picker', 'jquery', 'jquery-ui-dialog'), false, true);
        wp_enqueue_script('alpha-color-picker-admin', get_js_file('libs/alpha-color-picker-admin.js'), array('jquery', 'wp-color-picker'), '1.0.0', true);
        wp_enqueue_style (  'wp-jquery-ui-dialog');
    }
}

/*********************
 * GET ICOMOON FONT FACE
 *********************/
function get_icomoon_font_face()
{
    $template_directory_uri = get_template_directory_uri();
    ob_start();
    ?>
    @font-face {
    font-family: "icomoon";
    src: url("<?php echo $template_directory_uri; ?>/library/fonts/icomoon/icomoon.eot");
    src: url("<?php echo $template_directory_uri; ?>/library/fonts/icomoon/icomoon.eot#iefix") format("embedded-opentype"),
    url("<?php echo $template_directory_uri; ?>/library/fonts/icomoon/icomoon.ttf") format("truetype"),
    url("<?php echo $template_directory_uri; ?>/library/fonts/icomoon/icomoon.woff") format("woff"),
    url("<?php echo $template_directory_uri; ?>/library/fonts/icomoon/icomoon.svg#icomoon") format("svg");
    font-weight: normal;
    font-style: normal;
    }
    <?php

    return trim(ob_get_clean());
}

function the_icomoon_font_face()
{
    printf('<style>%s</style>', get_icomoon_font_face());
}

add_action('wp_head', 'the_icomoon_font_face');

/*********************
 * SET CUSTOM FIELD TO TAX
 *********************/
function add_tp_custom_field_to_taxonomy()
{
    // A callback function to add a custom field to our "colors" taxonomy
    function taxonomy_custom_fields($tag)
    {
        // Check for existing taxonomy meta for the term you're editing
        if (is_object($tag)) :
            $t_id = $tag->term_id; // Get the ID of the term you're editing
            $term_meta = get_option("taxonomy_term_$t_id"); // Do the check
            ?>
            <tr class="form-field">
                <th scope="row" valign="top">
                    <label for="tax_color"><?php _e('Theme color', 'pjax-blog'); ?></label>
                </th>
                <td>
                    <?php
                    admin_output_alpha_color_picker_field(
                        'alpha-color-picker',
                        'term_meta[tax_color]',
                        $term_meta['tax_color'] ? $term_meta['tax_color'] : '',
                        'true',
                        '',
                        'true'
                    );
                    ?>
                    <!--                    <input type="text" class="tp-color-picker" name="term_meta[tax_color]" id="term_meta[tax_color]"-->
                    <!--                           value="-->
                    <?php //echo $term_meta['tax_color'] ? $term_meta['tax_color'] : '';
                    ?><!--">-->
                    <p class="description"><?php _e('Picked color will be used in this theme.', 'pjax-blog'); ?></p>
                </td>
            </tr>
        <?php else: ?>
            <div class="form-field terms-tax_color-wrap">
                <label for="tax_color"><?php _e('Theme color', 'pjax-blog'); ?></label>
                <?php
                admin_output_alpha_color_picker_field(
                    'alpha-color-picker',
                    'term_meta[tax_color]',
                    '',
                    'true',
                    '',
                    'true'
                );
                ?>
                <p class="description"><?php _e('Picked color will be used in this theme.', 'pjax-blog'); ?></p>
            </div>
        <?php endif;
    }

    // A callback function to save our extra taxonomy field(s)
    function save_taxonomy_custom_fields($term_id)
    {
        if (isset($_POST['term_meta'])) {
            $t_id = $term_id;
            $term_meta = get_option("taxonomy_term_$t_id");
            $cat_keys = array_keys($_POST['term_meta']);
            foreach ($cat_keys as $key) {
                if (isset($_POST['term_meta'][$key])) {
                    $term_meta[$key] = $_POST['term_meta'][$key];
                }
            }
            //save the option array
            update_option("taxonomy_term_$t_id", $term_meta);
        }
    }

    global $tp_vars;
    $taxonomies = $tp_vars['taxonomies'];

    foreach ($taxonomies as $tax) {
        $tax_name = $tax->name;
        // Add the fields to taxonomies, using our callback function
        add_action("${tax_name}_edit_form_fields", 'taxonomy_custom_fields', 10, 2);
//        add_action("${tax_name}_add_form_fields", 'taxonomy_custom_fields', 10, 2);

        // Save the changes made on taxonomies, using our callback function
        add_action("edited_${tax_name}", 'save_taxonomy_custom_fields', 10, 2);
    }

}

add_action('wp_loaded', 'add_tp_custom_field_to_taxonomy', 11);

/*********************
 * ASYNCRONOUS SCRIPTS & STYLES LOADING
 *********************/
function replace_script_tag($tag, $handle, $href)
{
    if (is_admin()) return $tag;
    if (TP_Theme_Mod::get_instance()->get(TP_IDs::$tp_stop_async_jquery_loading)) {
        if ($handle == "jquery-core" || $handle == "jquery-migrate") return $tag;
    }

    $id = 'id="' . $handle . '"';
    return str_replace("type='text/javascript'", $id . ' defer', $tag);
}

add_filter('script_loader_tag', 'replace_script_tag', 9999, 3);

function add_load_css_js()
{
    if (is_admin()) return;

    require_once(ABSPATH . 'wp-admin/includes/file.php');
    if (WP_Filesystem()) {
        global $wp_filesystem;
        $css = $wp_filesystem->get_contents(get_js_file('libs/loadCSS.js'));
    }
    if (!empty($css)) {
        echo sprintf('<script>%s</script>', $css);
    }
}

add_action('wp_head', 'add_load_css_js', 7);

function link_to_loadCSS_script($html, $handle, $href)
{
    if (is_admin()) return $html;
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $id = 'id="lazy-load-' . $handle . '"';
    $a = $dom->getElementById($handle . '-css');
    return sprintf('<script %s>loadCSS("%s",0,"%s");</script>', $id, $a->getAttribute("href"), $a->getAttribute("media"));
}

add_filter('style_loader_tag', 'link_to_loadCSS_script', 9999, 3);

/*********************
 * THEME SUPPORT
 *********************/

// Adding WP 3+ Functions & Theme Support
function tp_theme_support()
{

    // wp thumbnails (sizes handled in functions.php)
    add_theme_support('post-thumbnails');

    // default thumb size
    set_post_thumbnail_size(700, 700, true);

    // wp custom background (thx to @bransonwerner for update)
    add_theme_support('custom-background',
        array(
            'default-image' => '',    // background image default
            'default-color' => '',    // background color default (dont add the #)
            'wp-head-callback' => '_custom_background_cb',
            'admin-head-callback' => '',
            'admin-preview-callback' => ''
        )
    );

    // title support
    add_theme_support('title-tag');

    // rss thingy
    add_theme_support('automatic-feed-links');

    // to add header image support go here: http://themble.com/support/adding-header-background-image-support/

    // adding post format support
    add_theme_support('post-formats',
        array(
            'aside',             // title less blurb
            'gallery',           // gallery of images
            'link',              // quick link to other site
            'image',             // an image
            'quote',             // a quick quote
            'status',            // a Facebook like status update
            'video',             // video
            'audio',             // audio
            'chat'               // chat transcript
        )
    );

    // Enable support for HTML5 markup.
    add_theme_support('html5', array(
        'comment-list',
        'search-form',
        'comment-form'
    ));


} /* end pjax blog theme support */

/*********************
 * PAGE NAVI
 *********************/

// Numeric Page Navi (built into the theme by default)
function tp_page_navi()
{
    global $wp_query;
    $bignum = 999999999;
    if ($wp_query->max_num_pages <= 1)
        return;
    echo '<nav class="pagination">';
    echo paginate_links(array(
        'base' => str_replace($bignum, '%#%', esc_url(get_pagenum_link($bignum))),
        'format' => '',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages,
        'prev_text' => '&larr;',
        'next_text' => '&rarr;',
        'type' => 'list',
        'end_size' => 3,
        'mid_size' => 3
    ));
    echo '</nav>';
} /* end page navi */

/*********************
 * RANDOM CLEANUP ITEMS
 *********************/

// remove the p from around imgs (http://css-tricks.com/snippets/wordpress/remove-paragraph-tags-from-around-images/)
function tp_filter_ptags_on_images($content)
{
    return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}

// cleaning up excerpt
function tp_excerpt_more($more)
{
    global $post;
    // edit here if you like to change more link description
    return '...';
}

add_filter('excerpt_more', 'tp_excerpt_more');

function tp_excerpt_mblength($length)
{
    return 100;
}

add_filter('excerpt_mblength', 'tp_excerpt_mblength');

function tp_excerpt_length($length)
{
    return 300;
}

add_filter('excerpt_length', 'tp_excerpt_length', 999);

/*********************
 * INSERT TAG BEFORE SCRIPT LOADING
 *********************/
function tp_insert_tag_before_load_script()
{
    echo TP_Theme_Mod::get_instance()->get_script();
}

function tp_insert_tag_in_footer()
{
    echo TP_Theme_Mod::get_instance()->get_style();
}

/*********************
 * SET CUSTOM ARCHIVE TITLE
 *********************/
add_filter('get_the_archive_title', function ($title) {
    if (is_category()) {
        $title = single_cat_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_author()) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    }
    return $title;
});
?>
