<?php
//http://wp.tutsplus.com/articles/getting-started-with-ajax-wordpress-pagination/

add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) 
{        
	if(!is_admin()){		
		wp_enqueue_script( 'ajax-script', plugins_url( 'ajax.js', __FILE__ ), array('jquery'));				
		$translations = array();
		$translations['ajax_url'] = admin_url( 'admin-ajax.php' );
		$translations['user_id'] = get_current_user_id();
		$translations['post_id'] = url_to_postid($_SERVER['REQUEST_URI']);
		
		$translations['post_succesfully_sent'] 	= __('E-mail enviado correctamente a','ainia_iwatch');
		$translations['mail_not_sent'] 			= __('Error. El e-mail no se pudo enviar.','ainia_iwatch');
		
		$translations['could_not_projectualize'] 	= __('Error. No se puede añadir la entrada al proyecto.','ainia_iwatch'); ;
		$translations['correctly_projectualized'] 	= __('Esta entrada se ha agregado al proyecto correctamente ','ainia_iwatch');
		$translations['remove_projectualized'] 	= __('La entrada se ha eliminado del proyecto','ainia_iwatch');
		
		
		$translations['could_not_classify'] 	= __('Error. No se puede clasificar la entrada.','ainia_iwatch'); ;
		$translations['correctly_classified'] 	= __('Esta entrada se ha clasificado correctamente en la categoría','ainia_iwatch');
		$translations['could_not_add_tag'] 		= __('Error. No se pudo añadir la etiqueta..','ainia_iwatch'); ;
		$translations['correctly_tagged'] 		= __('La entrada se ha etiquetado correctamente.','ainia_iwatch');
		$translations['added_to_favourites'] 	= __('La entrada se ha añadido a la lista de favoritos.','ainia_iwatch');
		$translations['removed_from_favourites']= __('La entrada se ha eliminado de la lista de favoritos.','ainia_iwatch');		
		$translations['is_favourite'] 			= __('Es favorito!','ainia_iwatch');
		$translations['remove'] 				= __('Eliminar','ainia_iwatch');
		$translations['is_not_favourite'] 		= __('No es favorito','ainia_iwatch');
		$translations['add'] 					= __('Add','ainia_iwatch');
		$translations['action_not_done'] 		= __('Error. No se ha ejecutado la acción.','ainia_iwatch');
		$translations['recommendation_not_sent']= __('Error. No se ha enviado la recomendación.','ainia_iwatch');
		$translations['recommendation_sent'] 	= __('Un e-mail de recomendción se ha enviado a ','ainia_iwatch');
		
		$translations['no_projects'] 			= __('No hay proyectos en estas fechas','ainia_iwatch');
		$translations['please_select_projects'] = __('Por favor seleccione algunos proyectos','ainia_iwatch');
		
		
		$translations['error_color'] 	= '#FF9999';
		$translations['success_color'] 	= '#99FF99';
				
		wp_localize_script( 'ajax-script', 'ajax_object', $translations );
		
		global $post;
		if(has_shortcode($post->post_content,'formulario_graficos')){
			wp_enqueue_script('jquery-ui-datepicker');
			wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
		}	
		
		if(has_shortcode($post->post_content,'formulario_graficos_modulos')){
			wp_enqueue_script('jquery-ui-datepicker');
			wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
		}

		if(has_shortcode($post->post_content,'grid_graficos_modulos')){
			wp_enqueue_script('jquery-ui-datepicker');
			wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
		}		
		
		wp_enqueue_script('highcharts',"http://code.highcharts.com/highcharts.js");
		wp_enqueue_script('highcharts-more',"http://code.highcharts.com/highcharts-more.js",'highcharts');
		wp_enqueue_script('highcharts-exporting',"http://code.highcharts.com/modules/exporting.js",'highcharts');
	}
}

