<?php

function theme_enqueue_styles() {

    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );

}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );



if ( !is_admin() ) {

	function custom_scripts() {

		wp_register_script( 'assets', get_stylesheet_directory_uri() . '/js/stopExecutionOnTimeout.js', array('jquery'), 1, true );

		wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/js/script.js', array('jquery'), 1, true );

		wp_register_script( 'scroll-to', get_stylesheet_directory_uri() . '/js/jquery.scrollTo-1.4.2-min.js', array('jquery'), 1, true );

		wp_enqueue_script( 'assets' );

		wp_enqueue_script( 'custom-script' );

		wp_enqueue_script( 'scroll-to' );

	}

	add_action( 'after_setup_theme', 'custom_scripts' );

}









// Genera los filtros

function GenerarFiltro(){



		$anoAr = array();

		$actividadAr = array();

		$paisAr = array();



		$results ='<div class="fixed-top">

					<div class="filter" style="border-top: none">

				    <form method="post" action="" style="height:51px !important;">

				    <div class="styled-select styled-select3">

					<select id="filtropais">';

		$results .= '<option value="0">PAIS</option>';



		$argsPais = array('parent' => 3,

                  'taxonomy' => 'portfolio_category',);



		$categories = get_categories( $argsPais );



		foreach($categories as $category) {

        $results .= ' <option class="obrasOption" value="';

        $results .= $category->name;

        $results .= '">';

        $results .= $category->name;

        $results .= '</option>';

		}



		$results .= '</select></div>

					<div class="styled-select styled-select4">

					<select id="filtroactividad">

					<option value="0">ACTIVIDAD</option>';

		$argsActividad = array('parent' => 116,

                  'taxonomy' => 'portfolio_category',);

		$categories = get_categories( $argsActividad );





		foreach($categories as $category) {

        $results .= ' <option class="obrasOption" value="';


			$str = $category->name;

			if(strlen($str) > 17) $str = substr($str, 0, 16);


        $results .= $category->name;

        $results .= '">';

        $results .= $category->name;

        $results .= '</option>';}

		$results .= "</select></div>";







		$results .= '<input id="FiltroButton" type="button" value="Filtrar" onclick="javascript:Paginate(1)">';

		$results .= '<input id="FiltroButton2" type="button" value="Dejar de filtrar" onclick="javascript:Reestablecer()">';

		$results .= '<span class="filter-link"><a href="#listadoCom" class="equipoBtn">Casos destacados</a><a href="#ListContainer" class="equipoBtn">Listado completo de casos</a></span>';

		$results .= '</form></div></div>';

		$results .='<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.2/isotope.pkgd.js"></script>';



	die($results);





}





//Genera la grilla de las fotos

