<?php 
session_start();

include "php/common.php";

$raceid=safe_get_arg( $_GET, "id" );
$category= rawurlencode( safe_get_arg( $_GET, "category" ));
$countstr = safe_get_arg( $_GET, "count" );
$count = 10;
$count = intval( $countstr );
if ( $count <= 0 )
	$count = 10;


$res = SysApiGet( "race/$raceid?count=$count&category=$category"); 
$json_string = $res['body'];

$json = json_decode($json_string, true);

$isError = $res['status'] != 200;
$errMessage = $isError? $res['body'] : '';
$title = "";
$source = null;


if (!$isError)
{
	$title = $json["event"]["name"];
	
	$date = parse_mysql_date($json["event"]["date"]);
	$dateStr = date_format( $date, "M jS Y" );
	
	$now = date_create("now");
	$diff = date_diff( $date, $now );
	
	$logo =  safe_get_arg( $json["event"], "logo" );
	
	$totalFinishers = intval( $json["finishers"]["overall"] );
	$femaleFinishers = intval( $json["finishers"]["female"] );
	$maleFinishers = intval( $json["finishers"]["male"] );
	$unassignedFinishers = intval( $json["finishers"]["unassigned"] );
	
	if ( getAppType() == 1 ) 
	{
		$sub3 = intval( $json["finishers"]["sub3"] );
		$sub3_percent =  '(' . round( 100 * $sub3 / $totalFinishers, 2 ) . '%)';
	}

	$titleInRtl = containsHebrew( $title );
	$RtlClass = $titleInRtl ? "hebrew" : "";
	
	$series_id = 0;
	$seriesname = "";
	if ( isset( $json["event"]["series_id"] ))
	{
		if ( $json["event"]["series_id"] )
		{
			$series = $json["event"]["series"]["id"];
			$seriesname = $json["event"]["series"]["name"];
		}
	}
}	


function print_leaders( $leaders, $title )
{
	echo "<table class='leaders table .table-sm'>\n";
	echo "<tr><th colspan=\"4\"><h3>$title</h3></tr>\n";
	
	$ranktype = "rank";
	for( $i = 0 ; $i < count( $leaders ) ; $i++ )
	{
		$r = $leaders[ $i ];
		if ( !$r[$ranktype] )
		{
			$ranktype = "rank";
			break;
		}
	}
	
	for( $i = 0 ; $i < count( $leaders ) ; $i++ )
	{
		$r = $leaders[ $i ];
		$c = $r["country"];
		
		$flag_image = null;
		if ( $c )
		{
			$flag_image = $c;
			$flag_file = 'image/flags/' . strtolower( $c ) . '.png';
			if ( file_exists( $flag_file ))
				$flag_image = "<img title='$c'  src='$flag_file'/>";
		}
		
		$resultid = $r['id'];		
		
		$result_type = isset( $r['result_type'] ) ? intval( $r['result_type'] ) : 0;  
		
		$actual_result = $r["personaltime"] ? min( floatval( $r["result"] ), floatval( $r["personaltime"] )) : floatval( $r["result"] );
		
		if ( $c )
			echo "<tr><td>$flag_image</td><td>" . $r[$ranktype] . "</td><td>" . get_search_html(  $r["name"], null ) . "</td><td><a href='./result/$resultid'>"  . getAsResult( $actual_result , $result_type) . "</a></td></tr>\n";
		else
		{
			echo "<tr><td></td><td>" . $r[$ranktype] . "</td><td>" . get_search_html(  $r["name"], null ) . "</td><td><a href='./result/$resultid'>"  . getAsResult( $actual_result , $result_type) . "</a></td></tr>\n";
		}
	}
	echo "</table>\n";
}	



?>

