<?php

global $kippis_is_smartphone;
global $kippis_options;

add_action('after_setup_theme','kippis_setup');  // Runs before the init hook.

if (!function_exists('kippis_setup')) {
function kippis_setup()
{
  global $kippis_is_smartphone;
  global $kippis_options;
  require(get_template_directory() . '/inc/class_mobile_detect.php');
  $pMobileDetect = new KMobileDetect();
  $kippis_is_smartphone = $pMobileDetect->isMobile();
  $kippis_options = kippis_get_options();
  if ($kippis_is_smartphone) add_filter('stylesheet_uri','kippis_stylesheet_uri');
  require(get_template_directory() . '/inc/define.php');
  load_theme_textdomain('kippis',get_template_directory() . '/languages');
  $locale = get_locale();
  $locale_file = get_template_directory() . "/languages/$locale.php";
  if (is_readable($locale_file)) require_once($locale_file);
  add_editor_style();
  register_nav_menus(array('primary'   => __('Primary Menu'  ,'kippis')
                          ,'secondary' => __('Secondary menu','kippis')
                          ));
  add_theme_support('automatic-feed-links');
  add_theme_support('post-formats',array('gallery','image'));
  add_theme_support('post-thumbnails');
  set_post_thumbnail_size(200);
  add_image_size('pic-icon',90);
  //add_filter('attachment_fields_to_edit','kippis_add_image_sizes_to_editor',100,2);
  add_filter('image_size_names_choose','kippis_add_image_sizes_to_editor');
  add_action('wp_enqueue_scripts','kippis_enqueue_scripts');
  add_action('admin_menu'        ,'kippis_adjust_admin_menu',999);
  if (is_admin()) require_once(get_template_directory() . '/options/kippis_admin.php');
}}

require(get_template_directory() . '/inc/widget_post.php'  );

if (!function_exists('kippis_enqueue_scripts')) {
function kippis_enqueue_scripts()
{
  wp_enqueue_script('jquery');
  wp_enqueue_script('kippis_script_js',get_template_directory_uri() . '/inc/script.js');
  if (is_singular() && get_option('thread_comments')) wp_enqueue_script('comment-reply');
}}

if (!function_exists('kippis_get_options')) {
function kippis_get_options()
{
  if (get_option('kippis_all_background') !== false) kippis_get_options_upgrade_options();
  include get_template_directory() . '/options/init_fields.php';
  $kippis_options = array();
  $arrOptions = get_option('kippis');
  if (empty($arrOptions)) {  // If upgraded from a version prior to 1.10, convert options.
    foreach ($options as $option) {
      if (!(($option['type'] == 'open') || ($option['type'] == 'close') || ($option['type'] == 'displayonly'))) {
        $kippis_options[$option['id']] = $option['std'];
      }
    }
    update_option('kippis',$kippis_options);
  }
  else {
    foreach ($options as $option) {
      if (!(($option['type'] == 'open') || ($option['type'] == 'close') || ($option['type'] == 'displayonly'))) {
        if (isset($arrOptions[$option['id']])) $kippis_options[$option['id']] = $arrOptions[$option['id']];
        else $kippis_options[$option['id']] = $option['std'];  // New items.
      }
    }
  }
  return $kippis_options;
}}

if (!function_exists('kippis_get_options_upgrade_options')) {
function kippis_get_options_upgrade_options()
{
  //  Upgrade from 0.99.20, where options were stored one row per item in the wp_options table. Now it's a single row.
  global $wpdb;
  $data = $wpdb->get_results('select option_name,option_value from wp_options where option_name like "kippis_%" order by option_name','ARRAY_A');
  $istop = count($data);
  if ($istop > 0) {
    $arrOptions = array();
    for ($i = 0; $i < $istop; $i++) {
      if (($data[$i]['option_name'] == 'kippis_body_image') || ($data[$i]['option_name'] == 'kippis_header_image')) {
        $val = get_option($data[$i]['option_name']);
        $arrOptions[$data[$i]['option_name']] = array('url'    => $val['url'   ]
                                                     ,'file'   => $val['file'  ]
                                                     ,'width'  => $val['width' ]
                                                     ,'height' => $val['height']);
      }
      else $arrOptions[$data[$i]['option_name']] = $data[$i]['option_value'];
      delete_option($data[$i]['option_name']);
    }
    update_option('kippis',$arrOptions);
  }
}}

