<?php
/*
functions.php
*/
global $next_pagenow;
global $smof_data;
//Theme Options
require_once get_template_directory() . "/admin/index.php";
// //Custom Post types
require_once get_template_directory() . "/admin/custom-post-types.php";
//Theme Stylesadmin
require_once get_template_directory() . "/admin/theme-styles.php";
//Theme scripts
require_once get_template_directory() . "/admin/theme-scripts.php";
//Theme scripts
require_once get_template_directory() . "/admin/text-menu.php";
//Theme scripts
require_once get_template_directory() . "/admin/icon-menu.php";
//Theme scripts
require_once get_template_directory() . "/admin/mobile-menu.php";

require_once(get_template_directory().'/admin/class-tgm-plugin-activation.php');


require_once(get_stylesheet_directory().'/admin/Custom-Meta-Boxes/custom-meta-boxes.php');
require_once(get_template_directory()."/admin/Custom-Meta-Boxes/metainit-functions.php");
/*---------------------------------------
---------Reason Initialiszation---------
-----------------------------------------*/
function next_setup() 
  {
        //Feed links
		add_theme_support( 'automatic-feed-links' );
		//Nav menu
		register_nav_menu( 'primary', __( 'Primary Menu','nextlang') );


        //Content width
		if (!isset( $content_width ) ) $content_width = 900;
		//Initiate custom post types
        add_action( 'init', 'next_post_types' );
        add_action( 'init', 'next_post_gallery' );
        add_action( 'init', 'next_services_type' );
        //Load the text domain
		load_theme_textdomain('nextlang', get_template_directory() . '/languages');
		//Post Thumbnails		
		add_theme_support( 'post-thumbnails', array('portfolio_item','services','gallery_item','post' ) );
        //Post formats
        add_theme_support(
			'post-formats', array(
				'image',
				'audio',
				'link',
				'quote',
				'video'
			)
		);

		set_post_thumbnail_size( 300, 300, true ); // Standard Size Thumbnails
		//Function to crop all thumbnails
		if(false === get_option("thumbnail_crop")) {
		add_option("thumbnail_crop", "1");
		} else {
		update_option("thumbnail_crop", "1");
		}	

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


/*---------------------------------------
--------Script and Style Enqueue---------
-----------------------------------------*/
    add_action('wp_enqueue_scripts', 'next_scripts');
    add_action('wp_enqueue_scripts', 'next_styles' );
    add_action('wp_enqueue_scripts', 'next_twitter_scripts' );
    add_action('wp_enqueue_scripts', 'next_sidehide_scripts');
    add_action('wp_enqueue_scripts', 'next_flicker_init');
    add_action('wp_enqueue_scripts', 'next_issingle');
    add_action('wp_enqueue_scripts', 'next_removeanimation');
    add_action('wp_enqueue_scripts', 'next_bgnd_slider');

    add_action( 'admin_enqueue_scripts', 'next_admin_only' );

    if(is_singular()): wp_enqueue_script( "comment-reply" ); endif;





/*---------------------------------------
--------Full Width Special-----------
-----------------------------------------*/
    //Desktop Menus
  if(isset($smof_data['menu_type'])):
  	$next_m_type = $smof_data['menu_type'];
  	if($next_m_type != 1)
  	{
       wp_enqueue_style("fullwidth", get_stylesheet_directory_uri(). "/stylesheets/full-width-layout-only.css"); 
  	}
  endif;

/*---------------------------------------
---------Format comment Callback-----------
-----------------------------------------*/

function next_format_comments($comment, $args, $depth) 
{
   $GLOBALS['comment'] = $comment; ?>
	<li <?php comment_class('commentlists'); ?>>
		<div id="comment-<?php comment_ID(); ?>" class=" clearfix cmntparent <?php
                        $authID = get_the_author_meta('ID');
                                                    
                        if($authID == $comment->user_id)
                           echo "cmntbyauthor";
                       else
                           echo "";
                        ?>">
			<div class="comment">


            				<div class="comment-author image-polaroid">
            					<?php 
                                $defimg = get_stylesheet_directory_uri(). "/images/avatar.png";
                                if(get_avatar($comment)):
                                	echo get_avatar($comment,$size='75');
                                else:
                                ?>
                                <img src="<?php echo $defimg; ?>"  alt="avatar" />
            					<?php endif; ?>
            				</div>
            				<div class="comment-body">
 										<div class="comment-meta">
											<span class="meta-name"><?php printf(__('%s','livelang'), get_comment_author_link()) ?></span>
											<span class="meta-date"> on <?php comment_time('F jS, Y'); ?></span>
											<div class="reply">
											<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
											<?php edit_comment_link(__('Edit','personalang'),'<span class="edit-comment">', '</span>'); ?>
										    </div>
									    </div>           					
                                <?php if ($comment->comment_approved == '0') : ?>
                   					<div class="alert-box success">
                      					<?php _e('Your comment is awaiting moderation.','personalang') ?>
                      				</div>
            					<?php endif; ?>
                                
                                <?php comment_text() ?>
                                
                                <!-- removing reply link on each comment since we're not nesting them -->
            					
                            </div>		
		</li>

<?php
}


/*---------------------------------------
-------Columns-----
-----------------------------------------*/
// GET FEATURED IMAGE
function next_ST4_get_featured_image($post_ID){
 $post_thumbnail_id = get_post_thumbnail_id($post_ID);
 if ($post_thumbnail_id){
  $post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id, 'featured_preview');
  return $post_thumbnail_img[0];
 }
}

