<?php
/**
 * Plugin Name: Rating Events add-on for Calendarize it!
 * Plugin URI: http://calendarize.it/add-ons/rsvp-events-for-calendarize-it/
 * Description: Ratings and Reviews Events add-on for Calendarize it! allows your visitors to Rate and Review an Events in your calendar. Easily Rating and Reviewing using Facebook Connect and Twitter Connect.
 * Version: 1.1.6.82867
 * Author: RightHere LLC
 *Author URI: http://plugins.righthere.com
 */

if ( defined( 'RHCRATING_PATH' ) ) {
	throw new Exception( __( 'A duplicate of this add-on/plugin is already active.', 'rhc' ) );
}

define( 'RHCRATING_VERSION', '1.1.6' );
define( 'RHCRATING_SLUG', plugin_basename( __FILE__ ) );
 
if ( defined( 'RHC_ADDON_PATH' ) && isset( $addon ) && ! strpos( __FILE__, 'plugins' ) ) {
	define( 'RHCRATING_PATH', trailingslashit( RHC_ADDON_PATH . dirname( $addon ) ) ); 
	define( 'RHCRATING_URL', trailingslashit( RHC_ADDON_URL . dirname( $addon ) ) );
	define( 'RHCRATING_LANGUAGE', plugin_righthere_calendar::get_relative_path( WP_PLUGIN_DIR, RHCRATING_PATH ) . 'languages/' );
} else {
	define( 'RHCRATING_PATH', plugin_dir_path( __FILE__ ) );
	define( 'RHCRATING_URL', plugin_dir_url( __FILE__ ) );
	define( 'RHCRATING_LANGUAGE', RHCRATING_PATH . 'languages/' );
}
 
class plugin_rhc_rating {
	public $count = 0;
	public $settings = '';
	
	function __construct() {	
		global $rhc_plugin;
	
		add_action( 'plugins_loaded', array( $this,'plugins_loaded' ), 999999 );
		add_action( 'admin_menu', array( $this, 'register_my_custom_menu_page' ) );
		add_action( 'admin_menu', array( $this, 'my_remove_menu_pages') );
		add_action( 'after_setup_theme', array( $this, 'after_setup_theme'), 20 );

		if ( ! empty( $rhc_plugin ) ) {
			rh_register_php( 'social-connection', RHCRATING_PATH . 'social_connection/class.SocialConnection.php', '1.0.1' );
		}

		add_shortcode( 'rhc_rar', array( $this, 'handle_shortcode' ) );
		add_action( 'rhc_vc_before_init', array( $this, 'rhc_vc_before_init' ) );
	}
	
	function handle_shortcode($atts, $template='', $code=""){
		global $post;//frontend uses post to work
		if( is_object( $post ) && property_exists( $post, 'ID' ) ){
			include_once(RHCRATING_PATH.'inc/frontend.php');
			$return_box = new frontend_rhc_rating_box();			
			return $return_box->return_data();				
		}
		return '';
	}
	
	function rhc_vc_before_init(){
		$vc_category = "Calendarize It!";
		$scripts = array();
		$styles = array();
		vc_map( array(
			"name" 				=> __( "Ratings and reviews", "rhc" ),
			"base" 				=> "rhc_rar",
			"category" 			=> $vc_category,
			"description"		=> __("Add ratings and reviews box.","rhc"),
			"params" 			=> array(),
			"show_settings_on_create" => false,	
			"admin_enqueue_js" 	=> $scripts,
			"admin_enqueue_css" => $styles,
			"front_enqueue_js" 	=> $scripts,
			"front_enqueue_css" => $styles
		)); // calendarizeit	
	}
	
	function after_setup_theme(){
		global $rhc_plugin;
			
		
		if(!empty($rhc_plugin) && class_exists('SocialConnection')){
			do_action('rh-php-commons');
	
			$settings = array(
				'options_capability'	=> $rhc_plugin->options_capability,
				'option_menu_parent'	=> 'edit.php?post_type='.RHC_EVENTS,		
				'stylesheet'			=> 'rhc-options',
				'path'					=> RHCRATING_PATH.'social_connection/',
				'url'					=> RHCRATING_URL.'social_connection/',				
				'pop_path'				=> RHC_PATH.'options-panel/',
				'pop_url'				=> RHC_URL.'options-panel/',
				'networks'				=> array('googleplus','facebook','linkedin','twitter')
			);
			$sco = new SocialConnection($settings);
		}
	}	
			
	function plugins_loaded() {
		load_plugin_textdomain( 'rhcrating', false, RHCRATING_LANGUAGE );

		$this->install();
		$this->settings = $settings_tmp = get_option('rhc_rating_options');
		
		require_once( RHCRATING_PATH . 'inc/uh_social/social_connection.php' );

		if(is_admin()){
			if(!empty($settings_tmp['overwritealleventpost'])){
				global $wpdb;
				$get_list_date = $wpdb->get_results("SELECT ID FROM {$wpdb->prefix}posts WHERE post_type='events'");				
				
				if(!empty($get_list_date)){
					$tmpss = true;
					
					if($settings_tmp['overwritealleventpost'] == 'no'){
						$tmpss = false;	
					} else if($settings_tmp['overwritealleventpost'] == 'yes'){
						$tmpss = true;	
					}

					foreach($get_list_date as $tmp_run){
						update_post_meta($tmp_run->ID,'enable_rhc_rating_box',$tmpss);
					}
				}
				
				$settings_tmp['overwritealleventpost'] = '';
				update_option('rhc_rating_options',$settings_tmp);
			}
		
			
			add_action("admin_head",array(&$this,'admin_init'));
			add_action('save_post', array(&$this,'save_post') );	
			add_action("admin_print_scripts-post-new.php",array(&$this,'admin_script'));
			add_action("admin_print_scripts-post.php",array(&$this,'admin_script'));
			add_filter( 'page_row_actions', array( &$this, 'remove_row_actions'), 10, 2 );
			add_action('quick_edit_custom_box',  array( &$this, 'add_quick_edit'), 999, 2);
			add_action('admin_footer', array( &$this, 'quick_edit_javascript'));
			
			
			
			do_action('rh-php-commons');	
			
			require_once RHCRATING_PATH.'inc/class.panel_settings.php';
			new rhc_rating_settings('rhc_rating');
			
			$settings = array(
				'id'					=> 'rhc_rating',
				'plugin_id'				=> 'rhc',
				'capability'			=> 'rhc_options',
				'options_varname'		=> 'rhc_rating_options',
				'menu_id'				=> 'rhc_rating-options',
				'page_title'			=> __('Ratings and Reviews','rhcrating'),
				'menu_text'				=> __('Ratings and Reviews','rhcrating'),
				'option_menu_parent'	=> 'edit.php?post_type='.RHC_EVENTS,
				'theme'					=> false,
				'extracss'				=> 'extracss-rhc-rating',
				'fileuploader'			=> true,
				'stylesheet'			=> 'rsvp-options',
				'option_show_in_metabox'=> true,
				'pluginurl'				=> RHCRATING_URL,
				'pluginslug'	=> RHCRATING_SLUG,
				'api_url' 		=> "http://plugins.righthere.com",
				'autoupdate'	=> false,
				'path'			=> RHC_PATH.'options-panel/',
				'url'			=> RHC_URL.'options-panel/'				
			);
			
			if( class_exists('PluginOptionsPanelModule')){
				new PluginOptionsPanelModule($settings);
			}					
		} else {
			$this->intercept_data();
			
			
			if(empty($settings_tmp['rating_allow_on_wp_users']) or (!empty($settings_tmp['rating_allow_on_wp_users']) and is_user_logged_in())){
			
				if(current_user_can('rating_read_list') || current_user_can('manage_options')){
					add_action( 'admin_bar_menu', array(&$this,'toolbar_link_to_mypage'), 999 );
				}
				
				add_filter('the_events_content',array(&$this,'the_content'),10);	
			}
		
			
			add_action( 'wp_enqueue_scripts', array(&$this,'script') );
			add_action( 'wp_enqueue_scripts', array(&$this,'stylesheet') );
		}
	}			
	
