<?php
/**
 * Author: JoinWebs
 * URL: http://joinwebs.com
 *
 * Classiera functions and definitions
 *
 * Set up the theme and provides some helper functions, which are used in the
 * theme as custom template tags. Others are attached to action and filter
 * hooks in WordPress to change core functionality.
 *
 * @link https://codex.wordpress.org/Theme_Development
 * @package WordPress
 * @subpackage Classiera
 * @since Classiera 1.0
 */

/** Various clean up functions */
require get_template_directory() . '/library/cleanup.php';

/** Required for Foundation to work properly */

require get_template_directory() . '/library/foundation.php';

/** Register all navigation menus */
require get_template_directory() . '/library/navigation.php';

/** Add desktop menu walker */
require get_template_directory() . '/library/menu-walker.php';

/** Add off-canvas menu walker */
require get_template_directory() . '/library/offcanvas-walker.php';

/** Return entry meta information for posts */
require get_template_directory() . '/library/entry-meta.php';

/** Add Header image */
require get_template_directory() . '/library/custom-header.php';

/****************************************
*****************************************
*******ClassiERA Functions Start*********
*****************************************
*****************************************
 ****************************************/
 add_action( 'after_setup_theme', 'classiera_theme_setup' );


function classiera_theme_setup() {

    add_theme_support( 'woocommerce' );

    add_theme_support( 'custom-background' );

    /**
     * Adds post custom meta.
     */
    require get_template_directory() . '/inc/post_meta.php';

    // Add Page Meta Fields
    require get_template_directory() . '/inc/page_meta.php';

    // Add Colors
    require get_template_directory() . '/inc/colors.php';
    require get_template_directory() . '/inc/package_manage.php';


    // Add Widgets
    require get_template_directory() . '/inc/widgets/recent_posts_widget.php';	
    require get_template_directory() . '/inc/widgets/twitter_widget.php';	
    require get_template_directory() . '/inc/widgets/categories.php';	
	require get_template_directory() . '/inc/widgets/social_widget.php';
	require get_template_directory() . '/inc/widgets/advance_search.php';
	require get_template_directory() . '/inc/widgets/blog-categories.php';
	require get_template_directory() . '/inc/widgets/recent-blog-post.php';

    /**
     * Sets up the content width value based on the theme's design.
     * @see classiera_content_width() for template-specific adjustments.
     */
    if ( ! isset( $content_width ) )
        $content_width = 1060;

    /**
     * Classiera only works in WordPress 4.3 or later.
     */
    if ( version_compare( $GLOBALS['wp_version'], '4.3-alpha', '<' ) )
        require get_template_directory() . '/inc/back-compat.php';

    /**
     * Sets up theme defaults and registers the various WordPress features that
     * ClassiEra supports.
     *
     * @uses load_theme_textdomain() For translation/localization support.
     * @uses add_editor_style() To add Visual Editor stylesheets.
     * @uses add_theme_support() To add support for automatic feed links, post
     * formats, and post thumbnails.
     * @uses register_nav_menu() To add support for a navigation menu.
     * @uses set_post_thumbnail_size() To set a custom post thumbnail size.
     *
     * @since ClassiEra 1.0
     *
     * @return void
    */

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

	/*
	 * This theme styles the visual editor to resemble the theme style,
	 * specifically font, colors, icons, and column width.
	 */
	add_editor_style( array( 'css/editor-style.css', 'fonts/genericons.css', classiera_fonts_url() ) );

	// Adds RSS feed links to <head> for posts and comments.
	add_theme_support( 'automatic-feed-links' );

	// Switches 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' ) );

	// This theme uses wp_nav_menu() in one location.
	//register_nav_menu( 'primary', esc_html__( 'Navigation Menu', 'classiera' ) );

	/*
	 * This theme uses a custom image size for featured images, displayed on
	 * "standard" posts and pages.
	 */
	add_theme_support( 'post-thumbnails' );
	set_post_thumbnail_size( 440, 266, true );
	add_image_size( 'classiera-grid', 370, 300, true );
	add_image_size( 'classiera-list', 270, 250, true );
	add_image_size( 'classiera-pslider', 400, 250, true );
	add_image_size( 'classiera-single', 770, 480, true );
	add_image_size( 'classiera-full', 960, 540, true );
	add_image_size( 'classiera-premium', 86, 86, true );
	add_image_size( 'classiera-recentpost', 70, 70, true );
	add_image_size( 'classiera-myads', 80, 80, true );	
	add_image_size( 'classiera-vsecond', 270, 180, true );

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

    // Disable Disqus commehts on woocommerce product //
    add_filter( 'woocommerce_product_tabs', 'disqus_override_tabs', 98);

    // Custom admin scripts
    add_action('admin_enqueue_scripts', 'classiera_admin_scripts' );

    // Author add new contact details
    add_filter('user_contactmethods','classiera_author_new_contact',10,1);

    // Lost Password and Login Error
    add_action( 'wp_login_failed', 'classiera_front_end_login_fail' );  // hook failed login

    
    // Load scripts and styles
    add_action( 'wp_enqueue_scripts', 'classiera_scripts_styles' );

    // Add custom metas
    add_action( 'add_meta_boxes', 'classiera_add_posts_metaboxes' );

    // Save custom posts
    add_action('save_post', 'classiera_save_post_meta', 1, 2); // save the custom fields

    // Category new fields (the form)
    add_filter('add_category_form', 'classiera_my_category_fields');
    add_filter('edit_category_form', 'classiera_my_category_fields');

    // Update category fields
    add_action( 'edited_category', 'classiera_update_my_category_fields', 10, 2 );  
    add_action( 'create_category', 'classiera_update_my_category_fields', 10, 2 );

    //Include the TGM_Plugin_Activation class.    
	require_once get_template_directory() . '/inc/class-tgm-plugin-activation.php';
    add_action( 'tgmpa_register', 'classiera_register_required_plugins' );

    // Google analitycs code
    add_action( 'wp_enqueue_scripts', 'classiera_google_analityc_code' );

    // Enqueue main font
    add_action( 'wp_enqueue_scripts', 'classiera_main_font' );

    // Enqueue main font
    add_action( 'wp_enqueue_scripts', 'classiera_second_font_armata' );

    // Track views
    add_action( 'wp_head', 'classiera_track_post_views');

    // Theme page titles
    add_filter( 'wp_title', 'classiera_wp_title', 10, 2 );


    // classiera sidebars spot
    add_action( 'widgets_init', 'classiera_widgets_init' );

    // classiera body class
    add_filter( 'body_class', 'classiera_body_class' );

    // classiera content width
    add_action( 'template_redirect', 'classiera_content_width' );

    // classiera customize register
    add_action( 'customize_register', 'classiera_customize_register' );

    // classiera customize preview
    add_action( 'customize_preview_init', 'classiera_customize_preview_js' );

    /* Add theme support for automatic feed links. */   
    add_theme_support( 'automatic-feed-links' );

}
/*-----------------------------------------------------------------------------------*/
/*	Register and load admin styles
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'classiera_admin_styles' ) ){
    function classiera_admin_styles($hook){
        wp_register_style( 'classiera-admin-styles', get_template_directory_uri() . '/css/classiera-admin-styles.css' );
        wp_enqueue_style('classiera-admin-styles');
    }
}
add_action('admin_enqueue_scripts','classiera_admin_styles');

// Disable Disqus comments on woocommerce product //
function disqus_override_tabs($tabs){
    if ( has_filter( 'comments_template', 'dsq_comments_template' ) ){
        remove_filter( 'comments_template', 'dsq_comments_template' );
        add_filter('comments_template', 'dsq_comments_template',90);//higher priority, so the filter is called after woocommerce filter
    }
    return $tabs;
}

// Custom admin scripts
function classiera_admin_scripts() {
	wp_enqueue_media();
}


// Author add new contact details
function classiera_author_new_contact( $contactmethods ) {

	// Add telephone
	$contactmethods['phone'] = esc_html__( 'Phone', 'classiera');
	$contactmethods['phone2'] = esc_html__( 'Mobile', 'classiera');	
	// add address
	$contactmethods['address'] = esc_html__( 'Address', 'classiera');	
	// add social
	$contactmethods['facebook'] = esc_html__( 'Facebook', 'classiera');
	$contactmethods['twitter'] = esc_html__( 'Twitter', 'classiera');
	$contactmethods['googleplus'] = esc_html__( 'Google Plus', 'classiera');
	$contactmethods['linkedin'] = esc_html__( 'Linkedin', 'classiera');
	$contactmethods['pinterest'] = esc_html__( 'Pinterest', 'classiera');
	$contactmethods['instagram'] = esc_html__( 'Instagram', 'classiera');
 
	return $contactmethods;
	
}


// Add user price plan info
function classiera_save_extra_profile_fields( $user_id ) {
	update_user_meta( $user_id, 'price_plan' );
	add_user_meta( $user_id, 'price_plan_id' );
}



// Lost Password and Login Error
function classiera_front_end_login_fail( $username ) {
   $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
   // if there's a valid referrer, and it's not the default log-in screen
   if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') && $user!=null ) {
      	wp_redirect( $referrer . '?login=failed' );  // let's append some information (login=failed) to the URL for the theme to use
      	exit;
   } elseif ( is_wp_error($user_verify) )  {
   		wp_redirect( $referrer . '?login=failed-user' );  // let's append some information (login=failed) to the URL for the theme to use
      	exit;
   }
}
// End


// Insert attachments front end
function classiera_insert_attachment($file_handler,$post_id,$setthumb='false') {

  // check to make sure its a successful upload
  if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');

  $attach_id = media_handle_upload( $file_handler, $post_id );

  if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
  return $attach_id;
}

/*--------------------------------------*/
/*          Custom Post Meta           */
/*--------------------------------------*/
// Add the Post Meta Boxes
function classiera_add_posts_metaboxes() {
	//add_meta_box('classiera_featured_post', 'Featured Post', 'classiera_featured_post', 'post', 'side', 'default');
}

// Show The Post On Slider Option
function classiera_featured_post() {
	global $post;
	
	// Noncename needed to verify where the data originated
	echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' . 
	wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
	
	// Get the location data if its already been entered
	$featured_post = get_post_meta($post->ID, 'featured_post', true);
	
	// Echo out the field
	echo '<span class="text overall" style="margin-right: 20px;">Check to have this as featured post:</span>';
	
	$checked = get_post_meta($post->ID, 'featured_post', true) == '1' ? "checked" : "";
	
	echo '<input type="checkbox" name="featured_post" id="featured_post" value="1" '. $checked .'/>';

}

// Save the Metabox Data
function classiera_save_post_meta($post_id, $post) {
	
	// verify this came from the our screen and with proper authorization,
	// because save_post can be triggered at other times
	if ( !wp_verify_nonce( isset( $_POST['eventmeta_noncename'] ) ? $_POST['eventmeta_noncename'] : '', plugin_basename(__FILE__) )) {
	return $post->ID;
	}

	// Is the user allowed to edit the post or page?
	if ( !current_user_can( 'edit_post', $post->ID ))
		return $post->ID;

	// OK, we're authenticated: we need to find and save the data
	// We'll put it into an array to make it easier to loop though.
	
	$events_meta['featured_post'] = $_POST['featured_post'];
	
	$chk = ( isset( $_POST['featured_post'] ) && $_POST['featured_post'] ) ? '1' : '2';
	update_post_meta( $post_id, 'featured_post', $chk );
	
	// Add values of $events_meta as custom fields
	foreach ($events_meta as $key => $value) { // Cycle through the $events_meta array!
		if( $post->post_type == 'post' ) return; // Don't store custom data twice
		$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
		if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
			update_post_meta($post->ID, $key, $value);
		} else { // If the custom field doesn't have a value
			add_post_meta($post->ID, $key, $value);
		}
		if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
	}

}
/* End */




/**
 * Returns the Google font stylesheet URL, if available.
 *
 * The use of Source Sans Pro and Bitter by default is localized. For languages
 * that use characters not supported by the font, the font can be disabled.
 *
 * @since classiera 1.0
 *
 * @return string Font stylesheet or empty string if disabled.
 */