// ADD NEW COLUMN
function next_ST4_columns_head($defaults) {
  $new = array();
  foreach($defaults as $key => $title) {
    if ($key=='title') // Put the Thumbnail column before the Author column
      $new['featured_image'] = 'Gallery Item';
    $new[$key] = $title;
  }
  return $new;


}

// SHOW INFO IN THE NEW COLUMN
function next_ST4_columns_content($column_name, $post_ID) {
 if ($column_name == 'featured_image') {
  $post_featured_image = next_ST4_get_featured_image($post_ID);
  if ($post_featured_image){
   echo '<img class="thumbnail" src="' . $post_featured_image . '" style="max-width:100px;" />'; 
  }
 }
}

add_filter('manage_gallery_item_posts_columns', 'next_ST4_columns_head');
add_filter('manage_gallery_item_posts_custom_column', 'next_ST4_columns_content', 1, 2);

function next_ST4_columns_content_with_default_image($column_name, $post_ID) {
 // Create a default.jpg image and save it in the images directory of your active theme.

 if ($column_name == 'featured_image') {
  $post_featured_image = next_ST4_get_featured_image($post_ID);
  if ($post_featured_image){
   // HAS A FEATURED IMAGE
   echo '<img src="' . $post_featured_image . '"  />';
   } else {
    // NO FEATURED IMAGE, USE THE DEFAULT ONE
    echo '<img src="' . get_template_directory_uri(). '/images/default.jpg" />'; 
   }
  }
}


//Pagination Code
function next_kriesi_pagination($pages = '', $range = 2)
{  
     $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 "<div class='pagination'>";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo;</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo;</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>&rsaquo;</a>";  
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>&raquo;</a>";
         echo "</div>\n";
     }
}

/*---------------------------------
Important Plugin Activation Check
-----------------------------------*/

/*---------------------------------
Important Plugin Activation Check
-----------------------------------*/
add_action( 'tgmpa_register', 'saga_register_required_plugins' );
/**
 * Register the required plugins for this theme.
 *
 * In this example, we register two plugins - one included with the TGMPA library
 * and one from the .org repo.
 *
 * The variable passed to tgmpa_register_plugins() should be an array of plugin
 * arrays.
 *
 * This function is hooked into tgmpa_init, which is fired within the
 * TGM_Plugin_Activation class constructor.
 */
