<?php 
session_start();

$show_view = true; // Note: this must come before common.php

include "php/common.php";
ensure_alive();

// Query count
$qcount = isset( $_COOKIE["qcount"] ) ? intval( $_COOKIE["qcount"] ) : 0;

$strip_dashes = safe_get_arg( $_GET, 'strip_dashes' ) == 'true';

// Globals
$query =  safe_get_arg( $_GET, 'query' );
if ( $strip_dashes )  // https://marathonview.net/marathon-results-of-Marie-No%C3%ABlle-Lamer
	$query = preg_replace( '/-/', ' ', $query );
	

$actual_query = $query;
$MAX_NON_LOGIN = 3;
$is_it_me = false;
$is_member = false;
$loose = safe_get_arg( $_GET, "loose");

$loose = $loose === 'true';

$is_logged_in = is_logged_in();
$qtype = "name";  // $qtype can be "name", "bib" or "fid"

$title = '';
$h1_text = '';
$name = '';

// These are not always needed but should be declared
$name = '';
$country = '';
$result_count = 0;

if ( !$query  )
{
	header("Location: " . getBase());
	die();
}


if ( !$is_logged_in &&  $qcount >= $MAX_NON_LOGIN )
{
	assert_login();
	die();
}

$one_word = preg_match( "/\s*/", $query ) === 0;
$exact = isset( $_GET[ "exact" ] ) && $_GET[ "exact" ] == 'true';
$members_first = !isset( $_GET[ "members_first" ] ) || ( $_GET[ "members_first" ] == 'true' );

$is_error = false;
$error_text = '';


		
if (preg_match("/^[0-9]{7,}$/", $query ) ) // That's an fid
	$qtype = "fid";
else 
{
	if (preg_match("/^[0-9]{,7}$/", $query ) ) // That's a bib
	$qtype = "bib";
}
		
if ( $query == "__SELF__" )
{
	assert_login();
	$actual_query = $_SESSION["user"]["fid"];
	$qtype = "fid";
	$is_it_me = true;
}
	
$heat_type = GetAppType() == 1 ? 3 : 0;
$marathon_results_str = GetAppType() == 1 ? 'Marathon results' :  L( 'Race results' );
$response_type = 'results_for_name';

// Find users. We do it in all cases of name search
if ( $qtype == "name"  ) 
{
	$res = SysApiGet(  "user/search/" . rawurlencode($actual_query) );
	if ( $res['status'] != 200 )
	{
		$is_error = true;
		$error_text = $res["body"];
		goto error_point;
	}

	
	$members_obj = json_decode( $res['body'], true );
	$members_count = count( $members_obj );
	$jsonstr = $res['body'];
	
	if ( $members_count == 0 )
		$members_first = false; // No members so search for name
	
	if ( $members_count == 1 && $members_first )
	{
		// Search this member using the fid
		$options = array ( 'search_type' => 2 , 'ipaddress' =>$_SERVER['REMOTE_ADDR'], 'heat_type' =>$heat_type);
		$fid = $members_obj[0]['fid'];
		
		$res = SysApiPost( "results/search/" . $fid , $options);
		if ( $res['status'] != 200 )
		{
			$is_error = true;
			$error_text = $res["body"];
			goto error_point;
		}
		
		$jsonstr = $res['body'];
		$response_type = 'results_for_fid';
	}

	else 
	{
		if ( $members_count > 1 && $members_first )
		{
			$response_type = 'member-suggestions';	
			$h1_text =  $title = L('Did you mean one of these?');
		}
		else 
		{
			$options = array ( 'search_type' => 'name', 'loose' => $loose, 'heat_type' =>$heat_type , 'ipaddress' =>$_SERVER['REMOTE_ADDR'] ); // Name
			$res = SysApiPost( "results/search/" . rawurlencode( $actual_query ) , $options);
			if ( $res['status'] != 200 )
			{
				$is_error = true;
				$error_text = $res["body"];
				goto error_point;
			}
			
			
			$jsonstr = $res['body'];

			$response_type = 'results_for_name';
			
			if ( is_rtl() ) 
				$h1_text =  $title = "התוצאות של " . ucwords( stripslashes (  $actual_query ));
			else
				$h1_text =  $title = "$marathon_results_str of " . ucwords( stripslashes (  $actual_query ));
			$name = $actual_query;
		}		
	}

}

if ( $qtype == "fid" && $response_type != 'member-suggestions'  ) 
{
	$fid = $actual_query ;

	// Search this member using the fid
	$options = array ( 'search_type' => 2 , 'ipaddress' =>$_SERVER['REMOTE_ADDR'], 'heat_type' => $heat_type );
	$res = SysApiPost( "results/search/" . $fid , $options);
	if ( $res['status'] != 200 )
	{
		$is_error = true;
		$error_text = $res["body"];
		goto error_point;
	}
	
	$jsonstr = $res['body'];
	$response_type = 'results_for_fid';
	
		if ( is_rtl() ) 
			$h1_text =  $title = "התוצאות של " .  preg_replace( '/-/', ' ', $query );
		else
			$h1_text =  $title = "$marathon_results_str of " .  preg_replace( '/-/', ' ', $query );

}

