<?php
function validateEmail($Email) {

    $errorArray = array();

    if( ! is_email($Email)) {

        $errorArray["signup_email"] = __("El email facilitado no parece ser válido", 'buddypress');

    } else if( email_exists($Email) ) {

        $errorArray["signup_email"] = __("Ya existe un usuario con este email", 'buddypress');
    }

    return $errorArray;
}

function validateUsername($Username) {

    $errorArray = array();

    if(strlen($Username) < 4) {

        $errorArray["signup_username"] = __("El nombre de usuario debe tener, al menos, 4 caracteres", 'buddypress');

    } else if (!validate_username($Username)) {

        $errorArray["signup_username"] = __("El nombre de usuario no parece correcto", 'buddypress');

    } else if ( is_numeric(username_exists($Username)) ) {

        $errorArray["signup_username"] = __("Nombre no disponible", 'buddypress');
    }

    return $errorArray;
}

if ( (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") ) {

    if (isset($_GET["fetch"]) and $_GET["fetch"] == "msgs") {

        $errorArray = array();
        $errorArray["signup_username"] = __("El nombre de usuario debe tener, al menos, 4 caracteres", 'buddypress');

        $errorArray["signup_password"][] = __("Las contraseñas facilitadas no coinciden", 'buddypress');
        $errorArray["signup_password"][] = __("La contraseña debe tener, al menos, 4 caracteres", 'buddypress');

        $errorArray["privacity_level"] = __("No ha seleccionado un grado de privacidad", 'buddypress');
        $errorArray["Poblacion"] = __("Por favor indique su población", 'buddypress');

        echo json_encode($errorArray);
        return;
    }

    if (isset($_GET["validate"])) {

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

            $resp = validateEmail($_POST["signup_email"]);
            $resp = isset($resp["signup_email"]) ? $resp["signup_email"] : "";

            echo json_encode(array("msg" => $resp));
            return;
        }

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

            $resp = validateUsername($_POST["signup_username"]);
            $resp = isset($resp["signup_username"]) ? $resp["signup_username"] : "";

            echo json_encode(array("msg" => $resp));
            return;
        }
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php

get_header("modals");
global $bp;

// REGISTER SCRIPT
wp_deregister_script( 'registrationScpt' );
wp_register_script( 'registrationScpt', get_stylesheet_directory_uri() .'/_inc/registration/registration.js', '' );
wp_print_scripts( 'registrationScpt' );

// Retrieve value of st
// to obtain user's category/estadoanimo
$st= (int)strip_tags($_GET['st']);

// Post confirmed
$errorArray = array();

if (count($_POST) > 0) {

//iron_signup_mail_message(996);

	// Retrieve variables
	if (!$st) $st=(int)strip_tags($_POST['st']);
	if (!$st) $st=5; // Default category/estadoanimo (sintomaticos)
	$cat=get_category($st);
	$NombreCompleto=strip_tags($_POST['signup_displayname']);
	$Apellidos=strip_tags($_POST['signup_apellidos']);
	$Username=strip_tags($_POST['signup_username']);
	$Password=strip_tags($_POST['signup_password']);
	$Email=strip_tags($_POST['signup_email']);
	$Poblacion=strip_tags($_POST['Poblacion']);
	$Pais =  strip_tags($_POST['pais']);
	$Patologia=strip_tags($_POST['Patologia']);
	$Privacidad=strip_tags($_POST['privacity_level']);
	$Estado=$cat->slug;
	$Categoria=$cat->slug;
	$signup_profile_field_ids=$_POST['signup_profile_field_ids'];

	$userAvatar = $_POST["userAvatar"];
	$userAvatarMime = $_POST["userAvatarMime"];
	$userAvatarSize = $_POST["userAvatarSize"];

	// Chek if user exist's
	$user_id = username_exists( $Username );

    //username
    if(!is_null($user_id)) {

        $errorArray["signup_username"] = __('Ya existe un usuario con ese nombre.', 'buddypress');
    }

	//user password
	if(!isset($_POST["signup_password"]) or !isset($_POST["signup_password_confirm"]) or ($_POST["signup_password"] == "")
	   or ($_POST["signup_password"] != $_POST["signup_password_confirm"])
	) {

	    $errorArray["signup_password"] = __("Las contraseñas facilitadas no coinciden", 'buddypress');

	} else if (strlen($_POST["signup_password"]) < 4) {

	    $errorArray["signup_password"] = __("La contraseña debe tener, al menos, 4 caracteres", 'buddypress');
	}

	//Username
	$errorArray = array_merge($errorArray, validateUsername($Username));

	//email
	$errorArray = array_merge($errorArray, validateEmail($Email));

	//privacidad
	if($Privacidad == "") {

	    $errorArray["privacity_level"] = __("No ha seleccionado un grado de privacidad", 'buddypress');
	}

	if($_POST["Poblacion"] == "") {

	    $errorArray["Poblacion"] = __("Por favor indique su población", 'buddypress');
	}

    $isValid = count($errorArray) == 0 ? true : false;

	if ( $_POST['confirm']=="true" && $isValid) {


		

		// Create user
		$user_id = bp_core_signup_user($Username, $Password, $Email, '' );
        update_user_meta( $user_id, 'activation_key', wp_hash( $user_id ) );

		if(! $user_id instanceof WP_Error) {

            // Add User meta
            update_user_meta( $user_id, 'first_name', $NombreCompleto);
            //update_user_meta( $user_id, 'bp_profile_privacy', 's:57:"s:49:"a:5:{i:0;s:0:"";i:2;i:0;i:3;i:0;i:4;i:0;i:5;i:0;}";";');
            // Ultimpo bp-profile-privacy data
            update_user_meta( $user_id, 'bp_profile_privacy', 'a:4:{i:0;s:57:"s:49:"a:5:{i:0;s:0:"";i:2;i:0;i:3;i:0;i:4;i:0;i:5;i:0;}";";i:4;i:2;i:3;i:0;i:25;i:0;}');

            // Profile data
            if ( function_exists( 'xprofile_set_field_data' ) ) {

                if ( !empty( $signup_profile_field_ids ) ) {
                    $profile_field_ids = explode( ',', $signup_profile_field_ids );

                    foreach( (array)$profile_field_ids as $field_id ) {

                        if ($field_id == 1) $current_field_data=$NombreCompleto;
                        elseif ($field_id == 2) $current_field_data=$Apellidos;
                        elseif ($field_id == 3) $current_field_data=$Poblacion;
                        elseif ($field_id == 4) $current_field_data=$Patologia;
                        elseif ($field_id == 5) $current_field_data=$Estado;
                        elseif ($field_id == 10) $current_field_data=$Categoria;
                        elseif ($field_id == 15) $current_field_data=$Privacidad;
                        elseif ($field_id == 25) $current_field_data=$Pais;

                        if ( !empty( $current_field_data ) ) {

                            xprofile_set_field_data( $field_id, $user_id, $current_field_data );
                        }
                    }

                }
            }

            //move Avatar files
            $sourcePath= str_replace("\\","/", getcwd())."/wp-content/uploads/avatars/signups/";
            $targetPath= str_replace("\\","/", getcwd())."/wp-content/uploads/avatars/".$user_id."/";

            if (!file_exists($targetPath)) {

                mkdir($targetPath, 0777, true);
            }

            //chmod($targetPath, 0777);

            if( file_exists($sourcePath.$userAvatar) and  $userAvatar != "") {

                rename($sourcePath.$userAvatar, $targetPath.$userAvatar);
                $userAvatar = str_replace("bpfull", "bpthumb", $userAvatar);

                rename($sourcePath.$userAvatar, $targetPath.$userAvatar);
            }

            iron_signup_mail_message($user_id);

		} else {

            $isValid = false;
            $errorArray["otros"] = $user_id->errors["registerfail"][0];
		}

	}
}
?>

<?php // Para pasarle la ruta de la imagen a mytabs.js ?>
<input type="hidden" id="ruta_imagen" name="ruta_imagen" value="<?php echo get_stylesheet_directory_uri() . "/registration/images/"; ?>" />

<div class="tunnel-counter">
	<ul id="tablist" class="tabul">
		<?php

		if($_POST['confirm']=="true") {

            $img  = "slider_counter_grey.png";
            $img2 = "slider_counter_on.png";

		} else  {

		    $img = $img2 = "slider_counter_off.png";
		}

		// Si viene desde Register, marcamos la segunda bolita
		if ($_POST['confirm']=="true") {
		?>
            <li class="tabtrigger"><img id="tabtrigger_1" style=""
            src="<?php echo get_stylesheet_directory_uri() . "/registration/images/slider_counter_grey.png"; ?>" /></li>
            <li class="tabtrigger"><img id="tabtrigger_2" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/slider_counter_grey.png"; ?>" /></li>
		<?php
		} else if ($st) { ?>
			<li class="tabtrigger"><img id="tabtrigger_1" style="visivility:hidden;"
			src="<?php echo get_stylesheet_directory_uri() . "/registration/images/slider_counter_on.png"; ?>" /></li>
			<li class="tabtrigger"><img id="tabtrigger_2" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/slider_counter_off.png"; ?>" /></li>
			<?php }
		else { ?>
			<li class="tabtrigger"><img id="tabtrigger_1" style="visivility:hidden;"
			src="<?php echo get_stylesheet_directory_uri() . "/registration/images/slider_counter_grey.png"; ?>" /></li>
			<li class="tabtrigger"><img id="tabtrigger_2" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/slider_counter_on.png"; ?>" /></li>
		<?php } ?>

		<li class="tabtrigger"><img id="tabtrigger_3" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/".$img; ?>" /></li>
		<li class="tabtrigger"><img id="tabtrigger_4" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/".$img; ?>" /></li>
		<li class="tabtrigger"><img id="tabtrigger_5" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/".$img; ?>" /></li>
		<li class="tabtrigger"><img id="tabtrigger_6" src="<?php echo get_stylesheet_directory_uri() . "/registration/images/".$img2; ?>" /></li>
	</ul>
	<script type="text/javascript">
    	(function(jQuery) {

    		  var $ = jQuery;

    		   $(document).ready(function () {

    			     $("#tablist img").click(function () {

    			    	    var img = $(this);

    			    	    if (img.attr("src").indexOf("slider_counter_grey.png") >= 0) {

    			    	    	var id = $(this).attr("id").replace(/[^0-9]*/i,"");
    			    	    	$("#tabcontinue_"+id).click();
        			    	}
        			 });
    		   });
    	})(jQuery);
	</script>
</div> <!-- tunnel-counter -->
<!-- TAB CONTENT 1 -->
<div id="mytab_1" class="tabcontent" <? if (!$st || count($_POST) > "") echo 'style="display: none;"'; else echo 'style="display: block;"'; ?>>

	<div id="tunnel-box">
		<div class="tunnel-title"><h1><?php echo __('¿Qu&eacute; vas a encontrar en la comunidad?', 'buddypress'); ?></h1></div>
		<div class="tunnel-action">

<?php
		$data = iron_tunnels_get_category_data($st);

		$clase = "st".$data->category_order;
		$clase2 = "tags".$data->category_order;

?>

			<div class="tunnel-chats <?php echo $clase?>">

				<?php iron_tunnels_display($st); ?>

			</div>
			<div class="tunnel-tags <?php echo $clase2?>">
				<?php iron_tunnels_display_tagcloud($st); ?>
			</div>
		</div>
		<div class="tunnel-buttons">
			<input type="button" value="<?php echo __('Continuar', 'buddypress'); ?>" id="tabcontinue_2" class="tunnel-next" />
		</div>
	</div> <!-- tunnel-box -->
</div>

<!-- TAB CONTENT 2 -->
<div id="mytab_2" class="tabcontent" <? if ( ((!isset($st) or $st < 1) and count($_POST) == 0)  or (count($errorArray) != 0 and ! isset($_POST["confirm"]))) echo 'style="display: block;"'; else echo 'style="display: none;"'; ?>>
<?php $lang_cookie_lang = $_COOKIE['LANG']; ?>
	<div id="tunnel-box">
		<div class="tunnel-title"><h1><?php echo __('Dinos qui&eacute;n eres', 'buddypress'); ?></h1></div>
		<div class="tunnel-action">
			<div class="tunnel-pic">
				<div id="dinamic_content_1" class="loadimg">
				<!-- UPLOAD FORM -->
                    <iframe id="upload_target" name="upload_target"
                    style="border: 0px solid rgb(255, 255, 255); width: 150px; overflow: hidden; height: 165px;background-color:transparent;"
                    src="<?php echo get_stylesheet_directory_uri().'/_inc/din-upload/din-upload.php'; ?>" frameBorder="0" scrolling="no"></iframe>

				</div>
			</div>

			<!-- SIGNUP FORM -->
			<form id="signupform" name="signupform" action="<?php echo site_url() . '/register'; ?>" method="post">
            <input type="hidden" value="1,2,4,3,10,15,25" id="signup_profile_field_ids" name="signup_profile_field_ids">
            <input type="hidden" id="userAvatar" name="userAvatar" value="<?php echo isset($_POST["userAvatar"]) ? $_POST["userAvatar"] : ""; ?>" />
            <input type="hidden" id="userAvatarMime" name="userAvatarMime" value="<?php echo isset($_POST["userAvatarMime"]) ? $_POST["userAvatarMime"] : ""; ?>" />
            <input type="hidden" id="userAvatarSize" name="userAvatarSize" value="<?php echo isset($_POST["userAvatarSize"]) ? $_POST["userAvatarSize"] : ""; ?>" />

			<div class="tunnel-data" style="">
				<label for="signup_displayname"><?php _e( 'Nombre', 'buddypress' ) ?></label>
				<input type="text" name="signup_displayname" id="signup_displayname" value="<?php echo $NombreCompleto; ?>" />
                <span style="color:red;"><?php if(isset($errorArray["signup_displayname"])) { echo $errorArray["signup_displayname"]; } ?></span>
				<label for="signup_displayname"><?php _e( 'Apellidos', 'buddypress' ) ?></label>
				<input type="text" name="signup_apellidos" id="signup_apellidos" value="<?php echo $Apellidos; ?>" />
                <span style="color:red;"><?php if(isset($errorArray["signup_apellidos"])) { echo $errorArray["signup_apellidos"]; } ?></span>

				<label for="signup_username"><?php _e( 'Nombre de Usuario', 'buddypress' ) ?></label>
				<input type="text" name="signup_username" id="signup_username" value="<?php bp_signup_username_value() ?>" />
                <span style="color:red;"><?php if(isset($errorArray["signup_username"])) { echo $errorArray["signup_username"]; } ?></span>

				<label for="signup_email"><?php _e( 'Direcci&oacute;n de correo', 'buddypress' ) ?></label>
				<input type="text" name="signup_email" id="signup_email" value="<?php bp_signup_email_value() ?>" />
				<span style="color:red;"><?php if(isset($errorArray["signup_email"])) { echo $errorArray["signup_email"]; } ?></span>

				<label for="signup_password"><?php _e( 'Elige una contrase&ntilde;a', 'buddypress' ) ?></label>
				<input type="password" name="signup_password" id="signup_password" value="" />
				<span style="color:red;"><?php if(isset($errorArray["signup_password"])) { echo $errorArray["signup_password"]; } ?></span>

				<label for="signup_password_confirm"><?php _e( 'Confirma la contrase&ntilde;a', 'buddypress' ) ?></label>
				<input type="password" name="signup_password_confirm" id="signup_password_confirm" value="" />

			</div>
		</div>
		<div style="display: block; clear: both;"> </div>
		<?php
		switch ($lang_cookie_lang) {
		    case 'es':
		            //$post_id_termns = 218;//test218
		            //$post_id_Privac = 214;//test218
		            $post_id_termns = 249;
		            $post_id_Privac = 250;
		    break;
		    case 'en':
		            $post_id_termns = 283;
		            $post_id_Privac = 281;
		    break;
		    case 'eu':
		            $post_id_termns = 282;
		            $post_id_Privac = 280;
		    break;
		    default;
		            $post_id_termns = 249;
		            $post_id_Privac = 250;
		}
		?>
                <div id="privacypolicy">
                <?php
                $post = get_post($post_id_Privac); 
                echo $post->post_content;
                ?>
                </div>
                
                <div id="termsuse">
                <?php
                $post = get_post($post_id_termns); 
                echo $post->post_content;
                ?>
                </div>


    <div class="privacy_policy" style="min-height:40px;">
                <label for="privacy_policy_check"><?php _e( 'I accept the Privacy policy And Terms of use.', 'buddypress' ); ?></label>
                <input type="checkbox" name="privacy_policy" id="privacy_policy_check" value="" />
                <span id="privacy_policy_a"><?php _e('Pol&iacute;tica de Privacidad','buddypress') ?> - </span>
                <span id="terms_use_a"><?php _e('Condiciones de uso','buddypress') ?></span>
    </div>

        <div class="tunnel-buttons">
            <input type="button" value="<?php echo __('Continuar', 'buddypress'); ?>" id="tabcontinue_3" class="tunnel-next"  disabled />
        </div>
<script>
(function($) {
	$('#privacy_policy_a').click(function () {
	    $('#privacypolicy').fadeIn(850, function () {
	          $('#privacypolicy').attr('class','privacypolicy_c');
		          $('#termsuse').fadeOut(500, function () {
		        	  $('html, body').animate({ scrollTop: '400px' }, 'slow');
		          });      
	    });
	});
    $('#terms_use_a').click(function () {
        $('#termsuse').fadeIn(850, function () {
              $('#termsuse').attr('class','privacypolicy_c');
	              $('#privacypolicy').fadeOut(500, function () {
	            	  $('html, body').animate({ scrollTop: '400px' }, 'slow');
	              });
        });
    });
	
	$('#privacy_policy_check').click(function () {
		if ( $('#privacy_policy_check').is(':checked') == true ){
			 $('#tabcontinue_3').removeAttr("disabled");
			} else {
			 $('#tabcontinue_3').attr('disabled', "disabled");
			} 
    });
})(jQuery);
</script>
	</div><!-- tunnelbox -->
</div>



<!-- TAB CONTENT 3 -->
<?php // GEOLOCATION
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
	if($pos=strpos($_SERVER["HTTP_X_FORWARDED_FOR"]," ")) {
		$ip = substr($_SERVER["HTTP_X_FORWARDED_FOR"],$pos+1);
	} else {
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}
} else {
	$ip = $_SERVER["REMOTE_ADDR"];
}

