<?php
define('ORANGE_THEME_VERSION', '1.0');
/**
 * Required: include OptionTree.
 */
require( trailingslashit(get_template_directory()) . 'inc/theme-options/functions.php' );

/**
 * Tgm init
 */
require get_template_directory() . '/inc/tgm-init.php';

/**
 * Extra functions
 */
require get_template_directory() . '/inc/theme-widgets.php';

/**
 * Extra functions
 */
require get_template_directory() . '/inc/extras.php';

/**
 * Image resize function
 */
require get_template_directory() . '/inc/dynamic-image.php';
/**
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';


/**
 * orange functions and definitions
 *
 * @package orange
 */
/**
 * Set the content width based on the theme's design and stylesheet.
 */
if (!isset($content_width)) {
    $content_width = 590; /* pixels */
}

if (!function_exists('orange_setup')) :

    /**
     * Sets 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 for post thumbnails.
     */
    function orange_setup() {

        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         * If you're building a theme based on orange, use a find and replace
         * to change 'orange' to the name of your theme in all the template files
         */
        load_theme_textdomain('orange', get_template_directory() . '/languages');

        // Add default posts and comments RSS feed links to head.
        add_theme_support('automatic-feed-links');

        /**
         * Post thumbnail
         */
        add_theme_support('post-thumbnails');

        /**
         * Post thumbnail image resize
         */
        add_image_size('post_thumbnail', 595, 224, true);

        // This theme uses wp_nav_menu() in one location.

        define('CUSTOM_MENU', 'custom_menu');

        register_nav_menus(array(
            CUSTOM_MENU => __('Main Menu', 'orange'),
        ));

        // Enable support for Post Formats.
        //add_theme_support('post-formats', array('aside', 'image', 'video', 'quote', 'link'));

        // Setup the WordPress core custom background feature.
        add_theme_support('custom-background', apply_filters('orange_custom_background_args', array(
            'default-color' => 'ffffff',
            'default-image' => '',
        )));

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

endif; // orange_setup
add_action('after_setup_theme', 'orange_setup');

/**
 * Get value from theme option 
 */
function orange_option($option_id, $default = null) {
    if (function_exists('ot_get_option')) {
        $options = ot_get_option($option_id, $default);
        return $options;
    }
    return $default;
}

/**
 * Update theme option values
 */
function orange_update_option($name, $value) {
    $options = get_option('orange_options');
    $options[$name] = $value;
    return update_option('orange_options', $options);
}

/**
 * Delete values from theme option
 */
function orange_delete_option($name) {
    $options = get_option('orange_options');
    unset($options[$name]);
    return update_option('orange_options', $options);
}

/**
 * Default nav fallback
 */
function orange_nav_fallback() {
    ?>
    <div id="menu">
        <ul class="pkmenu">
            <?php
            wp_list_pages('title_li=&show_home=1&sort_column=menu_order');
            ?>          
        </ul>
    </div>
    <?php
}

/**
 * Nav menu
 */
function orange_nav() {
    if (function_exists('wp_nav_menu')) {
        wp_nav_menu(array('theme_location' => 'custom_menu', 'container_id' => 'menu', 'menu_class' => 'pkmenu', 'fallback_cb' => 'orange_nav_fallback'));
    } else {
        orange_nav_fallback();
    }
}

/**
 * For attachment page
 */
if (!function_exists('orange_posted_in')) :

    /**
     * Prints HTML with meta information for the current post (category, tags and permalink).
     *
     */
    function orange_posted_in() {
        // Retrieves tag list of current post, separated by commas.
        $tag_list = get_the_tag_list('', ', ');
        if ($tag_list) {
            $posted_in = __('This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'orange');
        } elseif (is_object_in_taxonomy(get_post_type(), 'category')) {
            $posted_in = __('This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'orange');
        } else {
            $posted_in = __('Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'orange');
        }
        // Prints the string, replacing the placeholders.
        printf(
                $posted_in, get_the_category_list(', '), $tag_list, get_permalink(), the_title_attribute('echo=0')
        );
    }

endif;

/**
 * Pagination
 */
function orange_pagination($pages = '') {
    ?>
    <div class="nav-previous alignleft"><?php next_posts_link('Older posts', $pages); ?></div>
    <div class="nav-next alignright"><?php previous_posts_link('Newer posts'); ?></div>
    <?php
}

/**
 * Breadcrumbs
 * @global type $post
 * @global type $wp_query
 * @global type $author
 */
function orange_breadcrumbs() {
    $delimiter = '&raquo;';
    $home = 'Home'; // text for the 'Home' link
    $before = '<span class="current">'; // tag before the current crumb
    $after = '</span>'; // tag after the current crumb
    echo '<div id="crumbs">';
    global $post;
    $homeLink = home_url();
    echo '<a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' ';
    if (is_category()) {
        global $wp_query;
        $cat_obj = $wp_query->get_queried_object();
        $thisCat = $cat_obj->term_id;
        $thisCat = get_category($thisCat);
        $parentCat = get_category($thisCat->parent);
        if ($thisCat->parent != 0)
            echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
        echo $before . 'Archive by category "' . single_cat_title('', false) . '"' . $after;
    }
    elseif (is_day()) {
        echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
        echo '<a href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
        echo $before . get_the_time('d') . $after;
    } elseif (is_month()) {
        echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $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;
            echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a> ' . $delimiter . ' ';
            echo $before . get_the_title() . $after;
        } else {
            $cat = get_the_category();
            $cat = $cat[0];
            echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
            echo $before . get_the_title() . $after;
        }
    } elseif (!is_single() && !is_page() && get_post_type() != 'post') {
        $post_type = get_post_type_object(get_post_type());
        echo $before . $post_type->labels->singular_name . $after;
    } elseif (is_attachment()) {
        $parent = get_post($post->post_parent);
        $cat = get_the_category($parent->ID);
        $cat = $cat[0];
        echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
        echo '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a> ' . $delimiter . ' ';
        echo $before . get_the_title() . $after;
    } elseif (is_page() && !$post->post_parent) {
        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[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
            $parent_id = $page->post_parent;
        }
        $breadcrumbs = array_reverse($breadcrumbs);
        foreach ($breadcrumbs as $crumb)
            echo $crumb . ' ' . $delimiter . ' ';
        echo $before . get_the_title() . $after;
    } elseif (is_search()) {
        echo $before . 'Search results for "' . get_search_query() . '"' . $after;
    } elseif (is_tag()) {
        echo $before . 'Posts tagged "' . single_tag_title('', false) . '"' . $after;
    } elseif (is_author()) {
        global $author;
        $userdata = get_userdata($author);
        echo $before . 'Articles posted by ' . $userdata->display_name . $after;
    } elseif (is_404()) {
        echo $before . 'Error 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', 'swiftray') . ' ' . get_query_var('paged');
        if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author())
            echo ')';
    }
    echo '</div>';
}

/**
 * This function thumbnail id and
 * returns thumbnail image
 * @param type $iw
 * @param type $ih 
 */
function orange_get_thumbnail($iw, $ih) {
    $permalink = get_permalink();
    $thumb = get_post_thumbnail_id();
    $image = orange_thumbnail_resize($thumb, '', $iw, $ih, true, 90);
    if ((function_exists('has_post_thumbnail')) && (has_post_thumbnail())) {
        print "<a href='$permalink'><img class='postimg' src='{$image['url']}' width='{$image['width']}' height='{$image['height']}' /></a>";
    }
}

/**
 * This function gets image width and height and
 * Prints attached images from the post        
 */
function orange_get_image($width, $height) {
    $w = $width;
    $h = $height;
    global $post, $posts;
//This is required to set to Null
    $img_source = '';
    $permalink = get_permalink();
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    if (isset($matches [1] [0])) {
        $img_source = $matches [1] [0];
    }
    $img_path = orange_image_resize($img_source, $w, $h);
    if (!empty($img_path['url'])) {
        print "<a href='$permalink'><img src='{$img_path['url']}' class='postimg' alt='Post Image'/></a>";
    }
}

/**
 * Portfolio Image
 */
function orange_blog_image($imgwh, $imght) {
    global $post, $posts;
//This is required to set to Null
    $id = '';
    $the_title = '';
// Till Here
    $permalink = get_permalink();
    $homeLink = get_template_directory_uri();
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    if (isset($matches [1] [0])) {
        $first_img = $matches [1] [0];
    }
    if (!empty($first_img)) { //Defines a default image
        print "<img src='$first_img' class='postimg wp-post-image' alt='$the_title' />";
    }
}

/**
 * Favicon option
 */
function orange_childtheme_favicon() {
    if (orange_option('site_favicon') != '') {
        echo '<link rel="shortcut icon" href="' . orange_option('site_favicon') . '"/>' . "\n";
    }
}

add_action('wp_head', 'orange_childtheme_favicon');


/**
 * Custom css 
 */
function orange_custom_css() {
    $output = '';
    $custom_css = orange_option('custom_css');
    if ($custom_css <> '') {
        $output .= $custom_css . "\n";
    }
    // Output styles
    if ($output <> '') {
        $output = "<!-- Custom Styling -->\n<style type=\"text/css\">\n" . $output . "</style>\n";
        echo $output;
    }
}

add_action('wp_head', 'orange_custom_css');

/**
 * Alter default excerpt length
 */
function orange_excerpt_length($length) {
    return 35;
}

add_filter('excerpt_length', 'orange_excerpt_length');

/**
 * Custom excerpt
 */
function orange_trim_excerpt($length) {
    global $post;
    $explicit_excerpt = $post->post_excerpt;
    if ('' == $explicit_excerpt) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
    } else {
        $text = apply_filters('the_content', $explicit_excerpt);
    }
    $text = strip_shortcodes($text); // optional
    $text = strip_tags($text);
    $excerpt_length = $length;
    $words = explode(' ', $text, $excerpt_length + 1);
    if (count($words) > $excerpt_length) {
        array_pop($words);
        array_push($words, '[&hellip;]');
        $text = implode(' ', $words);
        $text = apply_filters('the_excerpt', $text);
    }
    return $text;
}