if ( $qtype == "bib"  ) 
{
	// Search this member using the fid
	$options = array ( 'search_type' => 3, 'ipaddress' =>$_SERVER['REMOTE_ADDR'], 'heat_type' => $heat_type  ); // Bib
	$bib = $actual_query ;
	
	$res = SysApiPost( "results/search/" . $bib , $options);
	if ( $res['status'] != 200 )
	{
		$is_error = true;
		$error_text = $res["body"];
		goto error_point;
	}
	
	$jsonstr = $res['body'];
	$response_type = 'results_for_bib';
	
	
	
	$h1_text =  $title = "$marathon_results_str for Bib No. $bib";
}

$json = json_decode( $jsonstr, true ); 
$is_member = $response_type == 'results_for_fid';

$qcount++;
setcookie( "qcount", $qcount, time() + (86400 * 30), "/" );

$gender = null;

if ( $is_member )
{
	$additional_info = $json['data']['additional_info'];
	$name = $additional_info['display_text'];
	$result_count = $additional_info['count'];
	$member_info = $additional_info['member_info'];
	$gender = $member_info['gender'];
	$country = $member_info['country'];
	$image = $member_info['image'];
	$image_copyright = $member_info['image_copyright'];
	$extra_data = $member_info['image_copyright'];
	
	//error_log( print_r( $member_info, true ));
	
	if ( is_rtl() ) 
			$h1_text =  $title = "התוצאות של " .  $name;
	else
			$h1_text =  $title = "$marathon_results_str of " . $name;


	$actual_query = $name;

	
	if ( is_logged_in() )
	{
		if ( $is_member && $member_info['fid'] == $_SESSION["user"]["fid"] )
			$is_it_me = true;
	}
}
else 
{
	if ( $json && isset( $json['data'] ) && isset( $json['data']['additional_info'] )  )
	{
		$additional_info = $json['data']['additional_info'];
		$result_count = $additional_info['count'];
	}
		
}



$banners = isset( $json['banners'] ) ? $json['banners'] : array();
	

$lang = is_rtl() ? 'he' : 'en';
$dir = is_rtl() ? 'rtl' : 'ltr';


error_point:

if ( $error_text == 'token expired' )
{
  if ( isset( $_SESSION[ "user" ]) )
    unset( $_SESSION[ "user" ] );
  header("Location: " . getBase() . "login");
  die();
}
 

?>