if (!function_exists('kippis_stylesheet_uri')) {
function kippis_stylesheet_uri()
{
  $stylesheet_uri = get_template_directory_uri() . "/style_mobile.css";
  return $stylesheet_uri;
}}

if (!function_exists('kippis_echo_css')) {
function kippis_echo_css()
{
  global $kippis_is_smartphone;
  global $kippis_options;
  global $kippis_sidebar_enable_left;
  global $kippis_sidebar_enable_right;
  global $kippis_sidebars_left;
  global $kippis_sidebars_right;
  $options_css = get_option('kippis_css');
  if (empty($options_css)) {
    include get_template_directory() . '/options/generate_css.php';
    kippis_update_options_css();
    $options_css = get_option('kippis_css');
  }
  echo '<style type="text/css">' . "\n";
  if (!$kippis_is_smartphone) {
    $width_left  = 0;
    $width_right = 0;
    if ($kippis_sidebar_enable_left ) $width_left  = (int)$kippis_options['kippis_sidebar_left_width' ];
    if ($kippis_sidebar_enable_right) $width_right = (int)$kippis_options['kippis_sidebar_right_width'];
    //  Some rudimentary sanity checks.
    if      ($width_left  <  0) $width_left  =  0;
    else if ($width_left  > 90) $width_left  = 30;
    if      ($width_right <  0) $width_right =  0;
    else if ($width_right > 90) $width_right = 30;
    if (($width_left + $width_right) > 80) {
      $width_left  = 30;
      $width_right = 30;
    }
    $width_content = 100 - $width_left - $width_right - 1;
    $kippis_sidebars_left  = $kippis_options['kippis_sidebars_position'] == 'left';
    $kippis_sidebars_right = $kippis_options['kippis_sidebars_position'] == 'right';
    $floater_right  = $kippis_sidebars_left ? 'left'  : 'right';
    $floater_middle = $kippis_sidebars_left ? 'right' : 'left';
    $floater_left   = 'left';
    if ($width_left  > 0) echo '#sidebar-left {float:' . $floater_left   . ';width:' . $width_left    . '%;}' . "\n";
                          echo '#content      {float:' . $floater_middle . ';width:' . $width_content . '%;}' . "\n";
    if ($width_right > 0) echo '#sidebar-right{float:' . $floater_right  . ';width:' . $width_right   . '%;}' . "\n";
    echo $options_css['screen'];
  }
  else echo $options_css['mobile'];
  echo '</style>' . "\n";
}}

if (!function_exists('kippis_admin_header_image')) {
function kippis_admin_header_image()
{
  ?>
  <div id="headimg">
    <?php
    if ('blank' == get_theme_mod('header_textcolor',HEADER_TEXTCOLOR) || '' == get_theme_mod('header_textcolor',HEADER_TEXTCOLOR)) {
      $style = ' style="display:none;"';
    }
    else $style = ' style="color:#' . get_theme_mod('header_textcolor',HEADER_TEXTCOLOR) . ';"';
    ?>
    <h1><a id="name"<?php echo $style; ?> onclick="return false;" href="<?php echo esc_url(home_url('/') ); ?>"><?php bloginfo('name'); ?></a></h1>
    <div id="desc"<?php echo $style; ?>><?php bloginfo('description'); ?></div>
    <?php $header_image = get_header_image();
    if (!empty($header_image)) : ?>
      <img src="<?php echo esc_url($header_image); ?>" alt="" />
    <?php endif; ?>
  </div>
  <?php
}}

if (!function_exists('kippis_adjust_admin_menu')) {
function kippis_adjust_admin_menu()
{
  //remove_submenu_page('themes.php','theme-editor.php');  // Irrelevant.
}}

