<?php
/*
	User rating functions
 
	WARNING: This file is part of the core WPRichSnippets plugin. DO NOT edit
	this file under any circumstances.
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

	// Load user rating column preview
	// @since 1.0.0
	require_once ('wprs-column-preview.php');
	require_once ('hide-comments/hide-comments.php');							
	
	
	add_action( 'wp_enqueue_scripts', 'wprs_comment_userrating_scripts', 5 );
	/*
    	Load comment rating scripts
		@since 1.0.0
    	*/
	function wprs_comment_userrating_scripts() {
		
		global $post;
		
		if ( is_admin() ) return;
		if ( !is_singular() ) return;
		if ( is_archive() ) return;
		if ( is_404() ) return;
		
		// Check for WooCommerce
		// @since 1.4.1
		if ( ! class_exists( 'WPRS_WOO' ) ) {
			if ( class_exists( 'WooCommerce' ) ) {
				if ( function_exists( 'is_product') ) {
					if ( is_product() ) return;
				}
			}
		}
		// End of WooCommerce check
		// if ( class_exists( 'WooCommerce' ) && ! class_exists( 'WPRS_WOO' ) ) return;
		
		if (!wprs_is_enabled($post->ID)) return;
		
		$type = wprs_get_type();
		
		if ($type == 'rating' || $type == 'percentage') return;
		
		$options = get_option('wprs_options');
		
		// Register the script
		wp_register_script(	'wprs-raty',						WPRS_JS_URL.'user-rating/jquery.raty-fa.js',		array('jquery') );
		wp_register_script( 'wprs-jquery-custom-script',		WPRS_JS_URL.'user-rating/custom.js',				array('jquery') );
		wp_register_script( 'wprs-colorbox',					WPRS_JS_URL.'colorbox/jquery.colorbox-min.js',		array('jquery') );

		// Enqueue the script
		if (!isset($options['wprs_no_jquery']) != '') { 
			wp_enqueue_script( 'jquery' );
		}
		if (!isset($options['wprs_no_jquery_ui']) != '') {
			wp_enqueue_script( 'jquery-ui-core' );
			wp_enqueue_script( 'jquery-ui-slider' );
		}
		if (!isset($options['wprs_no_jquery_ui_touch_punch']) != '') { 
			wp_enqueue_script( 'jquery-touch-punch' );
		}
		
		wp_enqueue_script( 'wprs-raty' );
		wp_enqueue_script( 'wprs-jquery-custom-script' );
		wp_enqueue_script( 'wprs-colorbox' );

	}
	

	
	add_action( 'wp_enqueue_scripts', 'wprs_comment_userrating_styles' );
	/*
    	Load comment rating styles
		@since 1.0.0
    	*/
	function wprs_comment_userrating_styles() {
		
		global $post;
		
		if ( is_admin() ) return;
		if ( !is_singular() ) return;
		if ( is_archive() ) return;
		if ( is_404() ) return;
		
		// Check for WooCommerce
		// @since 1.4.1
		if ( ! class_exists( 'WPRS_WOO' ) ) {
			if ( class_exists( 'WooCommerce' ) ) {
				if ( function_exists( 'is_product') ) {
					if ( is_product() ) return;
				}
			}
		}
		// End of WooCommerce check
		
		if (!wprs_is_enabled($post->ID)) return;
		
		$type = wprs_get_type();
		if ($type == 'rating' || $type == 'percentage') return;
		
		// Register the style
		wp_register_style( 'wprs-colorbox',			WPRS_CSS_URL.'colorbox/colorbox.css', array(), '1.0', 'all' );
		wp_register_style( 'jquery-ui-theme',		WPRS_CSS_URL.'smoothness/jquery-ui-1.10.3.custom.min.css', array(), '1.0', 'all' );
		
		// Enqueue the style
		wp_enqueue_style( 'wprs-colorbox' );
		wp_enqueue_style( 'jquery-ui-theme' );

	}
	
	
	
	add_filter('comment_form_defaults','wprs_comment_title_reply');  
	/*
    	Change comment form reply title to 'Add Review:',
		this is not working on all themes though, only on themes that uses default commenting form structure!
		@since 1.0.0
		*/
	function wprs_comment_title_reply ($arg) {
		
		global $post, $wprs_prefix;
		
		if (!wprs_is_enabled($post->ID)) return $arg;

		if (wprs_get_type() != 'aggregate') return $arg;
		
		$arg['title_reply'] = __('Add Review:', 'wprs');
		$arg['label_submit'] = __('Submit Review', 'wprs');
		return $arg;
	}
	
   

	add_action('wp_footer', 'wprs_DisplayRatingFields');
	/*
    	Appends the rating field to the end of the comment form, if required
		@since 1.0.0
		*/
    function wprs_DisplayRatingFields() {
		
		global $post, $wprs_prefix;
		
		if (!wprs_is_enabled($post->ID)) return;

		if (wprs_get_type() != 'aggregate') return;
		
		$field = '';
		$label = '';
		$row = '';
		$our = '';

		// Reset to default loop query so we can test if a single Page or Post
		wp_reset_query();
		
		// Check if user rating system is enabled
		$options = get_option('wprs_options');
		//if (!isset($options['wprs_chk_user_rating_enable']) != '') return;
		
		// Check if post can have user rating
		$id = get_the_ID();
		$mypost = get_post($id);
		$custom = get_post_custom($mypost->ID);
		
		if (wprs_is_user_author()) return;
		// Comments are no longer open
		if ($mypost->comment_status != 'open') return;
		
		// Check if replytocom is enabled
		// this option will hide user rating fields from the form
		// this feature won't work while setting the plugin to force users to leave a rating!
		// @since 1.0.0
		//$url_query = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_QUERY );
    	//if( FALSE === stripos( $url_query, 'replytocom' ) ) {
		if (!isset($options['wprs_chk_replytocom']) !='') {$user_rating_fileds = '';} else {$user_rating_fileds = ' user_rating_fileds';}
			
			// Add slider range
						// Get repeatable
						$out ='';
						$range ='';
						$i = 0;
						if (get_post_meta($mypost->ID, $wprs_prefix.'repeatable', true)) {
							$i = 0;
							$repeatable_array = get_post_meta($mypost->ID, $wprs_prefix.'repeatable', true);
							$out .= '<div class="container-fluid user_range'.$user_rating_fileds.'">';
							$out .= '<div class="row">';
							$out .= '<p>'. __('Add your review, and rating', 'wprs') .'</p>';
							foreach($repeatable_array as $key => $element){
								$uid = $element['title'];
								if (isset($element['range'])) $range = $element['range'];
									$out .= '<div class="col-md-6">';
									if ($element['desc'] !== '') {
										$out .= '<label class="item_range_label" for="amount_'.$uid.'">'.$element['desc'].'</label>';
									} else {
										$out .= '<label class="item_range_label" for="amount_'.$uid.'">'.$element['title'].'</label>';
									}
									$out .= '<div id="item_range_'.$uid.'">'.$range.'</div>';
									$out .= '<input type="hidden" name="amount_'.$uid.'" id="amount_'.$uid.'" value="'.$range.'" />';
									$out .= '</div>';
								$i++;
							}
							$out .= '</div>';
							$out .= '</div>';
						}
						
						// Do not display if there is only one criteria field.
						if ( $i == 1 ) $out = '';
		
						// Rating field
						$user_rating_field = '<div class="row item user_rating'.$user_rating_fileds.'"><div class="col-md-12">';
						$label = '<label for="rating-star">'. __('Rating', 'wprs') .'</label>';
    					$user_rating_field .= $label.'<div id="star-rating"></div>';
						$user_rating_field .= '</div></div>';
						
						// Headline field
						$headline_field = '<p><label class="wprs_form_headline" for="wprs_headline">'. __('Headline', 'wprs') .'</label>';
						$headline_field .= '<br />';
						$headline_field .= '<input id="wprs_headline" name="wprs_headline" value="" type="text" /></p>';
						
						
						// We got it all together
						// Let's decide which form to use...
						// @since 1.0.0
						if (isset($options['wprs_chk_user_rating_popup_enable']) != '') {$field = '';} else {$field = $out . $user_rating_field . $headline_field;}
						

		// Check if user is logged in, enable rating for visitors
		if (!isset($options['wprs_chk_user_rating_visitors_enable']) != '') {
			// If user is NOT loggedin
			if ( !is_user_logged_in() ) return;
		}
		
		// Check if user already added a review
		// Display user rating and a message
		// User function wprs_check_if_can_rate_ip($post_id)
		if (wprs_check_if_can_rate_ip($id) !=''){ $field = wprs_check_if_can_rate_ip($id);}
		
		?>
		<script type="text/javascript">
	    	jQuery(document).ready(function($) {
			   	
				
				if ($('form#commentform textarea[name=comment]').length > 0) {
			    	// If parent tag is a container for the comment field, append rating after the parent
			    	var commentField = $('form#commentform textarea[name=comment]');
			    	var parentTagName = $(commentField).parent().get(0).tagName;
			    	
					if (parentTagName == 'P' || parentTagName == 'DIV' || parentTagName == 'LI') {
			    		// Append rating field as a new element
			    		$(commentField).parent().before('<'+parentTagName+' class="wpar-field"><?php echo $field; ?></'+parentTagName+'>');
			    	} else {
			    		// Append rating field before comment field
			    		$(commentField).before('<?php echo $field; ?>');
			    	}
					
					// Raty FA
					$('#star-rating').raty({
						
						half		: false,
						cancel		: true,
						cancelHint	: 'Cancel my rating!',
						size 		: 24,
						scoreName	: 'rating',

					});
				}
				
				
			});
		</script>
    	<?php
    }
	
	
	
	/*
    	Comment popup form
		@since 1.0.0
    	*/
	function wprs_Comment_Popup($content) {
		
		global $post, $wprs_prefix;
		
		// Check if Thesis theme is active,
		// Popup comments do not work with Thesis theme
		$my_theme = wp_get_theme();
		if ( $my_theme->get( 'Name' ) == 'Thesis') return $content;

		// Check for WooCommerce
		// @since 1.4.1
		if ( ! class_exists( 'WPRS_WOO' ) ) {
			if ( class_exists( 'WooCommerce' ) ) {
				if ( function_exists( 'is_product') ) {
					if ( is_product() ) return $content;
				}
			}
		}
		// End of WooCommerce check
		
		if (!wprs_is_enabled($post->ID)) return $content;

		if (wprs_get_type() != 'aggregate') return $content;
		
		// Check if post can have user rating
		$id = get_the_ID();
		$mypost = get_post($id);
		$custom = get_post_custom($mypost->ID);
		
		// Get current user info
		$current_user = wp_get_current_user();
		// Check review author, do not display rating (if logged in)
		if ($mypost->post_author == $current_user->ID) return $content;
		// Comments are no longer open
		if ($mypost->comment_status != 'open') return $content;
		
		// get options
		$options = get_option('wprs_options');
		// Check if user rating system is enabled
		//if ( !isset($options['wprs_chk_user_rating_enable']) != '' ) return;
		if (!isset($options['wprs_chk_user_rating_popup_enable']) != '') return $content;	
		// Check if comments are open
		if ( !comments_open() ) return $content;
		
		?>
        <div style='display:none'>
        <div id="inline_content">
        <?php
		
		$title_reply = '';
		$commenter = wp_get_current_commenter();
		
		?> 
		<div id="review_form_wrapper"><div id="review_form" class="wprs_review_form">
   		<?php
		
		// Check if comment author url field is enabled within the plugin settings
		// @since 1.3.3
		$url = isset($options['wprs_chk_user_comment_url_disable']) ? '' : '<p class="comment-form-url"><label for="url">' . __( 'Website', 'wprs' ) . '</label> ' . '<input id="url" name="url" type="text" placeholder="http://" value="' . esc_attr(  $commenter['comment_author_url'] ) . '" size="30" aria-required="false" /></p>';
		
		$comment_form = array(
			'id_form' => 'commentform',
			'class_form' => 'comment-form',
			'title_reply' => $title_reply,
			'comment_notes_before' => '',
			'comment_notes_after' => '',
			'fields' => array(
				'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name', 'wprs' ) . ' <span class="required">*</span>' . '</label>' .
				            '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30" aria-required="true" /></p>',
				'email'  => '<p class="comment-form-email"><label for="email">' . __( 'Email', 'wprs' ) . ' <span class="required">*</span>' . '</label> ' .
				            '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30" aria-required="true" /></p>',
				'url'  => $url,
			),
			'label_submit' => __( 'Submit Review', 'wprs' ),
			'logged_in_as' => '',
			'comment_field' => ''
		);
		
		$field = '';
		$label = '';
		$row = '';
		$our = '';
		// Reset to default loop query so we can test if a single Page or Post
		wp_reset_query();

		// Add slider range
		//*****************
						
						// Get repeatable
						$out ='';
						$range ='';
						if (get_post_meta($mypost->ID, $wprs_prefix.'repeatable', true)) {
							$i = 0;
							$repeatable_array = get_post_meta($mypost->ID, $wprs_prefix.'repeatable', true);
							$out .= '<div class="row user_range">';
							$out .= '<p>'. __('Add your review, and rating', 'wprs') .'</p>';
							
							// Criteria fields
							foreach($repeatable_array as $key => $element){
								$uid = $element['title'];
								if (isset($element['range'])) $range = $element['range'];
									$out .= '<div class="col-sm-6">';
									if ($element['desc'] !== '') {
										$out .= '<label for="amount_'.$uid.'">'.$element['desc'].'</label>';
									} else {
										$out .= '<label for="amount_'.$uid.'">'.$element['title'].'</label>';
									}
									$out .= '<div id="item_range_'.$uid.'">'.$range.'</div>';
									$out .= '<input type="hidden" name="amount_'.$uid.'" id="amount_'.$uid.'" value="'.$range.'" />';
									$out .= '</div>';
								$i++;
							}
							
							$out .= '</div>';
						}
						
						// Do not display if there is only one criteria field.
						if ( $i == 1 ) $out = '';
						
						// Rating field
						$user_rating_field = '<div class="row item user_rating"><div class="col-md-12">';
						$label = '<label for="rating-star">'. __('Rating', 'wprs') .'</label>';
    					$user_rating_field .= $label.'<div id="star-rating"></div>';
						$user_rating_field .= '</div></div>';
						
						// Headline field
						$headline_field = '<p class="comment-form-author"><label for="wprs_headline">'. __('Headline', 'wprs') .'</label>';
						$headline_field .= '<input id="wprs_headline" name="wprs_headline" value="" type="text" /></p>';
						
						// We got it all together
						$comment_form['comment_field'] .= $out . $user_rating_field . $headline_field;
						
						$comment_form['comment_field'] .= '<p class="comment-form-comment"><label for="comment">' . __( 'Your Review', 'wprs' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>' . wp_nonce_field('wprs_comment_rating', true, false);
						
		comment_form( apply_filters( 'wprs_review_comment_form_args', $comment_form ) );
		
		?>
		</div></div>
        </div></div>
        <?php
		
	}
	add_filter( 'comments_template', 'wprs_Comment_Popup', 1 );
	
		
	/*
    	Comment popup form
		@since 1.0.0
    	*/
	function wprs_Comment_Popup_Button($content) {
		
		global $post;
		
		// Check if Thesis theme is active
		$my_theme = wp_get_theme();
		if ( $my_theme->get( 'Name' ) == 'Thesis') return $content;
		
		// Check for WooCommerce
		// @since 1.4.1
		if ( ! class_exists( 'WPRS_WOO' ) ) {
			if ( class_exists( 'WooCommerce' ) ) {
				if ( function_exists( 'is_product') ) {
					if ( is_product() ) return $content;
				}
			}
		}
		// End of WooCommerce check
		
		if (!wprs_is_enabled($post->ID)) return $content;

		if (wprs_get_type() != 'aggregate') return $content;
		
		
		// Check if logged-in user is the author of entry
		if (wprs_is_user_author()) return $content;
		
		// Get options
		$options = get_option('wprs_options');
		// Check if user rating system is enabled
		if ( !isset($options['wprs_chk_user_rating_enable']) != '' ) return $content;
		if ( !isset($options['wprs_chk_user_rating_popup_enable']) != '' ) return $content;	
		
		echo '<div class="wprs_add_review">';
		echo '<p><a href="#inline_content" class="inline ar_button" title="'.__('Add Your Review','wprs').'"><i class="fa fa-plus-circle"></i> '.__('Add Review','wprs').'</a></p>';
		echo '</div>';
		
	}
	add_filter( 'comments_template', 'wprs_Comment_Popup_Button', 1 );
	
	
	/*
    	Appends styles require for comment popup when needed
		@since 1.0.0
    	*/
	function wprs_Comment_Form_Hide() {
		
		global $post;
		
		if ( is_admin() ) return;
		if ( !is_singular() ) return;
		if ( is_archive() ) return;
		if ( is_404() ) return;
		
		// Check for WooCommerce
		// @since 1.4.1
		if ( ! class_exists( 'WPRS_WOO' ) ) {
			if ( class_exists( 'WooCommerce' ) ) {
				if ( function_exists( 'is_product') ) {
					if ( is_product() ) return;
				}
			}
		}
		// End of WooCommerce check
		
		if (!wprs_is_enabled($post->ID)) return;
		
		if (wprs_get_type() != 'aggregate') return;
		
		// Check if post is object otherwise you're not in singular post
		// @since 1.1.9.3
    	if( !is_object($post) ) return;
		
		// Check if Thesis theme is active
		$my_theme = wp_get_theme();
		if ( $my_theme->get( 'Name' ) == 'Thesis') return;
		
		// Get options
		$options = get_option('wprs_options');
		// Check if user rating system is enabled
		//if ( !isset($options['wprs_chk_user_rating_enable']) != '' ) return;
		if (!isset($options['wprs_chk_user_rating_popup_enable']) != '') return;	
		// Check if comments are open
		if ( !comments_open() ) return;
		$custom_css = "<style type='text/css'>";
		$custom_css .= '#respond, #commentform, #comments .reply, #comments a.comment-reply-link, a.comment-reply-link {display:none;}';
		$custom_css .= '#review_form_wrapper #respond, #review_form_wrapper #commentform {display: block;}';
		$custom_css .= "</style>";
		echo $custom_css;
	}
	add_action('wp_head', 'wprs_Comment_Form_Hide');
    

    
	/*
    	Appends the script require for range field
		@since 1.0.0
		*/
	function wprs_DisplayRatingFieldScript() {
		
		global $post, $wprs_prefix;
		
		if ( is_admin() ) return;
		if ( !is_singular() ) return;
		if ( is_archive() ) return;
		if ( is_404() ) return;
		
		if (!wprs_is_enabled($post->ID)) return;

		if (wprs_get_type() != 'aggregate') return;
		
		// Reset to default loop query so we can test if a single Page or Post
		wp_reset_query();
		
		// check if user rating system is enabled
		$options = get_option('wprs_options');
		//if (!isset($options['wprs_chk_user_rating_enable']) != '') return;
		
		// check if post can have user rating
		$id = get_the_ID();
		$mypost = get_post($id);
		$custom = get_post_custom($mypost->ID);

		// Check user is review author (if logged in)
		if (wprs_is_user_author()) return '';
		// Comments are no longer open
		if ($mypost->comment_status != 'open') return;
		
		// Get repeatable
		if (get_post_meta($mypost->ID, $wprs_prefix.'repeatable', true)) {
			$i = 0;
			$out = '';
			$myarray = get_post_meta($mypost->ID, $wprs_prefix.'repeatable', true);
			// Output the script
?>
<script>
	jQuery(function($){
		<?php foreach($myarray as $key => $element){
		$uid = $element['title'];
		?>
			$( '#<?php echo 'item_range_'.$uid; ?>' ).slider({
				range: "min",
				value: 50,
				min: 1,
				max: 100,
				slide: function( event, ui ) {
					$( "#amount" ).val( ui.value );
					$(this).find('.ui-slider-handle').text(ui.value);
					$( "#<?php echo 'amount_'.$uid; ?>" ).val( ui.value );
				},
				create: function(event, ui) {
					var v=$(this).slider('value');
					$(this).find('.ui-slider-handle').text(v);
				}
			});
			$( "#<?php echo 'amount_'.$uid; ?>" ).val( $( "#<?php echo 'item_range_'.$uid; ?>" ).slider( "value" ) );
		<?php $i++; } ?>
	});
</script>
<?php
		}

		if (isset($options['wprs_chk_user_rating_popup_enable']) != '') { ?>
<script>
	jQuery(document).ready(function($) {
		$(".inline").colorbox({
			inline:true,
			transition: 'elastic',
	        speed: 300,
			width: false,
        	initialWidth: 800,
        	innerWidth: false,
        	maxWidth: '95%',
        	height: false,
        	initialHeight: 450,
        	innerHeight: false,
        	maxHeight: '95%',
			arrowKey:false,
			closeButton:true
		});
	});
</script>
<?php		
		}
		
	}
	add_action('wp_footer', 'wprs_DisplayRatingFieldScript', 99);



	/*
    	Save data - user rating to comments,
		& save visitor IP if enabled 
		@since 1.0.0
		*/
	function wprs_save_comment_userrating_field( $comment_id ) {
		
		global $wpdb, $post, $wprs_prefix;
		
		// Get post ID in WP 4.4
		// @since 1.3.1
		//$post_id = get_the_ID();
		//$post_id = $post->ID;
		$comment = get_comment($comment_id);
		$post_id = $comment->comment_post_ID;
		
		if (!wprs_is_enabled($post_id)) return;
		if (wprs_get_type_by_id($post_id) != 'aggregate') return;
		
		// Check if user has submitted a rating
		if (!isset($_POST[ 'rating' ])) return;
		if ($_POST[ 'rating' ] == 0 ) return;
		
		$userrating = $_POST[ 'rating' ];
		
		// Update coment meta
		add_comment_meta( $comment_id, 'rating', $_POST[ 'rating' ] );
		
		if ($_POST[ 'wprs_headline' ] != '' ) {
			add_comment_meta( $comment_id, 'wprs_headline', $_POST[ 'wprs_headline' ] );
		}
		
		// Add extended repeatable meta
		if (get_post_meta($post_id, $wprs_prefix.'repeatable', true)) {
			$i = 0;
			$myarray = get_post_meta($post_id, $wprs_prefix.'repeatable', true);
			foreach($myarray as $key => $element){
				$uid = $element['title'];
				if (isset($_POST[ 'amount_'.$uid ]))
				add_comment_meta( $comment_id, 'item_range_'.$uid, $_POST[ 'amount_'.$uid ] );
				$i++;
			}
		}
		
		// Update userrating array
		// @since 1.0.0
		wprs_update_post_userrating_array($post_id, $userrating);
		
		// Update post meta with fresh data, moved here
		// @since 1.0.0
		wprs_update_post_rating_extended($post_id);
	}	
	add_action( 'comment_post', 'wprs_save_comment_userrating_field' );
    
	

	add_filter( 'preprocess_comment', 'wprs_verify_comment_userrating_meta_data' );
	/*
    	Make data mandatory - user must choose a rating
		@since 1.0.0
    	*/
    function wprs_verify_comment_userrating_meta_data( $commentdata ) {
		
		$id = $commentdata['comment_post_ID'];
		
		if ( wprs_is_enabled($id) && 'aggregate' == wprs_get_type_by_id($id) ) {
			
			$options = get_option('wprs_options');
		
			//if ( !isset($options['wprs_chk_replytocom']) !='') return $commentdata;
			
			$rating = 'on';
			
			if ( empty($_POST['rating']) || $_POST['rating'] == 0  ) $rating = "off";

			if ( $rating == 'off' && isset($options['wprs_chk_user_rating_required']) !='' ) {
 			 
			 	wp_die( __( 'Notice: please choose a rating before you submit your review!<br /><br />Hit the Back button to complete the review.', 'wprs' ) );
			 	exit;
		
			}
		}
		
			return $commentdata;
		
    }
	

	
	/*
    	Display data - user rating in comments
		@since 1.0.0
		*/
	function wprs_attach_comment_userrating_field_to_author( $author ) {
		
		if( is_admin() ) return $author;
		
		global $post;
		
		// Make sure the filter do not run on the main query or main loop
		// this will eliminate filtering sidebar content and widgets
		// @since 1.0.0
		if ( ! in_the_loop() || ! is_main_query() ) return $author;
		
		if ( ! wprs_is_enabled( $post->ID ) ) return $author;
		
		if (wprs_get_type() != 'aggregate') return $author;
		
		$userrating = get_comment_meta( get_comment_ID(), 'rating', true );
		$options = get_option('wprs_options');
		
		// Check if user reviews is enabled
		if ( $userrating && !isset($options['wprs_chk_user_criteria_to_author_display']) !='' ) {
			$author .= '<span class="sr-only">'.$userrating.'</span>';
			$author .= '<span class="wprs_rating rating-comment r-'.$userrating.'" title="'. __('Rating:', 'wprs') .' ' . $userrating . '"></span>';
		}
		
		return $author;
	}
	add_filter( 'get_comment_author_link', 'wprs_attach_comment_userrating_field_to_author' );
	
	
	
	/*
    	Display data - user criteria in single comment
		@since 1.0.0
    	*/
	/*
	function wprs_attach_comment_userrating_criteria_to_author( $content ) {
		
		global $post;
		
		if (!wprs_is_enabled($post->ID)) return $content;
		if (!wprs_get_type() == 'aggregate') return $content;
		
		$options = get_option('wprs_options');
		if ( !isset($options['wprs_chk_user_criteria_to_author_display']) !='' ) return $content;
		
		$userrating = get_comment_meta( get_comment_ID(), 'rating', true );
		$author_criteria = wprs_get_criteria_single($post->ID);
		// check if Thesis theme is active
		$my_theme = wp_get_theme();
		if ( $my_theme->get( 'Name' ) == 'Thesis') {$thesis_class = ' comment_criteria_thesis';} else {$thesis_class = '';}
		
		if ($userrating) {
			$box = '<div class="wprs_comment">';
			$box .= '<div class="wprs_comment_criteria'.$thesis_class.'">'. $author_criteria .'</div>';
			$box .= $content;
			$box .= '<div class="clr"></div>';
			$box .= '</div>';
			return $box;
		} else {
			return $content;
		}
	
	}
	if (!is_admin()) { // render only on front page
		add_filter( 'comment_text', 'wprs_attach_comment_userrating_criteria_to_author', 99 );
		add_filter( 'thesis_comment_text', 'wprs_attach_comment_userrating_criteria_to_author', 99 );
	}
	*/
	
	
	/*
    	Display data - user rating in comments for Genesis 2.0+
		@since 1.0.0
		*/
	function wprs_comment_author_says_text($author) {
		//$theme_name = get_current_theme();
    	//if ($theme_name == 'Genesis') { /* do something */ }
		
		global $post;
		
		if (!wprs_is_enabled($post->ID)) return $author;
		if (!wprs_get_type() == 'aggregate') return $author;
		
		$userrating = get_comment_meta( get_comment_ID(), 'rating', true );
		$options = get_option('wprs_options');
		// Check if user reviews is enabled
		if ( $userrating ) {
			$author .= '<span class="sr-only">'.$userrating.'</span>';
			$author .= '<span class="wprs_rating rating-comment r-'.$userrating.'" title="'. __('Rating:', 'wprs') .' ' . $userrating . '"></span>';
		}
		return $author;
	}
	add_filter( 'comment_author_says_text', 'wprs_comment_author_says_text' );



	/*
    	Disable comment author url
		@since 1.0.0
		*/
	function wprs_disable_comment_url($fields) { 
    	$options = get_option('wprs_options');
		if ( isset($options['wprs_chk_user_comment_url_disable']) ) unset($fields['url']);
    	return $fields;
	}
	add_filter('comment_form_default_fields','wprs_disable_comment_url', 99);

	

	/*
    	Update post meta with user rating data
		this happens whene a new review is added by user
		use function wprs_update_post_rating($postID) 
		@since 1.0.0
    	*/
	function wprs_update_post_rating($postID) {
    	global $wpdb, $wprs_prefix;	
		// Calculate average rating and total ratings								
		$results = $wpdb->get_results( $wpdb->prepare("SELECT ". $wpdb->prefix."commentmeta.meta_value FROM ".$wpdb->prefix."comments
										LEFT JOIN ".$wpdb->prefix."commentmeta
                                        ON ".$wpdb->prefix."comments.comment_ID = ".$wpdb->prefix."commentmeta.comment_id
                                        WHERE ".$wpdb->prefix."comments.comment_post_ID = %d
                                        AND ".$wpdb->prefix."comments.comment_approved = '1'
                                        AND ".$wpdb->prefix."commentmeta.meta_key = 'rating'
                                        AND ".$wpdb->prefix."commentmeta.meta_value != 0
                                        GROUP BY ".$wpdb->prefix."commentmeta.comment_id", $postID, null));
        if (count($results) == 0) {
			$countRatings = 0;
        	$averageRating = 0;
        } else {
			$countRatings = count($results);
	        foreach ($results as $key=>$result) $countRating += $result->meta_value;
			$averageRating = (($countRatings == 0 OR $countRating == 0) ? 0 : round(($countRating / $countRatings), 2, 0));
        }
		// Update post meta
        update_post_meta($postID, $wprs_prefix.'userrating_average', $averageRating);
		update_post_meta($postID, $wprs_prefix.'userrating_count', $countRatings);
        return true;
    }

	
	/*
    	Update post meta with user rating data (extended data)
		this happens whener a new review is added by user
		use function wprs_update_post_rating_extended($postID) 
		@since 1.0.0
    	*/
	function wprs_update_post_rating_extended($postID) {
    	global $wpdb, $wprs_prefix;	
		// Calculate average rating and total ratings
       $results = $wpdb->get_results( $wpdb->prepare("SELECT ". $wpdb->prefix."commentmeta.meta_value FROM ".$wpdb->prefix."comments
										LEFT JOIN ".$wpdb->prefix."commentmeta
                                        ON ".$wpdb->prefix."comments.comment_ID = ".$wpdb->prefix."commentmeta.comment_id
                                        WHERE ".$wpdb->prefix."comments.comment_post_ID = %d
                                        AND ".$wpdb->prefix."comments.comment_approved = '1'
                                        AND ".$wpdb->prefix."commentmeta.meta_key = 'rating'
                                        AND ".$wpdb->prefix."commentmeta.meta_value != 0
                                        GROUP BY ".$wpdb->prefix."commentmeta.comment_id", $postID, null));
		if (count($results) == 0) {
			$countRatings = 0;
			$countRating = 0;
        	$averageRating = 0;
			$ratings_array = array();
        } else {
			$countRatings = count($results);
			$countRating = 0;
			$ratings_array = array();
			$ratings_array = array(
								5	=>	0,
								4	=>	0,
								3	=>	0,
								2	=>	0,
								1	=>	0
							);
							
	        foreach ($results as $key => $result) {
				$countRating += $result->meta_value;
				$ratings_array[$result->meta_value] = $ratings_array[$result->meta_value] + 1;
			}
			
			$averageRating = (($countRatings == 0 OR $countRating == 0) ? 0 : round(($countRating / $countRatings), 2,0));
        
		}
		// Update post meta
        update_post_meta($postID, $wprs_prefix.'userrating_average', $averageRating);
		update_post_meta($postID, $wprs_prefix.'userrating_count', $countRatings);
		update_post_meta($postID, $wprs_prefix.'userrating_array', $ratings_array);
		
		// Get repeatable
		if (get_post_meta($postID, $wprs_prefix.'repeatable', true)) {
			$i = 0;
			$out ='';
			$key = 0;
			$myarray = get_post_meta($postID, $wprs_prefix.'repeatable', true);
			foreach($myarray as $key => $element){
				$countRating = 0;
				$comment_meta_id = 'item_range_'.$element['title'];
				$post_meta_id = $wprs_prefix.'userrating_criteria_'.$element['title'];
				// Calculate average rating and total ratings
        		$results = $wpdb->get_results( $wpdb->prepare("SELECT ". $wpdb->prefix."commentmeta.meta_value FROM ".$wpdb->prefix."comments
										LEFT JOIN ".$wpdb->prefix."commentmeta
                                        ON ".$wpdb->prefix."comments.comment_ID = ".$wpdb->prefix."commentmeta.comment_id
                                        WHERE ".$wpdb->prefix."comments.comment_post_ID = %d
                                        AND ".$wpdb->prefix."comments.comment_approved = '1'
                                        AND ".$wpdb->prefix."commentmeta.meta_key = '".$comment_meta_id."'
                                        AND ".$wpdb->prefix."commentmeta.meta_value != 0
                                        GROUP BY ".$wpdb->prefix."commentmeta.comment_id", $postID, null));
										
				if (count($results) == 0) {
					$countRatings = 0;

        			$averageRating = 0;
        		} else {
					$countRatings = count($results);
	        		//foreach ($results as $key=>$result) $countRating += $result->meta_value;
					foreach ($results as $key=>$result) $countRating += $result->meta_value;
					$averageRating = (($countRatings == 0 OR $countRating == 0) ? 0 : round(($countRating / $countRatings), 0,0));
        		}
				// Update post meta
        		update_post_meta($postID, $post_meta_id, $averageRating);
				//update_post_meta($postID, $uid.'_count', $countRatings);
			}
		}
		
        return true;
    }


	/*
    	Update post meta with user rating data on demand
		this function is called within the plugin settings page
		@since 1.0.0
    	*/
	function wprs_update_user_rating() {
		global $wpdb;
		
		// @since 1.0.0.8.1
		$querydetails = "
			SELECT wposts.*
			FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
			WHERE wposts.ID = wpostmeta.post_id
			AND wposts.post_status = 'publish'
			AND wpostmeta.meta_key = '_wprs_post_review_type'
			ORDER BY wposts.post_date DESC
			";
		
		$pageposts = $wpdb->get_results($querydetails, OBJECT);
		foreach($pageposts as $p) :
			// Update post meta with fresh data
			//wprs_update_post_rating($p->ID);
			wprs_update_post_rating_extended($p->ID);
		endforeach;
		wp_reset_postdata();
	}
	
	
	add_action('transition_comment_status', 'wprs_approve_comment_callback', 10, 3);
	/*
		Update post meta with user rating data when a comment is approved
		@since 1.0.0
		*/
	function wprs_approve_comment_callback($new_status, $old_status, $comment) {
		if($old_status != $new_status) {
			if($new_status == 'approved') {
				wprs_update_user_rating();
			}
		}
	}
	
	/*
    	Update all criteria fields on demand
		this function is called within the plugin settings page
		@since 1.0.0
		*/
	function wprs_update_criteria() {
		
		global $wprs_prefix;
		
		$posts = get_posts(array(
					//'numberposts' => 18446744073709551615,
					'numberposts' => -1,
					'meta_key'	=> $wprs_prefix.'repeatable'
				));
		
		$wprs_options = get_option('wprs_options');
		
		if ( isset($wprs_options['wprs_repeatable']) && $wprs_options['wprs_repeatable'] ) {
			
			$repeated_meta = $wprs_options['wprs_repeatable'];
			
			if ( $repeated_meta ) {
			
				foreach($posts as $p) :
				
					$old_meta = get_post_meta($p->ID, $wprs_prefix.'repeatable', true);
					// remove the old meta
					delete_post_meta($p->ID, $wprs_prefix.'repeatable', $old_meta);
					// add the new meta
					add_post_meta($p->ID, $wprs_prefix.'repeatable', $repeated_meta, true) or 
					// update the new meta
					update_post_meta($p->ID, $wprs_prefix.'repeatable', $repeated_meta);
				
			endforeach;
			}
		
		}
	}
	
	
	add_action( 'add_meta_boxes_comment', 'wprs_userrating_admin_add_meta_box' );
	/*
    	Add comment meta box to the edit comment page in admin
		@since 1.0.0
		*/
	function wprs_userrating_admin_add_meta_box() {
		add_meta_box( 'wprs_userrating', __( 'Review', 'wprs' ), 'wprs_userrating_admin_meta_box_cb', 'comment', 'normal', 'high' );
	}
	
	/*
    	Comment meta box call back
		@since 1.0.0
		*/
	function wprs_userrating_admin_meta_box_cb( $comment ) {
		
		global $post, $wprs_prefix;
		
		$headline = get_comment_meta( $comment->comment_ID, 'wprs_headline', true );
		$userrating = get_comment_meta( $comment->comment_ID, 'rating', true );
		wp_nonce_field( 'userrating_comment_update', 'userrating_comment_update', false );
		?>
		<p>
			<label for="wprs_headline"><?php _e( 'Headline', 'wprs' ); ?></label>
			<input type="text" name="wprs_headline" value="<?php echo esc_attr( $headline ); ?>" class="widefat" />
		</p>
        <p>
			<label for="rating"><?php _e( 'Rating', 'wprs' ); ?></label>
			<input type="text" name="rating" value="<?php echo esc_attr( $userrating ); ?>" class="widefat" />
		</p>
		<?php
		
		// add extended repeatable meta
		if (get_post_meta($comment->comment_post_ID, $wprs_prefix.'repeatable', true)) {
			$i = 0;
			$myarray = get_post_meta($comment->comment_post_ID, $wprs_prefix.'repeatable', true);
			foreach($myarray as $key => $element){
				$uid = $element['title'];
				$range_value = get_comment_meta( $comment->comment_ID, 'item_range_'.$uid, true );
				?>
				<p>
					<label for="<?php echo 'item_range_'.$uid; ?>"><?php _e( $element['title'] ); ?></label>
					<input type="text" name="<?php echo 'item_range_'.$uid; ?>" value="<?php echo esc_attr( $range_value ); ?>" class="widefat" />
				</p>
        		<?php
				$i++;
			}
		}
	}
	
	
	add_action( 'edit_comment', 'wprs_userrating_admin_edit_comment' );
	/*
    	Update comment meta box value
		@since 1.0.0
		*/
	function wprs_userrating_admin_edit_comment( $comment_id ) {

		global $post, $wprs_prefix;
	
		if (!isset($_POST['userrating_comment_update']) || !wp_verify_nonce($_POST['userrating_comment_update'], 'userrating_comment_update')) return;
		
		// Update userrating
		if( isset( $_POST['wprs_headline'] ) )
        	update_comment_meta( $comment_id, 'wprs_headline', esc_attr( $_POST['wprs_headline'] ) );
			
		// Update userrating
		if( isset( $_POST['rating'] ) )
        	update_comment_meta( $comment_id, 'rating', esc_attr( $_POST['rating'] ) );
		
		// Update extended repeatable meta
		$comment = get_comment( $comment_id ); 
		if (get_post_meta($comment->comment_post_ID, $wprs_prefix.'repeatable', true)) {
			$i = 0;
			$myarray = get_post_meta($comment->comment_post_ID, $wprs_prefix.'repeatable', true);
			foreach($myarray as $key => $element){
				$uid = $element['title'];
				if( isset( $_POST[ 'item_range_'.$uid ] ) )
		        	update_comment_meta( $comment_id, 'item_range_'.$uid, esc_attr( $_POST[ 'item_range_'.$uid ] ) );
				$i++;
			}
		}
	}
	
	
	/*
    	Get IP Address
		@since 1.0.0
		*/
	if(!function_exists('wprs_get_ip')) {
		function wprs_get_ip() {
			if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
				$ip_address = $_SERVER['HTTP_CLIENT_IP'];
			} else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} else if(!empty($_SERVER['REMOTE_ADDR'])) {
				$ip_address = $_SERVER['REMOTE_ADDR'];
			} else {
				$ip_address = '';
			}
			if(strpos($ip_address, ',') !== false) {
				$ip_address = explode(',', $ip_address);
				$ip_address = $ip_address[0];
			}
			return esc_attr($ip_address);
		}
	}

	
	/*
		Check if user has added a review/rating before by checking comment IP address,
		this will return rating and message, or false
		@since 1.0.0
		*/
	function wprs_check_if_can_rate_ip($postID) {
		// Get plugin options
		$options = get_option('wprs_options');
		// Check if enabled in plugin settings
		if ( isset($options['wprs_chk_user_rating_enable']) !=''
			&& isset($options['wprs_chk_user_rating_visitors_enable']) != ''
			&& isset($options['wprs_chk_user_rating_ip']) != ''
			) {
			// Get user IP address
			$ip = wprs_get_ip();
			// Comment args
			$args = array(
				'post_id' => $postID,				// Use post_id, not post_ID
				'status' => 'approve',				// Only approved
				'number' => '',						// Get all
				'meta_key' => 'rating',				// Has user rating
				'comment_author_IP' => $ip,			// Return all	
			);
		// Get comments
		$comments = get_comments($args);
		$info = '';
		foreach($comments as $comment) :
			$userrating = get_comment_meta( $comment->comment_ID, 'rating', true );
			// Check if user has added a review/rating before
			// We will run through all comments that has same IP and meta key: userrating
			if ($comment->comment_author_IP == $ip && $userrating !='' && $userrating !=0) {
				$rating_display = str_replace('.', '', $userrating);
				$info .= '<span class="wprs_rating rating-comment already-rating-comment r-'.$rating_display.'" title="'. __('Rated', 'wprs') . ' ' . $userrating . '"></span>';
				$info .= ' '. __('You have already added a rating!', 'wprs');
				return $info;
			}
		endforeach;
		}
		return false;
	}