<!doctype html>
<html lang="<?php echo getLang();?>" dir="<?php echo $dir;?>">
  <head>
  
	<?php if ($is_member ) { 
	$q = str_replace( " ", "-",  $member_info['display_name'] );
	?>

	<?php } ?>
	<base href='<?php echo getBase(); ?>'></base>
    <!-- Required meta tags -->
    <meta charset="utf-8">
		
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
	<?php writePageCss() ?>
    <link href="js/uploader-master/css/jquery.dm-uploader.min.css" rel="stylesheet">
    <link href="js/uploader-master/styles.css" rel="stylesheet">
	<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
	<link href="js/magnific-popup/magnific-popup.css" rel="stylesheet">
	<link href="js/SummaryTable.css" rel="stylesheet">
	
    <title>
		<?php echo $title; ?>
	</title>
	
	<style>
	
	tr.group,
	tr.group:hover {
		background-color: #ddd !important;
		font-weight: bold;

	}
	
	tr.group > td {
		padding-left: 20px !important;
	}
	
	.best_result
	{
		font-weight: bold;
	}
	
	
	#summaryTable 
	{
		margin-left: auto;
		margin-right: auto;
		width: 450px;
		font-weight: bold;
		line-height: 1;
	}
	
	.name 
	{
    padding-right: 24px;
    padding-left: 24px;
	}
	
	#imgProfile
	{
		max-height: 256px;
	}
	
	#rowDetails
	{
		margin-bottom: 3em;
	}
	
	#rowDetails .row
	{
		margin-left: -15px;
	}
	
	#rowDetails .col-sm
	{
		border-right: 1px solid #979797;
		padding-left: 8px;
	}
	
	#nonMemberText
	{
		padding-top: 1em;
		display: block;
		<?php  if ( is_logged_in() )  {?>
		display:none;
		<?php } ?>
	}
	
	#nonMemberText img
	{
		width: auto;
		height: auto;
	}
	
	#txtMembers {
		padding-top: 1em;
		display: block;
	}
	
	#moreResults
	{
		display: block;
	}
	
	@media only screen and  (max-width: 720px)
	{
		#txtMembers
		{
			width: 100%;
		}
	}
	
	.country-flag-large
	{
		max-width: 96px;
	}
	
	
	#resultsTextContainer
	{
		margin-bottom: 1rem;
	}
	
	#summaryContainer
	{
		text-align: center;
	}
	
	#divYourResults
	{
		display: block;

	}
	
	#alertWarning
	{
		display: none;
	}
	
	#rowSummary
	{
		padding-top: 1.5rem;
	}
	
	.col-summary 
	{
		text-align: center;
		.style='width:100%';
	}
	
	#rowSummary .col-sm
	{
		font-weight: bold;
	}
	
	#rowSummary .value
	{
		color: #00B0CD;
	}
	
	#rowSummary .delimiter
	{
		color: #979797;
		padding-left: 12px;
		display: none;
	}
	

	.normal-weight
	{
		font-weight: normal;
	}
	
	#divCompare
	{
		margin-top: 1.5rem;
	}
	
	.group td
	{
		background-color:#EFEFEF;
		color: #007487;
	}
	
	.nav-tabs
	{
		margin-top: 1.5rem;
	}
	
	.ql-tooltip
	{
		display: none;
	}
	
	.ql-editor
	{
		padding: 8px 10px;
	}
	
	#resultsTable th
	{
		text-align : center;
	}
  
  #txtBanners
  {
    margin-top: 1rem;
    padding-right: 8px;
    padding-top: 8px;
    padding-bottom: 8px;
    width: fit-content;
    
    display: flex;
    flex-direction: row;
    gap: 1rem;
    justify-content: center;
  }
  
  #txtBanners img
  {
    max-width: 64px;
  }
	
	#resultsTable
	{
		font-weight: 400;
    overflow-y: auto;
	}
	
	.admin-tools
	{
		margin-top: 1rem;
		display: flex;
		gap: 1rem;
		flex-direction: row;
	}
	
	.admin-tools img
	{
		height: 32px;
	}
	
	#extra_data
	{
		text-align: center;
    margin-top: 1rem;
    background-color: aliceblue;
	}
	
	.mainContent
	{
		max-width: 90%;
	}
	
	</style>

	
  </head>
  <body lang='<?php echo $lang ?>'>
  

	<?php writePageJs() ?>
	<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/rowgroup/1.1.0/js/dataTables.rowGroup.min.js"></script>
	<script src="js/LargeFlag.js"></script>
	<script src="js/ImageGallery.js"></script>	
	<script src="js/SummaryTable.js"></script>	
    <!--Load the charts API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
	<!-- Note that we have changed this file. Added 'this' as parameter to onInit -->
    <script src="js/uploader-master/js/jquery.dm-uploader.min.js"></script>
    <script src="js/uploader-master/uploader-config.js"></script>
	<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
	<script src="js/magnific-popup/jquery.magnific-popup.min.js"></script>
  
    <?php  writeNavBar( false , $actual_query ); ?>
	
 
<main role="main" class="mainContent">


	<div class="container" id='rowDetails'>
  <div class="row">
  
    <div class="col-sm-10" id='resultsTextContainer'>
		<h1 class='name'>
		
		<?php 
			echo $title;
			if ( $country ) 
				echo "<span id='spanFlag' class='country-flag-large'></span>\n";
		?></h1>
		
		<div class="alert alert-warning" role="alert" id='alertWarning'>&nbsp;</div>
		
		<?php if ( $is_error ) { show_error( $error_text ); } ?>
		
		
		<?php if ( is_admin() && isset( $member_info )  ) { ?>
		<div id='member_fid'>
			<?php echo $member_info['fid'] ?>
		</div>
		<?php } ?>
		
		<?php   if (  !$is_member && isset( $name ) &&  real_word_count( $name ) > 2  && !$loose ) {   ?>
		
		
		<div id='moreResults' class="row">
			Not enough results? <a href='./search?query=<?php echo rawurlencode($query); ?>&loose=true'>Search similar names</a>
		</div>
		
		<?php } ?>

		<?php if ( $is_it_me ) { 
      $_SESSION['results'] = $json;
    ?>
	

		

		<div class="row" id='divYourResults'>
		
				<?php if ( is_rtl() )  { ?>
				כאן אפשר לראות את התוצאות שלך כפי שאנשים אחרים רואים אותן. אם הרשימה כוללת תוצאות שאינן שלך, ניתן להסיר אותן מהרשימה. אפשר לעשות זאת <a href='./myresults'>בעמוד ניהול התוצאות</a>.
				<?php } else { ?>
			  These are your results as seen by other people. If the list contains results that are not yours, you can remove them from this list.
					To do that just go to <a href='./myresults'>Manage My Results</a>.				
  			<?php } ?>
		</div>

		<?php } ?>

	</div>
	    <div class="col-sm-2" id='imageContainer'>
	    <?php 
		
		if ( !$is_error )
		{
			if ( !$gender )
				$gender="M";
			if ($is_member ) 
			{
				
				$copyright = "";
				if ( $image_copyright )
				{
					$copyright = " data-balloon-pos='down' data-balloon-length='xlarge' aria-label='$image_copyright' ";
				}
				
				echo "<div $copyright class=\"profile_image_holder\" style=\"background-image:url('$image')\" ></div>";
			}
		}
		
		?>
		
    </div>