// Same handler function...
// add_action('wp_ajax_send_email', 'ajax_send_email');
// function ajax_send_email() 
// {	
// 	$to = $_POST['to'];
// 	$user_id = intval($_POST['user_id']);
// 	$post_id = intval($_POST['post_id']) ;	
// 	$user = get_userdata( $user_id );
// 	$subject = $user->display_name . __(" recommends a link to you.",'ainia_iwatch');
// 	$body = sprintf( __("This is an automatic email. %s recomends you this link: <a href='%s'>%s</a>",'ainia_iwatch'),
// 					$user->display_name,
// 					/*get_permalink($post_id)*/ get_post_meta( $post_id, 'url_article', true ),
// 					get_the_title($post_id));	
// 	$headers = sprintf("From: %s <%s> \r\n",$user->display_name,$user->user_email);
// 	$headers .= sprintf("Reply-To: %s \r\n",$user->user_email);
// 	$headers .= "MIME-Version: 1.0\r\n";
// 	$headers .= "Content-Type: text/html; charset=UTF-8\r\n";	
// 	add_extended_user_email_to($user_id,"hoy",$to,$subject,$body);		
// 	$result  = wp_mail($to,$subject,$body,$headers);
// 	die( $result ? 'OK' : "Error" );
// }

// Same handler function...
// add_action('wp_ajax_crear_etiqueta', 'ajax_crear_etiqueta');
// function ajax_crear_etiqueta() 
// {	
// 	$tags = $_POST['tags'];
// 	$user_id = intval($_POST['user_id']);
// 	$post_id = intval($_POST['post_id']) ;	

// 	wp_set_post_tags($post_id,$tags,true);
// 	$buffer = array();
// 	$posttags = get_the_tags($post_id);
// 	if ($posttags) 
// 	 foreach($posttags as $tag) 
// 	  $buffer[]='<a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a>'; 
    
// 	//add_extended_user_categorize($post_id,$cat_id,$user_id);	
// 	die( __( 'Tagged as: ','ainia_iwatch').implode(',',$buffer) );
// }

// add_action('wp_ajax_categorize', 'ajax_categorize');
// function ajax_categorize() 
// {	
// 	$user_id = intval($_POST['user_id']) ;
// 	$post_id = intval($_POST['post_id']) ;		
// 	$cat_id  = intval($_POST['cat']) ;		
// 	$term = get_term($cat_id,"category");
// 	if(!$term || is_wp_error($term) || !get_post($post_id) ) die('Error');	
// 	add_extended_user_categorize($post_id,$cat_id,$user_id);
	
// 	wp_set_post_categories( $post_id, $cat_id, true );
		
// 	die(sprintf('<a href="%s">%s</a>',get_term_link($term),$term->name));
// }

add_action('wp_ajax_projectualize', 'ajax_projectualize');
function ajax_projectualize() 
{
	$user_id = intval($_POST['user_id']) ;
	$post_id = intval($_POST['post_id']) ;		
	$proj_id  = intval($_POST['proj']) ;			
		
	$projs = get_field('proyecto',$post_id);
	wp_mail('hosting@a3p.es','test',print_r($projs,true));
	if(!is_array($projs))$projs = array();
	
	if(!in_array($proj_id,$projs)){
		$projs[]=$proj_id;
		update_field('proyecto',$projs,$post_id);
		die(sprintf('<a href="%s">%s</a>',get_permalink($proj_id),get_the_title($proj_id)));					
	}
	else die('');	
}


//-------- FORMULARIOS -----------

add_action('wp_ajax_list_projects', 'ajax_list_projects');
function ajax_list_projects() 
{		
	$desde = explode("/",$_POST['fecha_desde']) ;
	$hasta = explode("/",$_POST['fecha_hasta']) ;		
	
	if(count($desde)!=3 || count($hasta)!=3)die("KO");
		
	$args = array(
        'posts_per_page'=>-1,
        'post_status'=>'publish',
        'post_type'=>'project',
		'date_query' => array(
							array(
								'year'  => intval($desde[2]),
								'month' => intval($desde[1]),
								'day'   => intval($desde[0]),
								'compare'   => '>=',
							),
							array(
								'year'  => intval($hasta[2]),
								'month' => intval($hasta[1]),
								'day'   => intval($hasta[0]),
								'compare'   => '<=',
							),							
						),
    );
		
	$posts = get_posts($args);	
	if(!$posts) exit("KO");
	fieldtable_start('');
	fieldtable_add_row(array(
			'Código',
			'Título',		
			'Horizonte',		
			'Importancia',		
			'Prioridad',		
			'Entradas',		
			'Marcar',		
		),true);
	foreach($posts as $post)
	{
		
		fieldtable_add_row(array(
			get_field('codigo',$post->ID),
			sprintf('<a href="%s" target="_blank">%s</a>',get_permalink($post->ID),$post->post_title),
			get_field('horizonte',$post->ID),
			get_importancia_proyecto($post->ID),
			get_field('prioridad',$post->ID),
			contar_entradas_de_proyecto($post->ID),
			'<input class="marcador_proyecto" type="checkbox" checked="checked" value="'.$post->ID.'">'
		));
	}
	fieldtable_end();
	echo ' &nbsp;&nbsp;&nbsp;&nbsp; <input type="button" value="'.__('1. Proyectos por Importancia','ainia_iwatch').'" id="show_graph_1">';			
	echo ' &nbsp;&nbsp;&nbsp;&nbsp; <input type="button" value="'.__('2. Proyectos por Horizonte','ainia_iwatch').'" id="show_graph_2">';			
	echo ' &nbsp;&nbsp;&nbsp;&nbsp; <input type="button" value="'.__('3. Proyectos por Prioridad','ainia_iwatch').'" id="show_graph_3">';			
	exit();
}

