]> git.sesse.net Git - ultimatescore/blob - carousel.js
1e7d58851a064e449182c5bd09a70ae9c7b4d902
[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                         "ngames": 0,
373                         "nplayed": 0,
374                         "gd": 0,
375                         "pts": 0,
376                         "goals": 0
377                 });
378         }
379         return teams;
380 };
381
382 function parse_games_from_spreadsheet(response, group_name, include_unplayed) {
383         let games = [];
384         let i;
385         for (i = 0; i < response.values.length; ++i) {
386                 if (response.values[i][0] === 'Results') {
387                         i += 2;
388                         break;
389                 }
390         }
391
392         for ( ; response.values[i] !== undefined && response.values[i].length >= 1; ++i) {
393                 if ((response.values[i][2] && response.values[i][3]) || include_unplayed) {
394                         let real_group_name = response.values[i][9];
395                         if (real_group_name === undefined) {
396                                 real_group_name = group_name;
397                         }
398                         games.push({
399                                 "name1": response.values[i][0],
400                                 "name2": response.values[i][1],
401                                 "score1": parseInt(response.values[i][2]),
402                                 "score2": parseInt(response.values[i][3]),
403                                 "streamday": response.values[i][7],
404                                 "streamtime": response.values[i][8].replace('.', ':'),
405                                 "group_name": real_group_name
406                         });
407                 }
408         }
409         return games;
410 };
411
412 function get_team_code(teams, str) {
413         for (const team of teams) {
414                 if (team.name === str || team.mediumname === str || team.shortname === str) {
415                         return team.shortname;
416                 }
417         }
418         return str;
419 }
420
421 function get_all_group_games(teams, groups, cb) {
422         get_sheet('Results', function(response) {
423                 let games = [];
424                 for (const region of ultimateconfig['group_match_scores']) {
425                         for (let row = region.first_row; row <= region.last_row; ++row) {
426                                 let team1 = get_team_code(teams, response.values[row - 1][region.team1_column]);
427                                 let team2 = get_team_code(teams, response.values[row - 1][region.team2_column]);
428                                 if (team1 === undefined || team2 === undefined || team1 === '' || team2 === '' || team1 === null || team2 === null) {
429                                         continue;
430                                 }
431                                 let group_name = region.group_name;
432                                 if (group_name === undefined) {
433                                         // Infer group from whatever group both teams are in.
434                                         for (const [group, teams] of Object.entries(groups)) {
435                                                 if (teams.indexOf(team1) != -1 && teams.indexOf(team2) != -1) {
436                                                         group_name = group;
437                                                         break;
438                                                 }
439                                         }
440                                 }
441                                 let game = {
442                                         "name1": team1,
443                                         "name2": team2,
444                                         "score1": parseInt(response.values[row - 1][region.team1_score_column]),
445                                         "score2": parseInt(response.values[row - 1][region.team2_score_column]),
446                                         "group_name": group_name
447                                 };
448                                 if (region.stream_time_column !== undefined) {
449                                         game["streamtime"] = response.values[row - 1][region.stream_time_column].replace('.', ':');
450                                         game["streamday"] = region.stream_day;
451                                 }
452                                 games.push(game);
453                         }
454                 }
455                 cb(games);
456         });
457 };
458
459 function apply_games_to_teams(games, teams, group_name, ignored_teams, ret_ignored_games)
460 {
461         let teams_to_idx = make_teams_to_idx(teams);
462         let ignored_teams_idx;
463         if (ignored_teams === undefined) {
464                 ignored_teams_idx = [];
465         } else {
466                 ignored_teams_idx = make_teams_to_idx(ignored_teams);
467         }
468         for (let i = 0; i < teams.length; ++i) {
469                 teams[i].nplayed = 0;
470                 teams[i].goals = 0;
471                 teams[i].gd = 0;
472                 teams[i].pts = 0;
473         }
474         for (let i = 0; i < games.length; ++i) {
475                 if (games[i].group_name !== group_name) {
476                         continue;
477                 }
478                 let idx1 = teams_to_idx[games[i].name1];
479                 let idx2 = teams_to_idx[games[i].name2];
480                 if (games[i].score1 === undefined || games[i].score2 === undefined ||
481                     isNaN(games[i].score1) || isNaN(games[i].score2) ||
482                     idx1 === undefined || idx2 === undefined ||
483                     games[i].score1 == games[i].score2) {
484                         continue;
485                 }
486
487                 let ignored_idx1 = ignored_teams_idx[games[i].name1];
488                 let ignored_idx2 = ignored_teams_idx[games[i].name2];
489                 if (ignored_idx1 !== undefined || ignored_idx2 !== undefined) {
490                         if (ret_ignored_games !== undefined) {
491                                 // Figure out whether the fifth we're ignoring was only picked out arbitrarily
492                                 // (ie., there's a tie for 5th); if so, mark it as such.
493                                 let arbitrary = false;
494                                 if (ignored_idx1 !== undefined && ignored_teams[ignored_idx1].rank < 5) {
495                                         arbitrary = true;
496                                 } else if (ignored_idx2 !== undefined && ignored_teams[ignored_idx2].rank < 5) {
497                                         arbitrary = true;
498                                 }
499                                 ret_ignored_games.push([teams[idx1].shortname, teams[idx2].shortname, arbitrary]);
500                         }
501                         continue;
502                 }
503                 ++teams[idx1].nplayed;
504                 ++teams[idx2].nplayed;
505                 teams[idx1].goals += games[i].score1;
506                 teams[idx2].goals += games[i].score2;
507                 teams[idx1].gd += games[i].score1;
508                 teams[idx2].gd += games[i].score2;
509                 teams[idx1].gd -= games[i].score2;
510                 teams[idx2].gd -= games[i].score1;
511                 if (games[i].score1 > games[i].score2) {
512                         teams[idx1].pts += 2;
513                 } else {
514                         teams[idx2].pts += 2;
515                 }
516         }
517 }
518
519 // So that we can just have one team list, and let membership be defined by games.
520 function filter_teams(teams, response)
521 {
522         let teams_to_idx = make_teams_to_idx(teams);
523         let games = parse_games_from_spreadsheet(response, 'irrelevant group name', true);
524         for (let i = 0; i < games.length; ++i) {
525                 let idx1 = teams_to_idx[games[i].name1];
526                 let idx2 = teams_to_idx[games[i].name2];
527                 if (idx1 !== undefined) {
528                         ++teams[idx1].ngames;  // FIXME: shouldn't nplayed be just as good?
529                 }
530                 if (idx2 !== undefined) {
531                         ++teams[idx2].ngames;
532                 }
533         }
534         return teams.filter(function(team) { return team.ngames > 0; });
535 }
536
537 // So that we can just have one team list, and let membership be defined by the group list.
538 function filter_teams_by_group(teams, groups, group)
539 {
540         return teams.filter(function(team) {
541                 return groups[group].indexOf(team.shortname) != -1;
542         });
543 }
544
545 function display_group_parsed(teams, games, group_name)
546 {
547         document.getElementById('entire-bug').style.display = 'none';
548
549         apply_games_to_teams(games, teams, group_name);
550         let tiebreakers = [];
551         teams = rank(games, teams, 1, tiebreakers);
552
553         let carousel = document.getElementById('carousel');
554         clear_carousel(carousel);
555
556         addheading(carousel, 5, "Current standings, " + ultimateconfig['tournament_title'] + "<br />" + group_name);
557         let tr = document.createElement("tr");
558         tr.className = "subfooter";
559         addth(tr, "rank", "");
560         addth(tr, "team", "");
561         addth(tr, "nplayed", "P");
562         addth(tr, "gd", "GD");
563         addth(tr, "pts", "Pts");
564         carousel.appendChild(tr);
565
566         let row_num = 2;
567         for (let i = 0; i < teams.length; ++i) {
568                 let tr = document.createElement("tr");
569
570                 addth(tr, "rank", teams[i].rank);
571                 addtd(tr, "team", teams[i].name);
572                 addtd(tr, "nplayed", teams[i].nplayed);
573                 addtd(tr, "gd", teams[i].gd.toString().replace(/-/, '−'));
574                 addtd(tr, "pts", teams[i].pts);
575
576                 carousel.appendChild(tr);
577         }
578
579         if (tiebreakers.length > 0) {
580                 let tie_tr = document.createElement("tr");
581                 tie_tr.className = "footer";
582                 let td = document.createElement("td");
583                 td.appendChild(document.createTextNode("Tiebreaks applied: " + tiebreakers.join(', ')));
584                 td.setAttribute("colspan", "5");
585                 tie_tr.appendChild(td);
586                 carousel.appendChild(tie_tr);
587         }
588
589         let footer_tr = document.createElement("tr");
590         footer_tr.className = "footer";
591         let td = document.createElement("td");
592         td.appendChild(document.createTextNode(ultimateconfig['tournament_footer']));
593         td.setAttribute("colspan", "5");
594         footer_tr.appendChild(td);
595         carousel.appendChild(footer_tr);
596
597         fade_in_rows(carousel);
598
599         carousel.style.display = 'table';
600 };
601
602 function fade_in_rows(table)
603 {
604         let trs = table.getElementsByTagName("tr");
605         for (let i = 1; i < trs.length; ++i) {  // The header already has its own fade-in.
606                 if (trs[i].className === "footer") {
607                         trs[i].style = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-delay: " + (0.25 * i) + "s; -webkit-animation-fill-mode: both;";
608                 } else {
609                         trs[i].style = "-webkit-animation: fade-in 2.0s ease; -webkit-animation-delay: " + (0.25 * i) + "s; -webkit-animation-fill-mode: both;";
610                 }
611         }
612 };
613
614 function fade_out_rows(table)
615 {
616         let trs = table.getElementsByTagName("tr");
617         for (let i = 0; i < trs.length; ++i) {
618                 if (trs[i].className === "footer") {
619                         trs[i].style = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-delay: " + (0.125 * i) + "s; -webkit-animation-fill-mode: both;";
620                 } else {
621                         trs[i].style = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-delay: " + (0.125 * i) + "s; -webkit-animation-fill-mode: both;";
622                 }
623         }
624 };
625
626 function clear_carousel(table)
627 {
628         while (table.childNodes.length > 0) {
629                 table.removeChild(table.firstChild);
630         }
631 };
632
633 // Stream schedule
634 let max_list_len = 7;
635
636 function sort_game_list(games) {
637         games = games.filter(function(game) { return game.streamtime !== undefined && game.streamtime.match(/[0-9]+:[0-9]+/) != null; });
638         games.sort(function(a, b) {
639                 if (a.streamday !== b.streamday) {
640                         return a.streamday - b.streamday;
641                 }
642
643                 let m1 = a.streamtime.match(/([0-9]+):([0-9]+)/);
644                 let m2 = b.streamtime.match(/([0-9]+):([0-9]+)/);
645                 return (m1[1] * 60 + m1[2]) - (m2[1] * 60 + m2[2]);
646         });
647         return games;
648 }
649
650 function find_game_start_idx(games) {
651         // Pick out a reasonable place to start the list. We'll show the last
652         // completed match and start from there.
653         let start_idx = games.length - 1;
654         for (let i = 0; i < games.length; ++i) {
655                 if (isNaN(games[i].score1) || isNaN(games[i].score2) &&
656                     games[i].score1 === games[i].score2) {
657                         start_idx = i;
658                         break;
659                 }
660         }
661         if (start_idx > 0) start_idx--;
662         if (games.length >= max_list_len) {
663                 start_idx = Math.min(start_idx, games.length - max_list_len);
664         }
665         return start_idx;
666 }
667
668 function find_num_pages(games) {
669         games = sort_game_list(games);
670         let start_idx = find_game_start_idx(games);
671         return Math.ceil((games.length - start_idx) / max_list_len);
672 }
673
674 function get_mediumname(name, teams, teams_to_idx)
675 {
676         if (teams_to_idx[name] === undefined) {
677                 return name.replace(/^W /, 'Winner ').replace(/^L /, 'Loser ');
678         } else {
679                 return teams[teams_to_idx[name]].mediumname;
680         }
681 }
682
683 function display_stream_schedule_parsed(teams, games, page) {
684         document.getElementById('entire-bug').style.display = 'none';
685
686         games = sort_game_list(games);
687         let start_idx = find_game_start_idx(games);
688
689         start_idx += page * max_list_len;
690         if (start_idx >= games.length) {
691                 // Error.
692                 return;
693         }
694
695         let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
696         let shortdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
697         let today = days[(new Date).getDay()];
698
699         let covered_days = [];
700         let row_num = 0;
701         for (let i = start_idx; i < games.length && row_num++ < max_list_len; ++i) {
702                 if (i == start_idx || games[i].streamday != games[i - 1].streamday) {
703                         covered_days.push(days[games[i].streamday]);
704                 }
705         }
706         
707         let carousel = document.getElementById('carousel');
708         clear_carousel(carousel);
709         addheading(carousel, 3, "Stream schedule, " + ultimateconfig['tournament_title'] + "<br />" + covered_days.join('/') + " (all times CET)");
710
711         let teams_to_idx = make_teams_to_idx(teams);
712         row_num = 0;
713         for (let i = start_idx; i < games.length && row_num < max_list_len; ++i) {
714                 let tr = document.createElement("tr");
715
716                 let name1 = get_mediumname(games[i].name1, teams, teams_to_idx);
717                 let name2 = get_mediumname(games[i].name2, teams, teams_to_idx);
718
719                 addtd(tr, "matchup", name1 + "–" + name2);
720                 addtd(tr, "group", games[i].group_name);
721
722                 if (!isNaN(games[i].score1) && !isNaN(games[i].score2) &&
723                     games[i].score1 !== games[i].score2) {
724                         addtd(tr, "streamtime", games[i].score1 + "–" + games[i].score2);
725                 } else {
726                         let streamtime = games[i].streamtime;
727                         let streamday = days[games[i].streamday];
728                         if (streamday !== today) {
729                                 streamtime = shortdays[games[i].streamday] + " " + streamtime;
730                         }
731                         addth(tr, "streamtime", streamtime);
732                 }
733
734                 row_num++;
735                 carousel.appendChild(tr);
736         }
737
738         fade_in_rows(carousel);
739
740         carousel.style.display = 'table';
741 };
742
743 function get_sheet(sheet_name, cb)
744 {
745         let req = new XMLHttpRequest();
746         req.onload = function(e) {
747                 cb(JSON.parse(req.responseText));
748         };
749         req.open('GET', 'https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values/\'' + sheet_name + '\'!A1:Z50?key=' + ultimateconfig['api_key']);
750         req.send();
751 }
752
753 function get_group(group_name, cb)
754 {
755         get_sheet(group_name, function(response) {
756                 cb(response, group_name);
757         });
758 }
759
760 function get_teams(cb)
761 {
762         get_sheet('Teams', function(response) {
763                 cb(parse_teams_from_spreadsheet(response));
764         });
765 }
766
767 function get_groups(cb)
768 {
769         get_sheet('Groups', function(response) {
770                 let groups = {};
771                 for (let i = 1; i < response.values.length && response.values[i].length >= 1; ++i) {
772                         let team = response.values[i][0];
773                         let group = response.values[i][1];
774                         if (groups[group] === undefined) {
775                                 groups[group] = [];
776                         }
777                         groups[group].push(team);
778                 }
779                 cb(groups);
780         });
781 }
782
783 function showgroup(group_name)
784 {
785         get_teams(function(teams) {
786                 get_groups(function(groups) {
787                         get_all_group_games(teams, groups, function(games) {
788                                 teams = filter_teams_by_group(teams, groups, group_name);
789                                 display_group_parsed(teams, games, group_name);
790                                 publish_group_rank(response, group_name);  // Update the spreadsheet in the background.
791                         });
792                 });
793         });
794 }
795
796 function showgroup_from_state()
797 {
798         showgroup(state['group_name']);
799 }
800
801 let carousel_timeout = null;
802
803 function hidetable()
804 {
805         fade_out_rows(document.getElementById('carousel'));
806 };
807
808 function showschedule(page)
809 {
810         get_teams(function(teams) {
811                 get_groups(function(groups) {
812                         get_all_group_games(teams, groups, function(games) {
813                                 get_all_playoff_games(teams, groups, games, function(playoff_games) {
814                                         games = games.concat(playoff_games);
815                                         games = games.filter(function(game) { return game.streamday !== undefined; });
816                                         display_stream_schedule_parsed(teams, games, 0);
817                                 });
818                         });
819                 });
820         });
821 };
822
823 function do_series(series)
824 {
825         do_series_internal(series, 0);
826 };
827
828 function do_series_internal(series, idx)
829 {
830         (series[idx][1])();
831         if (idx + 1 < series.length) {
832                 carousel_timeout = setTimeout(function() { do_series_internal(series, idx + 1); }, series[idx][0]);
833         }
834 };
835
836 function showcarousel()
837 {
838         let groups_to_get = [
839                 'Group A',
840                 'Group B',
841                 'Group C',
842                 'Playoffs',
843                 'Playoffs 9th–11th',
844                 'Playoffs 12th–14th'
845         ];
846         get_teams(function(teams) {
847                 get_groups(function(groups) {
848                         get_all_group_games(teams, groups, function(games) {
849                                 get_all_playoff_games(teams, groups, games, function(playoff_games) {
850                                         games = games.concat(playoff_games);
851                                         games = games.filter(function(game) { return game.streamday !== undefined; });
852
853                                         let series = [
854                                                 [ 13000, function() { display_group_parsed(filter_teams_by_group(teams, groups, 'Group A'), games, 'Group A'); } ],
855                                                 [ 2000, function() { hidetable(); } ],
856                                                 [ 13000, function() { display_group_parsed(filter_teams_by_group(teams, groups, 'Group B'), games, 'Group B'); } ],
857                                                 [ 2000, function() { hidetable(); } ],
858                                                 [ 13000, function() { display_group_parsed(filter_teams_by_group(teams, groups, 'Group C'), games, 'Group C'); } ],
859                                                 [ 2000, function() { hidetable(); } ],
860                                                 // We don't show the playoff groups, since we don't even know whether they have data.
861                                         ];
862                                         let num_pages = find_num_pages(games);
863                                         for (let page = 0; page < num_pages; ++page) {
864                                                 series.push([ 13000, function() { display_stream_schedule_parsed(teams, games, page); } ]);
865                                                 series.push([ 2000, function() { hidetable(); } ]);
866                                         }
867
868                                         do_series(series);
869                                 });
870                         });
871                 });
872         });
873 };
874
875 function stopcarousel()
876 {
877         if (carousel_timeout !== null) {
878                 hidetable();
879                 clearTimeout(carousel_timeout);
880                 carousel_timeout = null;
881         }
882 };
883
884 function hidescorebug()
885 {
886         document.getElementById('entire-bug').style.display = 'none';
887 }
888
889 function showscorebug()
890 {
891         document.getElementById('entire-bug').style.display = null;
892 }
893
894 function showmatch2()
895 {
896         let css = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-fill-mode: both;";
897         document.getElementById('scorebug2').style = css;
898         document.getElementById('clockbug2').style = css;
899 }
900
901 function hidematch2()
902 {
903         let css = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-fill-mode: both;";
904         document.getElementById('scorebug2').style = css;
905         document.getElementById('clockbug2').style = css;
906 }
907
908 function showmatch3()
909 {
910         let css = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-fill-mode: both;";
911         document.getElementById('scorebug3').style = css;
912         document.getElementById('clockbug3').style = css;
913 }
914
915 function hidematch3()
916 {
917         let css = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-fill-mode: both;";
918         document.getElementById('scorebug3').style = css;
919         document.getElementById('clockbug3').style = css;
920 }