<?php
global $wpdb;
/**
 * Template Name: Buscar Amigos
 * Description: Buscar Amigos
 **/


if (isset($_POST["fetchInfo"])) {

    bp_has_members( bp_ajax_querystring( 'members' ) . '&include='.$_POST["fetchInfo"].'&per_page=7&type=alphabetical&action=alphabetical' );

    echo '<ul  id="members-list" class="item-list" >';
    while ( bp_members() ) {

        bp_the_member();
        ?>
            <li class="iron-member-list-modal" style="float: left;width:150px;">

                <?php
                // Calculate mood bar color
                $class=calculate_moodbar( bp_get_member_user_id() );
                ?>

                <div class="item-avatar <?php echo $class; ?>">
                    <a href="<?php bp_member_permalink() ?>"><?php bp_member_avatar() ?></a>

                    <?php
					// Check online icon
					// Checks users last activity and if less than 5 minute have passed, display online icon
					global $members_template;
					time();
					$online_time=strtotime($members_template->member->last_activity);

					if ($online_time+300>=time())
						echo '<img class="check-online" src="'. get_stylesheet_directory_uri() . '/_inc/images/user_online.png" />';					
					?>

                </div>

                <div class="item" style="width: 130px;">
                    <div class="item-title">
                        <a href="<?php bp_member_permalink() ?>"><b><?php bp_member_name() ?></b></a>

                    </div> <!-- item-title -->

                    <?php do_action( 'bp_directory_members_item' ) ?>
                </div> <!-- item -->

                <div class="clear"></div>

                <div class="iron-action">
                    <?php do_action( 'bp_directory_members_actions' ); ?>
                </div>

                <div class="clear"></div>
            </li>
      <?php
    }
    echo "</ul>";
    return;
}


get_header();
locate_template( array( 'leftsidebar.php' ), true );


global $bp;

// Campos del Perfil que se van a chequear
$fieldid = $wpdb->get_results("SELECT id from wp_bp_xprofile_fields WHERE name LIKE 'Privacidad'");
$fieldid_name = $wpdb->get_results("SELECT id from wp_bp_xprofile_fields WHERE name LIKE 'Nombre'");

// Listado de amigos del usuario actual
$friend_list = explode (',', bp_get_friend_ids(bp_loggedin_user_id()));

// Seleccionar los amigos de los amigos del usuario actual
foreach ($friend_list as $friend_id) {
	$new_friend_list .= bp_get_friend_ids($friend_id);
}
$new_friend_list = substr($new_friend_list,0,-1);

