]> git.sesse.net Git - ultimatescore/blob - carousel.js
Fix the display of the points in each group.
[ultimatescore] / carousel.js
1 'use strict';
2
3 function jsonclone(x)
4 {
5         return JSON.parse(JSON.stringify(x));
6 }
7
8 // Log with deep clone, so that the browser will show the object at time of log,
9 // instead of what it looks like at time of view.
10 function dlog()
11 {
12         let args = [];
13         for (const arg of arguments) {
14                 args.push(jsonclone(arg));
15         }
16         console.log(args);
17 }
18
19 function addheading(carousel, colspan, content)
20 {
21         let thead = document.createElement("thead");
22         let tr = document.createElement("tr");
23         let th = document.createElement("th");
24         th.innerHTML = content;
25         th.setAttribute("colspan", colspan);
26         tr.appendChild(th);
27         thead.appendChild(tr);
28         carousel.appendChild(thead);
29 }
30
31 function addtd(tr, className, content) {
32         let td = document.createElement("td");
33         td.appendChild(document.createTextNode(content));
34         td.className = className;
35         tr.appendChild(td);
36 }
37
38 function addth(tr, className, content) {
39         let th = document.createElement("th");
40         th.appendChild(document.createTextNode(content));
41         th.className = className;
42         tr.appendChild(th);
43 }
44
45 function subrank_partitions(games, parts, start_rank, tiebreakers, func) {
46         let result = [];
47         for (let i = 0; i < parts.length; ++i) {
48                 let part = func(games, parts[i], start_rank, tiebreakers);
49                 for (let j = 0; j < part.length; ++j) {
50                         result.push(part[j]);
51                 }
52                 start_rank += part.length;
53         }
54         return result;
55 };
56
57 function partition(teams, compare)
58 {
59         teams.sort(compare);
60
61         let parts = [];
62         let curr_part = [teams[0]];
63         for (let i = 1; i < teams.length; ++i) {
64                 if (compare(teams[i], curr_part[0]) != 0) {
65                         parts.push(curr_part);
66                         curr_part = [];
67                 }
68                 curr_part.push(teams[i]);
69         }
70         if (curr_part.length != 0) {
71                 parts.push(curr_part);
72         }
73         return parts;
74 };
75
76 function explain_tiebreaker(parts, rule_name)
77 {
78         let result = [];
79         for (let i = 0; i < parts.length; ++i) {
80                 result.push(parts[i].map(function(x) { return x.shortname; }).join("/"));
81         }
82         return result.join(" > ") + " (" + rule_name + ")";
83 }
84
85 function make_teams_to_idx(teams)
86 {
87         let teams_to_idx = [];
88         for (let i = 0; i < teams.length; i++) {
89                 teams_to_idx[teams[i].name] = i;
90                 teams_to_idx[teams[i].mediumname] = i;
91                 teams_to_idx[teams[i].shortname] = i;
92         }
93         return teams_to_idx;
94 }
95
96 function partition_by_beat(teams, fill_beatmatrix)
97 {
98         // Head-to-head score by way of components. First construct the beat matrix.
99         let n = teams.length;
100         let beat = new Array(n);
101         let teams_to_idx = make_teams_to_idx(teams);
102         for (let i = 0; i < n; i++) {
103                 beat[i] = new Array(n);
104                 for (let j = 0; j < n; j++) {
105                         beat[i][j] = 0;
106                 }
107         }
108         fill_beatmatrix(beat, teams_to_idx);
109         // Floyd-Warshall for transitive closure.
110         for (let k = 0; k < n; ++k) {
111                 for (let i = 0; i < n; ++i) {
112                         for (let j = 0; j < n; ++j) {
113                                 if (beat[i][k] && beat[k][j]) {
114                                         beat[i][j] = 1;
115                                 }
116                         }
117                 }
118         }
119
120         // See if we can find any team that is comparable to all others.
121         for (let pivot_idx = 0; pivot_idx < n; pivot_idx++) {
122                 let incomparable = false;
123                 for (let i = 0; i < n; ++i) {
124                         if (i != pivot_idx && beat[pivot_idx][i] == 0 && beat[i][pivot_idx] == 0) {
125                                 incomparable = true;
126                                 break;
127                         }
128                 }
129                 if (!incomparable) {
130                         // Split the teams into three partitions:
131                         let better_than_pivot = [], equal = [], worse_than_pivot = [];
132                         for (let i = 0; i < n; ++i) {
133                                 let we_beat = (beat[pivot_idx][i] == 1);
134                                 let they_beat = (beat[i][pivot_idx] == 1);
135                                 if ((i == pivot_idx) || (we_beat && they_beat)) {
136                                         equal.push(teams[i]);
137                                 } else if (we_beat && !they_beat) {
138                                         worse_than_pivot.push(teams[i]);
139                                 } else if (they_beat && !we_beat) {
140                                         better_than_pivot.push(teams[i]);
141                                 } else {
142                                         console.log("this shouldn't happen");
143                                 }
144                         } 
145                         let result = [];
146                         if (better_than_pivot.length > 0) {
147                                 result = partition_by_beat(better_than_pivot, fill_beatmatrix);
148                         }
149                         result.push(equal);  // Obviously can't be partitioned further.
150                         if (worse_than_pivot.length > 0) {
151                                 result = result.concat(partition_by_beat(worse_than_pivot, fill_beatmatrix));
152                         }
153                         return result;
154                 }
155         }
156
157         // No usable pivot was found, so the graph is inherently
158         // disconnected, and we cannot partition it.
159         return [teams];
160 }
161
162 // Takes in an array, gives every element a rank starting with 1, and returns.
163 function rank(games, teams, start_rank, tiebreakers) {
164         if (teams.length <= 1) {
165                 // Only one team, so trivial.
166                 teams[0].rank = start_rank;
167                 return teams;
168         }
169
170         // Rule #0: Partition the teams by score.
171         let score_parts = partition(teams, function(a, b) { return b.pts - a.pts });
172         if (score_parts.length > 1) {
173                 return subrank_partitions(games, score_parts, start_rank, tiebreakers, rank);
174         }
175
176         // Rule #1: Head-to-head wins.
177         let num_relevant_games = 0;
178         let beat_parts = partition_by_beat(teams, function(beat, teams_to_idx) {
179                 for (let i = 0; i < games.length; ++i) {
180                         let idx1 = teams_to_idx[games[i].name1];
181                         let idx2 = teams_to_idx[games[i].name2];
182                         if (idx1 !== undefined && idx2 !== undefined) {
183                                 if (games[i].score1 > games[i].score2) {
184                                         beat[idx1][idx2] = 1;
185                                         ++num_relevant_games;
186                                 } else if (games[i].score1 < games[i].score2) {
187                                         beat[idx2][idx1] = 1;
188                                         ++num_relevant_games;
189                                 }
190                         }
191                 }
192         });
193         if (beat_parts.length > 1) {
194                 tiebreakers.push(explain_tiebreaker(beat_parts, 'head-to-head'));
195                 return subrank_partitions(games, beat_parts, start_rank, tiebreakers, rank);
196         }
197
198         // Rule #2: Number of games played (fewer is better).
199         // Actually the rule says “fewest losses”, but fewer games is equivalent
200         // as long as teams have the same amount of points and ties don't exist.
201         let nplayed_parts = partition(teams, function(a, b) { return a.nplayed - b.nplayed });
202         if (nplayed_parts.length > 1) {
203                 tiebreakers.push(explain_tiebreaker(nplayed_parts, 'fewer losses'));
204                 return subrank_partitions(games, nplayed_parts, start_rank, tiebreakers, rank);
205         }
206
207         // Rule #3: Head-to-head goal difference (if all have played).
208         let teams_to_idx = make_teams_to_idx(teams);
209         if (num_relevant_games >= teams.length * (teams.length - 1) / 2) {
210                 for (let i = 0; i < teams.length; i++) {
211                         teams[i].h2h_gd = 0;
212                         teams[i].h2h_goals = 0;
213                 }
214                 for (let i = 0; i < games.length; ++i) {
215                         let idx1 = teams_to_idx[games[i].name1];
216                         let idx2 = teams_to_idx[games[i].name2];
217                         if (idx1 !== undefined && idx2 !== undefined &&
218                             !isNaN(games[i].score1) && !isNaN(games[i].score2)) {
219                                 teams[idx1].h2h_gd += games[i].score1;
220                                 teams[idx1].h2h_gd -= games[i].score2;
221                                 teams[idx2].h2h_gd += games[i].score2;
222                                 teams[idx2].h2h_gd -= games[i].score1;
223
224                                 teams[idx1].h2h_goals += games[i].score1;
225                                 teams[idx2].h2h_goals += games[i].score2;
226                         }
227                 }
228                 let h2h_gd_parts = partition(teams, function(a, b) { return b.h2h_gd - a.h2h_gd });
229                 if (h2h_gd_parts.length > 1) {
230                         tiebreakers.push(explain_tiebreaker(h2h_gd_parts, 'head-to-head goal difference'));
231                         return subrank_partitions(games, h2h_gd_parts, start_rank, tiebreakers, rank);
232                 }
233         }
234
235         // Rule #4: Goal difference against common opponents.
236         var results = {};
237         for (let i = 0; i < games.length; ++i) {
238                 if (results[games[i].name1] === undefined) {
239                         results[games[i].name1] = {};
240                 }
241                 if (results[games[i].name2] === undefined) {
242                         results[games[i].name2] = {};
243                 }
244                 results[games[i].name1][games[i].name2] = [ games[i].score1, games[i].score2 ];
245                 results[games[i].name2][games[i].name1] = [ games[i].score2, games[i].score1 ];
246         }
247         let gd_parts = partition_by_beat(teams, function(beat, teams_to_idx) {
248                 for (const team_i of Object.keys(teams_to_idx)) {
249                         let i = teams_to_idx[team_i];
250                         for (const team_j of Object.keys(teams_to_idx)) {
251                                 let j = teams_to_idx[team_j];
252                                 let results_i = results[team_i], results_j = results[team_j];
253                                 let gd_i = 0, gd_j = 0;
254
255                                 // See if the two teams have both played a third team k.
256                                 for (let k in results_i) {
257                                         if (!results_i.hasOwnProperty(k)) continue;
258                                         if (results_j !== undefined && results_j[k] !== undefined) {
259                                                 gd_i += results_i[k][0] - results_i[k][1];
260                                                 gd_j += results_j[k][0] - results_j[k][1];
261                                         }
262                                 }
263
264                                 if (gd_i > gd_j) {
265                                         beat[i][j] = 1;
266                                 } else if (gd_i < gd_j) {
267                                         beat[j][i] = 1;
268                                 }
269                         }
270                 }
271         });
272         if (gd_parts.length > 1) {
273                 tiebreakers.push(explain_tiebreaker(gd_parts, 'goal difference versus common opponents'));
274                 return subrank_partitions(games, gd_parts, start_rank, tiebreakers, rank);
275         }
276
277         // Rule #5: Head-to-head scored goals (if all have played).
278         if (num_relevant_games >= teams.length * (teams.length - 1) / 2) {
279                 let h2h_goals_parts = partition(teams, function(a, b) { return b.h2h_goals - a.h2h_goals });
280                 if (h2h_goals_parts.length > 1) {
281                         tiebreakers.push(explain_tiebreaker(h2h_goals_parts, 'head-to-head scored goals'));
282                         return subrank_partitions(games, h2h_goals_parts, start_rank, tiebreakers, rank);
283                 }
284         }
285
286         // Rule #6: Goals scored against common opponents.
287         let goals_parts = partition_by_beat(teams, function(beat, teams_to_idx) {
288                 for (const team_i of Object.keys(teams_to_idx)) {
289                         let i = teams_to_idx[team_i];
290                         for (const team_j of Object.keys(teams_to_idx)) {
291                                 let j = teams_to_idx[team_j];
292                                 let results_i = results[team_i], results_j = results[team_j];
293                                 let goals_i = 0, goals_j = 0;
294
295                                 // See if the two teams have both played a third team k.
296                                 for (let k in results_i) {
297                                         if (!results_i.hasOwnProperty(k)) continue;
298                                         if (results_j !== undefined && results_j[k] !== undefined) {
299                                                 goals_i += results_i[k][0];
300                                                 goals_j += results_j[k][0];
301                                         }
302                                 }
303
304                                 if (goals_i > goals_j) {
305                                         beat[i][j] = 1;
306                                 } else if (goals_i < goals_j) {
307                                         beat[j][i] = 1;
308                                 }
309                         }
310                 }
311         });
312         if (goals_parts.length > 1) {
313                 tiebreakers.push(explain_tiebreaker(goals_parts, 'goals scored against common opponents'));
314                 return subrank_partitions(games, goals_parts, start_rank, tiebreakers, rank);
315         }
316
317         // OK, it's a tie. Give them all the same rank.
318         let result = [];
319         for (let i = 0; i < teams.length; ++i) {
320                 result.push(teams[i]);
321                 result[i].rank = start_rank;
322         }
323         return result; 
324 }; 
325
326 // Same, but with the simplified rules for ranking thirds. games isn't used and can be empty.
327 function rank_thirds(games, teams, start_rank, tiebreakers) {
328         if (teams.length <= 1) {
329                 // Only one team, so trivial.
330                 teams[0].rank = start_rank;
331                 return teams;
332         }
333
334         // Rule #1: Partition the teams by score.
335         let score_parts = partition(teams, function(a, b) { return b.pts - a.pts });
336         if (score_parts.length > 1) {
337                 tiebreakers.push(explain_tiebreaker(score_parts, 'most games won'));
338                 return subrank_partitions(games, score_parts, start_rank, tiebreakers, rank_thirds);
339         }
340
341         // Rule #2: Goal difference against common opponents.
342         let gd_parts = partition(teams, function(a, b) { return b.gd - a.gd });
343         if (gd_parts.length > 1) {
344                 tiebreakers.push(explain_tiebreaker(gd_parts, 'goal difference'));
345                 return subrank_partitions(games, gd_parts, start_rank, tiebreakers, rank_thirds);
346         }
347         
348         // Rule #3: Goals scored.
349         let goal_parts = partition(teams, function(a, b) { return b.goals - a.goals });
350         if (goal_parts.length > 1) {
351                 tiebreakers.push(explain_tiebreaker(goal_parts, 'goals scored'));
352                 return subrank_partitions(games, goal_parts, start_rank, tiebreakers, rank_thirds);
353         }
354
355         // OK, it's a tie. Give them all the same rank.
356         let result = [];
357         for (let i = 0; i < teams.length; ++i) {
358                 result.push(teams[i]);
359                 result[i].rank = start_rank;
360         }
361         return result; 
362 }; 
363
364 function parse_teams_from_spreadsheet(response) {
365         let teams = [];
366         for (let i = 1; i < response.values.length && response.values[i].length >= 1; ++i) {
367                 teams.push({
368                         "name": response.values[i][0],
369                         "mediumname": response.values[i][1],
370                         "shortname": response.values[i][2],
371                         //"tags": response.values[i][3],
372                         "seeding": parseInt(response.values[i][3]),
373                         "ngames": 0,
374                         "nplayed": 0,
375                         "gd": 0,
376                         "pts": 0,
377                         "goals": 0
378                 });
379         }
380         return teams;
381 };
382
383 function parse_games_from_spreadsheet(response, group_name, include_unplayed) {
384         let games = [];
385         let i;
386         for (i = 0; i < response.values.length; ++i) {
387                 if (response.values[i][0] === 'Results') {
388                         i += 2;
389                         break;
390                 }
391         }
392
393         for ( ; response.values[i] !== undefined && response.values[i].length >= 1; ++i) {
394                 if ((response.values[i][2] && response.values[i][3]) || include_unplayed) {
395                         let real_group_name = response.values[i][9];
396                         if (real_group_name === undefined) {
397                                 real_group_name = group_name;
398                         }
399                         games.push({
400                                 "name1": response.values[i][0],
401                                 "name2": response.values[i][1],
402                                 "score1": parseInt(response.values[i][2]),
403                                 "score2": parseInt(response.values[i][3]),
404                                 "streamday": response.values[i][7],
405                                 "streamtime": response.values[i][8].replace('.', ':'),
406                                 "group_name": real_group_name
407                         });
408                 }
409         }
410         return games;
411 };
412
413 function get_team_code(teams, str) {
414         for (const team of teams) {
415                 if (team.name === str || team.mediumname === str || team.shortname === str) {
416                         return team.shortname;
417                 }
418         }
419         return str;
420 }
421
422 function get_all_group_games(teams, groups, cb) {
423         get_sheet('Results', function(response) {
424                 let games = [];
425                 for (const region of ultimateconfig['group_match_scores']) {
426                         for (let row = region.first_row; row <= region.last_row; ++row) {
427                                 let team1 = get_team_code(teams, response.values[row - 1][region.team1_column]);
428                                 let team2 = get_team_code(teams, response.values[row - 1][region.team2_column]);
429                                 if (team1 === undefined || team2 === undefined || team1 === '' || team2 === '' || team1 === null || team2 === null) {
430                                         continue;
431                                 }
432                                 let group_name = region.group_name;
433                                 if (group_name === undefined) {
434                                         // Infer group from whatever group both teams are in.
435                                         for (const [group, teams] of Object.entries(groups)) {
436                                                 if (teams.indexOf(team1) != -1 && teams.indexOf(team2) != -1) {
437                                                         group_name = group;
438                                                         break;
439                                                 }
440                                         }
441                                 }
442                                 let game = {
443                                         "name1": team1,
444                                         "name2": team2,
445                                         "score1": parseInt(response.values[row - 1][region.team1_score_column]),
446                                         "score2": parseInt(response.values[row - 1][region.team2_score_column]),
447                                         "group_name": group_name
448                                 };
449                                 if (region.stream_time_column !== undefined) {
450                                         game["streamtime"] = response.values[row - 1][region.stream_time_column].replace('.', ':');
451                                         game["streamday"] = region.stream_day;
452                                 }
453                                 games.push(game);
454                         }
455                 }
456                 cb(games);
457         });
458 };
459
460 function apply_games_to_teams(games, teams, group_name, ignored_teams, ret_ignored_games)
461 {
462         let teams_to_idx = make_teams_to_idx(teams);
463         let ignored_teams_idx;
464         if (ignored_teams === undefined) {
465                 ignored_teams_idx = [];
466         } else {
467                 ignored_teams_idx = make_teams_to_idx(ignored_teams);
468         }
469         for (let i = 0; i < teams.length; ++i) {
470                 teams[i].nplayed = 0;
471                 teams[i].goals = 0;
472                 teams[i].gd = 0;
473                 teams[i].pts = 0;
474         }
475         for (let i = 0; i < games.length; ++i) {
476                 if (games[i].group_name !== group_name) {
477                         continue;
478                 }
479                 let idx1 = teams_to_idx[games[i].name1];
480                 let idx2 = teams_to_idx[games[i].name2];
481                 if (games[i].score1 === undefined || games[i].score2 === undefined ||
482                     isNaN(games[i].score1) || isNaN(games[i].score2) ||
483                     idx1 === undefined || idx2 === undefined ||
484                     games[i].score1 == games[i].score2) {
485                         continue;
486                 }
487
488                 let ignored_idx1 = ignored_teams_idx[games[i].name1];
489                 let ignored_idx2 = ignored_teams_idx[games[i].name2];
490                 if (ignored_idx1 !== undefined || ignored_idx2 !== undefined) {
491                         if (ret_ignored_games !== undefined) {
492                                 // Figure out whether the fifth we're ignoring was only picked out arbitrarily
493                                 // (ie., there's a tie for 5th); if so, mark it as such.
494                                 let arbitrary = false;
495                                 if (ignored_idx1 !== undefined && ignored_teams[ignored_idx1].rank < 5) {
496                                         arbitrary = true;
497                                 } else if (ignored_idx2 !== undefined && ignored_teams[ignored_idx2].rank < 5) {
498                                         arbitrary = true;
499                                 }
500                                 ret_ignored_games.push([teams[idx1].shortname, teams[idx2].shortname, arbitrary]);
501                         }
502                         continue;
503                 }
504                 ++teams[idx1].nplayed;
505                 ++teams[idx2].nplayed;
506                 teams[idx1].goals += games[i].score1;
507                 teams[idx2].goals += games[i].score2;
508                 teams[idx1].gd += games[i].score1;
509                 teams[idx2].gd += games[i].score2;
510                 teams[idx1].gd -= games[i].score2;
511                 teams[idx2].gd -= games[i].score1;
512                 if (games[i].score1 > games[i].score2) {
513                         teams[idx1].pts += 2;
514                 } else {
515                         teams[idx2].pts += 2;
516                 }
517         }
518 }
519
520 // So that we can just have one team list, and let membership be defined by games.
521 function filter_teams(teams, response)
522 {
523         let teams_to_idx = make_teams_to_idx(teams);
524         let games = parse_games_from_spreadsheet(response, 'irrelevant group name', true);
525         for (let i = 0; i < games.length; ++i) {
526                 let idx1 = teams_to_idx[games[i].name1];
527                 let idx2 = teams_to_idx[games[i].name2];
528                 if (idx1 !== undefined) {
529                         ++teams[idx1].ngames;  // FIXME: shouldn't nplayed be just as good?
530                 }
531                 if (idx2 !== undefined) {
532                         ++teams[idx2].ngames;
533                 }
534         }
535         return teams.filter(function(team) { return team.ngames > 0; });
536 }
537
538 // So that we can just have one team list, and let membership be defined by the group list.
539 function filter_teams_by_group(teams, groups, group)
540 {
541         return teams.filter(function(team) {
542                 return groups[group].indexOf(team.shortname) != -1;
543         });
544 }
545
546 function display_group_parsed(teams, games, group_name)
547 {
548         document.getElementById('entire-bug').style.display = 'none';
549
550         apply_games_to_teams(games, teams, group_name);
551         let tiebreakers = [];
552         teams = rank(games, teams, 1, tiebreakers);
553
554         let carousel = document.getElementById('carousel');
555         clear_carousel(carousel);
556
557         addheading(carousel, 5, "Current standings, " + ultimateconfig['tournament_title'] + "<br />" + group_name);
558         let tr = document.createElement("tr");
559         tr.className = "subfooter";
560         addth(tr, "rank", "");
561         addth(tr, "team", "");
562         addth(tr, "nplayed", "P");
563         addth(tr, "gd", "GD");
564         addth(tr, "pts", "Pts");
565         carousel.appendChild(tr);
566
567         let row_num = 2;
568         for (let i = 0; i < teams.length; ++i) {
569                 let tr = document.createElement("tr");
570
571                 addth(tr, "rank", teams[i].rank);
572                 addtd(tr, "team", teams[i].name);
573                 addtd(tr, "nplayed", teams[i].nplayed);
574                 addtd(tr, "gd", teams[i].gd.toString().replace(/-/, '−'));
575                 addtd(tr, "pts", teams[i].pts);
576
577                 carousel.appendChild(tr);
578         }
579
580         if (tiebreakers.length > 0) {
581                 let tie_tr = document.createElement("tr");
582                 tie_tr.className = "footer";
583                 let td = document.createElement("td");
584                 td.appendChild(document.createTextNode("Tiebreaks applied: " + tiebreakers.join(', ')));
585                 td.setAttribute("colspan", "5");
586                 tie_tr.appendChild(td);
587                 carousel.appendChild(tie_tr);
588         }
589
590         let footer_tr = document.createElement("tr");
591         footer_tr.className = "footer";
592         let td = document.createElement("td");
593         td.appendChild(document.createTextNode(ultimateconfig['tournament_footer']));
594         td.setAttribute("colspan", "5");
595         footer_tr.appendChild(td);
596         carousel.appendChild(footer_tr);
597
598         fade_in_rows(carousel);
599
600         carousel.style.display = 'table';
601 };
602
603 function fade_in_rows(table)
604 {
605         let trs = table.getElementsByTagName("tr");
606         for (let i = 1; i < trs.length; ++i) {  // The header already has its own fade-in.
607                 if (trs[i].className === "footer") {
608                         trs[i].style = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-delay: " + (0.25 * i) + "s; -webkit-animation-fill-mode: both;";
609                 } else {
610                         trs[i].style = "-webkit-animation: fade-in 2.0s ease; -webkit-animation-delay: " + (0.25 * i) + "s; -webkit-animation-fill-mode: both;";
611                 }
612         }
613 };
614
615 function fade_out_rows(table)
616 {
617         let trs = table.getElementsByTagName("tr");
618         for (let i = 0; i < trs.length; ++i) {
619                 if (trs[i].className === "footer") {
620                         trs[i].style = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-delay: " + (0.125 * i) + "s; -webkit-animation-fill-mode: both;";
621                 } else {
622                         trs[i].style = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-delay: " + (0.125 * i) + "s; -webkit-animation-fill-mode: both;";
623                 }
624         }
625 };
626
627 function clear_carousel(table)
628 {
629         while (table.childNodes.length > 0) {
630                 table.removeChild(table.firstChild);
631         }
632 };
633
634 // Stream schedule
635 let max_list_len = 7;
636
637 function sort_game_list(games) {
638         games = games.filter(function(game) { return game.streamtime !== undefined && game.streamtime.match(/[0-9]+:[0-9]+/) != null; });
639         games.sort(function(a, b) {
640                 if (a.streamday !== b.streamday) {
641                         return a.streamday - b.streamday;
642                 }
643
644                 let m1 = a.streamtime.match(/([0-9]+):([0-9]+)/);
645                 let m2 = b.streamtime.match(/([0-9]+):([0-9]+)/);
646                 return (m1[1] * 60 + m1[2]) - (m2[1] * 60 + m2[2]);
647         });
648         return games;
649 }
650
651 function find_game_start_idx(games) {
652         // Pick out a reasonable place to start the list. We'll show the last
653         // completed match and start from there.
654         let start_idx = games.length - 1;
655         for (let i = 0; i < games.length; ++i) {
656                 if (isNaN(games[i].score1) || isNaN(games[i].score2) &&
657                     games[i].score1 === games[i].score2) {
658                         start_idx = i;
659                         break;
660                 }
661         }
662         if (start_idx > 0) start_idx--;
663         if (games.length >= max_list_len) {
664                 start_idx = Math.min(start_idx, games.length - max_list_len);
665         }
666         return start_idx;
667 }
668
669 function find_num_pages(games) {
670         games = sort_game_list(games);
671         let start_idx = find_game_start_idx(games);
672         return Math.ceil((games.length - start_idx) / max_list_len);
673 }
674
675 function get_mediumname(name, teams, teams_to_idx)
676 {
677         if (teams_to_idx[name] === undefined) {
678                 return name.replace(/^W /, 'Winner ').replace(/^L /, 'Loser ');
679         } else {
680                 return teams[teams_to_idx[name]].mediumname;
681         }
682 }
683
684 function display_stream_schedule_parsed(teams, games, page) {
685         document.getElementById('entire-bug').style.display = 'none';
686
687         games = sort_game_list(games);
688         let start_idx = find_game_start_idx(games);
689
690         start_idx += page * max_list_len;
691         if (start_idx >= games.length) {
692                 // Error.
693                 return;
694         }
695
696         let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
697         let shortdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
698         let today = days[(new Date).getDay()];
699
700         let covered_days = [];
701         let row_num = 0;
702         for (let i = start_idx; i < games.length && row_num++ < max_list_len; ++i) {
703                 if (i == start_idx || games[i].streamday != games[i - 1].streamday) {
704                         covered_days.push(days[games[i].streamday]);
705                 }
706         }
707         
708         let carousel = document.getElementById('carousel');
709         clear_carousel(carousel);
710         addheading(carousel, 3, "Stream schedule, " + ultimateconfig['tournament_title'] + "<br />" + covered_days.join('/') + " (all times CET)");
711
712         let teams_to_idx = make_teams_to_idx(teams);
713         row_num = 0;
714         for (let i = start_idx; i < games.length && row_num < max_list_len; ++i) {
715                 let tr = document.createElement("tr");
716
717                 let name1 = get_mediumname(games[i].name1, teams, teams_to_idx);
718                 let name2 = get_mediumname(games[i].name2, teams, teams_to_idx);
719
720                 addtd(tr, "matchup", name1 + "–" + name2);
721                 addtd(tr, "group", games[i].group_name);
722
723                 if (!isNaN(games[i].score1) && !isNaN(games[i].score2) &&
724                     games[i].score1 !== games[i].score2) {
725                         addtd(tr, "streamtime", games[i].score1 + "–" + games[i].score2);
726                 } else {
727                         let streamtime = games[i].streamtime;
728                         let streamday = days[games[i].streamday];
729                         if (streamday !== today) {
730                                 streamtime = shortdays[games[i].streamday] + " " + streamtime;
731                         }
732                         addth(tr, "streamtime", streamtime);
733                 }
734
735                 row_num++;
736                 carousel.appendChild(tr);
737         }
738
739         fade_in_rows(carousel);
740
741         carousel.style.display = 'table';
742 };
743
744 function get_sheet(sheet_name, cb)
745 {
746         let req = new XMLHttpRequest();
747         req.onload = function(e) {
748                 cb(JSON.parse(req.responseText));
749         };
750         req.open('GET', 'https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values/\'' + sheet_name + '\'!A1:Z50?key=' + ultimateconfig['api_key']);
751         req.send();
752 }
753
754 function get_group(group_name, cb)
755 {
756         get_sheet(group_name, function(response) {
757                 cb(response, group_name);
758         });
759 }
760
761 function get_teams(cb)
762 {
763         get_sheet('Teams', function(response) {
764                 cb(parse_teams_from_spreadsheet(response));
765         });
766 }
767
768 function get_groups(cb)
769 {
770         get_sheet('Groups', function(response) {
771                 let groups = {};
772                 for (let i = 1; i < response.values.length && response.values[i].length >= 1; ++i) {
773                         let team = response.values[i][0];
774                         let group = response.values[i][1];
775                         if (groups[group] === undefined) {
776                                 groups[group] = [];
777                         }
778                         groups[group].push(team);
779                 }
780                 cb(groups);
781         });
782 }
783
784 function showgroup(group_name)
785 {
786         get_teams(function(teams) {
787                 get_groups(function(groups) {
788                         get_all_group_games(teams, groups, function(games) {
789                                 teams = filter_teams_by_group(teams, groups, group_name);
790                                 display_group_parsed(teams, games, group_name);
791                                 publish_group_rank(response, group_name);  // Update the spreadsheet in the background.
792                         });
793                 });
794         });
795 }
796
797 function showgroup_from_state()
798 {
799         showgroup(state['group_name']);
800 }
801
802 let carousel_timeout = null;
803
804 function hidetable()
805 {
806         fade_out_rows(document.getElementById('carousel'));
807 };
808
809 function showschedule(page)
810 {
811         get_teams(function(teams) {
812                 get_groups(function(groups) {
813                         get_all_group_games(teams, groups, function(games) {
814                                 get_all_playoff_games(teams, groups, games, function(playoff_games) {
815                                         games = games.concat(playoff_games);
816                                         games = games.filter(function(game) { return game.streamday !== undefined; });
817                                         display_stream_schedule_parsed(teams, games, 0);
818                                 });
819                         });
820                 });
821         });
822 };
823
824 function do_series(series)
825 {
826         do_series_internal(series, 0);
827 };
828
829 function do_series_internal(series, idx)
830 {
831         (series[idx][1])();
832         if (idx + 1 < series.length) {
833                 carousel_timeout = setTimeout(function() { do_series_internal(series, idx + 1); }, series[idx][0]);
834         }
835 };
836
837 function showcarousel()
838 {
839         let groups_to_get = [
840                 'Group A',
841                 'Group B',
842                 'Group C',
843                 'Playoffs',
844                 'Playoffs 9th–11th',
845                 'Playoffs 12th–14th'
846         ];
847         get_teams(function(teams) {
848                 get_groups(function(groups) {
849                         get_all_group_games(teams, groups, function(games) {
850                                 get_all_playoff_games(teams, groups, games, function(playoff_games) {
851                                         games = games.concat(playoff_games);
852                                         games = games.filter(function(game) { return game.streamday !== undefined; });
853
854                                         let series = [
855                                                 [ 13000, function() { display_group_parsed(filter_teams_by_group(teams, groups, 'Group A'), games, 'Group A'); } ],
856                                                 [ 2000, function() { hidetable(); } ],
857                                                 [ 13000, function() { display_group_parsed(filter_teams_by_group(teams, groups, 'Group B'), games, 'Group B'); } ],
858                                                 [ 2000, function() { hidetable(); } ],
859                                                 [ 13000, function() { display_group_parsed(filter_teams_by_group(teams, groups, 'Group C'), games, 'Group C'); } ],
860                                                 [ 2000, function() { hidetable(); } ],
861                                                 // We don't show the playoff groups, since we don't even know whether they have data.
862                                         ];
863                                         let num_pages = find_num_pages(games);
864                                         for (let page = 0; page < num_pages; ++page) {
865                                                 series.push([ 13000, function() { display_stream_schedule_parsed(teams, games, page); } ]);
866                                                 series.push([ 2000, function() { hidetable(); } ]);
867                                         }
868
869                                         do_series(series);
870                                 });
871                         });
872                 });
873         });
874 };
875
876 function stopcarousel()
877 {
878         if (carousel_timeout !== null) {
879                 hidetable();
880                 clearTimeout(carousel_timeout);
881                 carousel_timeout = null;
882         }
883 };
884
885 function hidescorebug()
886 {
887         document.getElementById('entire-bug').style.display = 'none';
888 }
889
890 function showscorebug()
891 {
892         document.getElementById('entire-bug').style.display = null;
893 }
894
895 function showmatch2()
896 {
897         let css = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-fill-mode: both;";
898         document.getElementById('scorebug2').style = css;
899         document.getElementById('clockbug2').style = css;
900 }
901
902 function hidematch2()
903 {
904         let css = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-fill-mode: both;";
905         document.getElementById('scorebug2').style = css;
906         document.getElementById('clockbug2').style = css;
907 }
908
909 function showmatch3()
910 {
911         let css = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-fill-mode: both;";
912         document.getElementById('scorebug3').style = css;
913         document.getElementById('clockbug3').style = css;
914 }
915
916 function hidematch3()
917 {
918         let css = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-fill-mode: both;";
919         document.getElementById('scorebug3').style = css;
920         document.getElementById('clockbug3').style = css;
921 }