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

add_action( 'wp_enqueue_scripts', 'my_enqueue_base' );
function my_enqueue_base($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_base');
		$translations['mail_not_sent'] 			= __('Error. El e-mail no se pudo enviar.','ainia_base');
		
		$translations['could_not_projectualize'] 	= __('Error. No se puede añadir la entrada al proyecto.','ainia_base'); ;
		$translations['correctly_projectualized'] 	= __('Esta entrada se ha agregado al proyecto correctamente ','ainia_base');
		$translations['remove_projectualized'] 	= __('La entrada se ha eliminado del proyecto','ainia_base');
		
		
		$translations['could_not_classify'] 	= __('Error. No se puede clasificar la entrada.','ainia_base'); ;
		$translations['correctly_classified'] 	= __('Esta entrada se ha clasificado correctamente en la categoría','ainia_base');
		$translations['could_not_add_tag'] 		= __('Error. No se pudo añadir la etiqueta..','ainia_base'); ;
		$translations['correctly_tagged'] 		= __('La entrada se ha etiquetado correctamente.','ainia_base');
		$translations['added_to_favourites'] 	= __('El post se ha añadido a la lista de Favoritos.','ainia_base');
		$translations['removed_from_favourites']= __('Se ha eliminado de la lista de Favoritos.','ainia_base');		
		$translations['is_favourite'] 			= __('Es Favorito!','ainia_base');
		$translations['remove'] 				= __('Eliminar','ainia_base');
		$translations['is_not_favourite'] 		= __('No Favorito','ainia_base');
		$translations['add'] 					= __('Add','ainia_base');
		$translations['action_not_done'] 		= __('Error. Action was not done.','ainia_base');
		$translations['recommendation_not_sent']= __('Error. Recommendation has not been sent.','ainia_base');
		$translations['recommendation_sent'] 	= __('A recommendation email has been sent to','ainia_base');
		
		$translations['no_projects'] 			= __('No projects in this dates range','ainia_base');
		$translations['please_select_projects'] = __('Please select some projects','ainia_base');
		
		
		$translations['error_color'] 	= '#FF9999';
		$translations['success_color'] 	= '#99FF99';
				
		wp_localize_script( 'ajax-script', 'ajax_object', $translations );
		
		global $post;
	
		wp_enqueue_script('ainia_javascript_functions', plugins_url( 'ainia_javascript_functions.js', __FILE__ ));
		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() 
{	
	//echo('SEND MAIL');
	$to = $_POST['to'];
	$user_id = intval($_POST['user_id']);
	$post_id = intval($_POST['post_id']) ;	
	$user = get_userdata( $user_id );
	$app=get_bloginfo( 'name');
	$pos=strpos($app,'Foodalert 2.0');
	if ($pos!==false){	
		
		$subject = $user->display_name . __(" te envía información de una alerta de seguridad alimentaria.",'ainia');
	$body = sprintf( __("Este es un e-mail automático. %s te recomienda esta alerta: <a href='%s'>%s</a>",'ainia'),
					$user->display_name,
					/*get_permalink($post_id)*/ get_post_meta( $post_id, 'url_article', true ),
					get_the_title($post_id));
	}else{
		
		$subject = $user->display_name . __(" te recomienda un enlace desde ",'ainia').$app;
	$body = sprintf( __("Este es un e-mail automático. %s te recomienda este enlace: <a href='%s'>%s</a>",'ainia'),
					$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').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('');	
// }

add_action('wp_ajax_favorite', 'ajax_favorite');
function ajax_favorite() 
{	
	$post_id = intval($_POST['post_id']) ;		
	$user_id = intval($_POST['user_id']) ;
	if(!get_post($post_id)||!get_userdata( $user_id ))die('Error');
	$rel = get_user_relation_id( $user_id , 0, $post_id, 'favorite' );	
	if($rel){
		delete_user_relation($rel);
		die("removed");
	}
	else {
		add_extended_user_favorite($post_id,$user_id);	
		die("added");
	}
}
add_action('wp_ajax_delete', 'ajax_delete');
function ajax_delete()
{

	$post_id = intval($_POST['post_id']) ;
	$user_id = intval($_POST['user_id']) ;

	if(!get_post($post_id)||!get_userdata( $user_id ))die('Error');
	$rel = get_user_relation_id( $user_id , 0, $post_id, 'delete' );

	if($rel){
		delete_user_relation($rel);
		die("recovered");
	}
	else {

		add_extended_user_deleted($post_id,$user_id);
		die("deleted");
	}
}


add_action('wp_ajax_recommend', 'ajax_recommend');
function ajax_recommend() 
{		
	$user_from = $_POST['user_id'] ;
	$user_to   = $_POST['user_to'] ;
	$post_id   = $_POST['post_id'] ;			
	
	if( !get_userdata( $user_from ) || !get_userdata( $user_to ) || !get_post($post_id) )die('Error');	
	
	add_extended_user_recommend($post_id,$user_to);
	add_extended_user_recommended($post_id,$user_to,$user_from);		
	
	$destinatario = get_userdata( $user_to );
	die( $destinatario->display_name);
}



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



  function filter_where($where = '') {
    $where .= " AND post_date >= '2009-03-01' AND post_date <= '2009-03-15'";
    return $where;
  }




add_action('wp_ajax_filter_modules', 'ajax_filter_modules');
function ajax_filter_modules() 
{	
	
	//echo '\'FECHAS:'.$_POST['fecha_modulo_desde'];
	//global $modulo_desde;
	//$modulo_desde = explode("/",$_POST['fecha_modulo_desde']) ;
	//echo '\'FECHAS:'.$modulo_desde[0].'-'.$modulo_desde[1].'-'.$modulo_desde[2].'\'';
	//global $modulo_hasta;
	//$modulo_hasta = explode("/",$_POST['fecha_modulo_hasta']) ;		
	ajax_grafico_modulo_1();
	exit();
}

add_action('wp_ajax_graph_1', 'ajax_grafico_1');
function ajax_grafico_1() 
{
	global $proyectos;
	$proyectos = explode (",",$_POST['projects']);	
	include('graph1.js.php');
	exit();
}

add_action('wp_ajax_graph_2', 'ajax_grafico_2');
function ajax_grafico_2() 
{
	global $proyectos;
	$proyectos = explode (",",$_POST['projects']);	
	include('graph2.js.php');
	exit();	
}

add_action('wp_ajax_graph_3', 'ajax_grafico_3');
function ajax_grafico_3() 
{
	global $proyectos;
	$proyectos = explode (",",$_POST['projects']);	
	include('graph3.js.php');
	exit();
}

add_action('wp_ajax_graph_module_1', 'ajax_grafico_modulo_1');
function ajax_grafico_modulo_1() 
{	
	include('graph_module_1.js.php');
	exit();
}