function classiera_fonts_url() {
	$fonts_url = '';

	/* Translators: If there are characters in your language that are not
	 * supported by Source Sans Pro, translate this to 'off'. Do not translate
	 * into your own language.
	 */
	$source_sans_pro = _x( 'on', 'Source Sans Pro font: on or off', 'classiera' );

	/* Translators: If there are characters in your language that are not
	 * supported by Bitter, translate this to 'off'. Do not translate into your
	 * own language.
	 */
	$bitter = _x( 'on', 'Bitter font: on or off', 'classiera' );

	if ( 'off' !== $source_sans_pro || 'off' !== $bitter ) {
		$font_families = array();

		if ( 'off' !== $source_sans_pro )
			$font_families[] = 'Montserrat:400,700,400italic,700italic';

		if ( 'off' !== $bitter )
			$font_families[] = 'Lato:400,700';

		$query_args = array(
			'family' => urlencode( implode( '%7C', $font_families ) ),
			'subset' => urlencode( 'latin,latin-ext' ),
		);
		$fonts_url = esc_url( add_query_arg( $query_args, "//fonts.googleapis.com/css" ) ) ;
	}

	return $fonts_url;
}

//////////////////////////////////////////////////////////////////
//// function to display extra info on category admin
//////////////////////////////////////////////////////////////////
// the option name
define('MY_CATEGORY_FIELDS', 'my_category_fields_option');

// your fields (the form)
function classiera_my_category_fields($tag) {
    $tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
	$category_icon_code = isset( $tag_extra_fields[$tag->term_id]['category_icon_code'] ) ? esc_attr( $tag_extra_fields[$tag->term_id]['category_icon_code'] ) : '';
	$category_image = isset( $tag_extra_fields[$tag->term_id]['category_image'] ) ? esc_attr( $tag_extra_fields[$tag->term_id]['category_image'] ) : '';
    $category_icon_color = isset( $tag_extra_fields[$tag->term_id]['category_icon_color'] ) ? esc_attr( $tag_extra_fields[$tag->term_id]['category_icon_color'] ) : '';
    $your_image_url = isset( $tag_extra_fields[$tag->term_id]['your_image_url'] ) ? esc_attr( $tag_extra_fields[$tag->term_id]['your_image_url'] ) : '';
    ?>

<div class="form-field">	
<table class="form-table">
        <tr class="form-field">
        	<th scope="row" valign="top"><label for="category-page-slider"><?php esc_html_e( 'Icon Code', 'classiera' ); ?></label></th>
        	<td>

				<input id="category_icon_code" type="text" size="36" name="category_icon_code" value="<?php $category_icon = stripslashes($category_icon_code); echo esc_attr($category_icon); ?>" />
                <p class="description"><?php esc_html_e( 'AwesomeFont code', 'classiera' ); ?>: <a href="http://fontawesome.io/icons/" target="_blank">fontawesome.io/icons</a> Ex: fa fa-desktop</p>

			</td>
        </tr>
		<tr class="form-field">
            <th scope="row" valign="top"><label for="category-page-slider"><?php esc_html_e( 'Category Image', 'classiera' ); ?>&nbsp;Size:370x200px:</label></th>
            <td>
            <?php 

            if(!empty($category_image)) {

                echo '<div style="width: 100%; float: left;"><img id="category_image_img" src="'. $category_image .'" style="float: left; margin-bottom: 20px;" /> </div>';
                echo '<input id="category_image" type="text" size="36" name="category_image" style="max-width: 200px; float: left; margin-top: 10px; display: none;" value="'.$category_image.'" />';
                echo '<input id="category_image_button_remove" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px;" value="Remove" /> </br>';
                echo '<input id="category_image_button" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px; display: none;" value="Upload Image" /> </br>'; 

            } else {

                echo '<div style="width: 100%; float: left;"><img id="category_image_img" src="'. $category_image .'" style="float: left; margin-bottom: 20px;" /> </div>';
                echo '<input id="category_image" type="text" size="36" name="category_image" style="max-width: 200px; float: left; margin-top: 10px; display: none;" value="'.$category_image.'" />';
                echo '<input id="category_image_button_remove" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px; display: none;" value="Remove" /> </br>';
                echo '<input id="category_image_button" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px;" value="Upload Image" /> </br>';

            }

            ?>
            </td>
			
            <script>
            var image_custom_uploader;
            jQuery('#category_image_button').click(function(e) {
                e.preventDefault();

                //If the uploader object has already been created, reopen the dialog
                if (image_custom_uploader) {
                    image_custom_uploader.open();
                    return;
                }

                //Extend the wp.media object
                image_custom_uploader = wp.media.frames.file_frame = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: false
                });

                //When a file is selected, grab the URL and set it as the text field's value
                image_custom_uploader.on('select', function() {
                    attachment = image_custom_uploader.state().get('selection').first().toJSON();
                    var url = '';
                    url = attachment['url'];
                    jQuery('#category_image').val(url);
                    jQuery( "img#category_image_img" ).attr({
                        src: url
                    });
                    jQuery("#category_image_button").css("display", "none");
                    jQuery("#category_image_button_remove").css("display", "block");
                });

                //Open the uploader dialog
                image_custom_uploader.open();
             });

             jQuery('#category_image_button_remove').click(function(e) {
                jQuery('#category_image').val('');
                jQuery( "img#category_image_img" ).attr({
                    src: ''
                });
                jQuery("#category_image_button").css("display", "block");
                jQuery("#category_image_button_remove").css("display", "none");
             });
            </script>
        </tr>
        <tr class="form-field">
            <th scope="row" valign="top"><label for="category-page-slider"><?php esc_html_e( 'Icon Background Color', 'classiera' ); ?></label></th>
            <td>

                <link rel="stylesheet" media="screen" type="text/css" href="<?php echo get_template_directory_uri() ?>/inc/color-picker/css/colorpicker.css" />
                <script type="text/javascript" src="<?php echo get_template_directory_uri() ?>/inc/color-picker/js/colorpicker.js"></script>
                <script type="text/javascript">
                jQuery.noConflict();
                jQuery(document).ready(function(){
                    jQuery('#colorpickerHolder').ColorPicker({color: '<?php echo $category_icon_color; ?>', flat: true, onChange: function (hsb, hex, rgb) { jQuery('#category_icon_color').val('#' + hex); }});
                });
                </script>

                <p id="colorpickerHolder"></p>

                <input id="category_icon_color" type="text" size="36" name="category_icon_color" value="<?php echo $category_icon_color; ?>" style="margin-top: 20px; max-width: 90px; visibility: hidden;" />

            </td>
        </tr>
        <tr class="form-field">
            <th scope="row" valign="top"><label for="category-page-slider"><?php esc_html_e( 'Map Pin', 'classiera' ); ?>&nbsp;Size:70x70px:</label></th>
            <td>
            <?php 

            if(!empty($your_image_url)) {

                echo '<div style="width: 100%; float: left;"><img id="your_image_url_img" src="'. $your_image_url .'" style="float: left; margin-bottom: 20px;" /> </div>';
                echo '<input id="your_image_url" type="text" size="36" name="your_image_url" style="max-width: 200px; float: left; margin-top: 10px; display: none;" value="'.$your_image_url.'" />';
                echo '<input id="your_image_url_button_remove" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px;" value="Remove" /> </br>';
                echo '<input id="your_image_url_button" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px; display: none;" value="Upload Image" /> </br>'; 

            } else {

                echo '<div style="width: 100%; float: left;"><img id="your_image_url_img" src="'. $your_image_url .'" style="float: left; margin-bottom: 20px;" /> </div>';
                echo '<input id="your_image_url" type="text" size="36" name="your_image_url" style="max-width: 200px; float: left; margin-top: 10px; display: none;" value="'.$your_image_url.'" />';
                echo '<input id="your_image_url_button_remove" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px; display: none;" value="Remove" /> </br>';
                echo '<input id="your_image_url_button" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px;" value="Upload Image" /> </br>';

            }

            ?>
            </td>

            <script>
            var image_custom_uploader;
            jQuery('#your_image_url_button').click(function(e) {
                e.preventDefault();

                //If the uploader object has already been created, reopen the dialog
                if (image_custom_uploader) {
                    image_custom_uploader.open();
                    return;
                }

                //Extend the wp.media object
                image_custom_uploader = wp.media.frames.file_frame = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: false
                });

                //When a file is selected, grab the URL and set it as the text field's value
                image_custom_uploader.on('select', function() {
                    attachment = image_custom_uploader.state().get('selection').first().toJSON();
                    var url = '';
                    url = attachment['url'];
                    jQuery('#your_image_url').val(url);
                    jQuery( "img#your_image_url_img" ).attr({
                        src: url
                    });
                    jQuery("#your_image_url_button").css("display", "none");
                    jQuery("#your_image_url_button_remove").css("display", "block");
                });

                //Open the uploader dialog
                image_custom_uploader.open();
             });

             jQuery('#your_image_url_button_remove').click(function(e) {
                jQuery('#your_image_url').val('');
                jQuery( "img#your_image_url_img" ).attr({
                    src: ''
                });
                jQuery("#your_image_url_button").css("display", "block");
                jQuery("#your_image_url_button_remove").css("display", "none");
             });
            </script>
        </tr>
</table>
</div>

    <?php
}


// when the form gets submitted, and the category gets updated (in your case the option will get updated with the values of your custom fields above
function classiera_update_my_category_fields($term_id) {
if(isset($_POST['taxonomy'])){	
  if($_POST['taxonomy'] == 'category'):
    $tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
    $tag_extra_fields[$term_id]['your_image_url'] = strip_tags($_POST['your_image_url']);
	$tag_extra_fields[$term_id]['category_image'] = $_POST['category_image'];
    $tag_extra_fields[$term_id]['category_icon_code'] = $_POST['category_icon_code'];
    $tag_extra_fields[$term_id]['category_icon_color'] = $_POST['category_icon_color'];
    update_option(MY_CATEGORY_FIELDS, $tag_extra_fields);
  endif;
}
}


// when a category is removed
add_filter('deleted_term_taxonomy', 'classiera_remove_my_category_fields');
function classiera_remove_my_category_fields($term_id) {
if(isset($_POST['taxonomy'])){		
  if($_POST['taxonomy'] == 'category'):
    $tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
    unset($tag_extra_fields[$term_id]);
    update_option(MY_CATEGORY_FIELDS, $tag_extra_fields);
  endif;
} 
}