<!doctype html>
<html lang="<?php echo getLang();?>">
  <head>

 
  	<base href='<?php echo getBase(); ?>'></base>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

	<?php writePageCss() ?>
	<link rel="stylesheet" type='text/css' href="css/autocomplete.css">
    <title><?php  echo $title; ?> </title>
	
	<style>
	

	.medians 
	{
		margin-top: 2em;
		margin-left:10%
		margin-right: 10%;
		width: 50%;
		line-height: 150%;
	}
	
	
	
	.medians th
	{
		text-align: center;
	}
	
	.medians .label
	{
		font-weight: bold;
	}
	
	.medians .data
	{
		text-align: right;
	}
	
	.leaders 
	{
		width: 100%;
		line-height: 1.0;
	}
	
	#divNotFullInfo
	{
		margin-top: 1em;
		border: 1px solid #6ab446;
		padding: 0.5em;
	}
	
	#search_race
	{
		height: 2rem;
		display: inline;
		width: auto;
		border: var(--mv-search-border-width) solid var(--mv-search-border-color);
    border-radius: 45px;
		padding-inline: 1rem;
		outline: none;
	}
	
	#search_race_label
	{
		font-size: var(--mv-h3-font-size);
    color: var(--mv-h2-color);
		font-weight: 500;
	}
	

	
	.race_finishers
	{
		display: grid;
    grid-template-columns: 6rem 3rem 1fr;
		margin-bottom: 1rem;
	}
	
	.race_finishers > div:nth-child(3n+1)
	{
		color: var(--mv-h2-color);
		font-weight : 500;
	}
	
	.race_finishers > div:nth-child(3n+2)
	{
		text-align: right;
	}

	.race_finishers > div:nth-child(3n)
	{
		font-weight: 500;
		padding-left: 1rem;
	}	
	
	.medians_data
	{
		display: grid;
    grid-template-columns: 8ch 1fr;
	}
	
	.median_label
	{
		color: var(--mv-h2-color);
		font-weight : 500;
	}
	
	#div_search
	{
		display: grid;
    grid-template-columns: 4rem 1fr;
		gap: 6px;
    align-items: center;
		margin-bottom:1rem;
	}
	
	.event-name
	{
		color: var(--mv-h2-color);
		font-size : larger;
		font-weight : 500;
	}
	
	#div_categories_data
	{
		display : grid;
		grid-template-columns: 1fr 1fr;
	}
	
	.div_category_name
	{
		display: grid;
		grid-template-columns: 1fr 1fr;
		color: var(--mv-h2-color);
		font-size: var( --mv-h2-font-size );
		font-weight: 500;
	}
	
	<?php if ( getAppType() == 2 ) { ?>
	.div_category_name .div_race_name
	{
		padding-inline: 1rem;
		text-align : left;
	}
	
	.div_category_name .div_cat
	{
		padding-inline: 1rem;
		text-align : right;
	}
	<?php  } else { ?>
	.div_category_name .div_race_name
	{
		padding-inline: 1rem;
		text-align : right;
	}
	
	.div_category_name .div_cat
	{
		padding-inline: 1rem;
		text-align : left;
	}
	<?php  }  ?>
	
	h3 
	{
		margin-top: 1rem;
	}
	
	.mainContent
	{
		max-width: 90%;
	}
	
	</style>
	
	
  </head>
  <body>
  
  	<?php writePageJs() ?>
	<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  
   <?php writeNavBar( false , false, null); ?>
 