//-----------------------------------------------------------------------------------------------------------------------------
//
//  Excerpt Begin
//
if (!function_exists('kippis_excerpt_length')) {
function kippis_excerpt_length($length)
{
  return KIPPIS_EXCERPT_LENGTH;
}}

if (!function_exists('kippis_continue_reading_link')) {
function kippis_continue_reading_link()
{
  return ' <span class="continue-reading"><a href="'. esc_url(get_permalink()) . '">' . __('Continue reading <span class="meta-nav">&rarr;</span>','kippis') . '</a></span>';
}}

if (!function_exists('kippis_auto_excerpt_more')) {
function kippis_auto_excerpt_more($more)
{
  return ' &hellip;' . kippis_continue_reading_link();
}}

if (!function_exists('kippis_custom_excerpt_more')) {
function kippis_custom_excerpt_more($output)
{
  if (has_excerpt() && !is_attachment()) {
    $output .= kippis_continue_reading_link();
  }
  return $output;
}}

add_filter('excerpt_length' ,'kippis_excerpt_length'     );
add_filter('excerpt_more'   ,'kippis_auto_excerpt_more'  );
add_filter('get_the_excerpt','kippis_custom_excerpt_more');
//
//  Excerpt End
//
//-----------------------------------------------------------------------------------------------------------------------------

if (!function_exists('kippis_page_menu_args')) {
function kippis_page_menu_args($args)
{
  $args['show_home'] = true;
  return $args;
}}
add_filter('wp_page_menu_args','kippis_page_menu_args');

if (!function_exists('kippis_content_nav')) {
function kippis_content_nav($nav_id)
{
  global $wp_query;
  if ($wp_query->max_num_pages > 1) {
    ?>
    <nav id="<?php echo $nav_id; ?>">
      <div class="nav-previous"><?php next_posts_link('<span class="meta-nav">&laquo; </span>' . __('Older posts','kippis')); ?></div>
      <div class="nav-next"><?php previous_posts_link(__('Newer posts','kippis') . '<span class="meta-nav"> &raquo;</span>'); ?></div>
    </nav><!-- #nav-above -->
    <?php
  }
}}

if (!function_exists('kippis_url_grabber')) {
function kippis_url_grabber()
{
  if (!preg_match('/<a\s[^>]*?href=[\'"](.+?)[\'"]/is',get_the_content(),$matches)) return false;
  return esc_url_raw($matches[1]);
}}