/**
 * 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 classiera_register_required_plugins() {
 
    /**
     * Array of plugin arrays. Required keys are name, slug and required.
     * If the source is NOT from the .org repo, then source is also required.
     */
    $plugins = array(
	
		// Redux Framework
        array(            
			'name' => esc_html__( 'Redux Framework', 'classiera' ),
            'slug' => 'redux-framework',
            'required' => true,
            'force_activation' => false,
            'force_deactivation' => false
        ),

    	// Facebook Connect
        array(
            'name' => 'Nextend Facebook Connect',
            'slug' => 'nextend-facebook-connect',
            'required' => false,
            'force_activation' => false,
            'force_deactivation' => false
        ),

        // Twitter Connect
        array(
            'name' => 'Nextend Twitter Connect',
            'slug' => 'nextend-twitter-connect',
            'required' => false,
            'force_activation' => false,
            'force_deactivation' => false
        ),

        // Google Connect
        array(
            'name' => 'Nextend Google Connect',
            'slug' => 'nextend-google-connect',
            'required' => false,
            'force_activation' => false,
            'force_deactivation' => false
        ),
    
        // Layer SLider
        array(
            'name' => 'LayerSlider WP',
            'slug' => 'LayerSlider',
            'source' => get_template_directory() . '/inc/plugins/LayerSlider.zip',
            'required' => false,
            'version' => '6.1.6',
            'force_activation' => false,
            'force_deactivation' => false
        ),
		// Classiera Helper
        array(
            'name' => 'Classiera Helper',
            'slug' => 'ClassieraHelper',
            'source' => get_template_directory() . '/inc/plugins/ClassieraHelper.zip',
            'required' => false,
            'version' => '1.1',
            'force_activation' => false,
            'force_deactivation' => false
        ),
		// Classiera Locations
        array(
            'name' => 'Classiera Locations',
            'slug' => 'classiera-locations',
            'source' => get_template_directory() . '/inc/plugins/classiera-locations.zip',
            'required' => false,
            'version' => '1.0',
            'force_activation' => false,
            'force_deactivation' => false
        ),

        // Ratings
        array(
            'name' => 'WP-PostRatings',
            'slug' => 'wp-postratings',            
            'required' => false,            
            'force_activation' => false,
            'force_deactivation' => false
        ), 
		
		// Newsletter
        array(
            'name' => 'Newsletter',
            'slug' => 'newsletter',            
            'required' => false,            
            'force_activation' => false,
            'force_deactivation' => false
        ),
 
    );
 
    // Change this to your theme text domain, used for internationalising strings
    $theme_text_domain = 'wpcrown';
 
    /**
     * 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'            => 'wpcrown',           // 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', 'tgmpa' ),
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
				'notice_can_install_required'     => _n_noop(
					'This theme requires the following plugin: %1$s.',
					'This theme requires the following plugins: %1$s.',
					'tgmpa'
				),
				'notice_can_install_recommended'  => _n_noop(
					'This theme recommends the following plugin: %1$s.',
					'This theme recommends the following plugins: %1$s.',
					'tgmpa'
				),
				'notice_cannot_install'           => _n_noop(
					'Sorry, but you do not have the correct permissions to install the %1$s plugin.',
					'Sorry, but you do not have the correct permissions to install the %1$s plugins.',
					'tgmpa'
				),
				'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.',
					'tgmpa'
				),
				'notice_ask_to_update_maybe'      => _n_noop(
					'There is an update available for: %1$s.',
					'There are updates available for the following plugins: %1$s.',
					'tgmpa'
				),
				'notice_cannot_update'            => _n_noop(
					'Sorry, but you do not have the correct permissions to update the %1$s plugin.',
					'Sorry, but you do not have the correct permissions to update the %1$s plugins.',
					'tgmpa'
				),
				'notice_can_activate_required'    => _n_noop(
					'The following required plugin is currently inactive: %1$s.',
					'The following required plugins are currently inactive: %1$s.',
					'tgmpa'
				),
				'notice_can_activate_recommended' => _n_noop(
					'The following recommended plugin is currently inactive: %1$s.',
					'The following recommended plugins are currently inactive: %1$s.',
					'tgmpa'
				),
				'notice_cannot_activate'          => _n_noop(
					'Sorry, but you do not have the correct permissions to activate the %1$s plugin.',
					'Sorry, but you do not have the correct permissions to activate the %1$s plugins.',
					'tgmpa'
				),
				'install_link'                    => _n_noop(
					'Begin installing plugin',
					'Begin installing plugins',
					'tgmpa'
				),
				'update_link'                     => _n_noop(
					'Begin updating plugin',
					'Begin updating plugins',
					'tgmpa'
				),
				'activate_link'                   => _n_noop(
					'Begin activating plugin',
					'Begin activating plugins',
					'tgmpa'
				),
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
				'dashboard'                       => __( 'Return to the dashboard', 'tgmpa' ),
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
        )
    );
 
    tgmpa( $plugins, $config );
 
}



/**
* Google analytic code
*/
function classiera_google_analityc_code() { ?>

	<script type="text/javascript">

	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', '<?php global $redux_demo; $google_id = $redux_demo['google_id']; echo $google_id; ?>']);
	_gaq.push(['_setDomainName', 'none']);
	_gaq.push(['_setAllowLinker', true]);
	_gaq.push(['_trackPageview']);

	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();

</script>
	
<?php }



/**
 * Enqueues scripts and styles for front end.
 *
 * @since classiera 1.0
 *
 * @return void
 */
function classiera_scripts_styles() {
	//Load Script
	wp_register_script('classiera-theme', get_template_directory_uri() . '/js/theme.js', 'jquery', '', true);	
	
	wp_register_script('jquery.matchHeight', get_template_directory_uri() . '/js/jquery.matchHeight.js', 'jquery', '', true);
	
	wp_register_script('classiera-theme-rtl', get_template_directory_uri() . '/js/theme-rtl.js', 'jquery', '', true);
	
	wp_register_script('classiera-owl-carousel-min', get_template_directory_uri() . '/js/owl.carousel.min.js', 'jquery', '', true);
	
	wp_register_script('classiera-liMarquee', get_template_directory_uri() . '/js/jquery.liMarquee.js', 'jquery', '', true);
	
	wp_register_script('classiera-rrssb', get_template_directory_uri() . '/js/rrssb.min.js', 'jquery', '', true);
	
	wp_register_script('classiera-numscroller', get_template_directory_uri() . '/js/numscroller-1.0.js', 'jquery', '', true);	
	
	wp_register_script('classiera-app', get_template_directory_uri() . '/js/app.js', 'jquery', '', true);
	
	wp_register_script('classiera-foundation', get_template_directory_uri() . '/js/foundation.min.js', 'jquery', '', true);
	
	wp_register_script('classiera-modernizr', get_template_directory_uri() . '/js/modernizr.js', 'jquery', '', true);
	
	wp_register_script('classiera-infinitescroll', get_template_directory_uri() . '/js/infinitescroll.js', 'jquery', '', true);
	
	wp_register_script('classiera-MultiFile', get_template_directory_uri() . '/js/jquery.MultiFile.js', 'jquery', '', true);
	
	wp_register_script('chosenjquery', get_template_directory_uri() . '/js/chosen.jquery.min.js', 'jquery', '', true);
	
	wp_enqueue_script( 'classiera-modernizr' );
	wp_enqueue_script( 'jquery.matchHeight' );
	wp_enqueue_script( 'classiera-foundation' );
	wp_enqueue_script( 'classiera-owl-carousel-min' );
	wp_enqueue_script( 'classiera-liMarquee' );
	wp_enqueue_script( 'classiera-rrssb' );
	wp_enqueue_script( 'classiera-numscroller' );
	wp_enqueue_script( 'classiera-infinitescroll' );
	wp_enqueue_script( 'classiera-MultiFile' );
	

	if(is_rtl()){
		wp_enqueue_script( 'classiera-theme-rtl' );
	}else{
		wp_enqueue_script( 'classiera-theme' );
	}
	wp_enqueue_script( 'classiera-app' );
	wp_enqueue_script( 'chosenjquery' );
	
	
	
	
	
	// Adds JavaScript to pages with the comment form to support sites with
	// threaded comments (when in use).
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) )
		wp_enqueue_script( 'comment-reply' );

	// Adds Masonry to handle vertical alignment of footer widgets.
	if ( is_active_sidebar( 'sidebar-1' ) )
		wp_enqueue_script( 'jquery-masonry' );

	

	// Add Open Sans and Bitter fonts, used in the main stylesheet.
	wp_enqueue_style( 'classiera-fonts', classiera_fonts_url(), array(), null );

	// Add Genericons font, used in the main stylesheet.
	wp_enqueue_style( 'genericons', get_template_directory_uri() . '/fonts/genericons.css', array(), '2.09' );
   
	// Load google maps js
    global $redux_demo;
	$googleApiKey = $redux_demo['classiera_google_api'];
	
    wp_enqueue_script( 'classiera-google-maps-script', 'https://maps.googleapis.com/maps/api/js?key='.$googleApiKey.'&v=3.exp', array( 'jquery' ), '2014-07-18', true );

    // Load google maps js
    wp_enqueue_script( 'classiera-google-maps-script2', get_template_directory_uri() . '/js/gmap3.min.js', array( 'jquery' ), '2014-07-18', true );

    // Load google maps js
    wp_enqueue_script( 'classiera-google-maps-infobox', get_template_directory_uri() . '/js/gmap3.infobox.js', array( 'jquery' ), '2014-07-18', true );
	
	// Load jQuery UI script
	wp_enqueue_script( 'classiera-jquery-ui-script', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js', array( 'jquery' ), '2014-07-18', true );
	
	// Load jQuery tools forms script
	wp_enqueue_script( 'classiera-jquery-tools-forms-script', get_template_directory_uri() . '/js/jquery.tools.min.js', array( 'jquery' ), '2014-07-18', true );	
	

    if( is_page_template('template-add-post.php') ) {
        /* add javascript */
        wp_enqueue_script( 'classiera-google-custom-script', get_template_directory_uri() . '/js/getlocation-map-script.js', array( 'jquery' ), '2014-07-18', true );
    }

    // Load google maps js
    wp_enqueue_script( 'classiera-modernizer', get_template_directory_uri() . '/js/modernizr.touch.js', array( 'jquery' ), '2014-07-18', true );

    // Load google maps js
    wp_enqueue_script( 'classiera-slider-mobile', get_template_directory_uri() . '/js/jquery.ui.touch-punch.min.js', array( 'jquery' ), '2014-07-18', true );


	if( is_single() ) {
        // Load flexslider
        wp_enqueue_script( 'classiera-flexslider-script', get_template_directory_uri() . '/js/jquery.flexslider.js', array( 'jquery' ), '2014-07-18', true );
        
	}

    // Load awesomefont style
    wp_enqueue_style( 'font-awesome.min', get_template_directory_uri() . '/css/font-awesome.min.css', array(), '1' );  
     
    
// Load CSS 

if(is_rtl()){
	wp_enqueue_style( 'foundation-rtl', get_template_directory_uri() . '/css/foundation-rtl-min.css', array(), '1' );
}else{
	wp_enqueue_style( 'app-foundation', get_template_directory_uri() . '/css/foundation.css', array(), '1' );
}

wp_enqueue_style( 'app-ltr', get_template_directory_uri() . '/css/app-ltr.css', array(), '1' );

wp_enqueue_style( 'liMarquee', get_template_directory_uri() . '/css/liMarquee.css', array(), '1' );
wp_enqueue_style( 'owl.carousel', get_template_directory_uri() . '/css/owl.carousel.css', array(), '1' );
wp_enqueue_style( 'owl.theme.default', get_template_directory_uri() . '/css/owl.theme.default.css', array(), '1' );
wp_enqueue_style( 'chosen', get_template_directory_uri() . '/css/chosen.css', array(), '1' );
// Load responsive
    wp_enqueue_style( 'style-responsive', get_template_directory_uri() . '/css/responsive.css', array(), '1' );
// END CSS From HASSAN

	if(is_admin_bar_showing()) echo "<style type=\"text/css\">.navbar-fixed-top { margin-top: 28px; } </style>";

}
add_image_size( 'classiera_premium-post-image', 400, 280, true );
add_image_size( 'classiera_single-post-image', 300, 300, true );
add_image_size( 'classiera_single-cat-image', 255, 218, true );
add_image_size( '270x220', 270, 220, true );
function classiera_main_font() {
    $protocol = is_ssl() ? 'https' : 'http';
    //wp_enqueue_style( 'mytheme-roboto', "$protocol://fonts.googleapis.com/css?family=Roboto:400,400italic,500,300,300italic,500italic,700,700italic" );
}



function classiera_second_font_armata() {
    $protocol = is_ssl() ? 'https' : 'http';
    //wp_enqueue_style( 'mytheme-armata', "$protocol://fonts.googleapis.com/css?family=Armata" );
}


// Post views
function classiera_set_post_views($postID) {
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
//To keep the count accurate, lets get rid of prefetching


function classiera_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    classiera_set_post_views($post_id);
}


function classiera_get_post_views($postID){
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0";
    }
    return $count;
}




/**
 * Creates a nicely formatted and more specific title element text for output
 * in head of document, based on current view.
 *
 * @since classiera 1.0
 *
 * @param string $title Default title text for current view.
 * @param string $sep Optional separator.
 * @return string The filtered title.
 */
function classiera_wp_title( $title, $sep ) {
	global $paged, $page;

	if ( is_feed() )
		return $title;

	// Add the site name.
	$title .= get_bloginfo( 'name' );

	// Add the site description for the home/front page.
	$site_description = get_bloginfo( 'description', 'display' );
	if ( $site_description && ( is_home() || is_front_page() ) )
		$title = "$title $sep $site_description";

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

	return $title;
}


/**
 * Registers two widget areas.
 *
 * @since classiera 1.0
 *
 * @return void
 */