<main role="main" class="mainContent">

		<?php show_api_error( $res ); ?>
		
		<?php if ( !$isError  ) { ?>	
		
  
   <div class="container">
	 
	 		<h1><?php echo $title ?></h1>
		
		<?php if ( $category ) { 
			echo "<div class='div_category_name'>";
			echo "<div class='div_race_name'>" .   $json["name"] . "</div><div class='div_cat'>" . urldecode(  $category ) . ' </div>';
			echo "</div>";
		}
		?>
	 
	 
    <div class="row">
      <div class="col-md-4">
        <h2><?php echo L('General') ?></h2>
		
		<?php 
			//echo "<div class='event-name'>" . $title . "</div>" ;
			echo "<h3>" . $title . "</h3>" ;
			
			$country = $json["event"]["country"];
			
			if ( $country )
			{
				echo "<div class='country-flag-large'>\n";
				$flag_path = "image/flags-large/" . strtolower( $country) . ".png";
				$flag = file_exists(  $flag_path ) ? "<img src='$flag_path'/>" : "<div class='country-name'>" . L("Country") . ' : ' . strtolower( $country) . "</div>";
				echo "<a href='event/country%3A$country'>$flag</a><br/>";
				echo "</div>\n";
			}
			
			
			
			echo "$dateStr ";
			if ( $diff->days )
				echo "(" . expressDateDifference( $diff->days ) . ")<br/>";
			
			if ( isset( $series ) &&  $series )
				echo "Series: <a href='./series/$series'>$seriesname</a><br/>\n";
			
			$racenme = $json["name"];
			$raceInRtl = containsHebrew( $racenme );
			$RtlClass = $raceInRtl ? "hebrew" : "";
			$fullinfo = $json["full_info"];
			
			// Source
			$source = null;
			if ( isset( $json["event"]["source"] ))
				$source = $json["event"]["source"];
			
			if ( $source && isset( $source["name"] ))
				echo L('Source') . ": <a target='_new' href='" . $source["url"] . "'>" . $source["name"] . "</a><br/>\n" ;
			
			$eventid = $json["event"]["id"];
				echo "<a href='./event/" . $eventid . "'>" . L("Event Details")  . "</a><br/>\n" ;
			
			$finishersStr = $fullinfo ? "" : "Results";
			
			echo "<br><h3 class='$RtlClass'>$racenme</h3>";
			if ( $category )
				echo "<h3 class='$RtlClass'>" . urldecode( $category )  . "</h3>";
			
			$suffix = "";
			if ( $totalFinishers == $femaleFinishers )
				$suffix = " (" . L("All Females") . ")";
			if ( $totalFinishers == $maleFinishers )
				$suffix = " (" . L("All Males") . ")";
			
			echo "<div class='race_finishers'>\n";
			if ( $totalFinishers )
				echo  "<div>" .  L('Finishers')  . "</div><div>" .  number_format($totalFinishers) . "</div><div>$finishersStr$suffix</div>";

			if ( $femaleFinishers  &&  $femaleFinishers < $totalFinishers )
				echo  "<div>" . L('Females')  .  "</div><div>" .  number_format($femaleFinishers) . "</div><div></div>";
			if ( $maleFinishers  &&  $maleFinishers < $totalFinishers  )
				echo  "<div>" . L('Males')  .  "</div><div>" .  number_format($maleFinishers) . "</div><div></div>";
			if ( getAppType() == 1 && $sub3  )
				echo  "<div>Sub 3</div><div>" .  number_format($sub3) . "</div><div>$sub3_percent</div>";
			
			echo "</div>";
			
			
			if ( !$fullinfo )
			{
				echo "<div id='divNotFullInfo'><img src='image/warning.png'>&nbsp;Note: We have information just on some of the finishers of this race.</div>\n";
			}
		
			if ( $maleFinishers && $femaleFinishers && $fullinfo ) {
			?>	
				
			<div id="piechart"></div>
			
			<script type="text/javascript">
				// Load google charts
				google.charts.load('current', {'packages':['corechart']});
				google.charts.setOnLoadCallback(drawChart);

				// Draw the chart and set the chart values
				function drawChart() {
		 		  var data = google.visualization.arrayToDataTable([
				  ['Task', 'Finishers'],
				  ['Males', <?php echo $maleFinishers;  ?>],
				  ['Females', <?php echo $femaleFinishers;  ?>],
				  ['Unassigned', <?php echo $unassignedFinishers;  ?>],
				]);

			  // Optional; add a title and set the width and height of the chart
			  var options = { title: 'Finishers By Gender' ,   backgroundColor: 'transparent'};

			  // Display the chart inside the <div> element with id="piechart"
			  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
			  chart.draw(data, options);
			}
			</script>
				
			
			<?php
			
			}
			$siblings = $json["siblings"];
			if ( $siblings && count( $siblings ) > 0 )
			{
				echo "<br><h2>Other Races</h2>\n";
				for( $i = 0 ; $i < count( $siblings ) ; $i++ )
				{
					$race = $siblings[$i];
					$id = $race["id"];
					$name = $race["name"];
					echo "<a href='./race/$id'>$name</a><br>";
				}
			}
			?>
			
		
      </div>
	  
	<?php if ( $fullinfo ) { ?>
      <div class="col-md-4">
        <h2><?php echo L('Times') ?> </h2>
	<?php } else { ?>
      <div class="col-md-1">	  
	<?php } ?>	  

		
		<?php
	
			if ( $fullinfo )
			{
				echo '<h3>' . L("Medians" ) . '</h3>';
				echo "<div class='medians_data'>\n";
				if ( $totalFinishers && ( $totalFinishers > $femaleFinishers  ) && ( $totalFinishers > $maleFinishers) )
					echo "<div class='median_label'>" . L('Overall') . "</div><div  class=\"median_data\">" . getAsResult( intval( $json["medians"]["overall"] ), 0 ) . "</div>\n"; 
				if ( $femaleFinishers  )
					echo "<div class='median_label'>" . L('Female') . "</div><div  class=\"median_data\">" . getAsResult( intval( $json["medians"]["female"] ), 0 ) . "</div>\n"; 
				if ( $maleFinishers  )
					echo "<div class='median_label'>" . L('Male') . "</div><div  class=\"median_data\">" . getAsResult( intval( $json["medians"]["male"] ), 0 ) . "</div>\n"; 
				echo "</div>";					
				
				$categories_data = $json[ 'categories' ];
				if ( $categories_data && count( $categories_data ) > 0 )
				{
					echo '<h3>' . L("Race Categories" ) . '</h3>';
					
					echo "<div id='div_categories_data'>";
					for( $i = 0 ; $i < count( $categories_data ) ; $i++)
					{
						$cat = $categories_data[ $i ];
						echo "<div class='header'><a href='./race/" . $raceid . "?category=" . urlencode( $cat['name'] )  ."'>"   . $cat['name'] . "</a></div>";
						echo "<div class='value'>" .  number_format( floatval( $cat['count']),0, '', ',')  . "</div>";
					}
					echo "</div>";					
	

				}
			}
		?>
		
      </div>
      <div class="col-md-4">

      <h2><?php echo L('Leaderboard') ?></h2>	  
			<div id='div_search'>
	    <label for="search_race" id='search_race_label' ><?php echo L('Search') ?></label>
			<input type="search" id="search_race" placeholder='<?php echo  L("Finisher name...")  ?>'  required autofocus>
			</div>

		
		<?php
			
			$leaders = $json["leaders"]["overall"];
			$femaleleaders = $json["leaders"]["female"];
			$maleleaders = $json["leaders"]["male"];

			if ( count( $femaleleaders ) == 0 || count( $maleleaders ) == 0 )
			{
				print_leaders( $leaders , $category ? urldecode( $category )  :  L('Overall') );
			}
			else 
			{
				if ( count( $femaleleaders ) > 0 )
					print_leaders( $femaleleaders , L('Female') );
				if ( count( $maleleaders ) > 0 )
					print_leaders( $maleleaders ,  L('Male')  );
			}
			
		?>
		
      </div>

  
  
</div>

<script>



$(function() 
{
	$('.leaders td').each( function() 
	{
		var s = $(this).text();
		if ( isHebrew( s )) 
			$(this).css( "text-align",  "right" );
	});
	
	$("#search_race").keydown(function(event){
    if(event.keyCode == 13) {
			
      if($("#search_race").val().length==0) {
          event.preventDefault();
          return false;
      }
    }
 });
	

  $("#search_race").autocomplete({
	source: "./suggest?raceid=<?php echo $raceid; ?>",
	minLength: 2,
	select: function(event, ui) 
	{ 
		document.location = "./result/" + ui.item.result_id;
	},
  }).data( "ui-autocomplete" )._renderItem = function( ul, item ) 
  {
	  let s = item.value;
		
		if ( item.bib )	
			s += (' <b>' + item.bib + '</b>') ;
		
	  if ( item.result )
		s += " (" + item.result + ")";
	
	
	
	   return $( "<li>" )
	   .append(  "<a href='./result/" + item.result_id + "'>" + s + "</a>" )
	   .appendTo( ul );
  };


	
});

</script>

<?php } ?>

<img src='image/BottomIllustration.svg' id='imgBottom'>

</main>

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