//-----------------------------------------------------------------------------------------------------------------------------
//
//  Sidebars Begin
//
if (!function_exists('kippis_enable_sidebars')) {
function kippis_enable_sidebars()
{
  global $kippis_options;
  global $kippis_sidebars_left;
  global $kippis_sidebars_right;
  global $kippis_sidebar_enable_left;
  global $kippis_sidebar_enable_right;

  $kippis_sidebars_left  = $kippis_options['kippis_sidebars_position'] == 'left';
  $kippis_sidebars_right = $kippis_options['kippis_sidebars_position'] == 'right';
  $kippis_sidebar_enable_left  = (($kippis_options['kippis_sidebar_left_enable' ] == 'on') & ($kippis_options['kippis_sidebar_left_width' ] > 0));
  $kippis_sidebar_enable_right = (($kippis_options['kippis_sidebar_right_enable'] == 'on') & ($kippis_options['kippis_sidebar_right_width'] > 0));
  if ($kippis_sidebar_enable_left || $kippis_sidebar_enable_right) {
    $bSingular   = is_singular();
    $post_format = get_post_format();
    $post_type   = get_post_type();
    $bGallery    = ($post_format == 'gallery') || ($post_type == 'attachment');
    $bPage       = get_post_type() == 'page';
    $bPost       = (!$bPage) && ( $bSingular);
    $bPosts      = (!$bPage) && (!$bSingular);
    if ($kippis_sidebar_enable_left) {
      if      ($bGallery) $kippis_sidebar_enable_left  = $kippis_options['kippis_sidebar_left_enable_gallery' ] == 'on';
      else if ($bPage   ) $kippis_sidebar_enable_left  = $kippis_options['kippis_sidebar_left_enable_page'    ] == 'on';
      else if ($bPost   ) $kippis_sidebar_enable_left  = $kippis_options['kippis_sidebar_left_enable_post'    ] == 'on';
      else if ($bPosts  ) $kippis_sidebar_enable_left  = $kippis_options['kippis_sidebar_left_enable_posts'   ] == 'on';
    }
    if ($kippis_sidebar_enable_right) {
      if      ($bGallery) $kippis_sidebar_enable_right = $kippis_options['kippis_sidebar_right_enable_gallery'] == 'on';
      else if ($bPage   ) $kippis_sidebar_enable_right = $kippis_options['kippis_sidebar_right_enable_page'   ] == 'on';
      else if ($bPost   ) $kippis_sidebar_enable_right = $kippis_options['kippis_sidebar_right_enable_post'   ] == 'on';
      else if ($bPosts  ) $kippis_sidebar_enable_right = $kippis_options['kippis_sidebar_right_enable_posts'  ] == 'on';
    }
    $sidebar_left_disable_slug  = !empty($kippis_options['kippis_sidebar_left_disable_slug' ]);
    $sidebar_right_disable_slug = !empty($kippis_options['kippis_sidebar_right_disable_slug']);
    $sidebar_disable_slug_found_it = false;
    if ($sidebar_left_disable_slug || $sidebar_right_disable_slug) {
      global $post;
      if ($post) {
        if ($sidebar_left_disable_slug) {
          $arr = preg_split('/[\s]+/',$kippis_options['kippis_sidebar_left_disable_slug']);
          if (in_array($post->post_name,$arr)) {
            $sidebar_disable_left = $sidebar_disable_slug_found_it = true;
          }
        }
        if ($sidebar_right_disable_slug) {
          $arr = preg_split('/[\s]+/',$kippis_options['kippis_sidebar_right_disable_slug']);
          if (in_array($post->post_name,$arr)) {
            $sidebar_disable_right = $sidebar_disable_slug_found_it = true;
          }
        }
        if ($sidebar_disable_slug_found_it) {
          $kippis_sidebar_enable_left = $kippis_sidebar_enable_right = true;
          $kippis_sidebar_enable_left  = !$sidebar_disable_left;
          $kippis_sidebar_enable_right = !$sidebar_disable_right;
        }
      }
    }
  }
}}

if (!function_exists('kippis_register_sidebar')) {
function kippis_register_sidebar($id,$name,$desc = '')
{
  register_sidebar(array('id'            => $id                                      // Sidebar id - Must be all in lowercase, with no spaces.
                        ,'name'          => $name                                    // Sidebar name.
                        ,'description'   => $desc                                    // Text description of what/where the sidebar is. Shown(?) on widget management screen.
                        ,'before_widget' => '<aside id="%1$s" class="widget %2$s">'  // HTML to place before every widget.  (%1$s=id  %2$s=class)
                        ,'after_widget'  => '</aside>'                               // HTML to place after every widget.
                        ,'before_title'  => '<h3 class="widget-title">'              // HTML to place before every title.
                        ,'after_title'   => '</h3>'                                  // HTML to place after every title.
                        ));

}}

if (!function_exists('kippis_widgets_init')) {
function kippis_widgets_init()
{
  kippis_register_sidebar('sidebar-left'        ,__('Left Sidebar'     ,'kippis'));
  kippis_register_sidebar('sidebar-right'       ,__('Right Sidebar'    ,'kippis'));
  kippis_register_sidebar('sidebar-footer-one'  ,__('Footer Area One'  ,'kippis'));
  kippis_register_sidebar('sidebar-footer-two'  ,__('Footer Area Two'  ,'kippis'));
  kippis_register_sidebar('sidebar-footer-three',__('Footer Area Three','kippis'));
  kippis_register_sidebar('sidebar-footer-four' ,__('Footer Area Four' ,'kippis'));
  register_widget('kippis_widget_post');
}}
add_action('widgets_init','kippis_widgets_init');
//
//  Sidebars End
//
//-----------------------------------------------------------------------------------------------------------------------------