function classiera_widgets_init() {
	register_sidebar( array(
		'name'          => esc_html__( 'Footer Widget ', 'classiera' ),
		'id'            => 'footer-one',
		'description'   => esc_html__( 'Appears in the footer section of the site.', 'classiera' ),
		'before_widget' => '<div class="large-3 medium-6 columns"><div class="widgetBox">',
		'after_widget'  => '</div></div>',
		'before_title'  => '<div class="widgetTitle"><h4>',
		'after_title'   => '</h4></div>',
	) );

    register_sidebar( array(
        'name'          => esc_html__( 'Forum Widget Area', 'classiera' ),
        'id'            => 'forum',
        'description'   => esc_html__( 'Appears on posts and pages in the sidebar.', 'classiera' ),
        'before_widget' => '<div class="cat-widget"><div class="cat-widget-content">',
        'after_widget'  => '</div></div>',
        'before_title'  => '<div class="cat-widget-title"><h4>',
        'after_title'   => '</h4></div>',
    ) );	
	
	register_sidebar( array(
		'name'          => esc_html__( 'Pages Sidebar', 'classiera' ),
		'id'            => 'pages',
		'description'   => esc_html__( 'Appears on posts and pages in the sidebar.', 'classiera' ),
		'before_widget' => '<div class="large-12 medium-6 columns medium-centered"><div class="widgetBox">',
		'after_widget'  => '</div></div>',
		'before_title'  => '<h4>',
		'after_title'   => '</h4>',
	) ); 
	
	register_sidebar( array(
		'name'          => esc_html__( 'Listing HomPage Sidebar', 'classiera' ),
		'id'            => 'listing',
		'description'   => esc_html__( 'Appears on HomePage Listing Sidebar.', 'classiera' ),
		'before_widget' => '<div class="large-12 medium-6 columns medium-centered"><div class="widgetBox">',
		'after_widget'  => '</div></div>',
		'before_title'  => '<h4>',
		'after_title'   => '</h4>',
	) );
	
	register_sidebar( array(
		'name'          => esc_html__( 'Blog Sidebar', 'classiera' ),
		'id'            => 'blog',
		'description'   => esc_html__( 'Appears on Blog sidebar.', 'classiera' ),
		'before_widget' => '<div class="large-12 medium-6 columns medium-centered"><div class="widgetBox">',
		'after_widget'  => '</div></div>',
		'before_title'  => '<h4>',
		'after_title'   => '</h4>',
	) );

    
}

if ( ! function_exists( 'classiera_paging_nav' ) ) :
/**
 * Displays navigation to next/previous set of posts when applicable.
 *
 * @since classiera 1.0
 *
 * @return void
 */
function classiera_paging_nav() {
	global $wp_query;

	// Don't print empty markup if there's only one page.
	if ( $wp_query->max_num_pages < 2 )
		return;
	?>
	<nav class="navigation paging-navigation" role="navigation">
		<h1 class="screen-reader-text"><?php esc_html_e( 'Posts navigation', 'classiera' ); ?></h1>
		<div class="nav-links">

			<?php if ( get_next_posts_link() ) : ?>
			<div class="nav-previous"><?php next_posts_link(wp_kses( __( '<span class="meta-nav">&larr;</span> Older posts', 'classiera' ), $allowed ) ); ?></div>
			<?php endif; ?>

			<?php if ( get_previous_posts_link() ) : ?>
			<div class="nav-next"><?php previous_posts_link(wp_kses( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'classiera' ), $allowed ) ); ?></div>
			<?php endif; ?>

		</div><!-- .nav-links -->
	</nav><!-- .navigation -->
	<?php
}
endif;

if ( ! function_exists( 'classiera_post_nav' ) ) :
/**
 * Displays navigation to next/previous post when applicable.
*
* @since classiera 1.0
*
* @return void
*/
function classiera_post_nav() {
	global $post;

	// Don't print empty markup if there's nowhere to navigate.
	$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
	$next     = get_adjacent_post( false, '', false );

	if ( ! $next && ! $previous )
		return;
	?>
	<nav class="navigation post-navigation" role="navigation">
		<h1 class="screen-reader-text"><?php esc_html_e( 'Post navigation', 'classiera' ); ?></h1>
		<div class="nav-links">

			<?php previous_post_link( '%link', _x( '<span class="meta-nav">&larr;</span> %title', 'Previous post link', 'classiera' ) ); ?>
			<?php next_post_link( '%link', _x( '%title <span class="meta-nav">&rarr;</span>', 'Next post link', 'classiera' ) ); ?>

		</div><!-- .nav-links -->
	</nav><!-- .navigation -->
	<?php
}
endif;

if ( ! function_exists( 'classiera_entry_meta' ) ) :
/**
 * Prints HTML with meta information for current post: categories, tags, permalink, author, and date.
 *
 * Create your own classiera_entry_meta() to override in a child theme.
 *
 * @since classiera 1.0
 *
 * @return void
 */
function classiera_entry_meta() {
	if ( is_sticky() && is_home() && ! is_paged() )
		echo '<span class="featured-post">' . esc_html_e( 'Sticky', 'classiera' ) . '</span>';

	if ( ! has_post_format( 'link' ) && 'post' == get_post_type() )
		classiera_entry_date();

	// Translators: used between list items, there is a space after the comma.
	$categories_list = get_the_category_list( esc_html_e( ',', 'classiera' ) );
	if ( $categories_list ) {
		echo '<span class="categories-links">' . $categories_list . '</span>';
	}

	// Translators: used between list items, there is a space after the comma.
	$tag_list = get_the_tag_list( '', esc_html_e( ',', 'classiera' ) );
	if ( $tag_list ) {
		echo '<span class="tags-links">' . $tag_list . '</span>';
	}

	// Post author
	if ( 'post' == get_post_type() ) {
		printf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>',
			esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
			esc_attr( sprintf( __( 'View all posts by %s', 'classiera' ), get_the_author() ) ),
			get_the_author()
		);
	}
}
endif;

if ( ! function_exists( 'classiera_entry_date' ) ) :
/**
 * Prints HTML with date information for current post.
 *
 * Create your own classiera_entry_date() to override in a child theme.
 *
 * @since classiera 1.0
 *
 * @param boolean $echo Whether to echo the date. Default true.
 * @return string The HTML-formatted post date.
 */
function classiera_entry_date( $echo = true ) {
	if ( has_post_format( array( 'chat', 'status' ) ) )
		$format_prefix = _x( '%1$s on %2$s', '1: post format name. 2: date', 'classiera' );
	else
		$format_prefix = '%2$s';

	$date = sprintf( '<span class="date"><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a></span>',
		esc_url( get_permalink() ),
		esc_attr( sprintf( __( 'Permalink to %s', 'classiera' ), the_title_attribute( 'echo=0' ) ) ),
		esc_attr( get_the_date( 'c' ) ),
		esc_html( sprintf( $format_prefix, get_post_format_string( get_post_format() ), get_the_date() ) )
	);

	if ( $echo )
		echo $date;

	return $date;
}
endif;

if ( ! function_exists( 'classiera_the_attached_image' ) ) :
/**
 * Prints the attached image with a link to the next attached image.
 *
 * @since classiera 1.0
 *
 * @return void
 */
function classiera_the_attached_image() {
	$post                = get_post();
	$attachment_size     = apply_filters( 'classiera_attachment_size', array( 724, 724 ) );
	$next_attachment_url = wp_get_attachment_url();

	/**
	 * Grab the IDs of all the image attachments in a gallery so we can get the URL
	 * of the next adjacent image in a gallery, or the first image (if we're
	 * looking at the last image in a gallery), or, in a gallery of one, just the
	 * link to that image file.
	 */
	$attachment_ids = get_posts( array(
		'post_parent'    => $post->post_parent,
		'fields'         => 'ids',
		'numberposts'    => -1,
		'post_status'    => 'inherit',
		'post_type'      => 'attachment',
		'post_mime_type' => 'image',
		'order'          => 'ASC',
		'orderby'        => 'menu_order ID'
	) );

	// If there is more than 1 attachment in a gallery...
	if ( count( $attachment_ids ) > 1 ) {
		foreach ( $attachment_ids as $attachment_id ) {
			if ( $attachment_id == $post->ID ) {
				$next_id = current( $attachment_ids );
				break;
			}
		}

		// get the URL of the next image attachment...
		if ( $next_id )
			$next_attachment_url = get_attachment_link( $next_id );

		// or get the URL of the first image attachment.
		else
			$next_attachment_url = get_attachment_link( array_shift( $attachment_ids ) );
	}

	printf( '<a href="%1$s" title="%2$s" rel="attachment">%3$s</a>',
		esc_url( $next_attachment_url ),
		the_title_attribute( array( 'echo' => false ) ),
		wp_get_attachment_image( $post->ID, $attachment_size )
	);
}
endif;

/**
 * Returns the URL from the post.
 *
 * @uses get_url_in_content() to get the URL in the post meta (if it exists) or
 * the first link found in the post content.
 *
 * Falls back to the post permalink if no URL is found in the post.
 *
 * @since classiera 1.0
 *
 * @return string The Link format URL.
 */
function classiera_get_link_url() {
	$content = get_the_content();
	$has_url = get_url_in_content( $content );

	return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}

/**
 * Extends the default WordPress body classes.
 *
 * Adds body classes to denote:
 * 1. Single or multiple authors.
 * 2. Active widgets in the sidebar to change the layout and spacing.
 * 3. When avatars are disabled in discussion settings.
 *
 * @since classiera 1.0
 *
 * @param array $classes A list of existing body class values.
 * @return array The filtered body class list.
 */
function classiera_body_class( $classes ) {
	if ( ! is_multi_author() )
		$classes[] = 'single-author';

	if ( is_active_sidebar( 'sidebar-2' ) && ! is_attachment() && ! is_404() )
		$classes[] = 'sidebar';

	if ( ! get_option( 'show_avatars' ) )
		$classes[] = 'no-avatars';

	return $classes;
}


/**
 * Adjusts content_width value for video post formats and attachment templates.
 *
 * @since classiera 1.0
 *
 * @return void
 */
function classiera_content_width() {
	global $content_width;

	if ( is_attachment() )
		$content_width = 724;
	elseif ( has_post_format( 'audio' ) )
		$content_width = 484;
}

/**
 * Add postMessage support for site title and description for the Customizer.
 *
 * @since classiera 1.0
 *
 * @param WP_Customize_Manager $wp_customize Customizer object.
 * @return void
 */
function classiera_customize_register( $wp_customize ) {
	$wp_customize->get_setting( 'blogname' )->transport         = 'postMessage';
	$wp_customize->get_setting( 'blogdescription' )->transport  = 'postMessage';
	$wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage';
}


/**
 * Binds JavaScript handlers to make Customizer preview reload changes
 * asynchronously.
 *
 * @since classiera 1.0
 */