// Obtain Data from GeoIP database
//$GeoLocation = geoip_record_by_name('82.223.160.201'); // Esto es de prueba, una ip de Logroño


$GeoLocation = geoip_record_by_name($ip);
$GeoCity = utf8_encode($GeoLocation['city']);
?>

<div id="mytab_3" class="tabcontent" style="display: none;"; >

	<div id="tunnel-box">
		<div class="tunnel-title"><h1><?php echo __('¿D&oacute;nde te encuentras?', 'buddypress'); ?></h1></div>
		<div class="tunnel-action">
			<label for="poblacion"><?php echo __('Poblaci&oacute;n', 'buddypress'); ?></label>
			<?php /*<input type="text" name="Poblacion" id="Poblacion" value="<?php echo $Poblacion != "" ? $Poblacion : $GeoLocation; ?>" /> */ ?>
			<input type="text" name="Poblacion" id="Poblacion" value="<?php echo $GeoCity; ?>" />
            <select name="pais" id="Pais">
                    <?php
                    global $wpdb;

                    $results = $wpdb->get_results("SELECT * FROM iron_paises");

                    $targetCountry = isset($Pais) ? $Pais : "ES";

                    foreach ($results as $pais) {
                        if ($targetCountry == $pais->valor ) {

                            $sel="selected='selected'"; $s=1;
                        } else {

                            $sel = "";
                        }

                        echo '<option value="'. $pais->valor .'" '.$sel.'>'. $pais->pais .'</option>';
                    }


                    ?>

            </select>
            <span style="color:red;"><?php if(isset($errorArray["Poblacion"])) { echo $errorArray["Poblacion"]; } ?></span>


    <?php /*



<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&key=AIzaSyCJAoHvUyhZdfRQ1j6CzrsJloTviwH-aN8"></script>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&key=AIzaSyAqrP65jiBYXFbw0y7K-TBv-oujnBy5AyA"></script> -->
            
<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyCJAoHvUyhZdfRQ1j6CzrsJloTviwH-aN8" type="text/javascript"></script>

 die('a');*/ ?>