//add_shortcode ('prueba_ajax','prueba_ajax');
function prueba_ajax($content)
{
	global $post;
	if(!is_single()) return get_string_max_length($content,400);
	

	ob_start();
	$my_theme=wp_get_theme();
	$name=$my_theme->get( 'Name' ) ;

	?>
	<?php if($post->post_type!="project"):?>
		<div class="ainia-downloads">
			<?php echo ainia_post_attachments($post);?>
		</div>
		 <?php endif;?>
	<?php if($post->post_type=="project") return $content;?>
		 <div class="ainia-actions">

			 <?php if($post->post_type=="project"):?>			
			 <p class="action_category">
			 <?php _e( 'Categor&iacute;as:','ainia_iwatch');?> <span class="category_list">
			 <?php
			   $cats = get_ids_categorias_proyecto($post->ID);
			   $enlaces = array();
			   foreach($cats as $cat){
				 $term = get_term($cat,'category');
				 $enlaces[]=sprintf('<a href="%s">%s</a>',
					get_term_link($cat,'category'),
					$term->name);					
			   }
			   echo implode(', ',$enlaces);			 
			 ?></span>
			 </p>			 
			 <?php else:?>
		
			 <?php
			 if (strpos($name, 'incrustado') == false){?>
	 			<p class="action_category">
			 <?php _e( 'Categor&iacute;as: ','ainia_iwatch');?><span class="category_list"><?php the_category(', ');?></span>
			 <?php 
			  wp_dropdown_categories(array('hierarchical'=>1,'hide_empty'=>false,'exclude'=>wp_get_post_categories($post->ID)));?>
			 <input type="button" value="<?php _e('A&ntilde;adir Categor&iacute;a','ainia_iwatch');?>" id="categorizar">
			 </p>
			 <?php }else{?>	<p class="action_category">
			 <?php _e( 'Conceptos búsqueda: ','ainia_iwatch');?><span class="category_list"><?php the_category(', ');?></span>
			 	
			  <?php }; 
			 endif;?>
			 
			 <?php if (strpos($name, 'incrustado') == false): ?> 
			 
			 <p class="action_tags">
			 <?php _e( 'Etiquetas: ','ainia_iwatch')." ";?>
			 <span class="tag_list"><?php the_tags('',', '); ?></span> 
			 <?php echo ' - ';?>
			 <input type="text" value="tag" id="new_tag" style="width:auto" size="20">
			 <input type="button" value="<?php _e('Add Tag','ainia_iwatch');?>" id="crear_etiqueta"></p>			
			 <br/>
			 <?php endif;?>
			 
			 <?php $tags=wp_get_post_terms($post->ID,'scope');			 
			 if(count($tags)):?>	
			 <p class="action_tags"><?php the_terms( $post->ID, 'scope', __( 'Scope','ainia_iwatch').": ",', ' );?></p>
			 <?php endif;?>
			 
			 <?php if(false)://Cuando eran taxonomias los proyectos ?>
				 <p class="action_projects"><span class="project_list">			 
				 <?php $terms=wp_get_post_terms($post->ID,'proyecto');			 
					   $terms_ids = array();foreach($terms as $term) $terms_ids[]=$term->term_id;
					   if(count($terms))the_terms($post->ID,'proyecto',__( 'In Project: ','ainia_iwatch')." ",', '); 				   
				 ?></span> -
				 <?php wp_dropdown_categories(array('name'=>'proj','taxonomy'=>'proyecto','exclude'=>$terms_ids,'hide_empty'=>false));?>
				 <input type="button" value="<?php _e('Add to Project','ainia_iwatch');?>" id="proyectualizar">
				 </p>
				 <br/>			 
			 <?php endif;
			
			  if (strpos($name, 'incrustado') == false): ?>
					 <?php if($post->post_type!="project"):?>
					 <p class="action_projects"><span class="project_list">			 
					 <?php  echo __( 'En proyectos : ','ainia_iwatch');
					 
							$proj_ids = get_field("proyecto",$post->ID);					
							$enlaces = array();
							if($proj_ids){
								foreach($proj_ids as $proj_id)
									$enlaces[]=sprintf('<a href="%s">%s</a>',get_permalink($proj_id),get_the_title($proj_id));					
								if(count($enlaces))echo implode(", ",$enlaces);
							}
							
							
							$proyectos=get_posts(array(
										'post_type'=>'project',
										'posts_per_page'=>-1,
										'post_status'=>'publish',											
										'post__not_in'=>$proj_ids,
										));			 				   				  
						    				   
					 ?></span><?php if($proj_ids)echo' - ';?><select name="proj" id="proj"> 
					 <option value=""><?php _e('-- Seleccionar Proyecto --','ainia_iwatch');?></option>
					 <?php 
						foreach($proyectos as $proyecto)
						  echo sprintf('<option %s value="%s">%s</option>',
										selected($proyecto->ID,$actual),
										$proyecto->ID,
										$proyecto->post_title);
					 ?>
					 </select>
					 <input type="button" value="<?php _e('Añadir al proyecto','ainia_iwatch');?>" id="proyectualizar">
					 </p>
					 <br/>		
					 <?php endif;
					 
				endif; ?>
			 
			 <?php
			 $url_article = get_post_meta( $post->ID, 'url_article', true );
  			 $terms=wp_get_post_terms($post->ID,"fuente");			 
			 if(count($terms)):?>			 
			 <p class="action_source">
			 <?php _e( 'Fuente:','ainia_iwatch'); ?>
			 <a href="<?php echo get_term_link($terms[0],'fuente')?>"><?php echo $terms[0]->name;?></a> | 
			 <a href="<?php echo $url_article;?>" target="_blank"><?php _e( 'Leer Original&raquo;','ainia_iwatch');?></a>
			 </p>			 
			 <?php endif;?>			 			 
	
			 			 
			 <p class="action_favorito">
			 <?php
				$rel = get_user_relation_id( get_current_user_id() , 0, $post->ID, 'favorite' );				
				if($rel):?>		
					<span id="esFavorito"><?php _e('Es Favorito!','ainia_iwatch');?></span>
					<input type="button" value="<?php _e('Desmarcar Favorito','ainia_iwatch');?>" id="marcarFavorito"></p>			 					
			 <?php else: ?>
					<span id="esFavorito"><?php _e('No es Favorito','ainia_iwatch');?></span>
					<input type="button" value="<?php _e('Marcar como Favorito','ainia_iwatch');?>" id="marcarFavorito"></p>			 	    
			 <?php endif; 

			 
			 if (strpos($name, 'incrustado') == false): 
			 
			 $current_user=get_current_user_id();?>
			 		 
					 <p class="action_recommend">
					 <?php _e('Recomendar a:','ainia_iwatch');?>
					 <?php wp_dropdown_users(array('show_option_none' => '-','exclude'=>array($current_user)));?>
					 <input type="button" value="<?php _e('Recomendar','ainia_iwatch');?>" id="recomendar">
					 </p>
			  <?php endif;?>
			  
			 <p class="action_email">
			 <?php _e('Enviar a:','ainia_iwatch');?>
			 <input type="text" placeholder="e-mail destino" id="email_to" style="width:auto" size="20">
			 <input type="button" value="<?php _e('Enviar por e-mail','ainia_iwatch');?>" id="enviar_mail"></p>			

			 <br/><br/><p id="server_message" style="display:none">Esto es un mensaje</p>
	</div>
	<?php
	
	
	$metadata = ob_get_contents();
	ob_end_clean();
	return $content . $metadata;
}

add_action('the_content','prueba_ajax');