if (!function_exists('kippis_add_image_sizes_to_editor')) {
function kippis_add_image_sizes_to_editor($sizes)
{
  $myimgsizes = array('pic-icon'       => __('Icon'     ,'kippis')
                     ,'post-thumbnail' => __('Thumbnail','kippis')
                     );
  $newimgsizes = array_merge($sizes,$myimgsizes);
  return $newimgsizes;
}}

if (!function_exists('kippis_strip_img_width')) {
function kippis_strip_img_width($html)
{
  return preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i','<$1$4$7>',$html);
}}

if (!function_exists('kippis_delete_comment_link')) {
function kippis_delete_comment_link($id)
{
  if (current_user_can('edit_post')) {
    echo ' | <a href="' . admin_url("comment.php?action=cdc&dt=spam&c=$id") . '">' . __('Spam'  ,'kippis') . '</a>';
    echo ' | <a href="' . admin_url("comment.php?action=cdc&c=$id")         . '">' . __('Delete','kippis') . '</a>';
  }
}}

//  Might come in handy.
//if (!function_exists('kippis_comments_form_before')) {
//function kippis_comments_form_before()
//{
//  //echo '<article><div class="article">';
//}}
//
//if (!function_exists('kippis_comments_form_after')) {
//function kippis_comments_form_after()
//{
//  //echo '</div></article>';
//}}
//add_action('comment_form_before','kippis_comments_form_before');
//add_action('comment_form_after' ,'kippis_comments_form_after' );

if (!function_exists('kippis_comment')) {
function kippis_comment($comment,$args,$depth)
{
  $GLOBALS['comment'] = $comment;
  switch ($comment->comment_type) :
    case 'pingback':
    case 'trackback':
  ?>
  <li class="post pingback">
    <p><?php _e('Pingback:','kippis'); ?> <?php comment_author_link(); ?> <?php edit_comment_link(__('Edit','kippis'),'<span class="edit-link">','</span>'); kippis_delete_comment_link(get_comment_ID()); ?></p>
  <?php
      break;
    default:
  ?>
  <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
    <div id="comment-<?php comment_ID(); ?>" class="article comment">
      <footer class="comment-meta">
        <div class="comment-author vcard">
          <?php
            $avatar_size = 68;
            if ('0' != $comment->comment_parent) $avatar_size = 39;
            echo get_avatar($comment,$avatar_size);
            /* translators: 1: comment author, 2: date and time */
            printf( __( '%1$s on %2$s <span class="says">said:</span>', 'kippis' ),
              sprintf('<span class="fn">%s</span>',get_comment_author_link()),
              sprintf('<a href="%1$s"><time pubdate datetime="%2$s">%3$s</time></a>'
                ,esc_url(get_comment_link($comment->comment_ID))
                ,get_comment_time( 'c' )
                ,sprintf(__('%1$s at %2$s','kippis'),get_comment_date(),get_comment_time())
              )
            );
          ?>
          <?php
          edit_comment_link(__('Edit','kippis'),' <span class="edit-link">','</span>');
          kippis_delete_comment_link(get_comment_ID());
          ?>
        </div><!-- .comment-author .vcard -->
        <?php if ( $comment->comment_approved == '0' ) : ?>
          <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'kippis' ); ?></em>
          <br />
        <?php endif; ?>
      </footer>
      <div class="comment-content"><?php comment_text(); ?></div>
      <div class="reply">
        <?php comment_reply_link(array_merge($args,array('reply_text' => __('Reply <span>&darr;</span>','kippis'),'depth' => $depth,'max_depth' => $args['max_depth']))); ?>
      </div><!-- .reply -->
    </div><!-- #comment-## -->
  <?php
      break;
  endswitch;
}}