	// -----------------------------------------------------------------------------------------	
	// Front End -----------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------
	
	function toolbar_link_to_mypage( $wp_admin_bar ) {
		global $post;
		if($this->check_post_type()){
		
			$pagetype = 'post_type=events&';
			if(!current_user_can('manage_options') && current_user_can('rating_read_list') ){
				$pagetype = '';
			} 		
		
		    if(!empty($_GET['event_rdate'])){
			    $_REQUEST['event_rdate'] = $_GET['event_rdate'];
		    } else if(!empty($_POST['event_rdate'])){
		    	$_REQUEST['event_rdate'] = $_POST['event_rdate'];
		    } else if(!empty($post->ID)){
				$retrive_event_rdate = get_post_meta($post->ID,'fc_start_datetime',true);
				$retrive_event_rdate .= ','.get_post_meta($post->ID,'fc_end_datetime',true); 
				$_REQUEST['event_rdate'] = str_replace(array('-',' ',':'), array('','',''), $retrive_event_rdate);
			}	
		
			$wp_admin_bar->add_menu( array(
				'id'    => 'rating_list',
				'title' => __('Rating','rhcrating'),
				'meta'  => array( 'class' => 'my-toolbar-page' )
			));
			
			$wp_admin_bar->add_menu( array(
				'id' => 'rating_list_backend',
				'parent' => 'rating_list',
				'title' => __('Rating and Review list','rhcrating'),
				'href' => admin_url( 'edit.php?'.$pagetype.'page=rhc-rating-list&postID='.$post->ID.'&event_rdate='.$_REQUEST['event_rdate']),
				'meta' => array( 'class' => 'my-toolbar-page' )
			) );	
		}
	}	


    function script() {
    	global $post;
    
	    if($this->check_post_type()){
	        $settings = get_option('rhc_rating_options');
			
	        wp_register_script( 'rhc_rating_front', RHCRATING_URL . 'js/front.js', array( 'jquery' ) ,date('Ymd.his') );
	        
	        
			$retrive_event_rdate = '';
			if(!empty($_REQUEST['event_rdate'])){     
				$retrive_event_rdate = $this->rating_mysql_real_escape_string($_REQUEST['event_rdate']);
			} else if(!empty($post->ID)){
				$retrive_event_rdate = get_post_meta($post->ID,'fc_start_datetime',true);
				$retrive_event_rdate .= ','.get_post_meta($post->ID,'fc_end_datetime',true); 
				$retrive_event_rdate = str_replace(array('-',' ',':'), array('','',''), $retrive_event_rdate);
			}
			
			
			$permalink = get_permalink($post->ID);
			

			if (strpos($permalink, '?') === false) {
			    $permalink .= '?event_rdate='.$retrive_event_rdate;
			} else {
			    $permalink .= '&event_rdate='.$retrive_event_rdate;
			}
			
			
			$attachment_id = get_post_meta( $post->ID, 'rhc_tooltip_image', true);
			$thumbnail = '';
			if(empty($attachment_id) && !is_numeric($attachment_id)){
				$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID));		
			}else{
				$thumbnail=wp_get_attachment_image_src( $attachment_id, array(64,64));
			}
			
			if(!empty($thumbnail)){
				$thumbnail= $thumbnail[0];
			}
				
			if(empty($settings['rating_public_facebook_text'])){
				$settings['rating_public_facebook_text'] = '[EXCERPT]';
			}
			
			if(empty($settings['rating_public_facebook_title'])){
				$settings['rating_public_facebook_title'] = 'I just gave [RATING] stars to this event [TITLE]';
			}
			
			if(empty($settings['rating_public_facebook_subtitle'])){
				$settings['rating_public_facebook_subtitle'] = '[STARTDATE] @ [STARTTIME]';
			}	
			
			
			if(empty($settings['rating_facebook_publish'])){
				$settings['rating_facebook_publish'] = false;
			}	
			
			
			$fc_start_time = get_post_meta( $post->ID, 'fc_start_time', true );
			if(empty($fc_start_time)){
				$fc_start_time = '00:00';
			}
			
			$exception = $this->get_the_excerpt($post->ID);
			
			if(!empty($retrive_event_rdate)){
				$star_date = explode(',', $retrive_event_rdate);
				$star_date = $star_date[0];
				$star_date = date('F j, Y',strtotime($star_date));
			} else {
				$star_date = '';
			}
	        
	        
	        
			$ical_feed = site_url().'/?rhc_action=get_icalendar_events&ID='.$post->ID;
			$posttile = get_the_title($post->ID);
			$settings['rating_public_facebook_title'] = str_replace(array('[LINK]','[TITLE]','[STARTDATE]','[STARTTIME]','[EXCERPT]','[ICAL_FEED]'),array($permalink,$posttile,$star_date,$fc_start_time,$exception,$ical_feed),$settings['rating_public_facebook_title']);
			$settings['rating_public_facebook_subtitle'] = str_replace(array('[LINK]','[TITLE]','[STARTDATE]','[STARTTIME]','[EXCERPT]','[ICAL_FEED]'),array($permalink,$posttile,$star_date,$fc_start_time,$exception,$ical_feed),$settings['rating_public_facebook_subtitle']);			
			$settings['rating_public_facebook_text'] = str_replace(array('[LINK]','[TITLE]','[STARTDATE]','[STARTTIME]','[EXCERPT]','[ICAL_FEED]'),array($permalink,$posttile,$star_date,$fc_start_time,$exception,$ical_feed),$settings['rating_public_facebook_text']);	
	        
