function showRegionalRecordsSeparate()
{
    #----------------------------------------------------------------------
    global $chosenRegionId;
    require 'regions_get_current_records.php';
    tableBegin('results', 6);
    tableCaption(false, "Single");
    tableHeader(explode('|', 'Event|Result|Person|Citizen of|Competition|'), array(1 => "class='R2'", 5 => 'class="f"'));
    foreach ($results as $result) {
        extract($result);
        if ($type == 'Single') {
            $isNewEvent = !isset($currentEventId) || $eventId != $currentEventId;
            $currentEventId = $eventId;
            tableRow(array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $isNewEvent ? formatValue($value, $format) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), ''));
        }
    }
    tableCaption(false, "Average");
    tableHeader(explode('|', 'Event|Result|Person|Citizen of|Competition|Result Details'), array(1 => "class='R2'", 5 => 'class="f"'));
    $currentEventId = '';
    foreach ($results as $result) {
        extract($result);
        if ($type == 'Average') {
            $isNewEvent = $eventId != $currentEventId;
            $currentEventId = $eventId;
            tableRow(array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $isNewEvent ? formatValue($value, $format) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources(true, $result, $format)));
        }
    }
    tableEnd();
}
function showCompetitionResultsByPerson($resultsTable = 'Results')
{
    #----------------------------------------------------------------------
    global $chosenByPerson, $chosenAllResults, $chosenTop3, $chosenWinners;
    global $chosenCompetitionId;
    #--- Get the results.
    $competitionResults = getCompetitionResults($resultsTable);
    startTimer();
    tableBegin('results', 8);
    foreach ($competitionResults as $result) {
        extract($result);
        $isNewPerson = !isset($previousPersonId) || $personId != $previousPersonId;
        $isNewEvent = !isset($previousEventId) || $eventId != $previousEventId || $isNewPerson;
        #--- Welcome new persons.
        if ($isNewPerson) {
            if (isset($previousPersonId)) {
                tableRowBlank();
            }
            $bo3_as_mo3 = $formatId == '3' && ($eventId == '333bf' || $eventId == '333fm' || $eventId == '333ft');
            $headerAverage = $formatId == 'a' || $formatId == 'm' || $bo3_as_mo3 ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableCaptionNew(false, $personId, spaced(array(personLink($personId, $personName), $countryName)));
            tableHeader(explode('|', "Event|Round|Place|Best||{$headerAverage}||{$headerAllResults}"), array(2 => 'class="r"', 3 => 'class="R"', 5 => 'class="R"', 7 => 'class="f"'));
        }
        #--- One result row.
        tableRowStyled($isNewEvent ? '' : 'color:#AAA', array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $roundCellName, $isNewEvent ? "<b>{$pos}</b>" : $pos, formatValue($best, $valueFormat), $regionalSingleRecord, formatValue($average, $valueFormat), $regionalAverageRecord, formatAverageSources($formatId != '1', $result, $valueFormat)));
        $previousPersonId = $personId;
        $previousEventId = $eventId;
    }
    tableEnd();
    stopTimer("printing the huge table");
}
function sdRanking()
{
    global $WHERE;
    #--- Get ...
    $results = dbQuery("\n    SELECT personName, personId, value1, value2, value3, value4, value5,\n      (((value1*value1 + value2*value2 + value3*value3 + value4*value4 + value5*value5) / 5) - (((value1 + value2 + value3 + value4 + value5) / 5)*((value1 + value2 + value3 + value4 + value5) / 5))) sd\n    FROM Results result\n    {$WHERE} 1\n      AND eventId = '333'\n      AND value1 > 0\n      AND value2 > 0\n      AND value3 > 0\n      AND value4 > 0\n      AND value5 > 0\n    ORDER BY sd, personName\n    LIMIT 0, 10\n  ");
    foreach ($results as $result) {
        extract($result);
        $rows[] = array($personId, formatValue(sqrt($sd), 'time'), formatAverageSources(true, $result, 'time'));
    }
    return $rows;
}
function showResults()
{
    #----------------------------------------------------------------------
    global $chosenEventId, $chosenRegionId, $chosenYears, $chosenShow, $chosenSingle, $chosenAverage;
    #--- Try the cache
    tryCache('event', $chosenEventId, preg_replace('/ /', '', $chosenRegionId), $chosenYears, preg_replace('/ /', '', $chosenShow), $chosenSingle, $chosenAverage);
    #------------------------------
    # Prepare stuff for the query.
    #------------------------------
    $eventCondition = eventCondition();
    $yearCondition = yearCondition();
    $regionCondition = regionCondition('result');
    $limitCondition = '';
    if (preg_match('/^10+/', $chosenShow, $matches)) {
        $limitNumber = $matches[0];
        $limitCondition = 'LIMIT ' . 2 * $limitNumber;
    }
    $valueSource = $chosenAverage ? 'average' : 'best';
    $valueName = $chosenAverage ? 'Average' : 'Single';
    #------------------------------
    # Get results from database.
    #------------------------------
    if ($chosenShow == 'By Region') {
        require 'includes/events_regions.php';
        return;
    }
    if ($chosenShow == '100 Results' || $chosenShow == '1000 Results') {
        require 'includes/events_results.php';
    } else {
        require 'includes/events_persons.php';
    }
    #------------------------------
    # Show the table.
    #------------------------------
    startTimer();
    $event = getEvent($chosenEventId);
    tableBegin('results', 6);
    tableCaption(true, spaced(array($event['name'], chosenRegionName(), $chosenYears, $chosenShow)));
    $headerSources = $chosenAverage ? 'Result Details' : '';
    tableHeader(explode('|', "Rank|Person|Result|Citizen of|Competition|{$headerSources}"), array(0 => "class='r'", 2 => "class='R2'", 5 => 'class="f"'));
    $ctr = 0;
    foreach ($results as $result) {
        extract($result);
        $ctr++;
        $no = isset($previousValue) && $value == $previousValue ? '&nbsp;' : $ctr;
        if ($limitCondition && $no > $limitNumber) {
            break;
        }
        tableRow(array($no, personLink($personId, $personName), formatValue($value, $event['format']), htmlEntities($countryName), competitionLink($competitionId, $competitionName), formatAverageSources($chosenAverage, $result, $event['format'])));
        $previousValue = $value;
    }
    tableEnd();
    stopTimer("printing the table");
}
function showRegionalRecordsHistory()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenHistory, $chosenMixHist;
    #--- Compute the region condition and the normal record name.
    if (preg_match('/^(world)?$/i', $chosenRegionId)) {
        $regionCondition = "AND recordName = 'WR'";
        $normalRecordName = '';
    } elseif (preg_match('/^_/', $chosenRegionId)) {
        $tmp = dbQuery("SELECT recordName FROM Continents WHERE id = '{$chosenRegionId}'");
        $normalRecordName = $tmp[0][0];
        $regionCondition = "AND recordName in ('WR', '{$normalRecordName}' ) AND continentId = '{$chosenRegionId}'";
    } else {
        $regionCondition = "AND (recordName <> '') AND (result.countryId = '{$chosenRegionId}')";
        $normalRecordName = 'NR';
    }
    #--- Order: normal history or mixed?
    $order = $chosenHistory ? 'event.rank, type, value, year desc, month desc, day desc, roundId desc' : 'year desc, month desc, day desc, roundId desc, event.rank, type, value';
    #--- Get the results.
    $results = dbQuery("\n    SELECT\n      year, month, day,\n\n      event.id         eventId,\n      event.name       eventName,\n      event.cellName   eventCellName,\n\n      result.type      type,\n      result.value     value,\n      event.format     valueFormat,\n                       recordName,\n\n      result.personId   personId,\n      result.personName personName,\n\n      country.name     countryName,\n\n      competition.id   competitionId,\n      competition.cellName competitionName,\n\n      value1, value2, value3, value4, value5\n    FROM\n      (SELECT Results.*, 1 type, best    value, regionalSingleRecord  recordName FROM Results WHERE regionalSingleRecord<>'' UNION\n       SELECT Results.*, 2 type, average value, regionalAverageRecord recordName FROM Results WHERE regionalAverageRecord<>'') result,\n      Events event,\n      Competitions competition,\n      Countries country\n    WHERE " . randomDebug() . "\n      AND event.id = eventId\n      AND event.rank < 1000\n      AND competition.id = competitionId\n      AND country.id = result.countryId\n      {$regionCondition}\n      " . eventCondition() . yearCondition() . "\n    ORDER BY\n      {$order}\n  ");
    #--- Start the table
    if ($chosenHistory) {
        tableBegin('results', 7);
    } else {
        tableBegin('results', 9);
        tableHeader(explode('|', 'Date circa|Event|What|Single|Average|Person|Citizen of|Competition|Result Details'), array(3 => 'class="R2"', 4 => 'class="R2"', 8 => 'class="f"'));
    }
    #--- Process the results.
    $currentEventId = false;
    foreach ($results as $result) {
        extract($result);
        #--- Announce the event (only for normal history, not mixed)
        if ($chosenHistory && $eventId != $currentEventId) {
            $currentEventId = $eventId;
            tableCaptionNew(false, $eventId, eventLink($eventId, $eventName));
            tableHeader(explode('|', '|Single|Average|Person|Citizen of|Competition|Result Details'), array(1 => 'class="R2"', 2 => 'class="R2"', 6 => 'class="f"'));
        }
        #--- Determine how to display the record name.
        if ($recordName != $normalRecordName) {
            $recordName = "<span style='color:#f93;font-weight:bold'>{$recordName}</span>";
        }
        #--- Prepare the table row.
        $data = array($recordName, $type == 1 ? formatValue($value, $valueFormat) : '', $type == 2 ? formatValue($value, $valueFormat) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources($type == 2, $result, $valueFormat));
        if ($chosenMixHist) {
            array_unshift($data, sprintf('%4d-%02d-%02d', $year, $month, $day), eventLink($eventId, $eventCellName));
        }
        #--- Show the table row.
        tableRow($data);
    }
    tableEnd();
}
function showResultsByEvents()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n                           result.*,\n      event.name           eventName,\n      competition.cellName competitionCellName,\n      event.format         valueFormat,\n      round.cellName       roundCellName\n    FROM\n      Results result,\n      Events  event,\n      Competitions competition,\n      Rounds round\n    WHERE " . randomDebug() . "\n      AND personId = '{$chosenPersonId}'\n      AND event.id = eventId\n      AND event.rank < 1000\n      AND competition.id = competitionId\n      AND round.id = roundId\n    ORDER BY\n      event.rank, year DESC, month DESC, day DESC, competitionCellName, round.rank DESC\n  ");
    tableBegin('results', 8);
    tableCaption(false, "History (<a href='person_map.php?i={$chosenPersonId}'>Map</a>)");
    #--- Process results by event.
    foreach (structureBy($results, 'eventId') as $eventResults) {
        extract($eventResults[0]);
        #--- Announce the event.
        tableCaptionNew(false, $eventId, eventLink($eventId, $eventName));
        tableHeader(explode('|', 'Competition|Round|Place|Best||Average||Result Details'), array(2 => 'class="r"', 3 => 'class="R"', 5 => 'class="R"', 7 => 'class="f"'));
        #--- Initialize.
        $currentCompetitionId = '';
        #--- Compute PB Markers
        //$pbMarkers = [];
        $bestBest = 9999999999;
        $bestAverage = 9999999999;
        foreach (array_reverse($eventResults) as $result) {
            extract($result);
            $pbMarkers[$competitionId][$roundCellName] = 0;
            if ($best > 0 && $best <= $bestBest) {
                $bestBest = $best;
                $pbMarkers[$competitionId][$roundCellName] += 1;
            }
            if ($average > 0 && $average <= $bestAverage) {
                $bestAverage = $average;
                $pbMarkers[$competitionId][$roundCellName] += 2;
            }
        }
        #--- Show the results.
        foreach ($eventResults as $result) {
            extract($result);
            $isNewCompetition = $competitionId != $currentCompetitionId;
            $currentCompetitionId = $competitionId;
            $formatBest = formatValue($best, $valueFormat);
            if ($pbMarkers[$competitionId][$roundCellName] % 2) {
                $formatBest = "<span style='color:#F60;font-weight:bold'>{$formatBest}</span>";
            }
            $formatAverage = formatValue($average, $valueFormat);
            if ($pbMarkers[$competitionId][$roundCellName] > 1) {
                $formatAverage = "<span style='color:#F60;font-weight:bold'>{$formatAverage}</span>";
            }
            tableRowStyled($isNewCompetition ? '' : 'color:#AAA', array($isNewCompetition ? competitionLink($competitionId, $competitionCellName) : '', $roundCellName, $isNewCompetition ? "<b>{$pos}</b>" : $pos, $formatBest, $regionalSingleRecord, $formatAverage, $regionalAverageRecord, formatAverageSources(true, $result, $valueFormat)));
        }
    }
    tableEnd();
}
function showRegionalRecordsSlim()
{
    #----------------------------------------------------------------------
    global $chosenYears;
    require 'regions_get_current_records.php';
    tableBegin('results', 6);
    $caption = spaced(array(chosenRegionName(), $chosenYears));
    if ($caption) {
        tableCaption(true, $caption);
    } else {
        tableRowBlank();
    }
    tableHeader(explode('|', 'Person|Single|Event|Average|Person|Result Details'), array(1 => "class='R2'", 2 => "class='c'", 3 => "class='R2'", 5 => 'class="f"'));
    #--- Process events.
    foreach (structureBy($results, 'eventId') as $eventResults) {
        $structure = structureBy($eventResults, 'type');
        $singles = $structure[0];
        $averages = isset($structure[1]) ? $structure[1] : array();
        $wasShownSinglePerson = $wasShownAveragePerson = array();
        #--- Process records for this event.
        $first = true;
        while ($singles || $averages) {
            #--- Get next single.
            $s = array_shift($singles);
            if (isset($wasShownSinglePerson[$s['personId']])) {
                $s = false;
            }
            $wasShownSinglePerson[$s['personId']] = true;
            #--- Get next average.
            $a = array_shift($averages);
            if (isset($wasShownAveragePerson[$a['personId']])) {
                $a = false;
            }
            $wasShownAveragePerson[$a['personId']] = true;
            if ($s || $a) {
                tableRow(array($s ? personLink($s['personId'], $s['personName']) : '', $first ? formatValue($s['value'], $s['format']) : '', $first ? eventLink($s['eventId'], $s['eventCellName']) : '', $first ? formatValue($a['value'], $a['format']) : '', $a ? personLink($a['personId'], $a['personName']) : '', $a ? formatAverageSources(true, $a, $a['format']) : ''));
            }
            $first = false;
        }
    }
    tableEnd();
}
function showRegionalRecordsMixed()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenYears;
    require 'regions_get_current_records.php';
    tableBegin('results', 6);
    tableCaption(false, spaced(array(chosenRegionName(), $chosenYears)));
    tableHeader(explode('|', 'Type|Result|Person|Citizen of|Competition|Result Details'), array(1 => "class='R2'", 5 => 'class="f"'));
    foreach ($results as $result) {
        extract($result);
        $isNewEvent = !isset($currentEventId) || $eventId != $currentEventId;
        $currentEventId = $eventId;
        $isNewType = $isNewEvent || !isset($currentType) || $type != $currentType;
        $currentType = $type;
        if ($isNewEvent) {
            tableCaption(false, eventLink($eventId, $eventName));
        }
        tableRow(array($isNewType ? $type : '', $isNewType ? formatValue($value, $format) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources($type == 'Average', $result, $format)));
    }
    tableEnd();
}
function showHistoryOfContinentalRecords()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n      result.*,\n      event.format         valueFormat,\n      event.cellName       eventCellName,\n      competition.cellName competitionCellName,\n      round.cellName       roundCellName\n    FROM\n      Results      result,\n      Competitions competition,\n      Events       event,\n      Rounds       round\n    WHERE " . randomDebug() . "\n      AND result.personId = '{$chosenPersonId}'\n      AND ((result.regionalSingleRecord != '' AND result.regionalSingleRecord != 'NR' AND result.regionalSingleRecord != 'WR') OR (result.regionalAverageRecord != '' AND result.regionalAverageRecord != 'NR' AND result.regionalAverageRecord != 'WR'))\n      AND event.id = result.eventId\n      AND event.rank < 1000\n      AND competition.id = result.competitionId\n      AND round.id = result.roundId\n    ORDER BY\n      event.rank, year DESC, month DESC, day DESC, roundId DESC\n  ");
    if (!count($results)) {
        return;
    }
    tableBegin('results', 6);
    tableCaption(false, 'History of Continental Records');
    tableHeader(explode('|', 'Event|Single|Average|Competition|Round|Result Details'), array(1 => "class='R2'", 2 => "class='R2'", 5 => "class='f'"));
    foreach ($results as $result) {
        extract($result);
        if (isset($currentEventId) && $eventId != $currentEventId) {
            tableRowEmpty();
        }
        tableRow(array(isset($currentEventId) && $eventId == $currentEventId ? '' : eventLink($eventId, $eventCellName), ($regionalSingleRecord == '' or $regionalSingleRecord == 'NR' or $regionalSingleRecord == 'WR') ? '' : formatValue($best, $valueFormat), ($regionalAverageRecord == '' or $regionalAverageRecord == 'NR' or $regionalAverageRecord == 'WR') ? '' : formatValue($average, $valueFormat), competitionLink($competitionId, $competitionCellName), $roundCellName, formatAverageSources($regionalAverageRecord != '' and $regionalAverageRecord != 'NR' and $regionalAverageRecord != 'WR', $result, $valueFormat)));
        $currentEventId = $eventId;
    }
    tableEnd();
}
function showWorldChampionshipPodiums()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n      result.*,\n      event.format         valueFormat,\n      event.cellName       eventCellName,\n      competition.cellName competitionCellName,\n      year\n    FROM\n      Results      result,\n      Competitions competition,\n      Events       event\n    WHERE " . randomDebug() . "\n      AND best > 0\n      AND pos <= 3\n      AND roundId in ('f', 'c')\n      AND competition.cellName like 'World Championship %'\n      AND result.personId = '{$chosenPersonId}'\n      AND event.id = result.eventId\n      AND competition.id = result.competitionId\n      AND event.rank < 1000\n    ORDER BY\n      year DESC, event.rank\n  ");
    if (!count($results)) {
        return;
    }
    tableBegin('results', 6);
    tableCaption(false, 'World Championship Podiums');
    tableHeader(explode('|', 'Year|Event|Place|Single|Average|Result Details'), array(0 => "class='R2'", 2 => "class='R2'", 3 => "class='r'", 4 => "class='r'", 5 => "class='f'"));
    $lastYear = 0;
    foreach ($results as $result) {
        extract($result);
        if ($year < $lastYear) {
            tableRowEmpty();
        }
        tableRow(array($year != $lastYear ? $year : '', eventLink($eventId, $eventCellName), competitionLink($competitionId, $pos, $eventId, $roundId), formatValue($best, $valueFormat), formatValue($average, $valueFormat), formatAverageSources(true, $result, $valueFormat)));
        $lastYear = $year;
    }
    tableEnd();
}
function showCompetitionResults($competitionId, $eventId, $roundId)
{
    #----------------------------------------------------------------------
    # NOTE: This is mostly a copy of the same function in competition_results.php
    #--- Get the results.
    $competitionResults = getCompetitionResults($competitionId, $eventId, $roundId);
    tableBegin('results', 8);
    $prevEventId = $prevRoundId = '';
    foreach ($competitionResults as $result) {
        extract($result);
        $isNewEvent = $eventId != $prevEventId;
        $isNewRound = $roundId != $prevRoundId;
        #--- Welcome new rounds.
        if ($isNewEvent || $isNewRound) {
            $anchors = ($isNewEvent ? "{$eventId} " : "") . "{$eventId}_{$roundId}";
            $eventHtml = eventLink($eventId, $eventName);
            $caption = spaced(array($eventHtml, $roundName, $formatName));
            tableCaptionNew(false, $anchors, $caption);
            $bo3_as_mo3 = $formatId == '3' && ($eventId == '333bf' || $eventId == '333fm' || $eventId == '333ft');
            $headerAverage = $formatId == 'a' || $formatId == 'm' || $bo3_as_mo3 ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableHeader(explode('|', "Place|Person|Best||{$headerAverage}||Citizen of|{$headerAllResults}"), array(0 => 'class="r"', 2 => 'class="R"', 4 => 'class="R"', 7 => 'class="f"'));
        }
        #--- One result row.
        tableRow(array($pos, personLink($personId, $personName), formatValue($best, $valueFormat), $regionalSingleRecord, formatValue($average, $valueFormat), $regionalAverageRecord, $countryName, formatAverageSources($formatId != '1', $result, $valueFormat)));
        $prevEventId = $eventId;
        $prevRoundId = $roundId;
    }
    tableEnd();
}
    }
    $result['regionName'] = 'World';
    if ($value == $bestValueOfWorld) {
        $bestOfWorld[] = $result;
    }
}
#----------------------------------------------------------------------
#   Print the table.
#----------------------------------------------------------------------
startTimer();
$regionName = preg_replace('/^_/', '', $chosenRegionId);
$eventName = eventName($chosenEventId);
$headerSources = $chosenAverage ? 'Result Details' : '';
tableBegin('results', 5);
tableCaption(true, spaced(array($eventName, $chosenShow, $regionName, $chosenYears)));
tableHeader(explode('|', "Region|Result|Person|Competition|{$headerSources}"), array(0 => 'class="L"', 1 => "class='R2'", 4 => 'class="f"'));
if (isset($bestOfCountry)) {
    $all = array_merge($bestOfWorld, array(0), $bestOfContinent, array(0), $bestOfCountry);
    foreach ($all as $row) {
        if (!$row) {
            tableRowEmpty();
            continue;
        }
        extract($row);
        $isNewRegion = !isset($previousRegionName) || $regionName != $previousRegionName;
        $previousRegionName = $regionName;
        tableRow(array($isNewRegion ? $regionName : '', $isNewRegion ? formatValue($value, $valueFormat) : '', personLink($personId, $personName), competitionLink($competitionId, $competitionName), formatAverageSources($chosenAverage, $row, $valueFormat)));
    }
}
tableEnd();
stopTimer("printing the table");