if (!function_exists('kippis_encode_code_in_comment')) {
function kippis_encode_code_in_comment($src)
{
  // Escape html entities in comments.
  $encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims'
                                 ,create_function('$matches','$matches[1] = preg_replace(array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "", $matches[1]);
                                 return "<code>" . htmlentities($matches[1]) . "</"."code>";'),$src);
  if ($encoded) return $encoded;
  else          return $src;
}}
add_filter('pre_comment_content','kippis_encode_code_in_comment');

if (!function_exists('kippis_posted_on')) {
function kippis_posted_on()
{
  global $kippis_options;
  $show_author = $kippis_options['kippis_posts_author_enable'] == 'on';
  $show_date   = $kippis_options['kippis_posts_date_enable'  ] == 'on';
  if ($show_author || $show_date) {
    printf('<span class="sep">%1$s</span>'
         . '<a href="%2$s" title="%3$s" rel="bookmark"><time class="entry-date" datetime="%4$s" pubdate>%5$s</time></a>'
         . '<span class="by-author"> <span class="sep">%6$s</span> <span class="author vcard">'
         . '<a class="url fn n" href="%7$s" title="%8$s" rel="author">%9$s</a>'
         . '</span></span>'
      ,($show_date   ? __('Posted on','kippis') . ' '                                         : '')
      ,($show_date   ? esc_url (get_permalink())                                              : '')
      ,($show_date   ? esc_attr(get_the_time())                                               : '')
      ,($show_date   ? esc_attr(get_the_date('c'))                                            : '')
      ,($show_date   ? esc_html(get_the_date())                                               : '')
      ,($show_author ? ' ' . __('by','kippis') .' '                                           : '')
      ,($show_author ? esc_url (get_author_posts_url(get_the_author_meta('ID')))              : '')
      ,($show_author ? sprintf (esc_attr__('View all posts by %s','kippis'),get_the_author()) : '')
      ,($show_author ? esc_html(get_the_author())                                             : '')
    );
  }
}}

if (!function_exists('kippis_body_classes')) {
function kippis_body_classes($classes)
{
  if (!is_multi_author()) $classes[] = 'single-author';
  if ((is_singular()) && (!is_home()) && (!is_page_template('showcase.php')) && (!is_page_template('sidebar-page.php'))) $classes[] = 'singular';
  return $classes;
}}
add_filter('body_class','kippis_body_classes');

//-----------------------------------------------------------------------------------------------------------------------------
//
//  Compatibility with WP prior to 3.4 - Begin
//
if (!function_exists('wp_get_theme')) {
class kippis_old_wp_theme_data
{
  private $theme_data_version;
  private $theme_data_themeuri;
  private $theme_data_name;
  public function __construct()
  {
    $theme_data = get_theme_data(get_theme_root() . '/kippis/style.css');
    $this->theme_data_version  = $theme_data['Version'];
    $this->theme_data_themeuri = $theme_data['URI'    ];
    $this->theme_data_name     = $theme_data['Name'   ];
  }
  public function get($what)
  {
    switch ($what) {
      case 'Version' : return $this->theme_data_version;
      case 'ThemeURI': return $this->theme_data_themeuri;
      case 'Name'    : return $this->theme_data_name;
      default        : return '';
    }
  }
}
function wp_get_theme()
{
  return new kippis_old_wp_theme_data();
}}
//
//  Compatibility with WP prior to 3.4 - End
//
//-----------------------------------------------------------------------------------------------------------------------------

if (!function_exists('kippis_get_theme_data')) {
function kippis_get_theme_data()
{
  return wp_get_theme();
}}

if (!function_exists('kippis_credits')) {
function kippis_credits()
{
  $theme_data = kippis_get_theme_data();
  echo '<span style="font-family:Georgia,Times New Roman,Times,serif;font-size:12px;background-color:transparent;color:#555;">'
     . 'WordPress theme: '
     . '<a style="background-color:transparent;color:#559;" href="' . $theme_data->get('ThemeURI') . '" target="_blank" title="Get Kippis">' . $theme_data->get('Name') . ' ' . $theme_data->get('Version') . '</a>'
     . '</span>';

}}

if (!function_exists('kippis_is_smartphone')) {
function kippis_is_smartphone()
{
  global $kippis_is_smartphone;
  return $kippis_is_smartphone;
}}