function GenerarGrilla() {



	//Parametros traidos por alax

    $paged 		= 	$_POST['pageNumber'];

	$pais		= 	$_POST['select_pais'];

	$actividad	= 	$_POST['select_actividad'];



	remove_all_filters("posts_orderby");



	//Argumentos de la consulta

	$args = array(

        'post_type'     			=> 'portfolio',

        'meta_key'       			=> 'ano',

        'orderby'       			=> array('meta_value' => 'DESC','title' => 'ASC'),

        'portfolio_category'        => 'Casos destacados',

		'posts_per_page'         	=> 24,

		'paged'         		 	=> $paged,

		'update_post_term_cache' 	=> false,

		'update_post_meta_cache' 	=> false,

		'cache_results' 		 	=> false,

		'page' 					 	=> $paged,

		'tax_query' 			 	=> array(

											'tax_query2' => array(

																'taxonomy' 	=> 'portfolio_category',

																'field' 	=> 'name',

																'terms' 	=> array(

																					'pais' 		=> $pais,

																					'actividad' => $actividad

																					),

																'operator' => 'AND',

																  )

											 ),

				);





	if ($pais == "0" AND $actividad == "0") unset($args["tax_query"]);

	else  if ($pais != "0" AND $actividad == "0") unset($args["tax_query"]["tax_query2"]["terms"]["actividad"]);

	else  if ($pais == "0" AND $actividad != "0") unset($args["tax_query"]["tax_query2"]["terms"]["pais"]);



	//Realizo la consulta

	$the_query = new WP_Query( $args );





	//Parametros para el paginador

	$pages = '';

	$range = 8;

	$showitems = ($range * 2)+1;



	if(empty($paged)) $paged = 1;

    if($pages == '')

	{

       $pages = $the_query->max_num_pages;

	   if(!$pages)

	   {

		  $pages = 1;

	   }

	}



    if ( $the_query->have_posts() ) {



      $counter = 0;

	  $return = '<div class="portfolio portfolio-masonry-spacing portfolio-hover-style-2" style="position:relative; width:95%; margin-right:auto; margin-left:auto;">';



      while (  $the_query->have_posts() ) : $the_query->the_post();



        $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), $image_size );





         $actividad = get_field( "actividad" );

         $ano = get_field( "ano" );

         $pais = get_field( "pais" );





		 $actividadGet = str_replace("&", "-", $actividad);





        $url = get_the_permalink().'?actividad='.$actividadGet;







		 if($counter==2){

              $return .= '<article class="largeItemHC pagina1 '.$ano.' '.$pais.' '.$actividad.' destacados portfolio-item '. $class . '" data-id="' . get_the_ID() . '">';



          }else{

                $return .= '<article class="portfolio-item '. $class . '" data-id="' . get_the_ID() . '">';

          };











        $return .= '<a href="' . $url . '">';

        $return .= '<img src="' . $image[0] . '" alt="' . get_the_title() . '">';

        $return .= '<div class="hover">';

        $return .= '<div class="hover-content">';

        $return .= '<h5>' . get_the_title() . '</h5>';

        if( $below_title != 'none' ) {

            $return .= '<span>' .$actividad.' / '.$pais. '</span>';

              }

        $return .= '</div>';

        $return .= '</div>';

        $return .= '</a>';

        $return .= '</article>';

		$counter = $counter +1;



        endwhile;



        wp_reset_postdata();



		//Paginador

		/* if(1 != $pages)

		{

        $return.= "<div style=\"width:100%\"><div class=\"paginationStash\" style='width:300px'>";

        if($paged > 2 && $paged > $range+1 && $showitems < $pages) $return.= "<a href='".get_pagenum_link(1)."'>&laquo; Primera</a>";

        if($paged > 1 && $showitems < $pages) $return.= "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Anterior</a>";



        for ($i=1; $i <= $pages; $i++)

         {

             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))

             {

                 $return.= ($paged == $i)? "<span class=\"current\"></span>":"<a href='javascript:Paginate(" . $i . ",\"Grid\")' class=\"inactive\"></a>";

             }

         }



         if ($paged < $pages && $showitems < $pages) $return.= "<a href=\"".get_pagenum_link($paged + 1)."\">Siguiente &rsaquo;</a>";

         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) $return.= "<a href='".get_pagenum_link($pages)."'>Ultima &raquo;</a>";

         $results .= "</div></div>\n";

		} */



		if(1 != $pages)

		{

		$return .= "<div class=\"text-center paginadorsolo\"><ul class=\"pagination\">";

								for ($i=1; $i <= $pages; $i++)

								{

										if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))

										{

											$return .= ($paged == $i)? "<li><span class=\"current\"></span></li>":"<li><a href='javascript:Paginate(" . $i . ",\"Grid\")' class=\"inactive\"></a></li>";



										}

								}



		$return .= "</ul></div>";

		}













	  $return.='</div></div>';

    }



   // Delvuelvo el resultado

   die($return);

}





function menu_encuesta() {



     $return='<div class="anossWp">';



     $url = get_site_url();



     $return.=' <a id="2005" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2005/#pg-2397-1" class="">2005</a>

                <a id="2006" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2006/#pgc-2372-1-0" class="">2006</a>

                <a id="2007" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2007/#pgc-2367-1-0" class="">2007</a>

                <a id="2008" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2008/#pgc-2359-1-0" class="">2008</a>

                <a id="2009" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2009/#pgc-2335-1-0" class="">2009</a>

                <a id="2010" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2010/#pg-2332-1" class="">2010</a>

                <a id="2011" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2011/#pgc-2329-1-0" class="">2011</a>

                <a id="2012" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2012/#pg-2321-1" class="">2012</a>

                <a id="2013" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2013/#pgc-2301-1-0" class="">2013</a>

                <a id="2014" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2014/#pgc-2315-1-0" class="">2014</a>

                <a id="2015" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2015/#pg-2263-1" class="">2015</a>

                <a id="2016" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2016/#pg-2258-1" class="">2016</a>

                <a id="2017" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2017/#pgc-12066-1-0" class="">2017</a>

                <a id="2018" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2018/#pgc-14897-8-1" class="">2018</a>

                <a id="2019" href="'.$url.'/encuesta-de-satisfaccion-al-cliente-2019/#pgc-16329-2-0" class="">2019</a>';



     $return.='</div>';





   return $return;

 }





// Genera la tabla con los registros