</div>
	
		<div id='SummaryTable_Wrapper' translate='no'></div>

		
		<div id="divPortrait">
			<div class="alert alert-primary alert-dismissible fade show" role="alert">
			  <strong>Tip</strong> Try rotating your device. You might see more information.
			  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
			</div>
		</div>	
		<div id='txtMembers'></div>
		
						<?php 
					if ( isset( $member_info['extra_data']) )
						echo "<div id='extra_data' class='alert alert-primary' role='alert'>" . $member_info['extra_data'] . "</div>" 
					?>
    
    
    <?php 
    
    if ( $banners && count( $banners ) > 0  && $heat_type == 3 ) { ?>
 
		<div id='txtBanners'>
    
    <?php for( $i = 0  ; $i < count($banners ); $i++ )
    {
      $title = $banners[$i]['description'];
      $icon = $banners[$i]['icon'];
      if ( $icon )
        echo "<img title='$title' src='$icon'/>";
      else
        echo "<div>$title</div>";
    }
    
    ?>
    
    
    </div>
 
    
    <?php  } ?>
		
		
		<?php 
		
		if ( GetAppType() == 1 ) 
		{ 
			if ( $is_member && !$is_it_me && $result_count > 0 ) 
			{
				echo " <div id='divCompare'><button type='button' class='btn btn-primary' id='btnCompare' onclick='javascript:compareto(\"" . ($is_member ? $fid : $query)   .  "\")'>Compare to Me</button></div>\n" ;
			}
		}
		

			if ( ( is_admin() && isset( $fid ) ) || ( is_elite() && $is_it_me )  )
			{
				$token = $_SESSION[ 'user' ]['token'];
				echo "<div class='admin-tools'>";
				echo "<a href='./user-settings?email=$fid'>Edit Settings</a>";
				echo "<a title='Download Excel' href='./api/v2.0/results/download/$fid?token=$token'><img src='./image/excel.svg'></a>";
				if ( is_admin() )
					echo "<a title='Download PDF' href='./download_pdf?fid=$fid'><img src='./image/pdf.svg'></a>";
				else
					echo "<a title='Download PDF' href='./download_pdf'><img src='./image/pdf.svg'></a>";
				echo "</div>";
			}
		
		?>

		<div id='nonMemberText' class="row">
		<?php  
			if ( !is_logged_in() )  { 
				$remaining = 3 - $qcount;
				
			$rem_text = "You have only $remaining remaining anonymous searches left.";
				
		    switch ( $remaining )
			{
				case 0: $rem_text = "This is your last anonymous search."; break;
				case 1: $rem_text = "You have only one remaining search left."; break;
				default: break;
			}
		?>
		
		<img src='image/warning.png'><?php echo $rem_text; ?> Please <a href='./login?ref=search'>login</a> to have unrestricted number of searches.
		
		<?php } ?>
		</div>
		
		
		<?php if (false ) { ?>
		<div class="row">
			<ul class="nav nav-tabs" role="tablist" style='width:100%'>
				<li class="nav-item">
					<a class="nav-link" href="#marathon_results" role="tab" data-toggle="tab" id='tab_marathon'>Marathon</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" href="#all_results" role="tab" data-toggle="tab" id='tab_all'>All Results</a>
				</li>
			</ul>
		</div>
		<?php  } ?>


    <?php if ( GetAppType() == 3 ) { ?>
		<div id='div_hide_parkruns'>
			<input type="checkbox" id="cb_hide_parkruns"/>
			<label for="cb_hide_parkruns">Hide parkruns</label>
		</div>
		
				<script>
		
				const g_hide_parkruns = window.localStorage && window.localStorage.getItem( "hide_prakruns" ) && window.localStorage.getItem( "hide_prakruns" ) === 'true';
		

				
				function handle_hide_parkruns( to_hide )
				{
					if ( !window.localStorage )
					{
						alert( 'localStorage not supported. Talk to us' );
						return;
					}
					
					window.localStorage.setItem( "hide_prakruns" , to_hide ? "true" : "false" );
					document.location.reload();
				}					

				const cb_hide_parkruns = document.querySelector( '#cb_hide_parkruns' );	
				cb_hide_parkruns.checked =  g_hide_parkruns;
				cb_hide_parkruns.addEventListener( "change", () => handle_hide_parkruns( cb_hide_parkruns.checked )   );
	
		</script>
		
	
		<?php }  else {  ?>
		
			<script>
			const g_hide_parkruns = false;
			</script>
		
		<?php } ?>
		
		<div class="row">
			<div class="table-responsive">
			<table id='resultsTable' class="stripe dataTable hover" translate="no" style="width:100%">
			</table>
			</div>
			<div id='suggested-members'>
			</div>
		</div>
		
		<?php if ( $result_count ) { ?> 
		
		<div class="row">
			<label>
			  <input type="checkbox" value="clean-view" id='cbCleanView'> Clean View (no comments and images)
			</label>
		</div>
		<?php } ?>
		
		<div class="row">
		    <div id="results_chart" style="width: 100%"></div>
		</div>
		
		<script>

		
			function convert_to_timeofday( r )
			{
				var h = Math.floor( r / 3600 );
				var m =  Math.floor( (r - 3600 * h) / 60);
				var s = r - 3600 * h - 60 * m ;
				return [h,m,s,0];
			}

			<?php 
				echo "const json=$jsonstr;\n\n";
			?>	

			function set_clean_view( b_clean_view )
			{
				// Use value from cookie, if absent, set to false
				if ( arguments.length == 0 )
				{
					const c = get_cookie( "clean_view" )
					if ( c == "true" )
						b_clean_view = true;
					else
						b_clean_view = false;
					
					$('#cbCleanView').prop('checked', b_clean_view);
					
				}
				
				const is_clean_view = $('.rowComment').css("display" ) == "none";
				
				if ( is_clean_view == b_clean_view ) return ; // Nothing to do
				
				if ( b_clean_view )
				{
					$('.rowComment').css("display", "none" );
					$('.rowImage').css("display", "none" );
					$('.comment_tools').css( "visibility", "hidden" );
				}
				else
				{
					//$('.rowComment').css("display", "table-row" );
					//$('.rowImage').css("display", "inline" );
					//$('.comment_tools').css( "visibility", "visible" );
					location.reload();
				}
			}


			let chart_results_array = [];
			// Callback that creates and populates a data table,
			// instantiates the scatter chart, passes in the data and
			// draws it.
			function drawChart() 
			{
				

				// Create the data table.
				var chartdata = new google.visualization.DataTable();
				chartdata.addColumn('date', 'Date');
				chartdata.addColumn('timeofday', 'Result');
				chartdata.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
				chartdata.addColumn({'type': 'string', 'role': 'style'});
		
				const results = json["data"]["results" ];
				
				let maxResult = 0;
				let minResult = 12 * 3600;
				let prIndex = -1;
				let lastYear = 0;
				let firstYear = 3000;
				
				
				let resCount = 0;
				for( var i = results.length - 1 ; i >= 0 ; i-- )
				{
					var res = results[i];
					var r = parseInt(  get_result_to_show( res ));
					if ( parseInt( res["heat_type"] ) != 3 ) continue;
					
					if ( r < minResult )
					{
						minResult = r;
						prIndex = resCount;
					}
					if ( r > maxResult )
						maxResult = r;
					resCount++;
					chart_results_array.push( res );
				}
				
				if ( chart_results_array.length == 0 ) return;

				
				for( var i = chart_results_array.length - 1 ; i >= 0 ; i-- )
				{
					var res = chart_results_array[i];
					var d = parse_date( res["date"] );
					var year = d.getFullYear();
					
					
					let datestring =  d.getDate() + " " + month_names_short[ d.getMonth() ]  + " " + year  ;
					let r = parseInt(  get_result_to_show( res ));
					if ( parseInt( res["heat_type"] ) != 3 ) continue;
					if ( year < firstYear )
						firstYear = year;
					if ( year > lastYear )
						lastYear = year;
					let style = i == prIndex ? 'point { size: 10; shape-type: star; fill-color: #0069D9; }' : null;
					
					let event_name = res['event_name'].replace( /\d{4}$/g, '' );
				
					
					let htmltooltip = "<div style='font-size:0.8rem'>" + event_name + "<br>" + datestring + "<br><div style='font-weight:bold'>" + showAsResult(r) + "</div></div>";
					
					if ( i == prIndex )
						htmltooltip = "<div style='font-weight:bold;text-align:cnter;font-size:1rem'>Best Result</div>" + htmltooltip;
					
					htmltooltip = "<div style='padding:5px'>" + htmltooltip + "</div>";
					
					chartdata.addRow( [ d, convert_to_timeofday(r) , htmltooltip, style ] );
				}
				
				let ticks = [];
				
				for( var y = firstYear; y <= (lastYear + 1) ; y++ )
					ticks.push( new Date( y, 1, 1) );

				// Set chart options
				var options = {'title':"<?php echo addslashes( ucwords( ($name))); ?> - Marathon Results",
							   'width':'100%',
							   'height':300, 
							   'hAxis': {  'format': 'yyyy' , 
											ticks: ticks ,
											minValue : new Date( firstYear, 1, 1 ),
											maxValue : new Date( lastYear + 1, 1, 1 )
										},
							   'vAxis':  { 'format': 'h:mm:ss' , 'direction': -1 ,'minValue': convert_to_timeofday( minResult - 600 ), 'maxValue': convert_to_timeofday( maxResult + 600 ) },
							   'colors': [ '#39B893' ],
							   'tooltip': {'isHtml': true},
							   'trendlines': { 0: { tooltip: false} },
							   'titleTextStyle':
							   {
								   'color': '#017487',
								   'fontSize': 18,
								   'bold': false
							   },
						   
							   'legend' : { 'position':'none' }};

				// Instantiate and draw our chart, passing in some options.
				var chart = new google.visualization.ScatterChart(document.getElementById('results_chart'));
				chart.draw(chartdata, options);
				
				google.visualization.events.addListener(chart, 'select', selectHandler);
				
				function selectHandler() 
				{
					let selection = chart.getSelection();
					let res = chart_results_array[ selection[0].row ];
					let u = "./result/" + res["resultid"] ;
					document.location.href = u;
					return;
				}

				
			}

			var gView = 'm'; 
			function show_alert( msg )
			{
				$('.name').css( "display", "none" );
				$('#alertWarning').css( "display", "block" );
				$('#alertWarning').html( msg );
			}
		
			const column_headers = 
			{
				Year : '<?php echo L('Year') ?>',
				When : '<?php echo L('When') ?>',
				As : '<?php echo L('As') ?>',
				Where : '<?php echo L('Where') ?>',
				Result : '<?php echo L('Result') ?>',
				ResultRaw : '<?php echo L('Result') ?>',
				Category : '<?php echo L('Category') ?>',
				GenderRank :  '<?php echo L('Gender<br>Rank') ?>',
				OverallRank :  '<?php echo L('Overall<br>Rank') ?>',
				CategoryRank :  '<?php echo L('Category<br>Rank') ?>',
				Gender :  '<?php echo L('Gender') ?>',
				Heat :  '<?php echo L('Heat') ?>',
				BirthYear :  '<?php echo L('Birth<br>Year') ?>',
				Pace :  '<?php echo L('Pace') ?>'
			};
			
			
			$(function() 
			{
				set_clean_view();
				$('#cbCleanView').change( function () {
					
					const b = $(this).is(':checked');
					if ( b )
						set_cookie( "clean_view", "true", 180 );
					else
						set_cookie( "clean_view", "false", 1 );
					
					set_clean_view( b ) ;
				});
				
				<?php if ( GetAppType() == 1 ) { ?>
				// Load the Visualization API and the corechart package.
				google.charts.load('current', {'packages':['corechart']});

				// Set a callback to run when the Google Visualization API is loaded.
				google.charts.setOnLoadCallback(drawChart);
				
				<?php } ?>
				
				const domContainer = document.querySelector('#spanFlag');
				if ( domContainer )
					ReactDOM.render(React.createElement(LargeFlag, {country:"<?php echo $country; ?>"}), domContainer);
				
				$('#tab_marathon').addClass("active");
				$('#marathon_results').addClass("in");
				$('#marathon_results').addClass("active");	

				$('.nav-tabs a').on('shown.bs.tab', 
					function(event)
					{
						var tab_id = $(event.target).attr("id");
						if ( tab_id == "tab_all" )
							gView = 'a';
						else
							gView = 'm'
						
						var el = '#resultsTable';
						
						var showAdd = <?php echo  $is_it_me ? "true" : "false";  ?>;
						var showDelete = <?php echo  $is_it_me ? "true" : "false";  ?>;
						var showEdit = <?php echo  $is_it_me ? "true" : "false";  ?>;
						var showExpand = false;
						
						var showCommentTools = { "delete": showDelete , "edit" : showEdit, "expand" : showExpand };


						
						let stats = get_stats( json["data"], <?php echo $heat_type ?> , true );
            const heat_type = <?php echo $heat_type ?>;
						const server_type = <?php echo GetAppType() ?>;

						const options = {
								type : showGrouped,
								heattype : heat_type,
								showCommentAdd : true ,
								showCommentTools : showCommentTools ,
								headers : column_headers,
								server_type : server_type ,// Default 1 MV
								has_ag : json["data"] && json["data"]["additional_info"] 
									&& json["data"]["additional_info"]["member_info"] 
									&& json["data"]["additional_info"]["member_info"].has_ag
						}
						
						if ( !show_results( json["data"], $(el), stats, options ))
						{
							window.setTimeout( function() 
							{
								show_results( json["data"], $(el), stats, options );
							}, 10 );
						}
					});
					
			});
			
			function build_person_results( data )
			{
				add_to_local_history( data.additional_info.display_text ); 
				let stats = get_stats( data , <?php echo $heat_type ?> );
				build_results( json, stats, false ,  <?php  echo $is_it_me ? "true" : "false" ; ?> );
			}

			
			function build_member_suggestions( json )
			{
				
				<?php $url = './marathon-results-of-' . rawurlencode( preg_replace( "/\s/", '-',   $query )) . '?members_first=false'; ?>
				
				<?php if (is_rtl()) {  ?>
				
				
				$('#txtMembers').html( " אם מי שאתה מחפש לא ברשימה <a href='<?php echo $url; ?>'>לחץ כאן</a>");
				<?php } else {  ?>	
				$('#txtMembers').html( "The following <?php echo getAppName() ?> members match your search. If none of them is who you're looking for, click&nbsp;<a href='<?php echo $url; ?>'>here</a>.");

				<?php } ?>
	
				const count = json.length;
				
				let html = "<table class='table table-hover'>\n";
				let idx = 0;

				
				while( idx < count )
				{
					html += "<tr><td>\n";
					const sugg = json[ idx];
					html += ( "<a href='./query/" + sugg["fid"]  + "'><img class='imgProfile' src='" + sugg["image"] + "'></a>" );
					html += ( "<a href='./query/" + sugg["fid"]  + "'>" + sugg["display_name"] + "</a>" );
					if ( sugg["country" ] )
						html += "<img class='country-flag-large' src='image/flags-large/" + sugg["country" ] + ".png'>&nbsp";
					
					
					var d = parse_date( sugg["create_date" ] );
					var year = d.getFullYear();
					var datestring =  month_names_short[ d.getMonth() ]  + " " + year  ;

					html += ( "&nbsp;Member Since " + datestring);
					html += "</td></tr>\n";
					idx++;
				}
				html += ( "</table>\n");
				$('#suggested-members').html( html );
			}
			
			function build_name_suggestions( json )
			{
				var suggestions = json["data"]["suggestions"];
				var dataSet = [];
				
				if (  !suggestions || suggestions.length == 0 )
				{
					show_alert( "No results for <?php echo addslashes(  preg_replace( '/-/', ' ',  $actual_query)); ?>" );
					return;
				}
	
				for( var i = 0 ; i < suggestions.length ; i++ )
				{
					var suggest = suggestions[i];
					
					
					var url = "./query/" + encodeURIComponent( suggest["name"] );
					var a = "<a href='" + url + "'>" + suggest["name"] + "</a>&nbsp(" + suggest["count"] + ")";
					
					var row = [ a ];
					dataSet.push( row );
				}
				
				var bPaging = true;
				if ( dataSet.length < 10 )
					bPaging = false;
				
				var col_headers = [  { title:"" }  ];

				$('#fetching').html("");
				$('#resultsTable').DataTable( {
					"ordering": false, 
					"searching": false,
					"paging": bPaging,
					"lengthChange": false, 
					data: dataSet,
					columns: col_headers
				} );
				
				$('.name').html( '<?php echo L("Did you mean one of these?") ?>' );


			}
      
      function get_us_states_count( results )
      {
        if ( !results || results.length == 0 ) return 0;
        return   ( new Set(  results.map( r => ( r.event_country == 'usa' ? r.event_state : null ) ).filter( item => item != null ))).size;
      }
      
      function build_marathon_details( json, stats )
      {
        	const details = { heat_type : 3 };
					details.stats = stats;
					details.count = stats.count;
					details.countries = stats.countries;
					
					
					var mc = stats.majors.count;
					if ( mc  )
					{
						var s = "";
						if ( mc == 7 ) // Num of majors
							s = " (All)";
						details.majors = stats.majors.count + s;

					}
					
					const bq = json["data"]['additional_info']['bq_info']['is_bq']
					details.bq =  bq ? "Yes" : "No" ;

					const arank = json['data']['additional_info']['asphalt_rank'] / 100;
					details.asphalt_rank = number_format( arank, 2, ".", "" ) ;
          
          const us_states_count = get_us_states_count( json["data"]['results'] );
          details.us_states_count = us_states_count > 4 ? us_states_count : null;
          details.results = json.data.results;
					details.member_fid = json['data']['additional_info']['is_member'] ? json['data']['additional_info']['member_info']['fid'] : null
					
          return details;
      }
			
      function build_all_races_details( json, stats )
      {
        	const details = { heat_type : 0 };
					details.count = stats.count;
					details.stats = stats;
          return details;
      }
	
      
			function build_results( json, stats , is_bib , showCommentTools)
			{
				
				if ( !stats )
				{
					show_alert( "No results for <?php echo addslashes( $actual_query); ?>" 	);
					//return;
				}
				if ( stats && stats.count > 0 )
				{
          <?php if ( $heat_type == 3 ) { ?>
					const details = build_marathon_details( json, stats ); 
          <?php } else {  ?>        
 					const details = build_all_races_details( json, stats ); 
          <?php } ?>
					
					details.lang = '<?php echo $lang ?>';
          
					const domContainer = document.querySelector('#SummaryTable_Wrapper');
					if ( domContainer )
						ReactDOM.render(React.createElement(SummaryTable, details), domContainer);
				}
				
				const el = '#resultsTable';
				var showAdd = <?php echo  ($is_it_me || is_admin()) ? "true" : "false";  ?>;
				var showDelete = <?php echo  ($is_it_me || is_admin()) ? "true" : "false";  ?>;
				var showEdit = <?php echo  ($is_it_me || is_admin()) ? "true" : "false";  ?>;
				var showExpand = false;
				var showCommentTools = { "delete": showDelete , "edit" : showEdit, "expand" : showExpand };
        const heat_type = <?php echo $heat_type ?>;
				const server_type = <?php echo GetAppType() ?>;
				
				const options = {
								type : showGrouped,
								heattype : heat_type,
								showCommentAdd : true ,
								showCommentTools : showCommentTools ,
								headers : column_headers,
								server_type : server_type , // Default 1 MV
								has_ag : json["data"] && json["data"]["additional_info"] && 
								json["data"]["additional_info"]["member_info"] && 
								json["data"]["additional_info"]["member_info"].has_ag
				}
				
				if ( !show_results( json["data"], $(el), stats, options))
				{
					window.setTimeout( function() 
					{
						show_results( json["data"], $(el), stats, options );
					}, 10 );
				}

				
				
				if ( is_bib )
				{
					document.title = json["data"]["query"] ;
					$('.name').html( "Runs with number " + json["data"]["query"] );
				}
				else
				{
					const name  = json["data"]['additional_info']['display_text'];
					<?php if ( is_rtl() ) { ?>
					document.title = 'תוצאות של ' + name;
					<?php } else { ?>
					document.title = 'Marathon Results of ' + name;
					<?php }  ?>
				}
				
				
				<?php if ( !$is_it_me ) { ?>
				if ( json["data"]['additional_info']['member_info'] )
				{
					<?php 
					
					if ( isset( $json["data"]['additional_info']["description"] ))
					{
						$description = $json["data"]['additional_info']["description"];
						if ( !$description )
							$description = L("runner");
					}
					else
						$description = L("runner");
					?>
					
					// That's the original code
					//const name  = json["data"]['additional_info']['display_text'];
					//const base_name  = name;
					
					// New code 2025-09-07
					const base_name  = json["data"]['additional_info']['display_text'];
					const query = '<?php echo addslashes( $query ) ?>';
					
					// Not fid
					const name =  ( !/^\d+$/.test( query ) && json.options.search_type == 2 ) ? query : base_name;
					// End of new code

					const sname = "<span class='bold'>" + name + "</span>";
					
					if ( json["data"]["wiki_page"] )
						sname = "<a href='" + json["data"]["wiki_page"] + "' target='_new'>" + name + "</a>";
					
					const name2 = name.replace(/ /g, "-");
					const url_non_member = "./marathon-results-of-" + fixedEncodeURIComponent( name2 ) + '?members_first=false';
					
					const txtMembers = document.querySelector( '#txtMembers' );
					
					<?php error_log( "Just before someone else: " . $query) ?> 
					
					<?php if ( is_rtl() ) { ?>
					txtMembers.innerHTML =  "כדי לקבל תוצאות של אנשים אחרים באותו שם אפשר ללחוץ <a href='" + url_non_member + "'>כאן</a>";
					<?php } else { ?>
					txtMembers.innerHTML =  "We searched for <?php echo $description;?> " + "<b>" + base_name + "</b>. If you're looking for someone else, try <a href='" + url_non_member + "'>this link</a>. ";
					<?php }  ?>
				}
				else
				{
				}
				<?php } ?>
				


			}
			
			<?php 
			
				switch( $response_type )
				{
					case 'results_for_name': echo ( "build_person_results( json['data'] );\n" ); break;
					case 'results_for_fid': echo ( "build_person_results( json['data'] );\n" ); break;
					case 'results_for_bib': echo ( "build_results( json, null, true, false );\n" ); break;
					case 'member-suggestions': echo ( "build_member_suggestions( json  );\n" ); break;
					default : error_log( 'Unknown $repsonse_type ' . $response_type ); break;
				}
			
			
			?>
			
		<?php  if ( !$is_it_me  && $result_count > 0 )  { ?>
		

		function compareto( other )
		{
			document.location.href = './compareto?q=' + other;
		}
			
		<?php }  ?>
			
		</script>
	
		<img src='image/BottomIllustration.svg' id='imgBottom'>
</main>

<?php writeFooter(); ?>
	
  </body>
</html>