function classiera_customize_preview_js() {
	wp_enqueue_script( 'classiera-customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'customize-preview' ), '20130226', true );
}

// Add Redux Framework
require_once( get_template_directory() . '/ReduxFramework/theme-options.php' );
/*if ( !isset( $redux_demo ) && file_exists( get_template_directory() . '/ReduxFramework/theme-options.php' ) ) {
	require_once( get_template_directory() . '/ReduxFramework/theme-options.php' );
}*/

/*---------------------------------------------------
register categories custom fields page
----------------------------------------------------*/
add_action( 'admin_init', 'classiera_theme_settings_init' );
function classiera_theme_settings_init(){
  register_setting( 'theme_settings', 'theme_settings' );
  wp_enqueue_style("panel_style", get_template_directory_uri()."/css/categories-custom-fields.css", false, "1.0", "all");
  wp_enqueue_script("panel_script", get_template_directory_uri()."/js/categories-custom-fields-script.js", false, "1.0");
}
 
/*---------------------------------------------------
add categories custom fields page to menu
----------------------------------------------------*/
function classiera_add_settings_page() { 
 add_theme_page('Categories Custom Fields', 'Categories Custom Fields', 'manage_options', 'settings', 'classiera_theme_settings_page'); 
}
add_action( 'admin_menu', 'classiera_add_settings_page' );
/*---------------------------------------------------
Theme Panel Output
----------------------------------------------------*/
function classiera_theme_settings_page() {
  global $themename,$theme_options;
	$i = 0;
    $message = ''; 

    if ( 'savecat' == $_REQUEST['action'] ) {
		
		//print_r($_POST);exit();
        $args = array(
			  'orderby' => 'name',
			  'order' => 'ASC',
			  'hide_empty' => false
		);
		$categories = get_categories($args);
		foreach($categories as $category) {
			$user_id = $category->term_id;
            $tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
		    $tag_extra_fields[$user_id]['category_custom_fields'] = $_POST['wpcrown_category_custom_field_option_'.$user_id];
			$tag_extra_fields[$user_id]['category_custom_fields_type'] = $_POST['wpcrown_category_custom_field_type_'.$user_id];			
		    update_option(MY_CATEGORY_FIELDS, $tag_extra_fields);
        }
        $message='saved';
    }
     ?>

    <div class="wrap">
      <div id="icon-options-general"></div>
      <h2><?php esc_html_e('Categories Custom Fields', 'classiera') ?></h2>
      <?php
        if ( $message == 'saved' ) echo '<div class="updated settings-error" id="setting-error-settings_updated"> 
        <p>Custom Fields saved.</strong></p></div>';
      ?>
    </div>

    <form method="post">

    <div class="wrap">
      <h3><?php esc_html_e('Select category:', 'classiera') ?></h3>

        <select id="select-author">
          	<?php 

	          	$cat_args = array ( 'parent' => 0, 'hide_empty' => false, 'orderby' => 'name','order' => 'ASC' ) ;
	        	$parentcategories = get_categories($cat_args ) ;
	        	$no_of_categories = count ( $parentcategories ) ;
					
			    if ( $no_of_categories > 0 ) {
					echo '<option value="All" selected disabled>'.esc_html__('Select Category', 'classiera')."</option>";
			        foreach ( $parentcategories as $parentcategory ) {
			           
			        echo '<option value=' . $parentcategory->term_id . '>' . $parentcategory->name . '</option>';
			 
			                $parent_id = $parentcategory ->term_id;
			                $subcategories = get_categories(array ( 'child_of' => $parent_id, 'hide_empty' => false ) ) ;
			 
			            foreach ( $subcategories as $subcategory ) { 
			 
			                $args = array (
			                    'post-type'=> 'questions',
			                    'orderby'=> 'name',
			                    'order'=> 'ASC',
			                    'post_per_page'=> -1,
			                    'nopaging'=> 'true',
			                    'taxonomy_name'=> $subcategory->name
			                ); 
			                 
			                echo '<option value=' . $subcategory->term_id . '> - ' . $subcategory->name . '</option>';
			            
			            } 
			        }
			    } 
        ?>
        </select>
		<p>NOTE: <br/> Text fields will display as input type=text,<br/> Checkbox Will show as features and input type=checkbox,<br/> Dropdown will display as < select >, <br/>Add options for dropdown with comma sepration like  option1,option2,option3</p>
    </div>

    <div class="wrap">
      	<?php
        	$args = array(
        	  'hide_empty' => false,
			  'orderby' => 'name',
			  'order' => 'ASC'
			);

			$inum = 0;

			$categories = get_categories($args);
			  	foreach($categories as $category) {;

			  	$inum++;

          		$user_name = $category->name;
          		$user_id = $category->term_id; 


          		$tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
				$wpcrown_category_custom_field_option = $tag_extra_fields[$user_id]['category_custom_fields'];
				$wpcrown_category_custom_field_type = $tag_extra_fields[$user_id]['category_custom_fields_type'];
          ?>

          <div id="author-<?php echo $user_id; ?>" class="wrap-content" <?php if($inum == 1) { ?>style="display: block;"<?php } else { ?>style="display: none;"<?php } ?>>

            <h4><?php esc_html_e('Add Custom Fields to: ', 'classiera') ?><?php echo $user_name; ?></h4>
	
            <div id="badge_criteria_<?php echo $user_id; ?>">
				<table class="maintable">
					<tr class="custcathead">
						<th class="eratd"><span class="text ingredient-title"><?php esc_html_e( 'Custom field title', 'classiera' ); ?></span></th>
						<th class="eratd2"><span class="text ingredient-title"><?php esc_html_e( 'Input Type:', 'classiera' ); ?></span></th>
						<th class="eratd3"></th>
						<th class="eratd4"><span class="text ingredient-title"><?php esc_html_e( 'Delete', 'classiera' ); ?></span></th>
					</tr>
				</table>
              <?php 
                for ($i = 0; $i < (count($wpcrown_category_custom_field_option)); $i++) {
					//echo $wpcrown_category_custom_field_option."shabir";
              ?>
				<div class="badge_item" id="<?php echo $i; ?>">
					<table class="maintable" >
						<tr>  
							<td class="eratd">
								<input type='text' id='wpcrown_category_custom_field_option_<?php echo $user_id ?>[<?php echo $i; ?>][0]' name='wpcrown_category_custom_field_option_<?php echo $user_id ?>[<?php echo $i; ?>][0]' value='<?php if (!empty($wpcrown_category_custom_field_option[$i][0])) echo $wpcrown_category_custom_field_option[$i][0]; ?>' class='badge_name' placeholder='Add Title for Field'>
							</td>
							<td class="eratd2">
								<input class='field_type_<?php echo $user_id; ?>' type="radio" name="wpcrown_category_custom_field_type_<?php echo $user_id ?>[<?php echo $i; ?>][1]"
									<?php if (!empty($wpcrown_category_custom_field_type[$i][1]) && $wpcrown_category_custom_field_type[$i][1] == "text") echo "checked";?>
									value="text" >Text Field<br />
									<input class='field_type_<?php echo $user_id; ?>' type="radio" name="wpcrown_category_custom_field_type_<?php echo $user_id ?>[<?php echo $i; ?>][1]"
									<?php if (!empty($wpcrown_category_custom_field_type[$i][1]) && $wpcrown_category_custom_field_type[$i][1] == "checkbox") echo "checked";?>
									value="checkbox">Checkbox<br />
									<input class='field_type_<?php echo $user_id; ?>' type="radio" name="wpcrown_category_custom_field_type_<?php echo $user_id ?>[<?php echo $i; ?>][1]"
									<?php if (!empty($wpcrown_category_custom_field_type[$i][1]) && $wpcrown_category_custom_field_type[$i][1] == "dropdown") echo "checked";?>
									value="dropdown">Dropdown<br />
							</td>
							<?php
									$none = 'style="display:none"';
									if (!empty($wpcrown_category_custom_field_type[$i][1]) && $wpcrown_category_custom_field_type[$i][1] == "dropdown"){ 
										$none = '';
									}
								?>
							<td class="eratd3">
								
									<input <?php echo $none; ?> type='text' id='option_<?php echo $user_id ?>' name="wpcrown_category_custom_field_type_<?php echo $user_id ?>[<?php echo $i; ?>][2]" value='<?php echo $wpcrown_category_custom_field_type[$i][2]; ?>' class='options_c options_c_<?php echo $user_id; ?>' placeholder="Add Options with Comma , separated Example: One,Two,Three">

							</td>
							<td class="eratd4">
								<button name="button_del_badge" type="button" class="button-secondary button_del_badge_<?php echo $user_id; ?>">Delete</button>
							</td>
						</tr>  
					</table>
				</div>
              
              <?php 
                }
              ?>
            </div>

            <div id="template_badge_criterion_<?php echo $user_id; ?>" style="display: none;">
              
				<div class="badge_item" id="999">
					<table class="maintable">
						<tr>  
							<td class="eratd">
							  <input type='text' id='' name='' value='' class='badge_name' placeholder='Add Title for Field'>
							</td>
							<td class="eratd2">
								<input checked="cheched" type="radio" name="" value="text" class='field_type field_type_<?php echo $user_id; ?>'>Text Field<br />
								<input type="radio" name="" value="checkbox" class='field_type field_type_<?php echo $user_id; ?>'>Checkbox<br />
								<input type="radio" name="" value="dropdown" class='field_type field_type_<?php echo $user_id; ?>'>Dropdown<br />
							</td>
							<td class="eratd3">
								 <input style="display:none"  type='text' id='option_<?php echo $user_id ?>' name='' value='' class='options_c options_c_<?php echo $user_id; ?>' placeholder="Add Options with Comma , separated Example: One,Two,Three">
							</td>
							<td class="eratd4">
								<button name="button_del_badge" type="button" class="button-secondary button_del_badge_<?php echo $user_id; ?>">Delete</button>
								 
							</td>
						</tr>
					</table>
				</div>
            </div>
			<table class="maintable">
				<tr class="custcathead">
					<th class="eratd"><span class="text ingredient-title"><?php esc_html_e( 'Custom field title', 'classiera' ); ?></span></th>
					<th class="eratd2"><span class="text ingredient-title"><?php esc_html_e( 'Input Type:', 'classiera' ); ?></span></th>
					<th class="eratd3"></th>
					<th class="eratd4"><span class="text ingredient-title"><?php esc_html_e( 'Delete', 'classiera' ); ?></span></th>
				</tr>
			</table>
            <fieldset class="input-full-width">
              <button type="button" name="submit_add_badge" id='submit_add_badge_<?php echo $user_id; ?>' value="add" class="button-secondary">Add new custom field</button>
            </fieldset>
            <span class="submit"><input name="save<?php echo $user_id; ?>" type="submit" class="button-primary" value="Save changes" /></span>

            <script>

              // Add Badge

              jQuery('#template_badge_criterion_<?php echo $user_id; ?>').hide();
              jQuery('#submit_add_badge_<?php echo $user_id; ?>').on('click', function() {    
                $newItem = jQuery('#template_badge_criterion_<?php echo $user_id; ?> .badge_item').clone().appendTo('#badge_criteria_<?php echo $user_id; ?>').show();
                if ($newItem.prev('.badge_item').size() == 1) {
                  var id = parseInt($newItem.prev('.badge_item').attr('id')) + 1;
                } else {
                  var id = 0; 
                }
                $newItem.attr('id', id);

                var nameText = 'wpcrown_category_custom_field_option_<?php echo $user_id; ?>[' + id + '][0]';
                $newItem.find('.badge_name').attr('id', nameText).attr('name', nameText);
				
				var nameText2 = 'wpcrown_category_custom_field_type_<?php echo $user_id; ?>[' + id + '][1]';
							$newItem.find('.field_type').attr('id', nameText2).attr('name', nameText2);
							
				var nameText3 = 'wpcrown_category_custom_field_type_<?php echo $user_id; ?>[' + id + '][2]';
							$newItem.find('.options_c').attr('name', nameText3);

                //event handler for newly created element
                jQuery('.button_del_badge_<?php echo $user_id; ?>').on('click', function () {
                  jQuery(this).closest('.badge_item').remove();
                });

              });
              
              // Delete Ingredient
              jQuery('.button_del_badge_<?php echo $user_id; ?>').on('click', function() {
                jQuery(this).closest('.badge_item').remove();
              });

				// Delete Ingredient
			   jQuery( document ).ready(function() {
					jQuery(document).on('click', '.field_type_<?php echo $user_id; ?>', function(e) {
					var val = jQuery(this).val();
						if(val == 'dropdown'){
							jQuery(this).parent().next('td').find('#option_<?php echo $user_id ?>').css('display','block');
						}else{
							jQuery(this).parent().next('td').find('#option_<?php echo $user_id ?>').css('display','none');
						}
					});
				});
            </script>
          </div>
      <?php } ?>
    </div>

  <input type="hidden" name="action" value="savecat" />
  </form>

  <?php
}

function classiera_the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();

	if ( $length && is_numeric($length) ) {
		$title = substr( $title, 0, $length );
	}

	if ( strlen($title)> 0 ) {
		$title = apply_filters('classiera_the_titlesmall', $before . $title . $after, $before, $after);
		if ( $echo )
			echo $title;
		else
			return $title;
	}
}
add_action('template_redirect', 'classiera_add_scripts');
 
function classiera_add_scripts() {
    if (is_singular()) {
      add_thickbox(); 
    }
}
//Register tag cloud filter callback
add_filter('widget_tag_cloud_args', 'classiera_tag_widget_limit');
 