	        wp_localize_script('rhc_rating_front', 'rhc_rating_vars', array('siteurl' => get_site_url(),
																'event_rdate' => $retrive_event_rdate,
	        													'link' => $permalink,
	        													'picurl' => $thumbnail,
	        													'post_id' => $post->ID,
	        													'fb_pub' => $settings['rating_facebook_publish'],
	        													'fb_tw_text' => $settings['rating_public_facebook_text'],
	        													'fb_tw_subtitle' => $settings['rating_public_facebook_subtitle'],
																'fb_tw_title' => $settings['rating_public_facebook_title'],
	        													'pleaseRate' => __('Please rate this event','rhcrating'),
	        													'pleaseLastName' => __('Please fill in your last name','rhcrating'),
																'pleaseFirstName' => __('Please fill in your first name','rhcrating'),
																'pleaseValitEmail' => __('Please enter a valid email','rhcrating'),
																'previousEventRating' => __('Filter Events','rhcrating'),
																'overskrift0' => __('Be the first to rate and review','rhcrating'),
																'overskrift1' => __('Thank you for <span id="display_big_count">0</span> rating','rhcrating'),
																'overskrift2' => __('Thank you for <span id="display_big_count">0</span> ratings','rhcrating')));  
	        
	        wp_enqueue_script( 'rhc_rating_front');
	  
	        wp_register_script( 'flatui-checkbox', RHCRATING_URL . 'css/flat-ui/js/flatui-checkbox.js','','3.0.0' );
	        wp_enqueue_script( 'flatui-checkbox' );
	        
