]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Fix so that we can change existing events to pulls.
[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
8 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
9 addEventListener('click', possibly_close_menu);
10 fetch('ultimate.json')
11    .then(response => response.json())
12    .then(response => { global_json = response; process_matches(global_json, global_filters); });
13
14 function attribute_player_time(player, to, from, offense) {
15         let delta_time;
16         if (player.on_field_since > from) {
17                 // Player came in while play happened (without a stoppage!?).
18                 delta_time = to - player.on_field_since;
19         } else {
20                 delta_time = to - from;
21         }
22         player.playing_time_ms += delta_time;
23         if (offense === true) {
24                 player.offensive_playing_time_ms += delta_time;
25         } else if (offense === false) {
26                 player.defensive_playing_time_ms += delta_time;
27         }
28 }
29
30 function take_off_field(player, t, live_since, offense, keep) {
31         if (keep) {
32                 if (live_since === null) {
33                         // Play isn't live, so nothing to do.
34                 } else {
35                         attribute_player_time(player, t, live_since, offense);
36                 }
37                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
38                         player.field_time_ms += t - player.on_field_since;
39                 }
40         }
41         player.on_field_since = null;
42 }
43
44 function add_cell(tr, element_type, text) {
45         let element = document.createElement(element_type);
46         element.textContent = text;
47         tr.appendChild(element);
48         return element;
49 }
50
51 function add_th(tr, text, colspan) {
52         let element = document.createElement('th');
53         let link = document.createElement('a');
54         link.style.cursor = 'pointer';
55         link.addEventListener('click', (e) => {
56                 sort_by(element);
57                 process_matches(global_json, global_filters);
58         });
59         link.textContent = text;
60         element.appendChild(link);
61         tr.appendChild(element);
62
63         if (colspan > 0) {
64                 element.setAttribute('colspan', colspan);
65         } else {
66                 element.setAttribute('colspan', '3');
67         }
68         return element;
69 }
70
71 function add_3cell(tr, text, cls) {
72         let p1 = add_cell(tr, 'td', '');
73         let element = add_cell(tr, 'td', text);
74         let p2 = add_cell(tr, 'td', '');
75
76         p1.classList.add('pad');
77         p2.classList.add('pad');
78         if (cls === undefined) {
79                 element.classList.add('num');
80         } else {
81                 element.classList.add(cls);
82         }
83         return element;
84 }
85
86 function add_3cell_with_filler_ci(tr, text, cls) {
87         let element = add_3cell(tr, text, cls);
88
89         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
90         svg.classList.add('fillerci');
91         svg.setAttribute('width', ci_width);
92         svg.setAttribute('height', ci_height);
93         element.appendChild(svg);
94
95         return element;
96 }
97
98 function add_3cell_ci(tr, ci) {
99         if (isNaN(ci.val)) {
100                 add_3cell_with_filler_ci(tr, 'N/A');
101                 return;
102         }
103
104         let text;
105         if (ci.format === 'percentage') {
106                 text = (100 * ci.val).toFixed(0) + '%';
107         } else {
108                 text = ci.val.toFixed(2);
109         }
110         let element = add_3cell(tr, text);
111         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
112
113         // Container.
114         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
115         if (ci.inverted === true) {
116                 svg.classList.add('invertedci');
117         } else {
118                 svg.classList.add('ci');
119         }
120         svg.setAttribute('width', ci_width);
121         svg.setAttribute('height', ci_height);
122
123         // The good (green) and red (bad) ranges.
124         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
125         s0.classList.add('range');
126         s0.classList.add('s0');
127         s0.setAttribute('width', to_x(ci.desired));
128         s0.setAttribute('height', ci_height);
129         s0.setAttribute('x', '0');
130
131         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
132         s1.classList.add('range');
133         s1.classList.add('s1');
134         s1.setAttribute('width', ci_width - to_x(ci.desired));
135         s1.setAttribute('height', ci_height);
136         s1.setAttribute('x', to_x(ci.desired));
137
138         // Confidence bar.
139         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
140         bar.classList.add('bar');
141         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
142         bar.setAttribute('height', ci_height / 3);
143         bar.setAttribute('x', to_x(ci.lower_ci));
144         bar.setAttribute('y', ci_height / 3);
145
146         // Marker line for average.
147         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
148         marker.classList.add('marker');
149         marker.setAttribute('x1', to_x(ci.val));
150         marker.setAttribute('x2', to_x(ci.val));
151         marker.setAttribute('y1', ci_height / 6);
152         marker.setAttribute('y2', ci_height * 5 / 6);
153
154         svg.appendChild(s0);
155         svg.appendChild(s1);
156         svg.appendChild(bar);
157         svg.appendChild(marker);
158
159         element.appendChild(svg);
160 }
161
162 function process_matches(json, filters) {
163         let players = {};
164         for (const player of json['players']) {
165                 players[player['player_id']] = {
166                         'name': player['name'],
167                         'number': player['number'],
168
169                         'goals': 0,
170                         'assists': 0,
171                         'hockey_assists': 0,
172                         'catches': 0,
173                         'touches': 0,
174                         'num_throws': 0,
175                         'throwaways': 0,
176                         'drops': 0,
177                         'was_ds': 0,
178                         'stallouts': 0,
179
180                         'defenses': 0,
181                         'points_played': 0,
182                         'playing_time_ms': 0,
183                         'offensive_playing_time_ms': 0,
184                         'defensive_playing_time_ms': 0,
185                         'field_time_ms': 0,
186
187                         // For efficiency.
188                         'offensive_points_completed': 0,
189                         'offensive_points_won': 0,
190                         'defensive_points_completed': 0,
191                         'defensive_points_won': 0,
192
193                         'offensive_soft_plus': 0,
194                         'offensive_soft_minus': 0,
195                         'defensive_soft_plus': 0,
196                         'defensive_soft_minus': 0,
197
198                         'pulls': 0,
199                         'pull_times': [],
200                         'oob_pulls': 0,
201
202                         // Internal.
203                         'last_point_seen': null,
204                         'on_field_since': null,
205                 };
206         }
207
208         // Globals.
209         players['globals'] = {
210                 'points_played': 0,
211                 'playing_time_ms': 0,
212                 'offensive_playing_time_ms': 0,
213                 'defensive_playing_time_ms': 0,
214                 'field_time_ms': 0,
215
216                 'offensive_points_completed': 0,
217                 'offensive_points_won': 0,
218                 'defensive_points_completed': 0,
219                 'defensive_points_won': 0,
220         };
221         let globals = players['globals'];
222
223         for (const match of json['matches']) {
224                 if (!keep_match(match['match_id'], filters)) {
225                         continue;
226                 }
227
228                 let our_score = 0;
229                 let their_score = 0;
230                 let handler = null;
231                 let prev_handler = null;
232                 let live_since = null;
233                 let offense = null;  // True/false/null (unknown).
234                 let puller = null;
235                 let pull_started = null;
236                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
237                 let point_num = 0;
238                 let game_started = null;
239                 let last_goal = null;
240
241                 // The last used formations of the given kind, if any; they may be reused
242                 // when the point starts, if nothing else is set.
243                 let last_offensive_formation = null;
244                 let last_defensive_formation = null;
245
246                 // Formations we've set, but haven't really had the chance to use yet
247                 // (e.g., we get a “use zone defense” event while we're still on offense).
248                 let pending_offensive_formation = null;
249                 let pending_defensive_formation = null;
250
251                 // Formations that we have played at least once this point, after all
252                 // heuristics and similar.
253                 let formations_used_this_point = new Set();
254
255                 for (const [q,p] of Object.entries(players)) {
256                         p.on_field_since = null;
257                         p.last_point_seen = null;
258                 }
259                 for (const e of match['events']) {
260                         let t = e['t'];
261                         let type = e['type'];
262                         let p = players[e['player']];
263
264                         // Sub management
265                         let keep = keep_event(players, formations_used_this_point, filters);
266                         if (type === 'in' && p.on_field_since === null) {
267                                 p.on_field_since = t;
268                                 if (!keep && keep_event(players, formations_used_this_point, filters)) {
269                                         // A player needed for the filters went onto the field,
270                                         // so pretend people walked on right now (to start their
271                                         // counting time).
272                                         for (const [q,p2] of Object.entries(players)) {
273                                                 if (p2.on_field_since !== null) {
274                                                         p2.on_field_since = t;
275                                                 }
276                                         }
277                                 }
278                         } else if (type === 'out') {
279                                 take_off_field(p, t, live_since, offense, keep);
280                                 if (keep && !keep_event(players, formations_used_this_point, filters)) {
281                                         // A player needed for the filters went off the field,
282                                         // so we need to attribute time for all the others.
283                                         // Pretend they walked off and then immediately on again.
284                                         //
285                                         // TODO: We also need to take care of this to get the globals right.
286                                         for (const [q,p2] of Object.entries(players)) {
287                                                 if (p2.on_field_since !== null) {
288                                                         take_off_field(p2, t, live_since, offense, keep);
289                                                         p2.on_field_since = t;
290                                                 }
291                                         }
292                                 }
293                         }
294
295                         keep = keep_event(players, formations_used_this_point, filters);  // Recompute after in/out.
296
297                         // Liveness management
298                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
299                                 live_since = t;
300                         } else if (type === 'catch' && last_pull_was_ours === null) {
301                                 // Someone forgot to add the pull, so we'll need to wing it.
302                                 console.log('Missing pull on ' + our_score + '\u2013' + their_score + ' in ' + match['description'] + '; pretending to have one.');
303                                 live_since = t;
304                                 last_pull_was_ours = !offense;
305                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
306                                 for (const [q,p] of Object.entries(players)) {
307                                         if (p.on_field_since === null) {
308                                                 continue;
309                                         }
310                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
311                                                 if (keep) {
312                                                         // In case the player did nothing this point,
313                                                         // not even subbing in.
314                                                         p.last_point_seen = point_num;
315                                                         ++p.points_played;
316                                                 }
317                                         }
318                                         if (keep) attribute_player_time(p, t, live_since, offense);
319
320                                         if (type !== 'stoppage') {
321                                                 if (keep) {
322                                                         if (last_pull_was_ours === true) {  // D point.
323                                                                 ++p.defensive_points_completed;
324                                                                 if (type === 'goal') {
325                                                                         ++p.defensive_points_won;
326                                                                 }
327                                                         } else if (last_pull_was_ours === false) {  // O point.
328                                                                 ++p.offensive_points_completed;
329                                                                 if (type === 'goal') {
330                                                                         ++p.offensive_points_won;
331                                                                 }
332                                                         }
333                                                 }
334                                         }
335                                 }
336
337                                 if (keep) {
338                                         if (type !== 'stoppage') {
339                                                 // Update globals.
340                                                 ++globals.points_played;
341                                                 if (last_pull_was_ours === true) {  // D point.
342                                                         ++globals.defensive_points_completed;
343                                                         if (type === 'goal') {
344                                                                 ++globals.defensive_points_won;
345                                                         }
346                                                 } else if (last_pull_was_ours === false) {  // O point.
347                                                         ++globals.offensive_points_completed;
348                                                         if (type === 'goal') {
349                                                                 ++globals.offensive_points_won;
350                                                         }
351                                                 }
352                                         }
353                                         if (live_since !== null) {
354                                                 globals.playing_time_ms += t - live_since;
355                                                 if (offense === true) {
356                                                         globals.offensive_playing_time_ms += t - live_since;
357                                                 } else if (offense === false) {
358                                                         globals.defensive_playing_time_ms += t - live_since;
359                                                 }
360                                         }
361                                 }
362
363                                 live_since = null;
364                         }
365
366                         // Score management
367                         if (type === 'goal') {
368                                 ++our_score;
369                         } else if (type === 'their_goal') {
370                                 ++their_score;
371                         }
372
373                         // Point count management
374                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
375                                 if (keep) {
376                                         p.last_point_seen = point_num;
377                                         ++p.points_played;
378                                 }
379                         }
380                         if (type === 'goal' || type === 'their_goal') {
381                                 ++point_num;
382                                 last_goal = t;
383                         }
384                         if (type !== 'out' && game_started === null) {
385                                 game_started = t;
386                         }
387
388                         // Pull management
389                         if (type === 'pull') {
390                                 puller = e['player'];
391                                 pull_started = t;
392                                 if (keep) ++p.pulls;
393                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
394                                 // No effect on pull.
395                         } else if (type === 'pull_landed' && puller !== null) {
396                                 if (keep) players[puller].pull_times.push(t - pull_started);
397                         } else if (type === 'pull_oob' && puller !== null) {
398                                 if (keep) ++players[puller].oob_pulls;
399                         } else {
400                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
401                                 puller = pull_started = null;
402                         }
403
404                         // Offense/defense management
405                         let last_offense = offense;
406                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
407                                 offense = false;
408                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
409                                 offense = true;
410                         }
411                         if (last_offense !== offense && live_since !== null) {
412                                 // Switched offense/defense status, so attribute this drive as needed,
413                                 // and update live_since to take that into account.
414                                 if (keep) {
415                                         for (const [q,p] of Object.entries(players)) {
416                                                 if (p.on_field_since === null) {
417                                                         continue;
418                                                 }
419                                                 attribute_player_time(p, t, live_since, last_offense);
420                                         }
421                                         globals.playing_time_ms += t - live_since;
422                                         if (offense === true) {
423                                                 globals.offensive_playing_time_ms += t - live_since;
424                                         } else if (offense === false) {
425                                                 globals.defensive_playing_time_ms += t - live_since;
426                                         }
427                                 }
428                                 live_since = t;
429                         }
430
431                         if (type === 'pull') {
432                                 last_pull_was_ours = true;
433                         } else if (type === 'their_pull') {
434                                 last_pull_was_ours = false;
435                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
436                                 // set_offense could either be “changed to offense for some reason
437                                 // we could not express”, or “we started in the middle of a point,
438                                 // and we are offense”. We assume that if we already saw the pull,
439                                 // it's the former, and if not, it's the latter; thus, the === null
440                                 // test above. (It could also be “we set offense before the pull,
441                                 // so that we get the right button enabled”, in which case it will
442                                 // be overwritten by the next pull/their_pull event anyway.)
443                                 last_pull_was_ours = false;
444                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
445                                 // Similar.
446                                 last_pull_was_ours = true;
447                         } else if (type === 'goal' || type === 'their_goal') {
448                                 last_pull_was_ours = null;
449                         }
450
451                         // Formation management
452                         if (type === 'formation_offense' || type === 'formation_defense') {
453                                 let id = e.formation === null ? 0 : e.formation;
454                                 let for_offense = (type === 'formation_offense');
455                                 if (offense === for_offense) {
456                                         formations_used_this_point.add(id);
457                                 } else if (for_offense) {
458                                         pending_offensive_formation = id;
459                                 } else {
460                                         pending_defensive_formation = id;
461                                 }
462                                 if (for_offense) {
463                                         last_offensive_formation = id;
464                                 } else {
465                                         last_defensive_formation = id;
466                                 }
467                         } else if (last_offense !== offense) {
468                                 if (offense === true && pending_offensive_formation !== null) {
469                                         formations_used_this_point.add(pending_offensive_formation);
470                                         pending_offensive_formation = null;
471                                 } else if (offense === false && pending_defensive_formation !== null) {
472                                         formations_used_this_point.add(pending_defensive_formation);
473                                         pending_defensive_formation = null;
474                                 } else if (offense === true && last_defensive_formation !== null) {
475                                         if (should_reuse_last_formation(match['events'], t)) {
476                                                 formations_used_this_point.add(last_defensive_formation);
477                                         }
478                                 } else if (offense === false && last_offensive_formation !== null) {
479                                         if (should_reuse_last_formation(match['events'], t)) {
480                                                 formations_used_this_point.add(last_offensive_formation);
481                                         }
482                                 }
483                         }
484
485                         if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
486                                 console.log('Event “' + type + '” on subbed-out player ' + p.name + ' in ' + our_score + '\u2013' + their_score + ' in ' + match['description']);
487                         }
488                         if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
489                                 // The handler subbed out and was replaced with another handler,
490                                 // so this wasn't a pass.
491                                 console.log('Pass from subbed-out player ' + players[handler].name + ' in ' + our_score + '\u2013' + their_score + ' in ' + match['description'] + '; ignoring.');
492                                 handler = null;
493                         }
494
495                         // Event management
496                         if (type === 'catch' || type === 'goal') {
497                                 if (handler !== null) {
498                                         if (keep) {
499                                                 ++players[handler].num_throws;
500                                                 ++p.catches;
501                                         }
502                                 }
503
504                                 if (keep) ++p.touches;
505                                 if (type === 'goal') {
506                                         if (keep) {
507                                                 if (prev_handler !== null) {
508                                                         ++players[prev_handler].hockey_assists;
509                                                 }
510                                                 if (handler !== null) {
511                                                         ++players[handler].assists;
512                                                 }
513                                                 ++p.goals;
514                                         }
515                                         handler = prev_handler = null;
516                                 } else {
517                                         // Update hold history.
518                                         prev_handler = handler;
519                                         handler = e['player'];
520                                 }
521                         } else if (type === 'throwaway') {
522                                 if (keep) {
523                                         ++p.num_throws;
524                                         ++p.throwaways;
525                                 }
526                                 handler = prev_handler = null;
527                         } else if (type === 'drop') {
528                                 if (keep) ++p.drops;
529                                 handler = prev_handler = null;
530                         } else if (type === 'stallout') {
531                                 if (keep) ++p.stallouts;
532                                 handler = prev_handler = null;
533                         } else if (type === 'was_d') {
534                                 if (keep) ++p.was_ds;
535                                 handler = prev_handler = null;
536                         } else if (type === 'defense') {
537                                 if (keep) ++p.defenses;
538                         } else if (type === 'interception') {
539                                 if (keep) {
540                                         ++p.catches;
541                                         ++p.defenses;
542                                         ++p.touches;
543                                 }
544                                 prev_handler = null;
545                                 handler = e['player'];
546                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
547                                 if (keep) ++p[type];
548                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
549                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
550                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
551                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
552                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
553                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
554                                    type !== 'formation_offense' && type !== 'formation_defense') {
555                                 console.log("Unknown event:", e);
556                         }
557
558                         if (type === 'goal' || type === 'their_goal') {
559                                 formations_used_this_point.clear();
560                         }
561                 }
562
563                 // Add field time for all players still left at match end.
564                 const keep = keep_event(players, formations_used_this_point, filters);
565                 if (keep) {
566                         for (const [q,p] of Object.entries(players)) {
567                                 if (p.on_field_since !== null && last_goal !== null) {
568                                         p.field_time_ms += last_goal - p.on_field_since;
569                                 }
570                         }
571                         if (game_started !== null && last_goal !== null) {
572                                 globals.field_time_ms += last_goal - game_started;
573                         }
574                         if (live_since !== null && last_goal !== null) {
575                                 globals.playing_time_ms += last_goal - live_since;
576                                 if (offense === true) {
577                                         globals.offensive_playing_time_ms += last_goal - live_since;
578                                 } else if (offense === false) {
579                                         globals.defensive_playing_time_ms += last_goal - live_since;
580                                 }
581                         }
582                 }
583         }
584
585         let chosen_category = get_chosen_category();
586         write_main_menu(chosen_category);
587
588         let rows = [];
589         if (chosen_category === 'general') {
590                 rows = make_table_general(players);
591         } else if (chosen_category === 'offense') {
592                 rows = make_table_offense(players);
593         } else if (chosen_category === 'defense') {
594                 rows = make_table_defense(players);
595         } else if (chosen_category === 'playing_time') {
596                 rows = make_table_playing_time(players);
597         } else if (chosen_category === 'per_point') {
598                 rows = make_table_per_point(players);
599         }
600         document.getElementById('stats').replaceChildren(...rows);
601 }
602
603 function get_chosen_category() {
604         if (window.location.hash === '#offense') {
605                 return 'offense';
606         } else if (window.location.hash === '#defense') {
607                 return 'defense';
608         } else if (window.location.hash === '#playing_time') {
609                 return 'playing_time';
610         } else if (window.location.hash === '#per_point') {
611                 return 'per_point';
612         } else {
613                 return 'general';
614         }
615 }
616
617 function write_main_menu(chosen_category) {
618         let elems = [];
619         if (chosen_category === 'general') {
620                 let span = document.createElement('span');
621                 span.innerText = 'General';
622                 elems.push(span);
623         } else {
624                 let a = document.createElement('a');
625                 a.appendChild(document.createTextNode('General'));
626                 a.setAttribute('href', '#general');
627                 elems.push(a);
628         }
629
630         if (chosen_category === 'offense') {
631                 let span = document.createElement('span');
632                 span.innerText = 'Offense';
633                 elems.push(span);
634         } else {
635                 let a = document.createElement('a');
636                 a.appendChild(document.createTextNode('Offense'));
637                 a.setAttribute('href', '#offense');
638                 elems.push(a);
639         }
640
641         if (chosen_category === 'defense') {
642                 let span = document.createElement('span');
643                 span.innerText = 'Defense';
644                 elems.push(span);
645         } else {
646                 let a = document.createElement('a');
647                 a.appendChild(document.createTextNode('Defense'));
648                 a.setAttribute('href', '#defense');
649                 elems.push(a);
650         }
651
652         if (chosen_category === 'playing_time') {
653                 let span = document.createElement('span');
654                 span.innerText = 'Playing time';
655                 elems.push(span);
656         } else {
657                 let a = document.createElement('a');
658                 a.appendChild(document.createTextNode('Playing time'));
659                 a.setAttribute('href', '#playing_time');
660                 elems.push(a);
661         }
662
663         if (chosen_category === 'per_point') {
664                 let span = document.createElement('span');
665                 span.innerText = 'Per point';
666                 elems.push(span);
667         } else {
668                 let a = document.createElement('a');
669                 a.appendChild(document.createTextNode('Per point'));
670                 a.setAttribute('href', '#per_point');
671                 elems.push(a);
672         }
673
674         document.getElementById('mainmenu').replaceChildren(...elems);
675 }
676
677 // https://en.wikipedia.org/wiki/1.96#History
678 const z = 1.959964;
679
680 const ci_width = 100;
681 const ci_height = 20;
682
683 function make_binomial_ci(val, num, z) {
684         let avg = val / num;
685
686         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
687         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
688         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
689
690         // Fix the signs so that we don't get -0.00.
691         low = Math.max(low, 0.0);
692         return {
693                 'val': avg,
694                 'lower_ci': low,
695                 'upper_ci': high,
696                 'min': 0.0,
697                 'max': 1.0,
698         };
699 }
700
701 // These can only happen once per point, but you get -1 and +1
702 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
703 // and then we can rewrite back.
704 function make_efficiency_ci(points_won, points_completed, z)
705 {
706         let ci = make_binomial_ci(points_won, points_completed, z);
707         ci.val = 2.0 * ci.val - 1.0;
708         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
709         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
710         ci.min = -1.0;
711         ci.max = 1.0;
712         ci.desired = 0.0;  // Desired = positive efficiency.
713         return ci;
714 }
715
716 // Ds, throwaways and drops can happen multiple times per point,
717 // so they are Poisson distributed.
718 //
719 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
720 // since our rates are definitely below 2 per point).
721 function make_poisson_ci(val, num, z, inverted)
722 {
723         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
724         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
725
726         // Fix the signs so that we don't get -0.00.
727         low = Math.max(low, 0.0);
728
729         // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
730         let avg = val / num;
731         return {
732                 'val': avg,
733                 'lower_ci': low,
734                 'upper_ci': high,
735                 'min': 0.0,
736                 'max': 0.25,
737                 'desired': 0.05,
738                 'inverted': inverted,
739         };
740 }
741
742 function make_table_general(players) {
743         let rows = [];
744         {
745                 let header = document.createElement('tr');
746                 add_th(header, 'Player');
747                 add_th(header, '+/-');
748                 add_th(header, 'Soft +/-');
749                 add_th(header, 'O efficiency');
750                 add_th(header, 'D efficiency');
751                 add_th(header, 'Points played');
752                 rows.push(header);
753         }
754
755         for (const [q,p] of get_sorted_players(players)) {
756                 if (q === 'globals') continue;
757                 let row = document.createElement('tr');
758                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
759                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
760                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
761                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
762                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
763                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
764                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
765                 add_3cell_ci(row, o_efficiency);
766                 add_3cell_ci(row, d_efficiency);
767                 add_3cell(row, p.points_played);
768                 row.dataset.player = q;
769                 rows.push(row);
770         }
771
772         // Globals.
773         let globals = players['globals'];
774         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
775         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
776         let row = document.createElement('tr');
777         add_3cell(row, '');
778         add_3cell(row, '');
779         add_3cell(row, '');
780         add_3cell_ci(row, o_efficiency);
781         add_3cell_ci(row, d_efficiency);
782         add_3cell(row, globals.points_played);
783         rows.push(row);
784
785         return rows;
786 }
787
788 function make_table_offense(players) {
789         let rows = [];
790         {
791                 let header = document.createElement('tr');
792                 add_th(header, 'Player');
793                 add_th(header, 'Goals');
794                 add_th(header, 'Assists');
795                 add_th(header, 'Hockey assists');
796                 add_th(header, 'Throws');
797                 add_th(header, 'Throwaways');
798                 add_th(header, '%OK');
799                 add_th(header, 'Catches');
800                 add_th(header, 'Drops');
801                 add_th(header, 'D-ed');
802                 add_th(header, '%OK');
803                 add_th(header, 'Stalls');
804                 add_th(header, 'Soft +/-', 6);
805                 rows.push(header);
806         }
807
808         let num_throws = 0;
809         let throwaways = 0;
810         let catches = 0;
811         let drops = 0;
812         let was_ds = 0;
813         let stallouts = 0;
814         for (const [q,p] of get_sorted_players(players)) {
815                 if (q === 'globals') continue;
816                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
817                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
818
819                 throw_ok.format = 'percentage';
820                 catch_ok.format = 'percentage';
821
822                 // Desire at least 90% percentage. Fairly arbitrary.
823                 throw_ok.desired = 0.9;
824                 catch_ok.desired = 0.9;
825
826                 let row = document.createElement('tr');
827                 add_3cell(row, p.name, 'name');  // TODO: number?
828                 add_3cell(row, p.goals);
829                 add_3cell(row, p.assists);
830                 add_3cell(row, p.hockey_assists);
831                 add_3cell(row, p.num_throws);
832                 add_3cell(row, p.throwaways);
833                 add_3cell_ci(row, throw_ok);
834                 add_3cell(row, p.catches);
835                 add_3cell(row, p.drops);
836                 add_3cell(row, p.was_ds);
837                 add_3cell_ci(row, catch_ok);
838                 add_3cell(row, p.stallouts);
839                 add_3cell(row, '+' + p.offensive_soft_plus);
840                 add_3cell(row, '-' + p.offensive_soft_minus);
841                 row.dataset.player = q;
842                 rows.push(row);
843
844                 num_throws += p.num_throws;
845                 throwaways += p.throwaways;
846                 catches += p.catches;
847                 drops += p.drops;
848                 was_ds += p.was_ds;
849                 stallouts += p.stallouts;
850         }
851
852         // Globals.
853         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
854         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
855         throw_ok.format = 'percentage';
856         catch_ok.format = 'percentage';
857         throw_ok.desired = 0.9;
858         catch_ok.desired = 0.9;
859
860         let row = document.createElement('tr');
861         add_3cell(row, '');
862         add_3cell(row, '');
863         add_3cell(row, '');
864         add_3cell(row, '');
865         add_3cell(row, num_throws);
866         add_3cell(row, throwaways);
867         add_3cell_ci(row, throw_ok);
868         add_3cell(row, catches);
869         add_3cell(row, drops);
870         add_3cell(row, was_ds);
871         add_3cell_ci(row, catch_ok);
872         add_3cell(row, stallouts);
873         add_3cell(row, '');
874         add_3cell(row, '');
875         rows.push(row);
876
877         return rows;
878 }
879
880 function make_table_defense(players) {
881         let rows = [];
882         {
883                 let header = document.createElement('tr');
884                 add_th(header, 'Player');
885                 add_th(header, 'Ds');
886                 add_th(header, 'Pulls');
887                 add_th(header, 'OOB pulls');
888                 add_th(header, 'OOB%');
889                 add_th(header, 'Avg. hang time (IB)');
890                 add_th(header, 'Soft +/-', 6);
891                 rows.push(header);
892         }
893         for (const [q,p] of get_sorted_players(players)) {
894                 if (q === 'globals') continue;
895                 let sum_time = 0;
896                 for (const t of p.pull_times) {
897                         sum_time += t;
898                 }
899                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
900                 let oob_pct = 100 * p.oob_pulls / p.pulls;
901
902                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
903                 ci_oob.format = 'percentage';
904                 ci_oob.desired = 0.2;  // Arbitrary.
905                 ci_oob.inverted = true;
906
907                 let row = document.createElement('tr');
908                 add_3cell(row, p.name, 'name');  // TODO: number?
909                 add_3cell(row, p.defenses);
910                 add_3cell(row, p.pulls);
911                 add_3cell(row, p.oob_pulls);
912                 add_3cell_ci(row, ci_oob);
913                 if (p.pulls > p.oob_pulls) {
914                         add_3cell(row, avg_time.toFixed(1) + ' sec');
915                 } else {
916                         add_3cell(row, 'N/A');
917                 }
918                 add_3cell(row, '+' + p.defensive_soft_plus);
919                 add_3cell(row, '-' + p.defensive_soft_minus);
920                 row.dataset.player = q;
921                 rows.push(row);
922         }
923         return rows;
924 }
925
926 function make_table_playing_time(players) {
927         let rows = [];
928         {
929                 let header = document.createElement('tr');
930                 add_th(header, 'Player');
931                 add_th(header, 'Points played');
932                 add_th(header, 'Time played');
933                 add_th(header, 'O time');
934                 add_th(header, 'D time');
935                 add_th(header, 'Time on field');
936                 add_th(header, 'O points');
937                 add_th(header, 'D points');
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                 add_3cell(row, p.name, 'name');  // TODO: number?
945                 add_3cell(row, p.points_played);
946                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
947                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
948                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
949                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
950                 add_3cell(row, p.offensive_points_completed);
951                 add_3cell(row, p.defensive_points_completed);
952                 row.dataset.player = q;
953                 rows.push(row);
954         }
955
956         // Globals.
957         let globals = players['globals'];
958         let row = document.createElement('tr');
959         add_3cell(row, '');
960         add_3cell(row, globals.points_played);
961         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
962         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
963         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
964         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
965         add_3cell(row, globals.offensive_points_completed);
966         add_3cell(row, globals.defensive_points_completed);
967         rows.push(row);
968
969         return rows;
970 }
971
972 function make_table_per_point(players) {
973         let rows = [];
974         {
975                 let header = document.createElement('tr');
976                 add_th(header, 'Player');
977                 add_th(header, 'Goals');
978                 add_th(header, 'Assists');
979                 add_th(header, 'Hockey assists');
980                 add_th(header, 'Ds');
981                 add_th(header, 'Throwaways');
982                 add_th(header, 'Recv. errors');
983                 add_th(header, 'Touches');
984                 rows.push(header);
985         }
986
987         let goals = 0;
988         let assists = 0;
989         let hockey_assists = 0;
990         let defenses = 0;
991         let throwaways = 0;
992         let receiver_errors = 0;
993         let touches = 0;
994         for (const [q,p] of get_sorted_players(players)) {
995                 if (q === 'globals') continue;
996
997                 // Can only happen once per point, so these are binomials.
998                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
999                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1000                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1001                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1002                 ci_goals.desired = 0.1;
1003                 ci_assists.desired = 0.1;
1004                 ci_hockey_assists.desired = 0.1;
1005
1006                 let row = document.createElement('tr');
1007                 add_3cell(row, p.name, 'name');  // TODO: number?
1008                 add_3cell_ci(row, ci_goals);
1009                 add_3cell_ci(row, ci_assists);
1010                 add_3cell_ci(row, ci_hockey_assists);
1011                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1012                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1013                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1014                 if (p.points_played > 0) {
1015                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1016                 } else {
1017                         add_3cell(row, 'N/A');
1018                 }
1019                 row.dataset.player = q;
1020                 rows.push(row);
1021
1022                 goals += p.goals;
1023                 assists += p.assists;
1024                 hockey_assists += p.hockey_assists;
1025                 defenses += p.defenses;
1026                 throwaways += p.throwaways;
1027                 receiver_errors += p.drops + p.was_ds;
1028                 touches += p.touches;
1029         }
1030
1031         // Globals.
1032         let globals = players['globals'];
1033         let row = document.createElement('tr');
1034         add_3cell(row, '');
1035         if (globals.points_played > 0) {
1036                 add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
1037                 add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
1038                 add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
1039                 add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
1040                 add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
1041                 add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
1042                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1043         } else {
1044                 add_3cell_with_filler_ci(row, 'N/A');
1045                 add_3cell_with_filler_ci(row, 'N/A');
1046                 add_3cell_with_filler_ci(row, 'N/A');
1047                 add_3cell_with_filler_ci(row, 'N/A');
1048                 add_3cell_with_filler_ci(row, 'N/A');
1049                 add_3cell_with_filler_ci(row, 'N/A');
1050                 add_3cell(row, 'N/A');
1051         }
1052         rows.push(row);
1053
1054         return rows;
1055 }
1056
1057 function open_filter_menu() {
1058         document.getElementById('filter-submenu').style.display = 'none';
1059
1060         let menu = document.getElementById('filter-add-menu');
1061         menu.style.display = 'block';
1062         menu.replaceChildren();
1063
1064         // Place the menu directly under the “click to add” label;
1065         // we don't anchor it since that label will move around
1066         // and the menu shouldn't.
1067         let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
1068         menu.style.left = rect.left + 'px';
1069         menu.style.top = (rect.bottom + 10) + 'px';
1070
1071         add_menu_item(menu, 0, 'match', 'Match (any)');
1072         add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
1073         add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
1074         add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
1075         add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
1076 }
1077
1078 function add_menu_item(menu, menu_idx, filter_type, title) {
1079         let item = document.createElement('div');
1080         item.classList.add('option');
1081         item.appendChild(document.createTextNode(title));
1082
1083         let arrow = document.createElement('div');
1084         arrow.classList.add('arrow');
1085         arrow.textContent = '▸';
1086         item.appendChild(arrow);
1087
1088         menu.appendChild(item);
1089
1090         item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
1091 }
1092
1093 function show_submenu(menu_idx, pill, filter_type) {
1094         let submenu = document.getElementById('filter-submenu');
1095         let subitems = [];
1096         const filter = find_filter(filter_type);
1097
1098         let choices = [];
1099         if (filter_type === 'match') {
1100                 for (const match of global_json['matches']) {
1101                         choices.push({
1102                                 'title': match['description'],
1103                                 'id': match['match_id']
1104                         });
1105                 }
1106         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1107                 for (const player of global_json['players']) {
1108                         choices.push({
1109                                 'title': player['name'],
1110                                 'id': player['player_id']
1111                         });
1112                 }
1113         } else if (filter_type === 'formation_offense') {
1114                 choices.push({
1115                         'title': '(None/unknown)',
1116                         'id': 0,
1117                 });
1118                 for (const formation of global_json['formations']) {
1119                         if (formation['offense']) {
1120                                 choices.push({
1121                                         'title': formation['name'],
1122                                         'id': formation['formation_id']
1123                                 });
1124                         }
1125                 }
1126         } else if (filter_type === 'formation_defense') {
1127                 choices.push({
1128                         'title': '(None/unknown)',
1129                         'id': 0,
1130                 });
1131                 for (const formation of global_json['formations']) {
1132                         if (!formation['offense']) {
1133                                 choices.push({
1134                                         'title': formation['name'],
1135                                         'id': formation['formation_id']
1136                                 });
1137                         }
1138                 }
1139         }
1140
1141         for (const choice of choices) {
1142                 let label = document.createElement('label');
1143
1144                 let subitem = document.createElement('div');
1145                 subitem.classList.add('option');
1146
1147                 let check = document.createElement('input');
1148                 check.setAttribute('type', 'checkbox');
1149                 check.setAttribute('id', 'choice' + choice.id);
1150                 if (filter !== null && filter.elements.has(choice.id)) {
1151                         check.setAttribute('checked', 'checked');
1152                 }
1153                 check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
1154
1155                 subitem.appendChild(check);
1156                 subitem.appendChild(document.createTextNode(choice.title));
1157
1158                 label.appendChild(subitem);
1159                 subitems.push(label);
1160         }
1161         submenu.replaceChildren(...subitems);
1162         submenu.style.display = 'block';
1163
1164         if (pill !== null) {
1165                 let rect = pill.getBoundingClientRect();
1166                 submenu.style.top = (rect.bottom + 10) + 'px';
1167                 submenu.style.left = rect.left + 'px';
1168         } else {
1169                 // Position just outside the selected menu.
1170                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1171                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1172                 submenu.style.left = (rect.right - 1) + 'px';
1173         }
1174 }
1175
1176 // Find the right filter, if it exists.
1177 function find_filter(filter_type) {
1178         for (let f of global_filters) {
1179                 if (f.type === filter_type) {
1180                         return f;
1181                 }
1182         }
1183         return null;
1184 }
1185
1186 function checkbox_changed(e, filter_type, id) {
1187         let filter = find_filter(filter_type);
1188         if (e.target.checked) {
1189                 // See if we must add a new filter to the list.
1190                 if (filter === null) {
1191                         filter = {
1192                                 'type': filter_type,
1193                                 'elements': new Set([ id ]),
1194                         };
1195                         filter.pill = make_filter_pill(filter);
1196                         global_filters.push(filter);
1197                         document.getElementById('filters').appendChild(filter.pill);
1198                 } else {
1199                         filter.elements.add(id);
1200                         let new_pill = make_filter_pill(filter);
1201                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1202                         filter.pill = new_pill;
1203                 }
1204         } else {
1205                 filter.elements.delete(id);
1206                 if (filter.elements.size === 0) {
1207                         document.getElementById('filters').removeChild(filter.pill);
1208                         global_filters = global_filters.filter(f => f !== filter);
1209                 } else {
1210                         let new_pill = make_filter_pill(filter);
1211                         document.getElementById('filters').replaceChild(new_pill, filter.pill);
1212                         filter.pill = new_pill;
1213                 }
1214         }
1215
1216         process_matches(global_json, global_filters);
1217 }
1218
1219 function make_filter_pill(filter) {
1220         let pill = document.createElement('div');
1221         pill.classList.add('filter-pill');
1222         let text;
1223         if (filter.type === 'match') {
1224                 text = 'Match: ';
1225
1226                 let all_names = [];
1227                 for (const match_id of filter.elements) {
1228                         all_names.push(find_match(match_id)['description']);
1229                 }
1230                 let common_prefix = find_common_prefix_of_all(all_names);
1231                 if (common_prefix !== null) {
1232                         text += common_prefix + '(';
1233                 }
1234
1235                 let first = true;
1236                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1237                 for (const match_id of sorted_match_id) {
1238                         if (!first) {
1239                                 text += ', ';
1240                         }
1241                         let desc = find_match(match_id)['description'];
1242                         if (common_prefix === null) {
1243                                 text += desc;
1244                         } else {
1245                                 text += desc.substr(common_prefix.length);
1246                         }
1247                         first = false;
1248                 }
1249
1250                 if (common_prefix !== null) {
1251                         text += ')';
1252                 }
1253         } else if (filter.type === 'player_any') {
1254                 text = 'Player (any): ';
1255                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1256                 let first = true;
1257                 for (const player_id of sorted_players) {
1258                         if (!first) {
1259                                 text += ', ';
1260                         }
1261                         text += find_player(player_id)['name'];
1262                         first = false;
1263                 }
1264         } else if (filter.type === 'player_all') {
1265                 text = 'Players: ';
1266                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1267                 let first = true;
1268                 for (const player_id of sorted_players) {
1269                         if (!first) {
1270                                 text += ' AND ';
1271                         }
1272                         text += find_player(player_id)['name'];
1273                         first = false;
1274                 }
1275         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1276                 const offense = (filter.type === 'formation_offense');
1277                 if (offense) {
1278                         text = 'Offense: ';
1279                 } else {
1280                         text = 'Defense: ';
1281                 }
1282
1283                 let all_names = [];
1284                 for (const formation_id of filter.elements) {
1285                         all_names.push(find_formation(formation_id)['name']);
1286                 }
1287                 let common_prefix = find_common_prefix_of_all(all_names);
1288                 if (common_prefix !== null) {
1289                         text += common_prefix + '(';
1290                 }
1291
1292                 let first = true;
1293                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1294                 for (const formation_id of sorted_formation_id) {
1295                         if (!first) {
1296                                 text += ', ';
1297                         }
1298                         let desc = find_formation(formation_id)['name'];
1299                         if (common_prefix === null) {
1300                                 text += desc;
1301                         } else {
1302                                 text += desc.substr(common_prefix.length);
1303                         }
1304                         first = false;
1305                 }
1306
1307                 if (common_prefix !== null) {
1308                         text += ')';
1309                 }
1310         }
1311
1312         let text_node = document.createElement('span');
1313         text_node.innerText = text;
1314         text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
1315         pill.appendChild(text_node);
1316
1317         pill.appendChild(document.createTextNode(' '));
1318
1319         let delete_node = document.createElement('span');
1320         delete_node.innerText = '✖';
1321         delete_node.addEventListener('click', (e) => {
1322                 // Delete this filter entirely.
1323                 document.getElementById('filters').removeChild(pill);
1324                 global_filters = global_filters.filter(f => f !== filter);
1325                 process_matches(global_json, global_filters);
1326
1327                 let add_menu = document.getElementById('filter-add-menu');
1328                 let add_submenu = document.getElementById('filter-submenu');
1329                 add_menu.style.display = 'none';
1330                 add_submenu.style.display = 'none';
1331         });
1332         pill.appendChild(delete_node);
1333         pill.style.cursor = 'pointer';
1334
1335         return pill;
1336 }
1337
1338 function find_common_prefix(a, b) {
1339         let ret = '';
1340         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1341                 if (a[i] === b[i]) {
1342                         ret += a[i];
1343                 } else {
1344                         break;
1345                 }
1346         }
1347         return ret;
1348 }
1349
1350 function find_common_prefix_of_all(values) {
1351         if (values.length < 2) {
1352                 return null;
1353         }
1354         let common_prefix = null;
1355         for (const desc of values) {
1356                 if (common_prefix === null) {
1357                         common_prefix = desc;
1358                 } else {
1359                         common_prefix = find_common_prefix(common_prefix, desc);
1360                 }
1361         }
1362         if (common_prefix.length >= 3) {
1363                 return common_prefix;
1364         } else {
1365                 return null;
1366         }
1367 }
1368
1369 function find_match(match_id) {
1370         for (const match of global_json['matches']) {
1371                 if (match['match_id'] === match_id) {
1372                         return match;
1373                 }
1374         }
1375         return null;
1376 }
1377
1378 function find_formation(formation_id) {
1379         for (const formation of global_json['formations']) {
1380                 if (formation['formation_id'] === formation_id) {
1381                         return formation;
1382                 }
1383         }
1384         return null;
1385 }
1386
1387 function find_player(player_id) {
1388         for (const player of global_json['players']) {
1389                 if (player['player_id'] === player_id) {
1390                         return player;
1391                 }
1392         }
1393         return null;
1394 }
1395
1396 function player_pos(player_id) {
1397         let i = 0;
1398         for (const player of global_json['players']) {
1399                 if (player['player_id'] === player_id) {
1400                         return i;
1401                 }
1402                 ++i;
1403         }
1404         return null;
1405 }
1406
1407 function keep_match(match_id, filters) {
1408         for (const filter of filters) {
1409                 if (filter.type === 'match') {
1410                         return filter.elements.has(match_id);
1411                 }
1412         }
1413         return true;
1414 }
1415
1416 function filter_passes(players, formations_used_this_point, filter) {
1417         if (filter.type === 'player_any') {
1418                 for (const p of Array.from(filter.elements)) {
1419                         if (players[p].on_field_since !== null) {
1420                                 return true;
1421                         }
1422                 }
1423                 return false;
1424         } else if (filter.type === 'player_all') {
1425                 for (const p of Array.from(filter.elements)) {
1426                         if (players[p].on_field_since === null) {
1427                                 return false;
1428                         }
1429                 }
1430                 return true;
1431         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1432                 for (const f of Array.from(filter.elements)) {
1433                         if (formations_used_this_point.has(f)) {
1434                                 return true;
1435                         }
1436                 }
1437                 return false;
1438         }
1439         return true;
1440 }
1441
1442 function keep_event(players, formations_used_this_point, filters) {
1443         for (const filter of filters) {
1444                 if (!filter_passes(players, formations_used_this_point, filter)) {
1445                         return false;
1446                 }
1447         }
1448         return true;
1449 }
1450
1451 // Heuristic: If we go at least ten seconds without the possession changing
1452 // or the operator specifying some other formation, we probably play the
1453 // same formation as the last point.
1454 function should_reuse_last_formation(events, t) {
1455         for (const e of events) {
1456                 if (e.t <= t) {
1457                         continue;
1458                 }
1459                 if (e.t > t + 10000) {
1460                         break;
1461                 }
1462                 const type = e.type;
1463                 if (type === 'their_goal' || type === 'goal' ||
1464                     type === 'set_defense' || type === 'set_offense' ||
1465                     type === 'throwaway' || type === 'their_throwaway' ||
1466                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1467                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1468                     type === 'formation_offense' || type === 'formation_defense') {
1469                         return false;
1470                 }
1471         }
1472         return true;
1473 }
1474
1475 function possibly_close_menu(e) {
1476         if (e.target.closest('#filter-click-to-add') === null &&
1477             e.target.closest('#filter-add-menu') === null &&
1478             e.target.closest('#filter-submenu') === null &&
1479             e.target.closest('.filter-pill') === null) {
1480                 let add_menu = document.getElementById('filter-add-menu');
1481                 let add_submenu = document.getElementById('filter-submenu');
1482                 add_menu.style.display = 'none';
1483                 add_submenu.style.display = 'none';
1484         }
1485 }
1486
1487 let global_sort = {};
1488
1489 function sort_by(th) {
1490         let tr = th.parentElement;
1491         let child_idx = 0;
1492         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1493                 let element = tr.children[column_idx];
1494                 if (element === th) {
1495                         ++child_idx;  // Pad.
1496                         break;
1497                 }
1498                 if (element.hasAttribute('colspan')) {
1499                         child_idx += parseInt(element.getAttribute('colspan'));
1500                 } else {
1501                         ++child_idx;
1502                 }
1503         }
1504
1505         global_sort = {};
1506         let table = tr.parentElement;
1507         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
1508                 let row = table.children[row_idx];
1509                 let player = parseInt(row.dataset.player);
1510                 let value = row.children[child_idx].textContent;
1511                 global_sort[player] = value;
1512         }
1513 }
1514
1515 function get_sorted_players(players)
1516 {
1517         let p = Object.entries(players);
1518         if (global_sort.length !== 0) {
1519                 p.sort((a,b) => {
1520                         let ai = parseFloat(global_sort[a[0]]);
1521                         let bi = parseFloat(global_sort[b[0]]);
1522                         if (ai == ai && bi == bi) {
1523                                 return bi - ai;  // Reverse numeric.
1524                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
1525                                 return -1;
1526                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
1527                                 return 1;
1528                         } else {
1529                                 return 0;
1530                         }
1531                 });
1532         }
1533         return p;
1534 }