<script type="text/javascript"
    src="https://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 markers = new Array();

                $("#Poblacion").focus(function () {

                    if (map != null) {

                        return;
                    }

                	google.maps.Map.prototype.clearMarkers = function() {
                	    for(var i=0; i < this.markers.length; i++){
                	        this.markers[i].setMap(null);
                	    }
                	    this.markers = new Array();
                	};

                    var myLatlng = new google.maps.LatLng(37, -122);
                    var myOptions = {
                      zoom: 7,
                      center: myLatlng,
                      mapTypeId: google.maps.MapTypeId.ROADMAP
                    };

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

                    find($("#Poblacion").attr("value") + " , " + $("#Pais").attr("value"));
                });

                function find (address) {

                	 geocoder.geocode( { 'address': address}, function(results, status) {
                	      if (status == google.maps.GeocoderStatus.OK) {

                              if (markers.length > 0) {

                                  for (i in markers) {

                                      markers[i].setMap(null);
                                  }

                                  markers.push(marker);
                              }

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

                	        markers.push(marker);
                	      }
                	  });
                }

                $("#Poblacion").change(function () {

                	find($(this).attr("value") + " , " + $("#Pais").attr("value"));
                });

            })(jQuery);
            </script>

			<div class="tunnel-map" id="map_canvas">
			<!--
			<iframe width="490" height="230" frameborder="0"
			scrolling="no" marginheight="0" marginwidth="0"
			src="http://maps.google.es/maps?f=q&amp;source=s_q&amp;hl=es&amp;geocode=&amp;q=<?php echo $GeoCity; ?>&amp;aq=0&amp;ie=UTF8&amp;hq=&amp;hnear=<?php echo $GeoLocation; ?>&amp;z=12&amp;iwloc=B&amp;output=embed"></iframe>
			 -->
			</div>
		</div>
		<div class="tunnel-buttons">
			<input type="button" value="<?php echo __('Continuar', 'buddypress'); ?>" id="tabcontinue_4" class="tunnel-next" />
		</div>
	</div> <!-- tunnel-box -->