/**
 * Enqueuing css
 */
function orange_css() {
    wp_enqueue_style('orange-style', get_stylesheet_uri());
    wp_enqueue_style('orange-meanmenu', get_template_directory_uri() . '/css/meanmenu.css');
    wp_enqueue_style('orange-responsive', get_template_directory_uri() . '/css/responsive.css');
}

add_action('wp_enqueue_scripts', 'orange_css');

/**
 * Enqueue scripts and styles.
 */
function orange_scripts() {
    wp_enqueue_script('orange-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'), '', true);
    wp_enqueue_script('orange-flex', get_template_directory_uri() . '/js/jquery.flexslider-min.js', array('jquery'), '', true);
    wp_enqueue_script('orange-meanmenu', get_template_directory_uri() . '/js/jquery.meanmenu.js', array('jquery'), '', true);
    wp_enqueue_script('orange-init', get_template_directory_uri() . '/js/init.js', array('jquery'), '', true);
    if (is_singular() && get_option('thread_comments'))
        wp_enqueue_script('comment-reply');
}

add_action('wp_enqueue_scripts', 'orange_scripts');

function orange_posted_in() {
// Retrieves tag list of current post, separated by commas.
    $tag_list = get_the_tag_list('', ', ');
    if ($tag_list) {
        $posted_in = __('This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'swiftray');
    } elseif (is_object_in_taxonomy(get_post_type(), 'category')) {
        $posted_in = __('This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'swiftray');
    } else {
        $posted_in = __('Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'swiftray');
    }
// Prints the string, replacing the placeholders.
    printf($posted_in, get_the_category_list(', '), $tag_list, get_permalink(), the_title_attribute('echo=0'));
}