function saga_register_required_plugins() {

  /**
   * Array of plugin arrays. Required keys are name and slug.
   * If the source is NOT from the .org repo, then source is also required.
   */
  $plugins = array(

    // This is an example of how to include a plugin pre-packaged with a theme
    array(
      'name'            => 'Designova Next Shortcodes', // The plugin name
      'slug'            => 'designova-next-shortcodes', // The plugin slug (typically the folder name)
      'source'          => get_stylesheet_directory() . '/lib/designova-next-shortcodes.zip', // The plugin source
      'required'        => true, // If false, the plugin is only 'recommended' instead of required
      'version'         => '2.1', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
      'force_activation'    => true, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
      'force_deactivation'  => true, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
      'external_url'      => '', // If set, overrides default API URL and points to an external URL
    ),

    // This is an example of how to include a plugin from the WordPress Plugin Repository
    array(
      'name'    => 'WP Retina 2x',
      'slug'    => 'wp-retina-2x',
      'required'  => true,
      'force_activation'    => false,
    ),

  );

  // Change this to your theme text domain, used for internationalising strings
  $theme_text_domain = 'nextlang';

  /**
   * Array of configuration settings. Amend each line as needed.
   * If you want the default strings to be available under your own theme domain,
   * leave the strings uncommented.
   * Some of the strings are added into a sprintf, so see the comments at the
   * end of each line for what each argument will be.
   */
  $config = array(
    'domain'          => $theme_text_domain,          // Text domain - likely want to be the same as your theme.
    'default_path'    => '',                          // Default absolute path to pre-packaged plugins
    'parent_menu_slug'  => 'themes.php',        // Default parent menu slug
    'parent_url_slug'   => 'themes.php',        // Default parent URL slug
    'menu'            => 'install-required-plugins',  // Menu slug
    'has_notices'       => true,                        // Show admin notices or not
    'is_automatic'      => false,             // Automatically activate plugins after installation or not
    'message'       => '',              // Message to output right before the plugins table
    'strings'         => array(
      'page_title'                            => __( 'Install Required Plugins', $theme_text_domain ),
      'menu_title'                            => __( 'Install Plugins', $theme_text_domain ),
      'installing'                            => __( 'Installing Plugin: %s', $theme_text_domain ), // %1$s = plugin name
      'oops'                                  => __( 'Something went wrong with the plugin API.', $theme_text_domain ),
      'notice_can_install_required'           => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.' ), // %1$s = plugin name(s)
      'notice_can_install_recommended'      => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.' ), // %1$s = plugin name(s)
      'notice_cannot_install'           => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.' ), // %1$s = plugin name(s)
      'notice_can_activate_required'          => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s)
      'notice_can_activate_recommended'     => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s)
      'notice_cannot_activate'          => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.' ), // %1$s = plugin name(s)
      'notice_ask_to_update'            => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.' ), // %1$s = plugin name(s)
      'notice_cannot_update'            => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.' ), // %1$s = plugin name(s)
      'install_link'                  => _n_noop( 'Begin installing plugin', 'Begin installing plugins' ),
      'activate_link'                 => _n_noop( 'Activate installed plugin', 'Activate installed plugins' ),
      'return'                                => __( 'Return to Required Plugins Installer', $theme_text_domain ),
      'plugin_activated'                      => __( 'Plugin activated successfully.', $theme_text_domain ),
      'complete'                  => __( 'All plugins installed and activated successfully. %s', $theme_text_domain ), // %1$s = dashboard link
      'nag_type'                  => 'updated' // Determines admin notice type - can only be 'updated' or 'error'
    )
  );

  tgmpa( $plugins, $config );

}

/*---------------------------------
Excerpt Length
-----------------------------------*/
function next_excerpt_length($length) {
	return 80;
}
add_filter( 'excerpt_length', 'next_excerpt_length', 999 );
function next_excerpt_more( $more ) {
	return '';
}
add_filter('excerpt_more', 'next_excerpt_more');

/*---------------------------------
Custom Styles
-----------------------------------*/
function next_my_styles_method() {
global $smof_data;
wp_enqueue_style('custom-style',get_template_directory_uri() . '/stylesheets/custom_css.css');

  $custom_css ="";
  //Custom CSS
  if(isset($smof_data['custom_css']) AND $smof_data['custom_css'] != ''):
   $custom_css .= $smof_data['custom_css'];
  else:
   $custom_css .= '';
  endif;
 wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'next_my_styles_method' );

/*---------------------------------
Custom Styles
-----------------------------------*/

add_filter('next_posts_link_attributes', 'next_posts_link_attributes');
add_filter('previous_posts_link_attributes', 'next_posts_link_attributes');
function next_posts_link_attributes() {
    return 'class="btn-next-alt"';
}