</div>
<!-- TAB CONTENT 4 -->
<div id="mytab_4" class="tabcontent" style="display: none;"; >

	<div id="tunnel-box">
		<div class="tunnel-title"><h1><?php echo __('Cu&eacute;ntanos c&oacute;mo te encuentras', 'buddypress'); ?></h1></div>
		<div class="tunnel-action">
			<label for="patologia"><?php echo __('¿Qu&eacute; te pasa?', 'buddypress'); ?></label>
			<select name="Patologia" style="width:300px;">
                    <?php
                    global $wpdb;
                    $table_name = 'iron_patologias';

                    $familia = 'familia_' . $_COOKIE['LANG'];
                    $patologia = 'patologia_' . $_COOKIE['LANG'];
                    $results = $wpdb->get_results(
                    "SELECT DISTINCT " . $familia . " FROM " . $table_name . " ORDER BY " . $familia);
                    
                    foreach ($results as $fam) {
                        echo '<optgroup label="'. $fam->$familia .'">';

                        $results = $wpdb->get_results(
                        "SELECT " . $patologia . " FROM " . $table_name . " WHERE " . $familia . " ='". $fam->$familia ."' ORDER BY " . $patologia);
                        
                        foreach ($results as $pat) {
                            if (xprofile_get_field_data( 'Patologia', get_current_user_id()) == $pat->$patologia ) { $sel="selected"; $s=1; }
                            else $sel="";
                            echo '<option value="'. $pat->$patologia .'" '. $sel .'>'. utf8_decode($pat->$patologia) .'</option>';
                        }

                        echo '</optgroup>';
                    }
                    ?>
                <optgroup label="<?php _e('Otra patolog&iacute;a','buddypress')?>">
                    <option <?php if ($s!=1) echo 'selected'; ?> value="Otra patolog&iacute;a"><?php _e('Otra patolog&iacute;a','buddypress')?></option>
                </optgroup>
                </select>
			</select>
			<!-- <input type="text" name="Patologia" id="Patologia" value="<?php echo $Patologia; ?>" /> -->
		</div>
		<div class="tunnel-buttons">
			<input type="button" value="<?php echo __('Continuar', 'buddypress'); ?>" id="tabcontinue_5" class="tunnel-next" />
		</div>
	</div> <!-- tunnel-box -->