//Limit number of tags inside widget
function classiera_tag_widget_limit($args){
global $redux_demo;
 $tagsnumber= $redux_demo['tags_limit']; 
//Check if taxonomy option inside widget is set to tags
if(isset($args['taxonomy']) && $args['taxonomy'] == 'post_tag'){
  $args['number'] = $tagsnumber; //Limit number of tags
}
 
return $args;
}

function classiera_get_attachment_id_from_src($image_src) {

    global $wpdb;
    $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
    $id = $wpdb->get_var($query);
    return $id;

}


function classiera_add_media_upload_scripts() {
    if ( is_admin() ) {
         return;
       }
    wp_enqueue_media();
}
add_action('wp_enqueue_scripts', 'classiera_add_media_upload_scripts');

function classiera_get_avatar_url($author_id, $size){
    $get_avatar = get_avatar( $author_id, $size );
	$matches = array();     
   preg_match('/(?<!_)src=([\'"])?(.*?)\\1/',$get_avatar, $matches);	
    return ( $matches[2] );
}



function classiera_allow_users_uploads() {
	$contributor = get_role('contributor');
	$contributor->add_cap('upload_files');
	$contributor->add_cap('delete_published_posts');
	
	$subscriber = get_role('subscriber');
	$subscriber->add_cap('upload_files');
	$subscriber->add_cap('delete_published_posts');

}
add_action('admin_init', 'classiera_allow_users_uploads');


if ( current_user_can('subscriber') || current_user_can('contributor') && !current_user_can('upload_files') ) {
    add_action('admin_init', 'classiera_allow_contributor_uploads');
}
function classiera_allow_contributor_uploads() {	
	$contributor = get_role('contributor');
	$contributor->add_cap('upload_files');
	
    $subscriber = get_role('subscriber');
    $subscriber->add_cap('upload_files');	
}


add_filter( 'posts_where', 'classiera_devplus_attachments_wpquery_where' );
function classiera_devplus_attachments_wpquery_where( $where ){
    global $current_user;
	if ( !current_user_can( 'administrator' ) ) {
		if( is_user_logged_in() ){
			// we spreken over een ingelogde user
			if( isset( $_POST['action'] ) ){
				// library query
				if( $_POST['action'] == 'query-attachments' ){
					$where .= ' AND post_author='.$current_user->data->ID;
				}
			}
		}
	}
    return $where;
}

add_action('after_setup_theme', 'classiera_remove_admin_bar');
function classiera_remove_admin_bar() {
	if (!current_user_can('administrator') && !is_admin()) {
	  show_admin_bar(false);
	}
}

add_action( 'wp', 'classiera_ad_expiry_schedule' );
/**
 * On an early action hook, check if the hook is scheduled - if not, schedule it.
 */
function classiera_ad_expiry_schedule() {
	if ( ! wp_next_scheduled( 'classiera_ad_expiry_event' ) ) {
		wp_schedule_event( time(), 'hourly', 'classiera_ad_expiry_event');
	}
}


add_action( 'classiera_ad_expiry_event', 'classiera_ad_expiry' );
/**
 * On the scheduled action hook, run a function.
 */
function classiera_ad_expiry() {
global $wpdb;
global $redux_demo;
$daystogo = '';
if (!empty($redux_demo['ad_expiry'])){
	$daystogo = $redux_demo['ad_expiry'];	
	$sql =
	"UPDATE {$wpdb->posts}
	SET post_status = 'trash'
	WHERE (post_type = 'post' AND post_status = 'publish')
	AND DATEDIFF(NOW(), post_date) > %d";
	$wpdb->query($wpdb->prepare( $sql, $daystogo ));
}
}