	        wp_register_script( 'animateNumber', RHCRATING_URL . 'js/jquery.animateNumber.js','','0.1' );
	        wp_enqueue_script( 'animateNumber' );
        }
    }
    
    
    function stylesheet() {
	    if($this->check_post_type()){
	        wp_register_style( 'bootstrap_rhc_rsvp', RHCRATING_URL.'css/bootstrap/css/bootstrap.css','','3.0.0' );
	        wp_enqueue_style( 'bootstrap_rhc_rsvp' );	    
	        
	        wp_register_style( 'flat-ui', RHCRATING_URL.'css/flat-ui/css/flat-ui.css','','1.2.1' );
	        wp_enqueue_style( 'flat-ui' );	        
	        
	        wp_register_style( 'frontendrating_box', RHCRATING_URL.'css/frontend.css' );
	        wp_enqueue_style( 'frontendrating_box' );
        }
    }
	
	
	function the_content($content){
		global $post;
		if($this->check_post_type() and !empty($post->ID)){
			$get_value = get_post_meta($post->ID,'enable_rhc_rating_box',true);
			if($get_value){
				include_once(RHCRATING_PATH.'inc/frontend.php');
				$return_box = new frontend_rhc_rating_box();			
				$return_box = $return_box->return_data();	

				if(!empty($return_box)){
					$content .= $return_box;
				}
			}
		}
		return $content;
	}
	
	// -----------------------------------------------------------------------------------------	
	// Backend End -----------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------

	function add_quick_edit($column_name, $post_type) {
		if(!$this->check_post_type()) return false;
		
		if($column_name != 'fc_start') return false;
	    ?>
	    <fieldset class="inline-edit-col-right">
			<div class="inline-edit-group">
				<label class="alignleft">
						<input type="checkbox" value="true" id="rhc_rating_box" class="rhc_rating_box" name="rhc_rating_box">
						<span class="checkbox-title"><?php echo __('Rating Box','rhcrating'); ?></span>
				</label>
			</div>
		</fieldset>
	    <?php
	}
	
	function quick_edit_javascript() {
	    ?>
	    <script type="text/javascript">
	    
	    jQuery( document ).on( "mouseleave", "a.editinline", rhc_rating_inline_widget_set ); // jQuery 1.7+
	    function rhc_rating_inline_widget_set() {
	    	tmp = jQuery(this).parent().parent().parent().parent().attr('id');
	    	tmp=tmp.replace("post-","");
			setTimeout(function() {
	    	if(jQuery('.post-'+tmp+' .rhc_rating_box_data').val()!= 'undefined' && (jQuery('.post-'+tmp+' .rhc_rating_box_data').val()== 'true' || jQuery('.post-'+tmp+' .rhc_rating_box_data').val()== true || jQuery('.post-'+tmp+' .rhc_rating_box_data').val() == 1)){
		    	jQuery('#edit-'+tmp+' .rhc_rating_box').attr('checked', true);
	    	} else {
		    	jQuery('#edit-'+tmp+' .rhc_rating_box').removeAttr('checked');
		    	console.log('bbb');
	    	}
	    	},120);
	    }
	    </script>
	    <?php
	}



	function register_my_custom_menu_page(){
		if(current_user_can('manage_options') ){
			add_submenu_page(('edit.php?post_type=events'),__('Rating List','rhcrating'), __('Rating List','rhcrating'), 'manage_options',('rhc-rating-list'), array(&$this,'show_list') );
		} else {
			add_submenu_page(('edit.php'),__('Rating List','rhcrating'), __('Rating List','rhcrating'), 'rating_read_list',('rhc-rating-list'), array(&$this,'show_list') );
		}	  
	}

	function my_remove_menu_pages() {
	    global $submenu;
	    
		$pagetype = '?post_type=events';
		if(!current_user_can('manage_options') && current_user_can('rating_read_list') ){
			$pagetype = '';
		} 
	    
	    if(!empty($submenu['edit.php'.$pagetype])){
		    foreach($submenu['edit.php'.$pagetype] as $tmp_key => $tmp_tag){
			    if($tmp_tag[0] == __('Rating List','rhcrating')){
				    unset($submenu['edit.php'.$pagetype][$tmp_key]);
				    break;
			    }
		    }
		}
	}
	
	function show_list(){
		global $wpdb;
	
		$return_data_content = '';

		if(!empty($_GET['ratingid']) && is_numeric($_GET['ratingid']) && isset($_GET['delete']) && $_GET['delete'] == 'true'){
				$wpdb->delete( $wpdb->prefix.'rhc_rating', array( 'id' => $_GET['ratingid'] ), array( '%d' ) );
		}
		
		if(!empty($_GET['ratingid']) && is_numeric($_GET['ratingid']) && isset($_GET['change_allow']) && $_GET['change_allow'] == 'true'){
			$wpdb->update( 
				$wpdb->prefix.'rhc_rating', 
				array( 
					'show' => $_GET['status']
				), 
				array( 'ID' => $_GET['ratingid'] ), 
				array( 
					'%d'
				), 
				array( '%d' ) 
			);	
		}
		
		$pagetype = 'post_type=events&';
		if(!current_user_can('manage_options') && current_user_can('rating_read_list') ){
			$pagetype = '';
		} 
		
		
	
		if(!empty($_GET['postID'])){
			$option_settings = get_option('rhc_rating_options');
		
		
			if(empty($option_settings['rating_accept_inputs'])){
				$option_settings['rating_accept_inputs'] = false;
			}
		
		
		
		
			$current_dato_minusweeks = date('Ymdhis',strtotime("-4 week"));
		 	$get_date_type = $wpdb->get_results("SELECT event_date FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID']." group by event_date order by event_date ");
			$show_arrows = false;
			$show_arrows_forward = false;	
			$tmp_content = '';
			$count = 0;
			if(!empty($get_date_type)){
				foreach($get_date_type as $tmp_key => $tmpsql){
					$tmp = explode(',',$tmpsql->event_date);
					$tmp_show = false;
					$active = false;
					
					if(!empty($_REQUEST['event_rdate']) && $tmpsql->event_date == $_REQUEST['event_rdate']){
						$active = true;
						$tmp_show = true;
					}
					
					
					if($tmp[0]<$current_dato_minusweeks && $tmp_show != true && count($get_date_type) > 5) {
						$tmp_show = false;
						$show_arrows = true;
					} else{
						$tmp_show = true;
					}
					
					
					
					if($tmp_show){
						$count++;
					}
					
					if($count > 5 && !$active){
						$show_arrows_forward = true;
						$tmp_show = false;					
					}

					$tmp_content .= '<a class="item button button-large '.($active == true ? 'button-primary':'action').'" style="margin-right:10px;margin-top:10px;'.($tmp_show == true?'':'display:none;').'" href="?'.$pagetype.'page=rhc-rating-list&postID='.$_GET['postID'].'&event_rdate='.$tmpsql->event_date.'">'.date('F j, Y',strtotime($tmp[0])).'</a>';
				}
			}
		
			if(!empty($_REQUEST['event_rdate'])){
				$rating_count = $wpdb->get_var( "SELECT COUNT(id) FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID'] . " and event_date='".$this->rating_mysql_real_escape_string($_REQUEST['event_rdate'])."' ");
				$rating = $wpdb->get_var( "SELECT sum(rating) FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID'] ." and event_date='".$this->rating_mysql_real_escape_string($_REQUEST['event_rdate'])."'");
			} else {
				$rating_count = $wpdb->get_var( "SELECT COUNT(id) FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID']);
				$rating = $wpdb->get_var( "SELECT sum(rating) FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID']);
			}
			
			$rating_score = 0;
			
			if(empty($rating_count)){
				$rating_count = 0;
			}
			
			if(!empty($rating_count)){
				$rating_score = $rating/$rating_count;
			}
		
			$return_data_content .= '<div class="wrap"><div class="icon32" id="icon-options-general"><br></div><h2>'.__('Rating list for event','rhcrating').' "'.get_the_title($_GET['postID']).'" (id:'.$_GET['postID'].')</h2>';
			
			$return_data_content .= '<span style="margin-left:45px">'.__('Rating score','rhcrating').': '.number_format($rating_score, 2, '.', ' ').' | '.__('Number of rating','rhcrating').': '.$rating_count.'</span>';
			
			
			$return_data_content .= '<div style="margin-top:10px;margin-left: 5px;" id="kalenderdatebuttom">';
			
			if($show_arrows){
				$return_data_content .= '<a class="button button-large action" href="#" style="margin-right:10px;margin-top:10px;" onclick="rsvp_show_back(this);return false;"><<</a>';
			}
			
			if(empty($_REQUEST['event_rdate'])){
			$return_data_content .= '<a class="button button-large button-primary" style="margin-right:10px;margin-top:10px;" href="?'.$pagetype.'page=rhc-rating-list&postID='.$_GET['postID'].'">All</a>';
			} else {
				$return_data_content .= '<a class="button button-large action" style="margin-right:10px;margin-top:10px;" href="?'.$pagetype.'page=rhc-rating-list&postID='.$_GET['postID'].'">All</a>';
			}
			
			$return_data_content .= $tmp_content;
			
			if($show_arrows_forward){
				$return_data_content .= '<a class="button button-large action" href="#" style="margin-right:10px;margin-top:10px;" onclick="rsvp_show_forword(this);return false;">>></a>';
			}
			
			
			$return_data_content .= '</div>';
			
			
				
			if(empty($_REQUEST['event_rdate'])){
				$_REQUEST['event_rdate'] = 0;
			}	
				
			if(!empty($_REQUEST['event_rdate'])){
				$get_list_date = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID']."  and event_date='".$this->rating_mysql_real_escape_string($_REQUEST['event_rdate'])."' order by ".($option_settings['rating_accept_inputs'] == true ? "`show` ASC ,":"")." cDate DESC");
			} else {
				$get_list_date = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_GET['postID']." order by ".($option_settings['rating_accept_inputs'] == true ? "`show` ASC ,":"")." cDate DESC");
				
							
				
			}
			
			$return_data_content .= '<div style="left: 5px; bottom: 0px; margin-right: 20px; overflow: auto; position: relative; margin-top: 15px;"><table class="wp-list-table widefat fixed posts" cellspacing="0"><thead><tr>';
			$return_data_content .= '<th class="manage-column column-author column-comments" style="padding-left: 10px;">'.__('Count','rhcrating').'</th>';
			$return_data_content .= '<th class="manage-column column-author column-comments" scope="col">'.__('Pic','rhcrating').'</th>';
			$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Name','rhcrating').'</th>';
			$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Email','rhcrating').'</th>';
			$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Login Type','rhcrating').'</th>';
			$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Rating','rhcrating').'</th>';
			$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Time','rhcrating').'</th>';
	
			if(!empty($option_settings['rating_accept_inputs'])){
				if(current_user_can('manage_options') || current_user_can('rating_approvel') ){
					$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Show','rhcrating').'</th>';
				} else {
					$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Show','rhcrating').'<br><small>(No permission to change)</small></th>';
				}		
			}
			
			$return_data_content .= '<th class="manage-column column-title" scope="col">'.__('Comment','rhcrating').'</th>';
			
			

			$return_data_content .= '<th class="manage-column column-author column-comments" scope="col">'.__('Tools','rhcrating').'</th>';
	
			
			
			
			$return_data_content .= '</tr></thead><tbody id="the-list">';
	
			if(!empty($get_list_date)){
				$tmp_skift = true;
			
				foreach($get_list_date as $tmp_key => $tmp_data){
					$Loginbywp = 'Manual';
					
					if(!empty($tmp_data->extern)){
						if($tmp_data->extern == 'FACEBOOK'){
							$Loginbywp = '<a target="_black" href="'.$tmp_data->externUrl.'">Facebook link</a>';
						} else if($tmp_data->extern == 'TWITTER'){
							$Loginbywp = '<a target="_black" href="'.$tmp_data->externUrl.'">Twitter link</a>';
						} else if($tmp_data->extern == 'WP'){
							$Loginbywp = '<a target="_black" href="'.$tmp_data->externUrl.'">WordPress</a>';
						} else if($tmp_data->extern == 'LINKEDIN'){
							$Loginbywp = '<a target="_black" href="'.$tmp_data->externUrl.'">LinkedIn</a>';
						} else if($tmp_data->extern == 'GOOGLEPLUS'){
							$Loginbywp = '<a target="_black" href="'.$tmp_data->externUrl.'">Google+</a>';
						}
					}
					
					$get_avatar = get_avatar( $tmp_data->email, 40,RHCRATING_URL.'images/default_avatar.jpg',$tmp_data->firstName.' '.$tmp_data->lastName);
							
					if(!empty($tmp_data->externUrlPhoto)){
						$get_avatar = '<img width="40" height="40" class="avatar avatar-40 photo" src="'.$tmp_data->externUrlPhoto.'" alt="'.$tmp_data->firstName.' '.$tmp_data->lastName.'">';
					}
					
					$return_data_content .= '<tr class="'.($tmp_skift == true ? 'alternate' : '').'">';		
					$return_data_content .= '<td class="comments column-comments" style="padding-left: 10px;">'.($tmp_key+1).'</td>';
					$return_data_content .= '<td class="comments column-comments"><div style="border-radius: 40px 40px 40px 40px; width: 40px; height: 40px; display: block; overflow: hidden;">'.$get_avatar.'</div></td>';
					$return_data_content .= '<td class="categories column-categories">'.$tmp_data->firstName.' '.$tmp_data->lastName.'</td>';
					$return_data_content .= '<td class="categories column-categories"><a href="mailto:'.$tmp_data->email.'">'.$tmp_data->email.'</a></td>';
					$return_data_content .= '<td class="categories column-categories">'.$Loginbywp.'</td>';
					$return_data_content .= '<td class="categories column-categories">'.$tmp_data->rating.'</td>';
					$return_data_content .= '<td class="categories column-categories">'.date('F j, Y',strtotime($tmp_data->cDate)).'</td>';
					
					if(!empty($option_settings['rating_accept_inputs'])){
							$return_data_content .= '<td class="categories column-categories">';
							if(current_user_can('manage_options') || current_user_can('rating_approvel') ){
								$return_data_content .= '<a href="#" onclick="rhc_rating_change_status('.$_GET['postID'].','.$tmp_data->id.','.($tmp_data->show == true ? 0 : 1).');return false;">';
							}
							$return_data_content .= ($tmp_data->show == true ? 'Yes' : 'No');
							if(current_user_can('manage_options') || current_user_can('rating_approvel') ){
								$return_data_content .= '</a>';
							}
							$return_data_content .= '</td>';		
					}
						
					
					$return_data_content .= '<td class="categories column-categories">'.$tmp_data->comment.'</td>';
					$return_data_content .= '<td class="comments column-comments">';
					
					if(!empty($option_settings['rating_accept_inputs']) && (current_user_can('manage_options') || current_user_can('rating_approvel'))){
						$return_data_content .= '<a href="#" onclick="rhc_rating_change_status('.$_GET['postID'].','.$tmp_data->id.','.($tmp_data->show == true ? 0 : 1).');return false;">'.($tmp_data->show == true ? 'Hide' : 'Show').'</a>';
					}	
					if(current_user_can('manage_options') || current_user_can('rating_delete_ratings') ){
						$return_data_content .= '<a href="#" onclick="rhc_rating_delete('.$_GET['postID'].','.$tmp_data->id.');return false;">'.__('Delete','rhcrating').'</a>';
					}

					$return_data_content .= '</td>';
					$return_data_content .= '</tr>';	
					
					$tmp_skift = !$tmp_skift;
				}
			}
			$return_data_content .= '</tbody></table></div></div>';
		}
		
		?>
		<script>
			function rhc_rating_show_forword(tmp_this){
				var tmp = jQuery('#kalenderdatebuttom a.item').filter(':visible:first').index();
				var tmplength = jQuery('#kalenderdatebuttom a').length;
				for(var i=tmp; i<tmplength;i++){
					jQuery('#kalenderdatebuttom a:eq('+i+')').show();
				}
				jQuery(tmp_this).hide();
			}
			
			function rhc_rating_show_back(tmp_this){
			
				var tmp = jQuery('#kalenderdatebuttom a.item').filter(':visible:first').index();
				
				for(var i=0; i<tmp;i++){
					jQuery('#kalenderdatebuttom a:eq('+i+')').show();
				}
				jQuery(tmp_this).hide();
			}

			function rhc_rating_change_status(tmp_postID,tmp_id,tmp_status){
					window.location.href = '?<?php echo $pagetype; ?>page=rhc-rating-list&postID='+tmp_postID+'&change_allow=true&status='+tmp_status+'&event_rdate=<?php echo $_REQUEST['event_rdate']; ?>&ratingid='+tmp_id; 
			}


			function rhc_rating_delete(tmp_postID,tmp_id){
				if (window.confirm('<?php echo __('Are you sure you want to remove this entry','rhcrating'); ?>')){
					window.location.href = '?<?php echo $pagetype; ?>page=rhc-rating-list&postID='+tmp_postID+'&delete=true&event_rdate=<?php echo $_REQUEST['event_rdate']; ?>&ratingid='+tmp_id; 
				}
			}	
		</script>
		<?php
		
		echo $return_data_content;
	}
	

	function remove_row_actions( $actions,$post )
	{
	    if( get_post_type() === 'events' )
		    $tmp = get_post_meta($post->ID,'enable_rhc_rating_box',true);
		
			if(empty($tmp)){
				$tmp = false;
			}
			
			if($tmp){
				$pagetype = '?post_type=events&';
				if(!current_user_can('manage_options') && current_user_can('rating_read_list') ){
					$pagetype = '';
				} 
			
	        	$actions['eventratingpage'] = '<a href="edit.php'.$pagetype.'page=rhc-rating-list&postID='.$post->ID.'">'.__('Rating List','rhcrating').'</a>';
				$actions['eventratingpage'] .= '<input type="hidden" value="'.$tmp.'" class="rhc_rating_box_data">';
			}
	    return $actions;
	}

	function admin_script() {
	    if($this->check_post_type()){
	    	wp_enqueue_script( 'rhc_rating_admin', RHCRATING_URL . 'js/admin.js' );  
		}
	}		
			
	function admin_init(){
	    if($this->check_post_type()){
			global $post;
			$get_value = 0;
			if(!empty($post) && isset($_GET['post']) && isset($_GET['action']) && $_GET['action'] == 'edit'){
				$get_value = get_post_meta($post->ID,'enable_rhc_rating_box',true);
			} else if(!empty($post)){
				$settings = get_option('rhc_rating_options');
				
				if(!empty($settings['rating_newpost_on'])){
					$get_value = true;
				} 
			}
			
			echo '<script>if(typeof cit_rhc_rating_createbutton == \'function\'){cit_rhc_rating_createbutton(\''.__('Rating and Review Box','rhcrating').'\',\''.$get_value.'\');}</script>';	
		}

	}
	
	function save_post(){
		global $post;
		if($this->check_post_type() and !empty($post->ID) and $_POST['action'] != 'inline-save'){
			$value = isset($_REQUEST['enable_rhc_rating_box'])?$_REQUEST['enable_rhc_rating_box']:'';
			update_post_meta($post->ID,'enable_rhc_rating_box',$value);
		}
		
		
		if($this->check_post_type() and !empty($_POST['post_ID'])  and $_POST['action'] == 'inline-save'){
			$value = isset($_POST['rhc_rating_box'])?$_POST['rhc_rating_box']:'';
			update_post_meta($_POST['post_ID'],'enable_rhc_rating_box',$value);
		}	
	}
	
	
	// -----------------------------------------------------------------------------------------	
	// Intersept ajax data ---------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------
	
	
	function intercept_data(){
		if(isset($_REQUEST['rhc_rating_data'])){
			if($_REQUEST['rhc_rating_fn']=='saveanswer'){
				$this->saveanswer($_REQUEST);
			}

			if($_REQUEST['rhc_rating_fn']=='retrive_data_by_date'){
				$this->data_by_date();
				
			}
			
			die();
		}
	}
	
	function data_by_date(){
			global $wpdb;
	
			$settings = get_option('rhc_rating_options');
	
			$get_rating = 0;
			$get_rating_count = 0;

			$icon_count = 5;
			$icon_type = 'star';
			
			$faces_array = array('icon-angry','icon-sad','icon-wondering','icon-neutral','icon-cool','icon-smiley','icon-happy');
			$faces_string_array = array('Angry','Sad','Wondering','Neutral','Cool','Smilie','Happy');
			
			
			if(!empty($settings['rating_icon_numbers'])){
				$icon_count = (int)$settings['rating_icon_numbers'];
			}
			if(!empty($settings['rating_icon_type'])){
				$icon_type = $settings['rating_icon_type'];
			}
			
			if($icon_type == 'faces'){
				$icon_count = 7;
			}
	
			if(!empty($_REQUEST['rhc_rating_event_rdate'])){
				$tmp_d = explode(';', $_REQUEST['rhc_rating_event_rdate']);
				
				$tmp_d_back = '';
				foreach($tmp_d as $td){
					if(!empty($tmp_d_back)){
						$tmp_d_back .= ' or ';
					}
					$tmp_d_back .= "event_date='".$td."'";
				}
				
				$_REQUEST['rhc_rating_event_rdate'] = 'and ('.$tmp_d_back.') ';
				
			} else {
				$_REQUEST['rhc_rating_event_rdate'] = '';
			}
			
			
			if(!empty($_REQUEST['rhc_rating_postID']) and empty($_REQUEST['rhc_rating_next'])){

				$get_data_sql = "(SELECT sum(T0.rating) FROM  {$wpdb->prefix}rhc_rating T0 WHERE ".($settings['rating_accept_inputs'] == true ? ' T0.show=1 and' : '')." T0.postID=".$_REQUEST['rhc_rating_postID']." and T0.rating <= ".$icon_count." ".$_REQUEST['rhc_rating_event_rdate']." limit 1) as rating_sum,";
				$get_data_sql .= "(SELECT count(T1.rating) FROM  {$wpdb->prefix}rhc_rating T1 WHERE ".($settings['rating_accept_inputs'] == true ? ' T1.show=1 and' : '')." T1.postID=".$_REQUEST['rhc_rating_postID']." and T1.rating <= ".$icon_count." ".$_REQUEST['rhc_rating_event_rdate']." limit 1) as rating_count";
								
				for($i=0;$i<$icon_count;$i++){
					if(!empty($get_data_sql)){
						$get_data_sql .= ",";
					}
				
					$get_data_sql .= "(SELECT count(M".$i.".id) FROM {$wpdb->prefix}rhc_rating M".$i." WHERE ".($settings['rating_accept_inputs'] == true ? ' M'.$i.'.show=1 and' : '')." M".$i.".postID = ".$_REQUEST['rhc_rating_postID']." and M".$i.".rating >= ".($i+0.4)." and M".$i.".rating < ".($i+1.4)." ".$_REQUEST['rhc_rating_event_rdate']." limit 1) as v".$i." ";
				}
				
				$get_data_sql = "SELECT ". $get_data_sql . " FROM {$wpdb->prefix}rhc_rating WHERE 1 limit 1";
				
				$get_result_data = $wpdb->get_row($get_data_sql, ARRAY_A);

				if(!empty($get_result_data)){
					$get_rating = $get_result_data['rating_sum'];
					$get_rating_count = $get_result_data['rating_count'];
					
					unset($get_result_data['rating_sum']);
					unset($get_result_data['rating_count']);
						
				}
					
				if(empty($get_rating)){$get_rating = 0;}
				if(empty($get_rating_count)){$get_rating_count = 0;}
			
					
					
				$this->send_success_die(array('R'=>'DONE','AVAGE_RATING'=>$get_rating,'COUNT_RATING'=>$get_rating_count,'COUNT'=>$icon_count,'BAR'=>$get_result_data));
			} else if(!empty($_REQUEST['rhc_rating_postID'])  and !empty($_REQUEST['rhc_rating_next'])) {
				if(empty($_REQUEST['rhc_rating_next_c'])){
					$_REQUEST['rhc_rating_next_c'] = 0;
				}
			
				$get_list_date = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}rhc_rating WHERE ".($settings['rating_accept_inputs'] == true ? ' `show`=1 and' : '')." postID=".$_REQUEST['rhc_rating_postID']." and rating <= ".$icon_count. " " .$_REQUEST['rhc_rating_event_rdate']." order by cDate DESC limit ".$_REQUEST['rhc_rating_next_c'].",".($_REQUEST['rhc_rating_next_c']+11));
			
				$tmp_content = '';
				if(!empty($get_list_date)){
					foreach($get_list_date as $tmp_key => $tmp_data){
						if($tmp_key > 10){
							break;
						}
						$tmp_content .= $this->generate_avatar($tmp_data->email,$tmp_data->firstName,$tmp_data->lastName,$tmp_data->externUrlPhoto,$tmp_data->externUrl,$tmp_data->rating,$tmp_data->cDate,$tmp_data->comment,$settings,false);
					}
				}	
				
				$return_showmore = 'more';
				
				if(count($get_list_date) < 11){
					$return_showmore = '';
				}
				
				
				$this->send_success_die(array('R'=>'REVIEWS','REVIEWS'=>$tmp_content,'SHOWMORE'=>$return_showmore));
			}
	}
	
	function saveanswer($data){
	    global $wpdb,$post;
	    
	    $settings = get_option('rhc_rating_options');
	    
	    if(empty($_REQUEST['rhc_rating_postID']) || !is_numeric($_REQUEST['rhc_rating_postID'])){
		    $this->send_error_die(__('No post id','rhcrating'));
	    }
	    
	    if(empty($_REQUEST['rhc_rating_externUrlPhoto'])){
	    	$_REQUEST['rhc_rating_externUrlPhoto'] = '';
	    }
	    
	    
	    if($_REQUEST['rhc_rating_rating'] < 0 && $_REQUEST['rhc_rating_rating'] > 10){
		    $this->send_error_die(__('No rading found','rhcrating'));

	    }	
	    
		$check = $wpdb->get_var("SELECT id FROM {$wpdb->prefix}rhc_rating WHERE postID=".$_REQUEST['rhc_rating_postID']." and email like '%".$_REQUEST['rhc_rating_email']."%' and event_date='".$this->rating_mysql_real_escape_string($_REQUEST['event_rdate'])."' limit 1" );	    
	    
	    
	    if(!empty($check)){
		     $this->send_error_die(__('Your email have already been used','rhcrating'));
	    }
	     	    
	    $loginip = getenv("REMOTE_ADDR");
		
		if($_REQUEST['rhc_rating_extern'] == 'WP'){
			$_REQUEST['rhc_rating_firstname'] = utf8_decode($_REQUEST['rhc_rating_firstname']);
			$_REQUEST['rhc_rating_lastname'] = utf8_decode($_REQUEST['rhc_rating_lastname']);
		}
		error_reporting(E_ERROR | E_PARSE);
		$sqlevent = $wpdb->insert( 
			$wpdb->prefix.'rhc_rating', 
			array( 
				'postID' => $_REQUEST['rhc_rating_postID'], 
				'firstName' => $_REQUEST['rhc_rating_firstname'],
				'lastName' => $_REQUEST['rhc_rating_lastname'],
				'comment' => $_REQUEST['rhc_rating_comment'],
				'email' => $_REQUEST['rhc_rating_email'],
				'rating' => $_REQUEST['rhc_rating_rating'],
				'extern' => $_REQUEST['rhc_rating_extern'],
				'externUrl' => $_REQUEST['rhc_rating_externUrl'],
				'externUrlPhoto' =>$_REQUEST['rhc_rating_externUrlPhoto'],
				'event_date' => $_REQUEST['event_rdate'],
				'loginip' => $loginip
			), 
			array( 
			'%d', 
			'%s',
			'%s', 
			'%s', 
			'%s',
			'%d',
			'%s',
			'%s',
			'%s',
			'%s',
			'%s' 
			)
		);

		$return_string = __('Thank you for your rating [NAME].','rhcrating');
		$return_string = str_replace("[NAME]",$_REQUEST['rhc_rating_firstname'] . ' ' . $_REQUEST['rhc_rating_lastname'] ,$return_string);
		
		
		$get_avatar = '';
		
		
		if(empty($settings['rating_accept_inputs'])){
			$settings['rating_accept_inputs'] = false;
		}
		
		if(!empty($settings['rating_attend_show'])){
			$get_avatar = $this->generate_avatar($_REQUEST['rhc_rating_email'],$_REQUEST['rhc_rating_firstname'],$_REQUEST['rhc_rating_lastname'],$_REQUEST['rhc_rating_externUrlPhoto'],$_REQUEST['rhc_rating_externUrl'],$_REQUEST['rhc_rating_rating'],date('Y-m-d h:i:s'),$_REQUEST['rhc_rating_comment'],$settings);
		}

		
		$this->send_success_die(array('R'=>'DONE','MSG'=>$return_string,'RATING'=>$_REQUEST['rhc_rating_rating'],'AVATAR'=>$get_avatar,'rating_accept_inputs'=>$settings['rating_accept_inputs']));
	}
	
	// -----------------------------------------------------------------------------------------	
	// Other function --------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------
	
	function rating_mysql_real_escape_string($tmp_value){
		if(!empty($tmp_value)){
			$tmp_value_array = explode(',', $tmp_value);
			
			if(!empty($tmp_value_array) and count($tmp_value_array) == 1 and is_numeric($tmp_value_array[0])){
				return $tmp_value;
			} else if(!empty($tmp_value_array) and count($tmp_value_array) == 2 and is_numeric($tmp_value_array[0]) and is_numeric($tmp_value_array[1]) ){
				return $tmp_value;
			} else {
				return '';
			}
		} else {
			return '';
		}
	}
	
	
	function generate_avatar($email,$firstName,$lastName,$externUrlPhoto,$externUrl,$rating,$cDate,$comment,$settings,$show = true){
		$return_data_content = '';
		$get_avatar = get_avatar( $email, 75,RHCRATING_URL.'images/default_avatar.jpg',$firstName.' '.$lastName);
					
		$faces_array = array('icon-angry','icon-sad','icon-wondering','icon-neutral','icon-cool','icon-smiley','icon-happy');	
						
		if(!empty($externUrlPhoto)){
			$get_avatar = '<img width="75" height="75" class="avatar avatar-75 photo" src="'.$externUrlPhoto.'" alt="'.$firstName.' '.$lastName.'">';
		}
		
		if(!empty($settings['rating_icon_numbers'])){
			$icon_count = (int)$settings['rating_icon_numbers'];
		}
		if(!empty($settings['rating_icon_type'])){
			$icon_type = $settings['rating_icon_type'];
		}
		
		if($icon_type == 'faces'){
			$icon_count = 7;
		}		
		
		if(!empty($comment)){
			$comment=preg_replace("/[\n\r]/","<br>",$comment);
		    $comment = preg_replace('/(<br( \/|)>)+(<br( \/|)>)+(<br( \/|)>)+/', '<br><br>', $comment); 
		}
		
		
		$return_data_content .= '<div class="rhc_rating_tooltip_start">';
		
		if(!empty($settings['rating_show_link']) && !empty($externUrl)){
			$return_data_content .= '<a target="_blank" href="'.$externUrl.'">';
		}
		$return_data_content .= $get_avatar;
		
		if(!empty($settings['rating_show_link']) && !empty($externUrl)){
			$return_data_content .= '</a>';
		}

		$return_data_content .= '</div>';
		
		
					$return_data_content2 = '<div class="commentboxs" style="display:'.($show == true?'block':'none;margin-top:100px').';"><table width="100%"><tr><td class="td_avatar">';		
						$return_data_content2 .= $return_data_content;
						$return_data_content2 .= '</td><td valign="top">';
							$return_data_content2 .= '<div class="span12 first">';
								$return_data_content2 .= '<div class="span7 first">';
									$return_data_content2 .= '<div class="commentheadtext">'. $firstName. ' ' .$lastName.'</div>';
									
									
								$return_data_content2 .= '</div>';	
								$return_data_content2 .= '<div class="span5 timeClock">';
									$return_data_content2 .= strtoupper(date('F j, Y @ h:i A',strtotime($cDate)));
									$return_data_content2 .= '<div style="font-size: 10px ! important; margin-right: -5px; margin-top: 5px;">';
									for($i=0;$i<$icon_count;$i++){
										if($icon_type == 'faces'){
											if($i == floor($rating-0.5)){
												$return_data_content2 .= '<div class="'.$faces_array[$i].' commentselect"></div>';
											} else {
												$return_data_content2 .= '<div class="'.$faces_array[$i].'-3 commentselect"></div>';
											}	
										} else {
											if(floatval($i - 0.25) <= floatval($rating-1)){
												$return_data_content2 .= '<div class="icon-'.$icon_type.' commentselect"></div>';
											} else if(($i - 0.75) <= floatval($rating-1)){
												$return_data_content2 .= '<div class="icon-'.$icon_type.'-2 commentselect"></div>';	
											} else {
												$return_data_content2 .= '<div class="icon-'.$icon_type.'-3 commentselect"></div>';	
											}	
										}
									}
									$return_data_content2 .= '</div>';
								$return_data_content2 .= '</div>';	
							$return_data_content2 .= '</div>';	
							$return_data_content2 .= '<div class="textcomment span12 first">';	
								$return_data_content2 .= $comment;
							$return_data_content2 .= '</div>';
							
					$return_data_content2 .= '</td></tr></table></div>';

		
					
		return $return_data_content2;
	}
	
	function send_error_die($msg){
		die(json_encode(array('R'=>'ERR','MSG'=>$msg)));
	}	
	
	function send_success_die($tmp_data){
		die(json_encode($tmp_data));
	}
	
	function check_post_type() {
		global $post, $typenow, $current_screen;
		
		$return = null;
		
		if( !empty($_GET['page']) && $_GET['page'] == 'rhc-rating-list' )
			$return = 'events';
		elseif ( $post && $post->post_type )
			$return =  $post->post_type;
		elseif( $typenow )
			$return = $typenow;
		elseif( $current_screen && $current_screen->post_type )
			$return =  $current_screen->post_type;
		elseif( isset( $_REQUEST['post_type'] ) )
			$return = sanitize_key( $_REQUEST['post_type'] );
		
		return ($return == 'events');
	}
	
	function get_the_excerpt($post_id) {
	  global $post;  
	  $save_post = $post;
	  $post = get_post($post_id);
	  $output = get_the_excerpt();
	  $post = $save_post;
	  return $output;
	}
	
	// -----------------------------------------------------------------------------------------	
	// install ---------------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------
	
	function install(){
	    global $wpdb; 
			$installed = get_option('RHCRATING_INSTALL','');
			if(empty($installed) or version_compare($installed, '1.0.0','<')) {
		        $queries[] =  "DROP TABLE IF EXISTS #__rhc_rating;";
		        
		    	$queries[] =  "CREATE TABLE IF NOT EXISTS `#__rhc_rating` (
		  		`id` int(11) NOT NULL auto_increment,
		  		`postID` int(11) NOT NULL,
		  		`firstName` varchar(255) NOT NULL,
		  		`lastName` varchar(255) NOT NULL,
		  		`comment` text COLLATE utf8_unicode_ci NOT NULL,
		  		`email` varchar(255) NOT NULL,
		  		`rating` decimal(2,1) NOT NULL,
		  		`extern` varchar(10) NOT NULL,
		  		`externUrl` varchar(255) NOT NULL,
		  		`externUrlPhoto` varchar(255) NOT NULL,
		  		`event_date` varchar(255) NOT NULL,
		  		`loginip` varchar(255) NOT NULL,
		  		`cDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
		  		PRIMARY KEY  (`id`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
		
			}
			
			if(empty($installed) or version_compare($installed,'1.0.3', '<')) {
				$queries[] =  "ALTER TABLE `#__rhc_rating` ADD `show` INT( 5 ) NOT NULL DEFAULT '0' ;";

			}
			
			if(!empty($queries)){
				foreach($queries as $query){
					$query = str_replace('#__', $wpdb->prefix, $query);
		        	$wpdb->query($query);
				}
			}

			update_option('RHCRATING_INSTALL',RHCRATING_VERSION);	
	}
	
	
	
}

global $rhc_rating_plugin;

$rhc_rating_plugin = new plugin_rhc_rating();
?>