function GenerarTabla(){





	echo "<div class='loading' id='loading'>Loading&#8230;</div>";





    //Parametros traidos por alax

    $paged 		= 	$_POST['pageNumber'];

	$pais		= 	str_replace("+"," ",$_POST['select_pais']);

	$actividad	= 	str_replace("+"," ",$_POST['select_actividad']);





	remove_all_filters("posts_orderby");







	//Argumentos de la consulta

	$args = array(

			'post_type'              => 'portfolio',

			'meta_key'       		 => 'ano',

			'orderby'                => array('meta_value' => 'DESC','title' => 'ASC'),

			'posts_per_page'         => 70,

			'paged'         		 => $paged,

			'page' 					 => $paged,

			'tax_query' 			 => array(

											'tax_query2' => array(

																'taxonomy' 	=> 'portfolio_category',

																'field' 	=> 'name',

																'terms' 	=> array(

																					'pais' 		=> $pais,

																					'actividad' => $actividad

																						),

																'operator' => 'AND',

																)

											 ),

				);





	if ($pais == "0" AND $actividad == "0") unset($args["tax_query"]);

	else  if ($pais != "0" AND $actividad == "0") unset($args["tax_query"]["tax_query2"]["terms"]["actividad"]);

	else  if ($pais == "0" AND $actividad != "0") unset($args["tax_query"]["tax_query2"]["terms"]["pais"]);



	//Realizo la consulta

	$the_query = new WP_Query( $args );



	//Parametros para el paginador

	$pages = '';

	$range = 8;

	$showitems = ($range * 2)+1;



	if(empty($paged)) $paged = 1;

    if($pages == '')

	{

       $pages = $the_query->max_num_pages;

	   if(!$pages)

	   {

		  $pages = 1;

	   }

	}



	//Muestro los reultados por pantalla



	if ( $the_query->have_posts() ) {

	$results = "<table id='rowsCasos' style='width:100%' >

	<tr class='bolder'>

				<td class='col_titulo'><h3>Cliente</h3></td>

				<td class='col_actividad'><h3>Actividad</h3></td>

				<td class='col_pais'><h3>Pa&iacute;s</h3></td>

				<td class='col_ano'><h3>A&ntilde;o</h3></td>

	</tr>";



		   while ( $the_query->have_posts() ) : $the_query->the_post();



           $selected = get_field('link');

           $actividad = get_field( "actividad" );

           $ano = get_field( "ano" );

           $pais = get_field( "pais" );

           $idPost =  $post->ID;





		   $actividadGet = str_replace("&", "-", $actividad);



		   $results .= "<tr>

		         <td class='col_titulo'>";



				 if ( has_term( 'Casos destacados', 'portfolio_category', $idPost ) ){





                             $results .='<a target="_blank" href="'.get_the_permalink().'?actividad='.$actividadGet.'"><i class="fa fa-star"></i> ';



			 	  }

               else if (  has_term( 'Obra sin fotos', 'portfolio_category', $idPost )){







$results .='<a target="_blank" href="'.get_the_permalink().'?actividad='.$actividadGet.'">';







			  } else{





							 $results .='<a target="_blank" href="'.get_the_permalink().'?actividad='.$actividadGet.'"><i class="fa fa-instagram"></i> ';





               };

			   $title = get_the_title();


			   if(strlen($title) > 30) $title = substr($title, 0, 30)."...";

               $results .= $title;

			   $results .='</a>';



				if(strlen($actividad) > 35) $actividad = substr($actividad, 0, 30)."...";


			$results .="</td>

				<td class='col_actividad'>".$actividad."</td>

				<td class='col_pais'>".$pais."</td>

				<td class='col_ano'>".$ano."</td>

		</tr>";



		   endwhile;





		}

		else

		{

		$results .="<div style='display:block'><h3>Lo sentimos, la combinaci&oacute;n de filtros usada no arroja ning&uacute;n resultado</h3></div>";

		}

		wp_reset_postdata();

		$results .="</table>";



		//Paginador

		/* if(1 != $pages)

		{

        $results .= "<div style=\"width:100%\"><div class=\"paginationStash\">";



        for ($i=1; $i <= $pages; $i++)

         {

             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))

             {

                 $results .= ($paged == $i)? "<span class=\"current\"></span>":"<a href='javascript:Paginate(" . $i . ",\"List\")' class=\"inactive\"></a>";

             }

         }



         $results .= "</div></div>\n";

		} */



		if(1 != $pages)

		{

		$results .= "<div class=\"text-center\"><ul class=\"pagination\">";

								for ($i=1; $i <= $pages; $i++)

								{

										if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))

										{

											$results .= ($paged == $i)? "<li><span class=\"current\"></span></li>":"<li><a href='javascript:Paginate(" . $i . ",\"List\")' class=\"inactive\"></a></li>";



										}

								}



		$results .= "</ul></div>";

		}





	// Delvuelvo el resultado



   die($results);

}



//Agrega el javascript del Ajax

function add_myjavascript(){

  wp_enqueue_script( 'ajax-implementation.js', get_bloginfo('template_directory') . "/scripts/ajax-implementation.js", array( 'jquery' ), '4.5.3', true );

  }





// Creacion de llamado al Ajax

add_action( 'wp_ajax_nopriv_GenerarGrilla', 'GenerarGrilla' );

add_action( 'wp_ajax_GenerarGrilla', 'GenerarGrilla' );

add_action( 'wp_ajax_nopriv_GenerarTabla', 'GenerarTabla' );

add_action( 'wp_ajax_GenerarTabla', 'GenerarTabla' );

add_action( 'wp_ajax_nopriv_GenerarFiltro', 'GenerarFiltro' );

add_action( 'wp_ajax_GenerarFiltro', 'GenerarFiltro' );

add_action( 'init', 'add_myjavascript' );

add_shortcode( 'menu', 'menu_encuesta' );

// Stop heartbeat
add_action( 'init', 'stop_heartbeat', 1 );
  function stop_heartbeat() {
  wp_deregister_script('heartbeat');
}