</div>

<!-- TAB CONTENT 5 -->
<div id="mytab_5" class="tabcontent" style="display: none;"; >

    <script type="text/javascript">

        (function(jQuery) {

            var $ = jQuery;
            var containers = null;

            $(document).ready(function () {

                containers = $("#signup_privacity_select li a");
            	containers.click(function () {

            		containers.removeClass("selected");
                    $(this).addClass("selected");
                    $(this).blur();

                    $("#selected_privacity_level").attr("value", $(this).attr("rel"));
                });
            });

        })(jQuery);

    </script>
	<div id="tunnel-box">
		<div class="tunnel-title"><h1><?php echo __('¿C&oacute;mo quieres comunicarte?', 'buddypress'); ?></h1></div>
		<div class="tunnel-action">

		    <input type="hidden" id="selected_privacity_level" name="privacity_level" value="<?php echo isset($Privacidad) ? $Privacidad : "1"; ?>" />

			<ul id="signup_privacity_select" class="tunnel-privacy">
				<li id="sp_1">
				    <a href="#" rel="En privado" <?php if(isset($Privacidad) and $Privacidad == 2) {?> class="selected" <?php } ?>>
				        <?php echo __('En privado', 'buddypress'); ?>
				    </a>
				</li>
				<li id="sp_2">
				    <a href="#" rel="Con mis amigos" <?php if( (isset($Privacidad) and $Privacidad == 1) or !isset($Privacidad)) {?> class="selected" <?php } ?>>
				        <?php echo __('Con mis amigos', 'buddypress'); ?>
				    </a>
				</li>
				<li id="sp_3">
				    <a href="#" rel="Con toda la comunidad" <?php if(isset($Privacidad) and $Privacidad == 0) {?> class="selected" <?php } ?>>
				        <?php echo __('Con toda la comunidad', 'buddypress'); ?>
				    </a>
				</li>
			</ul>

		</div>
		<div class="tunnel-buttons">
			<input type="submit" value="<?php echo __('Continuar', 'buddypress'); ?>" id="" class="tunnel-next" />
		</div>
	</div> <!-- tunnel-box -->
    <input type="hidden" name="confirm" value="true">