// Si se ha realizado una busqueda
if ($_POST['friend-search'] or isset($_GET["type"])) {
	// Consulta sql

    //echo "#SELECT id from ".$wpdb->users." WHERE id!=".get_current_user_id()."<br />";
	$authors = $wpdb->get_results("SELECT id from ".$wpdb->users." WHERE id!=".get_current_user_id()." and user_status=0"); //

	foreach ($authors as $user) {
	    //echo "SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid[0]->id." AND user_id=".$user->id."<br />";
	    //echo "SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid_name[0]->id." AND user_id=".$user->id."<br />";

		$priv = $wpdb->get_results("SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid[0]->id." AND user_id=".$user->id);
		$name = $wpdb->get_results("SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid_name[0]->id." AND user_id=".$user->id);

		// SI COINCIDE CON LA BUSQUEDA
		if ($_POST['friend-search']) {

		    if (strstr(strtolower($name[0]->value), strtolower($_POST['friend-search']))) {
                // NO INCLUYE USUARIOS PRIVADOS NI AL ACTUAL
                if ($priv[0]->value != "Privado" && $user->id != bp_loggedin_user_id()) {

                	$include_list .= $user->id.",";
                	// SI NO ES AMIGO o TENEMOS LA AMISTAD PENDIENTE, LO MOSTRAMOS
                    /*
                	if (bp_is_friend($user->id) == 'not_friends' || bp_is_friend($user->id) == 'pending') {
                        $include_list .= $user->id.",";
                    }
                    */
                }
            }

		} else {

	        if ($priv[0]->value != "Privado" && $user->id != bp_loggedin_user_id()) {
                // SI NO ES AMIGO o TENEMOS LA AMISTAD PENDIENTE, LO MOSTRAMOS
                if (bp_is_friend($user->id) == 'not_friends' || bp_is_friend($user->id) == 'pending') {
                    $include_list .= $user->id.",";
                }
            }

		}
	} //end foreach

}
else {
	// Consulta sql
	//echo "@SELECT id from ".$wpdb->users." WHERE id IN (". $new_friend_list .")";
	$authors = $wpdb->get_results("SELECT id from ".$wpdb->users." WHERE id IN (". $new_friend_list .")");

	foreach ($authors as $user) {

	    //echo "SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid[0]->id." AND user_id=".$user->id."<br />";
		$priv = $wpdb->get_results("SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid[0]->id." AND user_id=".$user->id);
		//echo "SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid_name[0]->id." AND user_id=".$user->id."<br />";
		$name = $wpdb->get_results("SELECT value from wp_bp_xprofile_data WHERE field_id=".$fieldid_name[0]->id." AND user_id=".$user->id);

		// NO INCLUYE USUARIOS PRIVADOS NI AL ACTUAL
		if ($priv[0]->value != "Privado" && $user->id != bp_loggedin_user_id()) {
			// SI NO ES AMIGO o TENEMOS LA AMISTAD PENDIENTE, LO MOSTRAMOS
			if (bp_is_friend($user->id) == 'not_friends' || bp_is_friend($user->id) == 'pending') {
				$include_list .= $user->id.",";
			}
		}
	}
}

$include_list = substr($include_list,0,-1);
$per_page = 9;
?>

<?php bp_has_members( bp_ajax_querystring( 'members' ) . '&include='.$include_list.'&per_page='.$per_page.'&type=alphabetical&action=alphabetical' ) ?>

<div id="content">
        <div id="iron-encabezado-container">
            <h2 class="iron-encabezado-seccion"><?php _e('Haz amigos', 'buddypress'); ?></h2>

            <ul class="iron-encabezado-ul">
            	<?php if($_GET["type"] == "geo") { ?>
                	<li class="iron-encabezado-li"><a href="<? echo home_url("members-modal/index.php"); ?>"><?php _e('Buscar por nombre', 'buddypress'); ?></a></li>
                	<?php }
                	else { ?>
                	<li class="iron-encabezado-li"><a href="<? echo home_url("members-modal/index.php?type=geo"); ?>"><?php _e('Buscar por proximidad', 'buddypress'); ?></a></li>
                	<?php } ?>
            </ul>

        </div>

        <div class="padder">

            <div id="content-top"></div>

            <?php do_action( 'bp_before_directory_activity_content' ) ?>

            <div id="content-middle" style="padding: 0px 20px; width:auto;">
            <?php if(isset($_GET["type"]) and $_GET["type"] == "geo") { ?>

                <?php /*
                <div style="float: right; padding: 7px 10px 0pt;">
                    <a href="<? echo home_url("members-modal/index.php"); ?>"><?php _e('Buscar por nombre', 'buddypress'); ?></a>
                </div>
                */ ?>
                <h3 class="modal"><?php _e('Busca usuarios por próximidad', 'buddypress'); ?></h3>
                <?php
                    $geoUsers = array();

                    while ( bp_members() ) {

                        bp_the_member();
                        $userId = bp_get_member_user_id();
                        $pais = bp_get_member_profile_data(array('field' => 'Pais'));

                        if(!$pais) {

                            $pais = "ES";
                        }

                        if ($pais != "" or true) {

                            $poblacion = bp_get_member_profile_data(array('field' => 'Poblacion'));
                            $poblacion = trim($poblacion);

                            if ($poblacion != false) {

                                $geoUsers[$pais][$poblacion]["data"][] = array(
                                    'id' => $userId,
                                    'username' => apply_filters( 'bp_member_name', bp_get_member_name() ),
                                );

                                $geoUsers[$pais][$poblacion]["ids"][] = $userId;
                            }
                        }
                  } //end while
                ?>
                <div style="width:485px; height:300px;" id="map_canvas"></div>
                <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
                <script type="text/javascript">
                var marker = null;
                (function(jQuery) {

                    var $ = jQuery;
                    var map = null;
                    var geocoder = null;

                    var infowindow = new google.maps.InfoWindow();

                    var markers = new Array();

                    $(document).ready(function () {

                        if (map != null) {

                            return;
                        }

                        var myLatlng = new google.maps.LatLng(40.4166, -3.7003);
                        var myOptions = {
                          zoom: 5,
                          center: myLatlng,
                          mapTypeId: google.maps.MapTypeId.ROADMAP
                        };

                        geocoder = new google.maps.Geocoder();
                        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

                        <?php

                          foreach ($geoUsers as $pais => $users) {

                              foreach ($users as $localidad => $data) {
                              ?>
                                    find("<?php echo $localidad.", ".$pais; ?>","<?php echo implode(",",$data["ids"]);?>");
                              <?php
                              }
                          }
                        ?>
                    });

                    function find (address, info) {

                         geocoder.geocode( { 'address': address}, function(results, status) {

                              if (status == google.maps.GeocoderStatus.OK) {

                                var marker = new google.maps.Marker({
                                    map: map,
                                    position: results[0].geometry.location,
                                    title : results[0].formatted_address
                                });

                                markers.push(marker);

                                google.maps.event.addListener(marker, 'click', function(e) {

                                	var currentMarker = this;
                                	jQuery.ajax({
                                	    type: 'POST',
                                	    url: document.location.href,
                                	    data: {fetchInfo : info},
                                	    async : false,
                                	    success: function (resp) {

                                            infowindow.setContent(resp);
                                            infowindow.open(map,currentMarker);
                                    	}
                            		});
                                });
                              }
                          });
                    }

                })(jQuery);

                </script>

            <?php } else { ?>
            	<?php /*
                <div style="float: right; padding: 7px 10px 0pt;">
                    <a href="<? echo home_url("members-modal/index.php?type=geo"); ?>">Buscar por próximidad geográfica</a>
                </div>
                */ ?>
                <h3 class="modal"><?php _e('Busca usuarios por nombre', 'buddypress'); ?></h3>
                <form action="<?php echo site_url() . '/members-modal/index.php'; ?>" method="post" id="members-directory-form" class="dir-form">
                    <div id="members-modal-dir-search" class="dir-search">
                        <input type="text" name="friend-search" value="<?php echo $_POST['friend-search']; ?>" maxlength="100" style="width: 200px;">
                        <input type="submit" value="<?php _e ('Buscar','buddypress'); ?>">
                    </div><!-- #members-dir-search -->
                </form>

                <?php if ($include_list) : ?>
                    <?php if (!$_POST['friend-search']) { ?>
                    	<h3 class="modal"><?php _e('O tal vez conozcas a ...', 'buddypress'); ?></h3>
                    <?php } else { ?>
                    	<h3 class="modal"><?php _e('Resultados de la b&uacute;squeda', 'buddypress'); ?></h3>
                    <?php } ?>

                	<div id="pag-top" class="pagination">
                		<div class="pag-count" id="member-dir-count-top">
                			<?php //bp_members_pagination_count() ?>
                		</div>

                		<div class="pagination-links" id="member-dir-pag-top">
                			<?php bp_members_pagination_links() ?>
                		</div>
                	</div>
                	<ul id="members-list" class="item-list" style="padding-top: 14px; height: 380px;">

                	<?php while ( bp_members() ) { bp_the_member(); ?>

                		<li class="iron-member-list-modal" style="float: left;">

                			<?php
                			// Calculate mood bar color
                			$class=calculate_moodbar( bp_get_member_user_id() );
                			?>

                			<div class="item-avatar <?php echo $class; ?>">
                				<a href="<?php bp_member_permalink() ?>"><?php bp_member_avatar() ?></a>

                				<?php
								// Check online icon
								// Checks users last activity and if less than 5 minute have passed, display online icon
								global $members_template;
								time();
								$online_time=strtotime($members_template->member->last_activity);

								if ($online_time+300>=time())
									echo '<img class="check-online" src="'. get_stylesheet_directory_uri() . '/_inc/images/user_online.gif" />';								
								?>

                			</div>

                			<div class="item" style="width: 130px;">
                				<div class="item-title">
                					<a href="<?php bp_member_permalink() ?>"><b><?php bp_member_name() ?></b></a>

                					<?php /*
                					<?php if ( bp_get_member_latest_update() ) : ?>

                						<span class="update"> - <?php bp_member_latest_update( 'length=10' ) ?></span>

                					<?php endif; ?>
                					*/ ?>

                				</div> <!-- item-title -->

                				<?php do_action( 'bp_directory_members_item' ) ?>

                			</div> <!-- item -->

                			<div class="clear"></div>

                			<div class="iron-action">
                				<?php do_action( 'bp_directory_members_actions' ); ?>
                			</div>

                			<div class="clear"></div>
                		</li>

                	<?php } //endwhile; ?>
                	</ul>

                <?php else : ?>

                	<div class="item-list" style="padding-top: 14px; height: 380px;">
                	<?php if ($_POST['friend-search']) {
                		_e('No se han encontrado resultados para la b&uacute;squeda','buddypress');
                		echo' <i>'. $_POST['friend-search'] .'</i>';
                	} else {
                	    ?>
                	    <h3 class="modal"><?php _e('O tal vez conozcas a ...', 'buddypress'); ?></h3>
                	    <?php
                		_e('No tenemos ninguna sugerencia de amistad para t&iacute; en estos momentos. Prueba a encontrar a tus amigos realizando una b&uacute;squeda.','buddypress');
                	} ?>
                	</div>

                <?php endif; ?>
            <?php } //end if ?>
            </div>
            <div id="content-bottom"></div>
         </div>
</div>
<?php locate_template( array( 'sidebar.php' ), true ) ?>
<?php get_footer() ?>