add_action( 'after_setup_theme', 'classiera_admin_featuredPlan' );
function classiera_admin_featuredPlan() {
global $wpdb;
	$wpdb->query('CREATE TABLE IF NOT EXISTS `wpcads_paypal` (
                      `main_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                      `user_id` TEXT NOT NULL ,
                      `id` TEXT NOT NULL ,
                      `name` TEXT NOT NULL ,
                      `token` TEXT NOT NULL ,
                      `price` FLOAT UNSIGNED NOT NULL ,
                      `currency` TEXT NOT NULL ,
                      `ads` TEXT ,
                      `days` TEXT NOT NULL ,
                      `date` TEXT NOT NULL ,
                      `status` TEXT NOT NULL ,
                      `used` TEXT NOT NULL ,
                      `transaction_id` TEXT NOT NULL ,
                      `firstname` TEXT NOT NULL ,
                      `lastname` TEXT NOT NULL ,
                      `email` TEXT NOT NULL ,
                      `description` TEXT NOT NULL ,
                      `summary` TEXT NOT NULL ,
                      `created` INT( 4 ) UNSIGNED NOT NULL
                      ) ENGINE = MYISAM ;');
  $price_plan_information = array(
    'id' => '1',
    'user_id' => '1',
    'name' => '',
    'token' => "",
    'price' => '',
    'currency' => "",
    'ads' => 'unlimited',
    'days' => 'unlimited',
    'date' => date("m/d/Y H:i:s"),
    'status' => "success",
    'used' => "0",
    'transaction_id' => "",
    'firstname' => "",
    'lastname' => "",
    'email' => "",
    'description' => "",
    'summary' => "",
    'created' => time()
  ); 

  $insert_format = array('%s', '%s', '%s','%s', '%f', '%s', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s');
 $result = $wpdb->get_results( "SELECT * FROM wpcads_paypal WHERE user_id = 1 ORDER BY main_id DESC" );

if (empty($result )) {
     
  $wpdb->insert('wpcads_paypal', $price_plan_information, $insert_format);
  }
}



function classiera_cubiq_login_init () {
    $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'login';
	global $redux_demo;
	$login = $redux_demo['login'];	
	$reset = $redux_demo['reset'];	
    if ( isset( $_POST['wp-submit'] ) ) {
        $action = 'post-data';
    } else if ( isset( $_GET['reauth'] ) ) {
        $action = 'reauth';
    } else if ( isset($_GET['key']) ) {
        $action = 'resetpass-key';
    }

    // redirect to change password form
    if ( $action == 'rp' || $action == 'resetpass' ) {
        wp_redirect( $login.'/?action=resetpass' );
        exit;
    }
	
	// redirect to change password form
    if ( $action == 'register') {
        wp_redirect( $login.'/?action=resetpass' );
        exit;
    }

    // redirect from wrong key when resetting password
    if ( $action == 'lostpassword' && isset($_GET['error']) && ( $_GET['error'] == 'expiredkey' || $_GET['error'] == 'invalidkey' ) ) {
        wp_redirect($reset.'/?action=forgot&failed=wrongkey' );
        exit;
    }

    if (
        $action == 'post-data'        ||            // don't mess with POST requests
        $action == 'reauth'           ||            // need to reauthorize
        $action == 'resetpass-key'    ||            // password recovery
        $action == 'logout'           ||              // user is logging out
		$action == 'postpass'
    ) {
        return;
    }

    //wp_redirect( home_url( '/login/' ) );
    wp_redirect($login);
    exit;
}
add_action('login_init', 'classiera_cubiq_login_init');

function classiera_cubiq_registration_redirect ($errors, $sanitized_user_login, $user_email) {
	global $redux_demo;
	$login = $redux_demo['login'];	
	$register = $redux_demo['register'];	
    // don't lose your time with spammers, redirect them to a success page
    if ( !isset($_POST['confirm_email']) || $_POST['confirm_email'] !== '' ) {

        wp_redirect($login. '?action=register&success=1' );
        exit;

    }

    if ( !empty( $errors->errors) ) {
        if ( isset( $errors->errors['username_exists'] ) ) {

            wp_redirect( $register . '?action=register&failed=username_exists' );

        } else if ( isset( $errors->errors['email_exists'] ) ) {

            wp_redirect( $register . '?action=register&failed=email_exists' );

        } else if ( isset( $errors->errors['empty_username'] ) || isset( $errors->errors['empty_email'] ) ) {

            wp_redirect($register . '?action=register&failed=empty' );

        } else if ( !empty( $errors->errors ) ) {

            wp_redirect( $register . '?action=register&failed=generic' );

        }

        exit;
    }

    return $errors;

}
add_filter('registration_errors', 'classiera_cubiq_registration_redirect', 10, 3);

/*-----------------------------------------------------------------------------------*/
/*	Infinite Pagination
/*-----------------------------------------------------------------------------------*/

			if (!function_exists('infinite')) {

				function infinite($query) {
					$pages = intval($query->max_num_pages);
					$paged = (get_query_var('paged')) ? intval(get_query_var('paged')) : 1;
					if (empty($pages)) {
						$pages = 1;
					}
					if (1 != $pages) {
						echo '<p class="jw-pagination jw-infinite-scroll simple-pagination" data-has-next="' . ($paged === $pages ? 'false' : 'true') . '">';
						echo '<a class="btn btn-small no-more" href="#"><i class="fa fa-refresh"></i>' . esc_html_e('No more posts', 'classiera') . '</a>';
						echo '<a class="btn btn-small loading" href="#"><i class="fa fa-refresh"></i>' . esc_html_e('Loading posts ...', 'classiera') . '</a>';
						echo '<a class="btn btn-small next" href="' . get_pagenum_link($paged + 1) . '"><i class="fa fa-refresh"></i>' . esc_html_e('Load More ', 'classiera') . '</a>';
						echo '</p>';
						?>
						<div class="jw-pagination jw-infinite-scroll" data-has-next="<?php echo ($paged === $pages ? 'false' : 'true'); ?>">
							<div class="clearfix">
								
							</div>
							
							<div class="more-btn-main">
								<div class="view-more-separator"></div>
									<div class="view-more-btn">
									<div class="more-btn-inner text-center">
										<a class="next button round" href="<?php echo get_pagenum_link($paged + 1);?>">
											<i class="fa fa-refresh"></i>
											<span><?php esc_html_e( 'load more', 'classiera' ); ?></span>
										</a>
										<a class="loading button round">
											<i class="fa fa-refresh"></i>
											<span><?php esc_html_e( 'Loading posts ...', 'classiera' ); ?></span>
										</a>
										<a class="no-more button round">
											<i class="fa fa-refresh"></i>
											<span><?php esc_html_e( 'No more posts', 'classiera' ); ?></span>
										</a>
									</div>
								</div>				
							</div>		
						</div>
						<?php 
					}
				}

			}
/* set excerpt length for blog posts */

function classiera_blog_excerpt_length($length) {
	global $post;
	if ($post->post_type == 'blog_posts'){
		return 150;
	}
	else {
		return $length;
	}
}
add_filter('excerpt_length', 'classiera_blog_excerpt_length', 1000);	

/* Ajax Function */
add_action('wp_ajax_classiera_implement_ajax', 'classiera_implement_ajax');
add_action('wp_ajax_nopriv_classiera_implement_ajax', 'classiera_implement_ajax');//for users that are not logged in.
function classiera_implement_ajax() {	
	if(isset($_POST['mainCat']))
			{				
				$cat_child = get_term_children( $_POST['mainCat'], 'category' );
				if (!empty($cat_child)) {	
					$categories=  get_categories('child_of='.$_POST['mainCat'].'&hide_empty=0');
					  foreach ($categories as $cat) {
						$option .= '<option value="'.$cat->term_id.'">';
						$option .= $cat->cat_name;
						/*$option .= ' ('.$cat->category_count.')';*/
						$option .= '</option>';
					  }

					  echo '<option value="-1" selected="selected">'.esc_html__( "Select Sub Category..", "classiera" ).'</option>'.$option;
					die();
				}else{
					echo '<option value="-1">'.esc_html__( "No Sub Category Found", "classiera" ).'</option>';
				}
			} // end if
}	
//classiera_implement_ajax() ;

/*Start Classiera Favourite Function*/
function classiera_authors_tbl_create() {

    global $wpdb;

    $sql2 = ("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}author_followers (

        id int(11) NOT NULL AUTO_INCREMENT,

        author_id int(11) NOT NULL,

        follower_id int(11) NOT NULL,

        PRIMARY KEY (id)

    ) ENGINE=InnoDB AUTO_INCREMENT=1;");

 $wpdb->query($sql2);

     $sql = ("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}author_favorite (

        id int(11) NOT NULL AUTO_INCREMENT,

        author_id int(11) NOT NULL,

        post_id int(11) NOT NULL,

        PRIMARY KEY (id)

    ) ENGINE=InnoDB AUTO_INCREMENT=1;");

 $wpdb->query($sql);

}

add_action( 'init', 'classiera_authors_tbl_create', 1 );



function classiera_authors_insert($author_id, $follower_id) {

    global $wpdb;	

	$author_insert = ("INSERT into {$wpdb->prefix}author_followers (author_id,follower_id)value('".$author_id."','".$follower_id."')");

  $wpdb->query($author_insert);

}



function classiera_authors_unfollow($author_id, $follower_id) {

    global $wpdb;	

	$author_del = ("DELETE from {$wpdb->prefix}author_followers WHERE author_id = $author_id AND follower_id = $follower_id ");

  $wpdb->query($author_del);

}



function classiera_authors_follower_check($author_id, $follower_id) {

	global $wpdb;

	$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}author_followers WHERE follower_id = $follower_id AND author_id = $author_id", OBJECT );

    if(empty($results)){

		?>

		<form method="post">

			<input type="hidden" name="author_id" value="<?php echo $author_id; ?>"/>

			<input type="hidden" name="follower_id" value="<?php echo $follower_id; ?>"/>

			<input type="submit" name="follower" value="<?php esc_html_e( 'Follow', 'classiera' ); ?>" />

		</form>

		<div class="clearfix"></div>

		<?php

	}else{

		?>

		<form method="post">

			<input type="hidden" name="author_id" value="<?php echo $author_id; ?>"/>

			<input type="hidden" name="follower_id" value="<?php echo $follower_id; ?>"/>

			<input type="submit" name="unfollow" value="<?php esc_html_e( 'Unfollow', 'classiera' ); ?>" />

		</form>

		<div class="clearfix"></div>

		<?php

	}

}

function classiera_authors_all_follower($author_id) {

	global $wpdb;

	$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}author_followers WHERE author_id = $author_id", OBJECT );

	$results2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}author_followers WHERE follower_id = $author_id", OBJECT );

	$followcounter = count($results);

	$followingcounter = count($results2);

	?>

	<div class="clearfix"></div>

	<div class="followers clearfix">

	<?php

	echo '<h1>Followers &nbsp;'.$followcounter.'</h1>';

	if(!empty($results)){

	$avatar = $results['0']->follower_id;

	echo '<div class="follower-avatar">';

	echo get_avatar($avatar, 70);

	echo '</div>';

	}

	?>

	</div>

	<div class="following">

	<?php

	echo '<h1>Following &nbsp;'.$followingcounter.'</h1>';

	if(!empty($results2)){

	$avatar = $results2['0']->author_id;

	echo '<div class="follower-avatar">';

	echo get_avatar($avatar, 70);

	echo '</div>';

	}

	?>

	</div>

	<?php

}

function classiera_favorite_insert($author_id, $post_id) {

    global $wpdb;	

	$author_insert = ("INSERT into {$wpdb->prefix}author_favorite (author_id,post_id)value('".$author_id."','".$post_id."')");

  $wpdb->query($author_insert);

}



function classiera_authors_unfavorite($author_id, $post_id) {

    global $wpdb;	

	$author_del = ("DELETE from {$wpdb->prefix}author_favorite WHERE author_id = $author_id AND post_id = $post_id ");

  $wpdb->query($author_del);

}



function classiera_authors_favorite_check($author_id, $post_id) {

	global $wpdb;

	$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}author_favorite WHERE post_id = $post_id AND author_id = $author_id", OBJECT );

    if(empty($results)){

		?>

		<form method="post" class="fav-form clearfix">

			<input type="hidden" name="author_id" value="<?php echo $author_id; ?>"/>

			<input type="hidden" name="post_id" value="<?php echo $post_id; ?>"/>		

			<input type="submit" name="favorite" value="<?php esc_html_e( 'Add to Favourite', 'classiera' ); ?>" />

		</form>

		<?php

	}else{

		$all_fav = $wpdb->get_results("SELECT `post_id` FROM $wpdb->postmeta WHERE `meta_key` ='_wp_page_template' AND `meta_value` = 'template-favorite.php' ", ARRAY_A);

		$all_fav_permalink = get_permalink($all_fav[0]['post_id']);

		echo '<div class="browse-favourite"><a href="'.$all_fav_permalink.'"><i class="fa fa-heart unfavorite-i"></i> <span>'.esc_html__( 'Browse Favourites', 'classiera' ).'</span></a></div>';

	}

}

function classiera_authors_favorite_remove($author_id, $post_id) {

	global $wpdb;
	$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}author_favorite WHERE post_id = $post_id AND author_id = $author_id", OBJECT );
    if(!empty($results)){
		?>
		<form method="post" class="unfavorite">
			<input type="hidden" name="author_id" value="<?php echo $author_id; ?>"/>
			<input type="hidden" name="post_id" value="<?php echo $post_id; ?>"/>
			<div class="unfavorite">
			<input type="submit" name="unfavorite" value="<?php esc_html_e( 'unfavorite', 'classiera' ); ?>" />
			</div>
		</form>
		<?php
	}

}

function classiera_authors_all_favorite($author_id) {

	global $wpdb;
	$postids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM {$wpdb->prefix}author_favorite WHERE author_id = $author_id", OBJECT ));
	foreach ($postids as $v2) {
        $postids[] = $v2;
    }
		return $postids;
}
/*End Classiera Favourite Function*/
/*WooCommerece Functions Start*/

/*WooCommerece Rating Function */
add_action('woocommerce_after_shop_loop_item', 'classiera_get_star_rating' );
function classiera_get_star_rating()
{
    global $woocommerce, $product;
    $average = $product->get_average_rating();
	//echo $product->get_rating_html();
    echo '<div class="star-rating"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.esc_html_e( 'out of 5', 'classiera' ).'</span></div>';
}
/*WooCommerece great deal Function */
add_filter('woocommerce_sale_flash', 'classiera_custom_sale_flash', 10, 3);
function classiera_custom_sale_flash($text, $myPost) {
  return '<span class="great"> Great Deal </span>';   
}


/* Filter Email */
add_filter ("wp_mail_content_type", "classiera_mail_content_type");
function classiera_mail_content_type() {
	return "text/html";
}
/* Filter Name */
add_filter('wp_mail_from_name', 'classiera_blog_name_from_name');
function classiera_blog_name_from_name($name = '') {
     return get_bloginfo('name');
}
/* Filter Email */
add_filter ("wp_mail_from", "classiera_mail_from");
function classiera_mail_from() {
	$sendemail =  get_bloginfo('admin_email');
	return $sendemail;
}	
/* Publish Post Email Function*/
add_action("publish_post", "classieraPostEmail");
function classieraPostEmail($post_id) {
	$post = get_post($post_id);
	$author = get_userdata($post->post_author);
	global $redux_demo;
	$logo = $redux_demo['logo']['url'];
	$trns_listing_published = $redux_demo['trns_listing_published'];
	$email_subject = $trns_listing_published;
	
	$author_email = $author->user_email;    
	
	ob_start();
	
	include(TEMPLATEPATH . '/templates/email/email-header.php');
	
	?>
	<div class="logo" style="background:#f0f0f0; padding:30px 0; text-align:center; margin-bottom:20px;">
		<?php if (!empty($logo)) { ?>
		<img src="<?php echo $logo; ?>" alt="Logo" />
		<?php } else { ?>
		<div class="logo">
		<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo" />
		</div>
		<?php } ?>
	</div>
	<div class="emContent" style="padding:0 15px; font-size:15px; font-family:Open Sans;">
	<p>
		<?php esc_html_e( 'Hi', 'classiera' ); ?>, <?php echo $author->display_name ?>. <?php esc_html_e( 'Congratulations your item has been listed', 'classiera' ); ?>! 
		<strong>(<?php echo $post->post_title ?>)</strong> <?php esc_html_e( 'on', 'classiera' ); ?> <?php echo  $blog_title = get_bloginfo('name'); ?>!
	</p>
	<p><?php esc_html_e( 'You have successfully listed your item on', 'classiera' ); ?> <strong><?php echo  $blog_title = get_bloginfo('name'); ?></strong>, <?php esc_html_e( 'now sit back and let us do the hard work.', 'classiera' ); ?></p>
	<p>
		<?php esc_html_e( 'If youd like to take a look', 'classiera' ); ?>, <a href="<?php echo get_permalink($post->ID) ?>"><?php esc_html_e( 'Click Here', 'classiera' ); ?></a>.
		
	</p>
	</div>	
	
	<?php
	
	include(TEMPLATEPATH . '/templates/email/email-footer.php');
	
	
	$message = ob_get_contents();
	
	ob_end_clean();
	
	
	wp_mail($author_email, $email_subject, $message);
	
}
/* Publish Post Email Function End*/
/* New User Registration Function Start*/

function classieraUserNotification($email, $password, $username) {	

	$blog_title = get_bloginfo('name');
	$blog_url = esc_url( home_url() ) ;
	$adminEmail =  get_bloginfo('admin_email');
	global $redux_demo;
	$logo = $redux_demo['logo']['url'];
	$welComeUser = $redux_demo['trns_welcome_user_title'];
	
	$email_subject = $welComeUser." ".$username."!";
	
	ob_start();	
	include(get_template_directory() . '/templates/email/email-header.php');
	
	?>
	<div class="logo" style="background:#f0f0f0; padding:30px 0; text-align:center; margin-bottom:20px;">
		<?php if (!empty($logo)) { ?>		
		<img src="<?php echo $logo; ?>" alt="Logo" />		
		<?php } else { ?>		
		<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo" />		
		<?php } ?>
	</div>
	<div class="emContent" style="padding:0 15px; font-size:15px; font-family:Open Sans;">
	<p><?php esc_html_e( 'A very special welcome to you', 'classiera' ); ?>, <?php echo $username ?>. <?php esc_html_e( 'Thank you for joining', 'classiera' ); ?> <?php echo $blog_title; ?>!</p>
	<p>
		<?php esc_html_e( 'Your username is', 'classiera' ); ?> <strong style="color:orange"><?php echo $username ?></strong> <br>		
	</p>
	<p>
		<?php esc_html_e( 'Your password is', 'classiera' ); ?> <strong style="color:orange"><?php echo $password ?></strong> <br>
		<?php esc_html_e( 'Please keep it secret and keep it safe!', 'classiera' ); ?>
	</p>
	
	<p>
		<?php esc_html_e( 'We hope you enjoy your stay at', 'classiera' ); ?> <a href="<?php echo $blog_url; ?>"><?php echo $blog_title; ?></a>. <?php esc_html_e( 'If you have any problems, questions, opinions, praise, comments, suggestions, please feel free to contact us at', 'classiera' ); ?> 
		 <strong><?php echo $adminEmail; ?> </strong><?php esc_html_e( 'any time!', 'classiera' ); ?>
	</p>
	</div>
	
	<?php
	
	include(get_template_directory() . '/templates/email/email-footer.php');
	
	$message = ob_get_contents();
	ob_end_clean();

	wp_mail($email, $email_subject, $message);
	}

/* New User Registration Function End*/
/* Email to Admin On New User Registration */
function classieraNewUserNotifiy($email, $username) {	

	$blog_title = get_bloginfo('name');
	$blog_url = esc_url( home_url() ) ;
	$adminEmail =  get_bloginfo('admin_email');
	global $redux_demo;
	$logo = $redux_demo['logo']['url'];
	
	$email_subject = "New User Has been Registered On ".$blog_title;
	
	ob_start();	
	include(get_template_directory() . '/templates/email/email-header.php');
	
	?>
	<div class="logo" style="background:#f0f0f0; padding:30px 0; text-align:center; margin-bottom:20px;">
		<?php if (!empty($logo)) { ?>
		
		<img src="<?php echo $logo; ?>" alt="Logo" />		
		<?php } else { ?>		
		<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo" />		
		<?php } ?>
	</div>
	<div class="emContent" style="padding:0 15px; font-size:15px; font-family:Open Sans;">
	<p><?php esc_html_e( 'Hello, New User has been Registred on', 'classiera' ); ?>, <?php echo $blog_title ?>. <?php esc_html_e( 'By using this email', 'classiera' ); ?> <?php echo $email; ?>!</p>
	<p>
		<?php esc_html_e( 'His User name is:', 'classiera' ); ?> <strong style="color:orange"><?php echo $username ?></strong> <br>		
	</p>
	</div>
	<?php
	
	include(get_template_directory() . '/templates/email/email-footer.php');
	
	$message = ob_get_contents();
	ob_end_clean();

	wp_mail($adminEmail, $email_subject, $message);
	}
/* Email to Admin On New User Registration */
/*Pending Post Status Function*/
function classieraPendingPost( $new_status, $old_status, $post ) {
    if ( $new_status == 'private' ) {
        $author = get_userdata($post->post_author);
		global $redux_demo;
		$logo = $redux_demo['logo']['url'];
		$trns_new_post_posted = $redux_demo['trns_new_post_posted'];
		$email_subject = $trns_new_post_posted;
		$adminEmail =  get_bloginfo('admin_email');	
		ob_start();
		include(TEMPLATEPATH . '/templates/email/email-header.php');
		?>
			<div class="logo" style="background:#f0f0f0; padding:30px 0; text-align:center; margin-bottom:20px;">
				<?php if (!empty($logo)) { ?>
				<div class="logo">
					<img src="<?php echo $logo; ?>" alt="Logo" />
				</div>
				<?php } else { ?>
				<div class="logo">
					<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo" />
				</div>
				<?php } ?>
			</div>
			<div class="emContent" style="padding:0 15px; font-size:15px; font-family:Open Sans;">
			<p>
				<?php esc_html_e( 'Hi', 'classiera' ); ?>, <?php echo $author->display_name ?>. <?php esc_html_e( 'Have Post New Ads', 'classiera' ); ?><strong>(<?php echo $post->post_title ?>)</strong> <?php esc_html_e( 'on', 'classiera' ); ?> <?php echo  $blog_title = get_bloginfo('name'); ?>!
			</p>
			<p><?php esc_html_e( 'Please Approve or Reject this Post from WordPress Dashboard.', 'classiera' ); ?></p>
			</div>
		<?php
		include(TEMPLATEPATH . '/templates/email/email-footer.php');
		$message = ob_get_contents();
		ob_end_clean();
		wp_mail($adminEmail, $email_subject, $message);
    }
}
add_action(  'transition_post_status',  'classieraPendingPost', 10, 3 );
/*Pending Post Status Function End*/
/*Email to Post Author */
function contactToAuthor($emailTo, $subject, $name, $email, $comments, $headers, $classieraPostTitle, $classieraPostURL) {	

	$blog_title = get_bloginfo('name');
	$blog_url = esc_url( home_url() ) ;
	$adminEmail =  get_bloginfo('admin_email');
	global $redux_demo;
	$logo = $redux_demo['logo']['url'];
	
	$email_subject = $subject;
	
	ob_start();	
	include(get_template_directory() . '/templates/email/email-header.php');
	
	?>
	<div class="logo" style="background:#f0f0f0; padding:30px 0; text-align:center; margin-bottom:20px;">
		<?php if (!empty($logo)) { ?>		
		<img src="<?php echo $logo; ?>" alt="Logo" />		
		<?php } else { ?>		
		<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo" />
		
		<?php } ?>
	</div>
	<div class="emContent" style="padding:0 15px; font-size:15px; font-family:Open Sans;">
	<p><?php echo $comments; ?></p>
	<p><?php esc_html_e( 'Your have received this email from', 'classiera' ); ?></p>
	<p><strong><?php esc_html_e( 'Sender Name', 'classiera' ); ?></strong>:&nbsp;<?php echo  $name;?></p>
	<p><strong><?php esc_html_e( 'Sender Email', 'classiera' ); ?></strong>:&nbsp;<?php echo  $email;?></p>
	<p><strong><?php esc_html_e( 'Your Post Title', 'classiera' ); ?></strong>:&nbsp;<?php echo  $classieraPostTitle;?></p>
	<p><strong><?php esc_html_e( 'Your Post URL', 'classiera' ); ?></strong>:&nbsp;<?php echo  $classieraPostURL;?></p>
	</div>
	
	<?php
	
	include(get_template_directory() . '/templates/email/email-footer.php');
	
	$message = ob_get_contents();
	ob_end_clean();

	wp_mail($emailTo, $email_subject, $message, $headers);
	}
/*ResetPasswordemail*/
function classieraResetPassword($new_password, $userName, $userEmail ){
	$blog_title = get_bloginfo('name');
	$blog_url = esc_url( home_url() ) ;
	$emailTo = $userEmail;
	$adminEmail =  get_bloginfo('admin_email');
	global $redux_demo;
	$logo = $redux_demo['logo']['url'];
	$email_subject = esc_html__( 'Password Reset', 'classiera' );
	
	ob_start();
	include(get_template_directory() . '/templates/email/email-header.php');
	?>
	<div class="logo" style="background:#f0f0f0; padding:30px 0; text-align:center; margin-bottom:20px;">
		<?php if (!empty($logo)) { ?>		
		<img src="<?php echo $logo; ?>" alt="Logo" />		
		<?php } else { ?>		
		<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo" />
		
		<?php } ?>
	</div>
	<div class="emContent" style="padding:0 15px; font-size:15px; font-family:Open Sans;">
		<p>
			<?php esc_html_e( 'Your New Password is', 'classiera' ); ?><?php echo $new_password; ?>
		</p>
		<p>
			<?php esc_html_e( 'Your UserName Was', 'classiera' ); ?><?php echo $userName; ?>
		</p>
	</div>
	<?php
	include(get_template_directory() . '/templates/email/email-footer.php');
	$message = ob_get_contents();
	ob_end_clean();
	wp_mail($emailTo, $email_subject, $message);
}	
/*ResetPasswordemail*/	
/* Email Function End*/
/*Remove Notification from redux framework */
function classieraRemoveReduxDemoModeLink() { // Be sure to rename this function to something more unique
    if ( class_exists('ReduxFrameworkPlugin') ) {
        remove_filter( 'plugin_row_meta', array( ReduxFrameworkPlugin::get_instance(), 'plugin_metalinks'), null, 2 );
    }
    if ( class_exists('ReduxFrameworkPlugin') ) {
        remove_action('admin_notices', array( ReduxFrameworkPlugin::get_instance(), 'admin_notices' ) );    
    }
}
add_action('init', 'classieraRemoveReduxDemoModeLink');
/*Remove Notification from redux framework */

	/*Location with Images Start*/
	add_action( 'location_edit_form_fields', 'classiera_location_fields', 10, 2 );
	add_action( 'edited_location', 'classiera_save_location_fields', 10, 2 );
	
	// A callback function to save our extra taxonomy field(s)  
	function classiera_save_location_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 );  
		}  
	}


	function classiera_location_fields($tag) {  
	   // Check for existing taxonomy meta for the term you're editing  
		$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="eralocation_id"><?php esc_html_e('Location Image', 'classiera'); ?></label>  
		</th>  
		<td>  
			<?php 

            

				if(!empty($term_meta)) {

                echo '<div style="width: 100%; float: left;"><img id="category_location_img" src="'. $term_meta['eralocation_id'] .'" style="float: left; margin-bottom: 20px;" /> </div>';
                echo '<input id="location_image" type="text" size="36" name="term_meta[eralocation_id]" style="max-width: 200px; float: left; margin-top: 10px; display: none;" value="'.$term_meta['eralocation_id'].'" />';
               
			   echo '<input id="location_image_button_remove" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px;" value="Remove" /> </br>';
                echo '<input id="location_image_button" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px; display: none;" value="Upload Image" /> </br>'; 

            } else {

               
                echo '<div style="width: 100%; float: left;"><img id="category_location_img" src="'. $term_meta['eralocation_id'] .'" style="float: left; margin-bottom: 20px;" /> </div>';
               echo '<input id="location_image" type="text" size="36" name="term_meta[eralocation_id]" style="max-width: 200px; float: left; margin-top: 10px; display: none;" value="'.$term_meta['eralocation_id'].'" />';
               
			   echo '<input id="location_image_button_remove" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px; display: none;" value="Remove" /> </br>';
                echo '<input id="location_image_button" class="button" type="button" style="max-width: 140px; float: left; margin-top: 10px;" value="Upload Image" /> </br>';

            }        

          

            ?> 
		</td>  
		 <script>
            var image_custom_uploader;
            jQuery('#location_image_button').click(function(e) {
                e.preventDefault();

                //If the uploader object has already been created, reopen the dialog
                if (image_custom_uploader) {
                    image_custom_uploader.open();
                    return;
                }

                //Extend the wp.media object
                image_custom_uploader = wp.media.frames.file_frame = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: false
                });

                //When a file is selected, grab the URL and set it as the text field's value
                image_custom_uploader.on('select', function() {
                    attachment = image_custom_uploader.state().get('selection').first().toJSON();
                    var url = '';
                    url = attachment['url'];
                    jQuery('#location_image').val(url);
                    jQuery( "img#category_location_img" ).attr({
                        src: url
                    });
                    jQuery("#location_image_button").css("display", "none");
                    jQuery("#location_image_button_remove").css("display", "block");
                });

                //Open the uploader dialog
                image_custom_uploader.open();
             });

             jQuery('#location_image_button_remove').click(function(e) {
                jQuery('#location_image').val('');
                jQuery( "img#category_location_img" ).attr({
                    src: ''
                });
                jQuery("#location_image_button").css("display", "block");
                jQuery("#location_image_button_remove").css("display", "none");
             });
            </script>
	</tr>  
	  
	<?php  
	} 
/* Location with Images end*/
?>
<?php
add_action('wp_head','classiera_ajaxURL');
function classiera_ajaxURL() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
/* Fix nextend facebook connect doesn't remove cookie after logout */
if (!function_exists('classiera_clear_nextend_cookie')) {
    function classiera_clear_nextend_cookie(){
        setcookie( 'nextend_uniqid',' ', time() - YEAR_IN_SECONDS, '/', COOKIE_DOMAIN );
        return 0;
    }
}
add_action('clear_auth_cookie', 'classiera_clear_nextend_cookie');
function classieraRoleTrns($classieraRole){
	if($classieraRole == 'administrator'){
		$classieraUserRole =  esc_html__( 'Administrator', 'classiera' );
	}elseif($classieraRole == 'contributor'){
		$classieraUserRole =  esc_html__( 'Contributor', 'classiera' );
	}elseif($classieraRole == 'subscriber'){
		$classieraUserRole =  esc_html__( 'Subscriber', 'classiera' );
	}elseif($classieraRole == 'author'){
		$classieraUserRole =  esc_html__( 'Author', 'classiera' );
	}elseif($classieraRole == 'editor'){
		$classieraUserRole =  esc_html__( 'Editor', 'classiera' );
	}else{
		$classieraUserRole =  esc_html__( 'User', 'classiera' );
	}
	echo $classieraUserRole;
}
function classieraPStatusTrns($classieraPstatus){
	if($classieraPstatus == 'publish'){
		$pStatus =  esc_html__( 'Publish', 'classiera' );
	}elseif($classieraPstatus == 'pending'){
		$pStatus =  esc_html__( 'Pending', 'classiera' );
	}elseif($classieraPstatus == 'draft'){
		$pStatus =  esc_html__( 'Draft', 'classiera' );
	}elseif($classieraPstatus == 'auto-draft'){
		$pStatus =  esc_html__( 'Auto draft', 'classiera' );
	}elseif($classieraPstatus == 'future'){
		$pStatus =  esc_html__( 'Future', 'classiera' );
	}elseif($classieraPstatus == 'private'){
		$pStatus =  esc_html__( 'Private', 'classiera' );
	}elseif($classieraPstatus == 'inherit'){
		$pStatus =  esc_html__( 'Inherit', 'classiera' );
	}elseif($classieraPstatus == 'trash'){
		$pStatus =  esc_html__( 'Trash', 'classiera' );
	}else{
		$pStatus =  esc_html__( 'None', 'classiera' );
	}
	echo $pStatus;
}