function listCompetitions()
{
    #----------------------------------------------------------------------
    global $chosenEventId, $chosenYears, $chosenRegionId, $chosenPatternHtml;
    global $chosenList, $chosenMap;
    global $chosenCompetitions;
    $chosenCompetitions = getCompetitions($chosenList);
    tableBegin('results', 5);
    tableCaption(false, spaced(array(eventName($chosenEventId), chosenRegionName(), $chosenYears, $chosenPatternHtml ? "\"{$chosenPatternHtml}\"" : '')));
    if ($chosenList) {
        tableHeader(explode('|', 'Year|Date|Name|Country, City|Venue'), array(4 => 'class="f"'));
        foreach ($chosenCompetitions as $competition) {
            extract($competition);
            if (isset($previousYear) && $year != $previousYear) {
                tableRowEmpty();
            }
            $previousYear = $year;
            $isPast = wcaDate('Ymd') > 10000 * $year + 100 * $month + $day;
            tableRow(array($year, competitionDate($competition), $isPast ? competitionLink($id, $cellName) : ($showPreregForm || $showPreregList ? competitionLinkClassed('rg', $id, $cellName) : competitionLinkClassed('fc', $id, $cellName)), "<b>{$countryName}</b>, {$cityName}", processLinks($venue)));
        }
    }
    tableEnd();
    if ($chosenMap) {
        // create map markers
        $markers = array();
        foreach ($chosenCompetitions as $comp) {
            $markers[$comp['id']] = array();
            $markers[$comp['id']]['latitude'] = $comp['latitude'];
            $markers[$comp['id']]['longitude'] = $comp['longitude'];
            $markers[$comp['id']]['info'] = "<a href='c.php?i=" . $comp['id'] . "'>" . o($comp['cellName']) . "</a><br />" . date("M j, Y", mktime(0, 0, 0, $comp['month'], $comp['day'], $comp['year'])) . " - " . o($comp['cityName']);
        }
        displayMap($markers);
    }
}
function showResults()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenSingle, $chosenAverage;
    #------------------------------
    # Prepare stuff for the query.
    #------------------------------
    $regionCondition = regionCondition('result');
    $limitCondition = 'LIMIT 120';
    $valueSource = $chosenAverage ? 'average' : 'best';
    $valueName = $chosenAverage ? 'Average' : 'Single';
    #------------------------------
    # Get results from database.
    #------------------------------
    $limitNumber = 300;
    $ranks = getRanks($valueName, $chosenRegionId);
    list($rows, $header) = sumOfRanks($valueName, getAllEventIds(), $ranks, $limitNumber + 20);
    $header = preg_replace('/ +/', '|', preg_replace('/\\[\\w+\\]/', '', "Rank {$header} "));
    foreach (dbQuery("SELECT id, name FROM Persons WHERE subId=1") as $person) {
        $personName[$person[0]] = $person[1];
    }
    #------------------------------
    # Show the table.
    #------------------------------
    $numColumns = count($rows[0]) + 2;
    $headerAttributes = array(0 => "class='r'", 2 => "class='R2'", $numColumns - 1 => 'class="f"');
    for ($i = 3; $i < $numColumns - 1; $i++) {
        $headerAttributes[$i] = "class='r'";
    }
    tableBegin('results', $numColumns);
    tableCaption(true, chosenRegionName(true));
    #  tableHeader( explode( '|', $header), $headerAttributes );
    $ctr = $previousSumOfRanks = 0;
    $showHeader = true;
    foreach ($rows as $row) {
        $showHeader |= $ctr % 20 == 0;
        list($personId, $sumOfRanks) = $row;
        $ctr++;
        $no = $sumOfRanks == $previousSumOfRanks ? '' : $ctr;
        if ($limitCondition && $no > $limitNumber) {
            break;
        }
        if ($showHeader && $no) {
            tableHeader(explode('|', $header), $headerAttributes);
            $showHeader = false;
        }
        for ($i = 2; $i < $numColumns - 2; $i++) {
            if (preg_match('/^(10|[1-9])$/', $row[$i])) {
                $row[$i] = "<span style='color:#0D0'>{$row[$i]}</span>";
            }
        }
        $row[0] = personLink($row[0], $personName[$row[0]]);
        $row[] = '';
        array_unshift($row, $no);
        tableRow($row);
        $previousSumOfRanks = $sumOfRanks;
    }
    tableEnd();
}
function showMatchingPersons()
{
    #----------------------------------------------------------------------
    global $chosenPatternHtml, $chosenPatternMysql, $chosenEventId, $chosenRegionId;
    #--- If nothing chosen yet, display a help message.
    if (!$chosenPatternHtml && !$chosenEventId && !$chosenRegionId) {
        echo "<div style='width:85%; margin:auto; font-size:1.00em; font-weight:bold'><p>For the name field search, enter any name or name parts and don't worry about letter variations. For example, 'or joe' (enter without the quotes) will among others also find Jo&euml;l van Noort.</p></div>";
        return;
    }
    #--- The pattern should contain at least 2 non-whitespace characters.
    if (!preg_match('/\\S.*\\S/', $chosenPatternHtml)) {
        noticeBox3(-1, "Please Enter at least 2 characters.");
        echo "<div style='width:85%; margin:auto; font-size:1.00em; font-weight:bold'><p>For the name field search, enter any name or name parts and don't worry about letter variations. For example, 'or joe' (enter without the quotes) will among others also find Jo&euml;l van Noort.</p></div>";
        return;
    }
    #--- Otherwise, build up a query to search for people.
    global $wcadb_conn;
    $params = array(0 => '');
    $parts = array();
    $rawPattern = getRawParamThisShouldBeAnException('pattern');
    #--- Build the nameCondition (all searched parts must occur).
    $nameCondition = "";
    foreach (explode(' ', $rawPattern) as $namePart) {
        $parts[$namePart] = '%' . $namePart . '%';
        $params[0] .= 's';
        $params[] =& $parts[$namePart];
        $likeId = '';
        if (ctype_alnum($namePart)) {
            $params[0] .= 's';
            $params[] =& $parts[$namePart];
            $likeId = ' OR person.id LIKE ?';
        }
        $nameCondition .= ' AND (person.name LIKE ?' . $likeId . ')';
    }
    #--- Build the eventCondition (if any).
    if ($chosenEventId) {
        $eventConditionPart1 = ', (SELECT DISTINCT personId FROM ConciseSingleResults WHERE 1 ' . eventCondition() . ') result';
        $eventConditionPart2 = 'AND person.id = result.personId';
    } else {
        $eventConditionPart1 = '';
        $eventConditionPart2 = '';
    }
    #--- Do the query!
    $query = 'SELECT DISTINCT person.id AS personId, person.name AS personName, country.name AS countryName
            FROM Persons AS person, Countries AS country' . $eventConditionPart1 . ' WHERE ' . randomDebug() . $nameCondition . regionCondition('') . ' AND country.id = person.countryId' . $eventConditionPart2 . ' ORDER BY personName, countryName, personId';
    $persons = $wcadb_conn->boundQuery($query, $params);
    $count = count($persons);
    $ext = $count != 1 ? 's' : '';
    tableBegin('results', 3);
    tableCaption(false, spaced(array("{$count} person{$ext} matching:", eventName($chosenEventId), chosenRegionName($chosenRegionId), $chosenPatternHtml ? "\"{$chosenPatternHtml}\"" : '')));
    tableHeader(explode('|', 'Person|WCA id|Citizen of'), array(2 => 'class="f"'));
    foreach ($persons as $person) {
        extract($person);
        tableRow(array(personLink($personId, $personName), $personId, $countryName));
    }
    tableEnd();
}
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 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();
}