]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Add some team-wide touches stats.
[pkanalytics] / ultimate.js
1 'use strict';
2
3 // No frameworks, no compilers, no npm, just JavaScript. :-)
4
5 let global_json;
6 let global_filters = {};
7 let next_filterset_id = 2;  // Arbitrary IDs are fine as long as they never collide.
8
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12    .then(response => response.json())
13    .then(response => { global_json = response; process_matches(global_json, global_filters); });
14
15 function format_time(t)
16 {
17         const ms = t % 1000 + '';
18         t = Math.floor(t / 1000);
19         const sec = t % 60 + '';
20         t = Math.floor(t / 60);
21         const min = t % 60 + '';
22         const hour = Math.floor(t / 60) + '';
23         return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
24 }
25
26 function attribute_player_time(player, to, from, offense) {
27         let delta_time;
28         if (player.on_field_since > from) {
29                 // Player came in while play happened (without a stoppage!?).
30                 delta_time = to - player.on_field_since;
31         } else {
32                 delta_time = to - from;
33         }
34         player.playing_time_ms += delta_time;
35         if (offense === true) {
36                 player.offensive_playing_time_ms += delta_time;
37         } else if (offense === false) {
38                 player.defensive_playing_time_ms += delta_time;
39         }
40 }
41
42 function take_off_field(player, t, live_since, offense, keep) {
43         if (keep) {
44                 if (live_since === null) {
45                         // Play isn't live, so nothing to do.
46                 } else {
47                         attribute_player_time(player, t, live_since, offense);
48                 }
49                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
50                         player.field_time_ms += t - player.on_field_since;
51                 }
52         }
53         player.on_field_since = null;
54 }
55
56 function add_cell(tr, element_type, text) {
57         let element = document.createElement(element_type);
58         element.textContent = text;
59         tr.appendChild(element);
60         return element;
61 }
62
63 function add_th(tr, text, colspan) {
64         let element = document.createElement('th');
65         let link = document.createElement('a');
66         link.style.cursor = 'pointer';
67         link.addEventListener('click', (e) => {
68                 sort_by(element);
69                 process_matches(global_json, global_filters);
70         });
71         link.textContent = text;
72         element.appendChild(link);
73         tr.appendChild(element);
74
75         if (colspan > 0) {
76                 element.setAttribute('colspan', colspan);
77         } else {
78                 element.setAttribute('colspan', '3');
79         }
80         return element;
81 }
82
83 function add_3cell(tr, text, cls) {
84         let p1 = add_cell(tr, 'td', '');
85         let element = add_cell(tr, 'td', text);
86         let p2 = add_cell(tr, 'td', '');
87
88         p1.classList.add('pad');
89         p2.classList.add('pad');
90         if (cls === undefined) {
91                 element.classList.add('num');
92         } else {
93                 element.classList.add(cls);
94         }
95         return element;
96 }
97
98 function add_3cell_with_filler_ci(tr, text, cls) {
99         let element = add_3cell(tr, text, cls);
100
101         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102         svg.classList.add('fillerci');
103         svg.setAttribute('width', ci_width);
104         svg.setAttribute('height', ci_height);
105         element.appendChild(svg);
106
107         return element;
108 }
109
110 function add_3cell_ci(tr, ci) {
111         if (isNaN(ci.val)) {
112                 add_3cell_with_filler_ci(tr, 'N/A');
113                 return;
114         }
115
116         let text;
117         if (ci.format === 'percentage') {
118                 text = (100 * ci.val).toFixed(0) + '%';
119         } else {
120                 text = ci.val.toFixed(2);
121         }
122         let element = add_3cell(tr, text);
123         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
124
125         // Container.
126         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
127         if (ci.inverted === true) {
128                 svg.classList.add('invertedci');
129         } else {
130                 svg.classList.add('ci');
131         }
132         svg.setAttribute('width', ci_width);
133         svg.setAttribute('height', ci_height);
134
135         // The good (green) and red (bad) ranges.
136         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
137         s0.classList.add('range');
138         s0.classList.add('s0');
139         s0.setAttribute('width', to_x(ci.desired));
140         s0.setAttribute('height', ci_height);
141         s0.setAttribute('x', '0');
142
143         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
144         s1.classList.add('range');
145         s1.classList.add('s1');
146         s1.setAttribute('width', ci_width - to_x(ci.desired));
147         s1.setAttribute('height', ci_height);
148         s1.setAttribute('x', to_x(ci.desired));
149
150         // Confidence bar.
151         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
152         bar.classList.add('bar');
153         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
154         bar.setAttribute('height', ci_height / 3);
155         bar.setAttribute('x', to_x(ci.lower_ci));
156         bar.setAttribute('y', ci_height / 3);
157
158         // Marker line for average.
159         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
160         marker.classList.add('marker');
161         marker.setAttribute('x1', to_x(ci.val));
162         marker.setAttribute('x2', to_x(ci.val));
163         marker.setAttribute('y1', ci_height / 6);
164         marker.setAttribute('y2', ci_height * 5 / 6);
165
166         svg.appendChild(s0);
167         svg.appendChild(s1);
168         svg.appendChild(bar);
169         svg.appendChild(marker);
170
171         element.appendChild(svg);
172 }
173
174 function calc_stats(json, filters) {
175         let players = {};
176         for (const player of json['players']) {
177                 players[player['player_id']] = {
178                         'name': player['name'],
179                         'gender': player['gender'],
180                         'number': player['number'],
181
182                         'goals': 0,
183                         'assists': 0,
184                         'hockey_assists': 0,
185                         'catches': 0,
186                         'touches': 0,
187                         'num_throws': 0,
188                         'throwaways': 0,
189                         'drops': 0,
190                         'was_ds': 0,
191                         'stallouts': 0,
192
193                         'defenses': 0,
194                         'callahans': 0,
195                         'points_played': 0,
196                         'playing_time_ms': 0,
197                         'offensive_playing_time_ms': 0,
198                         'defensive_playing_time_ms': 0,
199                         'field_time_ms': 0,
200
201                         // For efficiency.
202                         'offensive_points_completed': 0,
203                         'offensive_points_won': 0,
204                         'defensive_points_completed': 0,
205                         'defensive_points_won': 0,
206
207                         'offensive_soft_plus': 0,
208                         'offensive_soft_minus': 0,
209                         'defensive_soft_plus': 0,
210                         'defensive_soft_minus': 0,
211
212                         'pulls': 0,
213                         'pull_times': [],
214                         'oob_pulls': 0,
215
216                         // Internal.
217                         'last_point_seen': null,
218                         'on_field_since': null,
219                 };
220         }
221
222         // Globals.
223         players['globals'] = {
224                 'points_played': 0,
225                 'playing_time_ms': 0,
226                 'offensive_playing_time_ms': 0,
227                 'defensive_playing_time_ms': 0,
228                 'field_time_ms': 0,
229
230                 'offensive_points_completed': 0,
231                 'offensive_points_won': 0,
232                 'clean_holds': 0,
233
234                 'defensive_points_completed': 0,
235                 'defensive_points_won': 0,
236                 'clean_breaks': 0,
237
238                 'turnovers_won': 0,
239                 'turnovers_lost': 0,
240                 'their_clean_holds': 0,
241                 'their_clean_breaks': 0,
242
243                 'touches_for_turnover': 0,
244                 'touches_for_goal': 0,
245         };
246         let globals = players['globals'];
247
248         for (const match of json['matches']) {
249                 if (!keep_match(match['match_id'], filters)) {
250                         continue;
251                 }
252
253                 let our_score = 0;
254                 let their_score = 0;
255                 let between_points = true;
256                 let handler = null;
257                 let handler_got_by_interception = false;  // Only relevant if handler !== null.
258                 let prev_handler = null;
259                 let live_since = null;
260                 let offense = null;  // True/false/null (unknown).
261                 let puller = null;
262                 let pull_started = null;
263                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
264                 let point_num = 0;
265                 let game_started = null;
266                 let last_goal = null;
267                 let current_predominant_gender = null;
268                 let current_num_players_on_field = null;
269
270                 let we_lost_disc = false;
271                 let they_lost_disc = false;
272                 let touches_this_possession = 0;
273
274                 // The last used formations of the given kind, if any; they may be reused
275                 // when the point starts, if nothing else is set.
276                 let last_offensive_formation = null;
277                 let last_defensive_formation = null;
278
279                 // Formations we've set, but haven't really had the chance to use yet
280                 // (e.g., we get a “use zone defense” event while we're still on offense).
281                 let pending_offensive_formation = null;
282                 let pending_defensive_formation = null;
283
284                 // Formations that we have played at least once this point, after all
285                 // heuristics and similar.
286                 let formations_used_this_point = new Set();
287
288                 for (const [q,p] of Object.entries(players)) {
289                         p.on_field_since = null;
290                         p.last_point_seen = null;
291                 }
292                 for (const e of match['events']) {
293                         let t = e['t'];
294                         let type = e['type'];
295                         let p = players[e['player']];
296
297                         // Sub management
298                         let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
299                         if (type === 'in' && p.on_field_since === null) {
300                                 p.on_field_since = t;
301                                 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
302                                         // A player needed for the filters went onto the field,
303                                         // so pretend people walked on right now (to start their
304                                         // counting time).
305                                         for (const [q,p2] of Object.entries(players)) {
306                                                 if (p2.on_field_since !== null) {
307                                                         p2.on_field_since = t;
308                                                 }
309                                         }
310                                 }
311                         } else if (type === 'out') {
312                                 take_off_field(p, t, live_since, offense, keep);
313                                 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
314                                         // A player needed for the filters went off the field,
315                                         // so we need to attribute time for all the others.
316                                         // Pretend they walked off and then immediately on again.
317                                         //
318                                         // TODO: We also need to take care of this to get the globals right.
319                                         for (const [q,p2] of Object.entries(players)) {
320                                                 if (p2.on_field_since !== null) {
321                                                         take_off_field(p2, t, live_since, offense, keep);
322                                                         p2.on_field_since = t;
323                                                 }
324                                         }
325                                 }
326                         }
327
328                         keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);  // Recompute after in/out.
329
330                         if (match['gender_rule_a']) {
331                                 if (type === 'restart' && !between_points) {
332                                         let predominant_gender = find_predominant_gender(players);
333                                         let num_players_on_field = find_num_players_on_field(players);
334                                         if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
335                                                 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
336                                         }
337                                         if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
338                                                 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed number of players on field from ' + current_num_players_on_field + ' to ' + num_players_on_field);
339                                         }
340                                         current_predominant_gender = predominant_gender;
341                                         current_num_players_on_field = num_players_on_field;
342                                 } else if (type === 'pull' || type === 'their_pull') {
343                                         let predominant_gender = find_predominant_gender(players);
344                                         let num_players_on_field = find_num_players_on_field(players);
345                                         let changed = (predominant_gender !== current_predominant_gender);
346                                         if (point_num !== 0) {
347                                                 let should_change = (point_num % 4 == 1 || point_num % 4 == 3);  // ABBA changes on 1 and 3.
348                                                 if (changed && !should_change) {
349                                                         console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
350                                                 } else if (!changed && should_change) {
351                                                         console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
352                                                 }
353                                                 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
354                                                         console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
355                                                 }
356                                         }
357                                         current_predominant_gender = predominant_gender;
358                                         current_num_players_on_field = num_players_on_field;
359                                 }
360                         }
361                         if (match['gender_pull_rule']) {
362                                 if (type === 'pull') {
363                                         if (current_predominant_gender !== null &&
364                                             p.gender !== current_predominant_gender) {
365                                                 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
366                                         }
367                                 }
368                         }
369
370                         // Liveness management
371                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
372                                 live_since = t;
373                                 between_points = false;
374                         } else if (type === 'catch' && last_pull_was_ours === null) {
375                                 // Someone forgot to add the pull, so we'll need to wing it.
376                                 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
377                                 live_since = t;
378                                 last_pull_was_ours = !offense;
379                                 between_points = false;
380                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
381                                 if (type === 'goal') {
382                                         if (keep) ++p.touches;
383                                         ++touches_this_possession;
384                                 }
385                                 for (const [q,p] of Object.entries(players)) {
386                                         if (p.on_field_since === null) {
387                                                 continue;
388                                         }
389                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
390                                                 if (keep) {
391                                                         // In case the player did nothing this point,
392                                                         // not even subbing in.
393                                                         p.last_point_seen = point_num;
394                                                         ++p.points_played;
395                                                 }
396                                         }
397                                         if (keep) attribute_player_time(p, t, live_since, offense);
398
399                                         if (type !== 'stoppage') {
400                                                 if (keep) {
401                                                         if (last_pull_was_ours === true) {  // D point.
402                                                                 ++p.defensive_points_completed;
403                                                                 if (type === 'goal') {
404                                                                         ++p.defensive_points_won;
405                                                                 }
406                                                         } else if (last_pull_was_ours === false) {  // O point.
407                                                                 ++p.offensive_points_completed;
408                                                                 if (type === 'goal') {
409                                                                         ++p.offensive_points_won;
410                                                                 }
411                                                         }
412                                                 }
413                                         }
414                                 }
415
416                                 if (keep) {
417                                         if (type !== 'stoppage') {
418                                                 // Update globals.
419                                                 ++globals.points_played;
420                                                 if (last_pull_was_ours === true) {  // D point.
421                                                         ++globals.defensive_points_completed;
422                                                         if (type === 'goal') {
423                                                                 ++globals.defensive_points_won;
424                                                         }
425                                                 } else if (last_pull_was_ours === false) {  // O point.
426                                                         ++globals.offensive_points_completed;
427                                                         if (type === 'goal') {
428                                                                 ++globals.offensive_points_won;
429                                                         }
430                                                 }
431                                         }
432                                         if (live_since !== null) {
433                                                 globals.playing_time_ms += t - live_since;
434                                                 if (offense === true) {
435                                                         globals.offensive_playing_time_ms += t - live_since;
436                                                 } else if (offense === false) {
437                                                         globals.defensive_playing_time_ms += t - live_since;
438                                                 }
439                                         }
440                                 }
441
442                                 live_since = null;
443                         }
444
445                         // Score management
446                         if (type === 'goal') {
447                                 ++our_score;
448                         } else if (type === 'their_goal') {
449                                 ++their_score;
450                         }
451
452                         // Point count management
453                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
454                                 if (keep) {
455                                         p.last_point_seen = point_num;
456                                         ++p.points_played;
457                                 }
458                         }
459                         if (type === 'goal' || type === 'their_goal') {
460                                 ++point_num;
461                                 last_goal = t;
462                         }
463                         if (type !== 'out' && game_started === null) {
464                                 game_started = t;
465                         }
466
467                         // Pull management
468                         if (type === 'pull') {
469                                 puller = e['player'];
470                                 pull_started = t;
471                                 if (keep) ++p.pulls;
472                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
473                                 // No effect on pull.
474                         } else if (type === 'pull_landed' && puller !== null) {
475                                 if (keep) players[puller].pull_times.push(t - pull_started);
476                         } else if (type === 'pull_oob' && puller !== null) {
477                                 if (keep) ++players[puller].oob_pulls;
478                         } else {
479                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
480                                 puller = pull_started = null;
481                         }
482
483                         // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
484                         if (keep) {
485                                 if (type === 'goal' && !we_lost_disc) {
486                                         if (last_pull_was_ours === false) {  // O point.
487                                                 ++globals.clean_holds;
488                                         } else if (last_pull_was_ours === true) {
489                                                 ++globals.clean_breaks;
490                                         }
491                                 } else if (type === 'their_goal' && !they_lost_disc) {
492                                         if (last_pull_was_ours === true) {  // O point for them.
493                                                 ++globals.their_clean_holds;
494                                         } else if (last_pull_was_ours === false) {
495                                                 ++globals.their_clean_breaks;
496                                         }
497                                 }
498                         }
499
500                         // Offense/defense management
501                         let last_offense = offense;
502                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
503                                 offense = false;
504                                 we_lost_disc = true;
505                                 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
506                                         ++globals.turnovers_lost;
507                                         globals.touches_for_turnover += touches_this_possession;
508                                 } else if (keep && type === 'goal') {
509                                         globals.touches_for_goal += touches_this_possession;
510                                 }
511                                 touches_this_possession = 0;
512                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
513                                 offense = true;
514                                 they_lost_disc = true;
515                                 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
516                                         ++globals.turnovers_won;
517                                 }
518                                 touches_this_possession = 0;
519                         }
520                         if (type === 'goal' || type === 'their_goal') {
521                                 between_points = true;
522                                 we_lost_disc = false;
523                                 they_lost_disc = false;
524                                 touches_this_possession = 0;
525                         }
526                         if (last_offense !== offense && live_since !== null) {
527                                 // Switched offense/defense status, so attribute this drive as needed,
528                                 // and update live_since to take that into account.
529                                 if (keep) {
530                                         for (const [q,p] of Object.entries(players)) {
531                                                 if (p.on_field_since === null) {
532                                                         continue;
533                                                 }
534                                                 attribute_player_time(p, t, live_since, last_offense);
535                                         }
536                                         globals.playing_time_ms += t - live_since;
537                                         if (offense === true) {
538                                                 globals.offensive_playing_time_ms += t - live_since;
539                                         } else if (offense === false) {
540                                                 globals.defensive_playing_time_ms += t - live_since;
541                                         }
542                                 }
543                                 live_since = t;
544                         }
545
546                         if (type === 'pull') {
547                                 last_pull_was_ours = true;
548                         } else if (type === 'their_pull') {
549                                 last_pull_was_ours = false;
550                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
551                                 // set_offense could either be “changed to offense for some reason
552                                 // we could not express”, or “we started in the middle of a point,
553                                 // and we are offense”. We assume that if we already saw the pull,
554                                 // it's the former, and if not, it's the latter; thus, the === null
555                                 // test above. (It could also be “we set offense before the pull,
556                                 // so that we get the right button enabled”, in which case it will
557                                 // be overwritten by the next pull/their_pull event anyway.)
558                                 last_pull_was_ours = false;
559                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
560                                 // Similar.
561                                 last_pull_was_ours = true;
562                         } else if (type === 'goal' || type === 'their_goal') {
563                                 last_pull_was_ours = null;
564                         }
565
566                         // Formation management
567                         if (type === 'formation_offense' || type === 'formation_defense') {
568                                 let id = e.formation === null ? 0 : e.formation;
569                                 let for_offense = (type === 'formation_offense');
570                                 if (offense === for_offense) {
571                                         formations_used_this_point.add(id);
572                                 } else if (for_offense) {
573                                         pending_offensive_formation = id;
574                                 } else {
575                                         pending_defensive_formation = id;
576                                 }
577                                 if (for_offense) {
578                                         last_offensive_formation = id;
579                                 } else {
580                                         last_defensive_formation = id;
581                                 }
582                         } else if (last_offense !== offense) {
583                                 if (offense === true && pending_offensive_formation !== null) {
584                                         formations_used_this_point.add(pending_offensive_formation);
585                                         pending_offensive_formation = null;
586                                 } else if (offense === false && pending_defensive_formation !== null) {
587                                         formations_used_this_point.add(pending_defensive_formation);
588                                         pending_defensive_formation = null;
589                                 } else if (offense === true && last_defensive_formation !== null) {
590                                         if (should_reuse_last_formation(match['events'], t)) {
591                                                 formations_used_this_point.add(last_defensive_formation);
592                                         }
593                                 } else if (offense === false && last_offensive_formation !== null) {
594                                         if (should_reuse_last_formation(match['events'], t)) {
595                                                 formations_used_this_point.add(last_offensive_formation);
596                                         }
597                                 }
598                         }
599
600                         if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
601                                 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
602                         }
603                         if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
604                                 // The handler subbed out and was replaced with another handler,
605                                 // so this wasn't a pass.
606                                 handler = null;
607                         }
608
609                         // Event management
610                         if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
611                                 // Self-pass to goal after an interception; this is not a real pass,
612                                 // just how we represent a Callahan right now -- so don't
613                                 // count the throw, any assists or similar.
614                                 //
615                                 // It's an open question how we should handle a self-pass that is
616                                 // _not_ after an interception, or a self-pass that's not a goal.
617                                 // (It must mean we tipped off someone.) We'll count it as a regular one
618                                 // for the time being, although it will make hockey assists weird.
619                                 if (keep) {
620                                         ++p.goals;
621                                         ++p.callahans;
622                                 }
623                                 handler = prev_handler = null;
624                         } else if (type === 'catch' || type === 'goal') {
625                                 if (handler !== null) {
626                                         if (keep) {
627                                                 ++players[handler].num_throws;
628                                                 ++p.catches;
629                                         }
630                                 }
631
632                                 if (keep) ++p.touches;
633                                 ++touches_this_possession;
634                                 if (type === 'goal') {
635                                         if (keep) {
636                                                 if (prev_handler !== null) {
637                                                         ++players[prev_handler].hockey_assists;
638                                                 }
639                                                 if (handler !== null) {
640                                                         ++players[handler].assists;
641                                                 }
642                                                 ++p.goals;
643                                         }
644                                         handler = prev_handler = null;
645                                 } else {
646                                         // Update hold history.
647                                         prev_handler = handler;
648                                         handler = e['player'];
649                                         handler_got_by_interception = false;
650                                 }
651                         } else if (type === 'throwaway') {
652                                 if (keep) {
653                                         ++p.num_throws;
654                                         ++p.throwaways;
655                                 }
656                                 handler = prev_handler = null;
657                         } else if (type === 'drop') {
658                                 if (keep) ++p.drops;
659                                 handler = prev_handler = null;
660                         } else if (type === 'stallout') {
661                                 if (keep) ++p.stallouts;
662                                 handler = prev_handler = null;
663                         } else if (type === 'was_d') {
664                                 if (keep) ++p.was_ds;
665                                 handler = prev_handler = null;
666                         } else if (type === 'defense') {
667                                 if (keep) ++p.defenses;
668                         } else if (type === 'interception') {
669                                 if (keep) {
670                                         ++p.catches;
671                                         ++p.defenses;
672                                         ++p.touches;
673                                         ++touches_this_possession;
674                                 }
675                                 prev_handler = null;
676                                 handler = e['player'];
677                                 handler_got_by_interception = true;
678                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
679                                 if (keep) ++p[type];
680                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
681                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
682                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
683                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
684                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
685                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
686                                    type !== 'formation_offense' && type !== 'formation_defense') {
687                                 console.log(format_time(t) + ": Unknown event “" + e + "”");
688                         }
689
690                         if (type === 'goal' || type === 'their_goal') {
691                                 formations_used_this_point.clear();
692                         }
693                 }
694
695                 // Add field time for all players still left at match end.
696                 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
697                 if (keep) {
698                         for (const [q,p] of Object.entries(players)) {
699                                 if (p.on_field_since !== null && last_goal !== null) {
700                                         p.field_time_ms += last_goal - p.on_field_since;
701                                 }
702                         }
703                         if (game_started !== null && last_goal !== null) {
704                                 globals.field_time_ms += last_goal - game_started;
705                         }
706                         if (live_since !== null && last_goal !== null) {
707                                 globals.playing_time_ms += last_goal - live_since;
708                                 if (offense === true) {
709                                         globals.offensive_playing_time_ms += last_goal - live_since;
710                                 } else if (offense === false) {
711                                         globals.defensive_playing_time_ms += last_goal - live_since;
712                                 }
713                         }
714                 }
715         }
716         return players;
717 }
718
719 function process_matches(json, filtersets) {
720         let chosen_category = get_chosen_category();
721         write_main_menu(chosen_category);
722
723         let filterset_values = Object.values(filtersets);
724         if (filterset_values.length === 0) {
725                 filterset_values = [[]];
726         }
727
728         let rowsets = [];
729         for (const filter of filterset_values) {
730                 let players = calc_stats(json, filter);
731                 let rows = [];
732                 if (chosen_category === 'general') {
733                         rows = make_table_general(players);
734                 } else if (chosen_category === 'offense') {
735                         rows = make_table_offense(players);
736                 } else if (chosen_category === 'defense') {
737                         rows = make_table_defense(players);
738                 } else if (chosen_category === 'playing_time') {
739                         rows = make_table_playing_time(players);
740                 } else if (chosen_category === 'per_point') {
741                         rows = make_table_per_point(players);
742                 } else if (chosen_category === 'team_wide') {
743                         rows = make_table_team_wide(players);
744                 }
745                 rowsets.push(rows);
746         }
747
748         let merged_rows = [];
749         if (filterset_values.length > 1) {
750                 for (let i = 0; i < rowsets.length; ++i) {
751                         let marker = make_filter_marker(filterset_values[i]);
752
753                         // Make filter header.
754                         let tr = rowsets[i][0];
755                         let th = document.createElement('th');
756                         th.textContent = '';
757                         tr.insertBefore(th, tr.firstChild);
758
759                         for (let j = 1; j < rowsets[i].length; ++j) {
760                                 let tr = rowsets[i][j];
761
762                                 // Remove the name for cleanness.
763                                 if (i != 0) {
764                                         tr.firstChild.nextSibling.textContent = '';
765                                 }
766
767                                 if (i != 0) {
768                                         tr.style.borderTop = '0px';
769                                 }
770                                 if (i != rowsets.length - 1) {
771                                         tr.style.borderBottom = '0px';
772                                 }
773
774                                 // Make filter marker.
775                                 let td = document.createElement('td');
776                                 td.textContent = marker;
777                                 td.classList.add('filtermarker');
778                                 tr.insertBefore(td, tr.firstChild);
779                         }
780                 }
781
782                 for (let i = 0; i < rowsets[0].length; ++i) {
783                         for (let j = 0; j < rowsets.length; ++j) {
784                                 merged_rows.push(rowsets[j][i]);
785                                 if (i === 0) break;  // Don't merge the headings.
786                         }
787                 }
788         } else {
789                 merged_rows = rowsets[0];
790         }
791         document.getElementById('stats').replaceChildren(...merged_rows);
792 }
793
794 function get_chosen_category() {
795         if (window.location.hash === '#offense') {
796                 return 'offense';
797         } else if (window.location.hash === '#defense') {
798                 return 'defense';
799         } else if (window.location.hash === '#playing_time') {
800                 return 'playing_time';
801         } else if (window.location.hash === '#per_point') {
802                 return 'per_point';
803         } else if (window.location.hash === '#team_wide') {
804                 return 'team_wide';
805         } else {
806                 return 'general';
807         }
808 }
809
810 function write_main_menu(chosen_category) {
811         let elems = [];
812         const categories = [
813                 ['general', 'General'],
814                 ['offense', 'Offense'],
815                 ['defense', 'Defense'],
816                 ['playing_time', 'Playing time'],
817                 ['per_point', 'Per point'],
818                 ['team_wide', 'Team-wide'],
819         ];
820         for (const [id, title] of categories) {
821                 if (chosen_category === id) {
822                         let span = document.createElement('span');
823                         span.innerText = title;
824                         elems.push(span);
825                 } else {
826                         let a = document.createElement('a');
827                         a.appendChild(document.createTextNode(title));
828                         a.setAttribute('href', '#' + id);
829                         elems.push(a);
830                 }
831         }
832
833         document.getElementById('mainmenu').replaceChildren(...elems);
834 }
835
836 // https://en.wikipedia.org/wiki/1.96#History
837 const z = 1.959964;
838
839 const ci_width = 100;
840 const ci_height = 20;
841
842 function make_binomial_ci(val, num, z) {
843         let avg = val / num;
844
845         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
846         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
847         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
848
849         // Fix the signs so that we don't get -0.00.
850         low = Math.max(low, 0.0);
851         return {
852                 'val': avg,
853                 'lower_ci': low,
854                 'upper_ci': high,
855                 'min': 0.0,
856                 'max': 1.0,
857         };
858 }
859
860 // These can only happen once per point, but you get -1 and +1
861 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
862 // and then we can rewrite back.
863 function make_efficiency_ci(points_won, points_completed, z)
864 {
865         let ci = make_binomial_ci(points_won, points_completed, z);
866         ci.val = 2.0 * ci.val - 1.0;
867         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
868         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
869         ci.min = -1.0;
870         ci.max = 1.0;
871         ci.desired = 0.0;  // Desired = positive efficiency.
872         return ci;
873 }
874
875 // Ds, throwaways and drops can happen multiple times per point,
876 // so they are Poisson distributed.
877 //
878 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
879 // since our rates are definitely below 2 per point).
880 //
881 // FIXME: z is ignored.
882 function make_poisson_ci(val, num, z, inverted)
883 {
884         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
885         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
886
887         // Fix the signs so that we don't get -0.00.
888         low = Math.max(low, 0.0);
889
890         // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
891         let avg = val / num;
892         return {
893                 'val': avg,
894                 'lower_ci': low,
895                 'upper_ci': high,
896                 'min': 0.0,
897                 'max': 0.5,
898                 'desired': 0.05,
899                 'inverted': inverted,
900         };
901 }
902
903 // Wilson and Hilferty, again recommended for general use in the PDF above
904 // (anything from their group “G1” works).
905 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
906 function make_poisson_ci_large(val, num, z, inverted)
907 {
908         let low  = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
909         let high = (val + 1.0) * Math.pow(1.0 - 1.0 / (9.0 * (val + 1.0)) + z / (3.0 * Math.sqrt(val + 1.0)), 3.0) / num;
910
911         // Fix the signs so that we don't get -0.00.
912         low = Math.max(low, 0.0);
913
914         // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
915         // (this is used for number of touches).
916         let avg = val / num;
917         return {
918                 'val': avg,
919                 'lower_ci': low,
920                 'upper_ci': high,
921                 'min': 0.0,
922                 'max': 25.0,
923                 'desired': 0.0,
924                 'inverted': inverted,
925         };
926 }
927
928 function make_table_general(players) {
929         let rows = [];
930         {
931                 let header = document.createElement('tr');
932                 add_th(header, 'Player');
933                 add_th(header, '+/-');
934                 add_th(header, 'Soft +/-');
935                 add_th(header, 'O efficiency');
936                 add_th(header, 'D efficiency');
937                 add_th(header, 'Points played');
938                 rows.push(header);
939         }
940
941         for (const [q,p] of get_sorted_players(players)) {
942                 if (q === 'globals') continue;
943                 let row = document.createElement('tr');
944                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
945                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
946                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
947                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
948                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
949                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
950                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
951                 add_3cell_ci(row, o_efficiency);
952                 add_3cell_ci(row, d_efficiency);
953                 add_3cell(row, p.points_played);
954                 row.dataset.player = q;
955                 rows.push(row);
956         }
957
958         // Globals.
959         let globals = players['globals'];
960         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
961         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
962         let row = document.createElement('tr');
963         add_3cell(row, '');
964         add_3cell(row, '');
965         add_3cell(row, '');
966         add_3cell_ci(row, o_efficiency);
967         add_3cell_ci(row, d_efficiency);
968         add_3cell(row, globals.points_played);
969         rows.push(row);
970
971         return rows;
972 }
973
974 function make_table_team_wide(players) {
975         let globals = players['globals'];
976
977         let rows = [];
978         {
979                 let header = document.createElement('tr');
980                 add_th(header, '');
981                 add_th(header, 'Our team', 6);
982                 add_th(header, 'Opponents', 6);
983                 rows.push(header);
984         }
985
986         // Turnovers.
987         {
988                 let row = document.createElement('tr');
989                 let name = add_3cell(row, 'Turnovers generated', 'name');
990                 add_3cell(row, globals.turnovers_won);
991                 add_3cell(row, '');
992                 add_3cell(row, globals.turnovers_lost);
993                 add_3cell(row, '');
994                 rows.push(row);
995         }
996
997         // Clean holds.
998         {
999                 let row = document.createElement('tr');
1000                 let name = add_3cell(row, 'Clean holds', 'name');
1001                 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1002                 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1003                 our_clean_holds.desired = 0.3;  // Arbitrary.
1004                 our_clean_holds.format = 'percentage';
1005                 their_clean_holds.desired = 0.3;
1006                 their_clean_holds.format = 'percentage';
1007                 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1008                 add_3cell_ci(row, our_clean_holds);
1009                 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1010                 add_3cell_ci(row, their_clean_holds);
1011                 rows.push(row);
1012         }
1013
1014         // Clean breaks.
1015         {
1016                 let row = document.createElement('tr');
1017                 let name = add_3cell(row, 'Clean breaks', 'name');
1018                 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1019                 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1020                 our_clean_breaks.desired = 0.3;  // Arbitrary.
1021                 our_clean_breaks.format = 'percentage';
1022                 their_clean_breaks.desired = 0.3;
1023                 their_clean_breaks.format = 'percentage';
1024                 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1025                 add_3cell_ci(row, our_clean_breaks);
1026                 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1027                 add_3cell_ci(row, their_clean_breaks);
1028                 rows.push(row);
1029         }
1030
1031         // Touches. We only have information for our team here.
1032         {
1033                 let goals = 0;
1034                 for (const [q,p] of get_sorted_players(players)) {
1035                         if (q === 'globals') continue;
1036                         goals += p.goals;
1037                 }
1038
1039                 let row = document.createElement('tr');
1040                 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1041                 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1042                 let possessions = goals + globals.turnovers_lost;
1043                 add_3cell(row, '');
1044                 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1045                 add_3cell(row, '');
1046                 add_3cell(row, '');
1047                 rows.push(row);
1048
1049                 row = document.createElement('tr');
1050                 add_3cell(row, 'Touches per possession (goals)', 'name');
1051                 add_3cell(row, '');
1052                 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1053                 add_3cell(row, '');
1054                 add_3cell(row, '');
1055                 rows.push(row);
1056
1057                 row = document.createElement('tr');
1058                 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1059                 add_3cell(row, '');
1060                 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1061                 add_3cell(row, '');
1062                 add_3cell(row, '');
1063                 rows.push(row);
1064         }
1065
1066         return rows;
1067 }
1068
1069 function make_table_offense(players) {
1070         let rows = [];
1071         {
1072                 let header = document.createElement('tr');
1073                 add_th(header, 'Player');
1074                 add_th(header, 'Goals');
1075                 add_th(header, 'Assists');
1076                 add_th(header, 'Hockey assists');
1077                 add_th(header, 'Throws');
1078                 add_th(header, 'Throwaways');
1079                 add_th(header, '%OK');
1080                 add_th(header, 'Catches');
1081                 add_th(header, 'Drops');
1082                 add_th(header, 'D-ed');
1083                 add_th(header, '%OK');
1084                 add_th(header, 'Stalls');
1085                 add_th(header, 'Soft +/-', 6);
1086                 rows.push(header);
1087         }
1088
1089         let goals = 0;
1090         let num_throws = 0;
1091         let throwaways = 0;
1092         let catches = 0;
1093         let drops = 0;
1094         let was_ds = 0;
1095         let stallouts = 0;
1096         for (const [q,p] of get_sorted_players(players)) {
1097                 if (q === 'globals') continue;
1098                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1099                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1100
1101                 throw_ok.format = 'percentage';
1102                 catch_ok.format = 'percentage';
1103
1104                 // Desire at least 90% percentage. Fairly arbitrary.
1105                 throw_ok.desired = 0.9;
1106                 catch_ok.desired = 0.9;
1107
1108                 let row = document.createElement('tr');
1109                 add_3cell(row, p.name, 'name');  // TODO: number?
1110                 add_3cell(row, p.goals);
1111                 add_3cell(row, p.assists);
1112                 add_3cell(row, p.hockey_assists);
1113                 add_3cell(row, p.num_throws);
1114                 add_3cell(row, p.throwaways);
1115                 add_3cell_ci(row, throw_ok);
1116                 add_3cell(row, p.catches);
1117                 add_3cell(row, p.drops);
1118                 add_3cell(row, p.was_ds);
1119                 add_3cell_ci(row, catch_ok);
1120                 add_3cell(row, p.stallouts);
1121                 add_3cell(row, '+' + p.offensive_soft_plus);
1122                 add_3cell(row, '-' + p.offensive_soft_minus);
1123                 row.dataset.player = q;
1124                 rows.push(row);
1125
1126                 goals += p.goals;
1127                 num_throws += p.num_throws;
1128                 throwaways += p.throwaways;
1129                 catches += p.catches;
1130                 drops += p.drops;
1131                 was_ds += p.was_ds;
1132                 stallouts += p.stallouts;
1133         }
1134
1135         // Globals.
1136         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1137         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1138         throw_ok.format = 'percentage';
1139         catch_ok.format = 'percentage';
1140         throw_ok.desired = 0.9;
1141         catch_ok.desired = 0.9;
1142
1143         let row = document.createElement('tr');
1144         add_3cell(row, '');
1145         add_3cell(row, goals);
1146         add_3cell(row, '');
1147         add_3cell(row, '');
1148         add_3cell(row, num_throws);
1149         add_3cell(row, throwaways);
1150         add_3cell_ci(row, throw_ok);
1151         add_3cell(row, catches);
1152         add_3cell(row, drops);
1153         add_3cell(row, was_ds);
1154         add_3cell_ci(row, catch_ok);
1155         add_3cell(row, stallouts);
1156         add_3cell(row, '');
1157         add_3cell(row, '');
1158         rows.push(row);
1159
1160         return rows;
1161 }
1162
1163 function make_table_defense(players) {
1164         let rows = [];
1165         {
1166                 let header = document.createElement('tr');
1167                 add_th(header, 'Player');
1168                 add_th(header, 'Ds');
1169                 add_th(header, 'Pulls');
1170                 add_th(header, 'OOB pulls');
1171                 add_th(header, 'OOB%');
1172                 add_th(header, 'Avg. hang time (IB)');
1173                 add_th(header, 'Callahans');
1174                 add_th(header, 'Soft +/-', 6);
1175                 rows.push(header);
1176         }
1177
1178         let defenses = 0;
1179         let pulls = 0;
1180         let oob_pulls = 0;
1181         let sum_sum_time = 0;
1182         let callahans = 0;
1183
1184         for (const [q,p] of get_sorted_players(players)) {
1185                 if (q === 'globals') continue;
1186                 let sum_time = 0;
1187                 for (const t of p.pull_times) {
1188                         sum_time += t;
1189                 }
1190                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1191                 let oob_pct = 100 * p.oob_pulls / p.pulls;
1192
1193                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1194                 ci_oob.format = 'percentage';
1195                 ci_oob.desired = 0.2;  // Arbitrary.
1196                 ci_oob.inverted = true;
1197
1198                 let row = document.createElement('tr');
1199                 add_3cell(row, p.name, 'name');  // TODO: number?
1200                 add_3cell(row, p.defenses);
1201                 add_3cell(row, p.pulls);
1202                 add_3cell(row, p.oob_pulls);
1203                 add_3cell_ci(row, ci_oob);
1204                 if (p.pulls > p.oob_pulls) {
1205                         add_3cell(row, avg_time.toFixed(1) + ' sec');
1206                 } else {
1207                         add_3cell(row, 'N/A');
1208                 }
1209                 add_3cell(row, p.callahans);
1210                 add_3cell(row, '+' + p.defensive_soft_plus);
1211                 add_3cell(row, '-' + p.defensive_soft_minus);
1212                 row.dataset.player = q;
1213                 rows.push(row);
1214
1215                 defenses += p.defenses;
1216                 pulls += p.pulls;
1217                 oob_pulls += p.oob_pulls;
1218                 sum_sum_time += sum_time;
1219                 callahans += p.callahans;
1220         }
1221
1222         // Globals.
1223         let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1224         ci_oob.format = 'percentage';
1225         ci_oob.desired = 0.2;  // Arbitrary.
1226         ci_oob.inverted = true;
1227
1228         let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1229         let oob_pct = 100 * oob_pulls / pulls;
1230
1231         let row = document.createElement('tr');
1232         add_3cell(row, '');
1233         add_3cell(row, defenses);
1234         add_3cell(row, pulls);
1235         add_3cell(row, oob_pulls);
1236         add_3cell_ci(row, ci_oob);
1237         if (pulls > oob_pulls) {
1238                 add_3cell(row, avg_time.toFixed(1) + ' sec');
1239         } else {
1240                 add_3cell(row, 'N/A');
1241         }
1242         add_3cell(row, callahans);
1243         add_3cell(row, '');
1244         add_3cell(row, '');
1245         rows.push(row);
1246
1247         return rows;
1248 }
1249
1250 function make_table_playing_time(players) {
1251         let rows = [];
1252         {
1253                 let header = document.createElement('tr');
1254                 add_th(header, 'Player');
1255                 add_th(header, 'Points played');
1256                 add_th(header, 'Time played');
1257                 add_th(header, 'O time');
1258                 add_th(header, 'D time');
1259                 add_th(header, 'Time on field');
1260                 add_th(header, 'O points');
1261                 add_th(header, 'D points');
1262                 rows.push(header);
1263         }
1264
1265         for (const [q,p] of get_sorted_players(players)) {
1266                 if (q === 'globals') continue;
1267                 let row = document.createElement('tr');
1268                 add_3cell(row, p.name, 'name');  // TODO: number?
1269                 add_3cell(row, p.points_played);
1270                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1271                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1272                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1273                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1274                 add_3cell(row, p.offensive_points_completed);
1275                 add_3cell(row, p.defensive_points_completed);
1276                 row.dataset.player = q;
1277                 rows.push(row);
1278         }
1279
1280         // Globals.
1281         let globals = players['globals'];
1282         let row = document.createElement('tr');
1283         add_3cell(row, '');
1284         add_3cell(row, globals.points_played);
1285         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1286         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1287         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1288         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1289         add_3cell(row, globals.offensive_points_completed);
1290         add_3cell(row, globals.defensive_points_completed);
1291         rows.push(row);
1292
1293         return rows;
1294 }
1295
1296 function make_table_per_point(players) {
1297         let rows = [];
1298         {
1299                 let header = document.createElement('tr');
1300                 add_th(header, 'Player');
1301                 add_th(header, 'Goals');
1302                 add_th(header, 'Assists');
1303                 add_th(header, 'Hockey assists');
1304                 add_th(header, 'Ds');
1305                 add_th(header, 'Throwaways');
1306                 add_th(header, 'Recv. errors');
1307                 add_th(header, 'Touches');
1308                 rows.push(header);
1309         }
1310
1311         let goals = 0;
1312         let assists = 0;
1313         let hockey_assists = 0;
1314         let defenses = 0;
1315         let throwaways = 0;
1316         let receiver_errors = 0;
1317         let touches = 0;
1318         for (const [q,p] of get_sorted_players(players)) {
1319                 if (q === 'globals') continue;
1320
1321                 // Can only happen once per point, so these are binomials.
1322                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1323                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1324                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1325                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1326                 ci_goals.desired = 0.1;
1327                 ci_assists.desired = 0.1;
1328                 ci_hockey_assists.desired = 0.1;
1329
1330                 let row = document.createElement('tr');
1331                 add_3cell(row, p.name, 'name');  // TODO: number?
1332                 add_3cell_ci(row, ci_goals);
1333                 add_3cell_ci(row, ci_assists);
1334                 add_3cell_ci(row, ci_hockey_assists);
1335                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1336                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1337                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1338                 if (p.points_played > 0) {
1339                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1340                 } else {
1341                         add_3cell(row, 'N/A');
1342                 }
1343                 row.dataset.player = q;
1344                 rows.push(row);
1345
1346                 goals += p.goals;
1347                 assists += p.assists;
1348                 hockey_assists += p.hockey_assists;
1349                 defenses += p.defenses;
1350                 throwaways += p.throwaways;
1351                 receiver_errors += p.drops + p.was_ds;
1352                 touches += p.touches;
1353         }
1354
1355         // Globals.
1356         let globals = players['globals'];
1357         let row = document.createElement('tr');
1358         add_3cell(row, '');
1359         if (globals.points_played > 0) {
1360                 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1361                 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1362                 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1363                 ci_goals.desired = 0.5;
1364                 ci_assists.desired = 0.5;
1365                 ci_hockey_assists.desired = 0.5;
1366
1367                 add_3cell_ci(row, ci_goals);
1368                 add_3cell_ci(row, ci_assists);
1369                 add_3cell_ci(row, ci_hockey_assists);
1370
1371                 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1372                 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1373                 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1374
1375                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1376         } else {
1377                 add_3cell_with_filler_ci(row, 'N/A');
1378                 add_3cell_with_filler_ci(row, 'N/A');
1379                 add_3cell_with_filler_ci(row, 'N/A');
1380                 add_3cell_with_filler_ci(row, 'N/A');
1381                 add_3cell_with_filler_ci(row, 'N/A');
1382                 add_3cell_with_filler_ci(row, 'N/A');
1383                 add_3cell(row, 'N/A');
1384         }
1385         rows.push(row);
1386
1387         return rows;
1388 }
1389
1390 function open_filter_menu(click_to_add_div) {
1391         document.getElementById('filter-submenu').style.display = 'none';
1392         let filter_div = click_to_add_div.parentElement;
1393         let filter_id = filter_div.dataset.filterId;
1394
1395         let menu = document.getElementById('filter-add-menu');
1396         menu.parentElement.removeChild(menu);
1397         filter_div.appendChild(menu);
1398         menu.style.display = 'block';
1399         menu.replaceChildren();
1400
1401         // Place the menu directly under the “click to add” label;
1402         // we don't anchor it since that label will move around
1403         // and the menu shouldn't.
1404         let rect = click_to_add_div.getBoundingClientRect();
1405         menu.style.left = rect.left + 'px';
1406         menu.style.top = (rect.bottom + 10) + 'px';
1407
1408         let filterset = global_filters[filter_id];
1409         if (filterset === undefined) {
1410                 global_filters[filter_id] = filterset = [];
1411         }
1412
1413         add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1414         add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1415         add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1416         add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1417         add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1418         add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1419         add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1420 }
1421
1422 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1423         let item = document.createElement('div');
1424         item.classList.add('option');
1425         item.appendChild(document.createTextNode(title));
1426
1427         let arrow = document.createElement('div');
1428         arrow.classList.add('arrow');
1429         arrow.textContent = '▸';
1430         item.appendChild(arrow);
1431
1432         menu.appendChild(item);
1433
1434         item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1435 }
1436
1437 function find_all_ratios(json)
1438 {
1439         let ratios = {};
1440         let players = {};
1441         for (const player of json['players']) {
1442                 players[player['player_id']] = {
1443                         'gender': player['gender'],
1444                         'last_point_seen': null,
1445                 };
1446         }
1447         for (const match of json['matches']) {
1448                 for (const [q,p] of Object.entries(players)) {
1449                         p.on_field_since = null;
1450                 }
1451                 for (const e of match['events']) {
1452                         let p = players[e['player']];
1453                         let type = e['type'];
1454                         if (type === 'in') {
1455                                 p.on_field_since = 1;
1456                         } else if (type === 'out') {
1457                                 p.on_field_since = null;
1458                         } else if (type === 'pull' || type == 'their_pull') {  // We assume no cross-gender subs for now.
1459                                 let code = find_gender_ratio_code(players);
1460                                 if (ratios[code] === undefined) {
1461                                         ratios[code] = code;
1462                                         if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1463                                                 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1464                                                             match['description'] + ', ' + format_time(e['t']));
1465                                         }
1466                                 }
1467                         }
1468                 }
1469         }
1470         return ratios;
1471 }
1472
1473 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1474         let submenu = document.getElementById('filter-submenu');
1475
1476         // Move to the same place as the top-level menu.
1477         submenu.parentElement.removeChild(submenu);
1478         document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1479
1480         let subitems = [];
1481         const filter = find_filter(filterset, filter_type);
1482
1483         let choices = [];
1484         if (filter_type === 'match') {
1485                 for (const match of global_json['matches']) {
1486                         choices.push({
1487                                 'title': match['description'],
1488                                 'id': match['match_id']
1489                         });
1490                 }
1491         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1492                 for (const player of global_json['players']) {
1493                         choices.push({
1494                                 'title': player['name'],
1495                                 'id': player['player_id']
1496                         });
1497                 }
1498         } else if (filter_type === 'formation_offense') {
1499                 choices.push({
1500                         'title': '(None/unknown)',
1501                         'id': 0,
1502                 });
1503                 for (const formation of global_json['formations']) {
1504                         if (formation['offense']) {
1505                                 choices.push({
1506                                         'title': formation['name'],
1507                                         'id': formation['formation_id']
1508                                 });
1509                         }
1510                 }
1511         } else if (filter_type === 'formation_defense') {
1512                 choices.push({
1513                         'title': '(None/unknown)',
1514                         'id': 0,
1515                 });
1516                 for (const formation of global_json['formations']) {
1517                         if (!formation['offense']) {
1518                                 choices.push({
1519                                         'title': formation['name'],
1520                                         'id': formation['formation_id']
1521                                 });
1522                         }
1523                 }
1524         } else if (filter_type === 'starting_on') {
1525                 choices.push({
1526                         'title': 'Offense',
1527                         'id': false,  // last_pull_was_ours
1528                 });
1529                 choices.push({
1530                         'title': 'Defense',
1531                         'id': true,  // last_pull_was_ours
1532                 });
1533         } else if (filter_type === 'gender_ratio') {
1534                 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1535                         choices.push({
1536                                 'title': title,
1537                                 'id': id,
1538                         });
1539                 }
1540         }
1541
1542         for (const choice of choices) {
1543                 let label = document.createElement('label');
1544
1545                 let subitem = document.createElement('div');
1546                 subitem.classList.add('option');
1547
1548                 let check = document.createElement('input');
1549                 check.setAttribute('type', 'checkbox');
1550                 check.setAttribute('id', 'choice' + choice.id);
1551                 if (filter !== null && filter.elements.has(choice.id)) {
1552                         check.setAttribute('checked', 'checked');
1553                 }
1554                 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1555
1556                 subitem.appendChild(check);
1557                 subitem.appendChild(document.createTextNode(choice.title));
1558
1559                 label.appendChild(subitem);
1560                 subitems.push(label);
1561         }
1562         submenu.replaceChildren(...subitems);
1563         submenu.style.display = 'block';
1564
1565         if (pill !== null) {
1566                 let rect = pill.getBoundingClientRect();
1567                 submenu.style.top = (rect.bottom + 10) + 'px';
1568                 submenu.style.left = rect.left + 'px';
1569         } else {
1570                 // Position just outside the selected menu.
1571                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1572                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1573                 submenu.style.left = (rect.right - 1) + 'px';
1574         }
1575 }
1576
1577 // Find the right filter, if it exists.
1578 function find_filter(filterset, filter_type) {
1579         for (let f of filterset) {
1580                 if (f.type === filter_type) {
1581                         return f;
1582                 }
1583         }
1584         return null;
1585 }
1586
1587 // Equivalent to Array.prototype.filter, but in-place.
1588 function inplace_filter(arr, cond) {
1589         let j = 0;
1590         for (let i = 0; i < arr.length; ++i) {
1591                 if (cond(arr[i])) {
1592                         arr[j++] = arr[i];
1593                 }
1594         }
1595         arr.length = j;
1596 }
1597
1598 function add_new_filterset() {
1599         let template = document.querySelector('.filter');  // First one is fine.
1600         let div = template.cloneNode(true);
1601         let add_menu = div.querySelector('#filter-add-menu');
1602         if (add_menu !== null) {
1603                 div.removeChild(add_menu);
1604         }
1605         let submenu = div.querySelector('#filter-submenu');
1606         if (submenu !== null) {
1607                 div.removeChild(submenu);
1608         }
1609         div.querySelector('.filters').replaceChildren();
1610         div.dataset.filterId = next_filterset_id++;
1611         template.parentElement.appendChild(div);
1612 }
1613
1614 function try_gc_filter_menus(cheap) {
1615         let empties = [];
1616         let divs = [];
1617         for (const filter_div of document.querySelectorAll('.filter')) {
1618                 let id = filter_div.dataset.filterId;
1619                 divs.push(filter_div);
1620                 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1621         }
1622         let last_div = divs[empties.length - 1];
1623         if (cheap) {
1624                 // See if we have two empty filter lists at the bottom of the list;
1625                 // if so, we can remove one without it looking funny in the UI.
1626                 // If not, we'll have to wait until closing the menu.
1627                 // (The menu is positioned at the second-last one, so we can
1628                 // remove the last one without issue.)
1629                 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1630                         delete global_filters[last_div.dataset.filterId];
1631                         last_div.parentElement.removeChild(last_div);
1632                 }
1633         } else {
1634                 // This is a different situation from try_cheap_gc(), where we should
1635                 // remove the one _not_ last. We might need to move the menu to the last one,
1636                 // though, so it doesn't get lost.
1637                 for (let i = 0; i < empties.length - 1; ++i) {
1638                         if (!empties[i]) {
1639                                 continue;
1640                         }
1641                         let div = divs[i];
1642                         delete global_filters[div.dataset.filterId];
1643                         let add_menu = div.querySelector('#filter-add-menu');
1644                         if (add_menu !== null) {
1645                                 div.removeChild(add_menu);
1646                                 last_div.appendChild(add_menu);
1647                         }
1648                         let submenu = div.querySelector('#filter-submenu');
1649                         if (submenu !== null) {
1650                                 div.removeChild(submenu);
1651                                 last_div.appendChild(submenu);
1652                         }
1653                         div.parentElement.removeChild(div);
1654                 }
1655         }
1656 }
1657
1658 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1659         let filter = find_filter(filterset, filter_type);
1660         let pills_div = filter_div.querySelector('.filters');
1661         if (e.target.checked) {
1662                 // See if we must create a new empty filterset (since this went from
1663                 // empty to non-empty).
1664                 if (filterset.length === 0) {
1665                         add_new_filterset();
1666                 }
1667
1668                 // See if we must add a new filter to the list.
1669                 if (filter === null) {
1670                         filter = {
1671                                 'type': filter_type,
1672                                 'elements': new Set([ id ]),
1673                         };
1674                         filter.pill = make_filter_pill(filter_div, filterset, filter);
1675                         filterset.push(filter);
1676                         pills_div.appendChild(filter.pill);
1677                 } else {
1678                         filter.elements.add(id);
1679                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1680                         pills_div.replaceChild(new_pill, filter.pill);
1681                         filter.pill = new_pill;
1682                 }
1683         } else {
1684                 filter.elements.delete(id);
1685                 if (filter.elements.size === 0) {
1686                         pills_div.removeChild(filter.pill);
1687                         inplace_filter(filterset, f => f !== filter);
1688
1689                         if (filterset.length == 0) {
1690                                 try_gc_filter_menus(true);
1691                         }
1692                 } else {
1693                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1694                         pills_div.replaceChild(new_pill, filter.pill);
1695                         filter.pill = new_pill;
1696                 }
1697         }
1698
1699         process_matches(global_json, global_filters);
1700 }
1701
1702 function make_filter_pill(filter_div, filterset, filter) {
1703         let pill = document.createElement('div');
1704         pill.classList.add('filter-pill');
1705         let text;
1706         if (filter.type === 'match') {
1707                 text = 'Match: ';
1708
1709                 let all_names = [];
1710                 for (const match_id of filter.elements) {
1711                         all_names.push(find_match(match_id)['description']);
1712                 }
1713                 let common_prefix = find_common_prefix_of_all(all_names);
1714                 if (common_prefix !== null) {
1715                         text += common_prefix + '(';
1716                 }
1717
1718                 let first = true;
1719                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1720                 for (const match_id of sorted_match_id) {
1721                         if (!first) {
1722                                 text += ', ';
1723                         }
1724                         let desc = find_match(match_id)['description'];
1725                         if (common_prefix === null) {
1726                                 text += desc;
1727                         } else {
1728                                 text += desc.substr(common_prefix.length);
1729                         }
1730                         first = false;
1731                 }
1732
1733                 if (common_prefix !== null) {
1734                         text += ')';
1735                 }
1736         } else if (filter.type === 'player_any') {
1737                 text = 'Player (any): ';
1738                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1739                 let first = true;
1740                 for (const player_id of sorted_players) {
1741                         if (!first) {
1742                                 text += ', ';
1743                         }
1744                         text += find_player(player_id)['name'];
1745                         first = false;
1746                 }
1747         } else if (filter.type === 'player_all') {
1748                 text = 'Players: ';
1749                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1750                 let first = true;
1751                 for (const player_id of sorted_players) {
1752                         if (!first) {
1753                                 text += ' AND ';
1754                         }
1755                         text += find_player(player_id)['name'];
1756                         first = false;
1757                 }
1758         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1759                 const offense = (filter.type === 'formation_offense');
1760                 if (offense) {
1761                         text = 'Offense: ';
1762                 } else {
1763                         text = 'Defense: ';
1764                 }
1765
1766                 let all_names = [];
1767                 for (const formation_id of filter.elements) {
1768                         all_names.push(find_formation(formation_id)['name']);
1769                 }
1770                 let common_prefix = find_common_prefix_of_all(all_names);
1771                 if (common_prefix !== null) {
1772                         text += common_prefix + '(';
1773                 }
1774
1775                 let first = true;
1776                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1777                 for (const formation_id of sorted_formation_id) {
1778                         if (!first) {
1779                                 ktext += ', ';
1780                         }
1781                         let desc = find_formation(formation_id)['name'];
1782                         if (common_prefix === null) {
1783                                 text += desc;
1784                         } else {
1785                                 text += desc.substr(common_prefix.length);
1786                         }
1787                         first = false;
1788                 }
1789
1790                 if (common_prefix !== null) {
1791                         text += ')';
1792                 }
1793         } else if (filter.type === 'starting_on') {
1794                 text = 'Starting on: ';
1795
1796                 if (filter.elements.has(false) && filter.elements.has(true)) {
1797                         text += 'Any';
1798                 } else if (filter.elements.has(false)) {
1799                         text += 'Offense';
1800                 } else {
1801                         text += 'Defense';
1802                 }
1803         } else if (filter.type === 'gender_ratio') {
1804                 text = 'Gender: ';
1805
1806                 let first = true;
1807                 for (const name of Array.from(filter.elements).sort()) {
1808                         if (!first) {
1809                                 text += '; ';
1810                         }
1811                         text += name;  // FIXME
1812                         first = false;
1813                 }
1814         }
1815
1816         let text_node = document.createElement('span');
1817         text_node.innerText = text;
1818         text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1819         pill.appendChild(text_node);
1820
1821         pill.appendChild(document.createTextNode(' '));
1822
1823         let delete_node = document.createElement('span');
1824         delete_node.innerText = '✖';
1825         delete_node.addEventListener('click', (e) => {
1826                 // Delete this filter entirely.
1827                 pill.parentElement.removeChild(pill);
1828                 inplace_filter(filterset, f => f !== filter);
1829                 if (filterset.length == 0) {
1830                         try_gc_filter_menus(false);
1831                 }
1832                 process_matches(global_json, global_filters);
1833
1834                 let add_menu = document.getElementById('filter-add-menu');
1835                 let add_submenu = document.getElementById('filter-submenu');
1836                 add_menu.style.display = 'none';
1837                 add_submenu.style.display = 'none';
1838         });
1839         pill.appendChild(delete_node);
1840         pill.style.cursor = 'pointer';
1841
1842         return pill;
1843 }
1844
1845 function make_filter_marker(filterset) {
1846         let text = '';
1847         for (const filter of filterset) {
1848                 if (text !== '') {
1849                         text += ',';
1850                 }
1851                 if (filter.type === 'match') {
1852                         let all_names = [];
1853                         for (const match of global_json['matches']) {
1854                                 all_names.push(match['description']);
1855                         }
1856                         let common_prefix = find_common_prefix_of_all(all_names);
1857
1858                         let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1859                         for (const match_id of sorted_match_id) {
1860                                 let desc = find_match(match_id)['description'];
1861                                 if (common_prefix === null) {
1862                                         text += desc.substr(0, 3);
1863                                 } else {
1864                                         text += desc.substr(common_prefix.length, 3);
1865                                 }
1866                         }
1867                 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1868                         let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1869                         for (const player_id of sorted_players) {
1870                                 text += find_player(player_id)['name'].substr(0, 3);
1871                         }
1872                 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1873                         let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1874                         for (const formation_id of sorted_formation_id) {
1875                                 text += find_formation(formation_id)['name'].substr(0, 3);
1876                         }
1877                 } else if (filter.type === 'starting_on') {
1878                         if (filter.elements.has(false) && filter.elements.has(true)) {
1879                                 // Nothing.
1880                         } else if (filter.elements.has(false)) {
1881                                 text += 'O';
1882                         } else {
1883                                 text += 'D';
1884                         }
1885                 } else if (filter.type === 'gender_ratio') {
1886                         let first = true;
1887                         for (const name of Array.from(filter.elements).sort()) {
1888                                 if (!first) {
1889                                         text += '; ';
1890                                 }
1891                                 text += name.replaceAll(' ', '').substr(0, 2);  // 4 F, 3M -> 4 F.
1892                                 first = false;
1893                         }
1894                 }
1895         }
1896         return text;
1897 }
1898
1899 function find_common_prefix(a, b) {
1900         let ret = '';
1901         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1902                 if (a[i] === b[i]) {
1903                         ret += a[i];
1904                 } else {
1905                         break;
1906                 }
1907         }
1908         return ret;
1909 }
1910
1911 function find_common_prefix_of_all(values) {
1912         if (values.length < 2) {
1913                 return null;
1914         }
1915         let common_prefix = null;
1916         for (const desc of values) {
1917                 if (common_prefix === null) {
1918                         common_prefix = desc;
1919                 } else {
1920                         common_prefix = find_common_prefix(common_prefix, desc);
1921                 }
1922         }
1923         if (common_prefix.length >= 3) {
1924                 return common_prefix;
1925         } else {
1926                 return null;
1927         }
1928 }
1929
1930 function find_match(match_id) {
1931         for (const match of global_json['matches']) {
1932                 if (match['match_id'] === match_id) {
1933                         return match;
1934                 }
1935         }
1936         return null;
1937 }
1938
1939 function find_formation(formation_id) {
1940         for (const formation of global_json['formations']) {
1941                 if (formation['formation_id'] === formation_id) {
1942                         return formation;
1943                 }
1944         }
1945         return null;
1946 }
1947
1948 function find_player(player_id) {
1949         for (const player of global_json['players']) {
1950                 if (player['player_id'] === player_id) {
1951                         return player;
1952                 }
1953         }
1954         return null;
1955 }
1956
1957 function player_pos(player_id) {
1958         let i = 0;
1959         for (const player of global_json['players']) {
1960                 if (player['player_id'] === player_id) {
1961                         return i;
1962                 }
1963                 ++i;
1964         }
1965         return null;
1966 }
1967
1968 function keep_match(match_id, filters) {
1969         for (const filter of filters) {
1970                 if (filter.type === 'match') {
1971                         return filter.elements.has(match_id);
1972                 }
1973         }
1974         return true;
1975 }
1976
1977 // Returns a map of e.g. F => 4, M => 3.
1978 function find_gender_ratio(players) {
1979         let map = {};
1980         for (const [q,p] of Object.entries(players)) {
1981                 if (p.on_field_since === null) {
1982                         continue;
1983                 }
1984                 let gender = p.gender;
1985                 if (gender === '' || gender === undefined || gender === null) {
1986                         gender = '?';
1987                 }
1988                 if (map[gender] === undefined) {
1989                         map[gender] = 1;
1990 q               } else {
1991                         ++map[gender];
1992                 }
1993         }
1994         return map;
1995 }
1996
1997 function find_gender_ratio_code(players) {
1998         let map = find_gender_ratio(players);
1999         let all_genders = Array.from(Object.keys(map)).sort(
2000                 (a,b) => {
2001                         if (map[a] !== map[b]) {
2002                                 return map[b] - map[a];  // Reverse numeric.
2003                         } else if (a < b) {
2004                                 return -1;
2005                         } else if (a > b) {
2006                                 return 1;
2007                         } else {
2008                                 return 0;
2009                         }
2010                 });
2011         let code = '';
2012         for (const g of all_genders) {
2013                 if (code !== '') {
2014                         code += ', ';
2015                 }
2016                 code += map[g];
2017                 code += ' ';
2018                 code += g;
2019         }
2020         return code;
2021 }
2022
2023 // null if none (e.g., if playing 3–3).
2024 function find_predominant_gender(players) {
2025         let max = 0;
2026         let predominant_gender = null;
2027         for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2028                 if (num > max) {
2029                         max = num;
2030                         predominant_gender = gender;
2031                 } else if (num == max) {
2032                         predominant_gender = null;  // At least two have the same.
2033                 }
2034         }
2035         return predominant_gender;
2036 }
2037
2038 function find_num_players_on_field(players) {
2039         let num = 0;
2040         for (const [q,p] of Object.entries(players)) {
2041                 if (p.on_field_since !== null) {
2042                         ++num;
2043                 }
2044         }
2045         return num;
2046 }
2047
2048 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2049         if (filter.type === 'player_any') {
2050                 for (const p of Array.from(filter.elements)) {
2051                         if (players[p].on_field_since !== null) {
2052                                 return true;
2053                         }
2054                 }
2055                 return false;
2056         } else if (filter.type === 'player_all') {
2057                 for (const p of Array.from(filter.elements)) {
2058                         if (players[p].on_field_since === null) {
2059                                 return false;
2060                         }
2061                 }
2062                 return true;
2063         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2064                 for (const f of Array.from(filter.elements)) {
2065                         if (formations_used_this_point.has(f)) {
2066                                 return true;
2067                         }
2068                 }
2069                 return false;
2070         } else if (filter.type === 'starting_on') {
2071                 return filter.elements.has(last_pull_was_ours);
2072         } else if (filter.type === 'gender_ratio') {
2073                 return filter.elements.has(find_gender_ratio_code(players));
2074         }
2075         return true;
2076 }
2077
2078 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2079         for (const filter of filters) {
2080                 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2081                         return false;
2082                 }
2083         }
2084         return true;
2085 }
2086
2087 // Heuristic: If we go at least ten seconds without the possession changing
2088 // or the operator specifying some other formation, we probably play the
2089 // same formation as the last point.
2090 function should_reuse_last_formation(events, t) {
2091         for (const e of events) {
2092                 if (e.t <= t) {
2093                         continue;
2094                 }
2095                 if (e.t > t + 10000) {
2096                         break;
2097                 }
2098                 const type = e.type;
2099                 if (type === 'their_goal' || type === 'goal' ||
2100                     type === 'set_defense' || type === 'set_offense' ||
2101                     type === 'throwaway' || type === 'their_throwaway' ||
2102                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2103                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2104                     type === 'formation_offense' || type === 'formation_defense') {
2105                         return false;
2106                 }
2107         }
2108         return true;
2109 }
2110
2111 function possibly_close_menu(e) {
2112         if (e.target.closest('.filter-click-to-add') === null &&
2113             e.target.closest('#filter-add-menu') === null &&
2114             e.target.closest('#filter-submenu') === null &&
2115             e.target.closest('.filter-pill') === null) {
2116                 let add_menu = document.getElementById('filter-add-menu');
2117                 let add_submenu = document.getElementById('filter-submenu');
2118                 add_menu.style.display = 'none';
2119                 add_submenu.style.display = 'none';
2120                 try_gc_filter_menus(false);
2121         }
2122 }
2123
2124 let global_sort = {};
2125
2126 function sort_by(th) {
2127         let tr = th.parentElement;
2128         let child_idx = 0;
2129         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2130                 let element = tr.children[column_idx];
2131                 if (element === th) {
2132                         ++child_idx;  // Pad.
2133                         break;
2134                 }
2135                 if (element.hasAttribute('colspan')) {
2136                         child_idx += parseInt(element.getAttribute('colspan'));
2137                 } else {
2138                         ++child_idx;
2139                 }
2140         }
2141
2142         global_sort = {};
2143         let table = tr.parentElement;
2144         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
2145                 let row = table.children[row_idx];
2146                 let player = parseInt(row.dataset.player);
2147                 let value = row.children[child_idx].textContent;
2148                 global_sort[player] = value;
2149         }
2150 }
2151
2152 function get_sorted_players(players)
2153 {
2154         let p = Object.entries(players);
2155         if (global_sort.length !== 0) {
2156                 p.sort((a,b) => {
2157                         let ai = parseFloat(global_sort[a[0]]);
2158                         let bi = parseFloat(global_sort[b[0]]);
2159                         if (ai == ai && bi == bi) {
2160                                 return bi - ai;  // Reverse numeric.
2161                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
2162                                 return -1;
2163                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
2164                                 return 1;
2165                         } else {
2166                                 return 0;
2167                         }
2168                 });
2169         }
2170         return p;
2171 }