</div>

</form>
<!-- TAB CONTENT 6 -->
<div id="mytab_6" class="tabcontent" <? if (isset($_POST['confirm'])) { echo 'style="display: block;"'; } else { echo 'display:none;'; }?>>

	<div id="tunnel-box">
		<div class="tunnel-title"><h1><?php echo __('¡ Muchas gracias !', 'buddypress'); ?></h1></div>
		<div class="tunnel-action">
		<?php
		  if(count($errorArray) == 0) {
		?>
		    <p><?php echo __('En breve recibir&aacute;s un correo electr&oacute;nico para validar el registro.', 'buddypress'); ?></p>


<?php

 if ( $_POST['confirm']=="true" && $isValid) {


?>

<!-- LAST STEP -->
<!-- Google Code for Registro completo Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 995460852;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "ckOACKSrngQQ9I3W2gM";
var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="https://www.googleadservices.com/pagead/conversion/995460852/?value=0&amp;label=ckOACKSrngQQ9I3W2gM&amp;guid=ON&amp;script=0"/>
</div>
</noscript> 


<?php
}
?>


            <div class="tunnel-buttons">
                <?php /*<input type="submit" class="tunnel-next" value="<?php _e('Finalizar', 'buddypress') ?>" onclick="parent.jQuery.fancybox.close();" /> */?>
                <?php /*<input type="submit" class="tunnel-next" value="<?php _e('Finalizar', 'buddypress') ?>" /> */?>

                <input type="hidden" id="signup_privacidad" name="Privacidad" value="2">
                <input type="hidden" id="signup_profile_field_ids" name="signup_profile_field_ids" value="1,2,3,4,5,10,15">
                <input type="hidden" name="st" value="<?php echo $st; ?>">
                <input id="finishRegister" type="button" class="tunnel-next"  value="<?php _e( 'Finalizar', 'buddypress' ) ?> &rarr;" />
            </div>
		<?php
		  } else {
		?>
		  <form id="signupform" name="signupform" action="<?php echo site_url() . '/register'; ?>" method="post">
		   <p>
		      <?php echo __('El registro no pudo completarse debido a los <span style="color:red;">errores detallados a continuación</span>.
              Por favor pulse en volver y complete las campos pendientes.', 'buddypress'); ?>
		   </p>
           <div>
            <?php
                // Debug
                echo "<ol style='color:red;list-style:upper-roman outside none;text-align:left;margin-left:130px;'>";
                foreach($errorArray as $key => $val) {

                    echo "<li>$val</li>";
                }
                echo "</ol>";
            ?>
             <div class="tunnel-buttons">
                <?php

                    foreach($_POST as $key => $value) {

                        if($key == "confirm") {

                            continue;
                        }
                    ?>
                     <input type="hidden" name="<?php echo $key; ?>" value="<?php echo $value; ?>" />
                    <?php
                    }
                ?>
                <!-- <input type="hidden" id="signup_profile_field_ids" name="signup_profile_field_ids" value="1,2,3,4,5,10,15"> -->
                <input type="hidden" name="st" value="<?php echo $st; ?>">
                <input type="submit" class="tunnel-next"  value="<?php _e( 'Volver', 'buddypress' ) ?> &rarr;" />
             </div>
           </div>
          </form>
		<?php
		  } //end if
		?>
		</div>

	</div>

</div>

<?php // wp_nonce_field( 'bp_new_signup' ) ?>
<!-- Google Analytics -->

                <script type="text/javascript">

                  var _gaq = _gaq || [];
                  _gaq.push(['_setAccount', 'UA-23573028-1']);
                  _gaq.push(['_setDomainName', '.kronikoensarea.net']);
                  _gaq.push(['_trackPageview']);

                  (function() {
                    var ga = document.createElement('script'); ga.type =
                'text/javascript'; ga.async = true;
                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
                'http://www') + '.google-analytics.com/ga.js';
                    var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(ga, s);
                  })();

                </script>

 <!-- signupform -->

</body>
</html>
